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