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