[Clang/AMDGPU] Zero sized arrays not allowed in HIP device code. (#113470)
[llvm-project.git] / llvm / lib / CodeGen / TargetPassConfig.cpp
blobd407e9f0871d4c5da37aed5d2cbc81fdafff41c5
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.
12 //===---------------------------------------------------------------------===//
14 #include "llvm/CodeGen/TargetPassConfig.h"
15 #include "llvm/ADT/DenseMap.h"
16 #include "llvm/ADT/SmallVector.h"
17 #include "llvm/ADT/StringRef.h"
18 #include "llvm/Analysis/BasicAliasAnalysis.h"
19 #include "llvm/Analysis/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>
57 using namespace llvm;
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> PrintLSR("print-lsr-output", cl::Hidden,
117 cl::desc("Print LLVM IR produced by the loop-reduce pass"));
118 static cl::opt<bool>
119 PrintISelInput("print-isel-input", cl::Hidden,
120 cl::desc("Print LLVM IR input to isel pass"));
121 static cl::opt<cl::boolOrDefault>
122 VerifyMachineCode("verify-machineinstrs", cl::Hidden,
123 cl::desc("Verify generated machine code"));
124 static cl::opt<cl::boolOrDefault>
125 DebugifyAndStripAll("debugify-and-strip-all-safe", cl::Hidden,
126 cl::desc("Debugify MIR before and Strip debug after "
127 "each pass except those known to be unsafe "
128 "when debug info is present"));
129 static cl::opt<cl::boolOrDefault> DebugifyCheckAndStripAll(
130 "debugify-check-and-strip-all-safe", cl::Hidden,
131 cl::desc(
132 "Debugify MIR before, by checking and stripping the debug info after, "
133 "each pass except those known to be unsafe when debug info is "
134 "present"));
135 // Enable or disable the MachineOutliner.
136 static cl::opt<RunOutliner> EnableMachineOutliner(
137 "enable-machine-outliner", cl::desc("Enable the machine outliner"),
138 cl::Hidden, cl::ValueOptional, cl::init(RunOutliner::TargetDefault),
139 cl::values(clEnumValN(RunOutliner::AlwaysOutline, "always",
140 "Run on all functions guaranteed to be beneficial"),
141 clEnumValN(RunOutliner::NeverOutline, "never",
142 "Disable all outlining"),
143 // Sentinel value for unspecified option.
144 clEnumValN(RunOutliner::AlwaysOutline, "", "")));
145 static cl::opt<bool> EnableGlobalMergeFunc(
146 "enable-global-merge-func", cl::Hidden,
147 cl::desc("Enable global merge functions that are based on hash function"));
148 // Disable the pass to fix unwind information. Whether the pass is included in
149 // the pipeline is controlled via the target options, this option serves as
150 // manual override.
151 static cl::opt<bool> DisableCFIFixup("disable-cfi-fixup", cl::Hidden,
152 cl::desc("Disable the CFI fixup pass"));
153 // Enable or disable FastISel. Both options are needed, because
154 // FastISel is enabled by default with -fast, and we wish to be
155 // able to enable or disable fast-isel independently from -O0.
156 static cl::opt<cl::boolOrDefault>
157 EnableFastISelOption("fast-isel", cl::Hidden,
158 cl::desc("Enable the \"fast\" instruction selector"));
160 static cl::opt<cl::boolOrDefault> EnableGlobalISelOption(
161 "global-isel", cl::Hidden,
162 cl::desc("Enable the \"global\" instruction selector"));
164 // FIXME: remove this after switching to NPM or GlobalISel, whichever gets there
165 // first...
166 static cl::opt<bool>
167 PrintAfterISel("print-after-isel", cl::init(false), cl::Hidden,
168 cl::desc("Print machine instrs after ISel"));
170 static cl::opt<GlobalISelAbortMode> EnableGlobalISelAbort(
171 "global-isel-abort", cl::Hidden,
172 cl::desc("Enable abort calls when \"global\" instruction selection "
173 "fails to lower/select an instruction"),
174 cl::values(
175 clEnumValN(GlobalISelAbortMode::Disable, "0", "Disable the abort"),
176 clEnumValN(GlobalISelAbortMode::Enable, "1", "Enable the abort"),
177 clEnumValN(GlobalISelAbortMode::DisableWithDiag, "2",
178 "Disable the abort but emit a diagnostic on failure")));
180 // Disable MIRProfileLoader before RegAlloc. This is for for debugging and
181 // tuning purpose.
182 static cl::opt<bool> DisableRAFSProfileLoader(
183 "disable-ra-fsprofile-loader", cl::init(false), cl::Hidden,
184 cl::desc("Disable MIRProfileLoader before RegAlloc"));
185 // Disable MIRProfileLoader before BloackPlacement. This is for for debugging
186 // and tuning purpose.
187 static cl::opt<bool> DisableLayoutFSProfileLoader(
188 "disable-layout-fsprofile-loader", cl::init(false), cl::Hidden,
189 cl::desc("Disable MIRProfileLoader before BlockPlacement"));
190 // Specify FSProfile file name.
191 static cl::opt<std::string>
192 FSProfileFile("fs-profile-file", cl::init(""), cl::value_desc("filename"),
193 cl::desc("Flow Sensitive profile file name."), cl::Hidden);
194 // Specify Remapping file for FSProfile.
195 static cl::opt<std::string> FSRemappingFile(
196 "fs-remapping-file", cl::init(""), cl::value_desc("filename"),
197 cl::desc("Flow Sensitive profile remapping file name."), cl::Hidden);
199 // Temporary option to allow experimenting with MachineScheduler as a post-RA
200 // scheduler. Targets can "properly" enable this with
201 // substitutePass(&PostRASchedulerID, &PostMachineSchedulerID).
202 // Targets can return true in targetSchedulesPostRAScheduling() and
203 // insert a PostRA scheduling pass wherever it wants.
204 static cl::opt<bool> MISchedPostRA(
205 "misched-postra", cl::Hidden,
206 cl::desc(
207 "Run MachineScheduler post regalloc (independent of preRA sched)"));
209 // Experimental option to run live interval analysis early.
210 static cl::opt<bool> EarlyLiveIntervals("early-live-intervals", cl::Hidden,
211 cl::desc("Run live interval analysis earlier in the pipeline"));
213 static cl::opt<bool> DisableReplaceWithVecLib(
214 "disable-replace-with-vec-lib", cl::Hidden,
215 cl::desc("Disable replace with vector math call pass"));
217 /// Option names for limiting the codegen pipeline.
218 /// Those are used in error reporting and we didn't want
219 /// to duplicate their names all over the place.
220 static const char StartAfterOptName[] = "start-after";
221 static const char StartBeforeOptName[] = "start-before";
222 static const char StopAfterOptName[] = "stop-after";
223 static const char StopBeforeOptName[] = "stop-before";
225 static cl::opt<std::string>
226 StartAfterOpt(StringRef(StartAfterOptName),
227 cl::desc("Resume compilation after a specific pass"),
228 cl::value_desc("pass-name"), cl::init(""), cl::Hidden);
230 static cl::opt<std::string>
231 StartBeforeOpt(StringRef(StartBeforeOptName),
232 cl::desc("Resume compilation before a specific pass"),
233 cl::value_desc("pass-name"), cl::init(""), cl::Hidden);
235 static cl::opt<std::string>
236 StopAfterOpt(StringRef(StopAfterOptName),
237 cl::desc("Stop compilation after a specific pass"),
238 cl::value_desc("pass-name"), cl::init(""), cl::Hidden);
240 static cl::opt<std::string>
241 StopBeforeOpt(StringRef(StopBeforeOptName),
242 cl::desc("Stop compilation before a specific pass"),
243 cl::value_desc("pass-name"), cl::init(""), cl::Hidden);
245 /// Enable the machine function splitter pass.
246 static cl::opt<bool> EnableMachineFunctionSplitter(
247 "enable-split-machine-functions", cl::Hidden,
248 cl::desc("Split out cold blocks from machine functions based on profile "
249 "information."));
251 /// Disable the expand reductions pass for testing.
252 static cl::opt<bool> DisableExpandReductions(
253 "disable-expand-reductions", cl::init(false), cl::Hidden,
254 cl::desc("Disable the expand reduction intrinsics pass from running"));
256 /// Disable the select optimization pass.
257 static cl::opt<bool> DisableSelectOptimize(
258 "disable-select-optimize", cl::init(true), cl::Hidden,
259 cl::desc("Disable the select-optimization pass from running"));
261 /// Enable garbage-collecting empty basic blocks.
262 static cl::opt<bool>
263 GCEmptyBlocks("gc-empty-basic-blocks", cl::init(false), cl::Hidden,
264 cl::desc("Enable garbage-collecting empty basic blocks"));
266 /// Allow standard passes to be disabled by command line options. This supports
267 /// simple binary flags that either suppress the pass or do nothing.
268 /// i.e. -disable-mypass=false has no effect.
269 /// These should be converted to boolOrDefault in order to use applyOverride.
270 static IdentifyingPassPtr applyDisable(IdentifyingPassPtr PassID,
271 bool Override) {
272 if (Override)
273 return IdentifyingPassPtr();
274 return PassID;
277 /// Allow standard passes to be disabled by the command line, regardless of who
278 /// is adding the pass.
280 /// StandardID is the pass identified in the standard pass pipeline and provided
281 /// to addPass(). It may be a target-specific ID in the case that the target
282 /// directly adds its own pass, but in that case we harmlessly fall through.
284 /// TargetID is the pass that the target has configured to override StandardID.
286 /// StandardID may be a pseudo ID. In that case TargetID is the name of the real
287 /// pass to run. This allows multiple options to control a single pass depending
288 /// on where in the pipeline that pass is added.
289 static IdentifyingPassPtr overridePass(AnalysisID StandardID,
290 IdentifyingPassPtr TargetID) {
291 if (StandardID == &PostRASchedulerID)
292 return applyDisable(TargetID, DisablePostRASched);
294 if (StandardID == &BranchFolderPassID)
295 return applyDisable(TargetID, DisableBranchFold);
297 if (StandardID == &TailDuplicateLegacyID)
298 return applyDisable(TargetID, DisableTailDuplicate);
300 if (StandardID == &EarlyTailDuplicateLegacyID)
301 return applyDisable(TargetID, DisableEarlyTailDup);
303 if (StandardID == &MachineBlockPlacementID)
304 return applyDisable(TargetID, DisableBlockPlacement);
306 if (StandardID == &StackSlotColoringID)
307 return applyDisable(TargetID, DisableSSC);
309 if (StandardID == &DeadMachineInstructionElimID)
310 return applyDisable(TargetID, DisableMachineDCE);
312 if (StandardID == &EarlyIfConverterLegacyID)
313 return applyDisable(TargetID, DisableEarlyIfConversion);
315 if (StandardID == &EarlyMachineLICMID)
316 return applyDisable(TargetID, DisableMachineLICM);
318 if (StandardID == &MachineCSELegacyID)
319 return applyDisable(TargetID, DisableMachineCSE);
321 if (StandardID == &MachineLICMID)
322 return applyDisable(TargetID, DisablePostRAMachineLICM);
324 if (StandardID == &MachineSinkingID)
325 return applyDisable(TargetID, DisableMachineSink);
327 if (StandardID == &PostRAMachineSinkingID)
328 return applyDisable(TargetID, DisablePostRAMachineSink);
330 if (StandardID == &MachineCopyPropagationID)
331 return applyDisable(TargetID, DisableCopyProp);
333 return TargetID;
336 // Find the FSProfile file name. The internal option takes the precedence
337 // before getting from TargetMachine.
338 static std::string getFSProfileFile(const TargetMachine *TM) {
339 if (!FSProfileFile.empty())
340 return FSProfileFile.getValue();
341 const std::optional<PGOOptions> &PGOOpt = TM->getPGOOption();
342 if (PGOOpt == std::nullopt || PGOOpt->Action != PGOOptions::SampleUse)
343 return std::string();
344 return PGOOpt->ProfileFile;
347 // Find the Profile remapping file name. The internal option takes the
348 // precedence before getting from TargetMachine.
349 static std::string getFSRemappingFile(const TargetMachine *TM) {
350 if (!FSRemappingFile.empty())
351 return FSRemappingFile.getValue();
352 const std::optional<PGOOptions> &PGOOpt = TM->getPGOOption();
353 if (PGOOpt == std::nullopt || PGOOpt->Action != PGOOptions::SampleUse)
354 return std::string();
355 return PGOOpt->ProfileRemappingFile;
358 //===---------------------------------------------------------------------===//
359 /// TargetPassConfig
360 //===---------------------------------------------------------------------===//
362 INITIALIZE_PASS(TargetPassConfig, "targetpassconfig",
363 "Target Pass Configuration", false, false)
364 char TargetPassConfig::ID = 0;
366 namespace {
368 struct InsertedPass {
369 AnalysisID TargetPassID;
370 IdentifyingPassPtr InsertedPassID;
372 InsertedPass(AnalysisID TargetPassID, IdentifyingPassPtr InsertedPassID)
373 : TargetPassID(TargetPassID), InsertedPassID(InsertedPassID) {}
375 Pass *getInsertedPass() const {
376 assert(InsertedPassID.isValid() && "Illegal Pass ID!");
377 if (InsertedPassID.isInstance())
378 return InsertedPassID.getInstance();
379 Pass *NP = Pass::createPass(InsertedPassID.getID());
380 assert(NP && "Pass ID not registered");
381 return NP;
385 } // end anonymous namespace
387 namespace llvm {
389 extern cl::opt<bool> EnableFSDiscriminator;
391 class PassConfigImpl {
392 public:
393 // List of passes explicitly substituted by this target. Normally this is
394 // empty, but it is a convenient way to suppress or replace specific passes
395 // that are part of a standard pass pipeline without overridding the entire
396 // pipeline. This mechanism allows target options to inherit a standard pass's
397 // user interface. For example, a target may disable a standard pass by
398 // default by substituting a pass ID of zero, and the user may still enable
399 // that standard pass with an explicit command line option.
400 DenseMap<AnalysisID,IdentifyingPassPtr> TargetPasses;
402 /// Store the pairs of <AnalysisID, AnalysisID> of which the second pass
403 /// is inserted after each instance of the first one.
404 SmallVector<InsertedPass, 4> InsertedPasses;
407 } // end namespace llvm
409 // Out of line virtual method.
410 TargetPassConfig::~TargetPassConfig() {
411 delete Impl;
414 static const PassInfo *getPassInfo(StringRef PassName) {
415 if (PassName.empty())
416 return nullptr;
418 const PassRegistry &PR = *PassRegistry::getPassRegistry();
419 const PassInfo *PI = PR.getPassInfo(PassName);
420 if (!PI)
421 report_fatal_error(Twine('\"') + Twine(PassName) +
422 Twine("\" pass is not registered."));
423 return PI;
426 static AnalysisID getPassIDFromName(StringRef PassName) {
427 const PassInfo *PI = getPassInfo(PassName);
428 return PI ? PI->getTypeInfo() : nullptr;
431 static std::pair<StringRef, unsigned>
432 getPassNameAndInstanceNum(StringRef PassName) {
433 StringRef Name, InstanceNumStr;
434 std::tie(Name, InstanceNumStr) = PassName.split(',');
436 unsigned InstanceNum = 0;
437 if (!InstanceNumStr.empty() && InstanceNumStr.getAsInteger(10, InstanceNum))
438 report_fatal_error("invalid pass instance specifier " + PassName);
440 return std::make_pair(Name, InstanceNum);
443 void TargetPassConfig::setStartStopPasses() {
444 StringRef StartBeforeName;
445 std::tie(StartBeforeName, StartBeforeInstanceNum) =
446 getPassNameAndInstanceNum(StartBeforeOpt);
448 StringRef StartAfterName;
449 std::tie(StartAfterName, StartAfterInstanceNum) =
450 getPassNameAndInstanceNum(StartAfterOpt);
452 StringRef StopBeforeName;
453 std::tie(StopBeforeName, StopBeforeInstanceNum)
454 = getPassNameAndInstanceNum(StopBeforeOpt);
456 StringRef StopAfterName;
457 std::tie(StopAfterName, StopAfterInstanceNum)
458 = getPassNameAndInstanceNum(StopAfterOpt);
460 StartBefore = getPassIDFromName(StartBeforeName);
461 StartAfter = getPassIDFromName(StartAfterName);
462 StopBefore = getPassIDFromName(StopBeforeName);
463 StopAfter = getPassIDFromName(StopAfterName);
464 if (StartBefore && StartAfter)
465 report_fatal_error(Twine(StartBeforeOptName) + Twine(" and ") +
466 Twine(StartAfterOptName) + Twine(" specified!"));
467 if (StopBefore && StopAfter)
468 report_fatal_error(Twine(StopBeforeOptName) + Twine(" and ") +
469 Twine(StopAfterOptName) + Twine(" specified!"));
470 Started = (StartAfter == nullptr) && (StartBefore == nullptr);
473 CGPassBuilderOption llvm::getCGPassBuilderOption() {
474 CGPassBuilderOption Opt;
476 #define SET_OPTION(Option) \
477 if (Option.getNumOccurrences()) \
478 Opt.Option = Option;
480 SET_OPTION(EnableFastISelOption)
481 SET_OPTION(EnableGlobalISelAbort)
482 SET_OPTION(EnableGlobalISelOption)
483 SET_OPTION(EnableIPRA)
484 SET_OPTION(OptimizeRegAlloc)
485 SET_OPTION(VerifyMachineCode)
486 SET_OPTION(DisableAtExitBasedGlobalDtorLowering)
487 SET_OPTION(DisableExpandReductions)
488 SET_OPTION(PrintAfterISel)
489 SET_OPTION(FSProfileFile)
490 SET_OPTION(GCEmptyBlocks)
492 #define SET_BOOLEAN_OPTION(Option) Opt.Option = Option;
494 SET_BOOLEAN_OPTION(EarlyLiveIntervals)
495 SET_BOOLEAN_OPTION(EnableBlockPlacementStats)
496 SET_BOOLEAN_OPTION(EnableGlobalMergeFunc)
497 SET_BOOLEAN_OPTION(EnableImplicitNullChecks)
498 SET_BOOLEAN_OPTION(EnableMachineOutliner)
499 SET_BOOLEAN_OPTION(MISchedPostRA)
500 SET_BOOLEAN_OPTION(DisableMergeICmps)
501 SET_BOOLEAN_OPTION(DisableLSR)
502 SET_BOOLEAN_OPTION(DisableConstantHoisting)
503 SET_BOOLEAN_OPTION(DisableCGP)
504 SET_BOOLEAN_OPTION(DisablePartialLibcallInlining)
505 SET_BOOLEAN_OPTION(DisableSelectOptimize)
506 SET_BOOLEAN_OPTION(PrintLSR)
507 SET_BOOLEAN_OPTION(PrintISelInput)
508 SET_BOOLEAN_OPTION(DebugifyAndStripAll)
509 SET_BOOLEAN_OPTION(DebugifyCheckAndStripAll)
510 SET_BOOLEAN_OPTION(DisableRAFSProfileLoader)
511 SET_BOOLEAN_OPTION(DisableCFIFixup)
512 SET_BOOLEAN_OPTION(EnableMachineFunctionSplitter)
514 return Opt;
517 void llvm::registerCodeGenCallback(PassInstrumentationCallbacks &PIC,
518 TargetMachine &TM) {
520 // Register a callback for disabling passes.
521 PIC.registerShouldRunOptionalPassCallback([](StringRef P, Any) {
523 #define DISABLE_PASS(Option, Name) \
524 if (Option && P.contains(#Name)) \
525 return false;
526 DISABLE_PASS(DisableBlockPlacement, MachineBlockPlacementPass)
527 DISABLE_PASS(DisableBranchFold, BranchFolderPass)
528 DISABLE_PASS(DisableCopyProp, MachineCopyPropagationPass)
529 DISABLE_PASS(DisableEarlyIfConversion, EarlyIfConverterLegacyPass)
530 DISABLE_PASS(DisableEarlyTailDup, EarlyTailDuplicatePass)
531 DISABLE_PASS(DisableMachineCSE, MachineCSELegacyPass)
532 DISABLE_PASS(DisableMachineDCE, DeadMachineInstructionElimPass)
533 DISABLE_PASS(DisableMachineLICM, EarlyMachineLICMPass)
534 DISABLE_PASS(DisableMachineSink, MachineSinkingPass)
535 DISABLE_PASS(DisablePostRAMachineLICM, MachineLICMPass)
536 DISABLE_PASS(DisablePostRAMachineSink, PostRAMachineSinkingPass)
537 DISABLE_PASS(DisablePostRASched, PostRASchedulerPass)
538 DISABLE_PASS(DisableSSC, StackSlotColoringPass)
539 DISABLE_PASS(DisableTailDuplicate, TailDuplicatePass)
541 return true;
545 Expected<TargetPassConfig::StartStopInfo>
546 TargetPassConfig::getStartStopInfo(PassInstrumentationCallbacks &PIC) {
547 auto [StartBefore, StartBeforeInstanceNum] =
548 getPassNameAndInstanceNum(StartBeforeOpt);
549 auto [StartAfter, StartAfterInstanceNum] =
550 getPassNameAndInstanceNum(StartAfterOpt);
551 auto [StopBefore, StopBeforeInstanceNum] =
552 getPassNameAndInstanceNum(StopBeforeOpt);
553 auto [StopAfter, StopAfterInstanceNum] =
554 getPassNameAndInstanceNum(StopAfterOpt);
556 if (!StartBefore.empty() && !StartAfter.empty())
557 return make_error<StringError>(
558 Twine(StartBeforeOptName) + " and " + StartAfterOptName + " specified!",
559 std::make_error_code(std::errc::invalid_argument));
560 if (!StopBefore.empty() && !StopAfter.empty())
561 return make_error<StringError>(
562 Twine(StopBeforeOptName) + " and " + StopAfterOptName + " specified!",
563 std::make_error_code(std::errc::invalid_argument));
565 StartStopInfo Result;
566 Result.StartPass = StartBefore.empty() ? StartAfter : StartBefore;
567 Result.StopPass = StopBefore.empty() ? StopAfter : StopBefore;
568 Result.StartInstanceNum =
569 StartBefore.empty() ? StartAfterInstanceNum : StartBeforeInstanceNum;
570 Result.StopInstanceNum =
571 StopBefore.empty() ? StopAfterInstanceNum : StopBeforeInstanceNum;
572 Result.StartAfter = !StartAfter.empty();
573 Result.StopAfter = !StopAfter.empty();
574 Result.StartInstanceNum += Result.StartInstanceNum == 0;
575 Result.StopInstanceNum += Result.StopInstanceNum == 0;
576 return Result;
579 // Out of line constructor provides default values for pass options and
580 // registers all common codegen passes.
581 TargetPassConfig::TargetPassConfig(TargetMachine &TM, PassManagerBase &PM)
582 : ImmutablePass(ID), PM(&PM), TM(&TM) {
583 Impl = new PassConfigImpl();
585 // Register all target independent codegen passes to activate their PassIDs,
586 // including this pass itself.
587 initializeCodeGen(*PassRegistry::getPassRegistry());
589 // Also register alias analysis passes required by codegen passes.
590 initializeBasicAAWrapperPassPass(*PassRegistry::getPassRegistry());
591 initializeAAResultsWrapperPassPass(*PassRegistry::getPassRegistry());
593 if (EnableIPRA.getNumOccurrences())
594 TM.Options.EnableIPRA = EnableIPRA;
595 else {
596 // If not explicitly specified, use target default.
597 TM.Options.EnableIPRA |= TM.useIPRA();
600 if (TM.Options.EnableIPRA)
601 setRequiresCodeGenSCCOrder();
603 if (EnableGlobalISelAbort.getNumOccurrences())
604 TM.Options.GlobalISelAbort = EnableGlobalISelAbort;
606 setStartStopPasses();
609 CodeGenOptLevel TargetPassConfig::getOptLevel() const {
610 return TM->getOptLevel();
613 /// Insert InsertedPassID pass after TargetPassID.
614 void TargetPassConfig::insertPass(AnalysisID TargetPassID,
615 IdentifyingPassPtr InsertedPassID) {
616 assert(((!InsertedPassID.isInstance() &&
617 TargetPassID != InsertedPassID.getID()) ||
618 (InsertedPassID.isInstance() &&
619 TargetPassID != InsertedPassID.getInstance()->getPassID())) &&
620 "Insert a pass after itself!");
621 Impl->InsertedPasses.emplace_back(TargetPassID, InsertedPassID);
624 /// createPassConfig - Create a pass configuration object to be used by
625 /// addPassToEmitX methods for generating a pipeline of CodeGen passes.
627 /// Targets may override this to extend TargetPassConfig.
628 TargetPassConfig *
629 CodeGenTargetMachineImpl::createPassConfig(PassManagerBase &PM) {
630 return new TargetPassConfig(*this, PM);
633 TargetPassConfig::TargetPassConfig()
634 : ImmutablePass(ID) {
635 report_fatal_error("Trying to construct TargetPassConfig without a target "
636 "machine. Scheduling a CodeGen pass without a target "
637 "triple set?");
640 bool TargetPassConfig::willCompleteCodeGenPipeline() {
641 return StopBeforeOpt.empty() && StopAfterOpt.empty();
644 bool TargetPassConfig::hasLimitedCodeGenPipeline() {
645 return !StartBeforeOpt.empty() || !StartAfterOpt.empty() ||
646 !willCompleteCodeGenPipeline();
649 std::string TargetPassConfig::getLimitedCodeGenPipelineReason() {
650 if (!hasLimitedCodeGenPipeline())
651 return std::string();
652 std::string Res;
653 static cl::opt<std::string> *PassNames[] = {&StartAfterOpt, &StartBeforeOpt,
654 &StopAfterOpt, &StopBeforeOpt};
655 static const char *OptNames[] = {StartAfterOptName, StartBeforeOptName,
656 StopAfterOptName, StopBeforeOptName};
657 bool IsFirst = true;
658 for (int Idx = 0; Idx < 4; ++Idx)
659 if (!PassNames[Idx]->empty()) {
660 if (!IsFirst)
661 Res += " and ";
662 IsFirst = false;
663 Res += OptNames[Idx];
665 return Res;
668 // Helper to verify the analysis is really immutable.
669 void TargetPassConfig::setOpt(bool &Opt, bool Val) {
670 assert(!Initialized && "PassConfig is immutable");
671 Opt = Val;
674 void TargetPassConfig::substitutePass(AnalysisID StandardID,
675 IdentifyingPassPtr TargetID) {
676 Impl->TargetPasses[StandardID] = TargetID;
679 IdentifyingPassPtr TargetPassConfig::getPassSubstitution(AnalysisID ID) const {
680 DenseMap<AnalysisID, IdentifyingPassPtr>::const_iterator
681 I = Impl->TargetPasses.find(ID);
682 if (I == Impl->TargetPasses.end())
683 return ID;
684 return I->second;
687 bool TargetPassConfig::isPassSubstitutedOrOverridden(AnalysisID ID) const {
688 IdentifyingPassPtr TargetID = getPassSubstitution(ID);
689 IdentifyingPassPtr FinalPtr = overridePass(ID, TargetID);
690 return !FinalPtr.isValid() || FinalPtr.isInstance() ||
691 FinalPtr.getID() != ID;
694 /// Add a pass to the PassManager if that pass is supposed to be run. If the
695 /// Started/Stopped flags indicate either that the compilation should start at
696 /// a later pass or that it should stop after an earlier pass, then do not add
697 /// the pass. Finally, compare the current pass against the StartAfter
698 /// and StopAfter options and change the Started/Stopped flags accordingly.
699 void TargetPassConfig::addPass(Pass *P) {
700 assert(!Initialized && "PassConfig is immutable");
702 // Cache the Pass ID here in case the pass manager finds this pass is
703 // redundant with ones already scheduled / available, and deletes it.
704 // Fundamentally, once we add the pass to the manager, we no longer own it
705 // and shouldn't reference it.
706 AnalysisID PassID = P->getPassID();
708 if (StartBefore == PassID && StartBeforeCount++ == StartBeforeInstanceNum)
709 Started = true;
710 if (StopBefore == PassID && StopBeforeCount++ == StopBeforeInstanceNum)
711 Stopped = true;
712 if (Started && !Stopped) {
713 if (AddingMachinePasses) {
714 // Construct banner message before PM->add() as that may delete the pass.
715 std::string Banner =
716 std::string("After ") + std::string(P->getPassName());
717 addMachinePrePasses();
718 PM->add(P);
719 addMachinePostPasses(Banner);
720 } else {
721 PM->add(P);
724 // Add the passes after the pass P if there is any.
725 for (const auto &IP : Impl->InsertedPasses)
726 if (IP.TargetPassID == PassID)
727 addPass(IP.getInsertedPass());
728 } else {
729 delete P;
732 if (StopAfter == PassID && StopAfterCount++ == StopAfterInstanceNum)
733 Stopped = true;
735 if (StartAfter == PassID && StartAfterCount++ == StartAfterInstanceNum)
736 Started = true;
737 if (Stopped && !Started)
738 report_fatal_error("Cannot stop compilation after pass that is not run");
741 /// Add a CodeGen pass at this point in the pipeline after checking for target
742 /// and command line overrides.
744 /// addPass cannot return a pointer to the pass instance because is internal the
745 /// PassManager and the instance we create here may already be freed.
746 AnalysisID TargetPassConfig::addPass(AnalysisID PassID) {
747 IdentifyingPassPtr TargetID = getPassSubstitution(PassID);
748 IdentifyingPassPtr FinalPtr = overridePass(PassID, TargetID);
749 if (!FinalPtr.isValid())
750 return nullptr;
752 Pass *P;
753 if (FinalPtr.isInstance())
754 P = FinalPtr.getInstance();
755 else {
756 P = Pass::createPass(FinalPtr.getID());
757 if (!P)
758 llvm_unreachable("Pass ID not registered");
760 AnalysisID FinalID = P->getPassID();
761 addPass(P); // Ends the lifetime of P.
763 return FinalID;
766 void TargetPassConfig::printAndVerify(const std::string &Banner) {
767 addPrintPass(Banner);
768 addVerifyPass(Banner);
771 void TargetPassConfig::addPrintPass(const std::string &Banner) {
772 if (PrintAfterISel)
773 PM->add(createMachineFunctionPrinterPass(dbgs(), Banner));
776 void TargetPassConfig::addVerifyPass(const std::string &Banner) {
777 bool Verify = VerifyMachineCode == cl::BOU_TRUE;
778 #ifdef EXPENSIVE_CHECKS
779 if (VerifyMachineCode == cl::BOU_UNSET)
780 Verify = TM->isMachineVerifierClean();
781 #endif
782 if (Verify)
783 PM->add(createMachineVerifierPass(Banner));
786 void TargetPassConfig::addDebugifyPass() {
787 PM->add(createDebugifyMachineModulePass());
790 void TargetPassConfig::addStripDebugPass() {
791 PM->add(createStripDebugMachineModulePass(/*OnlyDebugified=*/true));
794 void TargetPassConfig::addCheckDebugPass() {
795 PM->add(createCheckDebugMachineModulePass());
798 void TargetPassConfig::addMachinePrePasses(bool AllowDebugify) {
799 if (AllowDebugify && DebugifyIsSafe &&
800 (DebugifyAndStripAll == cl::BOU_TRUE ||
801 DebugifyCheckAndStripAll == cl::BOU_TRUE))
802 addDebugifyPass();
805 void TargetPassConfig::addMachinePostPasses(const std::string &Banner) {
806 if (DebugifyIsSafe) {
807 if (DebugifyCheckAndStripAll == cl::BOU_TRUE) {
808 addCheckDebugPass();
809 addStripDebugPass();
810 } else if (DebugifyAndStripAll == cl::BOU_TRUE)
811 addStripDebugPass();
813 addVerifyPass(Banner);
816 /// Add common target configurable passes that perform LLVM IR to IR transforms
817 /// following machine independent optimization.
818 void TargetPassConfig::addIRPasses() {
819 // Before running any passes, run the verifier to determine if the input
820 // coming from the front-end and/or optimizer is valid.
821 if (!DisableVerify)
822 addPass(createVerifierPass());
824 if (getOptLevel() != CodeGenOptLevel::None) {
825 // Basic AliasAnalysis support.
826 // Add TypeBasedAliasAnalysis before BasicAliasAnalysis so that
827 // BasicAliasAnalysis wins if they disagree. This is intended to help
828 // support "obvious" type-punning idioms.
829 addPass(createTypeBasedAAWrapperPass());
830 addPass(createScopedNoAliasAAWrapperPass());
831 addPass(createBasicAAWrapperPass());
833 // Run loop strength reduction before anything else.
834 if (!DisableLSR) {
835 addPass(createCanonicalizeFreezeInLoopsPass());
836 addPass(createLoopStrengthReducePass());
837 if (EnableLoopTermFold)
838 addPass(createLoopTermFoldPass());
839 if (PrintLSR)
840 addPass(createPrintFunctionPass(dbgs(),
841 "\n\n*** Code after LSR ***\n"));
844 // The MergeICmpsPass tries to create memcmp calls by grouping sequences of
845 // loads and compares. ExpandMemCmpPass then tries to expand those calls
846 // into optimally-sized loads and compares. The transforms are enabled by a
847 // target lowering hook.
848 if (!DisableMergeICmps)
849 addPass(createMergeICmpsLegacyPass());
850 addPass(createExpandMemCmpLegacyPass());
853 // Run GC lowering passes for builtin collectors
854 // TODO: add a pass insertion point here
855 addPass(&GCLoweringID);
856 addPass(&ShadowStackGCLoweringID);
858 // For MachO, lower @llvm.global_dtors into @llvm.global_ctors with
859 // __cxa_atexit() calls to avoid emitting the deprecated __mod_term_func.
860 if (TM->getTargetTriple().isOSBinFormatMachO() &&
861 !DisableAtExitBasedGlobalDtorLowering)
862 addPass(createLowerGlobalDtorsLegacyPass());
864 // Make sure that no unreachable blocks are instruction selected.
865 addPass(createUnreachableBlockEliminationPass());
867 // Prepare expensive constants for SelectionDAG.
868 if (getOptLevel() != CodeGenOptLevel::None && !DisableConstantHoisting)
869 addPass(createConstantHoistingPass());
871 if (getOptLevel() != CodeGenOptLevel::None && !DisableReplaceWithVecLib)
872 addPass(createReplaceWithVeclibLegacyPass());
874 if (getOptLevel() != CodeGenOptLevel::None && !DisablePartialLibcallInlining)
875 addPass(createPartiallyInlineLibCallsPass());
877 // Instrument function entry after all inlining.
878 addPass(createPostInlineEntryExitInstrumenterPass());
880 // Add scalarization of target's unsupported masked memory intrinsics pass.
881 // the unsupported intrinsic will be replaced with a chain of basic blocks,
882 // that stores/loads element one-by-one if the appropriate mask bit is set.
883 addPass(createScalarizeMaskedMemIntrinLegacyPass());
885 // Expand reduction intrinsics into shuffle sequences if the target wants to.
886 // Allow disabling it for testing purposes.
887 if (!DisableExpandReductions)
888 addPass(createExpandReductionsPass());
890 // Convert conditional moves to conditional jumps when profitable.
891 if (getOptLevel() != CodeGenOptLevel::None && !DisableSelectOptimize)
892 addPass(createSelectOptimizePass());
894 if (EnableGlobalMergeFunc)
895 addPass(createGlobalMergeFuncPass());
898 /// Turn exception handling constructs into something the code generators can
899 /// handle.
900 void TargetPassConfig::addPassesToHandleExceptions() {
901 const MCAsmInfo *MCAI = TM->getMCAsmInfo();
902 assert(MCAI && "No MCAsmInfo");
903 switch (MCAI->getExceptionHandlingType()) {
904 case ExceptionHandling::SjLj:
905 // SjLj piggy-backs on dwarf for this bit. The cleanups done apply to both
906 // Dwarf EH prepare needs to be run after SjLj prepare. Otherwise,
907 // catch info can get misplaced when a selector ends up more than one block
908 // removed from the parent invoke(s). This could happen when a landing
909 // pad is shared by multiple invokes and is also a target of a normal
910 // edge from elsewhere.
911 addPass(createSjLjEHPreparePass(TM));
912 [[fallthrough]];
913 case ExceptionHandling::DwarfCFI:
914 case ExceptionHandling::ARM:
915 case ExceptionHandling::AIX:
916 case ExceptionHandling::ZOS:
917 addPass(createDwarfEHPass(getOptLevel()));
918 break;
919 case ExceptionHandling::WinEH:
920 // We support using both GCC-style and MSVC-style exceptions on Windows, so
921 // add both preparation passes. Each pass will only actually run if it
922 // recognizes the personality function.
923 addPass(createWinEHPass());
924 addPass(createDwarfEHPass(getOptLevel()));
925 break;
926 case ExceptionHandling::Wasm:
927 // Wasm EH uses Windows EH instructions, but it does not need to demote PHIs
928 // on catchpads and cleanuppads because it does not outline them into
929 // funclets. Catchswitch blocks are not lowered in SelectionDAG, so we
930 // should remove PHIs there.
931 addPass(createWinEHPass(/*DemoteCatchSwitchPHIOnly=*/true));
932 addPass(createWasmEHPass());
933 break;
934 case ExceptionHandling::None:
935 addPass(createLowerInvokePass());
937 // The lower invoke pass may create unreachable code. Remove it.
938 addPass(createUnreachableBlockEliminationPass());
939 break;
943 /// Add pass to prepare the LLVM IR for code generation. This should be done
944 /// before exception handling preparation passes.
945 void TargetPassConfig::addCodeGenPrepare() {
946 if (getOptLevel() != CodeGenOptLevel::None && !DisableCGP)
947 addPass(createCodeGenPrepareLegacyPass());
950 /// Add common passes that perform LLVM IR to IR transforms in preparation for
951 /// instruction selection.
952 void TargetPassConfig::addISelPrepare() {
953 addPreISel();
955 // Force codegen to run according to the callgraph.
956 if (requiresCodeGenSCCOrder())
957 addPass(new DummyCGSCCPass);
959 if (getOptLevel() != CodeGenOptLevel::None)
960 addPass(createObjCARCContractPass());
962 addPass(createCallBrPass());
964 // Add both the safe stack and the stack protection passes: each of them will
965 // only protect functions that have corresponding attributes.
966 addPass(createSafeStackPass());
967 addPass(createStackProtectorPass());
969 if (PrintISelInput)
970 addPass(createPrintFunctionPass(
971 dbgs(), "\n\n*** Final LLVM Code input to ISel ***\n"));
973 // All passes which modify the LLVM IR are now complete; run the verifier
974 // to ensure that the IR is valid.
975 if (!DisableVerify)
976 addPass(createVerifierPass());
979 bool TargetPassConfig::addCoreISelPasses() {
980 // Enable FastISel with -fast-isel, but allow that to be overridden.
981 TM->setO0WantsFastISel(EnableFastISelOption != cl::BOU_FALSE);
983 // Determine an instruction selector.
984 enum class SelectorType { SelectionDAG, FastISel, GlobalISel };
985 SelectorType Selector;
987 if (EnableFastISelOption == cl::BOU_TRUE)
988 Selector = SelectorType::FastISel;
989 else if (EnableGlobalISelOption == cl::BOU_TRUE ||
990 (TM->Options.EnableGlobalISel &&
991 EnableGlobalISelOption != cl::BOU_FALSE))
992 Selector = SelectorType::GlobalISel;
993 else if (TM->getOptLevel() == CodeGenOptLevel::None &&
994 TM->getO0WantsFastISel())
995 Selector = SelectorType::FastISel;
996 else
997 Selector = SelectorType::SelectionDAG;
999 // Set consistently TM->Options.EnableFastISel and EnableGlobalISel.
1000 if (Selector == SelectorType::FastISel) {
1001 TM->setFastISel(true);
1002 TM->setGlobalISel(false);
1003 } else if (Selector == SelectorType::GlobalISel) {
1004 TM->setFastISel(false);
1005 TM->setGlobalISel(true);
1008 // FIXME: Injecting into the DAGISel pipeline seems to cause issues with
1009 // analyses needing to be re-run. This can result in being unable to
1010 // schedule passes (particularly with 'Function Alias Analysis
1011 // Results'). It's not entirely clear why but AFAICT this seems to be
1012 // due to one FunctionPassManager not being able to use analyses from a
1013 // previous one. As we're injecting a ModulePass we break the usual
1014 // pass manager into two. GlobalISel with the fallback path disabled
1015 // and -run-pass seem to be unaffected. The majority of GlobalISel
1016 // testing uses -run-pass so this probably isn't too bad.
1017 SaveAndRestore SavedDebugifyIsSafe(DebugifyIsSafe);
1018 if (Selector != SelectorType::GlobalISel || !isGlobalISelAbortEnabled())
1019 DebugifyIsSafe = false;
1021 // Add instruction selector passes.
1022 if (Selector == SelectorType::GlobalISel) {
1023 SaveAndRestore SavedAddingMachinePasses(AddingMachinePasses, true);
1024 if (addIRTranslator())
1025 return true;
1027 addPreLegalizeMachineIR();
1029 if (addLegalizeMachineIR())
1030 return true;
1032 // Before running the register bank selector, ask the target if it
1033 // wants to run some passes.
1034 addPreRegBankSelect();
1036 if (addRegBankSelect())
1037 return true;
1039 addPreGlobalInstructionSelect();
1041 if (addGlobalInstructionSelect())
1042 return true;
1044 // Pass to reset the MachineFunction if the ISel failed.
1045 addPass(createResetMachineFunctionPass(
1046 reportDiagnosticWhenGlobalISelFallback(), isGlobalISelAbortEnabled()));
1048 // Provide a fallback path when we do not want to abort on
1049 // not-yet-supported input.
1050 if (!isGlobalISelAbortEnabled() && addInstSelector())
1051 return true;
1053 } else if (addInstSelector())
1054 return true;
1056 // Expand pseudo-instructions emitted by ISel. Don't run the verifier before
1057 // FinalizeISel.
1058 addPass(&FinalizeISelID);
1060 // Print the instruction selected machine code...
1061 printAndVerify("After Instruction Selection");
1063 return false;
1066 bool TargetPassConfig::addISelPasses() {
1067 if (TM->useEmulatedTLS())
1068 addPass(createLowerEmuTLSPass());
1070 PM->add(createTargetTransformInfoWrapperPass(TM->getTargetIRAnalysis()));
1071 addPass(createPreISelIntrinsicLoweringPass());
1072 addPass(createExpandLargeDivRemPass());
1073 addPass(createExpandLargeFpConvertPass());
1074 addIRPasses();
1075 addCodeGenPrepare();
1076 addPassesToHandleExceptions();
1077 addISelPrepare();
1079 return addCoreISelPasses();
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"));
1089 /// Add the complete set of target-independent postISel code generator passes.
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.
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.
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;
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);
1119 if (TM->Options.EnableIPRA)
1120 addPass(createRegUsageInfoPropPass());
1122 // Run pre-ra passes.
1123 addPreRegAlloc();
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;
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));
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();
1149 // Run post-ra passes.
1150 addPostRegAlloc();
1152 addPass(&RemoveRedundantDebugValuesID);
1154 addPass(&FixupStatepointCallerSavedID);
1156 // Insert prolog/epilog code. Eliminate abstract frame index references...
1157 if (getOptLevel() != CodeGenOptLevel::None) {
1158 addPass(&PostRAMachineSinkingID);
1159 addPass(&ShrinkWrapID);
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());
1167 /// Add passes that optimize machine instructions after register allocation.
1168 if (getOptLevel() != CodeGenOptLevel::None)
1169 addMachineLateOptimization();
1171 // Expand pseudo instructions before second scheduling pass.
1172 addPass(&ExpandPostRAPseudosID);
1174 // Run pre-sched2 passes.
1175 addPreSched2();
1177 if (EnableImplicitNullChecks)
1178 addPass(&ImplicitNullChecksID);
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);
1191 // GC
1192 addGCPasses();
1194 // Basic block placement.
1195 if (getOptLevel() != CodeGenOptLevel::None)
1196 addBlockPlacement();
1198 // Insert before XRay Instrumentation.
1199 addPass(&FEntryInserterID);
1201 addPass(&XRayInstrumentationID);
1202 addPass(&PatchableFunctionID);
1204 addPreEmitPass();
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());
1211 // FIXME: Some backends are incompatible with running the verifier after
1212 // addPreEmitPass. Maybe only pass "false" here for those targets?
1213 addPass(&FuncletLayoutID);
1215 addPass(&RemoveLoadsIntoFakeUsesID);
1216 addPass(&StackMapLivenessID);
1217 addPass(&LiveDebugValuesID);
1218 addPass(&MachineSanitizerBinaryMetadataID);
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));
1231 if (GCEmptyBlocks)
1232 addPass(llvm::createGCEmptyBasicBlocksPass());
1234 if (EnableFSDiscriminator)
1235 addPass(createMIRAddFSDiscriminatorsPass(
1236 sampleprof::FSDiscriminatorPass::PassLast));
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";
1259 addPass(createMachineFunctionSplitterPass());
1261 // We run the BasicBlockSections pass if either we need BB sections or BB
1262 // address map (or both).
1263 if (TM->getBBSectionsType() != llvm::BasicBlockSection::None ||
1264 TM->Options.BBAddrMap) {
1265 if (TM->getBBSectionsType() == llvm::BasicBlockSection::List) {
1266 addPass(llvm::createBasicBlockSectionsProfileReaderWrapperPass(
1267 TM->getBBSectionsFuncListBuf()));
1268 addPass(llvm::createBasicBlockPathCloningPass());
1270 addPass(llvm::createBasicBlockSectionsPass());
1273 addPostBBSections();
1275 if (!DisableCFIFixup && TM->Options.EnableCFIFixup)
1276 addPass(createCFIFixup());
1278 PM->add(createStackFrameLayoutAnalysisPass());
1280 // Add passes that directly emit MI after all other MI passes.
1281 addPreEmitPass2();
1283 AddingMachinePasses = false;
1286 /// Add passes that optimize machine instructions in SSA form.
1287 void TargetPassConfig::addMachineSSAOptimization() {
1288 // Pre-ra tail duplication.
1289 addPass(&EarlyTailDuplicateLegacyID);
1291 // Optimize PHIs before DCE: removing dead PHI cycles may make more
1292 // instructions dead.
1293 addPass(&OptimizePHIsLegacyID);
1295 // This pass merges large allocas. StackSlotColoring is a different pass
1296 // which merges spill slots.
1297 addPass(&StackColoringLegacyID);
1299 // If the target requests it, assign local variables to stack slots relative
1300 // to one another and simplify frame index references where possible.
1301 addPass(&LocalStackSlotAllocationID);
1303 // With optimization, dead code should already be eliminated. However
1304 // there is one known exception: lowered code for arguments that are only
1305 // used by tail calls, where the tail calls reuse the incoming stack
1306 // arguments directly (see t11 in test/CodeGen/X86/sibcall.ll).
1307 addPass(&DeadMachineInstructionElimID);
1309 // Allow targets to insert passes that improve instruction level parallelism,
1310 // like if-conversion. Such passes will typically need dominator trees and
1311 // loop info, just like LICM and CSE below.
1312 addILPOpts();
1314 addPass(&EarlyMachineLICMID);
1315 addPass(&MachineCSELegacyID);
1317 addPass(&MachineSinkingID);
1319 addPass(&PeepholeOptimizerLegacyID);
1320 // Clean-up the dead code that may have been generated by peephole
1321 // rewriting.
1322 addPass(&DeadMachineInstructionElimID);
1325 //===---------------------------------------------------------------------===//
1326 /// Register Allocation Pass Configuration
1327 //===---------------------------------------------------------------------===//
1329 bool TargetPassConfig::getOptimizeRegAlloc() const {
1330 switch (OptimizeRegAlloc) {
1331 case cl::BOU_UNSET:
1332 return getOptLevel() != CodeGenOptLevel::None;
1333 case cl::BOU_TRUE: return true;
1334 case cl::BOU_FALSE: return false;
1336 llvm_unreachable("Invalid optimize-regalloc state");
1339 /// A dummy default pass factory indicates whether the register allocator is
1340 /// overridden on the command line.
1341 static llvm::once_flag InitializeDefaultRegisterAllocatorFlag;
1343 static RegisterRegAlloc
1344 defaultRegAlloc("default",
1345 "pick register allocator based on -O option",
1346 useDefaultRegisterAllocator);
1348 static void initializeDefaultRegisterAllocatorOnce() {
1349 if (!RegisterRegAlloc::getDefault())
1350 RegisterRegAlloc::setDefault(RegAlloc);
1353 /// Instantiate the default register allocator pass for this target for either
1354 /// the optimized or unoptimized allocation path. This will be added to the pass
1355 /// manager by addFastRegAlloc in the unoptimized case or addOptimizedRegAlloc
1356 /// in the optimized case.
1358 /// A target that uses the standard regalloc pass order for fast or optimized
1359 /// allocation may still override this for per-target regalloc
1360 /// selection. But -regalloc=... always takes precedence.
1361 FunctionPass *TargetPassConfig::createTargetRegisterAllocator(bool Optimized) {
1362 if (Optimized)
1363 return createGreedyRegisterAllocator();
1364 else
1365 return createFastRegisterAllocator();
1368 /// Find and instantiate the register allocation pass requested by this target
1369 /// at the current optimization level. Different register allocators are
1370 /// defined as separate passes because they may require different analysis.
1372 /// This helper ensures that the regalloc= option is always available,
1373 /// even for targets that override the default allocator.
1375 /// FIXME: When MachinePassRegistry register pass IDs instead of function ptrs,
1376 /// this can be folded into addPass.
1377 FunctionPass *TargetPassConfig::createRegAllocPass(bool Optimized) {
1378 // Initialize the global default.
1379 llvm::call_once(InitializeDefaultRegisterAllocatorFlag,
1380 initializeDefaultRegisterAllocatorOnce);
1382 RegisterRegAlloc::FunctionPassCtor Ctor = RegisterRegAlloc::getDefault();
1383 if (Ctor != useDefaultRegisterAllocator)
1384 return Ctor();
1386 // With no -regalloc= override, ask the target for a regalloc pass.
1387 return createTargetRegisterAllocator(Optimized);
1390 bool TargetPassConfig::isCustomizedRegAlloc() {
1391 return RegAlloc !=
1392 (RegisterRegAlloc::FunctionPassCtor)&useDefaultRegisterAllocator;
1395 bool TargetPassConfig::addRegAssignAndRewriteFast() {
1396 if (RegAlloc != (RegisterRegAlloc::FunctionPassCtor)&useDefaultRegisterAllocator &&
1397 RegAlloc != (RegisterRegAlloc::FunctionPassCtor)&createFastRegisterAllocator)
1398 report_fatal_error("Must use fast (default) register allocator for unoptimized regalloc.");
1400 addPass(createRegAllocPass(false));
1402 // Allow targets to change the register assignments after
1403 // fast register allocation.
1404 addPostFastRegAllocRewrite();
1405 return true;
1408 bool TargetPassConfig::addRegAssignAndRewriteOptimized() {
1409 // Add the selected register allocation pass.
1410 addPass(createRegAllocPass(true));
1412 // Allow targets to change the register assignments before rewriting.
1413 addPreRewrite();
1415 // Finally rewrite virtual registers.
1416 addPass(&VirtRegRewriterID);
1418 // Regalloc scoring for ML-driven eviction - noop except when learning a new
1419 // eviction policy.
1420 addPass(createRegAllocScoringPass());
1421 return true;
1424 /// Return true if the default global register allocator is in use and
1425 /// has not be overriden on the command line with '-regalloc=...'
1426 bool TargetPassConfig::usingDefaultRegAlloc() const {
1427 return RegAlloc.getNumOccurrences() == 0;
1430 /// Add the minimum set of target-independent passes that are required for
1431 /// register allocation. No coalescing or scheduling.
1432 void TargetPassConfig::addFastRegAlloc() {
1433 addPass(&PHIEliminationID);
1434 addPass(&TwoAddressInstructionPassID);
1436 addRegAssignAndRewriteFast();
1439 /// Add standard target-independent passes that are tightly coupled with
1440 /// optimized register allocation, including coalescing, machine instruction
1441 /// scheduling, and register allocation itself.
1442 void TargetPassConfig::addOptimizedRegAlloc() {
1443 addPass(&DetectDeadLanesID);
1445 addPass(&InitUndefID);
1447 addPass(&ProcessImplicitDefsID);
1449 // LiveVariables currently requires pure SSA form.
1451 // FIXME: Once TwoAddressInstruction pass no longer uses kill flags,
1452 // LiveVariables can be removed completely, and LiveIntervals can be directly
1453 // computed. (We still either need to regenerate kill flags after regalloc, or
1454 // preferably fix the scavenger to not depend on them).
1455 // FIXME: UnreachableMachineBlockElim is a dependant pass of LiveVariables.
1456 // When LiveVariables is removed this has to be removed/moved either.
1457 // Explicit addition of UnreachableMachineBlockElim allows stopping before or
1458 // after it with -stop-before/-stop-after.
1459 addPass(&UnreachableMachineBlockElimID);
1460 addPass(&LiveVariablesID);
1462 // Edge splitting is smarter with machine loop info.
1463 addPass(&MachineLoopInfoID);
1464 addPass(&PHIEliminationID);
1466 // Eventually, we want to run LiveIntervals before PHI elimination.
1467 if (EarlyLiveIntervals)
1468 addPass(&LiveIntervalsID);
1470 addPass(&TwoAddressInstructionPassID);
1471 addPass(&RegisterCoalescerID);
1473 // The machine scheduler may accidentally create disconnected components
1474 // when moving subregister definitions around, avoid this by splitting them to
1475 // separate vregs before. Splitting can also improve reg. allocation quality.
1476 addPass(&RenameIndependentSubregsID);
1478 // PreRA instruction scheduling.
1479 addPass(&MachineSchedulerID);
1481 if (addRegAssignAndRewriteOptimized()) {
1482 // Perform stack slot coloring and post-ra machine LICM.
1483 addPass(&StackSlotColoringID);
1485 // Allow targets to expand pseudo instructions depending on the choice of
1486 // registers before MachineCopyPropagation.
1487 addPostRewrite();
1489 // Copy propagate to forward register uses and try to eliminate COPYs that
1490 // were not coalesced.
1491 addPass(&MachineCopyPropagationID);
1493 // Run post-ra machine LICM to hoist reloads / remats.
1495 // FIXME: can this move into MachineLateOptimization?
1496 addPass(&MachineLICMID);
1500 //===---------------------------------------------------------------------===//
1501 /// Post RegAlloc Pass Configuration
1502 //===---------------------------------------------------------------------===//
1504 /// Add passes that optimize machine instructions after register allocation.
1505 void TargetPassConfig::addMachineLateOptimization() {
1506 // Cleanup of redundant immediate/address loads.
1507 addPass(&MachineLateInstrsCleanupID);
1509 // Branch folding must be run after regalloc and prolog/epilog insertion.
1510 addPass(&BranchFolderPassID);
1512 // Tail duplication.
1513 // Note that duplicating tail just increases code size and degrades
1514 // performance for targets that require Structured Control Flow.
1515 // In addition it can also make CFG irreducible. Thus we disable it.
1516 if (!TM->requiresStructuredCFG())
1517 addPass(&TailDuplicateLegacyID);
1519 // Copy propagation.
1520 addPass(&MachineCopyPropagationID);
1523 /// Add standard GC passes.
1524 bool TargetPassConfig::addGCPasses() {
1525 addPass(&GCMachineCodeAnalysisID);
1526 return true;
1529 /// Add standard basic block placement passes.
1530 void TargetPassConfig::addBlockPlacement() {
1531 if (EnableFSDiscriminator) {
1532 addPass(createMIRAddFSDiscriminatorsPass(
1533 sampleprof::FSDiscriminatorPass::Pass2));
1534 const std::string ProfileFile = getFSProfileFile(TM);
1535 if (!ProfileFile.empty() && !DisableLayoutFSProfileLoader)
1536 addPass(createMIRProfileLoaderPass(ProfileFile, getFSRemappingFile(TM),
1537 sampleprof::FSDiscriminatorPass::Pass2,
1538 nullptr));
1540 if (addPass(&MachineBlockPlacementID)) {
1541 // Run a separate pass to collect block placement statistics.
1542 if (EnableBlockPlacementStats)
1543 addPass(&MachineBlockPlacementStatsID);
1547 //===---------------------------------------------------------------------===//
1548 /// GlobalISel Configuration
1549 //===---------------------------------------------------------------------===//
1550 bool TargetPassConfig::isGlobalISelAbortEnabled() const {
1551 return TM->Options.GlobalISelAbort == GlobalISelAbortMode::Enable;
1554 bool TargetPassConfig::reportDiagnosticWhenGlobalISelFallback() const {
1555 return TM->Options.GlobalISelAbort == GlobalISelAbortMode::DisableWithDiag;
1558 bool TargetPassConfig::isGISelCSEEnabled() const {
1559 return true;
1562 std::unique_ptr<CSEConfigBase> TargetPassConfig::getCSEConfig() const {
1563 return std::make_unique<CSEConfigBase>();