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