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