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