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