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