14#ifndef LLVM_PASSES_CODEGENPASSBUILDER_H
15#define LLVM_PASSES_CODEGENPASSBUILDER_H
91#define DUMMY_FUNCTION_PASS(NAME, PASS_NAME) \
92 struct PASS_NAME : public PassInfoMixin<PASS_NAME> { \
93 template <typename... Ts> PASS_NAME(Ts &&...) {} \
94 PreservedAnalyses run(Function &, FunctionAnalysisManager &) { \
95 return PreservedAnalyses::all(); \
98#define DUMMY_MACHINE_MODULE_PASS(NAME, PASS_NAME) \
99 struct PASS_NAME : public PassInfoMixin<PASS_NAME> { \
100 template <typename... Ts> PASS_NAME(Ts &&...) {} \
101 PreservedAnalyses run(Module &, ModuleAnalysisManager &) { \
102 return PreservedAnalyses::all(); \
105#define DUMMY_MACHINE_FUNCTION_PASS(NAME, PASS_NAME) \
106 struct PASS_NAME : public PassInfoMixin<PASS_NAME> { \
107 template <typename... Ts> PASS_NAME(Ts &&...) {} \
108 PreservedAnalyses run(MachineFunction &, \
109 MachineFunctionAnalysisManager &) { \
110 return PreservedAnalyses::all(); \
113#include "llvm/Passes/MachinePassRegistry.def"
151 template <
typename PassT>
154 template <
typename PassT>
156 std::declval<Module &>(), std::declval<ModuleAnalysisManager &>()));
158 template <
typename PassT>
160 std::declval<Function &>(), std::declval<FunctionAnalysisManager &>()));
162 template <
typename PassT>
164 std::declval<MachineFunction &>(),
165 std::declval<MachineFunctionAnalysisManager &>()));
179 template <
typename PassT>
183 "Only module pass and function pass are supported.");
184 bool Required =
false;
186 Required = PassT::isRequired();
187 if (!PB.runBeforeAdding(
Name) && !Required)
214 : MPM(MPM),
PB(
PB) {}
225 template <
typename PassT>
230 "Only module pass and function pass are supported.");
232 if (!Force && !PB.runBeforeAdding(
Name))
249 for (
auto &
C : PB.AfterCallbacks)
263 template <
typename TMC> TMC &
getTM()
const {
return static_cast<TMC &
>(
TM); }
283 return make_error<StringError>(
"addInstSelector is not overridden",
351 return make_error<StringError>(
"addIRTranslator is not overridden",
362 return make_error<StringError>(
"addLegalizeMachineIR is not overridden",
374 return make_error<StringError>(
"addRegBankSelect is not overridden",
387 return make_error<StringError>(
388 "addGlobalInstructionSelect is not overridden",
453 std::function<Expected<std::unique_ptr<MCStreamer>>(
MCContext &)>;
477 BeforeCallbacks.emplace_back(
483 template <
typename TargetPassT,
typename InsertedPassT>
485 AfterCallbacks.emplace_back(
487 if (
Name == TargetPassT::name())
493 DerivedT &derived() {
return static_cast<DerivedT &
>(*this); }
494 const DerivedT &derived()
const {
495 return static_cast<const DerivedT &
>(*this);
498 bool runBeforeAdding(StringRef
Name)
const {
499 bool ShouldAdd =
true;
500 for (
auto &
C : BeforeCallbacks)
501 ShouldAdd &=
C(
Name);
505 void setStartStopPasses(
const TargetPassConfig::StartStopInfo &
Info)
const;
507 Error verifyStartStop(
const TargetPassConfig::StartStopInfo &
Info)
const;
516 mutable bool Started =
true;
517 mutable bool Stopped =
true;
520template <
typename Derived,
typename TargetMachineT>
526 return StartStopInfo.takeError();
527 setStartStopPasses(*StartStopInfo);
537 addISelPasses(addIRPass);
545 if (
auto Err = addCoreISelPasses(addPass))
546 return std::move(Err);
548 if (
auto Err = derived().addMachinePasses(addPass))
549 return std::move(Err);
552 derived().addAsmPrinter(
553 addPass, [
this, &Out, DwoOut, FileType](
MCContext &Ctx) {
554 return this->TM.createMCStreamer(Out, DwoOut, FileType, Ctx);
561 return verifyStartStop(*StartStopInfo);
564template <
typename Derived,
typename TargetMachineT>
567 if (!
Info.StartPass.empty()) {
569 BeforeCallbacks.emplace_back([
this, &
Info, AfterFlag =
Info.StartAfter,
570 Count = 0u](
StringRef ClassName)
mutable {
571 if (Count == Info.StartInstanceNum) {
581 Started = !
Info.StartAfter;
587 if (!
Info.StopPass.empty()) {
589 BeforeCallbacks.emplace_back([
this, &
Info, AfterFlag =
Info.StopAfter,
590 Count = 0u](StringRef ClassName)
mutable {
591 if (Count == Info.StopInstanceNum) {
601 Stopped = !
Info.StopAfter;
607template <
typename Derived,
typename TargetMachineT>
608Error CodeGenPassBuilder<Derived, TargetMachineT>::verifyStartStop(
609 const TargetPassConfig::StartStopInfo &
Info)
const {
610 if (Started && Stopped)
611 return Error::success();
614 return make_error<StringError>(
615 "Can't find start pass \"" +
Info.StartPass +
"\".",
616 std::make_error_code(std::errc::invalid_argument));
618 return make_error<StringError>(
619 "Can't find stop pass \"" +
Info.StopPass +
"\".",
620 std::make_error_code(std::errc::invalid_argument));
621 return Error::success();
624template <
typename Derived,
typename TargetMachineT>
628 if (TM.useEmulatedTLS())
635 derived().addIRPasses(addPass);
636 derived().addCodeGenPrepare(addPass);
637 addPassesToHandleExceptions(addPass);
638 derived().addISelPrepare(addPass);
643template <
typename Derived,
typename TargetMachineT>
652 if (getOptLevel() != CodeGenOptLevel::None && !Opt.
DisableLSR) {
660 if (getOptLevel() != CodeGenOptLevel::None) {
685 if (getOptLevel() != CodeGenOptLevel::None)
688 if (getOptLevel() != CodeGenOptLevel::None &&
710template <
typename Derived,
typename TargetMachineT>
713 const MCAsmInfo *MCAI = TM.getMCAsmInfo();
714 assert(MCAI &&
"No MCAsmInfo");
716 case ExceptionHandling::SjLj:
725 case ExceptionHandling::DwarfCFI:
726 case ExceptionHandling::ARM:
727 case ExceptionHandling::AIX:
728 case ExceptionHandling::ZOS:
731 case ExceptionHandling::WinEH:
738 case ExceptionHandling::Wasm:
746 case ExceptionHandling::None:
757template <
typename Derived,
typename TargetMachineT>
760 if (getOptLevel() != CodeGenOptLevel::None && !Opt.
DisableCGP)
768template <
typename Derived,
typename TargetMachineT>
781 "\n\n*** Final LLVM Code input to ISel ***\n"));
789template <
typename Derived,
typename TargetMachineT>
797 SelectorType Selector;
800 Selector = SelectorType::FastISel;
803 (TM.Options.EnableGlobalISel &&
806 Selector = SelectorType::GlobalISel;
807 else if (TM.getOptLevel() == CodeGenOptLevel::None && TM.getO0WantsFastISel())
808 Selector = SelectorType::FastISel;
810 Selector = SelectorType::SelectionDAG;
813 if (Selector == SelectorType::FastISel) {
814 TM.setFastISel(
true);
815 TM.setGlobalISel(
false);
816 }
else if (Selector == SelectorType::GlobalISel) {
817 TM.setFastISel(
false);
818 TM.setGlobalISel(
true);
822 if (Selector == SelectorType::GlobalISel) {
823 if (
auto Err = derived().addIRTranslator(addPass))
824 return std::move(Err);
826 derived().addPreLegalizeMachineIR(addPass);
828 if (
auto Err = derived().addLegalizeMachineIR(addPass))
829 return std::move(Err);
833 derived().addPreRegBankSelect(addPass);
835 if (
auto Err = derived().addRegBankSelect(addPass))
836 return std::move(Err);
838 derived().addPreGlobalInstructionSelect(addPass);
840 if (
auto Err = derived().addGlobalInstructionSelect(addPass))
841 return std::move(Err);
844 addPass(ResetMachineFunctionPass(reportDiagnosticWhenGlobalISelFallback(),
845 isGlobalISelAbortEnabled()));
849 if (!isGlobalISelAbortEnabled())
850 if (
auto Err = derived().addInstSelector(addPass))
851 return std::move(Err);
853 }
else if (
auto Err = derived().addInstSelector(addPass))
854 return std::move(Err);
863 return Error::success();
882template <
typename Derived,
typename TargetMachineT>
886 if (getOptLevel() != CodeGenOptLevel::None) {
894 if (TM.Options.EnableIPRA)
895 addPass(RegUsageInfoPropagationPass());
898 derived().addPreRegAlloc(addPass);
903 derived().addOptimizedRegAlloc(addPass);
905 if (
auto Err = derived().addFastRegAlloc(addPass))
910 derived().addPostRegAlloc(addPass);
912 addPass(RemoveRedundantDebugValuesPass());
915 if (getOptLevel() != CodeGenOptLevel::None) {
916 addPass(PostRAMachineSinkingPass());
917 addPass(ShrinkWrapPass());
920 addPass(PrologEpilogInserterPass());
923 if (getOptLevel() != CodeGenOptLevel::None)
924 derived().addMachineLateOptimization(addPass);
927 addPass(ExpandPostRAPseudosPass());
930 derived().addPreSched2(addPass);
933 addPass(ImplicitNullChecksPass());
938 if (getOptLevel() != CodeGenOptLevel::None &&
939 !TM.targetSchedulesPostRAScheduling()) {
941 addPass(PostMachineSchedulerPass());
943 addPass(PostRASchedulerPass());
947 derived().addGCPasses(addPass);
950 if (getOptLevel() != CodeGenOptLevel::None)
951 derived().addBlockPlacement(addPass);
954 addPass(FEntryInserterPass());
956 addPass(XRayInstrumentationPass());
957 addPass(PatchableFunctionPass());
959 derived().addPreEmitPass(addPass);
961 if (TM.Options.EnableIPRA)
964 addPass(RegUsageInfoCollectorPass());
966 addPass(FuncletLayoutPass());
968 addPass(StackMapLivenessPass());
969 addPass(LiveDebugValuesPass());
970 addPass(MachineSanitizerBinaryMetadata());
972 if (TM.Options.EnableMachineOutliner &&
973 getOptLevel() != CodeGenOptLevel::None &&
975 bool RunOnAllFunctions =
977 bool AddOutliner = RunOnAllFunctions || TM.Options.SupportsDefaultOutlining;
979 addPass(MachineOutlinerPass(RunOnAllFunctions));
983 derived().addPreEmitPass2(addPass);
985 return Error::success();
989template <
typename Derived,
typename TargetMachineT>
993 addPass(EarlyTailDuplicatePass());
997 addPass(OptimizePHIsPass());
1001 addPass(StackColoringPass());
1016 derived().addILPOpts(addPass);
1018 addPass(EarlyMachineLICMPass());
1019 addPass(MachineCSEPass());
1021 addPass(MachineSinkingPass());
1023 addPass(PeepholeOptimizerPass());
1041template <
typename Derived,
typename TargetMachineT>
1045 addPass(RAGreedyPass());
1053template <
typename Derived,
typename TargetMachineT>
1059template <
typename Derived,
typename TargetMachineT>
1063 addRegAllocPass(addPass,
false);
1064 return Error::success();
1067template <
typename Derived,
typename TargetMachineT>
1071 addRegAllocPass(addPass,
true);
1074 derived().addPreRewrite(addPass);
1077 addPass(VirtRegRewriterPass());
1082 addPass(StackSlotColoringPass());
1084 return Error::success();
1089template <
typename Derived,
typename TargetMachineT>
1094 return derived().addRegAssignmentFast(addPass);
1100template <
typename Derived,
typename TargetMachineT>
1103 addPass(DetectDeadLanesPass());
1105 addPass(InitUndefPass());
1107 addPass(ProcessImplicitDefsPass());
1117 addPass(RegisterCoalescerPass());
1122 addPass(RenameIndependentSubregsPass());
1125 addPass(MachineSchedulerPass());
1127 if (derived().addRegAssignmentOptimized(addPass)) {
1130 derived().addPostRewrite(addPass);
1134 addPass(MachineCopyPropagationPass());
1139 addPass(MachineLICMPass());
1148template <
typename Derived,
typename TargetMachineT>
1152 addPass(BranchFolderPass());
1158 if (!TM.requiresStructuredCFG())
1159 addPass(TailDuplicatePass());
1162 addPass(MachineLateInstrsCleanupPass());
1165 addPass(MachineCopyPropagationPass());
1169template <
typename Derived,
typename TargetMachineT>
1172 addPass(MachineBlockPlacementPass());
1175 addPass(MachineBlockPlacementStatsPass());
This is the interface for LLVM's primary stateless and local alias analysis.
Analysis containing CSE Info
Defines an IR pass for CodeGen Prepare.
This file defines passes to print out IR in various granularities.
This file contains the declaration of the InterleavedAccessPass class, its corresponding pass name is...
This header provides classes for managing a pipeline of passes over loops in LLVM IR.
The header file for the LowerConstantIntrinsics pass as used by the new pass manager.
PassInstrumentationCallbacks PIC
PassBuilder PB(Machine, PassOpts->PTO, std::nullopt, &PIC)
This header defines various interfaces for pass management in LLVM.
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
This is the interface for a metadata-based scoped no-alias analysis.
This file contains the declaration of the SelectOptimizePass class, its corresponding pass name is se...
This file defines the SmallVector class.
Target-Independent Code Generator Pass Configuration Options pass.
This is the interface for a metadata-based TBAA.
static const char PassName[]
AddIRPass(ModulePassManager &MPM, const DerivedT &PB)
void operator()(PassT &&Pass, StringRef Name=PassT::name())
AddMachinePass(ModulePassManager &MPM, const DerivedT &PB)
void operator()(PassT &&Pass, bool Force=false, StringRef Name=PassT::name())
This class provides access to building LLVM's passes.
void addPreRewrite(AddMachinePass &) const
addPreRewrite - Add passes to the optimized register allocation pipeline after register allocation is...
void addPostRegAlloc(AddMachinePass &) const
This method may be implemented by targets that want to run passes after register allocation pass pipe...
void insertPass(InsertedPassT &&Pass)
Insert InsertedPass pass after TargetPass pass.
void addPreGlobalInstructionSelect(AddMachinePass &) const
This method may be implemented by targets that want to run passes immediately before the (global) ins...
Error addRegAssignmentFast(AddMachinePass &) const
Add core register alloator passes which do the actual register assignment and rewriting.
Error addFastRegAlloc(AddMachinePass &) const
addFastRegAlloc - Add the minimum set of target-independent passes that are required for fast registe...
Error addIRTranslator(AddMachinePass &) const
This method should install an IR translator pass, which converts from LLVM code to machine instructio...
void addILPOpts(AddMachinePass &) const
Add passes that optimize instruction level parallelism for out-of-order targets.
void addRegAllocPass(AddMachinePass &, bool Optimized) const
addMachinePasses helper to create the target-selected or overriden regalloc pass.
void addPreSched2(AddMachinePass &) const
This method may be implemented by targets that want to run passes after prolog-epilog insertion and b...
std::function< Expected< std::unique_ptr< MCStreamer > >(MCContext &)> CreateMCStreamer
Error addRegBankSelect(AddMachinePass &) const
This method should install a register bank selector pass, which assigns register banks to virtual reg...
decltype(std::declval< PassT & >().isRequired()) has_required_t
bool isGlobalISelAbortEnabled() const
Check whether or not GlobalISel should abort on error.
void addPreRegAlloc(AddMachinePass &) const
This method may be implemented by targets that want to run passes immediately before register allocat...
void addGCPasses(AddMachinePass &) const
addGCPasses - Add late codegen passes that analyze code for garbage collection.
Error buildPipeline(ModulePassManager &MPM, raw_pwrite_stream &Out, raw_pwrite_stream *DwoOut, CodeGenFileType FileType) const
void addGlobalMergePass(AddIRPass &) const
Target can override this to add GlobalMergePass before all IR passes.
Error addLegalizeMachineIR(AddMachinePass &) const
This method should install a legalize pass, which converts the instruction sequence into one that can...
Error addCoreISelPasses(AddMachinePass &) const
Add the actual instruction selection passes.
void addOptimizedRegAlloc(AddMachinePass &) const
addOptimizedRegAlloc - Add passes related to register allocation.
void addISelPasses(AddIRPass &) const
High level function that adds all passes necessary to go from llvm IR representation to the MI repres...
PassInstrumentationCallbacks * PIC
void addMachineSSAOptimization(AddMachinePass &) const
Methods with trivial inline returns are convenient points in the common codegen pass pipeline where t...
decltype(std::declval< PassT & >().run(std::declval< Module & >(), std::declval< ModuleAnalysisManager & >())) is_module_pass_t
CodeGenPassBuilder(TargetMachineT &TM, const CGPassBuilderOption &Opts, PassInstrumentationCallbacks *PIC)
Error addRegAssignmentOptimized(AddMachinePass &) const
void addCodeGenPrepare(AddIRPass &) const
Add pass to prepare the LLVM IR for code generation.
Error addMachinePasses(AddMachinePass &) const
Add the complete, standard set of LLVM CodeGen passes.
void addISelPrepare(AddIRPass &) const
Add common passes that perform LLVM IR to IR transforms in preparation for instruction selection.
void disablePass()
Allow the target to disable a specific pass by default.
void addBlockPlacement(AddMachinePass &) const
Add standard basic block placement passes.
Error addInstSelector(AddMachinePass &) const
addInstSelector - This method should install an instruction selector pass, which converts from LLVM c...
void addTargetRegisterAllocator(AddMachinePass &, bool Optimized) const
Utilities for targets to add passes to the pass manager.
void addPreEmitPass2(AddMachinePass &) const
Targets may add passes immediately before machine code is emitted in this callback.
void addPostRewrite(AddMachinePass &) const
Add passes to be run immediately after virtual registers are rewritten to physical registers.
void addPreRegBankSelect(AddMachinePass &) const
This method may be implemented by targets that want to run passes immediately before the register ban...
void addPreEmitPass(AddMachinePass &) const
This pass may be implemented by targets that want to run passes immediately before machine code is em...
Error addGlobalInstructionSelect(AddMachinePass &) const
This method should install a (global) instruction selector pass, which converts possibly generic inst...
void addMachineLateOptimization(AddMachinePass &) const
Add passes that optimize machine instructions after register allocation.
void addIRPasses(AddIRPass &) const
Add common target configurable passes that perform LLVM IR to IR transforms following machine indepen...
decltype(std::declval< PassT & >().run(std::declval< Function & >(), std::declval< FunctionAnalysisManager & >())) is_function_pass_t
decltype(std::declval< PassT & >().run(std::declval< MachineFunction & >(), std::declval< MachineFunctionAnalysisManager & >())) is_machine_function_pass_t
void addPreLegalizeMachineIR(AddMachinePass &) const
This method may be implemented by targets that want to run passes immediately before legalization.
CodeGenOptLevel getOptLevel() const
void addPassesToHandleExceptions(AddIRPass &) const
Add passes to lower exception handling for the code generator.
PassInstrumentationCallbacks * getPassInstrumentationCallbacks() const
bool reportDiagnosticWhenGlobalISelFallback() const
Check whether or not a diagnostic should be emitted when GlobalISel uses the fallback path.
void addPreISel(AddIRPass &) const
{{@ For GlobalISel
void addAsmPrinter(AddMachinePass &, CreateMCStreamer) const
Lightweight error class with error context and mandatory checking.
This is a fast-path instruction selection class that generates poor code and doesn't support illegal ...
LowerIntrinsics - This pass rewrites calls to the llvm.gcread or llvm.gcwrite intrinsics,...
Performs Loop Strength Reduce Pass.
This class is intended to be used as a base class for asm properties and features specific to the tar...
ExceptionHandling getExceptionHandlingType() const
Context object for machine code objects.
This class manages callbacks registration, as well as provides a way for PassInstrumentation to pass ...
StringRef getPassNameForClassName(StringRef ClassName)
Get the pass name for a given pass class name.
LLVM_ATTRIBUTE_MINSIZE std::enable_if_t<!std::is_same_v< PassT, PassManager > > addPass(PassT &&Pass)
bool isEmpty() const
Returns if the pass manager contains any passes.
Pass interface - Implemented by all 'passes'.
Pass (for the new pass manager) for printing a Function as LLVM's text IR assembly.
This is used to represent a portion of an LLVM function in a low-level Data Dependence DAG representa...
StringRef - Represent a constant reference to a string, i.e.
static Expected< StartStopInfo > getStartStopInfo(PassInstrumentationCallbacks &PIC)
Returns pass name in -stop-before or -stop-after NOTE: New pass manager migration only.
static bool willCompleteCodeGenPipeline()
Returns true if none of the -stop-before and -stop-after options is set.
An abstract base class for streams implementations that also support a pwrite operation.
unique_function is a type-erasing functor similar to std::function.
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
@ C
The default llvm calling convention, compatible with C.
This is an optimization pass for GlobalISel generic memory operations.
PassManager< Function > FunctionPassManager
Convenience typedef for a pass manager over functions.
ModuleToFunctionPassAdaptor createModuleToFunctionPassAdaptor(FunctionPassT &&Pass, bool EagerlyInvalidate=false)
A function to deduce a function pass type and wrap it in the templated adaptor.
std::error_code inconvertibleErrorCode()
The value returned by this function can be returned from convertToErrorCode for Error values where no...
PassManager< MachineFunction > MachineFunctionPassManager
Convenience typedef for a pass manager over functions.
typename detail::detector< void, Op, Args... >::value_t is_detected
Detects if a given trait holds for some set of arguments 'Args'.
CodeGenFileType
These enums are meant to be passed into addPassesToEmitFile to indicate what type of file to emit,...
FunctionToMachineFunctionPassAdaptor createFunctionToMachineFunctionPassAdaptor(MachineFunctionPassT &&Pass)
raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
CodeGenOptLevel
Code generation optimization level.
class LLVM_GSL_OWNER SmallVector
Forward declaration of SmallVector so that calculateSmallVectorDefaultInlinedElements can reference s...
std::enable_if_t< is_detected< HasRunOnLoopT, LoopPassT >::value, FunctionToLoopPassAdaptor > createFunctionToLoopPassAdaptor(LoopPassT &&Pass, bool UseMemorySSA=false, bool UseBlockFrequencyInfo=false, bool UseBranchProbabilityInfo=false)
A function to deduce a loop pass type and wrap it in the templated adaptor.
bool DisablePartialLibcallInlining
std::optional< bool > EnableGlobalISelOption
std::optional< bool > EnableIPRA
bool DisableConstantHoisting
std::optional< bool > OptimizeRegAlloc
RunOutliner EnableMachineOutliner
std::optional< bool > EnableFastISelOption
std::optional< GlobalISelAbortMode > EnableGlobalISelAbort
bool EnableImplicitNullChecks
bool EnableBlockPlacementStats
bool DisableSelectOptimize
A no-op pass template which simply forces a specific analysis result to be invalidated.
A utility pass template to force an analysis result to be available.