9a776ed0e8d8e47f80efcc63a1a6c11dccbeade9
[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/Analysis/Verifier.h"
17 #include "llvm/Assembly/PrintModulePass.h"
18 #include "llvm/CodeGen/AsmPrinter.h"
19 #include "llvm/CodeGen/MachineFunctionAnalysis.h"
20 #include "llvm/CodeGen/MachineModuleInfo.h"
21 #include "llvm/CodeGen/GCStrategy.h"
22 #include "llvm/CodeGen/Passes.h"
23 #include "llvm/Target/TargetOptions.h"
24 #include "llvm/MC/MCAsmInfo.h"
25 #include "llvm/MC/MCStreamer.h"
26 #include "llvm/Target/TargetData.h"
27 #include "llvm/Target/TargetRegistry.h"
28 #include "llvm/Transforms/Scalar.h"
29 #include "llvm/ADT/OwningPtr.h"
30 #include "llvm/Support/CommandLine.h"
31 #include "llvm/Support/Debug.h"
32 #include "llvm/Support/FormattedStream.h"
33 using namespace llvm;
34
35 namespace llvm {
36   bool EnableFastISel;
37 }
38
39 static cl::opt<bool> DisablePostRA("disable-post-ra", cl::Hidden,
40     cl::desc("Disable Post Regalloc"));
41 static cl::opt<bool> DisableBranchFold("disable-branch-fold", cl::Hidden,
42     cl::desc("Disable branch folding"));
43 static cl::opt<bool> DisableTailDuplicate("disable-tail-duplicate", cl::Hidden,
44     cl::desc("Disable tail duplication"));
45 static cl::opt<bool> DisableEarlyTailDup("disable-early-taildup", cl::Hidden,
46     cl::desc("Disable pre-register allocation tail duplication"));
47 static cl::opt<bool> DisableCodePlace("disable-code-place", cl::Hidden,
48     cl::desc("Disable code placement"));
49 static cl::opt<bool> DisableSSC("disable-ssc", cl::Hidden,
50     cl::desc("Disable Stack Slot Coloring"));
51 static cl::opt<bool> DisableMachineLICM("disable-machine-licm", cl::Hidden,
52     cl::desc("Disable Machine LICM"));
53 static cl::opt<bool> DisablePostRAMachineLICM("disable-postra-machine-licm",
54     cl::Hidden,
55     cl::desc("Disable Machine LICM"));
56 static cl::opt<bool> DisableMachineSink("disable-machine-sink", cl::Hidden,
57     cl::desc("Disable Machine Sinking"));
58 static cl::opt<bool> DisableLSR("disable-lsr", cl::Hidden,
59     cl::desc("Disable Loop Strength Reduction Pass"));
60 static cl::opt<bool> DisableCGP("disable-cgp", cl::Hidden,
61     cl::desc("Disable Codegen Prepare"));
62 static cl::opt<bool> PrintLSR("print-lsr-output", cl::Hidden,
63     cl::desc("Print LLVM IR produced by the loop-reduce pass"));
64 static cl::opt<bool> PrintISelInput("print-isel-input", cl::Hidden,
65     cl::desc("Print LLVM IR input to isel pass"));
66 static cl::opt<bool> PrintGCInfo("print-gc", cl::Hidden,
67     cl::desc("Dump garbage collector data"));
68 static cl::opt<bool> ShowMCEncoding("show-mc-encoding", cl::Hidden,
69     cl::desc("Show encoding in .s output"));
70 static cl::opt<bool> ShowMCInst("show-mc-inst", cl::Hidden,
71     cl::desc("Show instruction structure in .s output"));
72 static cl::opt<bool> VerifyMachineCode("verify-machineinstrs", cl::Hidden,
73     cl::desc("Verify generated machine code"),
74     cl::init(getenv("LLVM_VERIFY_MACHINEINSTRS")!=NULL));
75
76 static cl::opt<cl::boolOrDefault>
77 AsmVerbose("asm-verbose", cl::desc("Add comments to directives."),
78            cl::init(cl::BOU_UNSET));
79
80 static bool getVerboseAsm() {
81   switch (AsmVerbose) {
82   default:
83   case cl::BOU_UNSET: return TargetMachine::getAsmVerbosityDefault();
84   case cl::BOU_TRUE:  return true;
85   case cl::BOU_FALSE: return false;
86   }      
87 }
88
89 // Enable or disable FastISel. Both options are needed, because
90 // FastISel is enabled by default with -fast, and we wish to be
91 // able to enable or disable fast-isel independently from -O0.
92 static cl::opt<cl::boolOrDefault>
93 EnableFastISelOption("fast-isel", cl::Hidden,
94   cl::desc("Enable the \"fast\" instruction selector"));
95
96 // Enable or disable an experimental optimization to split GEPs
97 // and run a special GVN pass which does not examine loads, in
98 // an effort to factor out redundancy implicit in complex GEPs.
99 static cl::opt<bool> EnableSplitGEPGVN("split-gep-gvn", cl::Hidden,
100     cl::desc("Split GEPs and run no-load GVN"));
101
102 LLVMTargetMachine::LLVMTargetMachine(const Target &T,
103                                      const std::string &Triple)
104   : TargetMachine(T), TargetTriple(Triple) {
105   AsmInfo = T.createAsmInfo(TargetTriple);
106 }
107
108 // Set the default code model for the JIT for a generic target.
109 // FIXME: Is small right here? or .is64Bit() ? Large : Small?
110 void LLVMTargetMachine::setCodeModelForJIT() {
111   setCodeModel(CodeModel::Small);
112 }
113
114 // Set the default code model for static compilation for a generic target.
115 void LLVMTargetMachine::setCodeModelForStatic() {
116   setCodeModel(CodeModel::Small);
117 }
118
119 bool LLVMTargetMachine::addPassesToEmitFile(PassManagerBase &PM,
120                                             formatted_raw_ostream &Out,
121                                             CodeGenFileType FileType,
122                                             CodeGenOpt::Level OptLevel,
123                                             bool DisableVerify) {
124   // Add common CodeGen passes.
125   MCContext *Context = 0;
126   if (addCommonCodeGenPasses(PM, OptLevel, DisableVerify, Context))
127     return true;
128   assert(Context != 0 && "Failed to get MCContext");
129
130   const MCAsmInfo &MAI = *getMCAsmInfo();
131   OwningPtr<MCStreamer> AsmStreamer;
132
133   switch (FileType) {
134   default: return true;
135   case CGFT_AssemblyFile: {
136     MCInstPrinter *InstPrinter =
137       getTarget().createMCInstPrinter(MAI.getAssemblerDialect(), MAI);
138
139     // Create a code emitter if asked to show the encoding.
140     //
141     // FIXME: These are currently leaked.
142     MCCodeEmitter *MCE = 0;
143     if (ShowMCEncoding)
144       MCE = getTarget().createCodeEmitter(*this, *Context);
145
146     AsmStreamer.reset(createAsmStreamer(*Context, Out,
147                                         getTargetData()->isLittleEndian(),
148                                         getVerboseAsm(), InstPrinter,
149                                         MCE, ShowMCInst));
150     break;
151   }
152   case CGFT_ObjectFile: {
153     // Create the code emitter for the target if it exists.  If not, .o file
154     // emission fails.
155     //
156     // FIXME: These are currently leaked.
157     MCCodeEmitter *MCE = getTarget().createCodeEmitter(*this, *Context);
158     TargetAsmBackend *TAB = getTarget().createAsmBackend(TargetTriple);
159     if (MCE == 0 || TAB == 0)
160       return true;
161     
162     AsmStreamer.reset(createMachOStreamer(*Context, *TAB, Out, MCE));
163     break;
164   }
165   case CGFT_Null:
166     // The Null output is intended for use for performance analysis and testing,
167     // not real users.
168     AsmStreamer.reset(createNullStreamer(*Context));
169     break;
170   }
171   
172   // Create the AsmPrinter, which takes ownership of AsmStreamer if successful.
173   FunctionPass *Printer = getTarget().createAsmPrinter(*this, *AsmStreamer);
174   if (Printer == 0)
175     return true;
176   
177   // If successful, createAsmPrinter took ownership of AsmStreamer.
178   AsmStreamer.take();
179   
180   PM.add(Printer);
181   
182   // Make sure the code model is set.
183   setCodeModelForStatic();
184   PM.add(createGCInfoDeleter());
185   return false;
186 }
187
188 /// addPassesToEmitMachineCode - Add passes to the specified pass manager to
189 /// get machine code emitted.  This uses a JITCodeEmitter object to handle
190 /// actually outputting the machine code and resolving things like the address
191 /// of functions.  This method should returns true if machine code emission is
192 /// not supported.
193 ///
194 bool LLVMTargetMachine::addPassesToEmitMachineCode(PassManagerBase &PM,
195                                                    JITCodeEmitter &JCE,
196                                                    CodeGenOpt::Level OptLevel,
197                                                    bool DisableVerify) {
198   // Make sure the code model is set.
199   setCodeModelForJIT();
200   
201   // Add common CodeGen passes.
202   MCContext *Ctx = 0;
203   if (addCommonCodeGenPasses(PM, OptLevel, DisableVerify, Ctx))
204     return true;
205
206   addCodeEmitter(PM, OptLevel, JCE);
207   PM.add(createGCInfoDeleter());
208
209   return false; // success!
210 }
211
212 static void printNoVerify(PassManagerBase &PM, const char *Banner) {
213   if (PrintMachineCode)
214     PM.add(createMachineFunctionPrinterPass(dbgs(), Banner));
215 }
216
217 static void printAndVerify(PassManagerBase &PM,
218                            const char *Banner,
219                            bool allowDoubleDefs = false) {
220   if (PrintMachineCode)
221     PM.add(createMachineFunctionPrinterPass(dbgs(), Banner));
222
223   if (VerifyMachineCode)
224     PM.add(createMachineVerifierPass(allowDoubleDefs));
225 }
226
227 /// addCommonCodeGenPasses - Add standard LLVM codegen passes used for both
228 /// emitting to assembly files or machine code output.
229 ///
230 bool LLVMTargetMachine::addCommonCodeGenPasses(PassManagerBase &PM,
231                                                CodeGenOpt::Level OptLevel,
232                                                bool DisableVerify,
233                                                MCContext *&OutContext) {
234   // Standard LLVM-Level Passes.
235
236   // Before running any passes, run the verifier to determine if the input
237   // coming from the front-end and/or optimizer is valid.
238   if (!DisableVerify)
239     PM.add(createVerifierPass());
240
241   // Optionally, tun split-GEPs and no-load GVN.
242   if (EnableSplitGEPGVN) {
243     PM.add(createGEPSplitterPass());
244     PM.add(createGVNPass(/*NoLoads=*/true));
245   }
246
247   // Run loop strength reduction before anything else.
248   if (OptLevel != CodeGenOpt::None && !DisableLSR) {
249     PM.add(createLoopStrengthReducePass(getTargetLowering()));
250     if (PrintLSR)
251       PM.add(createPrintFunctionPass("\n\n*** Code after LSR ***\n", &dbgs()));
252   }
253
254   // Turn exception handling constructs into something the code generators can
255   // handle.
256   switch (getMCAsmInfo()->getExceptionHandlingType()) {
257   case ExceptionHandling::SjLj:
258     // SjLj piggy-backs on dwarf for this bit. The cleanups done apply to both
259     // Dwarf EH prepare needs to be run after SjLj prepare. Otherwise,
260     // catch info can get misplaced when a selector ends up more than one block
261     // removed from the parent invoke(s). This could happen when a landing
262     // pad is shared by multiple invokes and is also a target of a normal
263     // edge from elsewhere.
264     PM.add(createSjLjEHPass(getTargetLowering()));
265     PM.add(createDwarfEHPass(this, OptLevel==CodeGenOpt::None));
266     break;
267   case ExceptionHandling::Dwarf:
268     PM.add(createDwarfEHPass(this, OptLevel==CodeGenOpt::None));
269     break;
270   case ExceptionHandling::None:
271     PM.add(createLowerInvokePass(getTargetLowering()));
272     break;
273   }
274
275   PM.add(createGCLoweringPass());
276
277   // Make sure that no unreachable blocks are instruction selected.
278   PM.add(createUnreachableBlockEliminationPass());
279
280   if (OptLevel != CodeGenOpt::None && !DisableCGP)
281     PM.add(createCodeGenPreparePass(getTargetLowering()));
282
283   PM.add(createStackProtectorPass(getTargetLowering()));
284
285   if (PrintISelInput)
286     PM.add(createPrintFunctionPass("\n\n"
287                                    "*** Final LLVM Code input to ISel ***\n",
288                                    &dbgs()));
289
290   // All passes which modify the LLVM IR are now complete; run the verifier
291   // to ensure that the IR is valid.
292   if (!DisableVerify)
293     PM.add(createVerifierPass());
294
295   // Standard Lower-Level Passes.
296   
297   // Install a MachineModuleInfo class, which is an immutable pass that holds
298   // all the per-module stuff we're generating, including MCContext.
299   MachineModuleInfo *MMI = new MachineModuleInfo(*getMCAsmInfo());
300   PM.add(MMI);
301   OutContext = &MMI->getContext(); // Return the MCContext specifically by-ref.
302   
303
304   // Set up a MachineFunction for the rest of CodeGen to work on.
305   PM.add(new MachineFunctionAnalysis(*this, OptLevel));
306
307   // Enable FastISel with -fast, but allow that to be overridden.
308   if (EnableFastISelOption == cl::BOU_TRUE ||
309       (OptLevel == CodeGenOpt::None && EnableFastISelOption != cl::BOU_FALSE))
310     EnableFastISel = true;
311
312   // Ask the target for an isel.
313   if (addInstSelector(PM, OptLevel))
314     return true;
315
316   // Print the instruction selected machine code...
317   printAndVerify(PM, "After Instruction Selection",
318                  /* allowDoubleDefs= */ true);
319
320   // Optimize PHIs before DCE: removing dead PHI cycles may make more
321   // instructions dead.
322   if (OptLevel != CodeGenOpt::None)
323     PM.add(createOptimizePHIsPass());
324
325   // Delete dead machine instructions regardless of optimization level.
326   PM.add(createDeadMachineInstructionElimPass());
327   printAndVerify(PM, "After codegen DCE pass",
328                  /* allowDoubleDefs= */ true);
329
330   if (OptLevel != CodeGenOpt::None) {
331     PM.add(createOptimizeExtsPass());
332     if (!DisableMachineLICM)
333       PM.add(createMachineLICMPass());
334     PM.add(createMachineCSEPass());
335     if (!DisableMachineSink)
336       PM.add(createMachineSinkingPass());
337     printAndVerify(PM, "After Machine LICM, CSE and Sinking passes",
338                    /* allowDoubleDefs= */ true);
339   }
340
341   // Pre-ra tail duplication.
342   if (OptLevel != CodeGenOpt::None && !DisableEarlyTailDup) {
343     PM.add(createTailDuplicatePass(true));
344     printAndVerify(PM, "After Pre-RegAlloc TailDuplicate",
345                    /* allowDoubleDefs= */ true);
346   }
347
348   // Run pre-ra passes.
349   if (addPreRegAlloc(PM, OptLevel))
350     printAndVerify(PM, "After PreRegAlloc passes",
351                    /* allowDoubleDefs= */ true);
352
353   // Perform register allocation.
354   PM.add(createRegisterAllocator());
355   printAndVerify(PM, "After Register Allocation");
356
357   // Perform stack slot coloring and post-ra machine LICM.
358   if (OptLevel != CodeGenOpt::None) {
359     // FIXME: Re-enable coloring with register when it's capable of adding
360     // kill markers.
361     if (!DisableSSC)
362       PM.add(createStackSlotColoringPass(false));
363
364     // Run post-ra machine LICM to hoist reloads / remats.
365     if (!DisablePostRAMachineLICM)
366       PM.add(createMachineLICMPass(false));
367
368     printAndVerify(PM, "After StackSlotColoring and postra Machine LICM");
369   }
370
371   // Run post-ra passes.
372   if (addPostRegAlloc(PM, OptLevel))
373     printAndVerify(PM, "After PostRegAlloc passes");
374
375   PM.add(createLowerSubregsPass());
376   printAndVerify(PM, "After LowerSubregs");
377
378   // Insert prolog/epilog code.  Eliminate abstract frame index references...
379   PM.add(createPrologEpilogCodeInserter());
380   printAndVerify(PM, "After PrologEpilogCodeInserter");
381
382   // Run pre-sched2 passes.
383   if (addPreSched2(PM, OptLevel))
384     printAndVerify(PM, "After PreSched2 passes");
385
386   // Second pass scheduler.
387   if (OptLevel != CodeGenOpt::None && !DisablePostRA) {
388     PM.add(createPostRAScheduler(OptLevel));
389     printAndVerify(PM, "After PostRAScheduler");
390   }
391
392   // Branch folding must be run after regalloc and prolog/epilog insertion.
393   if (OptLevel != CodeGenOpt::None && !DisableBranchFold) {
394     PM.add(createBranchFoldingPass(getEnableTailMergeDefault()));
395     printNoVerify(PM, "After BranchFolding");
396   }
397
398   // Tail duplication.
399   if (OptLevel != CodeGenOpt::None && !DisableTailDuplicate) {
400     PM.add(createTailDuplicatePass(false));
401     printNoVerify(PM, "After TailDuplicate");
402   }
403
404   PM.add(createGCMachineCodeAnalysisPass());
405
406   if (PrintGCInfo)
407     PM.add(createGCInfoPrinter(dbgs()));
408
409   if (OptLevel != CodeGenOpt::None && !DisableCodePlace) {
410     PM.add(createCodePlacementOptPass());
411     printNoVerify(PM, "After CodePlacementOpt");
412   }
413
414   if (addPreEmitPass(PM, OptLevel))
415     printNoVerify(PM, "After PreEmit passes");
416
417   return false;
418 }