Now that code placement optimization pass is run for JIT, make sure it's before pre...
[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/GCStrategy.h"
21 #include "llvm/CodeGen/MachineFunctionAnalysis.h"
22 #include "llvm/Target/TargetOptions.h"
23 #include "llvm/MC/MCAsmInfo.h"
24 #include "llvm/Target/TargetRegistry.h"
25 #include "llvm/Transforms/Scalar.h"
26 #include "llvm/Support/CommandLine.h"
27 #include "llvm/Support/FormattedStream.h"
28 using namespace llvm;
29
30 namespace llvm {
31   bool EnableFastISel;
32 }
33
34 static cl::opt<bool> DisablePostRA("disable-post-ra", cl::Hidden,
35     cl::desc("Disable Post Regalloc"));
36 static cl::opt<bool> DisableBranchFold("disable-branch-fold", cl::Hidden,
37     cl::desc("Disable branch folding"));
38 static cl::opt<bool> DisableCodePlace("disable-code-place", cl::Hidden,
39     cl::desc("Disable code placement"));
40 static cl::opt<bool> DisableSSC("disable-ssc", cl::Hidden,
41     cl::desc("Disable Stack Slot Coloring"));
42 static cl::opt<bool> DisableMachineLICM("disable-machine-licm", cl::Hidden,
43     cl::desc("Disable Machine LICM"));
44 static cl::opt<bool> DisableMachineSink("disable-machine-sink", cl::Hidden,
45     cl::desc("Disable Machine Sinking"));
46 static cl::opt<bool> DisableLSR("disable-lsr", cl::Hidden,
47     cl::desc("Disable Loop Strength Reduction Pass"));
48 static cl::opt<bool> DisableCGP("disable-cgp", cl::Hidden,
49     cl::desc("Disable Codegen Prepare"));
50 static cl::opt<bool> PrintLSR("print-lsr-output", cl::Hidden,
51     cl::desc("Print LLVM IR produced by the loop-reduce pass"));
52 static cl::opt<bool> PrintISelInput("print-isel-input", cl::Hidden,
53     cl::desc("Print LLVM IR input to isel pass"));
54 static cl::opt<bool> PrintEmittedAsm("print-emitted-asm", cl::Hidden,
55     cl::desc("Dump emitter generated instructions as assembly"));
56 static cl::opt<bool> PrintGCInfo("print-gc", cl::Hidden,
57     cl::desc("Dump garbage collector data"));
58 static cl::opt<bool> VerifyMachineCode("verify-machineinstrs", cl::Hidden,
59     cl::desc("Verify generated machine code"),
60     cl::init(getenv("LLVM_VERIFY_MACHINEINSTRS")!=NULL));
61
62 // Enable or disable FastISel. Both options are needed, because
63 // FastISel is enabled by default with -fast, and we wish to be
64 // able to enable or disable fast-isel independently from -O0.
65 static cl::opt<cl::boolOrDefault>
66 EnableFastISelOption("fast-isel", cl::Hidden,
67   cl::desc("Enable the \"fast\" instruction selector"));
68
69
70 LLVMTargetMachine::LLVMTargetMachine(const Target &T,
71                                      const std::string &TargetTriple)
72   : TargetMachine(T) {
73   AsmInfo = T.createAsmInfo(TargetTriple);
74 }
75
76
77
78 FileModel::Model
79 LLVMTargetMachine::addPassesToEmitFile(PassManagerBase &PM,
80                                        formatted_raw_ostream &Out,
81                                        CodeGenFileType FileType,
82                                        CodeGenOpt::Level OptLevel) {
83   // Add common CodeGen passes.
84   if (addCommonCodeGenPasses(PM, OptLevel))
85     return FileModel::Error;
86
87   switch (FileType) {
88   default:
89     break;
90   case TargetMachine::AssemblyFile:
91     if (addAssemblyEmitter(PM, OptLevel, getAsmVerbosityDefault(), Out))
92       return FileModel::Error;
93     return FileModel::AsmFile;
94   case TargetMachine::ObjectFile:
95     if (getMachOWriterInfo())
96       return FileModel::MachOFile;
97     else if (getELFWriterInfo())
98       return FileModel::ElfFile;
99   }
100
101   return FileModel::Error;
102 }
103
104 bool LLVMTargetMachine::addAssemblyEmitter(PassManagerBase &PM,
105                                            CodeGenOpt::Level OptLevel,
106                                            bool Verbose,
107                                            formatted_raw_ostream &Out) {
108   FunctionPass *Printer =
109     getTarget().createAsmPrinter(Out, *this, getMCAsmInfo(), Verbose);
110   if (!Printer)
111     return true;
112
113   PM.add(Printer);
114   return false;
115 }
116
117 /// addPassesToEmitFileFinish - If the passes to emit the specified file had to
118 /// be split up (e.g., to add an object writer pass), this method can be used to
119 /// finish up adding passes to emit the file, if necessary.
120 bool LLVMTargetMachine::addPassesToEmitFileFinish(PassManagerBase &PM,
121                                                   MachineCodeEmitter *MCE,
122                                                   CodeGenOpt::Level OptLevel) {
123   if (MCE)
124     addSimpleCodeEmitter(PM, OptLevel, *MCE);
125   if (PrintEmittedAsm)
126     addAssemblyEmitter(PM, OptLevel, true, ferrs());
127
128   PM.add(createGCInfoDeleter());
129
130   return false; // success!
131 }
132
133 /// addPassesToEmitFileFinish - If the passes to emit the specified file had to
134 /// be split up (e.g., to add an object writer pass), this method can be used to
135 /// finish up adding passes to emit the file, if necessary.
136 bool LLVMTargetMachine::addPassesToEmitFileFinish(PassManagerBase &PM,
137                                                   JITCodeEmitter *JCE,
138                                                   CodeGenOpt::Level OptLevel) {
139   if (JCE)
140     addSimpleCodeEmitter(PM, OptLevel, *JCE);
141   if (PrintEmittedAsm)
142     addAssemblyEmitter(PM, OptLevel, true, ferrs());
143
144   PM.add(createGCInfoDeleter());
145
146   return false; // success!
147 }
148
149 /// addPassesToEmitFileFinish - If the passes to emit the specified file had to
150 /// be split up (e.g., to add an object writer pass), this method can be used to
151 /// finish up adding passes to emit the file, if necessary.
152 bool LLVMTargetMachine::addPassesToEmitFileFinish(PassManagerBase &PM,
153                                                   ObjectCodeEmitter *OCE,
154                                                   CodeGenOpt::Level OptLevel) {
155   if (OCE)
156     addSimpleCodeEmitter(PM, OptLevel, *OCE);
157   if (PrintEmittedAsm)
158     addAssemblyEmitter(PM, OptLevel, true, ferrs());
159
160   PM.add(createGCInfoDeleter());
161
162   return false; // success!
163 }
164
165 /// addPassesToEmitMachineCode - Add passes to the specified pass manager to
166 /// get machine code emitted.  This uses a MachineCodeEmitter object to handle
167 /// actually outputting the machine code and resolving things like the address
168 /// of functions.  This method should returns true if machine code emission is
169 /// not supported.
170 ///
171 bool LLVMTargetMachine::addPassesToEmitMachineCode(PassManagerBase &PM,
172                                                    MachineCodeEmitter &MCE,
173                                                    CodeGenOpt::Level OptLevel) {
174   // Add common CodeGen passes.
175   if (addCommonCodeGenPasses(PM, OptLevel))
176     return true;
177
178   addCodeEmitter(PM, OptLevel, MCE);
179   if (PrintEmittedAsm)
180     addAssemblyEmitter(PM, OptLevel, true, ferrs());
181
182   PM.add(createGCInfoDeleter());
183
184   return false; // success!
185 }
186
187 /// addPassesToEmitMachineCode - Add passes to the specified pass manager to
188 /// get machine code emitted.  This uses a MachineCodeEmitter object to handle
189 /// actually outputting the machine code and resolving things like the address
190 /// of functions.  This method should returns true if machine code emission is
191 /// not supported.
192 ///
193 bool LLVMTargetMachine::addPassesToEmitMachineCode(PassManagerBase &PM,
194                                                    JITCodeEmitter &JCE,
195                                                    CodeGenOpt::Level OptLevel) {
196   // Add common CodeGen passes.
197   if (addCommonCodeGenPasses(PM, OptLevel))
198     return true;
199
200   addCodeEmitter(PM, OptLevel, JCE);
201   if (PrintEmittedAsm)
202     addAssemblyEmitter(PM, OptLevel, true, ferrs());
203
204   PM.add(createGCInfoDeleter());
205
206   return false; // success!
207 }
208
209 static void printAndVerify(PassManagerBase &PM,
210                            const char *Banner,
211                            bool allowDoubleDefs = false) {
212   if (PrintMachineCode)
213     PM.add(createMachineFunctionPrinterPass(errs(), Banner));
214
215   if (VerifyMachineCode)
216     PM.add(createMachineVerifierPass(allowDoubleDefs));
217 }
218
219 /// addCommonCodeGenPasses - Add standard LLVM codegen passes used for both
220 /// emitting to assembly files or machine code output.
221 ///
222 bool LLVMTargetMachine::addCommonCodeGenPasses(PassManagerBase &PM,
223                                                CodeGenOpt::Level OptLevel) {
224   // Standard LLVM-Level Passes.
225
226   // Run loop strength reduction before anything else.
227   if (OptLevel != CodeGenOpt::None && !DisableLSR) {
228     PM.add(createLoopStrengthReducePass(getTargetLowering()));
229     if (PrintLSR)
230       PM.add(createPrintFunctionPass("\n\n*** Code after LSR ***\n", &errs()));
231   }
232
233   // Turn exception handling constructs into something the code generators can
234   // handle.
235   switch (getMCAsmInfo()->getExceptionHandlingType())
236   {
237   case ExceptionHandling::SjLj:
238     // SjLj piggy-backs on dwarf for this bit. The cleanups done apply to both
239     PM.add(createDwarfEHPass(getTargetLowering(), OptLevel==CodeGenOpt::None));
240     PM.add(createSjLjEHPass(getTargetLowering()));
241     break;
242   case ExceptionHandling::Dwarf:
243     PM.add(createDwarfEHPass(getTargetLowering(), OptLevel==CodeGenOpt::None));
244     break;
245   case ExceptionHandling::None:
246     PM.add(createLowerInvokePass(getTargetLowering()));
247     break;
248   }
249
250   PM.add(createGCLoweringPass());
251
252   // Make sure that no unreachable blocks are instruction selected.
253   PM.add(createUnreachableBlockEliminationPass());
254
255   if (OptLevel != CodeGenOpt::None && !DisableCGP)
256     PM.add(createCodeGenPreparePass(getTargetLowering()));
257
258   PM.add(createStackProtectorPass(getTargetLowering()));
259
260   if (PrintISelInput)
261     PM.add(createPrintFunctionPass("\n\n"
262                                    "*** Final LLVM Code input to ISel ***\n",
263                                    &errs()));
264
265   // Standard Lower-Level Passes.
266
267   // Set up a MachineFunction for the rest of CodeGen to work on.
268   PM.add(new MachineFunctionAnalysis(*this, OptLevel));
269
270   // Enable FastISel with -fast, but allow that to be overridden.
271   if (EnableFastISelOption == cl::BOU_TRUE ||
272       (OptLevel == CodeGenOpt::None && EnableFastISelOption != cl::BOU_FALSE))
273     EnableFastISel = true;
274
275   // Ask the target for an isel.
276   if (addInstSelector(PM, OptLevel))
277     return true;
278
279   // Print the instruction selected machine code...
280   printAndVerify(PM, "After Instruction Selection",
281                  /* allowDoubleDefs= */ true);
282
283   if (OptLevel != CodeGenOpt::None) {
284     if (!DisableMachineLICM)
285       PM.add(createMachineLICMPass());
286     if (!DisableMachineSink)
287       PM.add(createMachineSinkingPass());
288     printAndVerify(PM, "After MachineLICM and MachineSinking",
289                    /* allowDoubleDefs= */ true);
290   }
291
292   // Run pre-ra passes.
293   if (addPreRegAlloc(PM, OptLevel))
294     printAndVerify(PM, "After PreRegAlloc passes",
295                    /* allowDoubleDefs= */ true);
296
297   // Perform register allocation.
298   PM.add(createRegisterAllocator());
299   printAndVerify(PM, "After Register Allocation");
300
301   // Perform stack slot coloring.
302   if (OptLevel != CodeGenOpt::None && !DisableSSC) {
303     // FIXME: Re-enable coloring with register when it's capable of adding
304     // kill markers.
305     PM.add(createStackSlotColoringPass(false));
306     printAndVerify(PM, "After StackSlotColoring");
307   }
308
309   // Run post-ra passes.
310   if (addPostRegAlloc(PM, OptLevel))
311     printAndVerify(PM, "After PostRegAlloc passes");
312
313   PM.add(createLowerSubregsPass());
314   printAndVerify(PM, "After LowerSubregs");
315
316   // Insert prolog/epilog code.  Eliminate abstract frame index references...
317   PM.add(createPrologEpilogCodeInserter());
318   printAndVerify(PM, "After PrologEpilogCodeInserter");
319
320   // Run pre-sched2 passes.
321   if (addPreSched2(PM, OptLevel))
322     printAndVerify(PM, "After PreSched2 passes");
323
324   // Second pass scheduler.
325   if (OptLevel != CodeGenOpt::None && !DisablePostRA) {
326     PM.add(createPostRAScheduler(OptLevel));
327     printAndVerify(PM, "After PostRAScheduler");
328   }
329
330   // Branch folding must be run after regalloc and prolog/epilog insertion.
331   if (OptLevel != CodeGenOpt::None && !DisableBranchFold) {
332     PM.add(createBranchFoldingPass(getEnableTailMergeDefault()));
333     printAndVerify(PM, "After BranchFolding");
334   }
335
336   PM.add(createGCMachineCodeAnalysisPass());
337
338   if (PrintGCInfo)
339     PM.add(createGCInfoPrinter(errs()));
340
341   // Fold redundant debug labels.
342   PM.add(createDebugLabelFoldingPass());
343   printAndVerify(PM, "After DebugLabelFolding");
344
345   if (OptLevel != CodeGenOpt::None && !DisableCodePlace) {
346     PM.add(createCodePlacementOptPass());
347     printAndVerify(PM, "After CodePlacementOpt");
348   }
349
350   if (addPreEmitPass(PM, OptLevel))
351     printAndVerify(PM, "After PreEmit passes");
352
353   return false;
354 }