LLVM 23.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"
24#include "AMDGPUHazardLatency.h"
25#include "AMDGPUIGroupLP.h"
26#include "AMDGPUISelDAGToDAG.h"
28#include "AMDGPUMacroFusion.h"
35#include "AMDGPUSplitModule.h"
40#include "GCNDPPCombine.h"
42#include "GCNNSAReassign.h"
46#include "GCNSchedStrategy.h"
47#include "GCNVOPDUtils.h"
48#include "R600.h"
49#include "R600TargetMachine.h"
50#include "SIFixSGPRCopies.h"
51#include "SIFixVGPRCopies.h"
52#include "SIFoldOperands.h"
53#include "SIFormMemoryClauses.h"
55#include "SILowerControlFlow.h"
56#include "SILowerSGPRSpills.h"
57#include "SILowerWWMCopies.h"
59#include "SIMachineScheduler.h"
63#include "SIPeepholeSDWA.h"
64#include "SIPostRABundler.h"
67#include "SIWholeQuadMode.h"
88#include "llvm/CodeGen/Passes.h"
92#include "llvm/IR/IntrinsicsAMDGPU.h"
93#include "llvm/IR/PassManager.h"
102#include "llvm/Transforms/IPO.h"
127#include <optional>
128
129using namespace llvm;
130using namespace llvm::PatternMatch;
131
132namespace {
133//===----------------------------------------------------------------------===//
134// AMDGPU CodeGen Pass Builder interface.
135//===----------------------------------------------------------------------===//
136
137class AMDGPUCodeGenPassBuilder
138 : public CodeGenPassBuilder<AMDGPUCodeGenPassBuilder, GCNTargetMachine> {
139 using Base = CodeGenPassBuilder<AMDGPUCodeGenPassBuilder, GCNTargetMachine>;
140
141public:
142 AMDGPUCodeGenPassBuilder(GCNTargetMachine &TM,
143 const CGPassBuilderOption &Opts,
144 PassInstrumentationCallbacks *PIC);
145
146 void addIRPasses(PassManagerWrapper &PMW) const;
147 void addCodeGenPrepare(PassManagerWrapper &PMW) const;
148 void addPreISel(PassManagerWrapper &PMW) const;
149 void addILPOpts(PassManagerWrapper &PMWM) const;
150 void addAsmPrinterBegin(PassManagerWrapper &PMW, CreateMCStreamer) const;
151 void addAsmPrinter(PassManagerWrapper &PMW, CreateMCStreamer) const;
152 void addAsmPrinterEnd(PassManagerWrapper &PMW, CreateMCStreamer) const;
153 Error addInstSelector(PassManagerWrapper &PMW) const;
154 void addPreRewrite(PassManagerWrapper &PMW) const;
155 void addMachineSSAOptimization(PassManagerWrapper &PMW) const;
156 void addPostRegAlloc(PassManagerWrapper &PMW) const;
157 void addPreEmitPass(PassManagerWrapper &PMWM) const;
158 void addPreEmitRegAlloc(PassManagerWrapper &PMW) const;
159 Error addRegAssignmentFast(PassManagerWrapper &PMW) const;
160 Error addRegAssignmentOptimized(PassManagerWrapper &PMW) const;
161 void addPreRegAlloc(PassManagerWrapper &PMW) const;
162 Error addFastRegAlloc(PassManagerWrapper &PMW) const;
163 Error addOptimizedRegAlloc(PassManagerWrapper &PMW) const;
164 void addPreSched2(PassManagerWrapper &PMW) const;
165 void addPostBBSections(PassManagerWrapper &PMW) const;
166
167private:
168 Error validateRegAllocOptions() const;
169
170public:
171 /// Check if a pass is enabled given \p Opt option. The option always
172 /// overrides defaults if explicitly used. Otherwise its default will be used
173 /// given that a pass shall work at an optimization \p Level minimum.
174 bool isPassEnabled(const cl::opt<bool> &Opt,
175 CodeGenOptLevel Level = CodeGenOptLevel::Default) const;
176 void addEarlyCSEOrGVNPass(PassManagerWrapper &PMW) const;
177 void addStraightLineScalarOptimizationPasses(PassManagerWrapper &PMW) const;
178};
179
180class SGPRRegisterRegAlloc : public RegisterRegAllocBase<SGPRRegisterRegAlloc> {
181public:
182 SGPRRegisterRegAlloc(const char *N, const char *D, FunctionPassCtor C)
183 : RegisterRegAllocBase(N, D, C) {}
184};
185
186class VGPRRegisterRegAlloc : public RegisterRegAllocBase<VGPRRegisterRegAlloc> {
187public:
188 VGPRRegisterRegAlloc(const char *N, const char *D, FunctionPassCtor C)
189 : RegisterRegAllocBase(N, D, C) {}
190};
191
192class WWMRegisterRegAlloc : public RegisterRegAllocBase<WWMRegisterRegAlloc> {
193public:
194 WWMRegisterRegAlloc(const char *N, const char *D, FunctionPassCtor C)
195 : RegisterRegAllocBase(N, D, C) {}
196};
197
198static bool onlyAllocateSGPRs(const TargetRegisterInfo &TRI,
200 const Register Reg) {
201 const TargetRegisterClass *RC = MRI.getRegClass(Reg);
202 return static_cast<const SIRegisterInfo &>(TRI).isSGPRClass(RC);
203}
204
205static bool onlyAllocateVGPRs(const TargetRegisterInfo &TRI,
207 const Register Reg) {
208 const TargetRegisterClass *RC = MRI.getRegClass(Reg);
209 return !static_cast<const SIRegisterInfo &>(TRI).isSGPRClass(RC);
210}
211
212static bool onlyAllocateWWMRegs(const TargetRegisterInfo &TRI,
214 const Register Reg) {
215 const SIMachineFunctionInfo *MFI =
216 MRI.getMF().getInfo<SIMachineFunctionInfo>();
217 const TargetRegisterClass *RC = MRI.getRegClass(Reg);
218 return !static_cast<const SIRegisterInfo &>(TRI).isSGPRClass(RC) &&
220}
221
222/// -{sgpr|wwm|vgpr}-regalloc=... command line option.
223static FunctionPass *useDefaultRegisterAllocator() { return nullptr; }
224
225/// A dummy default pass factory indicates whether the register allocator is
226/// overridden on the command line.
227static llvm::once_flag InitializeDefaultSGPRRegisterAllocatorFlag;
228static llvm::once_flag InitializeDefaultVGPRRegisterAllocatorFlag;
229static llvm::once_flag InitializeDefaultWWMRegisterAllocatorFlag;
230
231static SGPRRegisterRegAlloc
232defaultSGPRRegAlloc("default",
233 "pick SGPR register allocator based on -O option",
235
236static cl::opt<SGPRRegisterRegAlloc::FunctionPassCtor, false,
238SGPRRegAlloc("sgpr-regalloc", cl::Hidden, cl::init(&useDefaultRegisterAllocator),
239 cl::desc("Register allocator to use for SGPRs"));
240
241static cl::opt<VGPRRegisterRegAlloc::FunctionPassCtor, false,
243VGPRRegAlloc("vgpr-regalloc", cl::Hidden, cl::init(&useDefaultRegisterAllocator),
244 cl::desc("Register allocator to use for VGPRs"));
245
246static cl::opt<WWMRegisterRegAlloc::FunctionPassCtor, false,
248 WWMRegAlloc("wwm-regalloc", cl::Hidden,
250 cl::desc("Register allocator to use for WWM registers"));
251
252// New pass manager register allocator options for AMDGPU
254 "sgpr-regalloc-npm", cl::Hidden, cl::init(RegAllocType::Default),
255 cl::desc("Register allocator for SGPRs (new pass manager)"));
256
258 "vgpr-regalloc-npm", cl::Hidden, cl::init(RegAllocType::Default),
259 cl::desc("Register allocator for VGPRs (new pass manager)"));
260
262 "wwm-regalloc-npm", cl::Hidden, cl::init(RegAllocType::Default),
263 cl::desc("Register allocator for WWM registers (new pass manager)"));
264
265/// Check if the given RegAllocType is supported for AMDGPU NPM register
266/// allocation. Only Fast and Greedy are supported; Basic and PBQP are not.
267static Error checkRegAllocSupported(RegAllocType RAType, StringRef RegName) {
268 if (RAType == RegAllocType::Basic || RAType == RegAllocType::PBQP) {
270 Twine("unsupported register allocator '") +
271 (RAType == RegAllocType::Basic ? "basic" : "pbqp") + "' for " +
272 RegName + " registers",
274 }
275 return Error::success();
276}
277
278Error AMDGPUCodeGenPassBuilder::validateRegAllocOptions() const {
279 // 1. Generic --regalloc-npm is not supported for AMDGPU.
280 if (Opt.RegAlloc != RegAllocType::Unset) {
282 "-regalloc-npm not supported for amdgcn. Use -sgpr-regalloc-npm, "
283 "-vgpr-regalloc-npm, and -wwm-regalloc-npm",
285 }
286
287 // 2. Legacy PM regalloc options are not compatible with NPM.
288 if (SGPRRegAlloc.getNumOccurrences() > 0 ||
289 VGPRRegAlloc.getNumOccurrences() > 0 ||
290 WWMRegAlloc.getNumOccurrences() > 0) {
292 "-sgpr-regalloc, -vgpr-regalloc, and -wwm-regalloc are legacy PM "
293 "options. Use -sgpr-regalloc-npm, -vgpr-regalloc-npm, and "
294 "-wwm-regalloc-npm with the new pass manager",
296 }
297
298 // 3. Only Fast and Greedy allocators are supported for AMDGPU.
299 if (auto Err = checkRegAllocSupported(SGPRRegAllocNPM, "SGPR"))
300 return Err;
301 if (auto Err = checkRegAllocSupported(WWMRegAllocNPM, "WWM"))
302 return Err;
303 if (auto Err = checkRegAllocSupported(VGPRRegAllocNPM, "VGPR"))
304 return Err;
305
306 return Error::success();
307}
308
309static void initializeDefaultSGPRRegisterAllocatorOnce() {
310 RegisterRegAlloc::FunctionPassCtor Ctor = SGPRRegisterRegAlloc::getDefault();
311
312 if (!Ctor) {
313 Ctor = SGPRRegAlloc;
314 SGPRRegisterRegAlloc::setDefault(SGPRRegAlloc);
315 }
316}
317
318static void initializeDefaultVGPRRegisterAllocatorOnce() {
319 RegisterRegAlloc::FunctionPassCtor Ctor = VGPRRegisterRegAlloc::getDefault();
320
321 if (!Ctor) {
322 Ctor = VGPRRegAlloc;
323 VGPRRegisterRegAlloc::setDefault(VGPRRegAlloc);
324 }
325}
326
327static void initializeDefaultWWMRegisterAllocatorOnce() {
328 RegisterRegAlloc::FunctionPassCtor Ctor = WWMRegisterRegAlloc::getDefault();
329
330 if (!Ctor) {
331 Ctor = WWMRegAlloc;
332 WWMRegisterRegAlloc::setDefault(WWMRegAlloc);
333 }
334}
335
336static FunctionPass *createBasicSGPRRegisterAllocator() {
337 return createBasicRegisterAllocator(onlyAllocateSGPRs);
338}
339
340static FunctionPass *createGreedySGPRRegisterAllocator() {
341 return createGreedyRegisterAllocator(onlyAllocateSGPRs);
342}
343
344static FunctionPass *createFastSGPRRegisterAllocator() {
345 return createFastRegisterAllocator(onlyAllocateSGPRs, false);
346}
347
348static FunctionPass *createBasicVGPRRegisterAllocator() {
349 return createBasicRegisterAllocator(onlyAllocateVGPRs);
350}
351
352static FunctionPass *createGreedyVGPRRegisterAllocator() {
353 return createGreedyRegisterAllocator(onlyAllocateVGPRs);
354}
355
356static FunctionPass *createFastVGPRRegisterAllocator() {
357 return createFastRegisterAllocator(onlyAllocateVGPRs, true);
358}
359
360static FunctionPass *createBasicWWMRegisterAllocator() {
361 return createBasicRegisterAllocator(onlyAllocateWWMRegs);
362}
363
364static FunctionPass *createGreedyWWMRegisterAllocator() {
365 return createGreedyRegisterAllocator(onlyAllocateWWMRegs);
366}
367
368static FunctionPass *createFastWWMRegisterAllocator() {
369 return createFastRegisterAllocator(onlyAllocateWWMRegs, false);
370}
371
372static SGPRRegisterRegAlloc basicRegAllocSGPR(
373 "basic", "basic register allocator", createBasicSGPRRegisterAllocator);
374static SGPRRegisterRegAlloc greedyRegAllocSGPR(
375 "greedy", "greedy register allocator", createGreedySGPRRegisterAllocator);
376
377static SGPRRegisterRegAlloc fastRegAllocSGPR(
378 "fast", "fast register allocator", createFastSGPRRegisterAllocator);
379
380
381static VGPRRegisterRegAlloc basicRegAllocVGPR(
382 "basic", "basic register allocator", createBasicVGPRRegisterAllocator);
383static VGPRRegisterRegAlloc greedyRegAllocVGPR(
384 "greedy", "greedy register allocator", createGreedyVGPRRegisterAllocator);
385
386static VGPRRegisterRegAlloc fastRegAllocVGPR(
387 "fast", "fast register allocator", createFastVGPRRegisterAllocator);
388static WWMRegisterRegAlloc basicRegAllocWWMReg("basic",
389 "basic register allocator",
390 createBasicWWMRegisterAllocator);
391static WWMRegisterRegAlloc
392 greedyRegAllocWWMReg("greedy", "greedy register allocator",
393 createGreedyWWMRegisterAllocator);
394static WWMRegisterRegAlloc fastRegAllocWWMReg("fast", "fast register allocator",
395 createFastWWMRegisterAllocator);
396
398 return Phase == ThinOrFullLTOPhase::FullLTOPreLink ||
399 Phase == ThinOrFullLTOPhase::ThinLTOPreLink;
400}
401} // anonymous namespace
402
403static cl::opt<bool>
405 cl::desc("Run early if-conversion"),
406 cl::init(false));
407
408static cl::opt<bool>
409OptExecMaskPreRA("amdgpu-opt-exec-mask-pre-ra", cl::Hidden,
410 cl::desc("Run pre-RA exec mask optimizations"),
411 cl::init(true));
412
413static cl::opt<bool>
414 LowerCtorDtor("amdgpu-lower-global-ctor-dtor",
415 cl::desc("Lower GPU ctor / dtors to globals on the device."),
416 cl::init(true), cl::Hidden);
417
418// Option to disable vectorizer for tests.
420 "amdgpu-load-store-vectorizer",
421 cl::desc("Enable load store vectorizer"),
422 cl::init(true),
423 cl::Hidden);
424
425// Option to control global loads scalarization
427 "amdgpu-scalarize-global-loads",
428 cl::desc("Enable global load scalarization"),
429 cl::init(true),
430 cl::Hidden);
431
432// Option to run internalize pass.
434 "amdgpu-internalize-symbols",
435 cl::desc("Enable elimination of non-kernel functions and unused globals"),
436 cl::init(false),
437 cl::Hidden);
438
439// Option to inline all early.
441 "amdgpu-early-inline-all",
442 cl::desc("Inline all functions early"),
443 cl::init(false),
444 cl::Hidden);
445
447 "amdgpu-enable-remove-incompatible-functions", cl::Hidden,
448 cl::desc("Enable removal of functions when they"
449 "use features not supported by the target GPU"),
450 cl::init(true));
451
453 "amdgpu-sdwa-peephole",
454 cl::desc("Enable SDWA peepholer"),
455 cl::init(true));
456
458 "amdgpu-dpp-combine",
459 cl::desc("Enable DPP combiner"),
460 cl::init(true));
461
462// Enable address space based alias analysis
464 cl::desc("Enable AMDGPU Alias Analysis"),
465 cl::init(true));
466
467// Enable lib calls simplifications
469 "amdgpu-simplify-libcall",
470 cl::desc("Enable amdgpu library simplifications"),
471 cl::init(true),
472 cl::Hidden);
473
475 "amdgpu-ir-lower-kernel-arguments",
476 cl::desc("Lower kernel argument loads in IR pass"),
477 cl::init(true),
478 cl::Hidden);
479
481 "amdgpu-reassign-regs",
482 cl::desc("Enable register reassign optimizations on gfx10+"),
483 cl::init(true),
484 cl::Hidden);
485
487 "amdgpu-opt-vgpr-liverange",
488 cl::desc("Enable VGPR liverange optimizations for if-else structure"),
489 cl::init(true), cl::Hidden);
490
492 "amdgpu-atomic-optimizer-strategy",
493 cl::desc("Select DPP or Iterative strategy for scan"),
496 clEnumValN(ScanOptions::DPP, "DPP", "Use DPP operations for scan"),
498 "Use Iterative approach for scan"),
499 clEnumValN(ScanOptions::None, "None", "Disable atomic optimizer")));
500
501// Enable Mode register optimization
503 "amdgpu-mode-register",
504 cl::desc("Enable mode register pass"),
505 cl::init(true),
506 cl::Hidden);
507
508// Enable GFX11+ s_delay_alu insertion
509static cl::opt<bool>
510 EnableInsertDelayAlu("amdgpu-enable-delay-alu",
511 cl::desc("Enable s_delay_alu insertion"),
512 cl::init(true), cl::Hidden);
513
514// Enable GFX11+ VOPD
515static cl::opt<bool>
516 EnableVOPD("amdgpu-enable-vopd",
517 cl::desc("Enable VOPD, dual issue of VALU in wave32"),
518 cl::init(true), cl::Hidden);
519
520// Option is used in lit tests to prevent deadcoding of patterns inspected.
521static cl::opt<bool>
522EnableDCEInRA("amdgpu-dce-in-ra",
523 cl::init(true), cl::Hidden,
524 cl::desc("Enable machine DCE inside regalloc"));
525
526static cl::opt<bool> EnableSetWavePriority("amdgpu-set-wave-priority",
527 cl::desc("Adjust wave priority"),
528 cl::init(false), cl::Hidden);
529
531 "amdgpu-scalar-ir-passes",
532 cl::desc("Enable scalar IR passes"),
533 cl::init(true),
534 cl::Hidden);
535
537 "amdgpu-enable-lower-exec-sync",
538 cl::desc("Enable lowering of execution synchronization."), cl::init(true),
539 cl::Hidden);
540
541static cl::opt<bool>
542 EnableSwLowerLDS("amdgpu-enable-sw-lower-lds",
543 cl::desc("Enable lowering of lds to global memory pass "
544 "and asan instrument resulting IR."),
545 cl::init(true), cl::Hidden);
546
548 "amdgpu-enable-lower-module-lds", cl::desc("Enable lower module lds pass"),
550 cl::Hidden);
551
553 "amdgpu-enable-pre-ra-optimizations",
554 cl::desc("Enable Pre-RA optimizations pass"), cl::init(true),
555 cl::Hidden);
556
558 "amdgpu-enable-promote-kernel-arguments",
559 cl::desc("Enable promotion of flat kernel pointer arguments to global"),
560 cl::Hidden, cl::init(true));
561
563 "amdgpu-enable-image-intrinsic-optimizer",
564 cl::desc("Enable image intrinsic optimizer pass"), cl::init(true),
565 cl::Hidden);
566
567static cl::opt<bool>
568 EnableLoopPrefetch("amdgpu-loop-prefetch",
569 cl::desc("Enable loop data prefetch on AMDGPU"),
570 cl::Hidden, cl::init(false));
571
573 AMDGPUSchedStrategy("amdgpu-sched-strategy",
574 cl::desc("Select custom AMDGPU scheduling strategy."),
575 cl::Hidden, cl::init(""));
576
578 "amdgpu-enable-rewrite-partial-reg-uses",
579 cl::desc("Enable rewrite partial reg uses pass"), cl::init(true),
580 cl::Hidden);
581
583 "amdgpu-enable-hipstdpar",
584 cl::desc("Enable HIP Standard Parallelism Offload support"), cl::init(false),
585 cl::Hidden);
586
587static cl::opt<bool>
588 EnableAMDGPUAttributor("amdgpu-attributor-enable",
589 cl::desc("Enable AMDGPUAttributorPass"),
590 cl::init(true), cl::Hidden);
591
593 "new-reg-bank-select",
594 cl::desc("Run amdgpu-regbankselect and amdgpu-regbanklegalize instead of "
595 "regbankselect"),
596 cl::init(false), cl::Hidden);
597
599 "amdgpu-link-time-closed-world",
600 cl::desc("Whether has closed-world assumption at link time"),
601 cl::init(false), cl::Hidden);
602
604 "amdgpu-enable-uniform-intrinsic-combine",
605 cl::desc("Enable/Disable the Uniform Intrinsic Combine Pass"),
606 cl::init(true), cl::Hidden);
607
609 // Register the target
612
696}
697
698static std::unique_ptr<TargetLoweringObjectFile> createTLOF(const Triple &TT) {
699 return std::make_unique<AMDGPUTargetObjectFile>();
700}
701
705
706static ScheduleDAGInstrs *
708 const GCNSubtarget &ST = C->MF->getSubtarget<GCNSubtarget>();
709 ScheduleDAGMILive *DAG =
710 new GCNScheduleDAGMILive(C, std::make_unique<GCNMaxOccupancySchedStrategy>(C));
711 DAG->addMutation(createLoadClusterDAGMutation(DAG->TII, DAG->TRI));
712 if (ST.shouldClusterStores())
713 DAG->addMutation(createStoreClusterDAGMutation(DAG->TII, DAG->TRI));
715 DAG->addMutation(createAMDGPUMacroFusionDAGMutation());
716 DAG->addMutation(createAMDGPUExportClusteringDAGMutation());
717 DAG->addMutation(createAMDGPUBarrierLatencyDAGMutation(C->MF));
718 DAG->addMutation(createAMDGPUHazardLatencyDAGMutation(C->MF));
719 return DAG;
720}
721
722static ScheduleDAGInstrs *
724 ScheduleDAGMILive *DAG =
725 new GCNScheduleDAGMILive(C, std::make_unique<GCNMaxILPSchedStrategy>(C));
727 return DAG;
728}
729
730static ScheduleDAGInstrs *
732 const GCNSubtarget &ST = C->MF->getSubtarget<GCNSubtarget>();
734 C, std::make_unique<GCNMaxMemoryClauseSchedStrategy>(C));
735 DAG->addMutation(createLoadClusterDAGMutation(DAG->TII, DAG->TRI));
736 if (ST.shouldClusterStores())
737 DAG->addMutation(createStoreClusterDAGMutation(DAG->TII, DAG->TRI));
738 DAG->addMutation(createAMDGPUExportClusteringDAGMutation());
739 DAG->addMutation(createAMDGPUBarrierLatencyDAGMutation(C->MF));
740 DAG->addMutation(createAMDGPUHazardLatencyDAGMutation(C->MF));
741 return DAG;
742}
743
744static ScheduleDAGInstrs *
746 const GCNSubtarget &ST = C->MF->getSubtarget<GCNSubtarget>();
747 auto *DAG = new GCNIterativeScheduler(
749 DAG->addMutation(createLoadClusterDAGMutation(DAG->TII, DAG->TRI));
750 if (ST.shouldClusterStores())
751 DAG->addMutation(createStoreClusterDAGMutation(DAG->TII, DAG->TRI));
753 return DAG;
754}
755
762
763static ScheduleDAGInstrs *
765 const GCNSubtarget &ST = C->MF->getSubtarget<GCNSubtarget>();
767 DAG->addMutation(createLoadClusterDAGMutation(DAG->TII, DAG->TRI));
768 if (ST.shouldClusterStores())
769 DAG->addMutation(createStoreClusterDAGMutation(DAG->TII, DAG->TRI));
770 DAG->addMutation(createAMDGPUMacroFusionDAGMutation());
772 return DAG;
773}
774
775static MachineSchedRegistry
776SISchedRegistry("si", "Run SI's custom scheduler",
778
781 "Run GCN scheduler to maximize occupancy",
783
785 GCNMaxILPSchedRegistry("gcn-max-ilp", "Run GCN scheduler to maximize ilp",
787
789 "gcn-max-memory-clause", "Run GCN scheduler to maximize memory clause",
791
793 "gcn-iterative-max-occupancy-experimental",
794 "Run GCN scheduler to maximize occupancy (experimental)",
796
798 "gcn-iterative-minreg",
799 "Run GCN iterative scheduler for minimal register usage (experimental)",
801
803 "gcn-iterative-ilp",
804 "Run GCN iterative scheduler for ILP scheduling (experimental)",
806
809 if (!GPU.empty())
810 return GPU;
811
812 // Need to default to a target with flat support for HSA.
813 if (TT.isAMDGCN())
814 return TT.getOS() == Triple::AMDHSA ? "generic-hsa" : "generic";
815
816 return "r600";
817}
818
820 // The AMDGPU toolchain only supports generating shared objects, so we
821 // must always use PIC.
822 return Reloc::PIC_;
823}
824
826 StringRef CPU, StringRef FS,
827 const TargetOptions &Options,
828 std::optional<Reloc::Model> RM,
829 std::optional<CodeModel::Model> CM,
832 T, TT.computeDataLayout(), TT, getGPUOrDefault(TT, CPU), FS, Options,
834 OptLevel),
836 initAsmInfo();
837 if (TT.isAMDGCN()) {
838 if (getMCSubtargetInfo()->checkFeatures("+wavefrontsize64"))
840 else if (getMCSubtargetInfo()->checkFeatures("+wavefrontsize32"))
842 }
843}
844
847
849
851 Attribute GPUAttr = F.getFnAttribute("target-cpu");
852 return GPUAttr.isValid() ? GPUAttr.getValueAsString() : getTargetCPU();
853}
854
856 Attribute FSAttr = F.getFnAttribute("target-features");
857
858 return FSAttr.isValid() ? FSAttr.getValueAsString()
860}
861
864 const GCNSubtarget &ST = C->MF->getSubtarget<GCNSubtarget>();
866 DAG->addMutation(createLoadClusterDAGMutation(DAG->TII, DAG->TRI));
867 if (ST.shouldClusterStores())
868 DAG->addMutation(createStoreClusterDAGMutation(DAG->TII, DAG->TRI));
869 return DAG;
870}
871
872/// Predicate for Internalize pass.
873static bool mustPreserveGV(const GlobalValue &GV) {
874 if (const Function *F = dyn_cast<Function>(&GV))
875 return F->isDeclaration() || F->getName().starts_with("__asan_") ||
876 F->getName().starts_with("__sanitizer_") ||
877 AMDGPU::isEntryFunctionCC(F->getCallingConv());
878
880 return !GV.use_empty();
881}
882
887
890 if (Params.empty())
892 Params.consume_front("strategy=");
893 auto Result = StringSwitch<std::optional<ScanOptions>>(Params)
894 .Case("dpp", ScanOptions::DPP)
895 .Cases({"iterative", ""}, ScanOptions::Iterative)
896 .Case("none", ScanOptions::None)
897 .Default(std::nullopt);
898 if (Result)
899 return *Result;
900 return make_error<StringError>("invalid parameter", inconvertibleErrorCode());
901}
902
906 while (!Params.empty()) {
907 StringRef ParamName;
908 std::tie(ParamName, Params) = Params.split(';');
909 if (ParamName == "closed-world") {
910 Result.IsClosedWorld = true;
911 } else {
913 formatv("invalid AMDGPUAttributor pass parameter '{0}' ", ParamName)
914 .str(),
916 }
917 }
918 return Result;
919}
920
922
923#define GET_PASS_REGISTRY "AMDGPUPassRegistry.def"
925
926 PB.registerScalarOptimizerLateEPCallback(
927 [](FunctionPassManager &FPM, OptimizationLevel Level) {
928 if (Level == OptimizationLevel::O0)
929 return;
930
932 });
933
934 PB.registerVectorizerEndEPCallback(
935 [](FunctionPassManager &FPM, OptimizationLevel Level) {
936 if (Level == OptimizationLevel::O0)
937 return;
938
940 });
941
942 PB.registerPipelineEarlySimplificationEPCallback(
943 [this](ModulePassManager &PM, OptimizationLevel Level,
945 if (!isLTOPreLink(Phase) && getTargetTriple().isAMDGCN()) {
946 // When we are not using -fgpu-rdc, we can run accelerator code
947 // selection relatively early, but still after linking to prevent
948 // eager removal of potentially reachable symbols.
949 if (EnableHipStdPar) {
952 }
953
955 }
956
957 if (Level == OptimizationLevel::O0)
958 return;
959
960 // We don't want to run internalization at per-module stage.
964 }
965
968 });
969
970 PB.registerPeepholeEPCallback(
971 [](FunctionPassManager &FPM, OptimizationLevel Level) {
972 if (Level == OptimizationLevel::O0)
973 return;
974
978
981 });
982
983 PB.registerCGSCCOptimizerLateEPCallback(
984 [this](CGSCCPassManager &PM, OptimizationLevel Level) {
985 if (Level == OptimizationLevel::O0)
986 return;
987
989
990 // Add promote kernel arguments pass to the opt pipeline right before
991 // infer address spaces which is needed to do actual address space
992 // rewriting.
993 if (Level.getSpeedupLevel() > OptimizationLevel::O1.getSpeedupLevel() &&
996
997 // Add infer address spaces pass to the opt pipeline after inlining
998 // but before SROA to increase SROA opportunities.
1000
1001 // This should run after inlining to have any chance of doing
1002 // anything, and before other cleanup optimizations.
1004
1005 if (Level != OptimizationLevel::O0) {
1006 // Promote alloca to vector before SROA and loop unroll. If we
1007 // manage to eliminate allocas before unroll we may choose to unroll
1008 // less.
1010 }
1011
1012 PM.addPass(createCGSCCToFunctionPassAdaptor(std::move(FPM)));
1013 });
1014
1015 // FIXME: Why is AMDGPUAttributor not in CGSCC?
1016 PB.registerOptimizerLastEPCallback([this](ModulePassManager &MPM,
1017 OptimizationLevel Level,
1019 if (Level != OptimizationLevel::O0) {
1020 if (!isLTOPreLink(Phase)) {
1021 if (EnableAMDGPUAttributor && getTargetTriple().isAMDGCN()) {
1023 MPM.addPass(AMDGPUAttributorPass(*this, Opts, Phase));
1024 }
1025 }
1026 }
1027 });
1028
1029 PB.registerFullLinkTimeOptimizationLastEPCallback(
1030 [this](ModulePassManager &PM, OptimizationLevel Level) {
1031 // When we are using -fgpu-rdc, we can only run accelerator code
1032 // selection after linking to prevent, otherwise we end up removing
1033 // potentially reachable symbols that were exported as external in other
1034 // modules.
1035 if (EnableHipStdPar) {
1038 }
1039 // We want to support the -lto-partitions=N option as "best effort".
1040 // For that, we need to lower LDS earlier in the pipeline before the
1041 // module is partitioned for codegen.
1044 if (EnableSwLowerLDS)
1045 PM.addPass(AMDGPUSwLowerLDSPass(*this));
1048 if (Level != OptimizationLevel::O0) {
1049 // We only want to run this with O2 or higher since inliner and SROA
1050 // don't run in O1.
1051 if (Level != OptimizationLevel::O1) {
1052 PM.addPass(
1054 }
1055 // Do we really need internalization in LTO?
1056 if (InternalizeSymbols) {
1058 PM.addPass(GlobalDCEPass());
1059 }
1060 if (EnableAMDGPUAttributor && getTargetTriple().isAMDGCN()) {
1063 Opt.IsClosedWorld = true;
1066 }
1067 }
1068 if (!NoKernelInfoEndLTO) {
1070 FPM.addPass(KernelInfoPrinter(this));
1071 PM.addPass(createModuleToFunctionPassAdaptor(std::move(FPM)));
1072 }
1073 });
1074
1075 PB.registerRegClassFilterParsingCallback(
1076 [](StringRef FilterName) -> RegAllocFilterFunc {
1077 if (FilterName == "sgpr")
1078 return onlyAllocateSGPRs;
1079 if (FilterName == "vgpr")
1080 return onlyAllocateVGPRs;
1081 if (FilterName == "wwm")
1082 return onlyAllocateWWMRegs;
1083 return nullptr;
1084 });
1085}
1086
1087int64_t AMDGPUTargetMachine::getNullPointerValue(unsigned AddrSpace) {
1088 return (AddrSpace == AMDGPUAS::LOCAL_ADDRESS ||
1089 AddrSpace == AMDGPUAS::PRIVATE_ADDRESS ||
1090 AddrSpace == AMDGPUAS::REGION_ADDRESS)
1091 ? -1
1092 : 0;
1093}
1094
1096 unsigned DestAS) const {
1097 return AMDGPU::isFlatGlobalAddrSpace(SrcAS) &&
1099}
1100
1102 if (auto *Arg = dyn_cast<Argument>(V);
1103 Arg &&
1104 AMDGPU::isModuleEntryFunctionCC(Arg->getParent()->getCallingConv()) &&
1105 !Arg->hasByRefAttr())
1107
1108 const auto *LD = dyn_cast<LoadInst>(V);
1109 if (!LD) // TODO: Handle invariant load like constant.
1111
1112 // It must be a generic pointer loaded.
1113 assert(V->getType()->getPointerAddressSpace() == AMDGPUAS::FLAT_ADDRESS);
1114
1115 const auto *Ptr = LD->getPointerOperand();
1116 if (Ptr->getType()->getPointerAddressSpace() != AMDGPUAS::CONSTANT_ADDRESS)
1118 // For a generic pointer loaded from the constant memory, it could be assumed
1119 // as a global pointer since the constant memory is only populated on the
1120 // host side. As implied by the offload programming model, only global
1121 // pointers could be referenced on the host side.
1123}
1124
1125std::pair<const Value *, unsigned>
1127 if (auto *II = dyn_cast<IntrinsicInst>(V)) {
1128 switch (II->getIntrinsicID()) {
1129 case Intrinsic::amdgcn_is_shared:
1130 return std::pair(II->getArgOperand(0), AMDGPUAS::LOCAL_ADDRESS);
1131 case Intrinsic::amdgcn_is_private:
1132 return std::pair(II->getArgOperand(0), AMDGPUAS::PRIVATE_ADDRESS);
1133 default:
1134 break;
1135 }
1136 return std::pair(nullptr, -1);
1137 }
1138 // Check the global pointer predication based on
1139 // (!is_share(p) && !is_private(p)). Note that logic 'and' is commutative and
1140 // the order of 'is_shared' and 'is_private' is not significant.
1141 Value *Ptr;
1142 if (match(
1143 const_cast<Value *>(V),
1146 m_Deferred(Ptr))))))
1147 return std::pair(Ptr, AMDGPUAS::GLOBAL_ADDRESS);
1148
1149 return std::pair(nullptr, -1);
1150}
1151
1152unsigned
1167
1169 Module &M, unsigned NumParts,
1170 function_ref<void(std::unique_ptr<Module> MPart)> ModuleCallback) {
1171 // FIXME(?): Would be better to use an already existing Analysis/PassManager,
1172 // but all current users of this API don't have one ready and would need to
1173 // create one anyway. Let's hide the boilerplate for now to keep it simple.
1174
1179
1180 PassBuilder PB(this);
1181 PB.registerModuleAnalyses(MAM);
1182 PB.registerFunctionAnalyses(FAM);
1183 PB.crossRegisterProxies(LAM, FAM, CGAM, MAM);
1184
1186 MPM.addPass(AMDGPUSplitModulePass(NumParts, ModuleCallback));
1187 MPM.run(M, MAM);
1188 return true;
1189}
1190
1191//===----------------------------------------------------------------------===//
1192// GCN Target Machine (SI+)
1193//===----------------------------------------------------------------------===//
1194
1196 StringRef CPU, StringRef FS,
1197 const TargetOptions &Options,
1198 std::optional<Reloc::Model> RM,
1199 std::optional<CodeModel::Model> CM,
1200 CodeGenOptLevel OL, bool JIT)
1201 : AMDGPUTargetMachine(T, TT, CPU, FS, Options, RM, CM, OL) {}
1202
1203const TargetSubtargetInfo *
1205 StringRef GPU = getGPUName(F);
1207
1208 SmallString<128> SubtargetKey(GPU);
1209 SubtargetKey.append(FS);
1210
1211 auto &I = SubtargetMap[SubtargetKey];
1212 if (!I) {
1213 // This needs to be done before we create a new subtarget since any
1214 // creation will depend on the TM and the code generation flags on the
1215 // function that reside in TargetOptions.
1217 I = std::make_unique<GCNSubtarget>(TargetTriple, GPU, FS, *this);
1218 }
1219
1220 I->setScalarizeGlobalBehavior(ScalarizeGlobal);
1221
1222 return I.get();
1223}
1224
1227 return TargetTransformInfo(std::make_unique<GCNTTIImpl>(this, F));
1228}
1229
1232 CodeGenFileType FileType, const CGPassBuilderOption &Opts, MCContext &Ctx,
1234 AMDGPUCodeGenPassBuilder CGPB(*this, Opts, PIC);
1235 return CGPB.buildPipeline(MPM, Out, DwoOut, FileType, Ctx);
1236}
1237
1240 const GCNSubtarget &ST = C->MF->getSubtarget<GCNSubtarget>();
1241 if (ST.enableSIScheduler())
1243
1244 Attribute SchedStrategyAttr =
1245 C->MF->getFunction().getFnAttribute("amdgpu-sched-strategy");
1246 StringRef SchedStrategy = SchedStrategyAttr.isValid()
1247 ? SchedStrategyAttr.getValueAsString()
1249
1250 if (SchedStrategy == "max-ilp")
1252
1253 if (SchedStrategy == "max-memory-clause")
1255
1256 if (SchedStrategy == "iterative-ilp")
1258
1259 if (SchedStrategy == "iterative-minreg")
1260 return createMinRegScheduler(C);
1261
1262 if (SchedStrategy == "iterative-maxocc")
1264
1266}
1267
1270 ScheduleDAGMI *DAG =
1271 new GCNPostScheduleDAGMILive(C, std::make_unique<PostGenericScheduler>(C),
1272 /*RemoveKillFlags=*/true);
1273 const GCNSubtarget &ST = C->MF->getSubtarget<GCNSubtarget>();
1275 if (ST.shouldClusterStores())
1278 if ((EnableVOPD.getNumOccurrences() ||
1280 EnableVOPD)
1285 return DAG;
1286}
1287//===----------------------------------------------------------------------===//
1288// AMDGPU Legacy Pass Setup
1289//===----------------------------------------------------------------------===//
1290
1291std::unique_ptr<CSEConfigBase> llvm::AMDGPUPassConfig::getCSEConfig() const {
1292 return getStandardCSEConfigForOpt(TM->getOptLevel());
1293}
1294
1295namespace {
1296
1297class GCNPassConfig final : public AMDGPUPassConfig {
1298public:
1299 GCNPassConfig(TargetMachine &TM, PassManagerBase &PM)
1300 : AMDGPUPassConfig(TM, PM) {
1301 substitutePass(&PostRASchedulerID, &PostMachineSchedulerID);
1302 }
1303
1304 GCNTargetMachine &getGCNTargetMachine() const {
1305 return getTM<GCNTargetMachine>();
1306 }
1307
1308 bool addPreISel() override;
1309 void addMachineSSAOptimization() override;
1310 bool addILPOpts() override;
1311 bool addInstSelector() override;
1312 bool addIRTranslator() override;
1313 void addPreLegalizeMachineIR() override;
1314 bool addLegalizeMachineIR() override;
1315 void addPreRegBankSelect() override;
1316 bool addRegBankSelect() override;
1317 void addPreGlobalInstructionSelect() override;
1318 bool addGlobalInstructionSelect() override;
1319 void addPreRegAlloc() override;
1320 void addFastRegAlloc() override;
1321 void addOptimizedRegAlloc() override;
1322
1323 FunctionPass *createSGPRAllocPass(bool Optimized);
1324 FunctionPass *createVGPRAllocPass(bool Optimized);
1325 FunctionPass *createWWMRegAllocPass(bool Optimized);
1326 FunctionPass *createRegAllocPass(bool Optimized) override;
1327
1328 bool addRegAssignAndRewriteFast() override;
1329 bool addRegAssignAndRewriteOptimized() override;
1330
1331 bool addPreRewrite() override;
1332 void addPostRegAlloc() override;
1333 void addPreSched2() override;
1334 void addPreEmitPass() override;
1335 void addPostBBSections() override;
1336};
1337
1338} // end anonymous namespace
1339
1341 : TargetPassConfig(TM, PM) {
1342 // Exceptions and StackMaps are not supported, so these passes will never do
1343 // anything.
1346 // Garbage collection is not supported.
1349}
1350
1357
1362 // ReassociateGEPs exposes more opportunities for SLSR. See
1363 // the example in reassociate-geps-and-slsr.ll.
1365 // SeparateConstOffsetFromGEP and SLSR creates common expressions which GVN or
1366 // EarlyCSE can reuse.
1368 // Run NaryReassociate after EarlyCSE/GVN to be more effective.
1370 // NaryReassociate on GEPs creates redundant common expressions, so run
1371 // EarlyCSE after it.
1373}
1374
1377
1378 if (RemoveIncompatibleFunctions && TM.getTargetTriple().isAMDGCN())
1380
1381 // There is no reason to run these.
1385
1386 if (TM.getTargetTriple().isAMDGCN())
1388
1389 if (LowerCtorDtor)
1391
1392 if (TM.getTargetTriple().isAMDGCN() &&
1395
1398
1399 // This can be disabled by passing ::Disable here or on the command line
1400 // with --expand-variadics-override=disable.
1402
1403 // Function calls are not supported, so make sure we inline everything.
1406
1407 // Handle uses of OpenCL image2d_t, image3d_t and sampler_t arguments.
1408 if (TM.getTargetTriple().getArch() == Triple::r600)
1410
1411 // Make enqueued block runtime handles externally visible.
1413
1414 // Lower special LDS accesses.
1417
1418 // Lower LDS accesses to global memory pass if address sanitizer is enabled.
1419 if (EnableSwLowerLDS)
1421
1422 // Runs before PromoteAlloca so the latter can account for function uses
1425 }
1426
1427 // Run atomic optimizer before Atomic Expand
1428 if ((TM.getTargetTriple().isAMDGCN()) &&
1429 (TM.getOptLevel() >= CodeGenOptLevel::Less) &&
1432 }
1433
1435
1436 if (TM.getOptLevel() > CodeGenOptLevel::None) {
1438
1441
1445 AAResults &AAR) {
1446 if (auto *WrapperPass = P.getAnalysisIfAvailable<AMDGPUAAWrapperPass>())
1447 AAR.addAAResult(WrapperPass->getResult());
1448 }));
1449 }
1450
1451 if (TM.getTargetTriple().isAMDGCN()) {
1452 // TODO: May want to move later or split into an early and late one.
1454 }
1455
1456 // Try to hoist loop invariant parts of divisions AMDGPUCodeGenPrepare may
1457 // have expanded.
1458 if (TM.getOptLevel() > CodeGenOptLevel::Less)
1460 }
1461
1463
1464 // EarlyCSE is not always strong enough to clean up what LSR produces. For
1465 // example, GVN can combine
1466 //
1467 // %0 = add %a, %b
1468 // %1 = add %b, %a
1469 //
1470 // and
1471 //
1472 // %0 = shl nsw %a, 2
1473 // %1 = shl %a, 2
1474 //
1475 // but EarlyCSE can do neither of them.
1478}
1479
1481 if (TM->getTargetTriple().isAMDGCN() &&
1482 TM->getOptLevel() > CodeGenOptLevel::None)
1484
1485 if (TM->getTargetTriple().isAMDGCN() && EnableLowerKernelArguments)
1487
1489
1492
1493 if (TM->getTargetTriple().isAMDGCN()) {
1494 // This lowering has been placed after codegenprepare to take advantage of
1495 // address mode matching (which is why it isn't put with the LDS lowerings).
1496 // It could be placed anywhere before uniformity annotations (an analysis
1497 // that it changes by splitting up fat pointers into their components)
1498 // but has been put before switch lowering and CFG flattening so that those
1499 // passes can run on the more optimized control flow this pass creates in
1500 // many cases.
1503 }
1504
1505 // LowerSwitch pass may introduce unreachable blocks that can
1506 // cause unexpected behavior for subsequent passes. Placing it
1507 // here seems better that these blocks would get cleaned up by
1508 // UnreachableBlockElim inserted next in the pass flow.
1510}
1511
1513 if (TM->getOptLevel() > CodeGenOptLevel::None)
1515 return false;
1516}
1517
1522
1524 // Do nothing. GC is not supported.
1525 return false;
1526}
1527
1528//===----------------------------------------------------------------------===//
1529// GCN Legacy Pass Setup
1530//===----------------------------------------------------------------------===//
1531
1532bool GCNPassConfig::addPreISel() {
1534
1535 if (TM->getOptLevel() > CodeGenOptLevel::None)
1536 addPass(createSinkingPass());
1537
1538 if (TM->getOptLevel() > CodeGenOptLevel::None)
1540
1541 // Merge divergent exit nodes. StructurizeCFG won't recognize the multi-exit
1542 // regions formed by them.
1544 addPass(createFixIrreduciblePass());
1545 addPass(createUnifyLoopExitsPass());
1546 addPass(createStructurizeCFGPass(false)); // true -> SkipUniformRegions
1547
1550 // TODO: Move this right after structurizeCFG to avoid extra divergence
1551 // analysis. This depends on stopping SIAnnotateControlFlow from making
1552 // control flow modifications.
1554
1555 // SDAG requires LCSSA, GlobalISel does not. Disable LCSSA for -global-isel
1556 // with -new-reg-bank-select and without any of the fallback options.
1558 !isGlobalISelAbortEnabled() || !NewRegBankSelect)
1559 addPass(createLCSSAPass());
1560
1561 if (TM->getOptLevel() > CodeGenOptLevel::Less)
1563
1564 return false;
1565}
1566
1567void GCNPassConfig::addMachineSSAOptimization() {
1569
1570 // We want to fold operands after PeepholeOptimizer has run (or as part of
1571 // it), because it will eliminate extra copies making it easier to fold the
1572 // real source operand. We want to eliminate dead instructions after, so that
1573 // we see fewer uses of the copies. We then need to clean up the dead
1574 // instructions leftover after the operands are folded as well.
1575 //
1576 // XXX - Can we get away without running DeadMachineInstructionElim again?
1577 addPass(&SIFoldOperandsLegacyID);
1578 if (EnableDPPCombine)
1579 addPass(&GCNDPPCombineLegacyID);
1581 if (isPassEnabled(EnableSDWAPeephole)) {
1582 addPass(&SIPeepholeSDWALegacyID);
1583 addPass(&EarlyMachineLICMID);
1584 addPass(&MachineCSELegacyID);
1585 addPass(&SIFoldOperandsLegacyID);
1586 }
1589}
1590
1591bool GCNPassConfig::addILPOpts() {
1593 addPass(&EarlyIfConverterLegacyID);
1594
1596 return false;
1597}
1598
1599bool GCNPassConfig::addInstSelector() {
1601 addPass(&SIFixSGPRCopiesLegacyID);
1603 return false;
1604}
1605
1606bool GCNPassConfig::addIRTranslator() {
1607 addPass(new IRTranslator(getOptLevel()));
1608 return false;
1609}
1610
1611void GCNPassConfig::addPreLegalizeMachineIR() {
1612 bool IsOptNone = getOptLevel() == CodeGenOptLevel::None;
1613 addPass(createAMDGPUPreLegalizeCombiner(IsOptNone));
1614 addPass(new Localizer());
1615}
1616
1617bool GCNPassConfig::addLegalizeMachineIR() {
1618 addPass(new Legalizer());
1619 return false;
1620}
1621
1622void GCNPassConfig::addPreRegBankSelect() {
1623 bool IsOptNone = getOptLevel() == CodeGenOptLevel::None;
1624 addPass(createAMDGPUPostLegalizeCombiner(IsOptNone));
1626}
1627
1628bool GCNPassConfig::addRegBankSelect() {
1629 if (NewRegBankSelect) {
1632 } else {
1633 addPass(new RegBankSelect());
1634 }
1635 return false;
1636}
1637
1638void GCNPassConfig::addPreGlobalInstructionSelect() {
1639 bool IsOptNone = getOptLevel() == CodeGenOptLevel::None;
1640 addPass(createAMDGPURegBankCombiner(IsOptNone));
1641}
1642
1643bool GCNPassConfig::addGlobalInstructionSelect() {
1644 addPass(new InstructionSelect(getOptLevel()));
1645 return false;
1646}
1647
1648void GCNPassConfig::addFastRegAlloc() {
1649 // FIXME: We have to disable the verifier here because of PHIElimination +
1650 // TwoAddressInstructions disabling it.
1651
1652 // This must be run immediately after phi elimination and before
1653 // TwoAddressInstructions, otherwise the processing of the tied operand of
1654 // SI_ELSE will introduce a copy of the tied operand source after the else.
1656
1658
1660}
1661
1662void GCNPassConfig::addPreRegAlloc() {
1663 if (getOptLevel() != CodeGenOptLevel::None)
1665}
1666
1667void GCNPassConfig::addOptimizedRegAlloc() {
1668 if (EnableDCEInRA)
1670
1671 // FIXME: when an instruction has a Killed operand, and the instruction is
1672 // inside a bundle, seems only the BUNDLE instruction appears as the Kills of
1673 // the register in LiveVariables, this would trigger a failure in verifier,
1674 // we should fix it and enable the verifier.
1675 if (OptVGPRLiveRange)
1677
1678 // This must be run immediately after phi elimination and before
1679 // TwoAddressInstructions, otherwise the processing of the tied operand of
1680 // SI_ELSE will introduce a copy of the tied operand source after the else.
1682
1685
1686 if (isPassEnabled(EnablePreRAOptimizations))
1688
1689 // Allow the scheduler to run before SIWholeQuadMode inserts exec manipulation
1690 // instructions that cause scheduling barriers.
1692
1693 if (OptExecMaskPreRA)
1695
1696 // This is not an essential optimization and it has a noticeable impact on
1697 // compilation time, so we only enable it from O2.
1698 if (TM->getOptLevel() > CodeGenOptLevel::Less)
1700
1702}
1703
1704bool GCNPassConfig::addPreRewrite() {
1706 addPass(&GCNNSAReassignID);
1707
1709 return true;
1710}
1711
1712FunctionPass *GCNPassConfig::createSGPRAllocPass(bool Optimized) {
1713 // Initialize the global default.
1714 llvm::call_once(InitializeDefaultSGPRRegisterAllocatorFlag,
1715 initializeDefaultSGPRRegisterAllocatorOnce);
1716
1717 RegisterRegAlloc::FunctionPassCtor Ctor = SGPRRegisterRegAlloc::getDefault();
1718 if (Ctor != useDefaultRegisterAllocator)
1719 return Ctor();
1720
1721 if (Optimized)
1722 return createGreedyRegisterAllocator(onlyAllocateSGPRs);
1723
1724 return createFastRegisterAllocator(onlyAllocateSGPRs, false);
1725}
1726
1727FunctionPass *GCNPassConfig::createVGPRAllocPass(bool Optimized) {
1728 // Initialize the global default.
1729 llvm::call_once(InitializeDefaultVGPRRegisterAllocatorFlag,
1730 initializeDefaultVGPRRegisterAllocatorOnce);
1731
1732 RegisterRegAlloc::FunctionPassCtor Ctor = VGPRRegisterRegAlloc::getDefault();
1733 if (Ctor != useDefaultRegisterAllocator)
1734 return Ctor();
1735
1736 if (Optimized)
1737 return createGreedyVGPRRegisterAllocator();
1738
1739 return createFastVGPRRegisterAllocator();
1740}
1741
1742FunctionPass *GCNPassConfig::createWWMRegAllocPass(bool Optimized) {
1743 // Initialize the global default.
1744 llvm::call_once(InitializeDefaultWWMRegisterAllocatorFlag,
1745 initializeDefaultWWMRegisterAllocatorOnce);
1746
1747 RegisterRegAlloc::FunctionPassCtor Ctor = WWMRegisterRegAlloc::getDefault();
1748 if (Ctor != useDefaultRegisterAllocator)
1749 return Ctor();
1750
1751 if (Optimized)
1752 return createGreedyWWMRegisterAllocator();
1753
1754 return createFastWWMRegisterAllocator();
1755}
1756
1757FunctionPass *GCNPassConfig::createRegAllocPass(bool Optimized) {
1758 llvm_unreachable("should not be used");
1759}
1760
1762 "-regalloc not supported with amdgcn. Use -sgpr-regalloc, -wwm-regalloc, "
1763 "and -vgpr-regalloc";
1764
1765bool GCNPassConfig::addRegAssignAndRewriteFast() {
1766 if (!usingDefaultRegAlloc())
1768
1769 addPass(&GCNPreRALongBranchRegID);
1770
1771 addPass(createSGPRAllocPass(false));
1772
1773 // Equivalent of PEI for SGPRs.
1774 addPass(&SILowerSGPRSpillsLegacyID);
1775
1776 // To Allocate wwm registers used in whole quad mode operations (for shaders).
1778
1779 // For allocating other wwm register operands.
1780 addPass(createWWMRegAllocPass(false));
1781
1782 addPass(&SILowerWWMCopiesLegacyID);
1784
1785 // For allocating per-thread VGPRs.
1786 addPass(createVGPRAllocPass(false));
1787
1788 return true;
1789}
1790
1791bool GCNPassConfig::addRegAssignAndRewriteOptimized() {
1792 if (!usingDefaultRegAlloc())
1794
1795 addPass(&GCNPreRALongBranchRegID);
1796
1797 addPass(createSGPRAllocPass(true));
1798
1799 // Commit allocated register changes. This is mostly necessary because too
1800 // many things rely on the use lists of the physical registers, such as the
1801 // verifier. This is only necessary with allocators which use LiveIntervals,
1802 // since FastRegAlloc does the replacements itself.
1803 addPass(createVirtRegRewriter(false));
1804
1805 // At this point, the sgpr-regalloc has been done and it is good to have the
1806 // stack slot coloring to try to optimize the SGPR spill stack indices before
1807 // attempting the custom SGPR spill lowering.
1808 addPass(&StackSlotColoringID);
1809
1810 // Equivalent of PEI for SGPRs.
1811 addPass(&SILowerSGPRSpillsLegacyID);
1812
1813 // To Allocate wwm registers used in whole quad mode operations (for shaders).
1815
1816 // For allocating other whole wave mode registers.
1817 addPass(createWWMRegAllocPass(true));
1818 addPass(&SILowerWWMCopiesLegacyID);
1819 addPass(createVirtRegRewriter(false));
1821
1822 // For allocating per-thread VGPRs.
1823 addPass(createVGPRAllocPass(true));
1824
1825 addPreRewrite();
1826 addPass(&VirtRegRewriterID);
1827
1829
1830 return true;
1831}
1832
1833void GCNPassConfig::addPostRegAlloc() {
1834 addPass(&SIFixVGPRCopiesID);
1835 if (getOptLevel() > CodeGenOptLevel::None)
1838}
1839
1840void GCNPassConfig::addPreSched2() {
1841 if (TM->getOptLevel() > CodeGenOptLevel::None)
1843 addPass(&SIPostRABundlerLegacyID);
1844}
1845
1846void GCNPassConfig::addPreEmitPass() {
1847 if (isPassEnabled(EnableVOPD, CodeGenOptLevel::Less))
1848 addPass(&GCNCreateVOPDID);
1849 addPass(createSIMemoryLegalizerPass());
1850 addPass(createSIInsertWaitcntsPass());
1851
1852 addPass(createSIModeRegisterPass());
1853
1854 if (getOptLevel() > CodeGenOptLevel::None)
1855 addPass(&SIInsertHardClausesID);
1856
1858 if (isPassEnabled(EnableSetWavePriority, CodeGenOptLevel::Less))
1860 if (getOptLevel() > CodeGenOptLevel::None)
1861 addPass(&SIPreEmitPeepholeID);
1862 // The hazard recognizer that runs as part of the post-ra scheduler does not
1863 // guarantee to be able handle all hazards correctly. This is because if there
1864 // are multiple scheduling regions in a basic block, the regions are scheduled
1865 // bottom up, so when we begin to schedule a region we don't know what
1866 // instructions were emitted directly before it.
1867 //
1868 // Here we add a stand-alone hazard recognizer pass which can handle all
1869 // cases.
1870 addPass(&PostRAHazardRecognizerID);
1871
1873
1875
1876 if (isPassEnabled(EnableInsertDelayAlu, CodeGenOptLevel::Less))
1877 addPass(&AMDGPUInsertDelayAluID);
1878
1879 addPass(&BranchRelaxationPassID);
1880}
1881
1882void GCNPassConfig::addPostBBSections() {
1883 // We run this later to avoid passes like livedebugvalues and BBSections
1884 // having to deal with the apparent multi-entry functions we may generate.
1886}
1887
1889 return new GCNPassConfig(*this, PM);
1890}
1891
1897
1904
1908
1915
1918 SMDiagnostic &Error, SMRange &SourceRange) const {
1919 const yaml::SIMachineFunctionInfo &YamlMFI =
1920 static_cast<const yaml::SIMachineFunctionInfo &>(MFI_);
1921 MachineFunction &MF = PFS.MF;
1923 const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>();
1924
1925 if (MFI->initializeBaseYamlFields(YamlMFI, MF, PFS, Error, SourceRange))
1926 return true;
1927
1928 if (MFI->Occupancy == 0) {
1929 // Fixup the subtarget dependent default value.
1930 MFI->Occupancy = ST.getOccupancyWithWorkGroupSizes(MF).second;
1931 }
1932
1933 auto parseRegister = [&](const yaml::StringValue &RegName, Register &RegVal) {
1934 Register TempReg;
1935 if (parseNamedRegisterReference(PFS, TempReg, RegName.Value, Error)) {
1936 SourceRange = RegName.SourceRange;
1937 return true;
1938 }
1939 RegVal = TempReg;
1940
1941 return false;
1942 };
1943
1944 auto parseOptionalRegister = [&](const yaml::StringValue &RegName,
1945 Register &RegVal) {
1946 return !RegName.Value.empty() && parseRegister(RegName, RegVal);
1947 };
1948
1949 if (parseOptionalRegister(YamlMFI.VGPRForAGPRCopy, MFI->VGPRForAGPRCopy))
1950 return true;
1951
1952 if (parseOptionalRegister(YamlMFI.SGPRForEXECCopy, MFI->SGPRForEXECCopy))
1953 return true;
1954
1955 if (parseOptionalRegister(YamlMFI.LongBranchReservedReg,
1956 MFI->LongBranchReservedReg))
1957 return true;
1958
1959 auto diagnoseRegisterClass = [&](const yaml::StringValue &RegName) {
1960 // Create a diagnostic for a the register string literal.
1961 const MemoryBuffer &Buffer =
1962 *PFS.SM->getMemoryBuffer(PFS.SM->getMainFileID());
1963 Error = SMDiagnostic(*PFS.SM, SMLoc(), Buffer.getBufferIdentifier(), 1,
1964 RegName.Value.size(), SourceMgr::DK_Error,
1965 "incorrect register class for field", RegName.Value,
1966 {}, {});
1967 SourceRange = RegName.SourceRange;
1968 return true;
1969 };
1970
1971 if (parseRegister(YamlMFI.ScratchRSrcReg, MFI->ScratchRSrcReg) ||
1972 parseRegister(YamlMFI.FrameOffsetReg, MFI->FrameOffsetReg) ||
1973 parseRegister(YamlMFI.StackPtrOffsetReg, MFI->StackPtrOffsetReg))
1974 return true;
1975
1976 if (MFI->ScratchRSrcReg != AMDGPU::PRIVATE_RSRC_REG &&
1977 !AMDGPU::SGPR_128RegClass.contains(MFI->ScratchRSrcReg)) {
1978 return diagnoseRegisterClass(YamlMFI.ScratchRSrcReg);
1979 }
1980
1981 if (MFI->FrameOffsetReg != AMDGPU::FP_REG &&
1982 !AMDGPU::SGPR_32RegClass.contains(MFI->FrameOffsetReg)) {
1983 return diagnoseRegisterClass(YamlMFI.FrameOffsetReg);
1984 }
1985
1986 if (MFI->StackPtrOffsetReg != AMDGPU::SP_REG &&
1987 !AMDGPU::SGPR_32RegClass.contains(MFI->StackPtrOffsetReg)) {
1988 return diagnoseRegisterClass(YamlMFI.StackPtrOffsetReg);
1989 }
1990
1991 for (const auto &YamlReg : YamlMFI.WWMReservedRegs) {
1992 Register ParsedReg;
1993 if (parseRegister(YamlReg, ParsedReg))
1994 return true;
1995
1996 MFI->reserveWWMRegister(ParsedReg);
1997 }
1998
1999 for (const auto &[_, Info] : PFS.VRegInfosNamed) {
2000 MFI->setFlag(Info->VReg, Info->Flags);
2001 }
2002 for (const auto &[_, Info] : PFS.VRegInfos) {
2003 MFI->setFlag(Info->VReg, Info->Flags);
2004 }
2005
2006 for (const auto &YamlRegStr : YamlMFI.SpillPhysVGPRS) {
2007 Register ParsedReg;
2008 if (parseRegister(YamlRegStr, ParsedReg))
2009 return true;
2010 MFI->SpillPhysVGPRs.push_back(ParsedReg);
2011 }
2012
2013 auto parseAndCheckArgument = [&](const std::optional<yaml::SIArgument> &A,
2014 const TargetRegisterClass &RC,
2015 ArgDescriptor &Arg, unsigned UserSGPRs,
2016 unsigned SystemSGPRs) {
2017 // Skip parsing if it's not present.
2018 if (!A)
2019 return false;
2020
2021 if (A->IsRegister) {
2022 Register Reg;
2023 if (parseNamedRegisterReference(PFS, Reg, A->RegisterName.Value, Error)) {
2024 SourceRange = A->RegisterName.SourceRange;
2025 return true;
2026 }
2027 if (!RC.contains(Reg))
2028 return diagnoseRegisterClass(A->RegisterName);
2030 } else
2031 Arg = ArgDescriptor::createStack(A->StackOffset);
2032 // Check and apply the optional mask.
2033 if (A->Mask)
2034 Arg = ArgDescriptor::createArg(Arg, *A->Mask);
2035
2036 MFI->NumUserSGPRs += UserSGPRs;
2037 MFI->NumSystemSGPRs += SystemSGPRs;
2038 return false;
2039 };
2040
2041 if (YamlMFI.ArgInfo &&
2042 (parseAndCheckArgument(YamlMFI.ArgInfo->PrivateSegmentBuffer,
2043 AMDGPU::SGPR_128RegClass,
2044 MFI->ArgInfo.PrivateSegmentBuffer, 4, 0) ||
2045 parseAndCheckArgument(YamlMFI.ArgInfo->DispatchPtr,
2046 AMDGPU::SReg_64RegClass, MFI->ArgInfo.DispatchPtr,
2047 2, 0) ||
2048 parseAndCheckArgument(YamlMFI.ArgInfo->QueuePtr, AMDGPU::SReg_64RegClass,
2049 MFI->ArgInfo.QueuePtr, 2, 0) ||
2050 parseAndCheckArgument(YamlMFI.ArgInfo->KernargSegmentPtr,
2051 AMDGPU::SReg_64RegClass,
2052 MFI->ArgInfo.KernargSegmentPtr, 2, 0) ||
2053 parseAndCheckArgument(YamlMFI.ArgInfo->DispatchID,
2054 AMDGPU::SReg_64RegClass, MFI->ArgInfo.DispatchID,
2055 2, 0) ||
2056 parseAndCheckArgument(YamlMFI.ArgInfo->FlatScratchInit,
2057 AMDGPU::SReg_64RegClass,
2058 MFI->ArgInfo.FlatScratchInit, 2, 0) ||
2059 parseAndCheckArgument(YamlMFI.ArgInfo->PrivateSegmentSize,
2060 AMDGPU::SGPR_32RegClass,
2061 MFI->ArgInfo.PrivateSegmentSize, 0, 0) ||
2062 parseAndCheckArgument(YamlMFI.ArgInfo->LDSKernelId,
2063 AMDGPU::SGPR_32RegClass,
2064 MFI->ArgInfo.LDSKernelId, 0, 1) ||
2065 parseAndCheckArgument(YamlMFI.ArgInfo->WorkGroupIDX,
2066 AMDGPU::SGPR_32RegClass, MFI->ArgInfo.WorkGroupIDX,
2067 0, 1) ||
2068 parseAndCheckArgument(YamlMFI.ArgInfo->WorkGroupIDY,
2069 AMDGPU::SGPR_32RegClass, MFI->ArgInfo.WorkGroupIDY,
2070 0, 1) ||
2071 parseAndCheckArgument(YamlMFI.ArgInfo->WorkGroupIDZ,
2072 AMDGPU::SGPR_32RegClass, MFI->ArgInfo.WorkGroupIDZ,
2073 0, 1) ||
2074 parseAndCheckArgument(YamlMFI.ArgInfo->WorkGroupInfo,
2075 AMDGPU::SGPR_32RegClass,
2076 MFI->ArgInfo.WorkGroupInfo, 0, 1) ||
2077 parseAndCheckArgument(YamlMFI.ArgInfo->PrivateSegmentWaveByteOffset,
2078 AMDGPU::SGPR_32RegClass,
2079 MFI->ArgInfo.PrivateSegmentWaveByteOffset, 0, 1) ||
2080 parseAndCheckArgument(YamlMFI.ArgInfo->ImplicitArgPtr,
2081 AMDGPU::SReg_64RegClass,
2082 MFI->ArgInfo.ImplicitArgPtr, 0, 0) ||
2083 parseAndCheckArgument(YamlMFI.ArgInfo->ImplicitBufferPtr,
2084 AMDGPU::SReg_64RegClass,
2085 MFI->ArgInfo.ImplicitBufferPtr, 2, 0) ||
2086 parseAndCheckArgument(YamlMFI.ArgInfo->WorkItemIDX,
2087 AMDGPU::VGPR_32RegClass,
2088 MFI->ArgInfo.WorkItemIDX, 0, 0) ||
2089 parseAndCheckArgument(YamlMFI.ArgInfo->WorkItemIDY,
2090 AMDGPU::VGPR_32RegClass,
2091 MFI->ArgInfo.WorkItemIDY, 0, 0) ||
2092 parseAndCheckArgument(YamlMFI.ArgInfo->WorkItemIDZ,
2093 AMDGPU::VGPR_32RegClass,
2094 MFI->ArgInfo.WorkItemIDZ, 0, 0)))
2095 return true;
2096
2097 // Parse FirstKernArgPreloadReg separately, since it's a Register,
2098 // not ArgDescriptor.
2099 if (YamlMFI.ArgInfo && YamlMFI.ArgInfo->FirstKernArgPreloadReg) {
2100 const yaml::SIArgument &A = *YamlMFI.ArgInfo->FirstKernArgPreloadReg;
2101
2102 if (!A.IsRegister) {
2103 // For stack arguments, we don't have RegisterName.SourceRange,
2104 // but we should have some location info from the YAML parser
2105 const MemoryBuffer &Buffer =
2106 *PFS.SM->getMemoryBuffer(PFS.SM->getMainFileID());
2107 // Create a minimal valid source range
2109 SMRange Range(Loc, Loc);
2110
2112 *PFS.SM, Loc, Buffer.getBufferIdentifier(), 1, 0, SourceMgr::DK_Error,
2113 "firstKernArgPreloadReg must be a register, not a stack location", "",
2114 {}, {});
2115
2116 SourceRange = Range;
2117 return true;
2118 }
2119
2120 Register Reg;
2121 if (parseNamedRegisterReference(PFS, Reg, A.RegisterName.Value, Error)) {
2122 SourceRange = A.RegisterName.SourceRange;
2123 return true;
2124 }
2125
2126 if (!AMDGPU::SGPR_32RegClass.contains(Reg))
2127 return diagnoseRegisterClass(A.RegisterName);
2128
2129 MFI->ArgInfo.FirstKernArgPreloadReg = Reg;
2130 MFI->NumUserSGPRs += YamlMFI.NumKernargPreloadSGPRs;
2131 }
2132
2133 if (ST.hasIEEEMode())
2134 MFI->Mode.IEEE = YamlMFI.Mode.IEEE;
2135 if (ST.hasDX10ClampMode())
2136 MFI->Mode.DX10Clamp = YamlMFI.Mode.DX10Clamp;
2137
2138 // FIXME: Move proper support for denormal-fp-math into base MachineFunction
2139 MFI->Mode.FP32Denormals.Input = YamlMFI.Mode.FP32InputDenormals
2142 MFI->Mode.FP32Denormals.Output = YamlMFI.Mode.FP32OutputDenormals
2145
2152
2153 if (YamlMFI.HasInitWholeWave)
2154 MFI->setInitWholeWave();
2155
2156 return false;
2157}
2158
2159//===----------------------------------------------------------------------===//
2160// AMDGPU CodeGen Pass Builder interface.
2161//===----------------------------------------------------------------------===//
2162
2163AMDGPUCodeGenPassBuilder::AMDGPUCodeGenPassBuilder(
2164 GCNTargetMachine &TM, const CGPassBuilderOption &Opts,
2166 : CodeGenPassBuilder(TM, Opts, PIC) {
2167 Opt.MISchedPostRA = true;
2168 Opt.RequiresCodeGenSCCOrder = true;
2169 // Exceptions and StackMaps are not supported, so these passes will never do
2170 // anything.
2171 // Garbage collection is not supported.
2172 disablePass<StackMapLivenessPass, FuncletLayoutPass, PatchableFunctionPass,
2174}
2175
2176void AMDGPUCodeGenPassBuilder::addIRPasses(PassManagerWrapper &PMW) const {
2177 if (RemoveIncompatibleFunctions && TM.getTargetTriple().isAMDGCN()) {
2178 flushFPMsToMPM(PMW);
2179 addModulePass(AMDGPURemoveIncompatibleFunctionsPass(TM), PMW);
2180 }
2181
2182 flushFPMsToMPM(PMW);
2183
2184 if (TM.getTargetTriple().isAMDGCN())
2185 addModulePass(AMDGPUPrintfRuntimeBindingPass(), PMW);
2186
2187 if (LowerCtorDtor)
2188 addModulePass(AMDGPUCtorDtorLoweringPass(), PMW);
2189
2190 if (isPassEnabled(EnableImageIntrinsicOptimizer))
2191 addFunctionPass(AMDGPUImageIntrinsicOptimizerPass(TM), PMW);
2192
2194 addFunctionPass(AMDGPUUniformIntrinsicCombinePass(), PMW);
2195 // This can be disabled by passing ::Disable here or on the command line
2196 // with --expand-variadics-override=disable.
2197 flushFPMsToMPM(PMW);
2199
2200 addModulePass(AMDGPUAlwaysInlinePass(), PMW);
2201 addModulePass(AlwaysInlinerPass(), PMW);
2202
2203 addModulePass(AMDGPUExportKernelRuntimeHandlesPass(), PMW);
2204
2206 addModulePass(AMDGPULowerExecSyncPass(), PMW);
2207
2208 if (EnableSwLowerLDS)
2209 addModulePass(AMDGPUSwLowerLDSPass(TM), PMW);
2210
2211 // Runs before PromoteAlloca so the latter can account for function uses
2213 addModulePass(AMDGPULowerModuleLDSPass(TM), PMW);
2214
2215 // Run atomic optimizer before Atomic Expand
2216 if (TM.getOptLevel() >= CodeGenOptLevel::Less &&
2218 addFunctionPass(
2220
2221 addFunctionPass(AtomicExpandPass(TM), PMW);
2222
2223 if (TM.getOptLevel() > CodeGenOptLevel::None) {
2224 addFunctionPass(AMDGPUPromoteAllocaPass(TM), PMW);
2225 if (isPassEnabled(EnableScalarIRPasses))
2226 addStraightLineScalarOptimizationPasses(PMW);
2227
2228 // TODO: Handle EnableAMDGPUAliasAnalysis
2229
2230 // TODO: May want to move later or split into an early and late one.
2231 addFunctionPass(AMDGPUCodeGenPreparePass(TM), PMW);
2232
2233 // Try to hoist loop invariant parts of divisions AMDGPUCodeGenPrepare may
2234 // have expanded.
2235 if (TM.getOptLevel() > CodeGenOptLevel::Less) {
2237 /*UseMemorySSA=*/true),
2238 PMW);
2239 }
2240 }
2241
2242 Base::addIRPasses(PMW);
2243
2244 // EarlyCSE is not always strong enough to clean up what LSR produces. For
2245 // example, GVN can combine
2246 //
2247 // %0 = add %a, %b
2248 // %1 = add %b, %a
2249 //
2250 // and
2251 //
2252 // %0 = shl nsw %a, 2
2253 // %1 = shl %a, 2
2254 //
2255 // but EarlyCSE can do neither of them.
2256 if (isPassEnabled(EnableScalarIRPasses))
2257 addEarlyCSEOrGVNPass(PMW);
2258}
2259
2260void AMDGPUCodeGenPassBuilder::addCodeGenPrepare(
2261 PassManagerWrapper &PMW) const {
2262 if (TM.getOptLevel() > CodeGenOptLevel::None) {
2263 flushFPMsToMPM(PMW);
2264 addModulePass(AMDGPUPreloadKernelArgumentsPass(TM), PMW);
2265 }
2266
2268 addFunctionPass(AMDGPULowerKernelArgumentsPass(TM), PMW);
2269
2270 Base::addCodeGenPrepare(PMW);
2271
2272 if (isPassEnabled(EnableLoadStoreVectorizer))
2273 addFunctionPass(LoadStoreVectorizerPass(), PMW);
2274
2275 // This lowering has been placed after codegenprepare to take advantage of
2276 // address mode matching (which is why it isn't put with the LDS lowerings).
2277 // It could be placed anywhere before uniformity annotations (an analysis
2278 // that it changes by splitting up fat pointers into their components)
2279 // but has been put before switch lowering and CFG flattening so that those
2280 // passes can run on the more optimized control flow this pass creates in
2281 // many cases.
2282 flushFPMsToMPM(PMW);
2283 addModulePass(AMDGPULowerBufferFatPointersPass(TM), PMW);
2284 flushFPMsToMPM(PMW);
2285 requireCGSCCOrder(PMW);
2286
2287 addModulePass(AMDGPULowerIntrinsicsPass(TM), PMW);
2288
2289 // LowerSwitch pass may introduce unreachable blocks that can cause unexpected
2290 // behavior for subsequent passes. Placing it here seems better that these
2291 // blocks would get cleaned up by UnreachableBlockElim inserted next in the
2292 // pass flow.
2293 addFunctionPass(LowerSwitchPass(), PMW);
2294}
2295
2296void AMDGPUCodeGenPassBuilder::addPreISel(PassManagerWrapper &PMW) const {
2297
2298 if (TM.getOptLevel() > CodeGenOptLevel::None) {
2299 addFunctionPass(FlattenCFGPass(), PMW);
2300 addFunctionPass(SinkingPass(), PMW);
2301 addFunctionPass(AMDGPULateCodeGenPreparePass(TM), PMW);
2302 }
2303
2304 // Merge divergent exit nodes. StructurizeCFG won't recognize the multi-exit
2305 // regions formed by them.
2306
2307 addFunctionPass(AMDGPUUnifyDivergentExitNodesPass(), PMW);
2308 addFunctionPass(FixIrreduciblePass(), PMW);
2309 addFunctionPass(UnifyLoopExitsPass(), PMW);
2310 addFunctionPass(StructurizeCFGPass(/*SkipUniformRegions=*/false), PMW);
2311
2312 addFunctionPass(AMDGPUAnnotateUniformValuesPass(), PMW);
2313
2314 addFunctionPass(SIAnnotateControlFlowPass(TM), PMW);
2315
2316 // TODO: Move this right after structurizeCFG to avoid extra divergence
2317 // analysis. This depends on stopping SIAnnotateControlFlow from making
2318 // control flow modifications.
2319 addFunctionPass(AMDGPURewriteUndefForPHIPass(), PMW);
2320
2322 !isGlobalISelAbortEnabled() || !NewRegBankSelect)
2323 addFunctionPass(LCSSAPass(), PMW);
2324
2325 if (TM.getOptLevel() > CodeGenOptLevel::Less) {
2326 flushFPMsToMPM(PMW);
2327 addModulePass(AMDGPUPerfHintAnalysisPass(TM), PMW);
2328 }
2329
2330 // FIXME: Why isn't this queried as required from AMDGPUISelDAGToDAG, and why
2331 // isn't this in addInstSelector?
2333 /*Force=*/true);
2334}
2335
2336void AMDGPUCodeGenPassBuilder::addILPOpts(PassManagerWrapper &PMW) const {
2338 addMachineFunctionPass(EarlyIfConverterPass(), PMW);
2339
2340 Base::addILPOpts(PMW);
2341}
2342
2343void AMDGPUCodeGenPassBuilder::addAsmPrinterBegin(
2344 PassManagerWrapper &PMW, CreateMCStreamer CreateStreamer) const {
2345 // TODO: Add AsmPrinterBegin
2346}
2347
2348void AMDGPUCodeGenPassBuilder::addAsmPrinter(
2349 PassManagerWrapper &PMW, CreateMCStreamer CreateStreamer) const {
2350 // TODO: Add AsmPrinter.
2351}
2352
2353void AMDGPUCodeGenPassBuilder::addAsmPrinterEnd(
2354 PassManagerWrapper &PMW, CreateMCStreamer CreateStreamer) const {
2355 // TODO: Add AsmPrinterEnd
2356}
2357
2358Error AMDGPUCodeGenPassBuilder::addInstSelector(PassManagerWrapper &PMW) const {
2359 addMachineFunctionPass(AMDGPUISelDAGToDAGPass(TM), PMW);
2360 addMachineFunctionPass(SIFixSGPRCopiesPass(), PMW);
2361 addMachineFunctionPass(SILowerI1CopiesPass(), PMW);
2362 return Error::success();
2363}
2364
2365void AMDGPUCodeGenPassBuilder::addPreRewrite(PassManagerWrapper &PMW) const {
2366 if (EnableRegReassign) {
2367 addMachineFunctionPass(GCNNSAReassignPass(), PMW);
2368 }
2369
2370 addMachineFunctionPass(AMDGPURewriteAGPRCopyMFMAPass(), PMW);
2371}
2372
2373void AMDGPUCodeGenPassBuilder::addMachineSSAOptimization(
2374 PassManagerWrapper &PMW) const {
2375 Base::addMachineSSAOptimization(PMW);
2376
2377 addMachineFunctionPass(SIFoldOperandsPass(), PMW);
2378 if (EnableDPPCombine) {
2379 addMachineFunctionPass(GCNDPPCombinePass(), PMW);
2380 }
2381 addMachineFunctionPass(SILoadStoreOptimizerPass(), PMW);
2382 if (isPassEnabled(EnableSDWAPeephole)) {
2383 addMachineFunctionPass(SIPeepholeSDWAPass(), PMW);
2384 addMachineFunctionPass(EarlyMachineLICMPass(), PMW);
2385 addMachineFunctionPass(MachineCSEPass(), PMW);
2386 addMachineFunctionPass(SIFoldOperandsPass(), PMW);
2387 }
2388 addMachineFunctionPass(DeadMachineInstructionElimPass(), PMW);
2389 addMachineFunctionPass(SIShrinkInstructionsPass(), PMW);
2390}
2391
2392Error AMDGPUCodeGenPassBuilder::addFastRegAlloc(PassManagerWrapper &PMW) const {
2393 insertPass<PHIEliminationPass>(SILowerControlFlowPass());
2394
2395 insertPass<TwoAddressInstructionPass>(SIWholeQuadModePass());
2396
2397 return Base::addFastRegAlloc(PMW);
2398}
2399
2400Error AMDGPUCodeGenPassBuilder::addRegAssignmentFast(
2401 PassManagerWrapper &PMW) const {
2402 if (auto Err = validateRegAllocOptions())
2403 return Err;
2404
2405 addMachineFunctionPass(GCNPreRALongBranchRegPass(), PMW);
2406
2407 // SGPR allocation - default to fast at -O0.
2408 if (SGPRRegAllocNPM == RegAllocType::Greedy)
2409 addMachineFunctionPass(RAGreedyPass({onlyAllocateSGPRs, "sgpr"}), PMW);
2410 else
2411 addMachineFunctionPass(RegAllocFastPass({onlyAllocateSGPRs, "sgpr", false}),
2412 PMW);
2413
2414 // Equivalent of PEI for SGPRs.
2415 addMachineFunctionPass(SILowerSGPRSpillsPass(), PMW);
2416
2417 // To Allocate wwm registers used in whole quad mode operations (for shaders).
2418 addMachineFunctionPass(SIPreAllocateWWMRegsPass(), PMW);
2419
2420 // WWM allocation - default to fast at -O0.
2421 if (WWMRegAllocNPM == RegAllocType::Greedy)
2422 addMachineFunctionPass(RAGreedyPass({onlyAllocateWWMRegs, "wwm"}), PMW);
2423 else
2424 addMachineFunctionPass(
2425 RegAllocFastPass({onlyAllocateWWMRegs, "wwm", false}), PMW);
2426
2427 addMachineFunctionPass(SILowerWWMCopiesPass(), PMW);
2428 addMachineFunctionPass(AMDGPUReserveWWMRegsPass(), PMW);
2429
2430 // VGPR allocation - default to fast at -O0.
2431 if (VGPRRegAllocNPM == RegAllocType::Greedy)
2432 addMachineFunctionPass(RAGreedyPass({onlyAllocateVGPRs, "vgpr"}), PMW);
2433 else
2434 addMachineFunctionPass(RegAllocFastPass({onlyAllocateVGPRs, "vgpr"}), PMW);
2435
2436 return Error::success();
2437}
2438
2439Error AMDGPUCodeGenPassBuilder::addOptimizedRegAlloc(
2440 PassManagerWrapper &PMW) const {
2441 if (EnableDCEInRA)
2442 insertPass<DetectDeadLanesPass>(DeadMachineInstructionElimPass());
2443
2444 // FIXME: when an instruction has a Killed operand, and the instruction is
2445 // inside a bundle, seems only the BUNDLE instruction appears as the Kills of
2446 // the register in LiveVariables, this would trigger a failure in verifier,
2447 // we should fix it and enable the verifier.
2448 if (OptVGPRLiveRange)
2449 insertPass<RequireAnalysisPass<LiveVariablesAnalysis, MachineFunction>>(
2451
2452 // This must be run immediately after phi elimination and before
2453 // TwoAddressInstructions, otherwise the processing of the tied operand of
2454 // SI_ELSE will introduce a copy of the tied operand source after the else.
2455 insertPass<PHIEliminationPass>(SILowerControlFlowPass());
2456
2458 insertPass<RenameIndependentSubregsPass>(GCNRewritePartialRegUsesPass());
2459
2460 if (isPassEnabled(EnablePreRAOptimizations))
2461 insertPass<MachineSchedulerPass>(GCNPreRAOptimizationsPass());
2462
2463 // Allow the scheduler to run before SIWholeQuadMode inserts exec manipulation
2464 // instructions that cause scheduling barriers.
2465 insertPass<MachineSchedulerPass>(SIWholeQuadModePass());
2466
2467 if (OptExecMaskPreRA)
2468 insertPass<MachineSchedulerPass>(SIOptimizeExecMaskingPreRAPass());
2469
2470 // This is not an essential optimization and it has a noticeable impact on
2471 // compilation time, so we only enable it from O2.
2472 if (TM.getOptLevel() > CodeGenOptLevel::Less)
2473 insertPass<MachineSchedulerPass>(SIFormMemoryClausesPass());
2474
2475 return Base::addOptimizedRegAlloc(PMW);
2476}
2477
2478void AMDGPUCodeGenPassBuilder::addPreRegAlloc(PassManagerWrapper &PMW) const {
2479 if (getOptLevel() != CodeGenOptLevel::None)
2480 addMachineFunctionPass(AMDGPUPrepareAGPRAllocPass(), PMW);
2481}
2482
2483Error AMDGPUCodeGenPassBuilder::addRegAssignmentOptimized(
2484 PassManagerWrapper &PMW) const {
2485 if (auto Err = validateRegAllocOptions())
2486 return Err;
2487
2488 addMachineFunctionPass(GCNPreRALongBranchRegPass(), PMW);
2489
2490 // SGPR allocation - default to greedy at -O1 and above.
2491 if (SGPRRegAllocNPM == RegAllocType::Fast)
2492 addMachineFunctionPass(RegAllocFastPass({onlyAllocateSGPRs, "sgpr", false}),
2493 PMW);
2494 else
2495 addMachineFunctionPass(RAGreedyPass({onlyAllocateSGPRs, "sgpr"}), PMW);
2496
2497 // Commit allocated register changes. This is mostly necessary because too
2498 // many things rely on the use lists of the physical registers, such as the
2499 // verifier. This is only necessary with allocators which use LiveIntervals,
2500 // since FastRegAlloc does the replacements itself.
2501 addMachineFunctionPass(VirtRegRewriterPass(false), PMW);
2502
2503 // At this point, the sgpr-regalloc has been done and it is good to have the
2504 // stack slot coloring to try to optimize the SGPR spill stack indices before
2505 // attempting the custom SGPR spill lowering.
2506 addMachineFunctionPass(StackSlotColoringPass(), PMW);
2507
2508 // Equivalent of PEI for SGPRs.
2509 addMachineFunctionPass(SILowerSGPRSpillsPass(), PMW);
2510
2511 // To Allocate wwm registers used in whole quad mode operations (for shaders).
2512 addMachineFunctionPass(SIPreAllocateWWMRegsPass(), PMW);
2513
2514 // WWM allocation - default to greedy at -O1 and above.
2515 if (WWMRegAllocNPM == RegAllocType::Fast)
2516 addMachineFunctionPass(
2517 RegAllocFastPass({onlyAllocateWWMRegs, "wwm", false}), PMW);
2518 else
2519 addMachineFunctionPass(RAGreedyPass({onlyAllocateWWMRegs, "wwm"}), PMW);
2520 addMachineFunctionPass(SILowerWWMCopiesPass(), PMW);
2521 addMachineFunctionPass(VirtRegRewriterPass(false), PMW);
2522 addMachineFunctionPass(AMDGPUReserveWWMRegsPass(), PMW);
2523
2524 // VGPR allocation - default to greedy at -O1 and above.
2525 if (VGPRRegAllocNPM == RegAllocType::Fast)
2526 addMachineFunctionPass(RegAllocFastPass({onlyAllocateVGPRs, "vgpr"}), PMW);
2527 else
2528 addMachineFunctionPass(RAGreedyPass({onlyAllocateVGPRs, "vgpr"}), PMW);
2529
2530 addPreRewrite(PMW);
2531 addMachineFunctionPass(VirtRegRewriterPass(true), PMW);
2532
2533 addMachineFunctionPass(AMDGPUMarkLastScratchLoadPass(), PMW);
2534 return Error::success();
2535}
2536
2537void AMDGPUCodeGenPassBuilder::addPostRegAlloc(PassManagerWrapper &PMW) const {
2538 addMachineFunctionPass(SIFixVGPRCopiesPass(), PMW);
2539 if (TM.getOptLevel() > CodeGenOptLevel::None)
2540 addMachineFunctionPass(SIOptimizeExecMaskingPass(), PMW);
2541 Base::addPostRegAlloc(PMW);
2542}
2543
2544void AMDGPUCodeGenPassBuilder::addPreSched2(PassManagerWrapper &PMW) const {
2545 if (TM.getOptLevel() > CodeGenOptLevel::None)
2546 addMachineFunctionPass(SIShrinkInstructionsPass(), PMW);
2547 addMachineFunctionPass(SIPostRABundlerPass(), PMW);
2548}
2549
2550void AMDGPUCodeGenPassBuilder::addPostBBSections(
2551 PassManagerWrapper &PMW) const {
2552 // We run this later to avoid passes like livedebugvalues and BBSections
2553 // having to deal with the apparent multi-entry functions we may generate.
2554 addMachineFunctionPass(AMDGPUPreloadKernArgPrologPass(), PMW);
2555}
2556
2557void AMDGPUCodeGenPassBuilder::addPreEmitPass(PassManagerWrapper &PMW) const {
2558 if (isPassEnabled(EnableVOPD, CodeGenOptLevel::Less)) {
2559 addMachineFunctionPass(GCNCreateVOPDPass(), PMW);
2560 }
2561
2562 addMachineFunctionPass(SIMemoryLegalizerPass(), PMW);
2563 addMachineFunctionPass(SIInsertWaitcntsPass(), PMW);
2564
2565 addMachineFunctionPass(SIModeRegisterPass(), PMW);
2566
2567 if (TM.getOptLevel() > CodeGenOptLevel::None)
2568 addMachineFunctionPass(SIInsertHardClausesPass(), PMW);
2569
2570 addMachineFunctionPass(SILateBranchLoweringPass(), PMW);
2571
2572 if (isPassEnabled(EnableSetWavePriority, CodeGenOptLevel::Less))
2573 addMachineFunctionPass(AMDGPUSetWavePriorityPass(), PMW);
2574
2575 if (TM.getOptLevel() > CodeGenOptLevel::None)
2576 addMachineFunctionPass(SIPreEmitPeepholePass(), PMW);
2577
2578 // The hazard recognizer that runs as part of the post-ra scheduler does not
2579 // guarantee to be able handle all hazards correctly. This is because if there
2580 // are multiple scheduling regions in a basic block, the regions are scheduled
2581 // bottom up, so when we begin to schedule a region we don't know what
2582 // instructions were emitted directly before it.
2583 //
2584 // Here we add a stand-alone hazard recognizer pass which can handle all
2585 // cases.
2586 addMachineFunctionPass(PostRAHazardRecognizerPass(), PMW);
2587 addMachineFunctionPass(AMDGPUWaitSGPRHazardsPass(), PMW);
2588 addMachineFunctionPass(AMDGPULowerVGPREncodingPass(), PMW);
2589
2590 if (isPassEnabled(EnableInsertDelayAlu, CodeGenOptLevel::Less)) {
2591 addMachineFunctionPass(AMDGPUInsertDelayAluPass(), PMW);
2592 }
2593
2594 addMachineFunctionPass(BranchRelaxationPass(), PMW);
2595}
2596
2597bool AMDGPUCodeGenPassBuilder::isPassEnabled(const cl::opt<bool> &Opt,
2598 CodeGenOptLevel Level) const {
2599 if (Opt.getNumOccurrences())
2600 return Opt;
2601 if (TM.getOptLevel() < Level)
2602 return false;
2603 return Opt;
2604}
2605
2606void AMDGPUCodeGenPassBuilder::addEarlyCSEOrGVNPass(
2607 PassManagerWrapper &PMW) const {
2608 if (TM.getOptLevel() == CodeGenOptLevel::Aggressive)
2609 addFunctionPass(GVNPass(), PMW);
2610 else
2611 addFunctionPass(EarlyCSEPass(), PMW);
2612}
2613
2614void AMDGPUCodeGenPassBuilder::addStraightLineScalarOptimizationPasses(
2615 PassManagerWrapper &PMW) const {
2617 addFunctionPass(LoopDataPrefetchPass(), PMW);
2618
2619 addFunctionPass(SeparateConstOffsetFromGEPPass(), PMW);
2620
2621 // ReassociateGEPs exposes more opportunities for SLSR. See
2622 // the example in reassociate-geps-and-slsr.ll.
2623 addFunctionPass(StraightLineStrengthReducePass(), PMW);
2624
2625 // SeparateConstOffsetFromGEP and SLSR creates common expressions which GVN or
2626 // EarlyCSE can reuse.
2627 addEarlyCSEOrGVNPass(PMW);
2628
2629 // Run NaryReassociate after EarlyCSE/GVN to be more effective.
2630 addFunctionPass(NaryReassociatePass(), PMW);
2631
2632 // NaryReassociate on GEPs creates redundant common expressions, so run
2633 // EarlyCSE after it.
2634 addFunctionPass(EarlyCSEPass(), PMW);
2635}
unsigned const MachineRegisterInfo * MRI
aarch64 falkor hwpf fix Falkor HW Prefetch Fix Late Phase
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
static cl::opt< bool > EnableEarlyIfConversion("aarch64-enable-early-ifcvt", cl::Hidden, cl::desc("Run early if-conversion"), cl::init(true))
static std::unique_ptr< TargetLoweringObjectFile > createTLOF(const Triple &TT)
This is the AMGPU address space based alias analysis pass.
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< bool > EnableDCEInRA("amdgpu-dce-in-ra", cl::init(true), cl::Hidden, cl::desc("Enable machine DCE inside regalloc"))
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 MachineSchedRegistry GCNMaxMemoryClauseSchedRegistry("gcn-max-memory-clause", "Run GCN scheduler to maximize memory clause", createGCNMaxMemoryClauseMachineScheduler)
static Reloc::Model getEffectiveRelocModel()
static cl::opt< bool > EnableUniformIntrinsicCombine("amdgpu-enable-uniform-intrinsic-combine", cl::desc("Enable/Disable the Uniform Intrinsic Combine Pass"), cl::init(true), cl::Hidden)
static MachineSchedRegistry SISchedRegistry("si", "Run SI's custom scheduler", createSIMachineScheduler)
static ScheduleDAGInstrs * createIterativeILPMachineScheduler(MachineSchedContext *C)
static cl::opt< bool > EarlyInlineAll("amdgpu-early-inline-all", cl::desc("Inline all functions early"), cl::init(false), cl::Hidden)
static cl::opt< bool > EnableSwLowerLDS("amdgpu-enable-sw-lower-lds", cl::desc("Enable lowering of lds to global memory pass " "and asan instrument resulting IR."), cl::init(true), cl::Hidden)
static cl::opt< bool > EnableLowerKernelArguments("amdgpu-ir-lower-kernel-arguments", cl::desc("Lower kernel argument loads in IR pass"), cl::init(true), cl::Hidden)
static ScheduleDAGInstrs * createGCNMaxILPMachineScheduler(MachineSchedContext *C)
static cl::opt< bool > EnableSDWAPeephole("amdgpu-sdwa-peephole", cl::desc("Enable SDWA peepholer"), cl::init(true))
static MachineSchedRegistry GCNMinRegSchedRegistry("gcn-iterative-minreg", "Run GCN iterative scheduler for minimal register usage (experimental)", createMinRegScheduler)
static cl::opt< bool > EnableImageIntrinsicOptimizer("amdgpu-enable-image-intrinsic-optimizer", cl::desc("Enable image intrinsic optimizer pass"), cl::init(true), cl::Hidden)
static cl::opt< bool > HasClosedWorldAssumption("amdgpu-link-time-closed-world", cl::desc("Whether has closed-world assumption at link time"), cl::init(false), cl::Hidden)
static ScheduleDAGInstrs * createGCNMaxMemoryClauseMachineScheduler(MachineSchedContext *C)
static cl::opt< bool > EnableSIModeRegisterPass("amdgpu-mode-register", cl::desc("Enable mode register pass"), cl::init(true), cl::Hidden)
static cl::opt< std::string > AMDGPUSchedStrategy("amdgpu-sched-strategy", cl::desc("Select custom AMDGPU scheduling strategy."), cl::Hidden, cl::init(""))
static cl::opt< bool > EnableDPPCombine("amdgpu-dpp-combine", cl::desc("Enable DPP combiner"), cl::init(true))
static MachineSchedRegistry IterativeGCNMaxOccupancySchedRegistry("gcn-iterative-max-occupancy-experimental", "Run GCN scheduler to maximize occupancy (experimental)", createIterativeGCNMaxOccupancyMachineScheduler)
static cl::opt< bool > EnableSetWavePriority("amdgpu-set-wave-priority", cl::desc("Adjust wave priority"), cl::init(false), cl::Hidden)
static cl::opt< bool > LowerCtorDtor("amdgpu-lower-global-ctor-dtor", cl::desc("Lower GPU ctor / dtors to globals on the device."), cl::init(true), cl::Hidden)
static cl::opt< bool > OptExecMaskPreRA("amdgpu-opt-exec-mask-pre-ra", cl::Hidden, cl::desc("Run pre-RA exec mask optimizations"), cl::init(true))
static cl::opt< bool > EnablePromoteKernelArguments("amdgpu-enable-promote-kernel-arguments", cl::desc("Enable promotion of flat kernel pointer arguments to global"), cl::Hidden, cl::init(true))
LLVM_ABI LLVM_EXTERNAL_VISIBILITY void LLVMInitializeAMDGPUTarget()
static cl::opt< bool > EnableRewritePartialRegUses("amdgpu-enable-rewrite-partial-reg-uses", cl::desc("Enable rewrite partial reg uses pass"), cl::init(true), cl::Hidden)
static cl::opt< bool > EnableLibCallSimplify("amdgpu-simplify-libcall", cl::desc("Enable amdgpu library simplifications"), cl::init(true), cl::Hidden)
static MachineSchedRegistry GCNMaxILPSchedRegistry("gcn-max-ilp", "Run GCN scheduler to maximize ilp", createGCNMaxILPMachineScheduler)
static cl::opt< bool > InternalizeSymbols("amdgpu-internalize-symbols", cl::desc("Enable elimination of non-kernel functions and unused globals"), cl::init(false), cl::Hidden)
static cl::opt< bool > EnableAMDGPUAttributor("amdgpu-attributor-enable", cl::desc("Enable AMDGPUAttributorPass"), cl::init(true), cl::Hidden)
static LLVM_READNONE StringRef getGPUOrDefault(const Triple &TT, StringRef GPU)
Expected< AMDGPUAttributorOptions > parseAMDGPUAttributorPassOptions(StringRef Params)
static cl::opt< bool > EnableAMDGPUAliasAnalysis("enable-amdgpu-aa", cl::Hidden, cl::desc("Enable AMDGPU Alias Analysis"), cl::init(true))
static Expected< ScanOptions > parseAMDGPUAtomicOptimizerStrategy(StringRef Params)
static ScheduleDAGInstrs * createMinRegScheduler(MachineSchedContext *C)
static cl::opt< bool > EnableHipStdPar("amdgpu-enable-hipstdpar", cl::desc("Enable HIP Standard Parallelism Offload support"), cl::init(false), cl::Hidden)
static cl::opt< bool > EnableInsertDelayAlu("amdgpu-enable-delay-alu", cl::desc("Enable s_delay_alu insertion"), cl::init(true), cl::Hidden)
static ScheduleDAGInstrs * createIterativeGCNMaxOccupancyMachineScheduler(MachineSchedContext *C)
static cl::opt< bool > EnableLoadStoreVectorizer("amdgpu-load-store-vectorizer", cl::desc("Enable load store vectorizer"), cl::init(true), cl::Hidden)
static bool mustPreserveGV(const GlobalValue &GV)
Predicate for Internalize pass.
static cl::opt< bool > EnableLoopPrefetch("amdgpu-loop-prefetch", cl::desc("Enable loop data prefetch on AMDGPU"), cl::Hidden, cl::init(false))
static cl::opt< bool > NewRegBankSelect("new-reg-bank-select", cl::desc("Run amdgpu-regbankselect and amdgpu-regbanklegalize instead of " "regbankselect"), cl::init(false), cl::Hidden)
static cl::opt< bool > RemoveIncompatibleFunctions("amdgpu-enable-remove-incompatible-functions", cl::Hidden, cl::desc("Enable removal of functions when they" "use features not supported by the target GPU"), cl::init(true))
static cl::opt< bool > EnableScalarIRPasses("amdgpu-scalar-ir-passes", cl::desc("Enable scalar IR passes"), cl::init(true), cl::Hidden)
static cl::opt< bool > EnableRegReassign("amdgpu-reassign-regs", cl::desc("Enable register reassign optimizations on gfx10+"), cl::init(true), cl::Hidden)
static cl::opt< bool > OptVGPRLiveRange("amdgpu-opt-vgpr-liverange", cl::desc("Enable VGPR liverange optimizations for if-else structure"), cl::init(true), cl::Hidden)
static ScheduleDAGInstrs * createSIMachineScheduler(MachineSchedContext *C)
static cl::opt< bool > EnablePreRAOptimizations("amdgpu-enable-pre-ra-optimizations", cl::desc("Enable Pre-RA optimizations pass"), cl::init(true), cl::Hidden)
static cl::opt< ScanOptions > AMDGPUAtomicOptimizerStrategy("amdgpu-atomic-optimizer-strategy", cl::desc("Select DPP or Iterative strategy for scan"), cl::init(ScanOptions::Iterative), cl::values(clEnumValN(ScanOptions::DPP, "DPP", "Use DPP operations for scan"), clEnumValN(ScanOptions::Iterative, "Iterative", "Use Iterative approach for scan"), clEnumValN(ScanOptions::None, "None", "Disable atomic optimizer")))
static cl::opt< bool > EnableVOPD("amdgpu-enable-vopd", cl::desc("Enable VOPD, dual issue of VALU in wave32"), cl::init(true), cl::Hidden)
static ScheduleDAGInstrs * createGCNMaxOccupancyMachineScheduler(MachineSchedContext *C)
static cl::opt< bool > EnableLowerExecSync("amdgpu-enable-lower-exec-sync", cl::desc("Enable lowering of execution synchronization."), cl::init(true), cl::Hidden)
static MachineSchedRegistry GCNILPSchedRegistry("gcn-iterative-ilp", "Run GCN iterative scheduler for ILP scheduling (experimental)", createIterativeILPMachineScheduler)
static cl::opt< bool > ScalarizeGlobal("amdgpu-scalarize-global-loads", cl::desc("Enable global load scalarization"), cl::init(true), cl::Hidden)
static const char RegAllocOptNotSupportedMessage[]
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.
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 clEnumValN(ENUMVAL, FLAGNAME, DESC)
#define LLVM_READNONE
Definition Compiler.h:315
#define LLVM_ABI
Definition Compiler.h:213
#define LLVM_EXTERNAL_VISIBILITY
Definition Compiler.h:132
DXIL Legalizer
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.
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
PassInstrumentationCallbacks PIC
PassBuilder PB(Machine, PassOpts->PTO, std::nullopt, &PIC)
static bool isLTOPreLink(ThinOrFullLTOPhase Phase)
The AMDGPU TargetMachine interface definition for hw codegen targets.
This file describes the interface of the MachineFunctionPass responsible for assigning the generic vi...
const GCNTargetMachine & getTM(const GCNSubtarget *STI)
SI Machine Scheduler interface.
static bool contains(SmallPtrSetImpl< ConstantExpr * > &Cache, ConstantExpr *Expr, Constant *C)
Definition Value.cpp:487
static TableGen::Emitter::Opt Y("gen-skeleton-entry", EmitSkeleton, "Generate example skeleton entry")
static TableGen::Emitter::OptClass< SkeletonEmitter > X("gen-skeleton-class", "Generate example skeleton class")
static FunctionPass * useDefaultRegisterAllocator()
-regalloc=... command line option.
static cl::opt< cl::boolOrDefault > EnableGlobalISelOption("global-isel", cl::Hidden, cl::desc("Enable the \"global\" instruction selector"))
Target-Independent Code Generator Pass Configuration Options pass.
LLVM IR instance of the generic uniformity analysis.
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.
bool isPassEnabled(const cl::opt< bool > &Opt, CodeGenOptLevel Level=CodeGenOptLevel::Default) const
Check if a pass is enabled given Opt option.
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)
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
static int64_t getNullPointerValue(unsigned AddrSpace)
Get the integer value of a null pointer in the given address space.
unsigned getAddressSpaceForPseudoSourceKind(unsigned Kind) const override
getAddressSpaceForPseudoSourceKind - Given the kind of memory (e.g.
const TargetSubtargetInfo * getSubtargetImpl() const
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,...
StringRef getFeatureString(const Function &F) const
ScheduleDAGInstrs * createMachineScheduler(MachineSchedContext *C) const override
Create an instance of ScheduleDAGInstrs to be run within the standard MachineScheduler pass for this ...
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)
bool isNoopAddrSpaceCast(unsigned SrcAS, unsigned DestAS) const override
Returns true if a cast between SrcAS and DestAS is a noop.
void registerPassBuilderCallbacks(PassBuilder &PB) override
Allow the target to modify the pass pipeline.
StringRef getGPUName(const Function &F) const
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".
Functions, function parameters, and return types can have attributes to indicate how they should be t...
Definition Attributes.h:105
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:261
This class provides access to building LLVM's passes.
CodeGenTargetMachineImpl(const Target &T, StringRef DataLayoutString, 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.
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:314
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.
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...
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)
Error buildCodeGenPipeline(ModulePassManager &MPM, raw_pwrite_stream &Out, raw_pwrite_stream *DwoOut, CodeGenFileType FileType, const CGPassBuilderOption &Opts, MCContext &Ctx, PassInstrumentationCallbacks *PIC) override
MachineFunctionInfo * createMachineFunctionInfo(BumpPtrAllocator &Allocator, const Function &F, const TargetSubtargetInfo *STI) const override
Create the target's instance of MachineFunctionInfo.
The core GVN pass object.
Definition GVN.h:128
Pass to remove unused function declarations.
Definition GlobalDCE.h:38
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:66
This pass implements the localization mechanism described at the top of this file.
Definition Localizer.h:43
An optimization pass inserting data prefetches in loops.
Context object for machine code objects.
Definition MCContext.h:83
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:67
static LLVM_ABI const OptimizationLevel O0
Disable as many optimizations as possible.
static LLVM_ABI const OptimizationLevel O1
Optimize quickly without destroying debuggability.
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:99
This pass implements the reg bank selector pass used in the GlobalISel pipeline.
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:297
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.
const TargetRegisterInfo * TRI
Target processor register info.
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:26
void append(StringRef RHS)
Append from a StringRef.
Definition SmallString.h:68
unsigned getMainFileID() const
Definition SourceMgr.h:148
const MemoryBuffer * getMemoryBuffer(unsigned i) const
Definition SourceMgr.h:141
StringRef - Represent a constant reference to a string, i.e.
Definition StringRef.h:55
std::pair< StringRef, StringRef > split(char Separator) const
Split into two substrings around the first occurrence of a separator character.
Definition StringRef.h:730
constexpr bool empty() const
empty - Check if the string is empty.
Definition StringRef.h:140
bool consume_front(char Prefix)
Returns true if this StringRef has the given prefix and removes that prefix.
Definition StringRef.h:655
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
StringRef getTargetCPU() const
std::unique_ptr< const MCSubtargetInfo > STI
TargetOptions Options
void resetTargetOptions(const Function &F) const
Reset the target options based on the function's attributes.
std::unique_ptr< const MCRegisterInfo > MRI
CodeGenOptLevel OptLevel
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)
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:47
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:346
int getNumOccurrences() const
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 ...
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.
@ REGION_ADDRESS
Address space for region memory. (GDS)
@ 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.
bool isFlatGlobalAddrSpace(unsigned AS)
LLVM_READNONE constexpr bool isModuleEntryFunctionCC(CallingConv::ID CC)
LLVM_READNONE constexpr bool isEntryFunctionCC(CallingConv::ID CC)
@ C
The default llvm calling convention, compatible with C.
Definition CallingConv.h:34
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)
IntrinsicID_match m_Intrinsic()
Match intrinsic calls like this: m_Intrinsic<Intrinsic::fabs>(m_Value(X))
deferredval_ty< 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()...
class_match< Value > m_Value()
Match an arbitrary value and ignore it.
template class LLVM_TEMPLATE_ABI opt< bool >
ValuesClass values(OptsTy... Options)
Helper to build a ValuesClass by forwarding a variable number of arguments as an initializer list to ...
initializer< Ty > init(const Ty &Val)
LocationClass< Ty > location(Ty &L)
This is an optimization pass for GlobalISel generic memory operations.
Definition Types.h:26
ScheduleDAGMILive * createSchedLive(MachineSchedContext *C)
Create the standard converging machine scheduler.
LLVM_ABI FunctionPass * createFlattenCFGPass()
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:525
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 &)
ModulePass * createExpandVariadicsPass(ExpandVariadicsMode)
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.
ModulePass * createAMDGPUSwLowerLDSLegacyPass(const AMDGPUTargetMachine *TM=nullptr)
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 &)
char & AMDGPUWaitSGPRHazardsLegacyID
void initializeSILowerSGPRSpillsLegacyPass(PassRegistry &)
LLVM_ABI Pass * createLoadStoreVectorizerPass()
Create a legacy pass manager instance of the LoadStoreVectorizer pass.
std::unique_ptr< ScheduleDAGMutation > createIGroupLPDAGMutation(AMDGPU::SchedulingPhase Phase)
Phase specifes whether or not this is a reentry into the IGroupLPDAGMutation.
void initializeAMDGPUDAGToDAGISelLegacyPass(PassRegistry &)
FunctionPass * createAMDGPURegBankCombiner(bool IsOptNone)
LLVM_ABI FunctionPass * createNaryReassociatePass()
char & AMDGPUReserveWWMRegsLegacyID
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.
void initializeR600ExpandSpecialInstrsPassPass(PassRegistry &)
void initializeR600PacketizerPass(PassRegistry &)
std::unique_ptr< ScheduleDAGMutation > createVOPDPairingMutation()
ModulePass * createAMDGPUExportKernelRuntimeHandlesLegacyPass()
ModulePass * createAMDGPUAlwaysInlinePass(bool GlobalOpt=true)
void initializeAMDGPUAsmPrinterPass(PassRegistry &)
void initializeSIFoldOperandsLegacyPass(PassRegistry &)
char & SILoadStoreOptimizerLegacyID
void initializeAMDGPUGlobalISelDivergenceLoweringPass(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 Pass * createLICMPass()
Definition LICM.cpp:386
char & SIFormMemoryClausesID
void initializeSILoadStoreOptimizerLegacyPass(PassRegistry &)
void initializeAMDGPULowerModuleLDSLegacyPass(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()
void initializeAMDGPURegBankCombinerPass(PassRegistry &)
ThinOrFullLTOPhase
This enumerates the LLVM full LTO or ThinLTO optimization phases.
Definition Pass.h:77
@ FullLTOPostLink
Full LTO postlink (backend compile) phase.
Definition Pass.h:87
char & AMDGPUUnifyDivergentExitNodesID
void initializeAMDGPUPrepareAGPRAllocLegacyPass(PassRegistry &)
FunctionPass * createAMDGPUAtomicOptimizerPass(ScanOptions ScanStrategy)
FunctionPass * createAMDGPUPreloadKernArgPrologLegacyPass()
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 &)
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 &)
char & SILateBranchLoweringPassID
FunctionToLoopPassAdaptor createFunctionToLoopPassAdaptor(LoopPassT &&Pass, bool UseMemorySSA=false)
A function to deduce a loop pass type and wrap it in the templated adaptor.
std::function< Expected< std::unique_ptr< MCStreamer > >(TargetMachine &)> CreateMCStreamer
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:275
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()
void initializeR600MachineCFGStructurizerPass(PassRegistry &)
CodeGenFileType
These enums are meant to be passed into addPassesToEmitFile to indicate what type of file to emit,...
Definition CodeGen.h:111
char & GCNDPPCombineLegacyID
PassManager< Module > ModulePassManager
Convenience typedef for a pass manager over modules.
LLVM_ABI std::unique_ptr< ScheduleDAGMutation > createStoreClusterDAGMutation(const TargetInstrInfo *TII, const TargetRegisterInfo *TRI, bool ReorderWhileClustering=false)
If ReorderWhileClustering is set to true, no attempt will be made to reduce reordering due to store c...
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 &)
void initializeAMDGPUPostLegalizerCombinerPass(PassRegistry &)
void initializeAMDGPUExportKernelRuntimeHandlesLegacyPass(PassRegistry &)
CodeGenOptLevel
Code generation optimization level.
Definition CodeGen.h:82
void initializeSIInsertWaitcntsLegacyPass(PassRegistry &)
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)
void initializeAMDGPUPreLegalizerCombinerPass(PassRegistry &)
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 &)
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.
char & SILowerControlFlowLegacyID
ModulePass * createR600OpenCLImageTypeLoweringPass()
FunctionPass * createAMDGPUCodeGenPreparePass()
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 &)
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()
Create a legacy GVN pass.
Definition GVN.cpp:3411
void initializeAMDGPURewriteAGPRCopyMFMALegacyPass(PassRegistry &)
void initializeSIPostRABundlerLegacyPass(PassRegistry &)
FunctionPass * createAMDGPURegBankSelectPass()
FunctionPass * createAMDGPURegBankLegalizePass()
LLVM_ABI char & MachineCSELegacyID
MachineCSE - This pass performs global CSE on machine instructions.
char & SIWholeQuadModeID
LLVM_ABI std::unique_ptr< ScheduleDAGMutation > createLoadClusterDAGMutation(const TargetInstrInfo *TII, const TargetRegisterInfo *TRI, bool ReorderWhileClustering=false)
If ReorderWhileClustering is set to true, no attempt will be made to reduce reordering due to store c...
PassManager< Function > FunctionPassManager
Convenience typedef for a pass manager over functions.
LLVM_ABI char & LiveVariablesID
LiveVariables pass - This pass computes the set of blocks in which each variable is life and sets mac...
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 * createAMDGPUPostLegalizeCombiner(bool IsOptNone)
void initializeAMDGPULowerKernelAttributesPass(PassRegistry &)
char & SIInsertHardClausesID
char & SIFixSGPRCopiesLegacyID
void initializeGCNDPPCombineLegacyPass(PassRegistry &)
char & GCNCreateVOPDID
char & SIPeepholeSDWALegacyID
LLVM_ABI char & VirtRegRewriterID
VirtRegRewriter pass.
char & SIFixVGPRCopiesID
char & SIFoldOperandsLegacyID
void initializeGCNNSAReassignLegacyPass(PassRegistry &)
LLVM_ABI FunctionPass * createLowerSwitchPass()
void initializeAMDGPUPreloadKernArgPrologLegacyPass(PassRegistry &)
LLVM_ABI FunctionPass * createVirtRegRewriter(bool ClearVirtRegs=true)
void initializeR600VectorRegMergerPass(PassRegistry &)
char & AMDGPURewriteAGPRCopyMFMALegacyID
ModulePass * createAMDGPULowerExecSyncLegacyPass()
char & AMDGPULowerVGPREncodingLegacyID
FunctionPass * createAMDGPUGlobalISelDivergenceLoweringPass()
FunctionPass * createSIMemoryLegalizerPass()
void initializeAMDGPULateCodeGenPrepareLegacyPass(PassRegistry &)
void initializeSIOptimizeVGPRLiveRangeLegacyPass(PassRegistry &)
void initializeSIPeepholeSDWALegacyPass(PassRegistry &)
void initializeAMDGPURegBankLegalizePass(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 * createAMDGPUPreLegalizeCombiner(bool IsOptNone)
void initializeAMDGPURegBankSelectPass(PassRegistry &)
FunctionPass * createAMDGPULateCodeGenPrepareLegacyPass()
LLVM_ABI FunctionPass * createAtomicExpandLegacyPass()
AtomicExpandPass - At IR level this pass replace atomic instructions with __atomic_* library calls,...
MCRegisterInfo * createGCNMCRegisterInfo(AMDGPUDwarfFlavour DwarfFlavour)
LLVM_ABI FunctionPass * createStraightLineStrengthReducePass()
BumpPtrAllocatorImpl<> BumpPtrAllocator
The standard BumpPtrAllocator which just uses the default template parameters.
Definition Allocator.h:383
FunctionPass * createAMDGPUImageIntrinsicOptimizerPass(const TargetMachine *)
void initializeAMDGPUUnifyDivergentExitNodesPass(PassRegistry &)
void initializeAMDGPULowerBufferFatPointersPass(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
bool parseNamedRegisterReference(PerFunctionMIParsingState &PFS, Register &Reg, StringRef Src, SMDiagnostic &Error)
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.
void initializeSIPreEmitPeepholeLegacyPass(PassRegistry &)
AnalysisManager< Module > ModuleAnalysisManager
Convenience typedef for the Module analysis manager.
Definition MIRParser.h:39
char & AMDGPUPerfHintAnalysisLegacyID
LLVM_ABI ImmutablePass * createExternalAAWrapperPass(std::function< void(Pass &, Function &, AAResults &)> Callback)
A wrapper pass around a callback which can be used to populate the AAResults in the AAResultsWrapperP...
char & GCNPreRALongBranchRegID
LLVM_ABI CGPassBuilderOption getCGPassBuilderOption()
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)
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:177
DenseMap< Register, VRegInfo * > VRegInfos
Definition MIParser.h:176
RegisterTargetMachine - Helper template for registering a target machine implementation,...
A utility pass template to force an analysis result to be available.
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.