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