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

source code of llvm/lib/CodeGen/TargetPassConfig.cpp