Add an experimental early if-conversion pass, off by default.
[oota-llvm.git] / lib / CodeGen / Passes.cpp
1 //===-- Passes.cpp - Target independent code generation passes ------------===//
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 defines interfaces to access the target independent code
11 // generation passes provided by the LLVM backend.
12 //
13 //===---------------------------------------------------------------------===//
14
15 #include "llvm/Analysis/Passes.h"
16 #include "llvm/Analysis/Verifier.h"
17 #include "llvm/Transforms/Scalar.h"
18 #include "llvm/PassManager.h"
19 #include "llvm/CodeGen/GCStrategy.h"
20 #include "llvm/CodeGen/MachineFunctionPass.h"
21 #include "llvm/CodeGen/Passes.h"
22 #include "llvm/CodeGen/RegAllocRegistry.h"
23 #include "llvm/Target/TargetLowering.h"
24 #include "llvm/Target/TargetOptions.h"
25 #include "llvm/MC/MCAsmInfo.h"
26 #include "llvm/Assembly/PrintModulePass.h"
27 #include "llvm/Support/CommandLine.h"
28 #include "llvm/Support/Debug.h"
29 #include "llvm/Support/ErrorHandling.h"
30
31 using namespace llvm;
32
33 static cl::opt<bool> DisablePostRA("disable-post-ra", cl::Hidden,
34     cl::desc("Disable Post Regalloc"));
35 static cl::opt<bool> DisableBranchFold("disable-branch-fold", cl::Hidden,
36     cl::desc("Disable branch folding"));
37 static cl::opt<bool> DisableTailDuplicate("disable-tail-duplicate", cl::Hidden,
38     cl::desc("Disable tail duplication"));
39 static cl::opt<bool> DisableEarlyTailDup("disable-early-taildup", cl::Hidden,
40     cl::desc("Disable pre-register allocation tail duplication"));
41 static cl::opt<bool> DisableBlockPlacement("disable-block-placement",
42     cl::Hidden, cl::desc("Disable the probability-driven block placement, and "
43                          "re-enable the old code placement pass"));
44 static cl::opt<bool> EnableBlockPlacementStats("enable-block-placement-stats",
45     cl::Hidden, cl::desc("Collect probability-driven block placement stats"));
46 static cl::opt<bool> DisableCodePlace("disable-code-place", cl::Hidden,
47     cl::desc("Disable code placement"));
48 static cl::opt<bool> DisableSSC("disable-ssc", cl::Hidden,
49     cl::desc("Disable Stack Slot Coloring"));
50 static cl::opt<bool> DisableMachineDCE("disable-machine-dce", cl::Hidden,
51     cl::desc("Disable Machine Dead Code Elimination"));
52 static cl::opt<bool> EnableEarlyIfConversion("enable-early-ifcvt", cl::Hidden,
53     cl::desc("Enable Early If-conversion"));
54 static cl::opt<bool> DisableMachineLICM("disable-machine-licm", cl::Hidden,
55     cl::desc("Disable Machine LICM"));
56 static cl::opt<bool> DisableMachineCSE("disable-machine-cse", cl::Hidden,
57     cl::desc("Disable Machine Common Subexpression Elimination"));
58 static cl::opt<cl::boolOrDefault>
59 OptimizeRegAlloc("optimize-regalloc", cl::Hidden,
60     cl::desc("Enable optimized register allocation compilation path."));
61 static cl::opt<cl::boolOrDefault>
62 EnableMachineSched("enable-misched", cl::Hidden,
63     cl::desc("Enable the machine instruction scheduling pass."));
64 static cl::opt<bool> EnableStrongPHIElim("strong-phi-elim", cl::Hidden,
65     cl::desc("Use strong PHI 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> VerifyMachineCode("verify-machineinstrs", cl::Hidden,
84     cl::desc("Verify generated machine code"),
85     cl::init(getenv("LLVM_VERIFY_MACHINEINSTRS")!=NULL));
86 static cl::opt<std::string>
87 PrintMachineInstrs("print-machineinstrs", cl::ValueOptional,
88                    cl::desc("Print machine instrs"),
89                    cl::value_desc("pass-name"), cl::init("option-unspecified"));
90
91 /// Allow standard passes to be disabled by command line options. This supports
92 /// simple binary flags that either suppress the pass or do nothing.
93 /// i.e. -disable-mypass=false has no effect.
94 /// These should be converted to boolOrDefault in order to use applyOverride.
95 static AnalysisID applyDisable(AnalysisID PassID, bool Override) {
96   if (Override)
97     return 0;
98   return PassID;
99 }
100
101 /// Allow Pass selection to be overriden by command line options. This supports
102 /// flags with ternary conditions. TargetID is passed through by default. The
103 /// pass is suppressed when the option is false. When the option is true, the
104 /// StandardID is selected if the target provides no default.
105 static AnalysisID applyOverride(AnalysisID TargetID, cl::boolOrDefault Override,
106                                 AnalysisID StandardID) {
107   switch (Override) {
108   case cl::BOU_UNSET:
109     return TargetID;
110   case cl::BOU_TRUE:
111     if (TargetID)
112       return TargetID;
113     if (StandardID == 0)
114       report_fatal_error("Target cannot enable pass");
115     return StandardID;
116   case cl::BOU_FALSE:
117     return 0;
118   }
119   llvm_unreachable("Invalid command line option state");
120 }
121
122 /// Allow standard passes to be disabled by the command line, regardless of who
123 /// is adding the pass.
124 ///
125 /// StandardID is the pass identified in the standard pass pipeline and provided
126 /// to addPass(). It may be a target-specific ID in the case that the target
127 /// directly adds its own pass, but in that case we harmlessly fall through.
128 ///
129 /// TargetID is the pass that the target has configured to override StandardID.
130 ///
131 /// StandardID may be a pseudo ID. In that case TargetID is the name of the real
132 /// pass to run. This allows multiple options to control a single pass depending
133 /// on where in the pipeline that pass is added.
134 static AnalysisID overridePass(AnalysisID StandardID, AnalysisID TargetID) {
135   if (StandardID == &PostRASchedulerID)
136     return applyDisable(TargetID, DisablePostRA);
137
138   if (StandardID == &BranchFolderPassID)
139     return applyDisable(TargetID, DisableBranchFold);
140
141   if (StandardID == &TailDuplicateID)
142     return applyDisable(TargetID, DisableTailDuplicate);
143
144   if (StandardID == &TargetPassConfig::EarlyTailDuplicateID)
145     return applyDisable(TargetID, DisableEarlyTailDup);
146
147   if (StandardID == &MachineBlockPlacementID)
148     return applyDisable(TargetID, DisableCodePlace);
149
150   if (StandardID == &CodePlacementOptID)
151     return applyDisable(TargetID, DisableCodePlace);
152
153   if (StandardID == &StackSlotColoringID)
154     return applyDisable(TargetID, DisableSSC);
155
156   if (StandardID == &DeadMachineInstructionElimID)
157     return applyDisable(TargetID, DisableMachineDCE);
158
159   if (StandardID == &EarlyIfConverterID)
160     return applyDisable(TargetID, !EnableEarlyIfConversion);
161
162   if (StandardID == &MachineLICMID)
163     return applyDisable(TargetID, DisableMachineLICM);
164
165   if (StandardID == &MachineCSEID)
166     return applyDisable(TargetID, DisableMachineCSE);
167
168   if (StandardID == &MachineSchedulerID)
169     return applyOverride(TargetID, EnableMachineSched, StandardID);
170
171   if (StandardID == &TargetPassConfig::PostRAMachineLICMID)
172     return applyDisable(TargetID, DisablePostRAMachineLICM);
173
174   if (StandardID == &MachineSinkingID)
175     return applyDisable(TargetID, DisableMachineSink);
176
177   if (StandardID == &MachineCopyPropagationID)
178     return applyDisable(TargetID, DisableCopyProp);
179
180   return TargetID;
181 }
182
183 //===---------------------------------------------------------------------===//
184 /// TargetPassConfig
185 //===---------------------------------------------------------------------===//
186
187 INITIALIZE_PASS(TargetPassConfig, "targetpassconfig",
188                 "Target Pass Configuration", false, false)
189 char TargetPassConfig::ID = 0;
190
191 // Pseudo Pass IDs.
192 char TargetPassConfig::EarlyTailDuplicateID = 0;
193 char TargetPassConfig::PostRAMachineLICMID = 0;
194
195 namespace llvm {
196 class PassConfigImpl {
197 public:
198   // List of passes explicitly substituted by this target. Normally this is
199   // empty, but it is a convenient way to suppress or replace specific passes
200   // that are part of a standard pass pipeline without overridding the entire
201   // pipeline. This mechanism allows target options to inherit a standard pass's
202   // user interface. For example, a target may disable a standard pass by
203   // default by substituting a pass ID of zero, and the user may still enable
204   // that standard pass with an explicit command line option.
205   DenseMap<AnalysisID,AnalysisID> TargetPasses;
206
207   /// Store the pairs of <AnalysisID, AnalysisID> of which the second pass
208   /// is inserted after each instance of the first one.
209   SmallVector<std::pair<AnalysisID, AnalysisID>, 4> InsertedPasses;
210 };
211 } // namespace llvm
212
213 // Out of line virtual method.
214 TargetPassConfig::~TargetPassConfig() {
215   delete Impl;
216 }
217
218 // Out of line constructor provides default values for pass options and
219 // registers all common codegen passes.
220 TargetPassConfig::TargetPassConfig(TargetMachine *tm, PassManagerBase &pm)
221   : ImmutablePass(ID), PM(&pm), StartAfter(0), StopAfter(0),
222     Started(true), Stopped(false), TM(tm), Impl(0), Initialized(false),
223     DisableVerify(false),
224     EnableTailMerge(true) {
225
226   Impl = new PassConfigImpl();
227
228   // Register all target independent codegen passes to activate their PassIDs,
229   // including this pass itself.
230   initializeCodeGen(*PassRegistry::getPassRegistry());
231
232   // Substitute Pseudo Pass IDs for real ones.
233   substitutePass(&EarlyTailDuplicateID, &TailDuplicateID);
234   substitutePass(&PostRAMachineLICMID, &MachineLICMID);
235
236   // Disable early if-conversion. Targets that are ready can enable it.
237   disablePass(&EarlyIfConverterID);
238
239   // Temporarily disable experimental passes.
240   substitutePass(&MachineSchedulerID, 0);
241 }
242
243 /// Insert InsertedPassID pass after TargetPassID.
244 void TargetPassConfig::insertPass(AnalysisID TargetPassID,
245                                   AnalysisID InsertedPassID) {
246   assert(TargetPassID != InsertedPassID && "Insert a pass after itself!");
247   std::pair<AnalysisID, AnalysisID> P(TargetPassID, InsertedPassID);
248   Impl->InsertedPasses.push_back(P);
249 }
250
251 /// createPassConfig - Create a pass configuration object to be used by
252 /// addPassToEmitX methods for generating a pipeline of CodeGen passes.
253 ///
254 /// Targets may override this to extend TargetPassConfig.
255 TargetPassConfig *LLVMTargetMachine::createPassConfig(PassManagerBase &PM) {
256   return new TargetPassConfig(this, PM);
257 }
258
259 TargetPassConfig::TargetPassConfig()
260   : ImmutablePass(ID), PM(0) {
261   llvm_unreachable("TargetPassConfig should not be constructed on-the-fly");
262 }
263
264 // Helper to verify the analysis is really immutable.
265 void TargetPassConfig::setOpt(bool &Opt, bool Val) {
266   assert(!Initialized && "PassConfig is immutable");
267   Opt = Val;
268 }
269
270 void TargetPassConfig::substitutePass(AnalysisID StandardID,
271                                       AnalysisID TargetID) {
272   Impl->TargetPasses[StandardID] = TargetID;
273 }
274
275 AnalysisID TargetPassConfig::getPassSubstitution(AnalysisID ID) const {
276   DenseMap<AnalysisID, AnalysisID>::const_iterator
277     I = Impl->TargetPasses.find(ID);
278   if (I == Impl->TargetPasses.end())
279     return ID;
280   return I->second;
281 }
282
283 /// Add a pass to the PassManager if that pass is supposed to be run.  If the
284 /// Started/Stopped flags indicate either that the compilation should start at
285 /// a later pass or that it should stop after an earlier pass, then do not add
286 /// the pass.  Finally, compare the current pass against the StartAfter
287 /// and StopAfter options and change the Started/Stopped flags accordingly.
288 void TargetPassConfig::addPass(Pass *P) {
289   assert(!Initialized && "PassConfig is immutable");
290
291   // Cache the Pass ID here in case the pass manager finds this pass is
292   // redundant with ones already scheduled / available, and deletes it.
293   // Fundamentally, once we add the pass to the manager, we no longer own it
294   // and shouldn't reference it.
295   AnalysisID PassID = P->getPassID();
296
297   if (Started && !Stopped)
298     PM->add(P);
299   if (StopAfter == PassID)
300     Stopped = true;
301   if (StartAfter == PassID)
302     Started = true;
303   if (Stopped && !Started)
304     report_fatal_error("Cannot stop compilation after pass that is not run");
305 }
306
307 /// Add a CodeGen pass at this point in the pipeline after checking for target
308 /// and command line overrides.
309 AnalysisID TargetPassConfig::addPass(AnalysisID PassID) {
310   AnalysisID TargetID = getPassSubstitution(PassID);
311   AnalysisID FinalID = overridePass(PassID, TargetID);
312   if (FinalID == 0)
313     return FinalID;
314
315   Pass *P = Pass::createPass(FinalID);
316   if (!P)
317     llvm_unreachable("Pass ID not registered");
318   addPass(P);
319   // Add the passes after the pass P if there is any.
320   for (SmallVector<std::pair<AnalysisID, AnalysisID>, 4>::iterator
321          I = Impl->InsertedPasses.begin(), E = Impl->InsertedPasses.end();
322        I != E; ++I) {
323     if ((*I).first == PassID) {
324       assert((*I).second && "Illegal Pass ID!");
325       Pass *NP = Pass::createPass((*I).second);
326       assert(NP && "Pass ID not registered");
327       addPass(NP);
328     }
329   }
330   return FinalID;
331 }
332
333 void TargetPassConfig::printAndVerify(const char *Banner) {
334   if (TM->shouldPrintMachineCode())
335     addPass(createMachineFunctionPrinterPass(dbgs(), Banner));
336
337   if (VerifyMachineCode)
338     addPass(createMachineVerifierPass(Banner));
339 }
340
341 /// Add common target configurable passes that perform LLVM IR to IR transforms
342 /// following machine independent optimization.
343 void TargetPassConfig::addIRPasses() {
344   // Basic AliasAnalysis support.
345   // Add TypeBasedAliasAnalysis before BasicAliasAnalysis so that
346   // BasicAliasAnalysis wins if they disagree. This is intended to help
347   // support "obvious" type-punning idioms.
348   addPass(createTypeBasedAliasAnalysisPass());
349   addPass(createBasicAliasAnalysisPass());
350
351   // Before running any passes, run the verifier to determine if the input
352   // coming from the front-end and/or optimizer is valid.
353   if (!DisableVerify)
354     addPass(createVerifierPass());
355
356   // Run loop strength reduction before anything else.
357   if (getOptLevel() != CodeGenOpt::None && !DisableLSR) {
358     addPass(createLoopStrengthReducePass(getTargetLowering()));
359     if (PrintLSR)
360       addPass(createPrintFunctionPass("\n\n*** Code after LSR ***\n", &dbgs()));
361   }
362
363   addPass(createGCLoweringPass());
364
365   // Make sure that no unreachable blocks are instruction selected.
366   addPass(createUnreachableBlockEliminationPass());
367 }
368
369 /// Turn exception handling constructs into something the code generators can
370 /// handle.
371 void TargetPassConfig::addPassesToHandleExceptions() {
372   switch (TM->getMCAsmInfo()->getExceptionHandlingType()) {
373   case ExceptionHandling::SjLj:
374     // SjLj piggy-backs on dwarf for this bit. The cleanups done apply to both
375     // Dwarf EH prepare needs to be run after SjLj prepare. Otherwise,
376     // catch info can get misplaced when a selector ends up more than one block
377     // removed from the parent invoke(s). This could happen when a landing
378     // pad is shared by multiple invokes and is also a target of a normal
379     // edge from elsewhere.
380     addPass(createSjLjEHPreparePass(TM->getTargetLowering()));
381     // FALLTHROUGH
382   case ExceptionHandling::DwarfCFI:
383   case ExceptionHandling::ARM:
384   case ExceptionHandling::Win64:
385     addPass(createDwarfEHPass(TM));
386     break;
387   case ExceptionHandling::None:
388     addPass(createLowerInvokePass(TM->getTargetLowering()));
389
390     // The lower invoke pass may create unreachable code. Remove it.
391     addPass(createUnreachableBlockEliminationPass());
392     break;
393   }
394 }
395
396 /// Add common passes that perform LLVM IR to IR transforms in preparation for
397 /// instruction selection.
398 void TargetPassConfig::addISelPrepare() {
399   if (getOptLevel() != CodeGenOpt::None && !DisableCGP)
400     addPass(createCodeGenPreparePass(getTargetLowering()));
401
402   addPass(createStackProtectorPass(getTargetLowering()));
403
404   addPreISel();
405
406   if (PrintISelInput)
407     addPass(createPrintFunctionPass("\n\n"
408                                     "*** Final LLVM Code input to ISel ***\n",
409                                     &dbgs()));
410
411   // All passes which modify the LLVM IR are now complete; run the verifier
412   // to ensure that the IR is valid.
413   if (!DisableVerify)
414     addPass(createVerifierPass());
415 }
416
417 /// Add the complete set of target-independent postISel code generator passes.
418 ///
419 /// This can be read as the standard order of major LLVM CodeGen stages. Stages
420 /// with nontrivial configuration or multiple passes are broken out below in
421 /// add%Stage routines.
422 ///
423 /// Any TargetPassConfig::addXX routine may be overriden by the Target. The
424 /// addPre/Post methods with empty header implementations allow injecting
425 /// target-specific fixups just before or after major stages. Additionally,
426 /// targets have the flexibility to change pass order within a stage by
427 /// overriding default implementation of add%Stage routines below. Each
428 /// technique has maintainability tradeoffs because alternate pass orders are
429 /// not well supported. addPre/Post works better if the target pass is easily
430 /// tied to a common pass. But if it has subtle dependencies on multiple passes,
431 /// the target should override the stage instead.
432 ///
433 /// TODO: We could use a single addPre/Post(ID) hook to allow pass injection
434 /// before/after any target-independent pass. But it's currently overkill.
435 void TargetPassConfig::addMachinePasses() {
436   // Print the instruction selected machine code...
437   printAndVerify("After Instruction Selection");
438
439   // Insert a machine instr printer pass after the specified pass.
440   // If -print-machineinstrs specified, print machineinstrs after all passes.
441   if (StringRef(PrintMachineInstrs.getValue()).equals(""))
442     TM->Options.PrintMachineCode = true;
443   else if (!StringRef(PrintMachineInstrs.getValue())
444            .equals("option-unspecified")) {
445     const PassRegistry *PR = PassRegistry::getPassRegistry();
446     const PassInfo *TPI = PR->getPassInfo(PrintMachineInstrs.getValue());
447     const PassInfo *IPI = PR->getPassInfo(StringRef("print-machineinstrs"));
448     assert (TPI && IPI && "Pass ID not registered!");
449     const char *TID = (char *)(TPI->getTypeInfo());
450     const char *IID = (char *)(IPI->getTypeInfo());
451     insertPass(TID, IID);
452   }
453
454   // Expand pseudo-instructions emitted by ISel.
455   addPass(&ExpandISelPseudosID);
456
457   // Add passes that optimize machine instructions in SSA form.
458   if (getOptLevel() != CodeGenOpt::None) {
459     addMachineSSAOptimization();
460   }
461   else {
462     // If the target requests it, assign local variables to stack slots relative
463     // to one another and simplify frame index references where possible.
464     addPass(&LocalStackSlotAllocationID);
465   }
466
467   // Run pre-ra passes.
468   if (addPreRegAlloc())
469     printAndVerify("After PreRegAlloc passes");
470
471   // Run register allocation and passes that are tightly coupled with it,
472   // including phi elimination and scheduling.
473   if (getOptimizeRegAlloc())
474     addOptimizedRegAlloc(createRegAllocPass(true));
475   else
476     addFastRegAlloc(createRegAllocPass(false));
477
478   // Run post-ra passes.
479   if (addPostRegAlloc())
480     printAndVerify("After PostRegAlloc passes");
481
482   // Insert prolog/epilog code.  Eliminate abstract frame index references...
483   addPass(&PrologEpilogCodeInserterID);
484   printAndVerify("After PrologEpilogCodeInserter");
485
486   /// Add passes that optimize machine instructions after register allocation.
487   if (getOptLevel() != CodeGenOpt::None)
488     addMachineLateOptimization();
489
490   // Expand pseudo instructions before second scheduling pass.
491   addPass(&ExpandPostRAPseudosID);
492   printAndVerify("After ExpandPostRAPseudos");
493
494   // Run pre-sched2 passes.
495   if (addPreSched2())
496     printAndVerify("After PreSched2 passes");
497
498   // Second pass scheduler.
499   if (getOptLevel() != CodeGenOpt::None) {
500     addPass(&PostRASchedulerID);
501     printAndVerify("After PostRAScheduler");
502   }
503
504   // GC
505   addPass(&GCMachineCodeAnalysisID);
506   if (PrintGCInfo)
507     addPass(createGCInfoPrinter(dbgs()));
508
509   // Basic block placement.
510   if (getOptLevel() != CodeGenOpt::None)
511     addBlockPlacement();
512
513   if (addPreEmitPass())
514     printAndVerify("After PreEmit passes");
515 }
516
517 /// Add passes that optimize machine instructions in SSA form.
518 void TargetPassConfig::addMachineSSAOptimization() {
519   // Pre-ra tail duplication.
520   if (addPass(&EarlyTailDuplicateID))
521     printAndVerify("After Pre-RegAlloc TailDuplicate");
522
523   // Optimize PHIs before DCE: removing dead PHI cycles may make more
524   // instructions dead.
525   addPass(&OptimizePHIsID);
526
527   // If the target requests it, assign local variables to stack slots relative
528   // to one another and simplify frame index references where possible.
529   addPass(&LocalStackSlotAllocationID);
530
531   // With optimization, dead code should already be eliminated. However
532   // there is one known exception: lowered code for arguments that are only
533   // used by tail calls, where the tail calls reuse the incoming stack
534   // arguments directly (see t11 in test/CodeGen/X86/sibcall.ll).
535   addPass(&DeadMachineInstructionElimID);
536   printAndVerify("After codegen DCE pass");
537
538   addPass(&EarlyIfConverterID);
539   addPass(&MachineLICMID);
540   addPass(&MachineCSEID);
541   addPass(&MachineSinkingID);
542   printAndVerify("After Machine LICM, CSE and Sinking passes");
543
544   addPass(&PeepholeOptimizerID);
545   printAndVerify("After codegen peephole optimization pass");
546 }
547
548 //===---------------------------------------------------------------------===//
549 /// Register Allocation Pass Configuration
550 //===---------------------------------------------------------------------===//
551
552 bool TargetPassConfig::getOptimizeRegAlloc() const {
553   switch (OptimizeRegAlloc) {
554   case cl::BOU_UNSET: return getOptLevel() != CodeGenOpt::None;
555   case cl::BOU_TRUE:  return true;
556   case cl::BOU_FALSE: return false;
557   }
558   llvm_unreachable("Invalid optimize-regalloc state");
559 }
560
561 /// RegisterRegAlloc's global Registry tracks allocator registration.
562 MachinePassRegistry RegisterRegAlloc::Registry;
563
564 /// A dummy default pass factory indicates whether the register allocator is
565 /// overridden on the command line.
566 static FunctionPass *useDefaultRegisterAllocator() { return 0; }
567 static RegisterRegAlloc
568 defaultRegAlloc("default",
569                 "pick register allocator based on -O option",
570                 useDefaultRegisterAllocator);
571
572 /// -regalloc=... command line option.
573 static cl::opt<RegisterRegAlloc::FunctionPassCtor, false,
574                RegisterPassParser<RegisterRegAlloc> >
575 RegAlloc("regalloc",
576          cl::init(&useDefaultRegisterAllocator),
577          cl::desc("Register allocator to use"));
578
579
580 /// Instantiate the default register allocator pass for this target for either
581 /// the optimized or unoptimized allocation path. This will be added to the pass
582 /// manager by addFastRegAlloc in the unoptimized case or addOptimizedRegAlloc
583 /// in the optimized case.
584 ///
585 /// A target that uses the standard regalloc pass order for fast or optimized
586 /// allocation may still override this for per-target regalloc
587 /// selection. But -regalloc=... always takes precedence.
588 FunctionPass *TargetPassConfig::createTargetRegisterAllocator(bool Optimized) {
589   if (Optimized)
590     return createGreedyRegisterAllocator();
591   else
592     return createFastRegisterAllocator();
593 }
594
595 /// Find and instantiate the register allocation pass requested by this target
596 /// at the current optimization level.  Different register allocators are
597 /// defined as separate passes because they may require different analysis.
598 ///
599 /// This helper ensures that the regalloc= option is always available,
600 /// even for targets that override the default allocator.
601 ///
602 /// FIXME: When MachinePassRegistry register pass IDs instead of function ptrs,
603 /// this can be folded into addPass.
604 FunctionPass *TargetPassConfig::createRegAllocPass(bool Optimized) {
605   RegisterRegAlloc::FunctionPassCtor Ctor = RegisterRegAlloc::getDefault();
606
607   // Initialize the global default.
608   if (!Ctor) {
609     Ctor = RegAlloc;
610     RegisterRegAlloc::setDefault(RegAlloc);
611   }
612   if (Ctor != useDefaultRegisterAllocator)
613     return Ctor();
614
615   // With no -regalloc= override, ask the target for a regalloc pass.
616   return createTargetRegisterAllocator(Optimized);
617 }
618
619 /// Add the minimum set of target-independent passes that are required for
620 /// register allocation. No coalescing or scheduling.
621 void TargetPassConfig::addFastRegAlloc(FunctionPass *RegAllocPass) {
622   addPass(&PHIEliminationID);
623   addPass(&TwoAddressInstructionPassID);
624
625   addPass(RegAllocPass);
626   printAndVerify("After Register Allocation");
627 }
628
629 /// Add standard target-independent passes that are tightly coupled with
630 /// optimized register allocation, including coalescing, machine instruction
631 /// scheduling, and register allocation itself.
632 void TargetPassConfig::addOptimizedRegAlloc(FunctionPass *RegAllocPass) {
633   addPass(&ProcessImplicitDefsID);
634
635   // LiveVariables currently requires pure SSA form.
636   //
637   // FIXME: Once TwoAddressInstruction pass no longer uses kill flags,
638   // LiveVariables can be removed completely, and LiveIntervals can be directly
639   // computed. (We still either need to regenerate kill flags after regalloc, or
640   // preferably fix the scavenger to not depend on them).
641   addPass(&LiveVariablesID);
642
643   // Add passes that move from transformed SSA into conventional SSA. This is a
644   // "copy coalescing" problem.
645   //
646   if (!EnableStrongPHIElim) {
647     // Edge splitting is smarter with machine loop info.
648     addPass(&MachineLoopInfoID);
649     addPass(&PHIEliminationID);
650   }
651   addPass(&TwoAddressInstructionPassID);
652
653   if (EnableStrongPHIElim)
654     addPass(&StrongPHIEliminationID);
655
656   addPass(&RegisterCoalescerID);
657
658   // PreRA instruction scheduling.
659   if (addPass(&MachineSchedulerID))
660     printAndVerify("After Machine Scheduling");
661
662   // Add the selected register allocation pass.
663   addPass(RegAllocPass);
664   printAndVerify("After Register Allocation, before rewriter");
665
666   // Allow targets to change the register assignments before rewriting.
667   if (addPreRewrite())
668     printAndVerify("After pre-rewrite passes");
669
670   // Finally rewrite virtual registers.
671   addPass(&VirtRegRewriterID);
672   printAndVerify("After Virtual Register Rewriter");
673
674   // FinalizeRegAlloc is convenient until MachineInstrBundles is more mature,
675   // but eventually, all users of it should probably be moved to addPostRA and
676   // it can go away.  Currently, it's the intended place for targets to run
677   // FinalizeMachineBundles, because passes other than MachineScheduling an
678   // RegAlloc itself may not be aware of bundles.
679   if (addFinalizeRegAlloc())
680     printAndVerify("After RegAlloc finalization");
681
682   // Perform stack slot coloring and post-ra machine LICM.
683   //
684   // FIXME: Re-enable coloring with register when it's capable of adding
685   // kill markers.
686   addPass(&StackSlotColoringID);
687
688   // Run post-ra machine LICM to hoist reloads / remats.
689   //
690   // FIXME: can this move into MachineLateOptimization?
691   addPass(&PostRAMachineLICMID);
692
693   printAndVerify("After StackSlotColoring and postra Machine LICM");
694 }
695
696 //===---------------------------------------------------------------------===//
697 /// Post RegAlloc Pass Configuration
698 //===---------------------------------------------------------------------===//
699
700 /// Add passes that optimize machine instructions after register allocation.
701 void TargetPassConfig::addMachineLateOptimization() {
702   // Branch folding must be run after regalloc and prolog/epilog insertion.
703   if (addPass(&BranchFolderPassID))
704     printAndVerify("After BranchFolding");
705
706   // Tail duplication.
707   if (addPass(&TailDuplicateID))
708     printAndVerify("After TailDuplicate");
709
710   // Copy propagation.
711   if (addPass(&MachineCopyPropagationID))
712     printAndVerify("After copy propagation pass");
713 }
714
715 /// Add standard basic block placement passes.
716 void TargetPassConfig::addBlockPlacement() {
717   AnalysisID PassID = 0;
718   if (!DisableBlockPlacement) {
719     // MachineBlockPlacement is a new pass which subsumes the functionality of
720     // CodPlacementOpt. The old code placement pass can be restored by
721     // disabling block placement, but eventually it will be removed.
722     PassID = addPass(&MachineBlockPlacementID);
723   } else {
724     PassID = addPass(&CodePlacementOptID);
725   }
726   if (PassID) {
727     // Run a separate pass to collect block placement statistics.
728     if (EnableBlockPlacementStats)
729       addPass(&MachineBlockPlacementStatsID);
730
731     printAndVerify("After machine block placement.");
732   }
733 }