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