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