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