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