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