Added TargetPassConfig. The first little step toward configuring codegen passes.
[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/Passes.h"
17 #include "llvm/Analysis/Verifier.h"
18 #include "llvm/Assembly/PrintModulePass.h"
19 #include "llvm/CodeGen/AsmPrinter.h"
20 #include "llvm/CodeGen/MachineFunctionAnalysis.h"
21 #include "llvm/CodeGen/MachineModuleInfo.h"
22 #include "llvm/CodeGen/GCStrategy.h"
23 #include "llvm/CodeGen/Passes.h"
24 #include "llvm/Target/TargetLowering.h"
25 #include "llvm/Target/TargetOptions.h"
26 #include "llvm/MC/MCAsmInfo.h"
27 #include "llvm/MC/MCInstrInfo.h"
28 #include "llvm/MC/MCStreamer.h"
29 #include "llvm/MC/MCSubtargetInfo.h"
30 #include "llvm/Target/TargetData.h"
31 #include "llvm/Target/TargetInstrInfo.h"
32 #include "llvm/Target/TargetLowering.h"
33 #include "llvm/Target/TargetLoweringObjectFile.h"
34 #include "llvm/Target/TargetRegisterInfo.h"
35 #include "llvm/Target/TargetSubtargetInfo.h"
36 #include "llvm/Transforms/Scalar.h"
37 #include "llvm/ADT/OwningPtr.h"
38 #include "llvm/Support/CommandLine.h"
39 #include "llvm/Support/Debug.h"
40 #include "llvm/Support/FormattedStream.h"
41 #include "llvm/Support/TargetRegistry.h"
42 using namespace llvm;
43
44 static cl::opt<bool> DisablePostRA("disable-post-ra", cl::Hidden,
45     cl::desc("Disable Post Regalloc"));
46 static cl::opt<bool> DisableBranchFold("disable-branch-fold", cl::Hidden,
47     cl::desc("Disable branch folding"));
48 static cl::opt<bool> DisableTailDuplicate("disable-tail-duplicate", cl::Hidden,
49     cl::desc("Disable tail duplication"));
50 static cl::opt<bool> DisableEarlyTailDup("disable-early-taildup", cl::Hidden,
51     cl::desc("Disable pre-register allocation tail duplication"));
52 static cl::opt<bool> EnableBlockPlacement("enable-block-placement",
53     cl::Hidden, cl::desc("Enable probability-driven block placement"));
54 static cl::opt<bool> EnableBlockPlacementStats("enable-block-placement-stats",
55     cl::Hidden, cl::desc("Collect probability-driven block placement stats"));
56 static cl::opt<bool> DisableCodePlace("disable-code-place", cl::Hidden,
57     cl::desc("Disable code placement"));
58 static cl::opt<bool> DisableSSC("disable-ssc", cl::Hidden,
59     cl::desc("Disable Stack Slot Coloring"));
60 static cl::opt<bool> DisableMachineDCE("disable-machine-dce", cl::Hidden,
61     cl::desc("Disable Machine Dead Code Elimination"));
62 static cl::opt<bool> DisableMachineLICM("disable-machine-licm", cl::Hidden,
63     cl::desc("Disable Machine LICM"));
64 static cl::opt<bool> DisableMachineCSE("disable-machine-cse", cl::Hidden,
65     cl::desc("Disable Machine Common Subexpression Elimination"));
66 static cl::opt<bool> DisablePostRAMachineLICM("disable-postra-machine-licm",
67     cl::Hidden,
68     cl::desc("Disable Machine LICM"));
69 static cl::opt<bool> DisableMachineSink("disable-machine-sink", cl::Hidden,
70     cl::desc("Disable Machine Sinking"));
71 static cl::opt<bool> DisableLSR("disable-lsr", cl::Hidden,
72     cl::desc("Disable Loop Strength Reduction Pass"));
73 static cl::opt<bool> DisableCGP("disable-cgp", cl::Hidden,
74     cl::desc("Disable Codegen Prepare"));
75 static cl::opt<bool> DisableCopyProp("disable-copyprop", cl::Hidden,
76     cl::desc("Disable Copy Propagation pass"));
77 static cl::opt<bool> PrintLSR("print-lsr-output", cl::Hidden,
78     cl::desc("Print LLVM IR produced by the loop-reduce pass"));
79 static cl::opt<bool> PrintISelInput("print-isel-input", cl::Hidden,
80     cl::desc("Print LLVM IR input to isel pass"));
81 static cl::opt<bool> PrintGCInfo("print-gc", cl::Hidden,
82     cl::desc("Dump garbage collector data"));
83 static cl::opt<bool> ShowMCEncoding("show-mc-encoding", cl::Hidden,
84     cl::desc("Show encoding in .s output"));
85 static cl::opt<bool> ShowMCInst("show-mc-inst", cl::Hidden,
86     cl::desc("Show instruction structure in .s output"));
87 static cl::opt<bool> VerifyMachineCode("verify-machineinstrs", cl::Hidden,
88     cl::desc("Verify generated machine code"),
89     cl::init(getenv("LLVM_VERIFY_MACHINEINSTRS")!=NULL));
90
91 static cl::opt<cl::boolOrDefault>
92 AsmVerbose("asm-verbose", cl::desc("Add comments to directives."),
93            cl::init(cl::BOU_UNSET));
94
95 static bool getVerboseAsm() {
96   switch (AsmVerbose) {
97   case cl::BOU_UNSET: return TargetMachine::getAsmVerbosityDefault();
98   case cl::BOU_TRUE:  return true;
99   case cl::BOU_FALSE: return false;
100   }
101   llvm_unreachable("Invalid verbose asm state");
102 }
103
104 // Enable or disable FastISel. Both options are needed, because
105 // FastISel is enabled by default with -fast, and we wish to be
106 // able to enable or disable fast-isel independently from -O0.
107 static cl::opt<cl::boolOrDefault>
108 EnableFastISelOption("fast-isel", cl::Hidden,
109   cl::desc("Enable the \"fast\" instruction selector"));
110
111 LLVMTargetMachine::LLVMTargetMachine(const Target &T, StringRef Triple,
112                                      StringRef CPU, StringRef FS,
113                                      TargetOptions Options,
114                                      Reloc::Model RM, CodeModel::Model CM,
115                                      CodeGenOpt::Level OL)
116   : TargetMachine(T, Triple, CPU, FS, Options) {
117   CodeGenInfo = T.createMCCodeGenInfo(Triple, RM, CM, OL);
118   AsmInfo = T.createMCAsmInfo(Triple);
119   // TargetSelect.h moved to a different directory between LLVM 2.9 and 3.0,
120   // and if the old one gets included then MCAsmInfo will be NULL and
121   // we'll crash later.
122   // Provide the user with a useful error message about what's wrong.
123   assert(AsmInfo && "MCAsmInfo not initialized."
124          "Make sure you include the correct TargetSelect.h"
125          "and that InitializeAllTargetMCs() is being invoked!");
126 }
127
128 /// createPassConfig - Create a pass configuration object to be used by
129 /// addPassToEmitX methods for generating a pipeline of CodeGen passes.
130 TargetPassConfig *LLVMTargetMachine::createPassConfig(PassManagerBase &PM,
131                                                       bool DisableVerify) {
132   return new TargetPassConfig(this, PM, DisableVerify);
133 }
134
135 bool LLVMTargetMachine::addPassesToEmitFile(PassManagerBase &PM,
136                                             formatted_raw_ostream &Out,
137                                             CodeGenFileType FileType,
138                                             bool DisableVerify) {
139   // Add common CodeGen passes.
140   MCContext *Context = 0;
141   OwningPtr<TargetPassConfig> PassConfig(createPassConfig(PM, DisableVerify));
142   if (PassConfig->addCodeGenPasses(Context))
143     return true;
144   assert(Context != 0 && "Failed to get MCContext");
145
146   if (hasMCSaveTempLabels())
147     Context->setAllowTemporaryLabels(false);
148
149   const MCAsmInfo &MAI = *getMCAsmInfo();
150   const MCSubtargetInfo &STI = getSubtarget<MCSubtargetInfo>();
151   OwningPtr<MCStreamer> AsmStreamer;
152
153   switch (FileType) {
154   case CGFT_AssemblyFile: {
155     MCInstPrinter *InstPrinter =
156       getTarget().createMCInstPrinter(MAI.getAssemblerDialect(), MAI, STI);
157
158     // Create a code emitter if asked to show the encoding.
159     MCCodeEmitter *MCE = 0;
160     MCAsmBackend *MAB = 0;
161     if (ShowMCEncoding) {
162       const MCSubtargetInfo &STI = getSubtarget<MCSubtargetInfo>();
163       MCE = getTarget().createMCCodeEmitter(*getInstrInfo(), STI, *Context);
164       MAB = getTarget().createMCAsmBackend(getTargetTriple());
165     }
166
167     MCStreamer *S = getTarget().createAsmStreamer(*Context, Out,
168                                                   getVerboseAsm(),
169                                                   hasMCUseLoc(),
170                                                   hasMCUseCFI(),
171                                                   hasMCUseDwarfDirectory(),
172                                                   InstPrinter,
173                                                   MCE, MAB,
174                                                   ShowMCInst);
175     AsmStreamer.reset(S);
176     break;
177   }
178   case CGFT_ObjectFile: {
179     // Create the code emitter for the target if it exists.  If not, .o file
180     // emission fails.
181     MCCodeEmitter *MCE = getTarget().createMCCodeEmitter(*getInstrInfo(), STI,
182                                                          *Context);
183     MCAsmBackend *MAB = getTarget().createMCAsmBackend(getTargetTriple());
184     if (MCE == 0 || MAB == 0)
185       return true;
186
187     AsmStreamer.reset(getTarget().createMCObjectStreamer(getTargetTriple(),
188                                                          *Context, *MAB, Out,
189                                                          MCE, hasMCRelaxAll(),
190                                                          hasMCNoExecStack()));
191     AsmStreamer.get()->InitSections();
192     break;
193   }
194   case CGFT_Null:
195     // The Null output is intended for use for performance analysis and testing,
196     // not real users.
197     AsmStreamer.reset(createNullStreamer(*Context));
198     break;
199   }
200
201   // Create the AsmPrinter, which takes ownership of AsmStreamer if successful.
202   FunctionPass *Printer = getTarget().createAsmPrinter(*this, *AsmStreamer);
203   if (Printer == 0)
204     return true;
205
206   // If successful, createAsmPrinter took ownership of AsmStreamer.
207   AsmStreamer.take();
208
209   PM.add(Printer);
210
211   PM.add(createGCInfoDeleter());
212   return false;
213 }
214
215 /// addPassesToEmitMachineCode - Add passes to the specified pass manager to
216 /// get machine code emitted.  This uses a JITCodeEmitter object to handle
217 /// actually outputting the machine code and resolving things like the address
218 /// of functions.  This method should returns true if machine code emission is
219 /// not supported.
220 ///
221 bool LLVMTargetMachine::addPassesToEmitMachineCode(PassManagerBase &PM,
222                                                    JITCodeEmitter &JCE,
223                                                    bool DisableVerify) {
224   // Add common CodeGen passes.
225   MCContext *Ctx = 0;
226   OwningPtr<TargetPassConfig> PassConfig(createPassConfig(PM, DisableVerify));
227   if (PassConfig->addCodeGenPasses(Ctx))
228     return true;
229
230   addCodeEmitter(PM, 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                                           raw_ostream &Out,
244                                           bool DisableVerify) {
245   // Add common CodeGen passes.
246   OwningPtr<TargetPassConfig> PassConfig(createPassConfig(PM, DisableVerify));
247   if (PassConfig->addCodeGenPasses(Ctx))
248     return true;
249
250   if (hasMCSaveTempLabels())
251     Ctx->setAllowTemporaryLabels(false);
252
253   // Create the code emitter for the target if it exists.  If not, .o file
254   // emission fails.
255   const MCSubtargetInfo &STI = getSubtarget<MCSubtargetInfo>();
256   MCCodeEmitter *MCE = getTarget().createMCCodeEmitter(*getInstrInfo(),STI, *Ctx);
257   MCAsmBackend *MAB = getTarget().createMCAsmBackend(getTargetTriple());
258   if (MCE == 0 || MAB == 0)
259     return true;
260
261   OwningPtr<MCStreamer> AsmStreamer;
262   AsmStreamer.reset(getTarget().createMCObjectStreamer(getTargetTriple(), *Ctx,
263                                                        *MAB, Out, MCE,
264                                                        hasMCRelaxAll(),
265                                                        hasMCNoExecStack()));
266   AsmStreamer.get()->InitSections();
267
268   // Create the AsmPrinter, which takes ownership of AsmStreamer if successful.
269   FunctionPass *Printer = getTarget().createAsmPrinter(*this, *AsmStreamer);
270   if (Printer == 0)
271     return true;
272
273   // If successful, createAsmPrinter took ownership of AsmStreamer.
274   AsmStreamer.take();
275
276   PM.add(Printer);
277
278   return false; // success!
279 }
280
281 void TargetPassConfig::printNoVerify(const char *Banner) const {
282   if (TM->shouldPrintMachineCode())
283     PM.add(createMachineFunctionPrinterPass(dbgs(), Banner));
284 }
285
286 void TargetPassConfig::printAndVerify(const char *Banner) const {
287   if (TM->shouldPrintMachineCode())
288     PM.add(createMachineFunctionPrinterPass(dbgs(), Banner));
289
290   if (VerifyMachineCode)
291     PM.add(createMachineVerifierPass(Banner));
292 }
293
294 /// addCodeGenPasses - Add standard LLVM codegen passes used for both
295 /// emitting to assembly files or machine code output.
296 ///
297 bool TargetPassConfig::addCodeGenPasses(MCContext *&OutContext) {
298   // Standard LLVM-Level Passes.
299
300   // Basic AliasAnalysis support.
301   // Add TypeBasedAliasAnalysis before BasicAliasAnalysis so that
302   // BasicAliasAnalysis wins if they disagree. This is intended to help
303   // support "obvious" type-punning idioms.
304   PM.add(createTypeBasedAliasAnalysisPass());
305   PM.add(createBasicAliasAnalysisPass());
306
307   // Before running any passes, run the verifier to determine if the input
308   // coming from the front-end and/or optimizer is valid.
309   if (!DisableVerify)
310     PM.add(createVerifierPass());
311
312   // Run loop strength reduction before anything else.
313   if (getOptLevel() != CodeGenOpt::None && !DisableLSR) {
314     PM.add(createLoopStrengthReducePass(getTargetLowering()));
315     if (PrintLSR)
316       PM.add(createPrintFunctionPass("\n\n*** Code after LSR ***\n", &dbgs()));
317   }
318
319   PM.add(createGCLoweringPass());
320
321   // Make sure that no unreachable blocks are instruction selected.
322   PM.add(createUnreachableBlockEliminationPass());
323
324   // Turn exception handling constructs into something the code generators can
325   // handle.
326   switch (TM->getMCAsmInfo()->getExceptionHandlingType()) {
327   case ExceptionHandling::SjLj:
328     // SjLj piggy-backs on dwarf for this bit. The cleanups done apply to both
329     // Dwarf EH prepare needs to be run after SjLj prepare. Otherwise,
330     // catch info can get misplaced when a selector ends up more than one block
331     // removed from the parent invoke(s). This could happen when a landing
332     // pad is shared by multiple invokes and is also a target of a normal
333     // edge from elsewhere.
334     PM.add(createSjLjEHPass(getTargetLowering()));
335     // FALLTHROUGH
336   case ExceptionHandling::DwarfCFI:
337   case ExceptionHandling::ARM:
338   case ExceptionHandling::Win64:
339     PM.add(createDwarfEHPass(TM));
340     break;
341   case ExceptionHandling::None:
342     PM.add(createLowerInvokePass(getTargetLowering()));
343
344     // The lower invoke pass may create unreachable code. Remove it.
345     PM.add(createUnreachableBlockEliminationPass());
346     break;
347   }
348
349   if (getOptLevel() != CodeGenOpt::None && !DisableCGP)
350     PM.add(createCodeGenPreparePass(getTargetLowering()));
351
352   PM.add(createStackProtectorPass(getTargetLowering()));
353
354   addPreISel();
355
356   if (PrintISelInput)
357     PM.add(createPrintFunctionPass("\n\n"
358                                    "*** Final LLVM Code input to ISel ***\n",
359                                    &dbgs()));
360
361   // All passes which modify the LLVM IR are now complete; run the verifier
362   // to ensure that the IR is valid.
363   if (!DisableVerify)
364     PM.add(createVerifierPass());
365
366   // Standard Lower-Level Passes.
367
368   // Install a MachineModuleInfo class, which is an immutable pass that holds
369   // all the per-module stuff we're generating, including MCContext.
370   MachineModuleInfo *MMI =
371     new MachineModuleInfo(*TM->getMCAsmInfo(), *TM->getRegisterInfo(),
372                           &getTargetLowering()->getObjFileLowering());
373   PM.add(MMI);
374   OutContext = &MMI->getContext(); // Return the MCContext specifically by-ref.
375
376   // Set up a MachineFunction for the rest of CodeGen to work on.
377   PM.add(new MachineFunctionAnalysis(*TM));
378
379   // Enable FastISel with -fast, but allow that to be overridden.
380   if (EnableFastISelOption == cl::BOU_TRUE ||
381       (getOptLevel() == CodeGenOpt::None &&
382        EnableFastISelOption != cl::BOU_FALSE))
383     TM->setFastISel(true);
384
385   // Ask the target for an isel.
386   if (addInstSelector())
387     return true;
388
389   // Print the instruction selected machine code...
390   printAndVerify("After Instruction Selection");
391
392   // Expand pseudo-instructions emitted by ISel.
393   PM.add(createExpandISelPseudosPass());
394
395   // Pre-ra tail duplication.
396   if (getOptLevel() != CodeGenOpt::None && !DisableEarlyTailDup) {
397     PM.add(createTailDuplicatePass(true));
398     printAndVerify("After Pre-RegAlloc TailDuplicate");
399   }
400
401   // Optimize PHIs before DCE: removing dead PHI cycles may make more
402   // instructions dead.
403   if (getOptLevel() != CodeGenOpt::None)
404     PM.add(createOptimizePHIsPass());
405
406   // If the target requests it, assign local variables to stack slots relative
407   // to one another and simplify frame index references where possible.
408   PM.add(createLocalStackSlotAllocationPass());
409
410   if (getOptLevel() != CodeGenOpt::None) {
411     // With optimization, dead code should already be eliminated. However
412     // there is one known exception: lowered code for arguments that are only
413     // used by tail calls, where the tail calls reuse the incoming stack
414     // arguments directly (see t11 in test/CodeGen/X86/sibcall.ll).
415     if (!DisableMachineDCE)
416       PM.add(createDeadMachineInstructionElimPass());
417     printAndVerify("After codegen DCE pass");
418
419     if (!DisableMachineLICM)
420       PM.add(createMachineLICMPass());
421     if (!DisableMachineCSE)
422       PM.add(createMachineCSEPass());
423     if (!DisableMachineSink)
424       PM.add(createMachineSinkingPass());
425     printAndVerify("After Machine LICM, CSE and Sinking passes");
426
427     PM.add(createPeepholeOptimizerPass());
428     printAndVerify("After codegen peephole optimization pass");
429   }
430
431   // Run pre-ra passes.
432   if (addPreRegAlloc())
433     printAndVerify("After PreRegAlloc passes");
434
435   // Perform register allocation.
436   PM.add(createRegisterAllocator(getOptLevel()));
437   printAndVerify("After Register Allocation");
438
439   // Perform stack slot coloring and post-ra machine LICM.
440   if (getOptLevel() != CodeGenOpt::None) {
441     // FIXME: Re-enable coloring with register when it's capable of adding
442     // kill markers.
443     if (!DisableSSC)
444       PM.add(createStackSlotColoringPass(false));
445
446     // Run post-ra machine LICM to hoist reloads / remats.
447     if (!DisablePostRAMachineLICM)
448       PM.add(createMachineLICMPass(false));
449
450     printAndVerify("After StackSlotColoring and postra Machine LICM");
451   }
452
453   // Run post-ra passes.
454   if (addPostRegAlloc())
455     printAndVerify("After PostRegAlloc passes");
456
457   // Insert prolog/epilog code.  Eliminate abstract frame index references...
458   PM.add(createPrologEpilogCodeInserter());
459   printAndVerify("After PrologEpilogCodeInserter");
460
461   // Branch folding must be run after regalloc and prolog/epilog insertion.
462   if (getOptLevel() != CodeGenOpt::None && !DisableBranchFold) {
463     PM.add(createBranchFoldingPass(getEnableTailMergeDefault()));
464     printNoVerify("After BranchFolding");
465   }
466
467   // Tail duplication.
468   if (getOptLevel() != CodeGenOpt::None && !DisableTailDuplicate) {
469     PM.add(createTailDuplicatePass(false));
470     printNoVerify("After TailDuplicate");
471   }
472
473   // Copy propagation.
474   if (getOptLevel() != CodeGenOpt::None && !DisableCopyProp) {
475     PM.add(createMachineCopyPropagationPass());
476     printNoVerify("After copy propagation pass");
477   }
478
479   // Expand pseudo instructions before second scheduling pass.
480   PM.add(createExpandPostRAPseudosPass());
481   printNoVerify("After ExpandPostRAPseudos");
482
483   // Run pre-sched2 passes.
484   if (addPreSched2())
485     printNoVerify("After PreSched2 passes");
486
487   // Second pass scheduler.
488   if (getOptLevel() != CodeGenOpt::None && !DisablePostRA) {
489     PM.add(createPostRAScheduler(getOptLevel()));
490     printNoVerify("After PostRAScheduler");
491   }
492
493   PM.add(createGCMachineCodeAnalysisPass());
494
495   if (PrintGCInfo)
496     PM.add(createGCInfoPrinter(dbgs()));
497
498   if (getOptLevel() != CodeGenOpt::None && !DisableCodePlace) {
499     if (EnableBlockPlacement) {
500       // MachineBlockPlacement is an experimental pass which is disabled by
501       // default currently. Eventually it should subsume CodePlacementOpt, so
502       // when enabled, the other is disabled.
503       PM.add(createMachineBlockPlacementPass());
504       printNoVerify("After MachineBlockPlacement");
505     } else {
506       PM.add(createCodePlacementOptPass());
507       printNoVerify("After CodePlacementOpt");
508     }
509
510     // Run a separate pass to collect block placement statistics.
511     if (EnableBlockPlacementStats) {
512       PM.add(createMachineBlockPlacementStatsPass());
513       printNoVerify("After MachineBlockPlacementStats");
514     }
515   }
516
517   if (addPreEmitPass())
518     printNoVerify("After PreEmit passes");
519
520   return false;
521 }