LLVM 24.0.0git
AMDGPUTargetMachine.cpp
Go to the documentation of this file.
1//===-- AMDGPUTargetMachine.cpp - TargetMachine for hw codegen targets-----===//
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/// \file
10/// This file contains both AMDGPU target machine and the CodeGen pass builder.
11/// The AMDGPU target machine contains all of the hardware specific information
12/// needed to emit code for SI+ GPUs in the legacy pass manager pipeline. The
13/// CodeGen pass builder handles the pass pipeline for new pass manager.
14//
15//===----------------------------------------------------------------------===//
16
17#include "AMDGPUTargetMachine.h"
18#include "AMDGPU.h"
19#include "AMDGPUAliasAnalysis.h"
20#include "AMDGPUAsmPrinter.h"
26#include "AMDGPUHazardLatency.h"
27#include "AMDGPUIGroupLP.h"
28#include "AMDGPUISelDAGToDAG.h"
30#include "AMDGPUMacroFusion.h"
38#include "AMDGPUSplitModule.h"
43#include "GCNDPPCombine.h"
45#include "GCNNSAReassign.h"
49#include "GCNSchedStrategy.h"
50#include "GCNVOPDUtils.h"
51#include "R600.h"
52#include "R600TargetMachine.h"
53#include "SIFixSGPRCopies.h"
54#include "SIFixVGPRCopies.h"
55#include "SIFoldOperands.h"
56#include "SIFormMemoryClauses.h"
58#include "SILowerControlFlow.h"
59#include "SILowerSGPRSpills.h"
60#include "SILowerWWMCopies.h"
62#include "SIMachineScheduler.h"
66#include "SIPeepholeSDWA.h"
67#include "SIPostRABundler.h"
70#include "SIWholeQuadMode.h"
93#include "llvm/CodeGen/Passes.h"
104#include "llvm/IR/IntrinsicsAMDGPU.h"
105#include "llvm/IR/Module.h"
106#include "llvm/IR/PassManager.h"
107#include "llvm/IR/PatternMatch.h"
117#include "llvm/Transforms/IPO.h"
142#include <optional>
143
144using namespace llvm;
145using namespace llvm::PatternMatch;
146
147namespace {
148//===----------------------------------------------------------------------===//
149// AMDGPU CodeGen Pass Builder interface.
150//===----------------------------------------------------------------------===//
151
152class AMDGPUCodeGenPassBuilder : public CodeGenPassBuilder {
153 using Base = CodeGenPassBuilder;
154
155 const AMDGPUOptions &CLOpts;
156
157 GCNTargetMachine &getTM() const {
158 return static_cast<GCNTargetMachine &>(TM);
159 }
160
161public:
162 AMDGPUCodeGenPassBuilder(GCNTargetMachine &TM,
163 const CGPassBuilderOption &Opts,
164 PassInstrumentationCallbacks *PIC);
165
166protected:
167 void addIRPasses(PassManagerWrapper &PMW) override;
168 void addCodeGenPrepare(PassManagerWrapper &PMW) override;
169 void addPreISel(PassManagerWrapper &PMW) override;
170 void addILPOpts(PassManagerWrapper &PMW) override;
171 void addAsmPrinterBegin(PassManagerWrapper &PMW) override;
172 void addAsmPrinter(PassManagerWrapper &PMW) override;
173 void addAsmPrinterEnd(PassManagerWrapper &PMW) override;
174 Error addInstSelector(PassManagerWrapper &PMW) override;
175 Error addIRTranslator(PassManagerWrapper &PMW) override;
176 void addPreLegalizeMachineIR(PassManagerWrapper &PMW) override;
177 Error addLegalizeMachineIR(PassManagerWrapper &PMW) override;
178 void addPreRegBankSelect(PassManagerWrapper &PMW) override;
179 Error addRegBankSelect(PassManagerWrapper &PMW) override;
180 void addPreGlobalInstructionSelect(PassManagerWrapper &PMW) override;
181 Error addGlobalInstructionSelect(PassManagerWrapper &PMW) override;
182 void addPreRewrite(PassManagerWrapper &PMW) override;
183 void addMachineSSAOptimization(PassManagerWrapper &PMW) override;
184 void addPostRegAlloc(PassManagerWrapper &PMW) override;
185 void addPreEmitPass(PassManagerWrapper &PMW) override;
186 Error addRegAssignAndRewriteFast(PassManagerWrapper &PMW) override;
187 Error addRegAssignAndRewriteOptimized(PassManagerWrapper &PMW) override;
188 void addPreRegAlloc(PassManagerWrapper &PMW) override;
189 Error addFastRegAlloc(PassManagerWrapper &PMW) override;
190 Error addOptimizedRegAlloc(PassManagerWrapper &PMW) override;
191 void addPreSched2(PassManagerWrapper &PMW) override;
192 void addPostBBSections(PassManagerWrapper &PMW) override;
193
194private:
195 Error validateRegAllocOptions() const;
196
197public:
198 /// Check if a pass is enabled given \p Opt option. The option always
199 /// overrides defaults if explicitly used. Otherwise the pass is enabled at an
200 /// optimization \p Level minimum.
201 bool isPassEnabled(BoolOrDefault Opt,
202 CodeGenOptLevel Level = CodeGenOptLevel::Default) const;
203 void addEarlyCSEOrGVNPass(PassManagerWrapper &PMW);
204 void addStraightLineScalarOptimizationPasses(PassManagerWrapper &PMW);
205};
206
207class SGPRRegisterRegAlloc : public RegisterRegAllocBase<SGPRRegisterRegAlloc> {
208public:
209 SGPRRegisterRegAlloc(const char *N, const char *D, FunctionPassCtor C)
210 : RegisterRegAllocBase(N, D, C) {}
211};
212
213class VGPRRegisterRegAlloc : public RegisterRegAllocBase<VGPRRegisterRegAlloc> {
214public:
215 VGPRRegisterRegAlloc(const char *N, const char *D, FunctionPassCtor C)
216 : RegisterRegAllocBase(N, D, C) {}
217};
218
219class WWMRegisterRegAlloc : public RegisterRegAllocBase<WWMRegisterRegAlloc> {
220public:
221 WWMRegisterRegAlloc(const char *N, const char *D, FunctionPassCtor C)
222 : RegisterRegAllocBase(N, D, C) {}
223};
224
225} // anonymous namespace
226
229 const Register Reg) {
230 const TargetRegisterClass *RC = MRI.getRegClass(Reg);
231 return static_cast<const SIRegisterInfo &>(TRI).isSGPRClass(RC);
232}
233
236 const Register Reg) {
237 const TargetRegisterClass *RC = MRI.getRegClass(Reg);
238 return !static_cast<const SIRegisterInfo &>(TRI).isSGPRClass(RC);
239}
240
243 const Register Reg) {
244 const SIMachineFunctionInfo *MFI =
245 MRI.getMF().getInfo<SIMachineFunctionInfo>();
246 const TargetRegisterClass *RC = MRI.getRegClass(Reg);
247 return !static_cast<const SIRegisterInfo &>(TRI).isSGPRClass(RC) &&
249}
250
251/// -{sgpr|wwm|vgpr}-regalloc=... command line option.
252static FunctionPass *useDefaultRegisterAllocator() { return nullptr; }
253
254/// A dummy default pass factory indicates whether the register allocator is
255/// overridden on the command line.
259
260static SGPRRegisterRegAlloc
262 "pick SGPR register allocator based on -O option",
264
265static cl::opt<SGPRRegisterRegAlloc::FunctionPassCtor, false,
268 cl::desc("Register allocator to use for SGPRs"));
269
270static cl::opt<VGPRRegisterRegAlloc::FunctionPassCtor, false,
273 cl::desc("Register allocator to use for VGPRs"));
274
275static cl::opt<WWMRegisterRegAlloc::FunctionPassCtor, false,
277 WWMRegAlloc("wwm-regalloc", cl::Hidden,
279 cl::desc("Register allocator to use for WWM registers"));
280
281// New pass manager register allocator options for AMDGPU
283 "sgpr-regalloc-npm", cl::Hidden, cl::init(RegAllocType::Default),
284 cl::desc("Register allocator for SGPRs (new pass manager)"));
285
287 "vgpr-regalloc-npm", cl::Hidden, cl::init(RegAllocType::Default),
288 cl::desc("Register allocator for VGPRs (new pass manager)"));
289
291 "wwm-regalloc-npm", cl::Hidden, cl::init(RegAllocType::Default),
292 cl::desc("Register allocator for WWM registers (new pass manager)"));
293
294/// Check if the given RegAllocType is supported for AMDGPU NPM register
295/// allocation. Only Fast and Greedy are supported; Basic and PBQP are not.
297 if (RAType == RegAllocType::Basic || RAType == RegAllocType::PBQP) {
299 Twine("unsupported register allocator '") +
300 (RAType == RegAllocType::Basic ? "basic" : "pbqp") + "' for " +
301 RegName + " registers",
303 }
304 return Error::success();
305}
306
307Error AMDGPUCodeGenPassBuilder::validateRegAllocOptions() const {
308 // 1. Generic --regalloc-npm is not supported for AMDGPU.
309 if (Opt.RegAlloc != RegAllocType::Unset) {
311 "-regalloc-npm not supported for amdgcn. Use -sgpr-regalloc-npm, "
312 "-vgpr-regalloc-npm, and -wwm-regalloc-npm",
314 }
315
316 // 2. Legacy PM regalloc options are not compatible with NPM.
317 if (SGPRRegAlloc.getNumOccurrences() > 0 ||
318 VGPRRegAlloc.getNumOccurrences() > 0 ||
319 WWMRegAlloc.getNumOccurrences() > 0) {
321 "-sgpr-regalloc, -vgpr-regalloc, and -wwm-regalloc are legacy PM "
322 "options. Use -sgpr-regalloc-npm, -vgpr-regalloc-npm, and "
323 "-wwm-regalloc-npm with the new pass manager",
325 }
326
327 // 3. Only Fast and Greedy allocators are supported for AMDGPU.
328 if (auto Err = checkRegAllocSupported(SGPRRegAllocNPM, "SGPR"))
329 return Err;
330 if (auto Err = checkRegAllocSupported(WWMRegAllocNPM, "WWM"))
331 return Err;
332 if (auto Err = checkRegAllocSupported(VGPRRegAllocNPM, "VGPR"))
333 return Err;
334
335 return Error::success();
336}
337
339 RegisterRegAlloc::FunctionPassCtor Ctor = SGPRRegisterRegAlloc::getDefault();
340
341 if (!Ctor) {
342 Ctor = SGPRRegAlloc;
343 SGPRRegisterRegAlloc::setDefault(SGPRRegAlloc);
344 }
345}
346
348 RegisterRegAlloc::FunctionPassCtor Ctor = VGPRRegisterRegAlloc::getDefault();
349
350 if (!Ctor) {
351 Ctor = VGPRRegAlloc;
352 VGPRRegisterRegAlloc::setDefault(VGPRRegAlloc);
353 }
354}
355
357 RegisterRegAlloc::FunctionPassCtor Ctor = WWMRegisterRegAlloc::getDefault();
358
359 if (!Ctor) {
360 Ctor = WWMRegAlloc;
361 WWMRegisterRegAlloc::setDefault(WWMRegAlloc);
362 }
363}
364
368
372
376
380
384
388
392
396
400
401static SGPRRegisterRegAlloc basicRegAllocSGPR(
402 "basic", "basic register allocator", createBasicSGPRRegisterAllocator);
403static SGPRRegisterRegAlloc greedyRegAllocSGPR(
404 "greedy", "greedy register allocator", createGreedySGPRRegisterAllocator);
405
406static SGPRRegisterRegAlloc fastRegAllocSGPR(
407 "fast", "fast register allocator", createFastSGPRRegisterAllocator);
408
409
410static VGPRRegisterRegAlloc basicRegAllocVGPR(
411 "basic", "basic register allocator", createBasicVGPRRegisterAllocator);
412static VGPRRegisterRegAlloc greedyRegAllocVGPR(
413 "greedy", "greedy register allocator", createGreedyVGPRRegisterAllocator);
414
415static VGPRRegisterRegAlloc fastRegAllocVGPR(
416 "fast", "fast register allocator", createFastVGPRRegisterAllocator);
417static WWMRegisterRegAlloc basicRegAllocWWMReg("basic",
418 "basic register allocator",
420static WWMRegisterRegAlloc
421 greedyRegAllocWWMReg("greedy", "greedy register allocator",
423static WWMRegisterRegAlloc fastRegAllocWWMReg("fast", "fast register allocator",
425
430
432 "amdgpu-enable-object-linking",
433 cl::desc("Enable object linking for cross-TU LDS and ABI support"),
435 cl::Hidden);
436
438 "amdgpu-enable-lower-module-lds", cl::desc("Enable lower module lds pass"),
440 cl::Hidden);
441
442// Scheduler selection is consulted both when creating the scheduler and from
443// overrideSchedPolicy(), so keep the attribute and global command line handling
444// in one helper.
445StringRef llvm::AMDGPU::getSchedStrategy(const AMDGPUOptions &CLOpts,
446 const Function &F) {
447 Attribute SchedStrategyAttr = F.getFnAttribute("amdgpu-sched-strategy");
448 if (SchedStrategyAttr.isValid())
449 return SchedStrategyAttr.getValueAsString();
450
451 return CLOpts.sched_strategy;
452}
453
454static void
456 const GCNSubtarget &ST) {
457 if (ST.hasGFX1250Insts() || ST.hasGFX940Insts())
458 return;
459
460 F.getContext().diagnose(
462 "'amdgpu-sched-strategy'='coexec' is only "
463 "supported for gfx1250/gfx950/gfx942",
465}
466
467static bool useNoopPostScheduler(const AMDGPUOptions &CLOpts,
468 const Function &F) {
469 Attribute PostSchedStrategyAttr =
470 F.getFnAttribute("amdgpu-post-sched-strategy");
471 if (PostSchedStrategyAttr.isValid())
472 return PostSchedStrategyAttr.getValueAsString() == "nop";
473 return AMDGPU::getSchedStrategy(CLOpts, F) == "coexec";
474}
475
477 // Register the target
482
570}
571
572static std::unique_ptr<TargetLoweringObjectFile> createTLOF(const Triple &TT) {
573 return std::make_unique<AMDGPUTargetObjectFile>();
574}
575
579
580static ScheduleDAGInstrs *
582 const GCNSubtarget &ST = C->MF->getSubtarget<GCNSubtarget>();
583 ScheduleDAGMILive *DAG =
584 new GCNScheduleDAGMILive(C, std::make_unique<GCNMaxOccupancySchedStrategy>(C));
585 DAG->addMutation(createLoadClusterDAGMutation(DAG->TII));
586 if (ST.shouldClusterStores())
587 DAG->addMutation(createStoreClusterDAGMutation(DAG->TII));
589 DAG->addMutation(createAMDGPUMacroFusionDAGMutation());
590 DAG->addMutation(createAMDGPUExportClusteringDAGMutation());
591 DAG->addMutation(createAMDGPUBarrierLatencyDAGMutation(C->MF));
592 DAG->addMutation(createAMDGPUHazardLatencyDAGMutation(C->MF));
593 return DAG;
594}
595
596static ScheduleDAGInstrs *
598 ScheduleDAGMILive *DAG =
599 new GCNScheduleDAGMILive(C, std::make_unique<GCNMaxILPSchedStrategy>(C));
601 return DAG;
602}
603
604static ScheduleDAGInstrs *
606 const GCNSubtarget &ST = C->MF->getSubtarget<GCNSubtarget>();
608 C, std::make_unique<GCNMaxMemoryClauseSchedStrategy>(C));
609 DAG->addMutation(createLoadClusterDAGMutation(DAG->TII));
610 if (ST.shouldClusterStores())
611 DAG->addMutation(createStoreClusterDAGMutation(DAG->TII));
612 DAG->addMutation(createAMDGPUExportClusteringDAGMutation());
613 DAG->addMutation(createAMDGPUBarrierLatencyDAGMutation(C->MF));
614 DAG->addMutation(createAMDGPUHazardLatencyDAGMutation(C->MF));
615 return DAG;
616}
617
618static ScheduleDAGInstrs *
620 const GCNSubtarget &ST = C->MF->getSubtarget<GCNSubtarget>();
621 auto *DAG = new GCNIterativeScheduler(
623 DAG->addMutation(createLoadClusterDAGMutation(DAG->TII));
624 if (ST.shouldClusterStores())
625 DAG->addMutation(createStoreClusterDAGMutation(DAG->TII));
627 return DAG;
628}
629
636
637static ScheduleDAGInstrs *
639 const GCNSubtarget &ST = C->MF->getSubtarget<GCNSubtarget>();
641 DAG->addMutation(createLoadClusterDAGMutation(DAG->TII));
642 if (ST.shouldClusterStores())
643 DAG->addMutation(createStoreClusterDAGMutation(DAG->TII));
644 DAG->addMutation(createAMDGPUMacroFusionDAGMutation());
646 return DAG;
647}
648
649static MachineSchedRegistry
650SISchedRegistry("si", "Run SI's custom scheduler",
652
655 "Run GCN scheduler to maximize occupancy",
657
659 GCNMaxILPSchedRegistry("gcn-max-ilp", "Run GCN scheduler to maximize ilp",
661
663 "gcn-max-memory-clause", "Run GCN scheduler to maximize memory clause",
665
667 "gcn-iterative-max-occupancy-experimental",
668 "Run GCN scheduler to maximize occupancy (experimental)",
670
672 "gcn-iterative-minreg",
673 "Run GCN iterative scheduler for minimal register usage (experimental)",
675
677 "gcn-iterative-ilp",
678 "Run GCN iterative scheduler for ILP scheduling (experimental)",
680
683 if (!GPU.empty())
684 return GPU;
685
686 if (StringRef Name = AMDGPU::getArchNameFromSubArch(TT.getSubArch());
687 !Name.empty())
688 return Name;
689
690 // Need to default to a target with flat support for HSA.
691 if (TT.isAMDGCN())
692 return TT.getOS() == Triple::AMDHSA ? "generic-hsa" : "generic";
693
694 return "r600";
695}
696
698 // The AMDGPU toolchain only supports generating shared objects, so we
699 // must always use PIC.
700 return Reloc::PIC_;
701}
702
704 StringRef CPU, StringRef FS,
705 const TargetOptions &Options,
706 std::optional<Reloc::Model> RM,
707 std::optional<CodeModel::Model> CM,
712 OptLevel),
713 CLOpts(cl::LibraryOptionsContext::get<AMDGPUOptions>(
714 Options.MCOptions.LibraryOptions)),
716 initAsmInfo();
717 if (TT.isAMDGCN()) {
718 // Triple is missing a representation for non-empty, but unrecognized
719 // subarches. Only permit no subarch for any subtarget if it was really
720 // empty.
721 bool IsUnknownSubArch =
722 TT.getSubArch() == Triple::NoSubArch && TT.getArchName().size() != 6;
723 if (IsUnknownSubArch)
724 reportFatalUsageError("unknown subarch " + TT.getArchName());
725
726 if (TT.getSubArch() != Triple::NoSubArch) {
728 Triple::SubArchType GPUSubArch = AMDGPU::getSubArch(Kind);
729 if (Kind != AMDGPU::GK_NONE && GPUSubArch != TT.getSubArch() &&
730 TT.getSubArch() != AMDGPU::getMajorSubArch(GPUSubArch)) {
731 reportFatalUsageError("invalid cpu '" + CPU + "' for subarch " +
732 TT.getArchName());
733 }
734 }
735
736 if (getMCSubtargetInfo().checkFeatures("+wavefrontsize64"))
738 else if (getMCSubtargetInfo().checkFeatures("+wavefrontsize32"))
740 }
742}
743
747
749
752 const GCNSubtarget &ST = C->MF->getSubtarget<GCNSubtarget>();
754 DAG->addMutation(createLoadClusterDAGMutation(DAG->TII));
755 if (ST.shouldClusterStores())
756 DAG->addMutation(createStoreClusterDAGMutation(DAG->TII));
757 return DAG;
758}
759
760/// Predicate for Internalize pass.
761static bool mustPreserveGV(const GlobalValue &GV) {
762 if (const Function *F = dyn_cast<Function>(&GV))
763 return F->isDeclaration() || F->getName().starts_with("__asan_") ||
764 F->getName().starts_with("__sanitizer_") ||
765 AMDGPU::isEntryFunctionCC(F->getCallingConv());
766
768 return !GV.use_empty();
769}
770
775
778 if (Params.empty())
780 Params.consume_front("strategy=");
782 .Case("dpp", AMDGPU::ScanOptions::DPP)
783 .Cases({"iterative", ""}, AMDGPU::ScanOptions::Iterative)
784 .Case("none", AMDGPU::ScanOptions::None)
785 .Default(std::nullopt);
786 if (Result)
787 return *Result;
788 return make_error<StringError>("invalid parameter", inconvertibleErrorCode());
789}
790
794 while (!Params.empty()) {
795 StringRef ParamName;
796 std::tie(ParamName, Params) = Params.split(';');
797 if (ParamName == "closed-world") {
798 Result.IsClosedWorld = true;
799 } else {
801 formatv("invalid AMDGPUAttributor pass parameter '{0}' ", ParamName)
802 .str(),
804 }
805 }
806 return Result;
807}
808
810
811#define GET_PASS_REGISTRY "AMDGPUPassRegistry.def"
813
814 PB.registerPipelineParsingCallback(
815 [this](StringRef Name, CGSCCPassManager &PM,
817 if (Name == "amdgpu-attributor-cgscc" && getTargetTriple().isAMDGCN()) {
819 *static_cast<GCNTargetMachine *>(this)));
820 return true;
821 }
822 return false;
823 });
824
825 PB.registerScalarOptimizerLateEPCallback(
826 [](FunctionPassManager &FPM, OptimizationLevel Level) {
827 if (Level == OptimizationLevel::O0)
828 return;
829
831 });
832
833 PB.registerVectorizerEndEPCallback(
834 [](FunctionPassManager &FPM, OptimizationLevel Level) {
835 if (Level == OptimizationLevel::O0)
836 return;
837
839 });
840
841 PB.registerPipelineEarlySimplificationEPCallback(
842 [this](ModulePassManager &PM, OptimizationLevel Level,
844 if (!isLTOPreLink(Phase) && getTargetTriple().isAMDGCN()) {
845 // When we are not using -fgpu-rdc, we can run accelerator code
846 // selection relatively early, but still after linking to prevent
847 // eager removal of potentially reachable symbols.
848 if (CLOpts.enable_hipstdpar) {
851 }
852
854 }
855
856 if (Level == OptimizationLevel::O0)
857 return;
858
859 // We don't want to run internalization at per-module stage.
860 if (CLOpts.internalize_symbols && !isLTOPreLink(Phase)) {
863 }
864
865 if (CLOpts.early_inline_all && !EnableFunctionCalls)
867 });
868
869 PB.registerPeepholeEPCallback(
870 [this](FunctionPassManager &FPM, OptimizationLevel Level) {
871 if (Level == OptimizationLevel::O0)
872 return;
873
875 if (CLOpts.simplify_libcall)
877
878 if (CLOpts.enable_uniform_intrinsic_combine)
880 });
881
882 PB.registerCGSCCOptimizerLateEPCallback(
883 [this](CGSCCPassManager &PM, OptimizationLevel Level) {
884 if (Level == OptimizationLevel::O0)
885 return;
886
888
889 // Add promote kernel arguments pass to the opt pipeline right before
890 // infer address spaces which is needed to do actual address space
891 // rewriting.
892 if (Level > OptimizationLevel::O1 &&
893 CLOpts.enable_promote_kernel_arguments)
895
896 // Add infer address spaces pass to the opt pipeline after inlining
897 // but before SROA to increase SROA opportunities.
899
900 // This should run after inlining to have any chance of doing
901 // anything, and before other cleanup optimizations.
903
904 // Promote alloca to vector before SROA and loop unroll. If we
905 // manage to eliminate allocas before unroll we may choose to unroll
906 // less.
908
909 PM.addPass(createCGSCCToFunctionPassAdaptor(std::move(FPM)));
910 });
911
912 // FIXME: Why is AMDGPUAttributor not in CGSCC?
913 PB.registerOptimizerLastEPCallback([this](ModulePassManager &MPM,
914 OptimizationLevel Level,
916 if (Level != OptimizationLevel::O0) {
917 if (!isLTOPreLink(Phase)) {
918 if (CLOpts.attributor_enable && getTargetTriple().isAMDGCN()) {
920 MPM.addPass(AMDGPUAttributorPass(*this, Opts, Phase));
921 }
922 }
923 }
924 });
925
926 PB.registerFullLinkTimeOptimizationLastEPCallback(
927 [this](ModulePassManager &PM, OptimizationLevel Level) {
928 // Clean up redundant memory round-trips that the full-LTO pipeline,
929 // unlike the non-LTO/ThinLTO ones, otherwise leaves for codegen.
930 if (Level != OptimizationLevel::O0) {
932 EarlyCSEPass(/*UseMemorySSA=*/true)));
933 }
934
935 // When we are using -fgpu-rdc, we can only run accelerator code
936 // selection after linking to prevent, otherwise we end up removing
937 // potentially reachable symbols that were exported as external in other
938 // modules.
939 if (CLOpts.enable_hipstdpar) {
942 }
943 // We want to support the -lto-partitions=N option as "best effort".
944 // For that, we need to lower LDS earlier in the pipeline before the
945 // module is partitioned for codegen.
946 if (CLOpts.enable_lower_exec_sync)
948 if (CLOpts.enable_sw_lower_lds)
952 if (Level != OptimizationLevel::O0) {
953 // We only want to run this with O2 or higher since inliner and SROA
954 // don't run in O1.
955 if (Level != OptimizationLevel::O1) {
956 PM.addPass(
958 }
959 // Do we really need internalization in LTO?
960 if (CLOpts.internalize_symbols) {
963 }
964 if (CLOpts.attributor_enable && getTargetTriple().isAMDGCN()) {
966 if (CLOpts.link_time_closed_world)
967 Opt.IsClosedWorld = true;
970 }
971 }
972 if (!NoKernelInfoEndLTO) {
974 FPM.addPass(KernelInfoPrinter(this));
975 PM.addPass(createModuleToFunctionPassAdaptor(std::move(FPM)));
976 }
977 });
978
979 PB.registerRegClassFilterParsingCallback(
980 [](StringRef FilterName) -> RegAllocFilterFunc {
981 if (FilterName == "sgpr")
982 return onlyAllocateSGPRs;
983 if (FilterName == "vgpr")
984 return onlyAllocateVGPRs;
985 if (FilterName == "wwm")
986 return onlyAllocateWWMRegs;
987 return nullptr;
988 });
989}
990
992 unsigned SrcAS,
993 unsigned DestAS) const {
994 return AMDGPU::isFlatGlobalAddrSpace(SrcAS) &&
996}
997
999 if (auto *Arg = dyn_cast<Argument>(V);
1000 Arg &&
1001 AMDGPU::isModuleEntryFunctionCC(Arg->getParent()->getCallingConv()) &&
1002 !Arg->hasByRefAttr())
1004
1005 const auto *LD = dyn_cast<LoadInst>(V);
1006 if (!LD) // TODO: Handle invariant load like constant.
1008
1009 // It must be a generic pointer loaded.
1010 assert(V->getType()->getPointerAddressSpace() == AMDGPUAS::FLAT_ADDRESS);
1011
1012 const auto *Ptr = LD->getPointerOperand();
1013 if (Ptr->getType()->getPointerAddressSpace() != AMDGPUAS::CONSTANT_ADDRESS)
1015 // For a generic pointer loaded from the constant memory, it could be assumed
1016 // as a global pointer since the constant memory is only populated on the
1017 // host side. As implied by the offload programming model, only global
1018 // pointers could be referenced on the host side.
1020}
1021
1022std::pair<const Value *, unsigned>
1024 if (auto *II = dyn_cast<IntrinsicInst>(V)) {
1025 switch (II->getIntrinsicID()) {
1026 case Intrinsic::amdgcn_is_shared:
1027 return std::pair(II->getArgOperand(0), AMDGPUAS::LOCAL_ADDRESS);
1028 case Intrinsic::amdgcn_is_private:
1029 return std::pair(II->getArgOperand(0), AMDGPUAS::PRIVATE_ADDRESS);
1030 default:
1031 break;
1032 }
1033 return std::pair(nullptr, -1);
1034 }
1035 // Check the global pointer predication based on
1036 // (!is_share(p) && !is_private(p)). Note that logic 'and' is commutative and
1037 // the order of 'is_shared' and 'is_private' is not significant.
1038 Value *Ptr;
1039 if (match(
1040 const_cast<Value *>(V),
1043 m_Deferred(Ptr))))))
1044 return std::pair(Ptr, AMDGPUAS::GLOBAL_ADDRESS);
1045
1046 return std::pair(nullptr, -1);
1047}
1048
1049unsigned
1064
1066 Module &M, unsigned NumParts,
1067 function_ref<void(std::unique_ptr<Module> MPart)> ModuleCallback) {
1068 // FIXME(?): Would be better to use an already existing Analysis/PassManager,
1069 // but all current users of this API don't have one ready and would need to
1070 // create one anyway. Let's hide the boilerplate for now to keep it simple.
1071
1076
1077 PassBuilder PB(M.getContext(), this);
1078 PB.registerModuleAnalyses(MAM);
1079 PB.registerFunctionAnalyses(FAM);
1080 PB.crossRegisterProxies(LAM, FAM, CGAM, MAM);
1081
1083 MPM.addPass(AMDGPUSplitModulePass(NumParts, ModuleCallback));
1084 MPM.run(M, MAM);
1085 return true;
1086}
1087
1088//===----------------------------------------------------------------------===//
1089// GCN Target Machine (SI+)
1090//===----------------------------------------------------------------------===//
1091
1093 StringRef CPU, StringRef FS,
1094 const TargetOptions &Options,
1095 std::optional<Reloc::Model> RM,
1096 std::optional<CodeModel::Model> CM,
1097 CodeGenOptLevel OL, bool JIT)
1098 : AMDGPUTargetMachine(T, TT, CPU, FS, Options, RM, CM, OL) {
1100 // addFastRegAlloc inserts SIWholeQuadMode after TwoAddressInstructionPass.
1102}
1103
1104enum class OOBFlagValue {
1105 Any = 0,
1108};
1109
1110/// Returns the OOB mode encoded by a module flag.
1111/// An absent flag defaults to Any.
1112static OOBFlagValue getOOBFlagValue(const Module &M, StringRef FlagName) {
1113 const auto *Flag =
1114 mdconst::dyn_extract_or_null<ConstantInt>(M.getModuleFlag(FlagName));
1115 if (!Flag)
1116 return OOBFlagValue::Any;
1117 return static_cast<OOBFlagValue>(Flag->getZExtValue());
1118}
1119
1120/// Returns the xnack/sramecc setting encoded by a module flag.
1121/// Module flag values: 0 = disabled, 1 = enabled.
1122/// An absent flag defaults to Any.
1125 StringRef FlagName) const {
1127
1128 if (CLOpts.xnack != BoolOrDefault::Default && FlagName == "amdgpu.xnack")
1129 return CLOpts.xnack == BoolOrDefault::True ? TargetIDSetting::On
1130 : TargetIDSetting::Off;
1131 if (CLOpts.sramecc != BoolOrDefault::Default && FlagName == "amdgpu.sramecc")
1132 return CLOpts.sramecc == BoolOrDefault::True ? TargetIDSetting::On
1133 : TargetIDSetting::Off;
1134
1135 const auto *Flag =
1136 mdconst::dyn_extract_or_null<ConstantInt>(M.getModuleFlag(FlagName));
1137 if (!Flag)
1138 return TargetIDSetting::Any;
1139 return Flag->getZExtValue() == 0 ? TargetIDSetting::Off : TargetIDSetting::On;
1140}
1141
1142const TargetSubtargetInfo *
1144 AttributeSet FnAttrs = F.getAttributes().getFnAttrs();
1145 const Module *M = F.getParent();
1146 if (const GCNSubtarget *ST = LastSubtarget.lookup(FnAttrs, M))
1147 return ST;
1148
1149 SubtargetAttrs Attrs;
1150 Attrs.GPU = FnAttrs.getAttribute("target-cpu");
1151 Attrs.FS = FnAttrs.getAttribute("target-features");
1152 Attrs.BufRelaxed =
1154 Attrs.TBufRelaxed =
1156 Attrs.Xnack = getTargetIDSettingFromModuleFlag(*M, "amdgpu.xnack");
1157 Attrs.SramEcc = getTargetIDSettingFromModuleFlag(*M, "amdgpu.sramecc");
1158
1159 if (const GCNSubtarget *ST = LastSubtarget.lookup(FnAttrs, M, Attrs))
1160 return ST;
1161
1162 StringRef GPU =
1163 Attrs.GPU.isValid() ? Attrs.GPU.getValueAsString() : getTargetCPU();
1164 StringRef FS = Attrs.FS.isValid() ? Attrs.FS.getValueAsString()
1166
1168 SmallString<128> SubtargetKey(GPU);
1169 SubtargetKey.append(FS);
1170 if (Attrs.BufRelaxed)
1171 SubtargetKey.append(",buf-oob=1");
1172 if (Attrs.TBufRelaxed)
1173 SubtargetKey.append(",tbuf-oob=1");
1174 if (Attrs.Xnack != TargetIDSetting::Any) {
1175 SubtargetKey.append(",xnack=");
1176 SubtargetKey.push_back(Attrs.Xnack == TargetIDSetting::On ? '1' : '0');
1177 }
1178 if (Attrs.SramEcc != TargetIDSetting::Any) {
1179 SubtargetKey.append(",sramecc=");
1180 SubtargetKey.push_back(Attrs.SramEcc == TargetIDSetting::On ? '1' : '0');
1181 }
1182
1183 auto &I = SubtargetMap[SubtargetKey];
1184 if (!I) {
1186 Triple::SubArchType GPUSubArch = AMDGPU::getSubArch(Kind);
1187
1188 // Enforce the subtarget is covered by the subarch. Tolerate no subarch for
1189 // legacy compatibility.
1190 const Triple &TT = M->getTargetTriple();
1191 if (GPUSubArch != TT.getSubArch() && Kind != AMDGPU::GK_NONE) {
1192 // Check if this is a generic subarch which has subtargets. Ignore
1193 // unknown subtargets with a known subarch, since for whatever reason
1194 // the convention is to just print a warning and ignore unrecognized
1195 // subtargets.
1196 bool IsLegacyEmptySubArch = TT.getSubArch() == Triple::NoSubArch;
1197 if (!IsLegacyEmptySubArch &&
1198 AMDGPU::getMajorSubArch(GPUSubArch) != TT.getSubArch()) {
1199 F.getContext().emitError("invalid subtarget '" + Twine(GPU) +
1200 "' for subarch " + TT.getArchName());
1201 }
1202 }
1203
1204 I = std::make_unique<GCNSubtarget>(TargetTriple, GPU, FS, *this,
1205 Attrs.BufRelaxed, Attrs.TBufRelaxed,
1206 Attrs.Xnack, Attrs.SramEcc);
1207 }
1208
1209 LastSubtarget.set(FnAttrs, M, Attrs, I.get());
1210 return I.get();
1211}
1212
1215 return TargetTransformInfo(std::make_unique<GCNTTIImpl>(this, F));
1216}
1217
1220 raw_pwrite_stream *DwoOut, CodeGenFileType FileType,
1221 const CGPassBuilderOption &Opts, MCContext &Ctx,
1223 AMDGPUCodeGenPassBuilder CGPB(*this, Opts, PIC);
1224 return CGPB.buildPipeline(MPM, MAM, Out, DwoOut, FileType, Ctx);
1225}
1226
1229 const GCNSubtarget &ST = C->MF->getSubtarget<GCNSubtarget>();
1230 if (ST.enableSIScheduler())
1232
1233 StringRef SchedStrategy =
1234 AMDGPU::getSchedStrategy(CLOpts, C->MF->getFunction());
1235
1236 if (SchedStrategy == "max-ilp")
1238
1239 if (SchedStrategy == "max-memory-clause")
1241
1242 if (SchedStrategy == "iterative-ilp")
1244
1245 if (SchedStrategy == "iterative-minreg")
1246 return createMinRegScheduler(C);
1247
1248 if (SchedStrategy == "iterative-maxocc")
1250
1251 if (SchedStrategy == "coexec") {
1252 diagnoseUnsupportedCoExecSchedulerSelection(C->MF->getFunction(), ST);
1254 }
1255
1257}
1258
1261 if (useNoopPostScheduler(CLOpts, C->MF->getFunction()))
1263
1264 ScheduleDAGMI *DAG =
1265 new GCNPostScheduleDAGMILive(C, std::make_unique<PostGenericScheduler>(C),
1266 /*RemoveKillFlags=*/true);
1267 const GCNSubtarget &ST = C->MF->getSubtarget<GCNSubtarget>();
1269 if (ST.shouldClusterStores())
1272 if (valueOr(CLOpts.enable_vopd, getOptLevel() >= CodeGenOptLevel::Less))
1277 return DAG;
1278}
1279//===----------------------------------------------------------------------===//
1280// AMDGPU Legacy Pass Setup
1281//===----------------------------------------------------------------------===//
1282
1283std::unique_ptr<CSEConfigBase> llvm::AMDGPUPassConfig::getCSEConfig() const {
1284 return getStandardCSEConfigForOpt(TM->getOptLevel());
1285}
1286
1287namespace {
1288
1289class GCNPassConfig final : public AMDGPUPassConfig {
1290public:
1291 GCNPassConfig(TargetMachine &TM, PassManagerBase &PM)
1292 : AMDGPUPassConfig(TM, PM) {
1293 substitutePass(&PostRASchedulerID, &PostMachineSchedulerID);
1294 }
1295
1296 bool addPreISel() override;
1297 void addMachineSSAOptimization() override;
1298 bool addILPOpts() override;
1299 bool addInstSelector() override;
1300 bool addIRTranslator() override;
1301 void addPreLegalizeMachineIR() override;
1302 bool addLegalizeMachineIR() override;
1303 void addPreRegBankSelect() override;
1304 bool addRegBankSelect() override;
1305 void addPreGlobalInstructionSelect() override;
1306 bool addGlobalInstructionSelect() override;
1307 void addPreRegAlloc() override;
1308 void addFastRegAlloc() override;
1309 void addOptimizedRegAlloc() override;
1310
1311 FunctionPass *createSGPRAllocPass(bool Optimized);
1312 FunctionPass *createVGPRAllocPass(bool Optimized);
1313 FunctionPass *createWWMRegAllocPass(bool Optimized);
1314 FunctionPass *createRegAllocPass(bool Optimized) override;
1315
1316 void addRegAssignAndRewriteFast() override;
1317 void addRegAssignAndRewriteOptimized() override;
1318
1319 bool addPreRewrite() override;
1320 void addPostRegAlloc() override;
1321 void addPreSched2() override;
1322 void addPreEmitPass() override;
1323 void addPostBBSections() override;
1324};
1325
1326} // end anonymous namespace
1327
1329 : TargetPassConfig(TM, PM), CLOpts(getAMDGPUTargetMachine().getCLOpts()) {
1330 // Exceptions and StackMaps are not supported, so these passes will never do
1331 // anything.
1334 // Garbage collection is not supported.
1337
1338 if (CLOpts.use_ssa_machine_scheduler) {
1339 // Use SSA Machine Scheduler instead of regular Machine Scheduler.
1342 }
1343}
1344
1351
1353 if (CLOpts.loop_prefetch)
1356 // ReassociateGEPs exposes more opportunities for SLSR. See
1357 // the example in reassociate-geps-and-slsr.ll.
1359 // SeparateConstOffsetFromGEP and SLSR creates common expressions which GVN or
1360 // EarlyCSE can reuse.
1362 // Run NaryReassociate after EarlyCSE/GVN to be more effective.
1364 // NaryReassociate on GEPs creates redundant common expressions, so run
1365 // EarlyCSE after it.
1367}
1368
1371
1372 if (CLOpts.enable_remove_incompatible_functions &&
1373 TM.getTargetTriple().isAMDGCN())
1375
1376 // There is no reason to run these.
1380
1381 if (TM.getTargetTriple().isAMDGCN())
1383
1384 if (CLOpts.lower_global_ctor_dtor)
1386
1387 if (TM.getTargetTriple().isAMDGCN() &&
1388 isPassEnabled(CLOpts.enable_image_intrinsic_optimizer))
1390
1391 if (CLOpts.enable_uniform_intrinsic_combine)
1393
1394 // This can be disabled by passing ::Disable here or on the command line
1395 // with --expand-variadics-override=disable.
1397
1398 // Function calls are not supported, so make sure we inline everything.
1401
1402 // Handle uses of OpenCL image2d_t, image3d_t and sampler_t arguments.
1403 if (TM.getTargetTriple().getArch() == Triple::r600)
1405
1406 // Make enqueued block runtime handles externally visible.
1408
1409 // Lower special LDS accesses.
1410 if (CLOpts.enable_lower_exec_sync)
1412
1413 // Lower LDS accesses to global memory pass if address sanitizer is enabled.
1414 if (CLOpts.enable_sw_lower_lds)
1416
1417 // Runs before PromoteAlloca so the latter can account for function uses
1420 }
1421
1422 // Run atomic optimizer before Atomic Expand
1423 if ((TM.getTargetTriple().isAMDGCN()) &&
1424 (TM.getOptLevel() >= CodeGenOptLevel::Less) &&
1425 (CLOpts.atomic_optimizer_strategy != AMDGPU::ScanOptions::None)) {
1426 addPass(createAMDGPUAtomicOptimizerPass(CLOpts.atomic_optimizer_strategy));
1427 }
1428
1430
1431 if (TM.getOptLevel() > CodeGenOptLevel::None) {
1433
1434 if (isPassEnabled(CLOpts.scalar_ir_passes))
1436
1437 if (CLOpts.enable_aa) {
1440 AAResults &AAR) {
1441 if (auto *WrapperPass = P.getAnalysisIfAvailable<AMDGPUAAWrapperPass>())
1442 AAR.addAAResult(WrapperPass->getResult());
1443 }));
1444 }
1445
1446 if (TM.getTargetTriple().isAMDGCN()) {
1447 // TODO: May want to move later or split into an early and late one.
1448 addPass(
1449 createAMDGPUCodeGenPreparePass(CLOpts.codegenprepare_expand_div64));
1450 }
1451
1452 // Try to hoist loop invariant parts of divisions AMDGPUCodeGenPrepare may
1453 // have expanded.
1454 if (TM.getOptLevel() > CodeGenOptLevel::Less)
1456 }
1457
1459
1460 // EarlyCSE is not always strong enough to clean up what LSR produces. For
1461 // example, GVN can combine
1462 //
1463 // %0 = add %a, %b
1464 // %1 = add %b, %a
1465 //
1466 // and
1467 //
1468 // %0 = shl nsw %a, 2
1469 // %1 = shl %a, 2
1470 //
1471 // but EarlyCSE can do neither of them.
1472 if (isPassEnabled(CLOpts.scalar_ir_passes))
1474}
1475
1477 if (TM->getTargetTriple().isAMDGCN() &&
1478 TM->getOptLevel() > CodeGenOptLevel::None)
1480
1481 if (TM->getTargetTriple().isAMDGCN() && CLOpts.ir_lower_kernel_arguments)
1483
1485
1486 if (isPassEnabled(CLOpts.load_store_vectorizer))
1488
1489 if (TM->getTargetTriple().isAMDGCN()) {
1490 // This lowering has been placed after codegenprepare to take advantage of
1491 // address mode matching (which is why it isn't put with the LDS lowerings).
1492 // It could be placed anywhere before uniformity annotations (an analysis
1493 // that it changes by splitting up fat pointers into their components)
1494 // but has been put before switch lowering and CFG flattening so that those
1495 // passes can run on the more optimized control flow this pass creates in
1496 // many cases.
1499 }
1500
1501 // LowerSwitch pass may introduce unreachable blocks that can
1502 // cause unexpected behavior for subsequent passes. Placing it
1503 // here seems better that these blocks would get cleaned up by
1504 // UnreachableBlockElim inserted next in the pass flow.
1506}
1507
1509 if (TM->getOptLevel() > CodeGenOptLevel::None)
1511 return false;
1512}
1513
1518
1520 // Do nothing. GC is not supported.
1521 return false;
1522}
1523
1524//===----------------------------------------------------------------------===//
1525// GCN Legacy Pass Setup
1526//===----------------------------------------------------------------------===//
1527
1528bool GCNPassConfig::addPreISel() {
1530
1531 if (TM->getOptLevel() > CodeGenOptLevel::None) {
1532 addPass(createSinkingPass());
1534 }
1535
1536 // Merge divergent exit nodes. StructurizeCFG won't recognize the multi-exit
1537 // regions formed by them.
1539 addPass(createFixIrreduciblePass());
1540 addPass(createUnifyLoopExitsPass());
1541 addPass(createStructurizeCFGPass(/*SkipUniformRegions=*/true));
1542
1545 // TODO: Move this right after structurizeCFG to avoid extra divergence
1546 // analysis. This depends on stopping SIAnnotateControlFlow from making
1547 // control flow modifications.
1549
1550 // SDAG requires LCSSA, GlobalISel does not. Disable LCSSA for -global-isel
1551 // without any of the fallback options.
1554 !isGlobalISelAbortEnabled())
1555 addPass(createLCSSAPass());
1556
1557 if (TM->getOptLevel() > CodeGenOptLevel::Less)
1559
1560 return false;
1561}
1562
1563void GCNPassConfig::addMachineSSAOptimization() {
1565
1566 // We want to fold operands after PeepholeOptimizer has run (or as part of
1567 // it), because it will eliminate extra copies making it easier to fold the
1568 // real source operand. We want to eliminate dead instructions after, so that
1569 // we see fewer uses of the copies. We then need to clean up the dead
1570 // instructions leftover after the operands are folded as well.
1571 //
1572 // XXX - Can we get away without running DeadMachineInstructionElim again?
1573 addPass(&SIFoldOperandsLegacyID);
1574 if (CLOpts.dpp_combine)
1575 addPass(&GCNDPPCombineLegacyID);
1577 if (isPassEnabled(CLOpts.sdwa_peephole)) {
1578 addPass(&SIPeepholeSDWALegacyID);
1579 addPass(&EarlyMachineLICMID);
1580 addPass(&MachineCSELegacyID);
1581 addPass(&SIFoldOperandsLegacyID);
1582 }
1585}
1586
1587bool GCNPassConfig::addILPOpts() {
1588 if (CLOpts.early_ifcvt)
1589 addPass(&EarlyIfConverterLegacyID);
1590
1592 return false;
1593}
1594
1595bool GCNPassConfig::addInstSelector() {
1597 addPass(&SIFixSGPRCopiesLegacyID);
1599 return false;
1600}
1601
1602bool GCNPassConfig::addIRTranslator() {
1603 addPass(new IRTranslatorLegacy(getOptLevel()));
1604 return false;
1605}
1606
1607void GCNPassConfig::addPreLegalizeMachineIR() {
1608 bool IsOptLevelNone = getOptLevel() == CodeGenOptLevel::None;
1609 addPass(createAMDGPUPreLegalizeCombinerLegacyPass(IsOptLevelNone));
1610 addPass(new LocalizerLegacy());
1611}
1612
1613bool GCNPassConfig::addLegalizeMachineIR() {
1614 addPass(new LegalizerLegacy());
1615 return false;
1616}
1617
1618void GCNPassConfig::addPreRegBankSelect() {
1619 bool IsOptNone = getOptLevel() == CodeGenOptLevel::None;
1620 addPass(createAMDGPUPostLegalizeCombinerLegacy(IsOptNone));
1622}
1623
1624bool GCNPassConfig::addRegBankSelect() {
1627 return false;
1628}
1629
1630void GCNPassConfig::addPreGlobalInstructionSelect() {
1631 bool IsOptLevelNone = getOptLevel() == CodeGenOptLevel::None;
1632 addPass(createAMDGPURegBankCombinerLegacy(IsOptLevelNone));
1633}
1634
1635bool GCNPassConfig::addGlobalInstructionSelect() {
1636 addPass(new InstructionSelectLegacy(getOptLevel()));
1637 return false;
1638}
1639
1640void GCNPassConfig::addFastRegAlloc() {
1641 // FIXME: We have to disable the verifier here because of PHIElimination +
1642 // TwoAddressInstructions disabling it.
1643
1644 // This must be run immediately after phi elimination and before
1645 // TwoAddressInstructions, otherwise the processing of the tied operand of
1646 // SI_ELSE will introduce a copy of the tied operand source after the else.
1648
1650
1652}
1653
1654void GCNPassConfig::addPreRegAlloc() {
1655 if (getOptLevel() != CodeGenOptLevel::None)
1657}
1658
1659void GCNPassConfig::addOptimizedRegAlloc() {
1660 if (CLOpts.dce_in_ra)
1662
1663 if (CLOpts.opt_vgpr_liverange)
1665
1666 // This must be run immediately after phi elimination and before
1667 // TwoAddressInstructions, otherwise the processing of the tied operand of
1668 // SI_ELSE will introduce a copy of the tied operand source after the else.
1670
1671 if (CLOpts.enable_rewrite_partial_reg_uses)
1673
1674 // Insertion point for passes depends on whether MachineScheduler is enabled.
1675 AnalysisID EndOfPreRA = CLOpts.use_ssa_machine_scheduler
1678
1679 if (isPassEnabled(CLOpts.enable_pre_ra_optimizations))
1680 insertPass(EndOfPreRA, &GCNPreRAOptimizationsID);
1681
1682 // Allow the scheduler to run before SIWholeQuadMode inserts exec manipulation
1683 // instructions that cause scheduling barriers.
1684 insertPass(EndOfPreRA, &SIWholeQuadModeID);
1685
1686 if (CLOpts.opt_exec_mask_pre_ra)
1687 insertPass(EndOfPreRA, &SIOptimizeExecMaskingPreRAID);
1688
1689 // This is not an essential optimization and it has a noticeable impact on
1690 // compilation time, so we only enable it from O2.
1691 if (TM->getOptLevel() > CodeGenOptLevel::Less)
1692 insertPass(EndOfPreRA, &SIFormMemoryClausesID);
1693
1695}
1696
1697bool GCNPassConfig::addPreRewrite() {
1698 if (CLOpts.reassign_regs)
1699 addPass(&GCNNSAReassignID);
1700
1702 return true;
1703}
1704
1705FunctionPass *GCNPassConfig::createSGPRAllocPass(bool Optimized) {
1706 // Initialize the global default.
1709
1710 RegisterRegAlloc::FunctionPassCtor Ctor = SGPRRegisterRegAlloc::getDefault();
1711 if (Ctor != useDefaultRegisterAllocator)
1712 return Ctor();
1713
1714 if (Optimized)
1716
1718}
1719
1720FunctionPass *GCNPassConfig::createVGPRAllocPass(bool Optimized) {
1721 // Initialize the global default.
1724
1725 RegisterRegAlloc::FunctionPassCtor Ctor = VGPRRegisterRegAlloc::getDefault();
1726 if (Ctor != useDefaultRegisterAllocator)
1727 return Ctor();
1728
1729 if (Optimized)
1731
1733}
1734
1735FunctionPass *GCNPassConfig::createWWMRegAllocPass(bool Optimized) {
1736 // Initialize the global default.
1739
1740 RegisterRegAlloc::FunctionPassCtor Ctor = WWMRegisterRegAlloc::getDefault();
1741 if (Ctor != useDefaultRegisterAllocator)
1742 return Ctor();
1743
1744 if (Optimized)
1746
1748}
1749
1750FunctionPass *GCNPassConfig::createRegAllocPass(bool Optimized) {
1751 llvm_unreachable("should not be used");
1752}
1753
1755 "-regalloc not supported with amdgcn. Use -sgpr-regalloc, -wwm-regalloc, "
1756 "and -vgpr-regalloc";
1757
1758void GCNPassConfig::addRegAssignAndRewriteFast() {
1759 if (!usingDefaultRegAlloc())
1761
1762 addPass(&GCNPreRALongBranchRegID);
1763
1764 addPass(createSGPRAllocPass(false));
1765
1766 // Equivalent of PEI for SGPRs.
1767 addPass(&SILowerSGPRSpillsLegacyID);
1768
1769 // To Allocate wwm registers used in whole quad mode operations (for shaders).
1771
1772 // For allocating other wwm register operands.
1773 addPass(createWWMRegAllocPass(false));
1774
1775 addPass(&SILowerWWMCopiesLegacyID);
1777
1778 // For allocating per-thread VGPRs.
1779 addPass(createVGPRAllocPass(false));
1780}
1781
1782void GCNPassConfig::addRegAssignAndRewriteOptimized() {
1783 if (!usingDefaultRegAlloc())
1785
1786 addPass(&GCNPreRALongBranchRegID);
1787
1788 addPass(createSGPRAllocPass(true));
1789
1790 // Commit allocated register changes. This is mostly necessary because too
1791 // many things rely on the use lists of the physical registers, such as the
1792 // verifier. This is only necessary with allocators which use LiveIntervals,
1793 // since FastRegAlloc does the replacements itself.
1794 addPass(createVirtRegRewriter(false));
1795
1796 // At this point, the sgpr-regalloc has been done and it is good to have the
1797 // stack slot coloring to try to optimize the SGPR spill stack indices before
1798 // attempting the custom SGPR spill lowering.
1799 addPass(&StackSlotColoringID);
1800
1801 // Equivalent of PEI for SGPRs.
1802 addPass(&SILowerSGPRSpillsLegacyID);
1803
1804 // To Allocate wwm registers used in whole quad mode operations (for shaders).
1806
1807 // For allocating other whole wave mode registers.
1808 addPass(createWWMRegAllocPass(true));
1809 addPass(&SILowerWWMCopiesLegacyID);
1810 addPass(createVirtRegRewriter(false));
1812
1813 // For allocating per-thread VGPRs.
1814 addPass(createVGPRAllocPass(true));
1815
1816 addPreRewrite();
1817 addPass(&VirtRegRewriterID);
1818
1819 addPass(createRegAllocScoringPass());
1820
1822}
1823
1824void GCNPassConfig::addPostRegAlloc() {
1825 addPass(&SIFixVGPRCopiesID);
1826 if (getOptLevel() > CodeGenOptLevel::None)
1829}
1830
1831void GCNPassConfig::addPreSched2() {
1832 if (TM->getOptLevel() > CodeGenOptLevel::None)
1834 addPass(&SIPostRABundlerLegacyID);
1835}
1836
1838 Triple::SubArchType SubArch = TT.getSubArch();
1839 return SubArch == Triple::NoSubArch ||
1840 SubArch == Triple::AMDGPUSubArch1250S ||
1842}
1843
1844void GCNPassConfig::addPreEmitPass() {
1845 if (isPassEnabled(CLOpts.enable_vopd, CodeGenOptLevel::Less))
1846 addPass(&GCNCreateVOPDID);
1847 addPass(createSIMemoryLegalizerPass());
1848 if (getOptLevel() > CodeGenOptLevel::None)
1850 if (mayNeedAsyncBarrierArriveWorkaround(TM->getTargetTriple()))
1852 addPass(createSIInsertWaitcntsPass());
1853
1854 addPass(createSIModeRegisterPass());
1855
1856 if (getOptLevel() > CodeGenOptLevel::None)
1857 addPass(&SIInsertHardClausesID);
1858
1860 if (CLOpts.set_wave_priority)
1862 if (getOptLevel() > CodeGenOptLevel::None)
1863 addPass(&SIPreEmitPeepholeID);
1864 // The hazard recognizer that runs as part of the post-ra scheduler does not
1865 // guarantee to be able handle all hazards correctly. This is because if there
1866 // are multiple scheduling regions in a basic block, the regions are scheduled
1867 // bottom up, so when we begin to schedule a region we don't know what
1868 // instructions were emitted directly before it.
1869 //
1870 // Here we add a stand-alone hazard recognizer pass which can handle all
1871 // cases.
1872 addPass(&PostRAHazardRecognizerID);
1873
1875
1877
1878 if (isPassEnabled(CLOpts.enable_delay_alu, CodeGenOptLevel::Less))
1879 addPass(&AMDGPUInsertDelayAluID);
1880
1881 addPass(&BranchRelaxationPassID);
1882}
1883
1884void GCNPassConfig::addPostBBSections() {
1885 // We run this later to avoid passes like livedebugvalues and BBSections
1886 // having to deal with the apparent multi-entry functions we may generate.
1888}
1889
1891 return new GCNPassConfig(*this, PM);
1892}
1893
1899
1906
1910
1917
1920 SMDiagnostic &Error, SMRange &SourceRange) const {
1921 const yaml::SIMachineFunctionInfo &YamlMFI =
1922 static_cast<const yaml::SIMachineFunctionInfo &>(MFI_);
1923 MachineFunction &MF = PFS.MF;
1925 const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>();
1926
1927 if (MFI->initializeBaseYamlFields(YamlMFI, MF, PFS, Error, SourceRange))
1928 return true;
1929
1930 if (MFI->Occupancy == 0) {
1931 // Fixup the subtarget dependent default value.
1932 MFI->Occupancy = ST.getOccupancyWithWorkGroupSizes(MF).second;
1933 }
1934
1935 auto parseRegister = [&](const yaml::StringValue &RegName, Register &RegVal) {
1936 Register TempReg;
1937 if (parseNamedRegisterReference(PFS, TempReg, RegName.Value, Error)) {
1938 SourceRange = RegName.SourceRange;
1939 return true;
1940 }
1941 RegVal = TempReg;
1942
1943 return false;
1944 };
1945
1946 auto parseOptionalRegister = [&](const yaml::StringValue &RegName,
1947 Register &RegVal) {
1948 return !RegName.Value.empty() && parseRegister(RegName, RegVal);
1949 };
1950
1951 if (parseOptionalRegister(YamlMFI.VGPRForAGPRCopy, MFI->VGPRForAGPRCopy))
1952 return true;
1953
1954 if (parseOptionalRegister(YamlMFI.SGPRForEXECCopy, MFI->SGPRForEXECCopy))
1955 return true;
1956
1957 if (parseOptionalRegister(YamlMFI.LongBranchReservedReg,
1958 MFI->LongBranchReservedReg))
1959 return true;
1960
1961 auto diagnoseRegisterClass = [&](const yaml::StringValue &RegName) {
1962 // Create a diagnostic for a the register string literal.
1963 const MemoryBuffer &Buffer =
1964 *PFS.SM->getMemoryBuffer(PFS.SM->getMainFileID());
1966 *PFS.SM, SMLoc(), Buffer.getBufferIdentifier(), 1,
1967 static_cast<int>(RegName.Value.size()), SourceMgr::DK_Error,
1968 "incorrect register class for field", RegName.Value, {}, {});
1969 SourceRange = RegName.SourceRange;
1970 return true;
1971 };
1972
1973 if (parseRegister(YamlMFI.ScratchRSrcReg, MFI->ScratchRSrcReg) ||
1974 parseRegister(YamlMFI.FrameOffsetReg, MFI->FrameOffsetReg) ||
1975 parseRegister(YamlMFI.StackPtrOffsetReg, MFI->StackPtrOffsetReg))
1976 return true;
1977
1978 if (MFI->ScratchRSrcReg != AMDGPU::PRIVATE_RSRC_REG &&
1979 !AMDGPU::SGPR_128RegClass.contains(MFI->ScratchRSrcReg)) {
1980 return diagnoseRegisterClass(YamlMFI.ScratchRSrcReg);
1981 }
1982
1983 if (MFI->FrameOffsetReg != AMDGPU::FP_REG &&
1984 !AMDGPU::SGPR_32RegClass.contains(MFI->FrameOffsetReg)) {
1985 return diagnoseRegisterClass(YamlMFI.FrameOffsetReg);
1986 }
1987
1988 if (MFI->StackPtrOffsetReg != AMDGPU::SP_REG &&
1989 !AMDGPU::SGPR_32RegClass.contains(MFI->StackPtrOffsetReg)) {
1990 return diagnoseRegisterClass(YamlMFI.StackPtrOffsetReg);
1991 }
1992
1993 for (const auto &YamlReg : YamlMFI.WWMReservedRegs) {
1994 Register ParsedReg;
1995 if (parseRegister(YamlReg, ParsedReg))
1996 return true;
1997
1998 MFI->reserveWWMRegister(ParsedReg);
1999 }
2000
2001 for (const auto &[_, Info] : PFS.VRegInfosNamed) {
2002 MFI->setFlag(Info->VReg, Info->Flags);
2003 }
2004 for (const auto &[_, Info] : PFS.VRegInfos) {
2005 MFI->setFlag(Info->VReg, Info->Flags);
2006 }
2007
2008 for (const auto &YamlRegStr : YamlMFI.SpillPhysVGPRS) {
2009 Register ParsedReg;
2010 if (parseRegister(YamlRegStr, ParsedReg))
2011 return true;
2012 MFI->SpillPhysVGPRs.push_back(ParsedReg);
2013 }
2014
2015 auto parseAndCheckArgument = [&](const std::optional<yaml::SIArgument> &A,
2016 const TargetRegisterClass &RC,
2017 ArgDescriptor &Arg, unsigned UserSGPRs,
2018 unsigned SystemSGPRs) {
2019 // Skip parsing if it's not present.
2020 if (!A)
2021 return false;
2022
2023 if (A->IsRegister) {
2024 Register Reg;
2025 if (parseNamedRegisterReference(PFS, Reg, A->RegisterName.Value, Error)) {
2026 SourceRange = A->RegisterName.SourceRange;
2027 return true;
2028 }
2029 if (!RC.contains(Reg))
2030 return diagnoseRegisterClass(A->RegisterName);
2032 } else
2033 Arg = ArgDescriptor::createStack(A->StackOffset);
2034 // Check and apply the optional mask.
2035 if (A->Mask)
2036 Arg = ArgDescriptor::createArg(Arg, *A->Mask);
2037
2038 MFI->NumUserSGPRs += UserSGPRs;
2039 MFI->NumSystemSGPRs += SystemSGPRs;
2040 return false;
2041 };
2042
2043 if (YamlMFI.ArgInfo &&
2044 (parseAndCheckArgument(YamlMFI.ArgInfo->PrivateSegmentBuffer,
2045 AMDGPU::SGPR_128RegClass,
2046 MFI->ArgInfo.PrivateSegmentBuffer, 4, 0) ||
2047 parseAndCheckArgument(YamlMFI.ArgInfo->DispatchPtr,
2048 AMDGPU::SReg_64RegClass, MFI->ArgInfo.DispatchPtr,
2049 2, 0) ||
2050 parseAndCheckArgument(YamlMFI.ArgInfo->QueuePtr, AMDGPU::SReg_64RegClass,
2051 MFI->ArgInfo.QueuePtr, 2, 0) ||
2052 parseAndCheckArgument(YamlMFI.ArgInfo->KernargSegmentPtr,
2053 AMDGPU::SReg_64RegClass,
2054 MFI->ArgInfo.KernargSegmentPtr, 2, 0) ||
2055 parseAndCheckArgument(YamlMFI.ArgInfo->DispatchID,
2056 AMDGPU::SReg_64RegClass, MFI->ArgInfo.DispatchID,
2057 2, 0) ||
2058 parseAndCheckArgument(YamlMFI.ArgInfo->FlatScratchInit,
2059 AMDGPU::SReg_64RegClass,
2060 MFI->ArgInfo.FlatScratchInit, 2, 0) ||
2061 parseAndCheckArgument(YamlMFI.ArgInfo->PrivateSegmentSize,
2062 AMDGPU::SGPR_32RegClass,
2063 MFI->ArgInfo.PrivateSegmentSize, 1, 0) ||
2064 parseAndCheckArgument(YamlMFI.ArgInfo->LDSKernelId,
2065 AMDGPU::SGPR_32RegClass, MFI->ArgInfo.LDSKernelId,
2066 1, 0) ||
2067 parseAndCheckArgument(YamlMFI.ArgInfo->WorkGroupIDX,
2068 AMDGPU::SGPR_32RegClass, MFI->ArgInfo.WorkGroupIDX,
2069 0, 1) ||
2070 parseAndCheckArgument(YamlMFI.ArgInfo->WorkGroupIDY,
2071 AMDGPU::SGPR_32RegClass, MFI->ArgInfo.WorkGroupIDY,
2072 0, 1) ||
2073 parseAndCheckArgument(YamlMFI.ArgInfo->WorkGroupIDZ,
2074 AMDGPU::SGPR_32RegClass, MFI->ArgInfo.WorkGroupIDZ,
2075 0, 1) ||
2076 parseAndCheckArgument(YamlMFI.ArgInfo->WorkGroupInfo,
2077 AMDGPU::SGPR_32RegClass,
2078 MFI->ArgInfo.WorkGroupInfo, 0, 1) ||
2079 parseAndCheckArgument(YamlMFI.ArgInfo->PrivateSegmentWaveByteOffset,
2080 AMDGPU::SGPR_32RegClass,
2081 MFI->ArgInfo.PrivateSegmentWaveByteOffset, 0, 1) ||
2082 parseAndCheckArgument(YamlMFI.ArgInfo->ImplicitArgPtr,
2083 AMDGPU::SReg_64RegClass,
2084 MFI->ArgInfo.ImplicitArgPtr, 0, 0) ||
2085 parseAndCheckArgument(YamlMFI.ArgInfo->ImplicitBufferPtr,
2086 AMDGPU::SReg_64RegClass,
2087 MFI->ArgInfo.ImplicitBufferPtr, 2, 0) ||
2088 parseAndCheckArgument(YamlMFI.ArgInfo->WorkItemIDX,
2089 AMDGPU::VGPR_32RegClass, MFI->ArgInfo.WorkItemIDX,
2090 0, 0) ||
2091 parseAndCheckArgument(YamlMFI.ArgInfo->WorkItemIDY,
2092 AMDGPU::VGPR_32RegClass, MFI->ArgInfo.WorkItemIDY,
2093 0, 0) ||
2094 parseAndCheckArgument(YamlMFI.ArgInfo->WorkItemIDZ,
2095 AMDGPU::VGPR_32RegClass, MFI->ArgInfo.WorkItemIDZ,
2096 0, 0)))
2097 return true;
2098
2099 // Parse FirstKernArgPreloadReg separately, since it's a Register,
2100 // not ArgDescriptor.
2101 if (YamlMFI.ArgInfo && YamlMFI.ArgInfo->FirstKernArgPreloadReg) {
2102 const yaml::SIArgument &A = *YamlMFI.ArgInfo->FirstKernArgPreloadReg;
2103
2104 if (!A.IsRegister) {
2105 // For stack arguments, we don't have RegisterName.SourceRange,
2106 // but we should have some location info from the YAML parser
2107 const MemoryBuffer &Buffer =
2108 *PFS.SM->getMemoryBuffer(PFS.SM->getMainFileID());
2109 // Create a minimal valid source range
2111 SMRange Range(Loc, Loc);
2112
2114 *PFS.SM, Loc, Buffer.getBufferIdentifier(), 1, 0, SourceMgr::DK_Error,
2115 "firstKernArgPreloadReg must be a register, not a stack location", "",
2116 {}, {});
2117
2118 SourceRange = Range;
2119 return true;
2120 }
2121
2122 Register Reg;
2123 if (parseNamedRegisterReference(PFS, Reg, A.RegisterName.Value, Error)) {
2124 SourceRange = A.RegisterName.SourceRange;
2125 return true;
2126 }
2127
2128 if (!AMDGPU::SGPR_32RegClass.contains(Reg))
2129 return diagnoseRegisterClass(A.RegisterName);
2130
2131 MFI->ArgInfo.FirstKernArgPreloadReg = Reg;
2132 MFI->NumUserSGPRs += YamlMFI.NumKernargPreloadSGPRs;
2133 }
2134
2135 if (ST.hasFeature(AMDGPU::FeatureDX10ClampAndIEEEMode)) {
2136 MFI->Mode.IEEE = YamlMFI.Mode.IEEE;
2137 MFI->Mode.DX10Clamp = YamlMFI.Mode.DX10Clamp;
2138 }
2139
2140 // FIXME: Move proper support for denormal-fp-math into base MachineFunction
2141 MFI->Mode.FP32Denormals.Input = YamlMFI.Mode.FP32InputDenormals
2144 MFI->Mode.FP32Denormals.Output = YamlMFI.Mode.FP32OutputDenormals
2147
2154
2155 if (YamlMFI.HasInitWholeWave)
2156 MFI->setInitWholeWave();
2157
2158 return false;
2159}
2160
2161//===----------------------------------------------------------------------===//
2162// AMDGPU CodeGen Pass Builder interface.
2163//===----------------------------------------------------------------------===//
2164
2165AMDGPUCodeGenPassBuilder::AMDGPUCodeGenPassBuilder(
2166 GCNTargetMachine &TM, const CGPassBuilderOption &Opts,
2168 : CodeGenPassBuilder(TM, Opts, PIC), CLOpts(TM.getCLOpts()) {
2169 Opt.MISchedPostRA = true;
2170 Opt.RequiresCodeGenSCCOrder = true;
2171 Opt.EnableSSAMachineScheduler = CLOpts.use_ssa_machine_scheduler;
2172 // Exceptions and StackMaps are not supported, so these passes will never do
2173 // anything.
2174 // Garbage collection is not supported.
2175 disablePass<StackMapLivenessPass, FuncletLayoutPass, PatchableFunctionPass,
2177
2178 // If enabled, use the SSA machine scheduler instead of the regular machine
2179 // scheduler.
2180 if (Opt.EnableSSAMachineScheduler)
2181 disablePass<MachineSchedulerPass>();
2182}
2183
2184void AMDGPUCodeGenPassBuilder::addIRPasses(PassManagerWrapper &PMW) {
2185 if (CLOpts.enable_remove_incompatible_functions &&
2186 TM.getTargetTriple().isAMDGCN()) {
2187 flushFPMsToMPM(PMW);
2188 addModulePass(AMDGPURemoveIncompatibleFunctionsPass(TM), PMW);
2189 }
2190
2191 flushFPMsToMPM(PMW);
2192
2193 if (TM.getTargetTriple().isAMDGCN())
2194 addModulePass(AMDGPUPrintfRuntimeBindingPass(), PMW);
2195
2196 if (CLOpts.lower_global_ctor_dtor)
2197 addModulePass(AMDGPUCtorDtorLoweringPass(), PMW);
2198
2199 if (isPassEnabled(CLOpts.enable_image_intrinsic_optimizer))
2200 addFunctionPass(AMDGPUImageIntrinsicOptimizerPass(TM), PMW);
2201
2202 if (CLOpts.enable_uniform_intrinsic_combine)
2203 addFunctionPass(AMDGPUUniformIntrinsicCombinePass(), PMW);
2204 // This can be disabled by passing ::Disable here or on the command line
2205 // with --expand-variadics-override=disable.
2206 flushFPMsToMPM(PMW);
2208
2209 addModulePass(AMDGPUAlwaysInlinePass(), PMW);
2210 addModulePass(AlwaysInlinerPass(), PMW);
2211
2212 addModulePass(AMDGPUExportKernelRuntimeHandlesPass(), PMW);
2213
2214 if (CLOpts.enable_lower_exec_sync)
2215 addModulePass(AMDGPULowerExecSyncPass(), PMW);
2216
2217 if (CLOpts.enable_sw_lower_lds)
2218 addModulePass(AMDGPUSwLowerLDSPass(), PMW);
2219
2220 // Runs before PromoteAlloca so the latter can account for function uses
2222 addModulePass(AMDGPULowerModuleLDSPass(getTM()), PMW);
2223
2224 // Run atomic optimizer before Atomic Expand
2225 if (TM.getOptLevel() >= CodeGenOptLevel::Less &&
2226 (CLOpts.atomic_optimizer_strategy != AMDGPU::ScanOptions::None))
2227 addFunctionPass(
2228 AMDGPUAtomicOptimizerPass(TM, CLOpts.atomic_optimizer_strategy), PMW);
2229
2230 addFunctionPass(AtomicExpandPass(TM), PMW);
2231
2233 addFunctionPass(AMDGPUPromoteAllocaPass(TM), PMW);
2234 if (isPassEnabled(CLOpts.scalar_ir_passes))
2235 addStraightLineScalarOptimizationPasses(PMW);
2236
2237 // TODO: Handle CLOpts.enable_aa
2238
2239 // TODO: May want to move later or split into an early and late one.
2240 addFunctionPass(AMDGPUCodeGenPreparePass(TM), PMW);
2241
2242 // Try to hoist loop invariant parts of divisions AMDGPUCodeGenPrepare may
2243 // have expanded.
2246 /*UseMemorySSA=*/true),
2247 PMW);
2248 }
2249 }
2250
2251 Base::addIRPasses(PMW);
2252
2253 // EarlyCSE is not always strong enough to clean up what LSR produces. For
2254 // example, GVN can combine
2255 //
2256 // %0 = add %a, %b
2257 // %1 = add %b, %a
2258 //
2259 // and
2260 //
2261 // %0 = shl nsw %a, 2
2262 // %1 = shl %a, 2
2263 //
2264 // but EarlyCSE can do neither of them.
2265 if (isPassEnabled(CLOpts.scalar_ir_passes))
2266 addEarlyCSEOrGVNPass(PMW);
2267}
2268
2269void AMDGPUCodeGenPassBuilder::addCodeGenPrepare(PassManagerWrapper &PMW) {
2271 flushFPMsToMPM(PMW);
2272 addModulePass(AMDGPUPreloadKernelArgumentsPass(TM), PMW);
2273 }
2274
2275 if (CLOpts.ir_lower_kernel_arguments)
2276 addFunctionPass(AMDGPULowerKernelArgumentsPass(TM), PMW);
2277
2278 Base::addCodeGenPrepare(PMW);
2279
2280 if (isPassEnabled(CLOpts.load_store_vectorizer))
2281 addFunctionPass(LoadStoreVectorizerPass(), PMW);
2282
2283 // This lowering has been placed after codegenprepare to take advantage of
2284 // address mode matching (which is why it isn't put with the LDS lowerings).
2285 // It could be placed anywhere before uniformity annotations (an analysis
2286 // that it changes by splitting up fat pointers into their components)
2287 // but has been put before switch lowering and CFG flattening so that those
2288 // passes can run on the more optimized control flow this pass creates in
2289 // many cases.
2290 flushFPMsToMPM(PMW);
2291 addModulePass(AMDGPULowerBufferFatPointersPass(TM), PMW);
2292 flushFPMsToMPM(PMW);
2293 requireCGSCCOrder(PMW);
2294
2295 addModulePass(AMDGPULowerIntrinsicsPass(getTM()), PMW);
2296
2297 // LowerSwitch pass may introduce unreachable blocks that can cause unexpected
2298 // behavior for subsequent passes. Placing it here seems better that these
2299 // blocks would get cleaned up by UnreachableBlockElim inserted next in the
2300 // pass flow.
2301 addFunctionPass(LowerSwitchPass(), PMW);
2302}
2303
2304void AMDGPUCodeGenPassBuilder::addPreISel(PassManagerWrapper &PMW) {
2305
2307 addFunctionPass(FlattenCFGPass(), PMW);
2308 addFunctionPass(SinkingPass(), PMW);
2309 addFunctionPass(AMDGPULateCodeGenPreparePass(getTM()), PMW);
2310 }
2311
2312 // Merge divergent exit nodes. StructurizeCFG won't recognize the multi-exit
2313 // regions formed by them.
2314
2315 addFunctionPass(AMDGPUUnifyDivergentExitNodesPass(), PMW);
2316 addFunctionPass(FixIrreduciblePass(), PMW);
2317 addFunctionPass(UnifyLoopExitsPass(), PMW);
2318 addFunctionPass(StructurizeCFGPass(/*SkipUniformRegions=*/true), PMW);
2319
2320 addFunctionPass(AMDGPUAnnotateUniformValuesPass(), PMW);
2321
2322 addFunctionPass(SIAnnotateControlFlowPass(getTM()), PMW);
2323
2324 // TODO: Move this right after structurizeCFG to avoid extra divergence
2325 // analysis. This depends on stopping SIAnnotateControlFlow from making
2326 // control flow modifications.
2327 addFunctionPass(AMDGPURewriteUndefForPHIPass(), PMW);
2328
2329 if (getCGPassBuilderOption(TM).EnableGlobalISelOption !=
2331 !isGlobalISelAbortEnabled())
2332 addFunctionPass(LCSSAPass(), PMW);
2333
2335 flushFPMsToMPM(PMW);
2336 addModulePass(AMDGPUPerfHintAnalysisPass(getTM()), PMW);
2337 }
2338}
2339
2340void AMDGPUCodeGenPassBuilder::addILPOpts(PassManagerWrapper &PMW) {
2341 if (CLOpts.early_ifcvt)
2342 addMachineFunctionPass(EarlyIfConverterPass(), PMW);
2343
2344 Base::addILPOpts(PMW);
2345}
2346
2347void AMDGPUCodeGenPassBuilder::addAsmPrinterBegin(PassManagerWrapper &PMW) {
2348 addModulePass(AMDGPUAsmPrinterBeginPass(), PMW,
2349 /*Force=*/true);
2350}
2351
2352void AMDGPUCodeGenPassBuilder::addAsmPrinter(PassManagerWrapper &PMW) {
2353 addMachineFunctionPass(AMDGPUAsmPrinterPass(), PMW);
2354}
2355
2356void AMDGPUCodeGenPassBuilder::addAsmPrinterEnd(PassManagerWrapper &PMW) {
2357 addModulePass(AMDGPUAsmPrinterEndPass(), PMW);
2358}
2359
2360Error AMDGPUCodeGenPassBuilder::addInstSelector(PassManagerWrapper &PMW) {
2361 addMachineFunctionPass(AMDGPUISelDAGToDAGPass(TM), PMW);
2362 addMachineFunctionPass(SIFixSGPRCopiesPass(), PMW);
2363 addMachineFunctionPass(SILowerI1CopiesPass(), PMW);
2364 return Error::success();
2365}
2366
2367Error AMDGPUCodeGenPassBuilder::addIRTranslator(PassManagerWrapper &PMW) {
2368 addMachineFunctionPass(IRTranslatorPass(getOptLevel()), PMW);
2369 return Error::success();
2370}
2371
2372void AMDGPUCodeGenPassBuilder::addPreLegalizeMachineIR(
2373 PassManagerWrapper &PMW) {
2374 addMachineFunctionPass(AMDGPUPreLegalizerCombinerPass(), PMW);
2375 addMachineFunctionPass(LocalizerPass(), PMW);
2376}
2377
2378Error AMDGPUCodeGenPassBuilder::addLegalizeMachineIR(PassManagerWrapper &PMW) {
2379 addMachineFunctionPass(LegalizerPass(), PMW);
2380 return Error::success();
2381}
2382
2383void AMDGPUCodeGenPassBuilder::addPreRegBankSelect(PassManagerWrapper &PMW) {
2384 addMachineFunctionPass(AMDGPUPostLegalizerCombinerPass(), PMW);
2385 addMachineFunctionPass(AMDGPUGlobalISelDivergenceLoweringPass(), PMW);
2386}
2387
2388Error AMDGPUCodeGenPassBuilder::addRegBankSelect(PassManagerWrapper &PMW) {
2389 addMachineFunctionPass(AMDGPURegBankSelectPass(), PMW);
2390 addMachineFunctionPass(AMDGPURegBankLegalizePass(), PMW);
2391 return Error::success();
2392}
2393
2394void AMDGPUCodeGenPassBuilder::addPreGlobalInstructionSelect(
2395 PassManagerWrapper &PMW) {
2396 bool IsOptLevelNone = getOptLevel() == CodeGenOptLevel::None;
2397 addMachineFunctionPass(AMDGPURegBankCombinerPass(IsOptLevelNone), PMW);
2398}
2399
2400Error AMDGPUCodeGenPassBuilder::addGlobalInstructionSelect(
2401 PassManagerWrapper &PMW) {
2402 addMachineFunctionPass(InstructionSelectPass(getOptLevel()), PMW);
2403 return Error::success();
2404}
2405
2406void AMDGPUCodeGenPassBuilder::addPreRewrite(PassManagerWrapper &PMW) {
2407 if (CLOpts.reassign_regs) {
2408 addMachineFunctionPass(GCNNSAReassignPass(), PMW);
2409 }
2410
2411 addMachineFunctionPass(AMDGPURewriteAGPRCopyMFMAPass(), PMW);
2412}
2413
2414void AMDGPUCodeGenPassBuilder::addMachineSSAOptimization(
2415 PassManagerWrapper &PMW) {
2416 Base::addMachineSSAOptimization(PMW);
2417
2418 addMachineFunctionPass(SIFoldOperandsPass(), PMW);
2419 if (CLOpts.dpp_combine) {
2420 addMachineFunctionPass(GCNDPPCombinePass(), PMW);
2421 }
2422 addMachineFunctionPass(SILoadStoreOptimizerPass(), PMW);
2423 if (isPassEnabled(CLOpts.sdwa_peephole)) {
2424 addMachineFunctionPass(SIPeepholeSDWAPass(), PMW);
2425 addMachineFunctionPass(EarlyMachineLICMPass(), PMW);
2426 addMachineFunctionPass(MachineCSEPass(), PMW);
2427 addMachineFunctionPass(SIFoldOperandsPass(), PMW);
2428 }
2429 addMachineFunctionPass(DeadMachineInstructionElimPass(), PMW);
2430 addMachineFunctionPass(SIShrinkInstructionsPass(), PMW);
2431}
2432
2433Error AMDGPUCodeGenPassBuilder::addFastRegAlloc(PassManagerWrapper &PMW) {
2434 insertPass<PHIEliminationPass>(SILowerControlFlowPass());
2435
2436 insertPass<TwoAddressInstructionPass>(SIWholeQuadModePass());
2437
2438 return Base::addFastRegAlloc(PMW);
2439}
2440
2441Error AMDGPUCodeGenPassBuilder::addRegAssignAndRewriteFast(
2442 PassManagerWrapper &PMW) {
2443 if (auto Err = validateRegAllocOptions())
2444 return Err;
2445
2446 addMachineFunctionPass(GCNPreRALongBranchRegPass(), PMW);
2447
2448 // SGPR allocation - default to fast at -O0.
2450 addMachineFunctionPass(RAGreedyPass({onlyAllocateSGPRs, "sgpr"}), PMW);
2451 else
2452 addMachineFunctionPass(RegAllocFastPass({onlyAllocateSGPRs, "sgpr", false}),
2453 PMW);
2454
2455 // Equivalent of PEI for SGPRs.
2456 addMachineFunctionPass(SILowerSGPRSpillsPass(), PMW);
2457
2458 // To Allocate wwm registers used in whole quad mode operations (for shaders).
2459 addMachineFunctionPass(SIPreAllocateWWMRegsPass(), PMW);
2460
2461 // WWM allocation - default to fast at -O0.
2463 addMachineFunctionPass(RAGreedyPass({onlyAllocateWWMRegs, "wwm"}), PMW);
2464 else
2465 addMachineFunctionPass(
2466 RegAllocFastPass({onlyAllocateWWMRegs, "wwm", false}), PMW);
2467
2468 addMachineFunctionPass(SILowerWWMCopiesPass(), PMW);
2469 addMachineFunctionPass(AMDGPUReserveWWMRegsPass(), PMW);
2470
2471 // VGPR allocation - default to fast at -O0.
2473 addMachineFunctionPass(RAGreedyPass({onlyAllocateVGPRs, "vgpr"}), PMW);
2474 else
2475 addMachineFunctionPass(RegAllocFastPass({onlyAllocateVGPRs, "vgpr"}), PMW);
2476
2477 return Error::success();
2478}
2479
2480Error AMDGPUCodeGenPassBuilder::addOptimizedRegAlloc(PassManagerWrapper &PMW) {
2481 if (CLOpts.dce_in_ra)
2482 insertPass<DetectDeadLanesPass>(DeadMachineInstructionElimPass());
2483
2484 if (CLOpts.opt_vgpr_liverange)
2485 insertPass<RequireAnalysisPass<MachineLoopAnalysis, MachineFunction>>(
2487
2488 // This must be run immediately after phi elimination and before
2489 // TwoAddressInstructions, otherwise the processing of the tied operand of
2490 // SI_ELSE will introduce a copy of the tied operand source after the else.
2491 insertPass<PHIEliminationPass>(SILowerControlFlowPass());
2492
2493 if (CLOpts.enable_rewrite_partial_reg_uses)
2494 insertPass<RenameIndependentSubregsPass>(GCNRewritePartialRegUsesPass());
2495
2496 // Following passes run at the end of the pre-RA pipeline, so the pass they
2497 // are anchored on depends on which scheduler is enabled.
2498 auto insertAtEndOfPreRA = [this](auto &&Pass) {
2499 if (Opt.EnableSSAMachineScheduler)
2500 insertPass<RenameIndependentSubregsPass>(std::move(Pass));
2501 else
2502 insertPass<MachineSchedulerPass>(std::move(Pass));
2503 };
2504
2505 if (isPassEnabled(CLOpts.enable_pre_ra_optimizations))
2506 insertAtEndOfPreRA(GCNPreRAOptimizationsPass());
2507
2508 // Allow the scheduler to run before SIWholeQuadMode inserts exec manipulation
2509 // instructions that cause scheduling barriers.
2510 insertAtEndOfPreRA(SIWholeQuadModePass());
2511
2512 if (CLOpts.opt_exec_mask_pre_ra)
2513 insertAtEndOfPreRA(SIOptimizeExecMaskingPreRAPass());
2514
2515 // This is not an essential optimization and it has a noticeable impact on
2516 // compilation time, so we only enable it from O2.
2518 insertAtEndOfPreRA(SIFormMemoryClausesPass());
2519
2520 return Base::addOptimizedRegAlloc(PMW);
2521}
2522
2523void AMDGPUCodeGenPassBuilder::addPreRegAlloc(PassManagerWrapper &PMW) {
2524 if (getOptLevel() != CodeGenOptLevel::None)
2525 addMachineFunctionPass(AMDGPUPrepareAGPRAllocPass(), PMW);
2526}
2527
2528Error AMDGPUCodeGenPassBuilder::addRegAssignAndRewriteOptimized(
2529 PassManagerWrapper &PMW) {
2530 if (auto Err = validateRegAllocOptions())
2531 return Err;
2532
2533 addMachineFunctionPass(GCNPreRALongBranchRegPass(), PMW);
2534
2535 // SGPR allocation - default to greedy at -O1 and above.
2537 addMachineFunctionPass(RegAllocFastPass({onlyAllocateSGPRs, "sgpr", false}),
2538 PMW);
2539 else
2540 addMachineFunctionPass(RAGreedyPass({onlyAllocateSGPRs, "sgpr"}), PMW);
2541
2542 // Commit allocated register changes. This is mostly necessary because too
2543 // many things rely on the use lists of the physical registers, such as the
2544 // verifier. This is only necessary with allocators which use LiveIntervals,
2545 // since FastRegAlloc does the replacements itself.
2546 addMachineFunctionPass(VirtRegRewriterPass(false), PMW);
2547
2548 // At this point, the sgpr-regalloc has been done and it is good to have the
2549 // stack slot coloring to try to optimize the SGPR spill stack indices before
2550 // attempting the custom SGPR spill lowering.
2551 addMachineFunctionPass(StackSlotColoringPass(), PMW);
2552
2553 // Equivalent of PEI for SGPRs.
2554 addMachineFunctionPass(SILowerSGPRSpillsPass(), PMW);
2555
2556 // To Allocate wwm registers used in whole quad mode operations (for shaders).
2557 addMachineFunctionPass(SIPreAllocateWWMRegsPass(), PMW);
2558
2559 // WWM allocation - default to greedy at -O1 and above.
2561 addMachineFunctionPass(
2562 RegAllocFastPass({onlyAllocateWWMRegs, "wwm", false}), PMW);
2563 else
2564 addMachineFunctionPass(RAGreedyPass({onlyAllocateWWMRegs, "wwm"}), PMW);
2565 addMachineFunctionPass(SILowerWWMCopiesPass(), PMW);
2566 addMachineFunctionPass(VirtRegRewriterPass(false), PMW);
2567 addMachineFunctionPass(AMDGPUReserveWWMRegsPass(), PMW);
2568
2569 // VGPR allocation - default to greedy at -O1 and above.
2571 addMachineFunctionPass(RegAllocFastPass({onlyAllocateVGPRs, "vgpr"}), PMW);
2572 else
2573 addMachineFunctionPass(RAGreedyPass({onlyAllocateVGPRs, "vgpr"}), PMW);
2574
2575 addPreRewrite(PMW);
2576 addMachineFunctionPass(VirtRegRewriterPass(true), PMW);
2577
2578 addMachineFunctionPass(AMDGPUMarkLastScratchLoadPass(), PMW);
2579 return Error::success();
2580}
2581
2582void AMDGPUCodeGenPassBuilder::addPostRegAlloc(PassManagerWrapper &PMW) {
2583 addMachineFunctionPass(SIFixVGPRCopiesPass(), PMW);
2585 addMachineFunctionPass(SIOptimizeExecMaskingPass(), PMW);
2586 Base::addPostRegAlloc(PMW);
2587}
2588
2589void AMDGPUCodeGenPassBuilder::addPreSched2(PassManagerWrapper &PMW) {
2591 addMachineFunctionPass(SIShrinkInstructionsPass(), PMW);
2592 addMachineFunctionPass(SIPostRABundlerPass(), PMW);
2593}
2594
2595void AMDGPUCodeGenPassBuilder::addPostBBSections(PassManagerWrapper &PMW) {
2596 // We run this later to avoid passes like livedebugvalues and BBSections
2597 // having to deal with the apparent multi-entry functions we may generate.
2598 addMachineFunctionPass(AMDGPUPreloadKernArgPrologPass(), PMW);
2599}
2600
2601void AMDGPUCodeGenPassBuilder::addPreEmitPass(PassManagerWrapper &PMW) {
2602 if (isPassEnabled(CLOpts.enable_vopd, CodeGenOptLevel::Less)) {
2603 addMachineFunctionPass(GCNCreateVOPDPass(), PMW);
2604 }
2605
2606 addMachineFunctionPass(SIMemoryLegalizerPass(), PMW);
2608 addMachineFunctionPass(SIPostRA16BitMovFoldingPass(), PMW);
2610 addMachineFunctionPass(SIInsertAsyncBarrierArriveWorkaroundPass(), PMW);
2611 addMachineFunctionPass(SIInsertWaitcntsPass(), PMW);
2612
2613 addMachineFunctionPass(SIModeRegisterPass(), PMW);
2614
2616 addMachineFunctionPass(SIInsertHardClausesPass(), PMW);
2617
2618 addMachineFunctionPass(SILateBranchLoweringPass(), PMW);
2619
2620 if (CLOpts.set_wave_priority)
2621 addMachineFunctionPass(AMDGPUSetWavePriorityPass(), PMW);
2622
2624 addMachineFunctionPass(SIPreEmitPeepholePass(), PMW);
2625
2626 // The hazard recognizer that runs as part of the post-ra scheduler does not
2627 // guarantee to be able handle all hazards correctly. This is because if there
2628 // are multiple scheduling regions in a basic block, the regions are scheduled
2629 // bottom up, so when we begin to schedule a region we don't know what
2630 // instructions were emitted directly before it.
2631 //
2632 // Here we add a stand-alone hazard recognizer pass which can handle all
2633 // cases.
2634 addMachineFunctionPass(PostRAHazardRecognizerPass(), PMW);
2635 addMachineFunctionPass(AMDGPUWaitSGPRHazardsPass(), PMW);
2636 addMachineFunctionPass(AMDGPULowerVGPREncodingPass(), PMW);
2637
2638 if (isPassEnabled(CLOpts.enable_delay_alu, CodeGenOptLevel::Less)) {
2639 addMachineFunctionPass(AMDGPUInsertDelayAluPass(), PMW);
2640 }
2641
2642 addMachineFunctionPass(BranchRelaxationPass(), PMW);
2643}
2644
2645bool AMDGPUCodeGenPassBuilder::isPassEnabled(BoolOrDefault Opt,
2646 CodeGenOptLevel Level) const {
2647 return valueOr(Opt, TM.getOptLevel() >= Level);
2648}
2649
2650void AMDGPUCodeGenPassBuilder::addEarlyCSEOrGVNPass(PassManagerWrapper &PMW) {
2652 addFunctionPass(GVNPass(), PMW);
2653 else
2654 addFunctionPass(EarlyCSEPass(), PMW);
2655}
2656
2657void AMDGPUCodeGenPassBuilder::addStraightLineScalarOptimizationPasses(
2658 PassManagerWrapper &PMW) {
2659 if (CLOpts.loop_prefetch)
2660 addFunctionPass(LoopDataPrefetchPass(), PMW);
2661
2662 addFunctionPass(SeparateConstOffsetFromGEPPass(), PMW);
2663
2664 // ReassociateGEPs exposes more opportunities for SLSR. See
2665 // the example in reassociate-geps-and-slsr.ll.
2666 addFunctionPass(StraightLineStrengthReducePass(), PMW);
2667
2668 // SeparateConstOffsetFromGEP and SLSR creates common expressions which GVN or
2669 // EarlyCSE can reuse.
2670 addEarlyCSEOrGVNPass(PMW);
2671
2672 // Run NaryReassociate after EarlyCSE/GVN to be more effective.
2673 addFunctionPass(NaryReassociatePass(), PMW);
2674
2675 // NaryReassociate on GEPs creates redundant common expressions, so run
2676 // EarlyCSE after it.
2677 addFunctionPass(EarlyCSEPass(), PMW);
2678}
aarch64 falkor hwpf fix Falkor HW Prefetch Fix Late Phase
unsigned NumParts
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
static std::unique_ptr< TargetLoweringObjectFile > createTLOF(const Triple &TT)
This is the AMGPU address space based alias analysis pass.
AMDGPU Assembly printer class.
Coexecution-focused scheduling strategy for AMDGPU.
Defines an instruction selector for the AMDGPU target.
Analyzes if a function potentially memory bound and if a kernel kernel may benefit from limiting numb...
Analyzes how many registers and other resources are used by functions.
static cl::opt< RegAllocType, false, RegAllocTypeParser > SGPRRegAllocNPM("sgpr-regalloc-npm", cl::Hidden, cl::init(RegAllocType::Default), cl::desc("Register allocator for SGPRs (new pass manager)"))
static cl::opt< bool, true > EnableLowerModuleLDS("amdgpu-enable-lower-module-lds", cl::desc("Enable lower module lds pass"), cl::location(AMDGPUTargetMachine::EnableLowerModuleLDS), cl::init(true), cl::Hidden)
static VGPRRegisterRegAlloc greedyRegAllocVGPR("greedy", "greedy register allocator", createGreedyVGPRRegisterAllocator)
static MachineSchedRegistry GCNMaxMemoryClauseSchedRegistry("gcn-max-memory-clause", "Run GCN scheduler to maximize memory clause", createGCNMaxMemoryClauseMachineScheduler)
static Reloc::Model getEffectiveRelocModel()
static llvm::once_flag InitializeDefaultVGPRRegisterAllocatorFlag
static Error checkRegAllocSupported(RegAllocType RAType, StringRef RegName)
Check if the given RegAllocType is supported for AMDGPU NPM register allocation.
static MachineSchedRegistry SISchedRegistry("si", "Run SI's custom scheduler", createSIMachineScheduler)
static ScheduleDAGInstrs * createIterativeILPMachineScheduler(MachineSchedContext *C)
static bool useNoopPostScheduler(const AMDGPUOptions &CLOpts, const Function &F)
static SGPRRegisterRegAlloc defaultSGPRRegAlloc("default", "pick SGPR register allocator based on -O option", useDefaultRegisterAllocator)
static OOBFlagValue getOOBFlagValue(const Module &M, StringRef FlagName)
Returns the OOB mode encoded by a module flag.
static FunctionPass * useDefaultRegisterAllocator()
-{sgpr|wwm|vgpr}-regalloc=... command line option.
static cl::opt< bool, true > EnableObjectLinking("amdgpu-enable-object-linking", cl::desc("Enable object linking for cross-TU LDS and ABI support"), cl::location(AMDGPUTargetMachine::EnableObjectLinking), cl::init(false), cl::Hidden)
static ScheduleDAGInstrs * createGCNMaxILPMachineScheduler(MachineSchedContext *C)
static llvm::once_flag InitializeDefaultSGPRRegisterAllocatorFlag
A dummy default pass factory indicates whether the register allocator is overridden on the command li...
static FunctionPass * createFastVGPRRegisterAllocator()
static FunctionPass * createGreedyWWMRegisterAllocator()
static SGPRRegisterRegAlloc fastRegAllocSGPR("fast", "fast register allocator", createFastSGPRRegisterAllocator)
static MachineSchedRegistry GCNMinRegSchedRegistry("gcn-iterative-minreg", "Run GCN iterative scheduler for minimal register usage (experimental)", createMinRegScheduler)
static SGPRRegisterRegAlloc greedyRegAllocSGPR("greedy", "greedy register allocator", createGreedySGPRRegisterAllocator)
static void diagnoseUnsupportedCoExecSchedulerSelection(const Function &F, const GCNSubtarget &ST)
static ScheduleDAGInstrs * createGCNMaxMemoryClauseMachineScheduler(MachineSchedContext *C)
static bool onlyAllocateSGPRs(const TargetRegisterInfo &TRI, const MachineRegisterInfo &MRI, const Register Reg)
static WWMRegisterRegAlloc greedyRegAllocWWMReg("greedy", "greedy register allocator", createGreedyWWMRegisterAllocator)
static FunctionPass * createFastSGPRRegisterAllocator()
static Expected< AMDGPU::ScanOptions > parseAMDGPUAtomicOptimizerStrategy(StringRef Params)
static FunctionPass * createGreedyVGPRRegisterAllocator()
static WWMRegisterRegAlloc basicRegAllocWWMReg("basic", "basic register allocator", createBasicWWMRegisterAllocator)
static cl::opt< RegAllocType, false, RegAllocTypeParser > WWMRegAllocNPM("wwm-regalloc-npm", cl::Hidden, cl::init(RegAllocType::Default), cl::desc("Register allocator for WWM registers (new pass manager)"))
static MachineSchedRegistry IterativeGCNMaxOccupancySchedRegistry("gcn-iterative-max-occupancy-experimental", "Run GCN scheduler to maximize occupancy (experimental)", createIterativeGCNMaxOccupancyMachineScheduler)
static void initializeDefaultWWMRegisterAllocatorOnce()
static bool onlyAllocateWWMRegs(const TargetRegisterInfo &TRI, const MachineRegisterInfo &MRI, const Register Reg)
static cl::opt< WWMRegisterRegAlloc::FunctionPassCtor, false, RegisterPassParser< WWMRegisterRegAlloc > > WWMRegAlloc("wwm-regalloc", cl::Hidden, cl::init(&useDefaultRegisterAllocator), cl::desc("Register allocator to use for WWM registers"))
static cl::opt< RegAllocType, false, RegAllocTypeParser > VGPRRegAllocNPM("vgpr-regalloc-npm", cl::Hidden, cl::init(RegAllocType::Default), cl::desc("Register allocator for VGPRs (new pass manager)"))
static cl::opt< VGPRRegisterRegAlloc::FunctionPassCtor, false, RegisterPassParser< VGPRRegisterRegAlloc > > VGPRRegAlloc("vgpr-regalloc", cl::Hidden, cl::init(&useDefaultRegisterAllocator), cl::desc("Register allocator to use for VGPRs"))
LLVM_ABI LLVM_EXTERNAL_VISIBILITY void LLVMInitializeAMDGPUTarget()
static MachineSchedRegistry GCNMaxILPSchedRegistry("gcn-max-ilp", "Run GCN scheduler to maximize ilp", createGCNMaxILPMachineScheduler)
static FunctionPass * createGreedySGPRRegisterAllocator()
static LLVM_READNONE StringRef getGPUOrDefault(const Triple &TT, StringRef GPU)
Expected< AMDGPUAttributorOptions > parseAMDGPUAttributorPassOptions(StringRef Params)
static ScheduleDAGInstrs * createMinRegScheduler(MachineSchedContext *C)
static void initializeDefaultVGPRRegisterAllocatorOnce()
static ScheduleDAGInstrs * createIterativeGCNMaxOccupancyMachineScheduler(MachineSchedContext *C)
static FunctionPass * createFastWWMRegisterAllocator()
static bool mustPreserveGV(const GlobalValue &GV)
Predicate for Internalize pass.
static FunctionPass * createBasicVGPRRegisterAllocator()
static VGPRRegisterRegAlloc basicRegAllocVGPR("basic", "basic register allocator", createBasicVGPRRegisterAllocator)
static WWMRegisterRegAlloc fastRegAllocWWMReg("fast", "fast register allocator", createFastWWMRegisterAllocator)
static VGPRRegisterRegAlloc fastRegAllocVGPR("fast", "fast register allocator", createFastVGPRRegisterAllocator)
static SGPRRegisterRegAlloc basicRegAllocSGPR("basic", "basic register allocator", createBasicSGPRRegisterAllocator)
static llvm::once_flag InitializeDefaultWWMRegisterAllocatorFlag
static cl::opt< SGPRRegisterRegAlloc::FunctionPassCtor, false, RegisterPassParser< SGPRRegisterRegAlloc > > SGPRRegAlloc("sgpr-regalloc", cl::Hidden, cl::init(&useDefaultRegisterAllocator), cl::desc("Register allocator to use for SGPRs"))
static bool onlyAllocateVGPRs(const TargetRegisterInfo &TRI, const MachineRegisterInfo &MRI, const Register Reg)
static ScheduleDAGInstrs * createSIMachineScheduler(MachineSchedContext *C)
static void initializeDefaultSGPRRegisterAllocatorOnce()
static ScheduleDAGInstrs * createGCNMaxOccupancyMachineScheduler(MachineSchedContext *C)
static MachineSchedRegistry GCNILPSchedRegistry("gcn-iterative-ilp", "Run GCN iterative scheduler for ILP scheduling (experimental)", createIterativeILPMachineScheduler)
static FunctionPass * createBasicWWMRegisterAllocator()
static bool mayNeedAsyncBarrierArriveWorkaround(const Triple &TT)
static const char RegAllocOptNotSupportedMessage[]
static FunctionPass * createBasicSGPRRegisterAllocator()
static MachineSchedRegistry GCNMaxOccupancySchedRegistry("gcn-max-occupancy", "Run GCN scheduler to maximize occupancy", createGCNMaxOccupancyMachineScheduler)
The AMDGPU TargetMachine interface definition for hw codegen targets.
This file declares the AMDGPU-specific subclass of TargetLoweringObjectFile.
This file a TargetTransformInfoImplBase conforming object specific to the AMDGPU target machine.
Provides passes to inlining "always_inline" functions.
#define X(NUM, ENUM, NAME)
Definition ELF.h:665
static GCRegistry::Add< ShadowStackGC > C("shadow-stack", "Very portable GC for uncooperative code generators")
static GCRegistry::Add< ErlangGC > A("erlang", "erlang-compatible garbage collector")
static GCRegistry::Add< StatepointGC > D("statepoint-example", "an example strategy for statepoint")
This header provides classes for managing passes over SCCs of the call graph.
Provides analysis for continuously CSEing during GISel passes.
Interfaces for producing common pass manager configurations.
#define LLVM_READNONE
Definition Compiler.h:327
#define LLVM_ABI
Definition Compiler.h:211
#define LLVM_EXTERNAL_VISIBILITY
Definition Compiler.h:132
Analysis that tracks defined/used subregister lanes across COPY instructions and instructions that ge...
This file provides the interface for a simple, fast CSE pass.
This file defines the class GCNIterativeScheduler, which uses an iterative approach to find a best sc...
This file provides the interface for LLVM's Global Value Numbering pass which eliminates fully redund...
#define _
AcceleratorCodeSelection - Identify all functions reachable from a kernel, removing those that are un...
This file declares the IRTranslator pass.
Module.h This file contains the declarations for the Module class.
This header defines various interfaces for pass management in LLVM.
#define RegName(no)
This file provides the interface for LLVM's Loop Data Prefetching Pass.
This header provides classes for managing a pipeline of passes over loops in LLVM IR.
#define F(x, y, z)
Definition MD5.cpp:54
#define I(x, y, z)
Definition MD5.cpp:57
Register Reg
Register const TargetRegisterInfo * TRI
#define T
ConstantRange Range(APInt(BitWidth, Low), APInt(BitWidth, High))
uint64_t IntrinsicInst * II
#define P(N)
CGSCCAnalysisManager CGAM
LoopAnalysisManager LAM
FunctionAnalysisManager FAM
ModuleAnalysisManager MAM
PassBuilder PB(Mod->getContext(), Machine, PassOpts->PTO, std::nullopt, &PIC)
PassInstrumentationCallbacks PIC
static bool isLTOPreLink(ThinOrFullLTOPhase Phase)
The AMDGPU TargetMachine interface definition for hw codegen targets.
MachineRegisterInfo & MRI
const GCNTargetMachine & getTM(const GCNSubtarget *STI)
SI Machine Scheduler interface.
static bool contains(SmallPtrSetImpl< ConstantExpr * > &Cache, ConstantExpr *Expr, Constant *C)
Definition Value.cpp:479
static TableGen::Emitter::Opt Y("gen-skeleton-entry", EmitSkeleton, "Generate example skeleton entry")
static FunctionPass * useDefaultRegisterAllocator()
-regalloc=... command line option.
Target-Independent Code Generator Pass Configuration Options pass.
static std::unique_ptr< TargetLoweringObjectFile > createTLOF()
A manager for alias analyses.
void registerFunctionAnalysis()
Register a specific AA result.
void addAAResult(AAResultT &AAResult)
Register a specific AA result.
Legacy wrapper pass to provide the AMDGPUAAResult object.
Analysis pass providing a never-invalidated alias analysis result.
Lower llvm.global_ctors and llvm.global_dtors to special kernels.
AMDGPUTargetMachine & getAMDGPUTargetMachine() const
std::unique_ptr< CSEConfigBase > getCSEConfig() const override
Returns the CSEConfig object to use for the current optimization level.
const AMDGPUOptions & CLOpts
bool addPreISel() override
Methods with trivial inline returns are convenient points in the common codegen pass pipeline where t...
bool addInstSelector() override
addInstSelector - This method should install an instruction selector pass, which converts from LLVM c...
bool addGCPasses() override
addGCPasses - Add late codegen passes that analyze code for garbage collection.
AMDGPUPassConfig(TargetMachine &TM, PassManagerBase &PM)
bool isPassEnabled(BoolOrDefault Opt, CodeGenOptLevel Level=CodeGenOptLevel::Default) const
Check if a pass is enabled given Opt option.
void addIRPasses() override
Add common target configurable passes that perform LLVM IR to IR transforms following machine indepen...
void addCodeGenPrepare() override
Add pass to prepare the LLVM IR for code generation.
Splits the module M into N linkable partitions.
std::unique_ptr< TargetLoweringObjectFile > TLOF
unsigned getAddressSpaceForPseudoSourceKind(unsigned Kind) const override
getAddressSpaceForPseudoSourceKind - Given the kind of memory (e.g.
bool isNoopAddrSpaceCast(const DataLayout &DL, unsigned SrcAS, unsigned DestAS) const override
Returns true if a cast between SrcAS and DestAS is a noop.
void registerDefaultAliasAnalyses(AAManager &) override
Allow the target to register alias analyses with the AAManager for use with the new pass manager.
std::pair< const Value *, unsigned > getPredicatedAddrSpace(const Value *V) const override
If the specified predicate checks whether a generic pointer falls within a specified address space,...
ScheduleDAGInstrs * createMachineScheduler(MachineSchedContext *C) const override
Create an instance of ScheduleDAGInstrs to be run within the standard MachineScheduler pass for this ...
const AMDGPUOptions & CLOpts
AMDGPUTargetMachine(const Target &T, const Triple &TT, StringRef CPU, StringRef FS, const TargetOptions &Options, std::optional< Reloc::Model > RM, std::optional< CodeModel::Model > CM, CodeGenOptLevel OL)
void registerPassBuilderCallbacks(PassBuilder &PB) override
Allow the target to modify the pass pipeline.
unsigned getAssumedAddrSpace(const Value *V) const override
If the specified generic pointer could be assumed as a pointer to a specific address space,...
bool splitModule(Module &M, unsigned NumParts, function_ref< void(std::unique_ptr< Module > MPart)> ModuleCallback) override
Entry point for module splitting.
Inlines functions marked as "always_inline".
Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition ArrayRef.h:40
This class holds the attributes for a particular argument, parameter, function, or return value.
Definition Attributes.h:445
LLVM_ABI Attribute getAttribute(Attribute::AttrKind Kind) const
Return the attribute object.
Functions, function parameters, and return types can have attributes to indicate how they should be t...
Definition Attributes.h:106
LLVM_ABI StringRef getValueAsString() const
Return the attribute's value as a string.
bool isValid() const
Return true if the attribute is any kind of attribute.
Definition Attributes.h:260
This class provides access to building LLVM's passes.
CodeGenTargetMachineImpl(const Target &T, const Triple &TT, StringRef CPU, StringRef FS, const TargetOptions &Options, Reloc::Model RM, CodeModel::Model CM, CodeGenOptLevel OL)
LLVM_ABI void removeDeadConstantUsers() const
If there are any dead constant users dangling off of this constant, remove them.
A parsed version of the target data layout string in and methods for querying it.
Definition DataLayout.h:63
Diagnostic information for unsupported feature in backend.
Lightweight error class with error context and mandatory checking.
Definition Error.h:159
static ErrorSuccess success()
Create a success value.
Definition Error.h:336
Tagged union holding either a T or a Error.
Definition Error.h:485
FunctionPass class - This class is used to implement most global optimizations.
Definition Pass.h:312
LowerIntrinsics - This pass rewrites calls to the llvm.gcread or llvm.gcwrite intrinsics,...
Definition GCMetadata.h:229
const SIRegisterInfo * getRegisterInfo() const override
TargetTransformInfo getTargetTransformInfo(const Function &F) const override
Get a TargetTransformInfo implementation for the target.
const TargetSubtargetInfo * getSubtargetImpl(const Function &) const override
Virtual method implemented by subclasses that returns a reference to that target's TargetSubtargetInf...
ScheduleDAGInstrs * createPostMachineScheduler(MachineSchedContext *C) const override
Similar to createMachineScheduler but used when postRA machine scheduling is enabled.
ScheduleDAGInstrs * createMachineScheduler(MachineSchedContext *C) const override
Create an instance of ScheduleDAGInstrs to be run within the standard MachineScheduler pass for this ...
void registerMachineRegisterInfoCallback(MachineFunction &MF) const override
bool parseMachineFunctionInfo(const yaml::MachineFunctionInfo &, PerFunctionMIParsingState &PFS, SMDiagnostic &Error, SMRange &SourceRange) const override
Parse out the target's MachineFunctionInfo from the YAML reprsentation.
yaml::MachineFunctionInfo * convertFuncInfoToYAML(const MachineFunction &MF) const override
Allocate and initialize an instance of the YAML representation of the MachineFunctionInfo.
yaml::MachineFunctionInfo * createDefaultFuncInfoYAML() const override
Allocate and return a default initialized instance of the YAML representation for the MachineFunction...
Error buildCodeGenPipeline(ModulePassManager &MPM, ModuleAnalysisManager &MAM, raw_pwrite_stream &Out, raw_pwrite_stream *DwoOut, CodeGenFileType FileType, const CGPassBuilderOption &Opts, MCContext &Ctx, PassInstrumentationCallbacks *PIC) override
TargetPassConfig * createPassConfig(PassManagerBase &PM) override
Create a pass configuration object to be used by addPassToEmitX methods for generating a pipeline of ...
GCNTargetMachine(const Target &T, const Triple &TT, StringRef CPU, StringRef FS, const TargetOptions &Options, std::optional< Reloc::Model > RM, std::optional< CodeModel::Model > CM, CodeGenOptLevel OL, bool JIT)
AMDGPU::TargetIDSetting getTargetIDSettingFromModuleFlag(const Module &M, StringRef FlagName) const
Get xnack/sramecc setting from module flag or command line option (for testing).
MachineFunctionInfo * createMachineFunctionInfo(BumpPtrAllocator &Allocator, const Function &F, const TargetSubtargetInfo *STI) const override
Create the target's instance of MachineFunctionInfo.
Pass to remove unused function declarations.
Definition GlobalDCE.h:39
This pass is responsible for selecting generic machine instructions to target-specific instructions.
A pass that internalizes all functions and variables other than those that must be preserved accordin...
Definition Internalize.h:37
Converts loops into loop-closed SSA form.
Definition LCSSA.h:38
Performs Loop Invariant Code Motion Pass.
Definition LICM.h:71
static void setUseExtended(bool Enable)
This pass implements the localization mechanism described at the top of this file.
Definition Localizer.h:40
An optimization pass inserting data prefetches in loops.
Context object for machine code objects.
Definition MCContext.h:84
const TargetSubtargetInfo & getSubtarget() const
getSubtarget - Return the subtarget for which this machine code is being compiled.
MachineRegisterInfo & getRegInfo()
getRegInfo - Return information about the registers currently in use.
Ty * getInfo()
getInfo - Keep track of various per-function pieces of information for backends that would like to do...
MachineRegisterInfo - Keep track of information for virtual and physical registers,...
void addDelegate(Delegate *delegate)
MachineSchedRegistry provides a selection of available machine instruction schedulers.
This interface provides simple read-only access to a block of memory, and provides simple methods for...
virtual StringRef getBufferIdentifier() const
Return an identifier for this buffer, typically the filename it was read from.
const char * getBufferStart() const
A Module instance is used to store all the information related to an LLVM module.
Definition Module.h:68
This class provides access to building LLVM's passes.
This class manages callbacks registration, as well as provides a way for PassInstrumentation to pass ...
LLVM_ATTRIBUTE_MINSIZE std::enable_if_t<!std::is_same_v< PassT, PassManager > > addPass(PassT &&Pass)
PreservedAnalyses run(IRUnitT &IR, AnalysisManagerT &AM, ExtraArgTs... ExtraArgs)
Run all of the passes in this manager over the given unit of IR.
PassRegistry - This class manages the registration and intitialization of the pass subsystem as appli...
static LLVM_ABI PassRegistry * getPassRegistry()
getPassRegistry - Access the global registry object, which is automatically initialized at applicatio...
Pass interface - Implemented by all 'passes'.
Definition Pass.h:97
RegisterPassParser class - Handle the addition of new machine passes.
RegisterRegAllocBase class - Track the registration of register allocators.
Wrapper class representing virtual and physical registers.
Definition Register.h:20
This class keeps track of the SPI_SP_INPUT_ADDR config register, which tells the hardware which inter...
bool initializeBaseYamlFields(const yaml::SIMachineFunctionInfo &YamlMFI, const MachineFunction &MF, PerFunctionMIParsingState &PFS, SMDiagnostic &Error, SMRange &SourceRange)
void setFlag(Register Reg, uint8_t Flag)
bool checkFlag(Register Reg, uint8_t Flag) const
Instances of this class encapsulate one diagnostic report, allowing printing to a raw_ostream as a ca...
Definition SourceMgr.h:307
Represents a location in source code.
Definition SMLoc.h:22
static SMLoc getFromPointer(const char *Ptr)
Definition SMLoc.h:35
Represents a range in source code.
Definition SMLoc.h:47
A ScheduleDAG for scheduling lists of MachineInstr.
ScheduleDAGMILive is an implementation of ScheduleDAGInstrs that schedules machine instructions while...
ScheduleDAGMI is an implementation of ScheduleDAGInstrs that simply schedules machine instructions ac...
void addMutation(std::unique_ptr< ScheduleDAGMutation > Mutation)
Add a postprocessing step to the DAG builder.
const TargetInstrInfo * TII
Target instruction information.
Move instructions into successor blocks when possible.
Definition Sink.h:24
SmallString - A SmallString is just a SmallVector with methods and accessors that make it work better...
Definition SmallString.h:28
void append(StringRef RHS)
Append from a StringRef.
Definition SmallString.h:70
void push_back(const T &Elt)
unsigned getMainFileID() const
Definition SourceMgr.h:150
const MemoryBuffer * getMemoryBuffer(unsigned i) const
Definition SourceMgr.h:141
Represent a constant reference to a string, i.e.
Definition StringRef.h:56
std::pair< StringRef, StringRef > split(char Separator) const
Split into two substrings around the first occurrence of a separator character.
Definition StringRef.h:728
constexpr bool empty() const
Check if the string is empty.
Definition StringRef.h:141
bool consume_front(char Prefix)
Returns true if this StringRef has the given prefix and removes that prefix.
Definition StringRef.h:653
A switch()-like statement whose cases are string literals.
StringSwitch & Cases(std::initializer_list< StringLiteral > CaseStrings, T Value)
Primary interface to the complete machine description for the target machine.
CodeGenOptLevel getOptLevel() const
Returns the optimization level: None, Less, Default, or Aggressive.
Triple TargetTriple
Triple string, CPU name, and target feature strings the TargetMachine instance is created with.
const Triple & getTargetTriple() const
const MCSubtargetInfo & getMCSubtargetInfo() const
StringRef getTargetFeatureString() const
const DataLayout DL
DataLayout for the target: keep ABI type size and alignment.
StringRef getTargetCPU() const
std::unique_ptr< const MCSubtargetInfo > STI
TargetOptions Options
void setEnableTiedFastRegAlloc(bool Value)
std::unique_ptr< const MCRegisterInfo > MRI
CodeGenOptLevel OptLevel
void setEnableDefaultMachineVerifier(bool Enable)
Target-Independent Code Generator Pass Configuration Options.
virtual void addCodeGenPrepare()
Add pass to prepare the LLVM IR for code generation.
virtual bool addILPOpts()
Add passes that optimize instruction level parallelism for out-of-order targets.
virtual void addPostRegAlloc()
This method may be implemented by targets that want to run passes after register allocation pass pipe...
CodeGenOptLevel getOptLevel() const
virtual void addOptimizedRegAlloc()
addOptimizedRegAlloc - Add passes related to register allocation.
virtual void addIRPasses()
Add common target configurable passes that perform LLVM IR to IR transforms following machine indepen...
virtual void addFastRegAlloc()
addFastRegAlloc - Add the minimum set of target-independent passes that are required for fast registe...
virtual void addMachineSSAOptimization()
addMachineSSAOptimization - Add standard passes that optimize machine instructions in SSA form.
void disablePass(AnalysisID PassID)
Allow the target to disable a specific standard pass by default.
AnalysisID addPass(AnalysisID PassID)
Utilities for targets to add passes to the pass manager.
TargetPassConfig(TargetMachine &TM, PassManagerBase &PM)
void setEnableSSAMachineScheduler(bool Enable)
TargetRegisterInfo base class - We assume that the target defines a static array of TargetRegisterDes...
TargetSubtargetInfo - Generic base class for all target subtargets.
This pass provides access to the codegen interfaces that are needed for IR-level transformations.
Target - Wrapper for Target specific information.
Triple - Helper class for working with autoconf configuration names.
Definition Triple.h:48
bool isAMDGCN() const
Tests whether the target is AMDGCN.
Definition Triple.h:998
@ AMDGPUSubArch1250S
Definition Triple.h:275
@ AMDGPUSubArch12_5
Definition Triple.h:274
Twine - A lightweight data structure for efficiently representing the concatenation of temporary valu...
Definition Twine.h:82
LLVM Value Representation.
Definition Value.h:75
bool use_empty() const
Definition Value.h:348
An efficient, type-erasing, non-owning reference to a callable.
PassManagerBase - An abstract interface to allow code to add passes to a pass manager without having ...
Registers T with cl::parseCommandLineOptions.
An abstract base class for streams implementations that also support a pwrite operation.
Interfaces for registering analysis passes, producing common pass manager configurations,...
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
@ LOCAL_ADDRESS
Address space for local memory.
@ CONSTANT_ADDRESS
Address space for constant memory (VTX2).
@ FLAT_ADDRESS
Address space for flat memory.
@ GLOBAL_ADDRESS
Address space for global memory (RAT0, VTX0).
@ PRIVATE_ADDRESS
Address space for private memory.
constexpr StringLiteral BufferFlag("amdgpu.buffer.oob.mode")
constexpr StringLiteral TBufferFlag("amdgpu.tbuffer.oob.mode")
bool isFlatGlobalAddrSpace(unsigned AS)
LLVM_READNONE constexpr bool isModuleEntryFunctionCC(CallingConv::ID CC)
StringRef getSchedStrategy(const AMDGPUOptions &CLOpts, const Function &F)
GPUKind
GPU kinds supported by the AMDGPU target.
LLVM_READNONE constexpr bool isEntryFunctionCC(CallingConv::ID CC)
LLVM_ABI Triple::SubArchType getSubArch(GPUKind AK)
LLVM_ABI StringRef getArchNameFromSubArch(Triple::SubArchType SubArch)
Returns the canonical GPU name for an AMDGPU subarch, e.g.
LLVM_ABI GPUKind parseArchAMDGCN(StringRef CPU)
LLVM_ABI Triple::SubArchType getMajorSubArch(Triple::SubArchType SubArch)
BinaryOp_match< SrcTy, SpecificConstantMatch, TargetOpcode::G_XOR, true > m_Not(const SrcTy &&Src)
Matches a register not-ed by a G_XOR.
BinaryOp_match< LHS, RHS, Instruction::And, true > m_c_And(const LHS &L, const RHS &R)
Matches an And with LHS and RHS in either order.
bool match(Val *V, const Pattern &P)
match_deferred< Value > m_Deferred(Value *const &V)
Like m_Specific(), but works if the specific value to match is determined as part of the same match()...
auto m_Value()
Match an arbitrary value and ignore it.
auto m_Intrinsic(const Ts &...Ops)
Match intrinsic calls like this: m_Intrinsic<Intrinsic::fabs>(m_Value(X))
This namespace contains all of the command line option processing machinery.
initializer< Ty > init(const Ty &Val)
LocationClass< Ty > location(Ty &L)
std::enable_if_t< detail::IsValidPointer< X, Y >::value, X * > dyn_extract_or_null(Y &&MD)
Extract a Value from Metadata, if any, allowing null.
Definition Metadata.h:721
This is an optimization pass for GlobalISel generic memory operations.
ScheduleDAGMILive * createSchedLive(MachineSchedContext *C)
Create the standard converging machine scheduler.
LLVM_ABI FunctionPass * createFlattenCFGPass()
ModulePass * createAMDGPUSwLowerLDSLegacyPass()
std::unique_ptr< ScheduleDAGMutation > createAMDGPUBarrierLatencyDAGMutation(MachineFunction *MF)
LLVM_ABI FunctionPass * createFastRegisterAllocator()
FastRegisterAllocation Pass - This pass register allocates as fast as possible.
LLVM_ABI char & EarlyMachineLICMID
This pass performs loop invariant code motion on machine instructions.
ImmutablePass * createAMDGPUAAWrapperPass()
LLVM_ABI char & PostRAHazardRecognizerID
PostRAHazardRecognizer - This pass runs the post-ra hazard recognizer.
std::function< bool(const TargetRegisterInfo &TRI, const MachineRegisterInfo &MRI, const Register Reg)> RegAllocFilterFunc
Filter function for register classes during regalloc.
FunctionPass * createAMDGPUSetWavePriorityPass()
LLVM_ABI Pass * createLCSSAPass()
Definition LCSSA.cpp:544
void initializeAMDGPUMarkLastScratchLoadLegacyPass(PassRegistry &)
void initializeAMDGPUInsertDelayAluLegacyPass(PassRegistry &)
void initializeSIOptimizeExecMaskingPreRALegacyPass(PassRegistry &)
char & GCNPreRAOptimizationsID
LLVM_ABI char & GCLoweringID
GCLowering Pass - Used by gc.root to perform its default lowering operations.
void initializeSIInsertHardClausesLegacyPass(PassRegistry &)
FunctionPass * createSIAnnotateControlFlowLegacyPass()
Create the annotation pass.
FunctionPass * createSIModeRegisterPass()
void initializeGCNPreRAOptimizationsLegacyPass(PassRegistry &)
void initializeSILowerWWMCopiesLegacyPass(PassRegistry &)
LLVM_ABI FunctionPass * createGreedyRegisterAllocator()
Greedy register allocation pass - This pass implements a global register allocator for optimized buil...
void initializeAMDGPUAAWrapperPassPass(PassRegistry &)
void initializeSIShrinkInstructionsLegacyPass(PassRegistry &)
ModulePass * createAMDGPULowerBufferFatPointersPass()
void initializeR600ClauseMergePassPass(PassRegistry &)
ModulePass * createAMDGPUCtorDtorLoweringLegacyPass()
decltype(auto) dyn_cast(const From &Val)
dyn_cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:643
ModuleToFunctionPassAdaptor createModuleToFunctionPassAdaptor(FunctionPassT &&Pass, bool EagerlyInvalidate=false)
A function to deduce a function pass type and wrap it in the templated adaptor.
void initializeGCNRewritePartialRegUsesLegacyPass(llvm::PassRegistry &)
void initializeAMDGPURewriteUndefForPHILegacyPass(PassRegistry &)
char & GCNRewritePartialRegUsesID
void initializeAMDGPUSwLowerLDSLegacyPass(PassRegistry &)
LLVM_ABI std::error_code inconvertibleErrorCode()
The value returned by this function can be returned from convertToErrorCode for Error values where no...
Definition Error.cpp:94
void initializeAMDGPULowerVGPREncodingLegacyPass(PassRegistry &)
LLVM_ABI std::unique_ptr< ScheduleDAGMutation > createLoadClusterDAGMutation(const TargetInstrInfo *TII, bool ReorderWhileClustering=false)
If ReorderWhileClustering is set to true, no attempt will be made to reduce reordering due to store c...
char & AMDGPUWaitSGPRHazardsLegacyID
void initializeSILowerSGPRSpillsLegacyPass(PassRegistry &)
char & SILowerControlFlowLegacyID
void initializeAMDGPURegBankCombinerLegacyPass(PassRegistry &)
LLVM_ABI Pass * createLoadStoreVectorizerPass()
Create a legacy pass manager instance of the LoadStoreVectorizer pass.
FunctionPass * createAMDGPURegBankCombinerLegacy(bool IsOptLevelNone)
void initializeAMDGPUPostLegalizerCombinerLegacyPass(PassRegistry &)
std::unique_ptr< ScheduleDAGMutation > createIGroupLPDAGMutation(AMDGPU::SchedulingPhase Phase)
Phase specifes whether or not this is a reentry into the IGroupLPDAGMutation.
void initializeAMDGPUDAGToDAGISelLegacyPass(PassRegistry &)
char & AMDGPUReserveWWMRegsLegacyID
LLVM_ABI FunctionPass * createNaryReassociatePass()
void initializeAMDGPUWaitSGPRHazardsLegacyPass(PassRegistry &)
LLVM_ABI char & PatchableFunctionID
This pass implements the "patchable-function" attribute.
char & SIOptimizeExecMaskingLegacyID
LLVM_ABI char & PostRASchedulerID
PostRAScheduler - This pass performs post register allocation scheduling.
FunctionPass * createAMDGPUPostLegalizeCombinerLegacy(bool IsOptNone)
void initializeAMDGPUNextUseAnalysisLegacyPassPass(PassRegistry &)
void initializeR600ExpandSpecialInstrsPassPass(PassRegistry &)
void initializeR600PacketizerPass(PassRegistry &)
void initializeAMDGPURegBankSelectLegacyPass(PassRegistry &)
@ O1
Optimize quickly without destroying debuggability.
@ O0
Disable as many optimizations as possible.
std::unique_ptr< ScheduleDAGMutation > createVOPDPairingMutation()
ModulePass * createAMDGPUExportKernelRuntimeHandlesLegacyPass()
ModulePass * createAMDGPUAlwaysInlinePass(bool GlobalOpt=true)
void initializeAMDGPUAsmPrinterPass(PassRegistry &)
void initializeSIFoldOperandsLegacyPass(PassRegistry &)
void initializeAMDGPURegBankLegalizeLegacyPass(PassRegistry &)
char & SILoadStoreOptimizerLegacyID
void initializeAMDGPUPreLegalizerCombinerLegacyPass(PassRegistry &)
PassManager< LazyCallGraph::SCC, CGSCCAnalysisManager, LazyCallGraph &, CGSCCUpdateResult & > CGSCCPassManager
The CGSCC pass manager.
LLVM_ABI std::unique_ptr< CSEConfigBase > getStandardCSEConfigForOpt(CodeGenOptLevel Level)
Definition CSEInfo.cpp:85
Target & getTheR600Target()
The target for R600 GPUs.
LLVM_ABI char & MachineSchedulerID
MachineScheduler - This pass schedules machine instructions.
LLVM_ABI Pass * createStructurizeCFGPass(bool SkipUniformRegions=false)
When SkipUniformRegions is true the structizer will not structurize regions that only contain uniform...
LLVM_ABI char & PostMachineSchedulerID
PostMachineScheduler - This pass schedules machine instructions postRA.
LLVM_ABI std::unique_ptr< ScheduleDAGMutation > createStoreClusterDAGMutation(const TargetInstrInfo *TII, bool ReorderWhileClustering=false)
If ReorderWhileClustering is set to true, no attempt will be made to reduce reordering due to store c...
LLVM_ABI Pass * createLICMPass()
Definition LICM.cpp:346
char & SIFormMemoryClausesID
void initializeSILoadStoreOptimizerLegacyPass(PassRegistry &)
void initializeAMDGPULowerModuleLDSLegacyPass(PassRegistry &)
void initializeSIInsertAsyncBarrierArriveWorkaroundLegacyPass(PassRegistry &)
AnalysisManager< LazyCallGraph::SCC, LazyCallGraph & > CGSCCAnalysisManager
The CGSCC analysis manager.
void initializeAMDGPUCtorDtorLoweringLegacyPass(PassRegistry &)
LLVM_ABI char & EarlyIfConverterLegacyID
EarlyIfConverter - This pass performs if-conversion on SSA form by inserting cmov instructions.
AnalysisManager< Loop, LoopStandardAnalysisResults & > LoopAnalysisManager
The loop analysis manager.
FunctionPass * createAMDGPUUniformIntrinsicCombineLegacyPass()
ThinOrFullLTOPhase
This enumerates the LLVM full LTO or ThinLTO optimization phases.
Definition Pass.h:75
@ FullLTOPreLink
Full LTO prelink phase.
Definition Pass.h:83
@ FullLTOPostLink
Full LTO postlink (backend compile) phase.
Definition Pass.h:85
@ ThinLTOPreLink
ThinLTO prelink (summary) phase.
Definition Pass.h:79
char & AMDGPUUnifyDivergentExitNodesID
void initializeAMDGPUPrepareAGPRAllocLegacyPass(PassRegistry &)
FunctionPass * createAMDGPUPreloadKernArgPrologLegacyPass()
LLVM_ABI char & MachineLoopInfoID
MachineLoopInfo - This pass is a loop analysis pass.
char & SIOptimizeVGPRLiveRangeLegacyID
LLVM_ABI char & ShadowStackGCLoweringID
ShadowStackGCLowering - Implements the custom lowering mechanism used by the shadow stack GC.
char & GCNNSAReassignID
void initializeAMDGPURewriteOutArgumentsPass(PassRegistry &)
static Reloc::Model getEffectiveRelocModel(std::optional< Reloc::Model > RM)
void initializeAMDGPUExternalAAWrapperPass(PassRegistry &)
char & SIFoldOperandsLegacyID
auto formatv(bool Validate, const char *Fmt, Ts &&...Vals)
void initializeAMDGPULowerKernelArgumentsPass(PassRegistry &)
void initializeSIModeRegisterLegacyPass(PassRegistry &)
CodeModel::Model getEffectiveCodeModel(std::optional< CodeModel::Model > CM, CodeModel::Model Default)
Helper method for getting the code model, returning Default if CM does not have a value.
void initializeAMDGPUPreloadKernelArgumentsLegacyPass(PassRegistry &)
LLVM_ABI ModulePass * createExpandVariadicsPass(ExpandVariadicsMode)
char & SILateBranchLoweringPassID
FunctionToLoopPassAdaptor createFunctionToLoopPassAdaptor(LoopPassT &&Pass, bool UseMemorySSA=false)
A function to deduce a loop pass type and wrap it in the templated adaptor.
char & SIPostRA16BitMovFoldingLegacyID
LLVM_ABI char & BranchRelaxationPassID
BranchRelaxation - This pass replaces branches that need to jump further than is supported by a branc...
LLVM_ABI FunctionPass * createSinkingPass()
Definition Sink.cpp:274
CGSCCToFunctionPassAdaptor createCGSCCToFunctionPassAdaptor(FunctionPassT &&Pass, bool EagerlyInvalidate=false, bool NoRerun=false)
A function to deduce a function pass type and wrap it in the templated adaptor.
void initializeSIMemoryLegalizerLegacyPass(PassRegistry &)
ModulePass * createAMDGPULowerIntrinsicsLegacyPass()
decltype(auto) get(const PointerIntPair< PointerTy, IntBits, IntType, PtrTraits, Info > &Pair)
void initializeR600MachineCFGStructurizerPass(PassRegistry &)
CodeGenFileType
These enums are meant to be passed into addPassesToEmitFile to indicate what type of file to emit,...
Definition CodeGen.h:309
char & GCNDPPCombineLegacyID
FunctionPass * createSIInsertAsyncBarrierArriveWorkaroundPass()
PassManager< Module > ModulePassManager
Convenience typedef for a pass manager over modules.
LLVM_ABI FunctionPass * createLoopDataPrefetchPass()
FunctionPass * createAMDGPULowerKernelArgumentsPass()
char & AMDGPUInsertDelayAluID
std::unique_ptr< ScheduleDAGMutation > createAMDGPUMacroFusionDAGMutation()
Note that you have to add: DAG.addMutation(createAMDGPUMacroFusionDAGMutation()); to AMDGPUTargetMach...
LLVM_ABI char & StackMapLivenessID
StackMapLiveness - This pass analyses the register live-out set of stackmap/patchpoint intrinsics and...
void initializeGCNPreRALongBranchRegLegacyPass(PassRegistry &)
char & SILowerWWMCopiesLegacyID
LLVM_ABI FunctionPass * createUnifyLoopExitsPass()
char & SIOptimizeExecMaskingPreRAID
LLVM_ABI FunctionPass * createFixIrreduciblePass()
void initializeR600EmitClauseMarkersPass(PassRegistry &)
LLVM_ABI char & FuncletLayoutID
This pass lays out funclets contiguously.
LLVM_ABI char & DetectDeadLanesID
This pass adds dead/undef flags after analyzing subregister lanes.
void initializeAMDGPULowerExecSyncLegacyPass(PassRegistry &)
ScheduleDAGInstrs * createGCNNoopPostMachineScheduler(MachineSchedContext *C)
void initializeAMDGPUExportKernelRuntimeHandlesLegacyPass(PassRegistry &)
LLVM_ABI FunctionPass * createRegAllocScoringPass()
When learning an eviction policy, extract score(reward) information, otherwise this does nothing.
CodeGenOptLevel
Code generation optimization level.
Definition CodeGen.h:280
void initializeSIInsertWaitcntsLegacyPass(PassRegistry &)
LLVM_ABI CGPassBuilderOption getCGPassBuilderOption(const TargetMachine &TM)
ModulePass * createAMDGPUPreloadKernelArgumentsLegacyPass(const TargetMachine *)
ModulePass * createAMDGPUPrintfRuntimeBinding()
LLVM_ABI char & StackSlotColoringID
StackSlotColoring - This pass performs stack slot coloring.
LLVM_ABI Pass * createAlwaysInlinerLegacyPass(bool InsertLifetime=true)
Create a legacy pass manager instance of a pass to inline and remove functions marked as "always_inli...
void initializeR600ControlFlowFinalizerPass(PassRegistry &)
void initializeAMDGPUImageIntrinsicOptimizerPass(PassRegistry &)
void initializeSILateBranchLoweringLegacyPass(PassRegistry &)
void initializeSILowerControlFlowLegacyPass(PassRegistry &)
void initializeSIFormMemoryClausesLegacyPass(PassRegistry &)
char & SIPreAllocateWWMRegsLegacyID
Error make_error(ArgTs &&... Args)
Make a Error instance representing failure using the given error info type.
Definition Error.h:340
ModulePass * createAMDGPULowerModuleLDSLegacyPass(const AMDGPUTargetMachine *TM=nullptr)
FunctionPass * createAMDGPUPromoteAlloca()
LLVM_ABI FunctionPass * createSeparateConstOffsetFromGEPPass(bool LowerGEP=false)
void initializeAMDGPUReserveWWMRegsLegacyPass(PassRegistry &)
char & SIPreEmitPeepholeID
char & SIPostRABundlerLegacyID
ModulePass * createAMDGPURemoveIncompatibleFunctionsPass(const TargetMachine *)
void initializeGCNRegPressurePrinterPass(PassRegistry &)
void initializeSILowerI1CopiesLegacyPass(PassRegistry &)
LLVM_ABI ImmutablePass * createExternalAAWrapperPass(std::function< void(Pass &, Function &, AAResults &)> Callback, bool RunEarly=false)
A wrapper pass around a callback which can be used to populate the AAResults in the AAResultsWrapperP...
char & SILowerSGPRSpillsLegacyID
LLVM_ABI FunctionPass * createBasicRegisterAllocator()
BasicRegisterAllocation Pass - This pass implements a degenerate global register allocator using the ...
LLVM_ABI void initializeGlobalISel(PassRegistry &)
Initialize all passes linked into the GlobalISel library.
ModulePass * createR600OpenCLImageTypeLoweringPass()
void initializeSIAnnotateControlFlowLegacyPass(PassRegistry &)
FunctionPass * createAMDGPUISelDag(TargetMachine &TM, CodeGenOptLevel OptLevel)
This pass converts a legalized DAG into a AMDGPU-specific.
void initializeGCNCreateVOPDLegacyPass(PassRegistry &)
void initializeAMDGPUUniformIntrinsicCombineLegacyPass(PassRegistry &)
ScheduleDAGInstrs * createGCNCoExecMachineScheduler(MachineSchedContext *C)
void initializeSIPreAllocateWWMRegsLegacyPass(PassRegistry &)
void initializeSIFixVGPRCopiesLegacyPass(PassRegistry &)
Target & getTheGCNTarget()
The target for GCN GPUs.
void initializeSIFixSGPRCopiesLegacyPass(PassRegistry &)
void initializeAMDGPUAtomicOptimizerPass(PassRegistry &)
void initializeAMDGPULowerIntrinsicsLegacyPass(PassRegistry &)
LLVM_ABI FunctionPass * createGVNPass()
Definition GVN.cpp:4474
void initializeAMDGPURewriteAGPRCopyMFMALegacyPass(PassRegistry &)
void initializeAMDGPUNextUseAnalysisPrinterLegacyPassPass(PassRegistry &)
void initializeSIPostRABundlerLegacyPass(PassRegistry &)
LLVM_ABI char & MachineCSELegacyID
MachineCSE - This pass performs global CSE on machine instructions.
char & SIWholeQuadModeID
PassManager< Function > FunctionPassManager
Convenience typedef for a pass manager over functions.
void initializeAMDGPUCodeGenPreparePass(PassRegistry &)
FunctionPass * createAMDGPURewriteUndefForPHILegacyPass()
void initializeSIOptimizeExecMaskingLegacyPass(PassRegistry &)
void call_once(once_flag &flag, Function &&F, Args &&... ArgList)
Execute the function specified as a parameter once.
Definition Threading.h:86
FunctionPass * createSILowerI1CopiesLegacyPass()
FunctionPass * createAMDGPURegBankSelectLegacyPass()
void initializeAMDGPULowerKernelAttributesPass(PassRegistry &)
char & SIInsertHardClausesID
char & SIFixSGPRCopiesLegacyID
void initializeGCNDPPCombineLegacyPass(PassRegistry &)
char & GCNCreateVOPDID
char & SIPeepholeSDWALegacyID
LLVM_ABI char & VirtRegRewriterID
VirtRegRewriter pass.
char & SIFixVGPRCopiesID
void initializeGCNNSAReassignLegacyPass(PassRegistry &)
LLVM_ABI FunctionPass * createLowerSwitchPass()
void initializeAMDGPUPreloadKernArgPrologLegacyPass(PassRegistry &)
Target & getTheGCNLegacyTarget()
The target for GCN GPUs, registered under the legacy "amdgcn" architecture name for use with -march.
LLVM_ABI FunctionPass * createVirtRegRewriter(bool ClearVirtRegs=true)
void initializeR600VectorRegMergerPass(PassRegistry &)
char & AMDGPURewriteAGPRCopyMFMALegacyID
ModulePass * createAMDGPULowerExecSyncLegacyPass()
constexpr bool valueOr(BoolOrDefault X, bool Default)
char & AMDGPULowerVGPREncodingLegacyID
FunctionPass * createAMDGPUGlobalISelDivergenceLoweringPass()
FunctionPass * createAMDGPUPreLegalizeCombinerLegacyPass(bool IsOptLevelNone)
FunctionPass * createSIMemoryLegalizerPass()
void initializeAMDGPULateCodeGenPrepareLegacyPass(PassRegistry &)
void initializeSIOptimizeVGPRLiveRangeLegacyPass(PassRegistry &)
void initializeSIPeepholeSDWALegacyPass(PassRegistry &)
LLVM_ABI char & TwoAddressInstructionPassID
TwoAddressInstruction - This pass reduces two-address instructions to use two operands.
AnalysisManager< Function > FunctionAnalysisManager
Convenience typedef for the Function analysis manager.
FunctionPass * createAMDGPULateCodeGenPrepareLegacyPass()
LLVM_ABI FunctionPass * createAtomicExpandLegacyPass()
AtomicExpandPass - At IR level this pass replace atomic instructions with __atomic_* library calls,...
void initializeAMDGPUGlobalISelDivergenceLoweringLegacyPass(PassRegistry &)
MCRegisterInfo * createGCNMCRegisterInfo(AMDGPUDwarfFlavour DwarfFlavour)
LLVM_ABI FunctionPass * createStraightLineStrengthReducePass()
BumpPtrAllocatorImpl<> BumpPtrAllocator
The standard BumpPtrAllocator which just uses the default template parameters.
Definition Allocator.h:391
FunctionPass * createAMDGPUImageIntrinsicOptimizerPass(const TargetMachine *)
void initializeAMDGPULowerBufferFatPointersPass(PassRegistry &)
void initializeAMDGPUUnifyDivergentExitNodesLegacyPass(PassRegistry &)
FunctionPass * createSIInsertWaitcntsPass()
FunctionPass * createAMDGPUAnnotateUniformValuesLegacy()
LLVM_ABI FunctionPass * createEarlyCSEPass(bool UseMemorySSA=false)
void initializeSIWholeQuadModeLegacyPass(PassRegistry &)
LLVM_ABI char & PHIEliminationID
PHIElimination - This pass eliminates machine instruction PHI nodes by inserting copy instructions.
LLVM_ABI llvm::cl::opt< bool > NoKernelInfoEndLTO
LLVM_ABI bool parseNamedRegisterReference(PerFunctionMIParsingState &PFS, Register &Reg, StringRef Src, SMDiagnostic &Error)
FunctionPass * createAMDGPUAtomicOptimizerPass(AMDGPU::ScanOptions ScanStrategy)
void initializeAMDGPUResourceUsageAnalysisWrapperPassPass(PassRegistry &)
FunctionPass * createSIShrinkInstructionsLegacyPass()
char & AMDGPUPrepareAGPRAllocLegacyID
char & AMDGPUMarkLastScratchLoadID
LLVM_ABI char & RenameIndependentSubregsID
This pass detects subregister lanes in a virtual register that are used independently of other lanes ...
void initializeAMDGPUAnnotateUniformValuesLegacyPass(PassRegistry &)
std::unique_ptr< ScheduleDAGMutation > createAMDGPUExportClusteringDAGMutation()
void initializeAMDGPUPrintfRuntimeBindingPass(PassRegistry &)
void initializeAMDGPUPromoteAllocaPass(PassRegistry &)
void initializeAMDGPURemoveIncompatibleFunctionsLegacyPass(PassRegistry &)
std::unique_ptr< ScheduleDAGMutation > createAMDGPUHazardLatencyDAGMutation(MachineFunction *MF)
void initializeAMDGPUAlwaysInlinePass(PassRegistry &)
LLVM_ABI char & DeadMachineInstructionElimID
DeadMachineInstructionElim - This pass removes dead machine instructions.
const void * AnalysisID
Definition Pass.h:51
void initializeSIPreEmitPeepholeLegacyPass(PassRegistry &)
AnalysisManager< Module > ModuleAnalysisManager
Convenience typedef for the Module analysis manager.
Definition MIRParser.h:39
char & AMDGPUPerfHintAnalysisLegacyID
char & GCNPreRALongBranchRegID
FunctionPass * createAMDGPUCodeGenPreparePass(bool ExpandDiv64InIR)
void initializeSIPostRA16BitMovFoldingLegacyPass(PassRegistry &)
FunctionPass * createAMDGPURegBankLegalizeLegacyPass()
MCRegisterClass TargetRegisterClass
Definition FastISel.h:58
LLVM_ABI void reportFatalUsageError(Error Err)
Report a fatal error that does not indicate a bug in LLVM.
Definition Error.cpp:177
void initializeAMDGPUPromoteKernelArgumentsPass(PassRegistry &)
#define N
static ArgDescriptor createStack(unsigned Offset, unsigned Mask=~0u)
static ArgDescriptor createArg(const ArgDescriptor &Arg, unsigned Mask)
static ArgDescriptor createRegister(Register Reg, unsigned Mask=~0u)
cl::boolOrDefault EnableGlobalISelOption
DenormalModeKind Input
Denormal treatment kind for floating point instruction inputs in the default floating-point environme...
@ PreserveSign
The sign of a flushed-to-zero number is preserved in the sign of 0.
@ IEEE
IEEE-754 denormal numbers preserved.
DenormalModeKind Output
Denormal flushing mode for floating point instruction results in the default floating point environme...
A simple and fast domtree-based CSE pass.
Definition EarlyCSE.h:31
MachineFunctionInfo - This class can be derived from and used by targets to hold private target-speci...
static FuncInfoTy * create(BumpPtrAllocator &Allocator, const Function &F, const SubtargetTy *STI)
Factory function: default behavior is to call new using the supplied allocator.
MachineSchedContext provides enough context from the MachineScheduler pass for the target to instanti...
StringMap< VRegInfo * > VRegInfosNamed
Definition MIParser.h:180
DenseMap< Register, VRegInfo * > VRegInfos
Definition MIParser.h:179
RegisterTargetMachine - Helper template for registering a target machine implementation,...
bool DX10Clamp
Used by the vector ALU to force DX10-style treatment of NaNs: when set, clamp NaN to zero; otherwise,...
DenormalMode FP64FP16Denormals
If this is set, neither input or output denormals are flushed for both f64 and f16/v2f16 instructions...
bool IEEE
Floating point opcodes that support exception flag gathering quiet and propagate signaling NaN inputs...
DenormalMode FP32Denormals
If this is set, neither input or output denormals are flushed for most f32 instructions.
The llvm::once_flag structure.
Definition Threading.h:67
Targets should override this in a way that mirrors the implementation of llvm::MachineFunctionInfo.
SmallVector< StringValue > WWMReservedRegs
std::optional< SIArgumentInfo > ArgInfo
SmallVector< StringValue, 2 > SpillPhysVGPRS
A wrapper around std::string which contains a source range that's being set during parsing.