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