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).
100 // Targets can return true in targetSchedulesPostRAScheduling() and
101 // insert a PostRA scheduling pass wherever it wants.
102 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.
applyDisable(IdentifyingPassPtr PassID,bool Override)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.
overridePass(AnalysisID StandardID,IdentifyingPassPtr TargetID)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 {
193 struct InsertedPass {
194   AnalysisID TargetPassID;
195   IdentifyingPassPtr InsertedPassID;
196   bool VerifyAfter;
197   bool PrintAfter;
198 
InsertedPass__anone1b8a5c50111::InsertedPass199   InsertedPass(AnalysisID TargetPassID, IdentifyingPassPtr InsertedPassID,
200                bool VerifyAfter, bool PrintAfter)
201       : TargetPassID(TargetPassID), InsertedPassID(InsertedPassID),
202         VerifyAfter(VerifyAfter), PrintAfter(PrintAfter) {}
203 
getInsertedPass__anone1b8a5c50111::InsertedPass204   Pass *getInsertedPass() const {
205     assert(InsertedPassID.isValid() && "Illegal Pass ID!");
206     if (InsertedPassID.isInstance())
207       return InsertedPassID.getInstance();
208     Pass *NP = Pass::createPass(InsertedPassID.getID());
209     assert(NP && "Pass ID not registered");
210     return NP;
211   }
212 };
213 }
214 
215 namespace llvm {
216 class PassConfigImpl {
217 public:
218   // List of passes explicitly substituted by this target. Normally this is
219   // empty, but it is a convenient way to suppress or replace specific passes
220   // that are part of a standard pass pipeline without overridding the entire
221   // pipeline. This mechanism allows target options to inherit a standard pass's
222   // user interface. For example, a target may disable a standard pass by
223   // default by substituting a pass ID of zero, and the user may still enable
224   // that standard pass with an explicit command line option.
225   DenseMap<AnalysisID,IdentifyingPassPtr> TargetPasses;
226 
227   /// Store the pairs of <AnalysisID, AnalysisID> of which the second pass
228   /// is inserted after each instance of the first one.
229   SmallVector<InsertedPass, 4> InsertedPasses;
230 };
231 } // namespace llvm
232 
233 // Out of line virtual method.
~TargetPassConfig()234 TargetPassConfig::~TargetPassConfig() {
235   delete Impl;
236 }
237 
238 // Out of line constructor provides default values for pass options and
239 // registers all common codegen passes.
TargetPassConfig(TargetMachine * tm,PassManagerBase & pm)240 TargetPassConfig::TargetPassConfig(TargetMachine *tm, PassManagerBase &pm)
241     : ImmutablePass(ID), PM(&pm), StartBefore(nullptr), StartAfter(nullptr),
242       StopAfter(nullptr), Started(true), Stopped(false),
243       AddingMachinePasses(false), TM(tm), Impl(nullptr), Initialized(false),
244       DisableVerify(false), EnableTailMerge(true) {
245 
246   Impl = new PassConfigImpl();
247 
248   // Register all target independent codegen passes to activate their PassIDs,
249   // including this pass itself.
250   initializeCodeGen(*PassRegistry::getPassRegistry());
251 
252   // Also register alias analysis passes required by codegen passes.
253   initializeBasicAAWrapperPassPass(*PassRegistry::getPassRegistry());
254   initializeAAResultsWrapperPassPass(*PassRegistry::getPassRegistry());
255 
256   // Substitute Pseudo Pass IDs for real ones.
257   substitutePass(&EarlyTailDuplicateID, &TailDuplicateID);
258   substitutePass(&PostRAMachineLICMID, &MachineLICMID);
259 }
260 
261 /// Insert InsertedPassID pass after TargetPassID.
insertPass(AnalysisID TargetPassID,IdentifyingPassPtr InsertedPassID,bool VerifyAfter,bool PrintAfter)262 void TargetPassConfig::insertPass(AnalysisID TargetPassID,
263                                   IdentifyingPassPtr InsertedPassID,
264                                   bool VerifyAfter, bool PrintAfter) {
265   assert(((!InsertedPassID.isInstance() &&
266            TargetPassID != InsertedPassID.getID()) ||
267           (InsertedPassID.isInstance() &&
268            TargetPassID != InsertedPassID.getInstance()->getPassID())) &&
269          "Insert a pass after itself!");
270   Impl->InsertedPasses.emplace_back(TargetPassID, InsertedPassID, VerifyAfter,
271                                     PrintAfter);
272 }
273 
274 /// createPassConfig - Create a pass configuration object to be used by
275 /// addPassToEmitX methods for generating a pipeline of CodeGen passes.
276 ///
277 /// Targets may override this to extend TargetPassConfig.
createPassConfig(PassManagerBase & PM)278 TargetPassConfig *LLVMTargetMachine::createPassConfig(PassManagerBase &PM) {
279   return new TargetPassConfig(this, PM);
280 }
281 
TargetPassConfig()282 TargetPassConfig::TargetPassConfig()
283   : ImmutablePass(ID), PM(nullptr) {
284   llvm_unreachable("TargetPassConfig should not be constructed on-the-fly");
285 }
286 
287 // Helper to verify the analysis is really immutable.
setOpt(bool & Opt,bool Val)288 void TargetPassConfig::setOpt(bool &Opt, bool Val) {
289   assert(!Initialized && "PassConfig is immutable");
290   Opt = Val;
291 }
292 
substitutePass(AnalysisID StandardID,IdentifyingPassPtr TargetID)293 void TargetPassConfig::substitutePass(AnalysisID StandardID,
294                                       IdentifyingPassPtr TargetID) {
295   Impl->TargetPasses[StandardID] = TargetID;
296 }
297 
getPassSubstitution(AnalysisID ID) const298 IdentifyingPassPtr TargetPassConfig::getPassSubstitution(AnalysisID ID) const {
299   DenseMap<AnalysisID, IdentifyingPassPtr>::const_iterator
300     I = Impl->TargetPasses.find(ID);
301   if (I == Impl->TargetPasses.end())
302     return ID;
303   return I->second;
304 }
305 
306 /// Add a pass to the PassManager if that pass is supposed to be run.  If the
307 /// Started/Stopped flags indicate either that the compilation should start at
308 /// a later pass or that it should stop after an earlier pass, then do not add
309 /// the pass.  Finally, compare the current pass against the StartAfter
310 /// and StopAfter options and change the Started/Stopped flags accordingly.
addPass(Pass * P,bool verifyAfter,bool printAfter)311 void TargetPassConfig::addPass(Pass *P, bool verifyAfter, bool printAfter) {
312   assert(!Initialized && "PassConfig is immutable");
313 
314   // Cache the Pass ID here in case the pass manager finds this pass is
315   // redundant with ones already scheduled / available, and deletes it.
316   // Fundamentally, once we add the pass to the manager, we no longer own it
317   // and shouldn't reference it.
318   AnalysisID PassID = P->getPassID();
319 
320   if (StartBefore == PassID)
321     Started = true;
322   if (Started && !Stopped) {
323     std::string Banner;
324     // Construct banner message before PM->add() as that may delete the pass.
325     if (AddingMachinePasses && (printAfter || verifyAfter))
326       Banner = std::string("After ") + std::string(P->getPassName());
327     PM->add(P);
328     if (AddingMachinePasses) {
329       if (printAfter)
330         addPrintPass(Banner);
331       if (verifyAfter)
332         addVerifyPass(Banner);
333     }
334 
335     // Add the passes after the pass P if there is any.
336     for (auto IP : Impl->InsertedPasses) {
337       if (IP.TargetPassID == PassID)
338         addPass(IP.getInsertedPass(), IP.VerifyAfter, IP.PrintAfter);
339     }
340   } else {
341     delete P;
342   }
343   if (StopAfter == PassID)
344     Stopped = true;
345   if (StartAfter == PassID)
346     Started = true;
347   if (Stopped && !Started)
348     report_fatal_error("Cannot stop compilation after pass that is not run");
349 }
350 
351 /// Add a CodeGen pass at this point in the pipeline after checking for target
352 /// and command line overrides.
353 ///
354 /// addPass cannot return a pointer to the pass instance because is internal the
355 /// PassManager and the instance we create here may already be freed.
addPass(AnalysisID PassID,bool verifyAfter,bool printAfter)356 AnalysisID TargetPassConfig::addPass(AnalysisID PassID, bool verifyAfter,
357                                      bool printAfter) {
358   IdentifyingPassPtr TargetID = getPassSubstitution(PassID);
359   IdentifyingPassPtr FinalPtr = overridePass(PassID, TargetID);
360   if (!FinalPtr.isValid())
361     return nullptr;
362 
363   Pass *P;
364   if (FinalPtr.isInstance())
365     P = FinalPtr.getInstance();
366   else {
367     P = Pass::createPass(FinalPtr.getID());
368     if (!P)
369       llvm_unreachable("Pass ID not registered");
370   }
371   AnalysisID FinalID = P->getPassID();
372   addPass(P, verifyAfter, printAfter); // Ends the lifetime of P.
373 
374   return FinalID;
375 }
376 
printAndVerify(const std::string & Banner)377 void TargetPassConfig::printAndVerify(const std::string &Banner) {
378   addPrintPass(Banner);
379   addVerifyPass(Banner);
380 }
381 
addPrintPass(const std::string & Banner)382 void TargetPassConfig::addPrintPass(const std::string &Banner) {
383   if (TM->shouldPrintMachineCode())
384     PM->add(createMachineFunctionPrinterPass(dbgs(), Banner));
385 }
386 
addVerifyPass(const std::string & Banner)387 void TargetPassConfig::addVerifyPass(const std::string &Banner) {
388   if (VerifyMachineCode)
389     PM->add(createMachineVerifierPass(Banner));
390 }
391 
392 /// Add common target configurable passes that perform LLVM IR to IR transforms
393 /// following machine independent optimization.
addIRPasses()394 void TargetPassConfig::addIRPasses() {
395   // Basic AliasAnalysis support.
396   // Add TypeBasedAliasAnalysis before BasicAliasAnalysis so that
397   // BasicAliasAnalysis wins if they disagree. This is intended to help
398   // support "obvious" type-punning idioms.
399   if (UseCFLAA)
400     addPass(createCFLAAWrapperPass());
401   addPass(createTypeBasedAAWrapperPass());
402   addPass(createScopedNoAliasAAWrapperPass());
403   addPass(createBasicAAWrapperPass());
404 
405   // Before running any passes, run the verifier to determine if the input
406   // coming from the front-end and/or optimizer is valid.
407   if (!DisableVerify)
408     addPass(createVerifierPass());
409 
410   // Run loop strength reduction before anything else.
411   if (getOptLevel() != CodeGenOpt::None && !DisableLSR) {
412     addPass(createLoopStrengthReducePass());
413     if (PrintLSR)
414       addPass(createPrintFunctionPass(dbgs(), "\n\n*** Code after LSR ***\n"));
415   }
416 
417   // Run GC lowering passes for builtin collectors
418   // TODO: add a pass insertion point here
419   addPass(createGCLoweringPass());
420   addPass(createShadowStackGCLoweringPass());
421 
422   // Make sure that no unreachable blocks are instruction selected.
423   addPass(createUnreachableBlockEliminationPass());
424 
425   // Prepare expensive constants for SelectionDAG.
426   if (getOptLevel() != CodeGenOpt::None && !DisableConstantHoisting)
427     addPass(createConstantHoistingPass());
428 
429   if (getOptLevel() != CodeGenOpt::None && !DisablePartialLibcallInlining)
430     addPass(createPartiallyInlineLibCallsPass());
431 }
432 
433 /// Turn exception handling constructs into something the code generators can
434 /// handle.
addPassesToHandleExceptions()435 void TargetPassConfig::addPassesToHandleExceptions() {
436   switch (TM->getMCAsmInfo()->getExceptionHandlingType()) {
437   case ExceptionHandling::SjLj:
438     // SjLj piggy-backs on dwarf for this bit. The cleanups done apply to both
439     // Dwarf EH prepare needs to be run after SjLj prepare. Otherwise,
440     // catch info can get misplaced when a selector ends up more than one block
441     // removed from the parent invoke(s). This could happen when a landing
442     // pad is shared by multiple invokes and is also a target of a normal
443     // edge from elsewhere.
444     addPass(createSjLjEHPreparePass());
445     // FALLTHROUGH
446   case ExceptionHandling::DwarfCFI:
447   case ExceptionHandling::ARM:
448     addPass(createDwarfEHPass(TM));
449     break;
450   case ExceptionHandling::WinEH:
451     // We support using both GCC-style and MSVC-style exceptions on Windows, so
452     // add both preparation passes. Each pass will only actually run if it
453     // recognizes the personality function.
454     addPass(createWinEHPass(TM));
455     addPass(createDwarfEHPass(TM));
456     break;
457   case ExceptionHandling::None:
458     addPass(createLowerInvokePass());
459 
460     // The lower invoke pass may create unreachable code. Remove it.
461     addPass(createUnreachableBlockEliminationPass());
462     break;
463   }
464 }
465 
466 /// Add pass to prepare the LLVM IR for code generation. This should be done
467 /// before exception handling preparation passes.
addCodeGenPrepare()468 void TargetPassConfig::addCodeGenPrepare() {
469   if (getOptLevel() != CodeGenOpt::None && !DisableCGP)
470     addPass(createCodeGenPreparePass(TM));
471   addPass(createRewriteSymbolsPass());
472 }
473 
474 /// Add common passes that perform LLVM IR to IR transforms in preparation for
475 /// instruction selection.
addISelPrepare()476 void TargetPassConfig::addISelPrepare() {
477   addPreISel();
478 
479   // Add both the safe stack and the stack protection passes: each of them will
480   // only protect functions that have corresponding attributes.
481   addPass(createSafeStackPass(TM));
482   addPass(createStackProtectorPass(TM));
483 
484   if (PrintISelInput)
485     addPass(createPrintFunctionPass(
486         dbgs(), "\n\n*** Final LLVM Code input to ISel ***\n"));
487 
488   // All passes which modify the LLVM IR are now complete; run the verifier
489   // to ensure that the IR is valid.
490   if (!DisableVerify)
491     addPass(createVerifierPass());
492 }
493 
494 /// Add the complete set of target-independent postISel code generator passes.
495 ///
496 /// This can be read as the standard order of major LLVM CodeGen stages. Stages
497 /// with nontrivial configuration or multiple passes are broken out below in
498 /// add%Stage routines.
499 ///
500 /// Any TargetPassConfig::addXX routine may be overriden by the Target. The
501 /// addPre/Post methods with empty header implementations allow injecting
502 /// target-specific fixups just before or after major stages. Additionally,
503 /// targets have the flexibility to change pass order within a stage by
504 /// overriding default implementation of add%Stage routines below. Each
505 /// technique has maintainability tradeoffs because alternate pass orders are
506 /// not well supported. addPre/Post works better if the target pass is easily
507 /// tied to a common pass. But if it has subtle dependencies on multiple passes,
508 /// the target should override the stage instead.
509 ///
510 /// TODO: We could use a single addPre/Post(ID) hook to allow pass injection
511 /// before/after any target-independent pass. But it's currently overkill.
addMachinePasses()512 void TargetPassConfig::addMachinePasses() {
513   AddingMachinePasses = true;
514 
515   // Insert a machine instr printer pass after the specified pass.
516   // If -print-machineinstrs specified, print machineinstrs after all passes.
517   if (StringRef(PrintMachineInstrs.getValue()).equals(""))
518     TM->Options.PrintMachineCode = true;
519   else if (!StringRef(PrintMachineInstrs.getValue())
520            .equals("option-unspecified")) {
521     const PassRegistry *PR = PassRegistry::getPassRegistry();
522     const PassInfo *TPI = PR->getPassInfo(PrintMachineInstrs.getValue());
523     const PassInfo *IPI = PR->getPassInfo(StringRef("machineinstr-printer"));
524     assert (TPI && IPI && "Pass ID not registered!");
525     const char *TID = (const char *)(TPI->getTypeInfo());
526     const char *IID = (const char *)(IPI->getTypeInfo());
527     insertPass(TID, IID);
528   }
529 
530   // Print the instruction selected machine code...
531   printAndVerify("After Instruction Selection");
532 
533   // Expand pseudo-instructions emitted by ISel.
534   addPass(&ExpandISelPseudosID);
535 
536   // Add passes that optimize machine instructions in SSA form.
537   if (getOptLevel() != CodeGenOpt::None) {
538     addMachineSSAOptimization();
539   } else {
540     // If the target requests it, assign local variables to stack slots relative
541     // to one another and simplify frame index references where possible.
542     addPass(&LocalStackSlotAllocationID, false);
543   }
544 
545   // Run pre-ra passes.
546   addPreRegAlloc();
547 
548   // Run register allocation and passes that are tightly coupled with it,
549   // including phi elimination and scheduling.
550   if (getOptimizeRegAlloc())
551     addOptimizedRegAlloc(createRegAllocPass(true));
552   else
553     addFastRegAlloc(createRegAllocPass(false));
554 
555   // Run post-ra passes.
556   addPostRegAlloc();
557 
558   // Insert prolog/epilog code.  Eliminate abstract frame index references...
559   if (getOptLevel() != CodeGenOpt::None)
560     addPass(&ShrinkWrapID);
561 
562   addPass(&PrologEpilogCodeInserterID);
563 
564   /// Add passes that optimize machine instructions after register allocation.
565   if (getOptLevel() != CodeGenOpt::None)
566     addMachineLateOptimization();
567 
568   // Expand pseudo instructions before second scheduling pass.
569   addPass(&ExpandPostRAPseudosID);
570 
571   // Run pre-sched2 passes.
572   addPreSched2();
573 
574   if (EnableImplicitNullChecks)
575     addPass(&ImplicitNullChecksID);
576 
577   // Second pass scheduler.
578   // Let Target optionally insert this pass by itself at some other
579   // point.
580   if (getOptLevel() != CodeGenOpt::None &&
581       !TM->targetSchedulesPostRAScheduling()) {
582     if (MISchedPostRA)
583       addPass(&PostMachineSchedulerID);
584     else
585       addPass(&PostRASchedulerID);
586   }
587 
588   // GC
589   if (addGCPasses()) {
590     if (PrintGCInfo)
591       addPass(createGCInfoPrinter(dbgs()), false, false);
592   }
593 
594   // Basic block placement.
595   if (getOptLevel() != CodeGenOpt::None)
596     addBlockPlacement();
597 
598   addPreEmitPass();
599 
600   addPass(&FuncletLayoutID, false);
601 
602   addPass(&StackMapLivenessID, false);
603   addPass(&LiveDebugValuesID, false);
604 
605   AddingMachinePasses = false;
606 }
607 
608 /// Add passes that optimize machine instructions in SSA form.
addMachineSSAOptimization()609 void TargetPassConfig::addMachineSSAOptimization() {
610   // Pre-ra tail duplication.
611   addPass(&EarlyTailDuplicateID);
612 
613   // Optimize PHIs before DCE: removing dead PHI cycles may make more
614   // instructions dead.
615   addPass(&OptimizePHIsID, false);
616 
617   // This pass merges large allocas. StackSlotColoring is a different pass
618   // which merges spill slots.
619   addPass(&StackColoringID, false);
620 
621   // If the target requests it, assign local variables to stack slots relative
622   // to one another and simplify frame index references where possible.
623   addPass(&LocalStackSlotAllocationID, false);
624 
625   // With optimization, dead code should already be eliminated. However
626   // there is one known exception: lowered code for arguments that are only
627   // used by tail calls, where the tail calls reuse the incoming stack
628   // arguments directly (see t11 in test/CodeGen/X86/sibcall.ll).
629   addPass(&DeadMachineInstructionElimID);
630 
631   // Allow targets to insert passes that improve instruction level parallelism,
632   // like if-conversion. Such passes will typically need dominator trees and
633   // loop info, just like LICM and CSE below.
634   addILPOpts();
635 
636   addPass(&MachineLICMID, false);
637   addPass(&MachineCSEID, false);
638   addPass(&MachineSinkingID);
639 
640   addPass(&PeepholeOptimizerID);
641   // Clean-up the dead code that may have been generated by peephole
642   // rewriting.
643   addPass(&DeadMachineInstructionElimID);
644 }
645 
646 //===---------------------------------------------------------------------===//
647 /// Register Allocation Pass Configuration
648 //===---------------------------------------------------------------------===//
649 
getOptimizeRegAlloc() const650 bool TargetPassConfig::getOptimizeRegAlloc() const {
651   switch (OptimizeRegAlloc) {
652   case cl::BOU_UNSET: return getOptLevel() != CodeGenOpt::None;
653   case cl::BOU_TRUE:  return true;
654   case cl::BOU_FALSE: return false;
655   }
656   llvm_unreachable("Invalid optimize-regalloc state");
657 }
658 
659 /// RegisterRegAlloc's global Registry tracks allocator registration.
660 MachinePassRegistry RegisterRegAlloc::Registry;
661 
662 /// A dummy default pass factory indicates whether the register allocator is
663 /// overridden on the command line.
useDefaultRegisterAllocator()664 static FunctionPass *useDefaultRegisterAllocator() { return nullptr; }
665 static RegisterRegAlloc
666 defaultRegAlloc("default",
667                 "pick register allocator based on -O option",
668                 useDefaultRegisterAllocator);
669 
670 /// -regalloc=... command line option.
671 static cl::opt<RegisterRegAlloc::FunctionPassCtor, false,
672                RegisterPassParser<RegisterRegAlloc> >
673 RegAlloc("regalloc",
674          cl::init(&useDefaultRegisterAllocator),
675          cl::desc("Register allocator to use"));
676 
677 
678 /// Instantiate the default register allocator pass for this target for either
679 /// the optimized or unoptimized allocation path. This will be added to the pass
680 /// manager by addFastRegAlloc in the unoptimized case or addOptimizedRegAlloc
681 /// in the optimized case.
682 ///
683 /// A target that uses the standard regalloc pass order for fast or optimized
684 /// allocation may still override this for per-target regalloc
685 /// selection. But -regalloc=... always takes precedence.
createTargetRegisterAllocator(bool Optimized)686 FunctionPass *TargetPassConfig::createTargetRegisterAllocator(bool Optimized) {
687   if (Optimized)
688     return createGreedyRegisterAllocator();
689   else
690     return createFastRegisterAllocator();
691 }
692 
693 /// Find and instantiate the register allocation pass requested by this target
694 /// at the current optimization level.  Different register allocators are
695 /// defined as separate passes because they may require different analysis.
696 ///
697 /// This helper ensures that the regalloc= option is always available,
698 /// even for targets that override the default allocator.
699 ///
700 /// FIXME: When MachinePassRegistry register pass IDs instead of function ptrs,
701 /// this can be folded into addPass.
createRegAllocPass(bool Optimized)702 FunctionPass *TargetPassConfig::createRegAllocPass(bool Optimized) {
703   RegisterRegAlloc::FunctionPassCtor Ctor = RegisterRegAlloc::getDefault();
704 
705   // Initialize the global default.
706   if (!Ctor) {
707     Ctor = RegAlloc;
708     RegisterRegAlloc::setDefault(RegAlloc);
709   }
710   if (Ctor != useDefaultRegisterAllocator)
711     return Ctor();
712 
713   // With no -regalloc= override, ask the target for a regalloc pass.
714   return createTargetRegisterAllocator(Optimized);
715 }
716 
717 /// Return true if the default global register allocator is in use and
718 /// has not be overriden on the command line with '-regalloc=...'
usingDefaultRegAlloc() const719 bool TargetPassConfig::usingDefaultRegAlloc() const {
720   return RegAlloc.getNumOccurrences() == 0;
721 }
722 
723 /// Add the minimum set of target-independent passes that are required for
724 /// register allocation. No coalescing or scheduling.
addFastRegAlloc(FunctionPass * RegAllocPass)725 void TargetPassConfig::addFastRegAlloc(FunctionPass *RegAllocPass) {
726   addPass(&PHIEliminationID, false);
727   addPass(&TwoAddressInstructionPassID, false);
728 
729   if (RegAllocPass)
730     addPass(RegAllocPass);
731 }
732 
733 /// Add standard target-independent passes that are tightly coupled with
734 /// optimized register allocation, including coalescing, machine instruction
735 /// scheduling, and register allocation itself.
addOptimizedRegAlloc(FunctionPass * RegAllocPass)736 void TargetPassConfig::addOptimizedRegAlloc(FunctionPass *RegAllocPass) {
737   addPass(&ProcessImplicitDefsID, false);
738 
739   // LiveVariables currently requires pure SSA form.
740   //
741   // FIXME: Once TwoAddressInstruction pass no longer uses kill flags,
742   // LiveVariables can be removed completely, and LiveIntervals can be directly
743   // computed. (We still either need to regenerate kill flags after regalloc, or
744   // preferably fix the scavenger to not depend on them).
745   addPass(&LiveVariablesID, false);
746 
747   // Edge splitting is smarter with machine loop info.
748   addPass(&MachineLoopInfoID, false);
749   addPass(&PHIEliminationID, false);
750 
751   // Eventually, we want to run LiveIntervals before PHI elimination.
752   if (EarlyLiveIntervals)
753     addPass(&LiveIntervalsID, false);
754 
755   addPass(&TwoAddressInstructionPassID, false);
756   addPass(&RegisterCoalescerID);
757 
758   // PreRA instruction scheduling.
759   addPass(&MachineSchedulerID);
760 
761   if (RegAllocPass) {
762     // Add the selected register allocation pass.
763     addPass(RegAllocPass);
764 
765     // Allow targets to change the register assignments before rewriting.
766     addPreRewrite();
767 
768     // Finally rewrite virtual registers.
769     addPass(&VirtRegRewriterID);
770 
771     // Perform stack slot coloring and post-ra machine LICM.
772     //
773     // FIXME: Re-enable coloring with register when it's capable of adding
774     // kill markers.
775     addPass(&StackSlotColoringID);
776 
777     // Run post-ra machine LICM to hoist reloads / remats.
778     //
779     // FIXME: can this move into MachineLateOptimization?
780     addPass(&PostRAMachineLICMID);
781   }
782 }
783 
784 //===---------------------------------------------------------------------===//
785 /// Post RegAlloc Pass Configuration
786 //===---------------------------------------------------------------------===//
787 
788 /// Add passes that optimize machine instructions after register allocation.
addMachineLateOptimization()789 void TargetPassConfig::addMachineLateOptimization() {
790   // Branch folding must be run after regalloc and prolog/epilog insertion.
791   addPass(&BranchFolderPassID);
792 
793   // Tail duplication.
794   // Note that duplicating tail just increases code size and degrades
795   // performance for targets that require Structured Control Flow.
796   // In addition it can also make CFG irreducible. Thus we disable it.
797   if (!TM->requiresStructuredCFG())
798     addPass(&TailDuplicateID);
799 
800   // Copy propagation.
801   addPass(&MachineCopyPropagationID);
802 }
803 
804 /// Add standard GC passes.
addGCPasses()805 bool TargetPassConfig::addGCPasses() {
806   addPass(&GCMachineCodeAnalysisID, false);
807   return true;
808 }
809 
810 /// Add standard basic block placement passes.
addBlockPlacement()811 void TargetPassConfig::addBlockPlacement() {
812   if (addPass(&MachineBlockPlacementID, false)) {
813     // Run a separate pass to collect block placement statistics.
814     if (EnableBlockPlacementStats)
815       addPass(&MachineBlockPlacementStatsID);
816   }
817 }
818