1 //===- TargetPassConfig.cpp - Target independent code generation passes ---===//
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
7 //===----------------------------------------------------------------------===//
9 // This file defines interfaces to access the target independent code
10 // generation passes provided by the LLVM backend.
12 //===---------------------------------------------------------------------===//
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"
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",
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",
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"),
117 static cl::opt<cl::boolOrDefault> DebugifyAndStripAll(
118 "debugify-and-strip-all-safe", cl::Hidden,
120 "Debugify MIR before and Strip debug after "
121 "each pass except those known to be unsafe when debug info is present"),
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"));
140 static cl::opt<cl::boolOrDefault> EnableGlobalISelOption(
141 "global-isel", cl::Hidden,
142 cl::desc("Enable the \"global\" instruction selector"));
144 static cl::opt<std::string> PrintMachineInstrs(
145 "print-machineinstrs", cl::ValueOptional, cl::desc("Print machine instrs"),
146 cl::value_desc("pass-name"), cl::init("option-unspecified"), cl::Hidden);
148 static cl::opt<GlobalISelAbortMode> EnableGlobalISelAbort(
149 "global-isel-abort", cl::Hidden,
150 cl::desc("Enable abort calls when \"global\" instruction selection "
151 "fails to lower/select an instruction"),
153 clEnumValN(GlobalISelAbortMode::Disable, "0", "Disable the abort"),
154 clEnumValN(GlobalISelAbortMode::Enable, "1", "Enable the abort"),
155 clEnumValN(GlobalISelAbortMode::DisableWithDiag, "2",
156 "Disable the abort but emit a diagnostic on failure")));
158 // Temporary option to allow experimenting with MachineScheduler as a post-RA
159 // scheduler. Targets can "properly" enable this with
160 // substitutePass(&PostRASchedulerID, &PostMachineSchedulerID).
161 // Targets can return true in targetSchedulesPostRAScheduling() and
162 // insert a PostRA scheduling pass wherever it wants.
163 static cl::opt<bool> MISchedPostRA(
164 "misched-postra", cl::Hidden,
166 "Run MachineScheduler post regalloc (independent of preRA sched)"));
168 // Experimental option to run live interval analysis early.
169 static cl::opt<bool> EarlyLiveIntervals("early-live-intervals", cl::Hidden,
170 cl::desc("Run live interval analysis earlier in the pipeline"));
172 // Experimental option to use CFL-AA in codegen
173 enum class CFLAAType { None, Steensgaard, Andersen, Both };
174 static cl::opt<CFLAAType> UseCFLAA(
175 "use-cfl-aa-in-codegen", cl::init(CFLAAType::None), cl::Hidden,
176 cl::desc("Enable the new, experimental CFL alias analysis in CodeGen"),
177 cl::values(clEnumValN(CFLAAType::None, "none", "Disable CFL-AA"),
178 clEnumValN(CFLAAType::Steensgaard, "steens",
179 "Enable unification-based CFL-AA"),
180 clEnumValN(CFLAAType::Andersen, "anders",
181 "Enable inclusion-based CFL-AA"),
182 clEnumValN(CFLAAType::Both, "both",
183 "Enable both variants of CFL-AA")));
185 /// Option names for limiting the codegen pipeline.
186 /// Those are used in error reporting and we didn't want
187 /// to duplicate their names all over the place.
188 static const char StartAfterOptName[] = "start-after";
189 static const char StartBeforeOptName[] = "start-before";
190 static const char StopAfterOptName[] = "stop-after";
191 static const char StopBeforeOptName[] = "stop-before";
193 static cl::opt<std::string>
194 StartAfterOpt(StringRef(StartAfterOptName),
195 cl::desc("Resume compilation after a specific pass"),
196 cl::value_desc("pass-name"), cl::init(""), cl::Hidden);
198 static cl::opt<std::string>
199 StartBeforeOpt(StringRef(StartBeforeOptName),
200 cl::desc("Resume compilation before a specific pass"),
201 cl::value_desc("pass-name"), cl::init(""), cl::Hidden);
203 static cl::opt<std::string>
204 StopAfterOpt(StringRef(StopAfterOptName),
205 cl::desc("Stop compilation after a specific pass"),
206 cl::value_desc("pass-name"), cl::init(""), cl::Hidden);
208 static cl::opt<std::string>
209 StopBeforeOpt(StringRef(StopBeforeOptName),
210 cl::desc("Stop compilation before a specific pass"),
211 cl::value_desc("pass-name"), cl::init(""), cl::Hidden);
213 /// Allow standard passes to be disabled by command line options. This supports
214 /// simple binary flags that either suppress the pass or do nothing.
215 /// i.e. -disable-mypass=false has no effect.
216 /// These should be converted to boolOrDefault in order to use applyOverride.
217 static IdentifyingPassPtr applyDisable(IdentifyingPassPtr PassID,
220 return IdentifyingPassPtr();
224 /// Allow standard passes to be disabled by the command line, regardless of who
225 /// is adding the pass.
227 /// StandardID is the pass identified in the standard pass pipeline and provided
228 /// to addPass(). It may be a target-specific ID in the case that the target
229 /// directly adds its own pass, but in that case we harmlessly fall through.
231 /// TargetID is the pass that the target has configured to override StandardID.
233 /// StandardID may be a pseudo ID. In that case TargetID is the name of the real
234 /// pass to run. This allows multiple options to control a single pass depending
235 /// on where in the pipeline that pass is added.
236 static IdentifyingPassPtr overridePass(AnalysisID StandardID,
237 IdentifyingPassPtr TargetID) {
238 if (StandardID == &PostRASchedulerID)
239 return applyDisable(TargetID, DisablePostRASched);
241 if (StandardID == &BranchFolderPassID)
242 return applyDisable(TargetID, DisableBranchFold);
244 if (StandardID == &TailDuplicateID)
245 return applyDisable(TargetID, DisableTailDuplicate);
247 if (StandardID == &EarlyTailDuplicateID)
248 return applyDisable(TargetID, DisableEarlyTailDup);
250 if (StandardID == &MachineBlockPlacementID)
251 return applyDisable(TargetID, DisableBlockPlacement);
253 if (StandardID == &StackSlotColoringID)
254 return applyDisable(TargetID, DisableSSC);
256 if (StandardID == &DeadMachineInstructionElimID)
257 return applyDisable(TargetID, DisableMachineDCE);
259 if (StandardID == &EarlyIfConverterID)
260 return applyDisable(TargetID, DisableEarlyIfConversion);
262 if (StandardID == &EarlyMachineLICMID)
263 return applyDisable(TargetID, DisableMachineLICM);
265 if (StandardID == &MachineCSEID)
266 return applyDisable(TargetID, DisableMachineCSE);
268 if (StandardID == &MachineLICMID)
269 return applyDisable(TargetID, DisablePostRAMachineLICM);
271 if (StandardID == &MachineSinkingID)
272 return applyDisable(TargetID, DisableMachineSink);
274 if (StandardID == &PostRAMachineSinkingID)
275 return applyDisable(TargetID, DisablePostRAMachineSink);
277 if (StandardID == &MachineCopyPropagationID)
278 return applyDisable(TargetID, DisableCopyProp);
283 //===---------------------------------------------------------------------===//
285 //===---------------------------------------------------------------------===//
287 INITIALIZE_PASS(TargetPassConfig, "targetpassconfig",
288 "Target Pass Configuration", false, false)
289 char TargetPassConfig::ID = 0;
293 struct InsertedPass {
294 AnalysisID TargetPassID;
295 IdentifyingPassPtr InsertedPassID;
299 InsertedPass(AnalysisID TargetPassID, IdentifyingPassPtr InsertedPassID,
300 bool VerifyAfter, bool PrintAfter)
301 : TargetPassID(TargetPassID), InsertedPassID(InsertedPassID),
302 VerifyAfter(VerifyAfter), PrintAfter(PrintAfter) {}
304 Pass *getInsertedPass() const {
305 assert(InsertedPassID.isValid() && "Illegal Pass ID!");
306 if (InsertedPassID.isInstance())
307 return InsertedPassID.getInstance();
308 Pass *NP = Pass::createPass(InsertedPassID.getID());
309 assert(NP && "Pass ID not registered");
314 } // end anonymous namespace
318 class PassConfigImpl {
320 // List of passes explicitly substituted by this target. Normally this is
321 // empty, but it is a convenient way to suppress or replace specific passes
322 // that are part of a standard pass pipeline without overridding the entire
323 // pipeline. This mechanism allows target options to inherit a standard pass's
324 // user interface. For example, a target may disable a standard pass by
325 // default by substituting a pass ID of zero, and the user may still enable
326 // that standard pass with an explicit command line option.
327 DenseMap<AnalysisID,IdentifyingPassPtr> TargetPasses;
329 /// Store the pairs of <AnalysisID, AnalysisID> of which the second pass
330 /// is inserted after each instance of the first one.
331 SmallVector<InsertedPass, 4> InsertedPasses;
334 } // end namespace llvm
336 // Out of line virtual method.
337 TargetPassConfig::~TargetPassConfig() {
341 static const PassInfo *getPassInfo(StringRef PassName) {
342 if (PassName.empty())
345 const PassRegistry &PR = *PassRegistry::getPassRegistry();
346 const PassInfo *PI = PR.getPassInfo(PassName);
348 report_fatal_error(Twine('\"') + Twine(PassName) +
349 Twine("\" pass is not registered."));
353 static AnalysisID getPassIDFromName(StringRef PassName) {
354 const PassInfo *PI = getPassInfo(PassName);
355 return PI ? PI->getTypeInfo() : nullptr;
358 static std::pair<StringRef, unsigned>
359 getPassNameAndInstanceNum(StringRef PassName) {
360 StringRef Name, InstanceNumStr;
361 std::tie(Name, InstanceNumStr) = PassName.split(',');
363 unsigned InstanceNum = 0;
364 if (!InstanceNumStr.empty() && InstanceNumStr.getAsInteger(10, InstanceNum))
365 report_fatal_error("invalid pass instance specifier " + PassName);
367 return std::make_pair(Name, InstanceNum);
370 void TargetPassConfig::setStartStopPasses() {
371 StringRef StartBeforeName;
372 std::tie(StartBeforeName, StartBeforeInstanceNum) =
373 getPassNameAndInstanceNum(StartBeforeOpt);
375 StringRef StartAfterName;
376 std::tie(StartAfterName, StartAfterInstanceNum) =
377 getPassNameAndInstanceNum(StartAfterOpt);
379 StringRef StopBeforeName;
380 std::tie(StopBeforeName, StopBeforeInstanceNum)
381 = getPassNameAndInstanceNum(StopBeforeOpt);
383 StringRef StopAfterName;
384 std::tie(StopAfterName, StopAfterInstanceNum)
385 = getPassNameAndInstanceNum(StopAfterOpt);
387 StartBefore = getPassIDFromName(StartBeforeName);
388 StartAfter = getPassIDFromName(StartAfterName);
389 StopBefore = getPassIDFromName(StopBeforeName);
390 StopAfter = getPassIDFromName(StopAfterName);
391 if (StartBefore && StartAfter)
392 report_fatal_error(Twine(StartBeforeOptName) + Twine(" and ") +
393 Twine(StartAfterOptName) + Twine(" specified!"));
394 if (StopBefore && StopAfter)
395 report_fatal_error(Twine(StopBeforeOptName) + Twine(" and ") +
396 Twine(StopAfterOptName) + Twine(" specified!"));
397 Started = (StartAfter == nullptr) && (StartBefore == nullptr);
400 // Out of line constructor provides default values for pass options and
401 // registers all common codegen passes.
402 TargetPassConfig::TargetPassConfig(LLVMTargetMachine &TM, PassManagerBase &pm)
403 : ImmutablePass(ID), PM(&pm), TM(&TM) {
404 Impl = new PassConfigImpl();
406 // Register all target independent codegen passes to activate their PassIDs,
407 // including this pass itself.
408 initializeCodeGen(*PassRegistry::getPassRegistry());
410 // Also register alias analysis passes required by codegen passes.
411 initializeBasicAAWrapperPassPass(*PassRegistry::getPassRegistry());
412 initializeAAResultsWrapperPassPass(*PassRegistry::getPassRegistry());
414 if (StringRef(PrintMachineInstrs.getValue()).equals(""))
415 TM.Options.PrintMachineCode = true;
417 if (EnableIPRA.getNumOccurrences())
418 TM.Options.EnableIPRA = EnableIPRA;
420 // If not explicitly specified, use target default.
421 TM.Options.EnableIPRA |= TM.useIPRA();
424 if (TM.Options.EnableIPRA)
425 setRequiresCodeGenSCCOrder();
427 if (EnableGlobalISelAbort.getNumOccurrences())
428 TM.Options.GlobalISelAbort = EnableGlobalISelAbort;
430 setStartStopPasses();
433 CodeGenOpt::Level TargetPassConfig::getOptLevel() const {
434 return TM->getOptLevel();
437 /// Insert InsertedPassID pass after TargetPassID.
438 void TargetPassConfig::insertPass(AnalysisID TargetPassID,
439 IdentifyingPassPtr InsertedPassID,
440 bool VerifyAfter, bool PrintAfter) {
441 assert(((!InsertedPassID.isInstance() &&
442 TargetPassID != InsertedPassID.getID()) ||
443 (InsertedPassID.isInstance() &&
444 TargetPassID != InsertedPassID.getInstance()->getPassID())) &&
445 "Insert a pass after itself!");
446 Impl->InsertedPasses.emplace_back(TargetPassID, InsertedPassID, VerifyAfter,
450 /// createPassConfig - Create a pass configuration object to be used by
451 /// addPassToEmitX methods for generating a pipeline of CodeGen passes.
453 /// Targets may override this to extend TargetPassConfig.
454 TargetPassConfig *LLVMTargetMachine::createPassConfig(PassManagerBase &PM) {
455 return new TargetPassConfig(*this, PM);
458 TargetPassConfig::TargetPassConfig()
459 : ImmutablePass(ID) {
460 report_fatal_error("Trying to construct TargetPassConfig without a target "
461 "machine. Scheduling a CodeGen pass without a target "
465 bool TargetPassConfig::willCompleteCodeGenPipeline() {
466 return StopBeforeOpt.empty() && StopAfterOpt.empty();
469 bool TargetPassConfig::hasLimitedCodeGenPipeline() {
470 return !StartBeforeOpt.empty() || !StartAfterOpt.empty() ||
471 !willCompleteCodeGenPipeline();
475 TargetPassConfig::getLimitedCodeGenPipelineReason(const char *Separator) {
476 if (!hasLimitedCodeGenPipeline())
477 return std::string();
479 static cl::opt<std::string> *PassNames[] = {&StartAfterOpt, &StartBeforeOpt,
480 &StopAfterOpt, &StopBeforeOpt};
481 static const char *OptNames[] = {StartAfterOptName, StartBeforeOptName,
482 StopAfterOptName, StopBeforeOptName};
484 for (int Idx = 0; Idx < 4; ++Idx)
485 if (!PassNames[Idx]->empty()) {
489 Res += OptNames[Idx];
494 // Helper to verify the analysis is really immutable.
495 void TargetPassConfig::setOpt(bool &Opt, bool Val) {
496 assert(!Initialized && "PassConfig is immutable");
500 void TargetPassConfig::substitutePass(AnalysisID StandardID,
501 IdentifyingPassPtr TargetID) {
502 Impl->TargetPasses[StandardID] = TargetID;
505 IdentifyingPassPtr TargetPassConfig::getPassSubstitution(AnalysisID ID) const {
506 DenseMap<AnalysisID, IdentifyingPassPtr>::const_iterator
507 I = Impl->TargetPasses.find(ID);
508 if (I == Impl->TargetPasses.end())
513 bool TargetPassConfig::isPassSubstitutedOrOverridden(AnalysisID ID) const {
514 IdentifyingPassPtr TargetID = getPassSubstitution(ID);
515 IdentifyingPassPtr FinalPtr = overridePass(ID, TargetID);
516 return !FinalPtr.isValid() || FinalPtr.isInstance() ||
517 FinalPtr.getID() != ID;
520 /// Add a pass to the PassManager if that pass is supposed to be run. If the
521 /// Started/Stopped flags indicate either that the compilation should start at
522 /// a later pass or that it should stop after an earlier pass, then do not add
523 /// the pass. Finally, compare the current pass against the StartAfter
524 /// and StopAfter options and change the Started/Stopped flags accordingly.
525 void TargetPassConfig::addPass(Pass *P, bool verifyAfter, bool printAfter) {
526 assert(!Initialized && "PassConfig is immutable");
528 // Cache the Pass ID here in case the pass manager finds this pass is
529 // redundant with ones already scheduled / available, and deletes it.
530 // Fundamentally, once we add the pass to the manager, we no longer own it
531 // and shouldn't reference it.
532 AnalysisID PassID = P->getPassID();
534 if (StartBefore == PassID && StartBeforeCount++ == StartBeforeInstanceNum)
536 if (StopBefore == PassID && StopBeforeCount++ == StopBeforeInstanceNum)
538 if (Started && !Stopped) {
539 if (AddingMachinePasses)
540 addMachinePrePasses();
542 // Construct banner message before PM->add() as that may delete the pass.
543 if (AddingMachinePasses && (printAfter || verifyAfter))
544 Banner = std::string("After ") + std::string(P->getPassName());
546 if (AddingMachinePasses)
547 addMachinePostPasses(Banner, /*AllowPrint*/ printAfter,
548 /*AllowVerify*/ verifyAfter);
550 // Add the passes after the pass P if there is any.
551 for (auto IP : Impl->InsertedPasses) {
552 if (IP.TargetPassID == PassID)
553 addPass(IP.getInsertedPass(), IP.VerifyAfter, IP.PrintAfter);
559 if (StopAfter == PassID && StopAfterCount++ == StopAfterInstanceNum)
562 if (StartAfter == PassID && StartAfterCount++ == StartAfterInstanceNum)
564 if (Stopped && !Started)
565 report_fatal_error("Cannot stop compilation after pass that is not run");
568 /// Add a CodeGen pass at this point in the pipeline after checking for target
569 /// and command line overrides.
571 /// addPass cannot return a pointer to the pass instance because is internal the
572 /// PassManager and the instance we create here may already be freed.
573 AnalysisID TargetPassConfig::addPass(AnalysisID PassID, bool verifyAfter,
575 IdentifyingPassPtr TargetID = getPassSubstitution(PassID);
576 IdentifyingPassPtr FinalPtr = overridePass(PassID, TargetID);
577 if (!FinalPtr.isValid())
581 if (FinalPtr.isInstance())
582 P = FinalPtr.getInstance();
584 P = Pass::createPass(FinalPtr.getID());
586 llvm_unreachable("Pass ID not registered");
588 AnalysisID FinalID = P->getPassID();
589 addPass(P, verifyAfter, printAfter); // Ends the lifetime of P.
594 void TargetPassConfig::printAndVerify(const std::string &Banner) {
595 addPrintPass(Banner);
596 addVerifyPass(Banner);
599 void TargetPassConfig::addPrintPass(const std::string &Banner) {
600 if (TM->shouldPrintMachineCode())
601 PM->add(createMachineFunctionPrinterPass(dbgs(), Banner));
604 void TargetPassConfig::addVerifyPass(const std::string &Banner) {
605 bool Verify = VerifyMachineCode == cl::BOU_TRUE;
606 #ifdef EXPENSIVE_CHECKS
607 if (VerifyMachineCode == cl::BOU_UNSET)
608 Verify = TM->isMachineVerifierClean();
611 PM->add(createMachineVerifierPass(Banner));
614 void TargetPassConfig::addDebugifyPass() {
615 PM->add(createDebugifyMachineModulePass());
618 void TargetPassConfig::addStripDebugPass() {
619 PM->add(createStripDebugMachineModulePass(/*OnlyDebugified=*/true));
622 void TargetPassConfig::addMachinePrePasses(bool AllowDebugify) {
623 if (AllowDebugify && DebugifyAndStripAll == cl::BOU_TRUE && DebugifyIsSafe)
627 void TargetPassConfig::addMachinePostPasses(const std::string &Banner,
628 bool AllowPrint, bool AllowVerify,
630 if (DebugifyAndStripAll == cl::BOU_TRUE && DebugifyIsSafe)
633 addPrintPass(Banner);
635 addVerifyPass(Banner);
638 /// Add common target configurable passes that perform LLVM IR to IR transforms
639 /// following machine independent optimization.
640 void TargetPassConfig::addIRPasses() {
641 // Before running any passes, run the verifier to determine if the input
642 // coming from the front-end and/or optimizer is valid.
644 addPass(createVerifierPass());
646 if (getOptLevel() != CodeGenOpt::None) {
648 case CFLAAType::Steensgaard:
649 addPass(createCFLSteensAAWrapperPass());
651 case CFLAAType::Andersen:
652 addPass(createCFLAndersAAWrapperPass());
654 case CFLAAType::Both:
655 addPass(createCFLAndersAAWrapperPass());
656 addPass(createCFLSteensAAWrapperPass());
662 // Basic AliasAnalysis support.
663 // Add TypeBasedAliasAnalysis before BasicAliasAnalysis so that
664 // BasicAliasAnalysis wins if they disagree. This is intended to help
665 // support "obvious" type-punning idioms.
666 addPass(createTypeBasedAAWrapperPass());
667 addPass(createScopedNoAliasAAWrapperPass());
668 addPass(createBasicAAWrapperPass());
670 // Run loop strength reduction before anything else.
672 addPass(createCanonicalizeFreezeInLoopsPass());
673 addPass(createLoopStrengthReducePass());
675 addPass(createPrintFunctionPass(dbgs(),
676 "\n\n*** Code after LSR ***\n"));
679 // The MergeICmpsPass tries to create memcmp calls by grouping sequences of
680 // loads and compares. ExpandMemCmpPass then tries to expand those calls
681 // into optimally-sized loads and compares. The transforms are enabled by a
682 // target lowering hook.
683 if (!DisableMergeICmps)
684 addPass(createMergeICmpsLegacyPass());
685 addPass(createExpandMemCmpPass());
688 // Run GC lowering passes for builtin collectors
689 // TODO: add a pass insertion point here
690 addPass(createGCLoweringPass());
691 addPass(createShadowStackGCLoweringPass());
692 addPass(createLowerConstantIntrinsicsPass());
694 // Make sure that no unreachable blocks are instruction selected.
695 addPass(createUnreachableBlockEliminationPass());
697 // Prepare expensive constants for SelectionDAG.
698 if (getOptLevel() != CodeGenOpt::None && !DisableConstantHoisting)
699 addPass(createConstantHoistingPass());
701 if (getOptLevel() != CodeGenOpt::None && !DisablePartialLibcallInlining)
702 addPass(createPartiallyInlineLibCallsPass());
704 // Instrument function entry and exit, e.g. with calls to mcount().
705 addPass(createPostInlineEntryExitInstrumenterPass());
707 // Add scalarization of target's unsupported masked memory intrinsics pass.
708 // the unsupported intrinsic will be replaced with a chain of basic blocks,
709 // that stores/loads element one-by-one if the appropriate mask bit is set.
710 addPass(createScalarizeMaskedMemIntrinPass());
712 // Expand reduction intrinsics into shuffle sequences if the target wants to.
713 addPass(createExpandReductionsPass());
716 /// Turn exception handling constructs into something the code generators can
718 void TargetPassConfig::addPassesToHandleExceptions() {
719 const MCAsmInfo *MCAI = TM->getMCAsmInfo();
720 assert(MCAI && "No MCAsmInfo");
721 switch (MCAI->getExceptionHandlingType()) {
722 case ExceptionHandling::SjLj:
723 // SjLj piggy-backs on dwarf for this bit. The cleanups done apply to both
724 // Dwarf EH prepare needs to be run after SjLj prepare. Otherwise,
725 // catch info can get misplaced when a selector ends up more than one block
726 // removed from the parent invoke(s). This could happen when a landing
727 // pad is shared by multiple invokes and is also a target of a normal
728 // edge from elsewhere.
729 addPass(createSjLjEHPreparePass(TM));
731 case ExceptionHandling::DwarfCFI:
732 case ExceptionHandling::ARM:
733 addPass(createDwarfEHPass(getOptLevel()));
735 case ExceptionHandling::WinEH:
736 // We support using both GCC-style and MSVC-style exceptions on Windows, so
737 // add both preparation passes. Each pass will only actually run if it
738 // recognizes the personality function.
739 addPass(createWinEHPass());
740 addPass(createDwarfEHPass(getOptLevel()));
742 case ExceptionHandling::Wasm:
743 // Wasm EH uses Windows EH instructions, but it does not need to demote PHIs
744 // on catchpads and cleanuppads because it does not outline them into
745 // funclets. Catchswitch blocks are not lowered in SelectionDAG, so we
746 // should remove PHIs there.
747 addPass(createWinEHPass(/*DemoteCatchSwitchPHIOnly=*/false));
748 addPass(createWasmEHPass());
750 case ExceptionHandling::None:
751 addPass(createLowerInvokePass());
753 // The lower invoke pass may create unreachable code. Remove it.
754 addPass(createUnreachableBlockEliminationPass());
759 /// Add pass to prepare the LLVM IR for code generation. This should be done
760 /// before exception handling preparation passes.
761 void TargetPassConfig::addCodeGenPrepare() {
762 if (getOptLevel() != CodeGenOpt::None && !DisableCGP)
763 addPass(createCodeGenPreparePass());
764 addPass(createRewriteSymbolsPass());
767 /// Add common passes that perform LLVM IR to IR transforms in preparation for
768 /// instruction selection.
769 void TargetPassConfig::addISelPrepare() {
772 // Force codegen to run according to the callgraph.
773 if (requiresCodeGenSCCOrder())
774 addPass(new DummyCGSCCPass);
776 // Add both the safe stack and the stack protection passes: each of them will
777 // only protect functions that have corresponding attributes.
778 addPass(createSafeStackPass());
779 addPass(createStackProtectorPass());
782 addPass(createPrintFunctionPass(
783 dbgs(), "\n\n*** Final LLVM Code input to ISel ***\n"));
785 // All passes which modify the LLVM IR are now complete; run the verifier
786 // to ensure that the IR is valid.
788 addPass(createVerifierPass());
791 bool TargetPassConfig::addCoreISelPasses() {
792 // Enable FastISel with -fast-isel, but allow that to be overridden.
793 TM->setO0WantsFastISel(EnableFastISelOption != cl::BOU_FALSE);
795 // Determine an instruction selector.
796 enum class SelectorType { SelectionDAG, FastISel, GlobalISel };
797 SelectorType Selector;
799 if (EnableFastISelOption == cl::BOU_TRUE)
800 Selector = SelectorType::FastISel;
801 else if (EnableGlobalISelOption == cl::BOU_TRUE ||
802 (TM->Options.EnableGlobalISel &&
803 EnableGlobalISelOption != cl::BOU_FALSE))
804 Selector = SelectorType::GlobalISel;
805 else if (TM->getOptLevel() == CodeGenOpt::None && TM->getO0WantsFastISel())
806 Selector = SelectorType::FastISel;
808 Selector = SelectorType::SelectionDAG;
810 // Set consistently TM->Options.EnableFastISel and EnableGlobalISel.
811 if (Selector == SelectorType::FastISel) {
812 TM->setFastISel(true);
813 TM->setGlobalISel(false);
814 } else if (Selector == SelectorType::GlobalISel) {
815 TM->setFastISel(false);
816 TM->setGlobalISel(true);
819 // FIXME: Injecting into the DAGISel pipeline seems to cause issues with
820 // analyses needing to be re-run. This can result in being unable to
821 // schedule passes (particularly with 'Function Alias Analysis
822 // Results'). It's not entirely clear why but AFAICT this seems to be
823 // due to one FunctionPassManager not being able to use analyses from a
824 // previous one. As we're injecting a ModulePass we break the usual
825 // pass manager into two. GlobalISel with the fallback path disabled
826 // and -run-pass seem to be unaffected. The majority of GlobalISel
827 // testing uses -run-pass so this probably isn't too bad.
828 SaveAndRestore<bool> SavedDebugifyIsSafe(DebugifyIsSafe);
829 if (Selector != SelectorType::GlobalISel || !isGlobalISelAbortEnabled())
830 DebugifyIsSafe = false;
832 // Add instruction selector passes.
833 if (Selector == SelectorType::GlobalISel) {
834 SaveAndRestore<bool> SavedAddingMachinePasses(AddingMachinePasses, true);
835 if (addIRTranslator())
838 addPreLegalizeMachineIR();
840 if (addLegalizeMachineIR())
843 // Before running the register bank selector, ask the target if it
844 // wants to run some passes.
845 addPreRegBankSelect();
847 if (addRegBankSelect())
850 addPreGlobalInstructionSelect();
852 if (addGlobalInstructionSelect())
855 // Pass to reset the MachineFunction if the ISel failed.
856 addPass(createResetMachineFunctionPass(
857 reportDiagnosticWhenGlobalISelFallback(), isGlobalISelAbortEnabled()));
859 // Provide a fallback path when we do not want to abort on
860 // not-yet-supported input.
861 if (!isGlobalISelAbortEnabled() && addInstSelector())
864 } else if (addInstSelector())
867 // Expand pseudo-instructions emitted by ISel. Don't run the verifier before
869 addPass(&FinalizeISelID);
871 // Print the instruction selected machine code...
872 printAndVerify("After Instruction Selection");
877 bool TargetPassConfig::addISelPasses() {
878 if (TM->useEmulatedTLS())
879 addPass(createLowerEmuTLSPass());
881 addPass(createPreISelIntrinsicLoweringPass());
882 addPass(createTargetTransformInfoWrapperPass(TM->getTargetIRAnalysis()));
885 addPassesToHandleExceptions();
888 return addCoreISelPasses();
891 /// -regalloc=... command line option.
892 static FunctionPass *useDefaultRegisterAllocator() { return nullptr; }
893 static cl::opt<RegisterRegAlloc::FunctionPassCtor, false,
894 RegisterPassParser<RegisterRegAlloc>>
895 RegAlloc("regalloc", cl::Hidden, cl::init(&useDefaultRegisterAllocator),
896 cl::desc("Register allocator to use"));
898 /// Add the complete set of target-independent postISel code generator passes.
900 /// This can be read as the standard order of major LLVM CodeGen stages. Stages
901 /// with nontrivial configuration or multiple passes are broken out below in
902 /// add%Stage routines.
904 /// Any TargetPassConfig::addXX routine may be overriden by the Target. The
905 /// addPre/Post methods with empty header implementations allow injecting
906 /// target-specific fixups just before or after major stages. Additionally,
907 /// targets have the flexibility to change pass order within a stage by
908 /// overriding default implementation of add%Stage routines below. Each
909 /// technique has maintainability tradeoffs because alternate pass orders are
910 /// not well supported. addPre/Post works better if the target pass is easily
911 /// tied to a common pass. But if it has subtle dependencies on multiple passes,
912 /// the target should override the stage instead.
914 /// TODO: We could use a single addPre/Post(ID) hook to allow pass injection
915 /// before/after any target-independent pass. But it's currently overkill.
916 void TargetPassConfig::addMachinePasses() {
917 AddingMachinePasses = true;
919 // Insert a machine instr printer pass after the specified pass.
920 StringRef PrintMachineInstrsPassName = PrintMachineInstrs.getValue();
921 if (!PrintMachineInstrsPassName.equals("") &&
922 !PrintMachineInstrsPassName.equals("option-unspecified")) {
923 if (const PassInfo *TPI = getPassInfo(PrintMachineInstrsPassName)) {
924 const PassRegistry *PR = PassRegistry::getPassRegistry();
925 const PassInfo *IPI = PR->getPassInfo(StringRef("machineinstr-printer"));
926 assert(IPI && "failed to get \"machineinstr-printer\" PassInfo!");
927 const char *TID = (const char *)(TPI->getTypeInfo());
928 const char *IID = (const char *)(IPI->getTypeInfo());
929 insertPass(TID, IID);
933 // Add passes that optimize machine instructions in SSA form.
934 if (getOptLevel() != CodeGenOpt::None) {
935 addMachineSSAOptimization();
937 // If the target requests it, assign local variables to stack slots relative
938 // to one another and simplify frame index references where possible.
939 addPass(&LocalStackSlotAllocationID);
942 if (TM->Options.EnableIPRA)
943 addPass(createRegUsageInfoPropPass());
945 // Run pre-ra passes.
948 // Debugifying the register allocator passes seems to provoke some
949 // non-determinism that affects CodeGen and there doesn't seem to be a point
950 // where it becomes safe again so stop debugifying here.
951 DebugifyIsSafe = false;
953 // Run register allocation and passes that are tightly coupled with it,
954 // including phi elimination and scheduling.
955 if (getOptimizeRegAlloc())
956 addOptimizedRegAlloc();
960 // Run post-ra passes.
963 addPass(&FixupStatepointCallerSavedID);
965 // Insert prolog/epilog code. Eliminate abstract frame index references...
966 if (getOptLevel() != CodeGenOpt::None) {
967 addPass(&PostRAMachineSinkingID);
968 addPass(&ShrinkWrapID);
971 // Prolog/Epilog inserter needs a TargetMachine to instantiate. But only
972 // do so if it hasn't been disabled, substituted, or overridden.
973 if (!isPassSubstitutedOrOverridden(&PrologEpilogCodeInserterID))
974 addPass(createPrologEpilogInserterPass());
976 /// Add passes that optimize machine instructions after register allocation.
977 if (getOptLevel() != CodeGenOpt::None)
978 addMachineLateOptimization();
980 // Expand pseudo instructions before second scheduling pass.
981 addPass(&ExpandPostRAPseudosID);
983 // Run pre-sched2 passes.
986 if (EnableImplicitNullChecks)
987 addPass(&ImplicitNullChecksID);
989 // Second pass scheduler.
990 // Let Target optionally insert this pass by itself at some other
992 if (getOptLevel() != CodeGenOpt::None &&
993 !TM->targetSchedulesPostRAScheduling()) {
995 addPass(&PostMachineSchedulerID);
997 addPass(&PostRASchedulerID);
1001 if (addGCPasses()) {
1003 addPass(createGCInfoPrinter(dbgs()), false, false);
1006 // Basic block placement.
1007 if (getOptLevel() != CodeGenOpt::None)
1008 addBlockPlacement();
1010 // Insert before XRay Instrumentation.
1011 addPass(&FEntryInserterID);
1013 addPass(&XRayInstrumentationID);
1014 addPass(&PatchableFunctionID);
1018 if (TM->Options.EnableIPRA)
1019 // Collect register usage information and produce a register mask of
1020 // clobbered registers, to be used to optimize call sites.
1021 addPass(createRegUsageInfoCollector());
1023 // FIXME: Some backends are incompatible with running the verifier after
1024 // addPreEmitPass. Maybe only pass "false" here for those targets?
1025 addPass(&FuncletLayoutID, false);
1027 addPass(&StackMapLivenessID, false);
1028 addPass(&LiveDebugValuesID, false);
1030 if (TM->Options.EnableMachineOutliner && getOptLevel() != CodeGenOpt::None &&
1031 EnableMachineOutliner != NeverOutline) {
1032 bool RunOnAllFunctions = (EnableMachineOutliner == AlwaysOutline);
1033 bool AddOutliner = RunOnAllFunctions ||
1034 TM->Options.SupportsDefaultOutlining;
1036 addPass(createMachineOutlinerPass(RunOnAllFunctions));
1039 if (TM->getBBSectionsType() != llvm::BasicBlockSection::None)
1040 addPass(llvm::createBBSectionsPreparePass(TM->getBBSectionsFuncListBuf()));
1042 // Add passes that directly emit MI after all other MI passes.
1045 AddingMachinePasses = false;
1048 /// Add passes that optimize machine instructions in SSA form.
1049 void TargetPassConfig::addMachineSSAOptimization() {
1050 // Pre-ra tail duplication.
1051 addPass(&EarlyTailDuplicateID);
1053 // Optimize PHIs before DCE: removing dead PHI cycles may make more
1054 // instructions dead.
1055 addPass(&OptimizePHIsID);
1057 // This pass merges large allocas. StackSlotColoring is a different pass
1058 // which merges spill slots.
1059 addPass(&StackColoringID);
1061 // If the target requests it, assign local variables to stack slots relative
1062 // to one another and simplify frame index references where possible.
1063 addPass(&LocalStackSlotAllocationID);
1065 // With optimization, dead code should already be eliminated. However
1066 // there is one known exception: lowered code for arguments that are only
1067 // used by tail calls, where the tail calls reuse the incoming stack
1068 // arguments directly (see t11 in test/CodeGen/X86/sibcall.ll).
1069 addPass(&DeadMachineInstructionElimID);
1071 // Allow targets to insert passes that improve instruction level parallelism,
1072 // like if-conversion. Such passes will typically need dominator trees and
1073 // loop info, just like LICM and CSE below.
1076 addPass(&EarlyMachineLICMID);
1077 addPass(&MachineCSEID);
1079 addPass(&MachineSinkingID);
1081 addPass(&PeepholeOptimizerID);
1082 // Clean-up the dead code that may have been generated by peephole
1084 addPass(&DeadMachineInstructionElimID);
1087 //===---------------------------------------------------------------------===//
1088 /// Register Allocation Pass Configuration
1089 //===---------------------------------------------------------------------===//
1091 bool TargetPassConfig::getOptimizeRegAlloc() const {
1092 switch (OptimizeRegAlloc) {
1093 case cl::BOU_UNSET: return getOptLevel() != CodeGenOpt::None;
1094 case cl::BOU_TRUE: return true;
1095 case cl::BOU_FALSE: return false;
1097 llvm_unreachable("Invalid optimize-regalloc state");
1100 /// A dummy default pass factory indicates whether the register allocator is
1101 /// overridden on the command line.
1102 static llvm::once_flag InitializeDefaultRegisterAllocatorFlag;
1104 static RegisterRegAlloc
1105 defaultRegAlloc("default",
1106 "pick register allocator based on -O option",
1107 useDefaultRegisterAllocator);
1109 static void initializeDefaultRegisterAllocatorOnce() {
1110 if (!RegisterRegAlloc::getDefault())
1111 RegisterRegAlloc::setDefault(RegAlloc);
1114 /// Instantiate the default register allocator pass for this target for either
1115 /// the optimized or unoptimized allocation path. This will be added to the pass
1116 /// manager by addFastRegAlloc in the unoptimized case or addOptimizedRegAlloc
1117 /// in the optimized case.
1119 /// A target that uses the standard regalloc pass order for fast or optimized
1120 /// allocation may still override this for per-target regalloc
1121 /// selection. But -regalloc=... always takes precedence.
1122 FunctionPass *TargetPassConfig::createTargetRegisterAllocator(bool Optimized) {
1124 return createGreedyRegisterAllocator();
1126 return createFastRegisterAllocator();
1129 /// Find and instantiate the register allocation pass requested by this target
1130 /// at the current optimization level. Different register allocators are
1131 /// defined as separate passes because they may require different analysis.
1133 /// This helper ensures that the regalloc= option is always available,
1134 /// even for targets that override the default allocator.
1136 /// FIXME: When MachinePassRegistry register pass IDs instead of function ptrs,
1137 /// this can be folded into addPass.
1138 FunctionPass *TargetPassConfig::createRegAllocPass(bool Optimized) {
1139 // Initialize the global default.
1140 llvm::call_once(InitializeDefaultRegisterAllocatorFlag,
1141 initializeDefaultRegisterAllocatorOnce);
1143 RegisterRegAlloc::FunctionPassCtor Ctor = RegisterRegAlloc::getDefault();
1144 if (Ctor != useDefaultRegisterAllocator)
1147 // With no -regalloc= override, ask the target for a regalloc pass.
1148 return createTargetRegisterAllocator(Optimized);
1151 bool TargetPassConfig::addRegAssignmentFast() {
1152 if (RegAlloc != &useDefaultRegisterAllocator &&
1153 RegAlloc != &createFastRegisterAllocator)
1154 report_fatal_error("Must use fast (default) register allocator for unoptimized regalloc.");
1156 addPass(createRegAllocPass(false));
1160 bool TargetPassConfig::addRegAssignmentOptimized() {
1161 // Add the selected register allocation pass.
1162 addPass(createRegAllocPass(true));
1164 // Allow targets to change the register assignments before rewriting.
1167 // Finally rewrite virtual registers.
1168 addPass(&VirtRegRewriterID);
1170 // Perform stack slot coloring and post-ra machine LICM.
1172 // FIXME: Re-enable coloring with register when it's capable of adding
1174 addPass(&StackSlotColoringID);
1179 /// Return true if the default global register allocator is in use and
1180 /// has not be overriden on the command line with '-regalloc=...'
1181 bool TargetPassConfig::usingDefaultRegAlloc() const {
1182 return RegAlloc.getNumOccurrences() == 0;
1185 /// Add the minimum set of target-independent passes that are required for
1186 /// register allocation. No coalescing or scheduling.
1187 void TargetPassConfig::addFastRegAlloc() {
1188 addPass(&PHIEliminationID, false);
1189 addPass(&TwoAddressInstructionPassID, false);
1191 addRegAssignmentFast();
1194 /// Add standard target-independent passes that are tightly coupled with
1195 /// optimized register allocation, including coalescing, machine instruction
1196 /// scheduling, and register allocation itself.
1197 void TargetPassConfig::addOptimizedRegAlloc() {
1198 addPass(&DetectDeadLanesID, false);
1200 addPass(&ProcessImplicitDefsID, false);
1202 // LiveVariables currently requires pure SSA form.
1204 // FIXME: Once TwoAddressInstruction pass no longer uses kill flags,
1205 // LiveVariables can be removed completely, and LiveIntervals can be directly
1206 // computed. (We still either need to regenerate kill flags after regalloc, or
1207 // preferably fix the scavenger to not depend on them).
1208 addPass(&LiveVariablesID, false);
1210 // Edge splitting is smarter with machine loop info.
1211 addPass(&MachineLoopInfoID, false);
1212 addPass(&PHIEliminationID, false);
1214 // Eventually, we want to run LiveIntervals before PHI elimination.
1215 if (EarlyLiveIntervals)
1216 addPass(&LiveIntervalsID, false);
1218 addPass(&TwoAddressInstructionPassID, false);
1219 addPass(&RegisterCoalescerID);
1221 // The machine scheduler may accidentally create disconnected components
1222 // when moving subregister definitions around, avoid this by splitting them to
1223 // separate vregs before. Splitting can also improve reg. allocation quality.
1224 addPass(&RenameIndependentSubregsID);
1226 // PreRA instruction scheduling.
1227 addPass(&MachineSchedulerID);
1229 if (addRegAssignmentOptimized()) {
1230 // Allow targets to expand pseudo instructions depending on the choice of
1231 // registers before MachineCopyPropagation.
1234 // Copy propagate to forward register uses and try to eliminate COPYs that
1235 // were not coalesced.
1236 addPass(&MachineCopyPropagationID);
1238 // Run post-ra machine LICM to hoist reloads / remats.
1240 // FIXME: can this move into MachineLateOptimization?
1241 addPass(&MachineLICMID);
1245 //===---------------------------------------------------------------------===//
1246 /// Post RegAlloc Pass Configuration
1247 //===---------------------------------------------------------------------===//
1249 /// Add passes that optimize machine instructions after register allocation.
1250 void TargetPassConfig::addMachineLateOptimization() {
1251 // Branch folding must be run after regalloc and prolog/epilog insertion.
1252 addPass(&BranchFolderPassID);
1254 // Tail duplication.
1255 // Note that duplicating tail just increases code size and degrades
1256 // performance for targets that require Structured Control Flow.
1257 // In addition it can also make CFG irreducible. Thus we disable it.
1258 if (!TM->requiresStructuredCFG())
1259 addPass(&TailDuplicateID);
1261 // Copy propagation.
1262 addPass(&MachineCopyPropagationID);
1265 /// Add standard GC passes.
1266 bool TargetPassConfig::addGCPasses() {
1267 addPass(&GCMachineCodeAnalysisID, false);
1271 /// Add standard basic block placement passes.
1272 void TargetPassConfig::addBlockPlacement() {
1273 if (addPass(&MachineBlockPlacementID)) {
1274 // Run a separate pass to collect block placement statistics.
1275 if (EnableBlockPlacementStats)
1276 addPass(&MachineBlockPlacementStatsID);
1280 //===---------------------------------------------------------------------===//
1281 /// GlobalISel Configuration
1282 //===---------------------------------------------------------------------===//
1283 bool TargetPassConfig::isGlobalISelAbortEnabled() const {
1284 return TM->Options.GlobalISelAbort == GlobalISelAbortMode::Enable;
1287 bool TargetPassConfig::reportDiagnosticWhenGlobalISelFallback() const {
1288 return TM->Options.GlobalISelAbort == GlobalISelAbortMode::DisableWithDiag;
1291 bool TargetPassConfig::isGISelCSEEnabled() const {
1295 std::unique_ptr<CSEConfigBase> TargetPassConfig::getCSEConfig() const {
1296 return std::make_unique<CSEConfigBase>();