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