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