eliminate FileModel::Model, just use CodeGenFileType. The client
[oota-llvm.git] / lib / CodeGen / LLVMTargetMachine.cpp
1 //===-- LLVMTargetMachine.cpp - Implement the LLVMTargetMachine class -----===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file implements the LLVMTargetMachine class.
11 //
12 //===----------------------------------------------------------------------===//
13
14 #include "llvm/Target/TargetMachine.h"
15 #include "llvm/PassManager.h"
16 #include "llvm/Pass.h"
17 #include "llvm/Assembly/PrintModulePass.h"
18 #include "llvm/CodeGen/AsmPrinter.h"
19 #include "llvm/CodeGen/Passes.h"
20 #include "llvm/CodeGen/FileWriters.h"
21 #include "llvm/CodeGen/GCStrategy.h"
22 #include "llvm/CodeGen/MachineFunctionAnalysis.h"
23 #include "llvm/Target/TargetOptions.h"
24 #include "llvm/MC/MCAsmInfo.h"
25 #include "llvm/Target/TargetRegistry.h"
26 #include "llvm/Transforms/Scalar.h"
27 #include "llvm/Support/CommandLine.h"
28 #include "llvm/Support/Debug.h"
29 #include "llvm/Support/FormattedStream.h"
30 using namespace llvm;
31
32 namespace llvm {
33   bool EnableFastISel;
34 }
35
36 static cl::opt<bool> DisablePostRA("disable-post-ra", cl::Hidden,
37     cl::desc("Disable Post Regalloc"));
38 static cl::opt<bool> DisableBranchFold("disable-branch-fold", cl::Hidden,
39     cl::desc("Disable branch folding"));
40 static cl::opt<bool> DisableTailDuplicate("disable-tail-duplicate", cl::Hidden,
41     cl::desc("Disable tail duplication"));
42 static cl::opt<bool> DisableEarlyTailDup("disable-early-taildup", cl::Hidden,
43     cl::desc("Disable pre-register allocation tail duplication"));
44 static cl::opt<bool> DisableCodePlace("disable-code-place", cl::Hidden,
45     cl::desc("Disable code placement"));
46 static cl::opt<bool> DisableSSC("disable-ssc", cl::Hidden,
47     cl::desc("Disable Stack Slot Coloring"));
48 static cl::opt<bool> DisableMachineLICM("disable-machine-licm", cl::Hidden,
49     cl::desc("Disable Machine LICM"));
50 static cl::opt<bool> DisableMachineSink("disable-machine-sink", cl::Hidden,
51     cl::desc("Disable Machine Sinking"));
52 static cl::opt<bool> DisableLSR("disable-lsr", cl::Hidden,
53     cl::desc("Disable Loop Strength Reduction Pass"));
54 static cl::opt<bool> DisableCGP("disable-cgp", cl::Hidden,
55     cl::desc("Disable Codegen Prepare"));
56 static cl::opt<bool> PrintLSR("print-lsr-output", cl::Hidden,
57     cl::desc("Print LLVM IR produced by the loop-reduce pass"));
58 static cl::opt<bool> PrintISelInput("print-isel-input", cl::Hidden,
59     cl::desc("Print LLVM IR input to isel pass"));
60 static cl::opt<bool> PrintGCInfo("print-gc", cl::Hidden,
61     cl::desc("Dump garbage collector data"));
62 static cl::opt<bool> VerifyMachineCode("verify-machineinstrs", cl::Hidden,
63     cl::desc("Verify generated machine code"),
64     cl::init(getenv("LLVM_VERIFY_MACHINEINSTRS")!=NULL));
65
66
67 // Enable or disable FastISel. Both options are needed, because
68 // FastISel is enabled by default with -fast, and we wish to be
69 // able to enable or disable fast-isel independently from -O0.
70 static cl::opt<cl::boolOrDefault>
71 EnableFastISelOption("fast-isel", cl::Hidden,
72   cl::desc("Enable the \"fast\" instruction selector"));
73
74 // Enable or disable an experimental optimization to split GEPs
75 // and run a special GVN pass which does not examine loads, in
76 // an effort to factor out redundancy implicit in complex GEPs.
77 static cl::opt<bool> EnableSplitGEPGVN("split-gep-gvn", cl::Hidden,
78     cl::desc("Split GEPs and run no-load GVN"));
79
80 LLVMTargetMachine::LLVMTargetMachine(const Target &T,
81                                      const std::string &TargetTriple)
82   : TargetMachine(T) {
83   AsmInfo = T.createAsmInfo(TargetTriple);
84 }
85
86 // Set the default code model for the JIT for a generic target.
87 // FIXME: Is small right here? or .is64Bit() ? Large : Small?
88 void
89 LLVMTargetMachine::setCodeModelForJIT() {
90   setCodeModel(CodeModel::Small);
91 }
92
93 // Set the default code model for static compilation for a generic target.
94 void
95 LLVMTargetMachine::setCodeModelForStatic() {
96   setCodeModel(CodeModel::Small);
97 }
98
99 TargetMachine::CodeGenFileType
100 LLVMTargetMachine::addPassesToEmitFile(PassManagerBase &PM,
101                                        formatted_raw_ostream &Out,
102                                        CodeGenFileType FileType,
103                                        CodeGenOpt::Level OptLevel) {
104   // Add common CodeGen passes.
105   if (addCommonCodeGenPasses(PM, OptLevel))
106     return CGFT_ErrorOccurred;
107
108   switch (FileType) {
109   default:
110   case CGFT_ObjectFile:
111     return CGFT_ErrorOccurred;
112   case CGFT_AssemblyFile: {
113     FunctionPass *Printer =
114       getTarget().createAsmPrinter(Out, *this, getMCAsmInfo(),
115                                    getAsmVerbosityDefault());
116     if (Printer == 0) return CGFT_ErrorOccurred;
117     PM.add(Printer);
118     break;
119   }
120   }
121   
122   // Make sure the code model is set.
123   setCodeModelForStatic();
124   PM.add(createGCInfoDeleter());
125   return FileType;
126 }
127
128 /// addPassesToEmitMachineCode - Add passes to the specified pass manager to
129 /// get machine code emitted.  This uses a MachineCodeEmitter object to handle
130 /// actually outputting the machine code and resolving things like the address
131 /// of functions.  This method should returns true if machine code emission is
132 /// not supported.
133 ///
134 bool LLVMTargetMachine::addPassesToEmitMachineCode(PassManagerBase &PM,
135                                                    JITCodeEmitter &JCE,
136                                                    CodeGenOpt::Level OptLevel) {
137   // Make sure the code model is set.
138   setCodeModelForJIT();
139   
140   // Add common CodeGen passes.
141   if (addCommonCodeGenPasses(PM, OptLevel))
142     return true;
143
144   addCodeEmitter(PM, OptLevel, JCE);
145   PM.add(createGCInfoDeleter());
146
147   return false; // success!
148 }
149
150 static void printAndVerify(PassManagerBase &PM,
151                            const char *Banner,
152                            bool allowDoubleDefs = false) {
153   if (PrintMachineCode)
154     PM.add(createMachineFunctionPrinterPass(dbgs(), Banner));
155
156   if (VerifyMachineCode)
157     PM.add(createMachineVerifierPass(allowDoubleDefs));
158 }
159
160 /// addCommonCodeGenPasses - Add standard LLVM codegen passes used for both
161 /// emitting to assembly files or machine code output.
162 ///
163 bool LLVMTargetMachine::addCommonCodeGenPasses(PassManagerBase &PM,
164                                                CodeGenOpt::Level OptLevel) {
165   // Standard LLVM-Level Passes.
166
167   // Optionally, tun split-GEPs and no-load GVN.
168   if (EnableSplitGEPGVN) {
169     PM.add(createGEPSplitterPass());
170     PM.add(createGVNPass(/*NoPRE=*/false, /*NoLoads=*/true));
171   }
172
173   // Run loop strength reduction before anything else.
174   if (OptLevel != CodeGenOpt::None && !DisableLSR) {
175     PM.add(createLoopStrengthReducePass(getTargetLowering()));
176     if (PrintLSR)
177       PM.add(createPrintFunctionPass("\n\n*** Code after LSR ***\n", &dbgs()));
178   }
179
180   // Turn exception handling constructs into something the code generators can
181   // handle.
182   switch (getMCAsmInfo()->getExceptionHandlingType())
183   {
184   case ExceptionHandling::SjLj:
185     // SjLj piggy-backs on dwarf for this bit. The cleanups done apply to both
186     // Dwarf EH prepare needs to be run after SjLj prepare. Otherwise,
187     // catch info can get misplaced when a selector ends up more than one block
188     // removed from the parent invoke(s). This could happen when a landing
189     // pad is shared by multiple invokes and is also a target of a normal
190     // edge from elsewhere.
191     PM.add(createSjLjEHPass(getTargetLowering()));
192     PM.add(createDwarfEHPass(getTargetLowering(), OptLevel==CodeGenOpt::None));
193     break;
194   case ExceptionHandling::Dwarf:
195     PM.add(createDwarfEHPass(getTargetLowering(), OptLevel==CodeGenOpt::None));
196     break;
197   case ExceptionHandling::None:
198     PM.add(createLowerInvokePass(getTargetLowering()));
199     break;
200   }
201
202   PM.add(createGCLoweringPass());
203
204   // Make sure that no unreachable blocks are instruction selected.
205   PM.add(createUnreachableBlockEliminationPass());
206
207   if (OptLevel != CodeGenOpt::None && !DisableCGP)
208     PM.add(createCodeGenPreparePass(getTargetLowering()));
209
210   PM.add(createStackProtectorPass(getTargetLowering()));
211
212   if (PrintISelInput)
213     PM.add(createPrintFunctionPass("\n\n"
214                                    "*** Final LLVM Code input to ISel ***\n",
215                                    &dbgs()));
216
217   // Standard Lower-Level Passes.
218
219   // Set up a MachineFunction for the rest of CodeGen to work on.
220   PM.add(new MachineFunctionAnalysis(*this, OptLevel));
221
222   // Enable FastISel with -fast, but allow that to be overridden.
223   if (EnableFastISelOption == cl::BOU_TRUE ||
224       (OptLevel == CodeGenOpt::None && EnableFastISelOption != cl::BOU_FALSE))
225     EnableFastISel = true;
226
227   // Ask the target for an isel.
228   if (addInstSelector(PM, OptLevel))
229     return true;
230
231   // Print the instruction selected machine code...
232   printAndVerify(PM, "After Instruction Selection",
233                  /* allowDoubleDefs= */ true);
234
235   if (OptLevel != CodeGenOpt::None) {
236     PM.add(createOptimizeExtsPass());
237     if (!DisableMachineLICM)
238       PM.add(createMachineLICMPass());
239     if (!DisableMachineSink)
240       PM.add(createMachineSinkingPass());
241     printAndVerify(PM, "After MachineLICM and MachineSinking",
242                    /* allowDoubleDefs= */ true);
243   }
244
245   // Pre-ra tail duplication.
246   if (OptLevel != CodeGenOpt::None && !DisableEarlyTailDup) {
247     PM.add(createTailDuplicatePass(true));
248     printAndVerify(PM, "After Pre-RegAlloc TailDuplicate",
249                    /* allowDoubleDefs= */ true);
250   }
251
252   // Run pre-ra passes.
253   if (addPreRegAlloc(PM, OptLevel))
254     printAndVerify(PM, "After PreRegAlloc passes",
255                    /* allowDoubleDefs= */ true);
256
257   // Perform register allocation.
258   PM.add(createRegisterAllocator());
259   printAndVerify(PM, "After Register Allocation");
260
261   // Perform stack slot coloring.
262   if (OptLevel != CodeGenOpt::None && !DisableSSC) {
263     // FIXME: Re-enable coloring with register when it's capable of adding
264     // kill markers.
265     PM.add(createStackSlotColoringPass(false));
266     printAndVerify(PM, "After StackSlotColoring");
267   }
268
269   // Run post-ra passes.
270   if (addPostRegAlloc(PM, OptLevel))
271     printAndVerify(PM, "After PostRegAlloc passes");
272
273   PM.add(createLowerSubregsPass());
274   printAndVerify(PM, "After LowerSubregs");
275
276   // Insert prolog/epilog code.  Eliminate abstract frame index references...
277   PM.add(createPrologEpilogCodeInserter());
278   printAndVerify(PM, "After PrologEpilogCodeInserter");
279
280   // Run pre-sched2 passes.
281   if (addPreSched2(PM, OptLevel))
282     printAndVerify(PM, "After PreSched2 passes");
283
284   // Second pass scheduler.
285   if (OptLevel != CodeGenOpt::None && !DisablePostRA) {
286     PM.add(createPostRAScheduler(OptLevel));
287     printAndVerify(PM, "After PostRAScheduler");
288   }
289
290   // Branch folding must be run after regalloc and prolog/epilog insertion.
291   if (OptLevel != CodeGenOpt::None && !DisableBranchFold) {
292     PM.add(createBranchFoldingPass(getEnableTailMergeDefault()));
293     printAndVerify(PM, "After BranchFolding");
294   }
295
296   // Tail duplication.
297   if (OptLevel != CodeGenOpt::None && !DisableTailDuplicate) {
298     PM.add(createTailDuplicatePass(false));
299     printAndVerify(PM, "After TailDuplicate");
300   }
301
302   PM.add(createGCMachineCodeAnalysisPass());
303
304   if (PrintGCInfo)
305     PM.add(createGCInfoPrinter(dbgs()));
306
307   if (OptLevel != CodeGenOpt::None && !DisableCodePlace) {
308     PM.add(createCodePlacementOptPass());
309     printAndVerify(PM, "After CodePlacementOpt");
310   }
311
312   if (addPreEmitPass(PM, OptLevel))
313     printAndVerify(PM, "After PreEmit passes");
314
315   return false;
316 }