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