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,
199 const MachineRegisterInfo &MRI,
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,
206 const MachineRegisterInfo &MRI,
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,
213 const MachineRegisterInfo &MRI,
214 const Register Reg) {
215 const SIMachineFunctionInfo *MFI =
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.registerPipelineParsingCallback(
927 [this](StringRef Name, CGSCCPassManager &PM,
929 if (Name == "amdgpu-attributor-cgscc" && getTargetTriple().isAMDGCN()) {
931 *static_cast<GCNTargetMachine *>(this)));
932 return true;
933 }
934 return false;
935 });
936
937 PB.registerScalarOptimizerLateEPCallback(
938 [](FunctionPassManager &FPM, OptimizationLevel Level) {
939 if (Level == OptimizationLevel::O0)
940 return;
941
943 });
944
945 PB.registerVectorizerEndEPCallback(
946 [](FunctionPassManager &FPM, OptimizationLevel Level) {
947 if (Level == OptimizationLevel::O0)
948 return;
949
951 });
952
953 PB.registerPipelineEarlySimplificationEPCallback(
954 [this](ModulePassManager &PM, OptimizationLevel Level,
956 if (!isLTOPreLink(Phase) && getTargetTriple().isAMDGCN()) {
957 // When we are not using -fgpu-rdc, we can run accelerator code
958 // selection relatively early, but still after linking to prevent
959 // eager removal of potentially reachable symbols.
960 if (EnableHipStdPar) {
963 }
964
966 }
967
968 if (Level == OptimizationLevel::O0)
969 return;
970
971 // We don't want to run internalization at per-module stage.
975 }
976
979 });
980
981 PB.registerPeepholeEPCallback(
982 [](FunctionPassManager &FPM, OptimizationLevel Level) {
983 if (Level == OptimizationLevel::O0)
984 return;
985
989
992 });
993
994 PB.registerCGSCCOptimizerLateEPCallback(
995 [this](CGSCCPassManager &PM, OptimizationLevel Level) {
996 if (Level == OptimizationLevel::O0)
997 return;
998
1000
1001 // Add promote kernel arguments pass to the opt pipeline right before
1002 // infer address spaces which is needed to do actual address space
1003 // rewriting.
1004 if (Level.getSpeedupLevel() > OptimizationLevel::O1.getSpeedupLevel() &&
1007
1008 // Add infer address spaces pass to the opt pipeline after inlining
1009 // but before SROA to increase SROA opportunities.
1011
1012 // This should run after inlining to have any chance of doing
1013 // anything, and before other cleanup optimizations.
1015
1016 if (Level != OptimizationLevel::O0) {
1017 // Promote alloca to vector before SROA and loop unroll. If we
1018 // manage to eliminate allocas before unroll we may choose to unroll
1019 // less.
1021 }
1022
1023 PM.addPass(createCGSCCToFunctionPassAdaptor(std::move(FPM)));
1024 });
1025
1026 // FIXME: Why is AMDGPUAttributor not in CGSCC?
1027 PB.registerOptimizerLastEPCallback([this](ModulePassManager &MPM,
1028 OptimizationLevel Level,
1030 if (Level != OptimizationLevel::O0) {
1031 if (!isLTOPreLink(Phase)) {
1032 if (EnableAMDGPUAttributor && getTargetTriple().isAMDGCN()) {
1034 MPM.addPass(AMDGPUAttributorPass(*this, Opts, Phase));
1035 }
1036 }
1037 }
1038 });
1039
1040 PB.registerFullLinkTimeOptimizationLastEPCallback(
1041 [this](ModulePassManager &PM, OptimizationLevel Level) {
1042 // When we are using -fgpu-rdc, we can only run accelerator code
1043 // selection after linking to prevent, otherwise we end up removing
1044 // potentially reachable symbols that were exported as external in other
1045 // modules.
1046 if (EnableHipStdPar) {
1049 }
1050 // We want to support the -lto-partitions=N option as "best effort".
1051 // For that, we need to lower LDS earlier in the pipeline before the
1052 // module is partitioned for codegen.
1055 if (EnableSwLowerLDS)
1056 PM.addPass(AMDGPUSwLowerLDSPass(*this));
1059 if (Level != OptimizationLevel::O0) {
1060 // We only want to run this with O2 or higher since inliner and SROA
1061 // don't run in O1.
1062 if (Level != OptimizationLevel::O1) {
1063 PM.addPass(
1065 }
1066 // Do we really need internalization in LTO?
1067 if (InternalizeSymbols) {
1069 PM.addPass(GlobalDCEPass());
1070 }
1071 if (EnableAMDGPUAttributor && getTargetTriple().isAMDGCN()) {
1074 Opt.IsClosedWorld = true;
1077 }
1078 }
1079 if (!NoKernelInfoEndLTO) {
1081 FPM.addPass(KernelInfoPrinter(this));
1082 PM.addPass(createModuleToFunctionPassAdaptor(std::move(FPM)));
1083 }
1084 });
1085
1086 PB.registerRegClassFilterParsingCallback(
1087 [](StringRef FilterName) -> RegAllocFilterFunc {
1088 if (FilterName == "sgpr")
1089 return onlyAllocateSGPRs;
1090 if (FilterName == "vgpr")
1091 return onlyAllocateVGPRs;
1092 if (FilterName == "wwm")
1093 return onlyAllocateWWMRegs;
1094 return nullptr;
1095 });
1096}
1097
1099 unsigned DestAS) const {
1100 return AMDGPU::isFlatGlobalAddrSpace(SrcAS) &&
1102}
1103
1105 if (auto *Arg = dyn_cast<Argument>(V);
1106 Arg &&
1107 AMDGPU::isModuleEntryFunctionCC(Arg->getParent()->getCallingConv()) &&
1108 !Arg->hasByRefAttr())
1110
1111 const auto *LD = dyn_cast<LoadInst>(V);
1112 if (!LD) // TODO: Handle invariant load like constant.
1114
1115 // It must be a generic pointer loaded.
1116 assert(V->getType()->getPointerAddressSpace() == AMDGPUAS::FLAT_ADDRESS);
1117
1118 const auto *Ptr = LD->getPointerOperand();
1119 if (Ptr->getType()->getPointerAddressSpace() != AMDGPUAS::CONSTANT_ADDRESS)
1121 // For a generic pointer loaded from the constant memory, it could be assumed
1122 // as a global pointer since the constant memory is only populated on the
1123 // host side. As implied by the offload programming model, only global
1124 // pointers could be referenced on the host side.
1126}
1127
1128std::pair<const Value *, unsigned>
1130 if (auto *II = dyn_cast<IntrinsicInst>(V)) {
1131 switch (II->getIntrinsicID()) {
1132 case Intrinsic::amdgcn_is_shared:
1133 return std::pair(II->getArgOperand(0), AMDGPUAS::LOCAL_ADDRESS);
1134 case Intrinsic::amdgcn_is_private:
1135 return std::pair(II->getArgOperand(0), AMDGPUAS::PRIVATE_ADDRESS);
1136 default:
1137 break;
1138 }
1139 return std::pair(nullptr, -1);
1140 }
1141 // Check the global pointer predication based on
1142 // (!is_share(p) && !is_private(p)). Note that logic 'and' is commutative and
1143 // the order of 'is_shared' and 'is_private' is not significant.
1144 Value *Ptr;
1145 if (match(
1146 const_cast<Value *>(V),
1149 m_Deferred(Ptr))))))
1150 return std::pair(Ptr, AMDGPUAS::GLOBAL_ADDRESS);
1151
1152 return std::pair(nullptr, -1);
1153}
1154
1155unsigned
1170
1172 Module &M, unsigned NumParts,
1173 function_ref<void(std::unique_ptr<Module> MPart)> ModuleCallback) {
1174 // FIXME(?): Would be better to use an already existing Analysis/PassManager,
1175 // but all current users of this API don't have one ready and would need to
1176 // create one anyway. Let's hide the boilerplate for now to keep it simple.
1177
1182
1183 PassBuilder PB(this);
1184 PB.registerModuleAnalyses(MAM);
1185 PB.registerFunctionAnalyses(FAM);
1186 PB.crossRegisterProxies(LAM, FAM, CGAM, MAM);
1187
1189 MPM.addPass(AMDGPUSplitModulePass(NumParts, ModuleCallback));
1190 MPM.run(M, MAM);
1191 return true;
1192}
1193
1194//===----------------------------------------------------------------------===//
1195// GCN Target Machine (SI+)
1196//===----------------------------------------------------------------------===//
1197
1199 StringRef CPU, StringRef FS,
1200 const TargetOptions &Options,
1201 std::optional<Reloc::Model> RM,
1202 std::optional<CodeModel::Model> CM,
1203 CodeGenOptLevel OL, bool JIT)
1204 : AMDGPUTargetMachine(T, TT, CPU, FS, Options, RM, CM, OL) {}
1205
1206const TargetSubtargetInfo *
1208 StringRef GPU = getGPUName(F);
1210
1211 SmallString<128> SubtargetKey(GPU);
1212 SubtargetKey.append(FS);
1213
1214 auto &I = SubtargetMap[SubtargetKey];
1215 if (!I) {
1216 // This needs to be done before we create a new subtarget since any
1217 // creation will depend on the TM and the code generation flags on the
1218 // function that reside in TargetOptions.
1220 I = std::make_unique<GCNSubtarget>(TargetTriple, GPU, FS, *this);
1221 }
1222
1223 I->setScalarizeGlobalBehavior(ScalarizeGlobal);
1224
1225 return I.get();
1226}
1227
1230 return TargetTransformInfo(std::make_unique<GCNTTIImpl>(this, F));
1231}
1232
1235 CodeGenFileType FileType, const CGPassBuilderOption &Opts, MCContext &Ctx,
1237 AMDGPUCodeGenPassBuilder CGPB(*this, Opts, PIC);
1238 return CGPB.buildPipeline(MPM, Out, DwoOut, FileType, Ctx);
1239}
1240
1243 const GCNSubtarget &ST = C->MF->getSubtarget<GCNSubtarget>();
1244 if (ST.enableSIScheduler())
1246
1247 Attribute SchedStrategyAttr =
1248 C->MF->getFunction().getFnAttribute("amdgpu-sched-strategy");
1249 StringRef SchedStrategy = SchedStrategyAttr.isValid()
1250 ? SchedStrategyAttr.getValueAsString()
1252
1253 if (SchedStrategy == "max-ilp")
1255
1256 if (SchedStrategy == "max-memory-clause")
1258
1259 if (SchedStrategy == "iterative-ilp")
1261
1262 if (SchedStrategy == "iterative-minreg")
1263 return createMinRegScheduler(C);
1264
1265 if (SchedStrategy == "iterative-maxocc")
1267
1269}
1270
1273 ScheduleDAGMI *DAG =
1274 new GCNPostScheduleDAGMILive(C, std::make_unique<PostGenericScheduler>(C),
1275 /*RemoveKillFlags=*/true);
1276 const GCNSubtarget &ST = C->MF->getSubtarget<GCNSubtarget>();
1278 if (ST.shouldClusterStores())
1281 if ((EnableVOPD.getNumOccurrences() ||
1283 EnableVOPD)
1288 return DAG;
1289}
1290//===----------------------------------------------------------------------===//
1291// AMDGPU Legacy Pass Setup
1292//===----------------------------------------------------------------------===//
1293
1294std::unique_ptr<CSEConfigBase> llvm::AMDGPUPassConfig::getCSEConfig() const {
1295 return getStandardCSEConfigForOpt(TM->getOptLevel());
1296}
1297
1298namespace {
1299
1300class GCNPassConfig final : public AMDGPUPassConfig {
1301public:
1302 GCNPassConfig(TargetMachine &TM, PassManagerBase &PM)
1303 : AMDGPUPassConfig(TM, PM) {
1304 substitutePass(&PostRASchedulerID, &PostMachineSchedulerID);
1305 }
1306
1307 GCNTargetMachine &getGCNTargetMachine() const {
1308 return getTM<GCNTargetMachine>();
1309 }
1310
1311 bool addPreISel() override;
1312 void addMachineSSAOptimization() override;
1313 bool addILPOpts() override;
1314 bool addInstSelector() override;
1315 bool addIRTranslator() override;
1316 void addPreLegalizeMachineIR() override;
1317 bool addLegalizeMachineIR() override;
1318 void addPreRegBankSelect() override;
1319 bool addRegBankSelect() override;
1320 void addPreGlobalInstructionSelect() override;
1321 bool addGlobalInstructionSelect() override;
1322 void addPreRegAlloc() override;
1323 void addFastRegAlloc() override;
1324 void addOptimizedRegAlloc() override;
1325
1326 FunctionPass *createSGPRAllocPass(bool Optimized);
1327 FunctionPass *createVGPRAllocPass(bool Optimized);
1328 FunctionPass *createWWMRegAllocPass(bool Optimized);
1329 FunctionPass *createRegAllocPass(bool Optimized) override;
1330
1331 bool addRegAssignAndRewriteFast() override;
1332 bool addRegAssignAndRewriteOptimized() override;
1333
1334 bool addPreRewrite() override;
1335 void addPostRegAlloc() override;
1336 void addPreSched2() override;
1337 void addPreEmitPass() override;
1338 void addPostBBSections() override;
1339};
1340
1341} // end anonymous namespace
1342
1344 : TargetPassConfig(TM, PM) {
1345 // Exceptions and StackMaps are not supported, so these passes will never do
1346 // anything.
1349 // Garbage collection is not supported.
1352}
1353
1360
1365 // ReassociateGEPs exposes more opportunities for SLSR. See
1366 // the example in reassociate-geps-and-slsr.ll.
1368 // SeparateConstOffsetFromGEP and SLSR creates common expressions which GVN or
1369 // EarlyCSE can reuse.
1371 // Run NaryReassociate after EarlyCSE/GVN to be more effective.
1373 // NaryReassociate on GEPs creates redundant common expressions, so run
1374 // EarlyCSE after it.
1376}
1377
1380
1381 if (RemoveIncompatibleFunctions && TM.getTargetTriple().isAMDGCN())
1383
1384 // There is no reason to run these.
1388
1389 if (TM.getTargetTriple().isAMDGCN())
1391
1392 if (LowerCtorDtor)
1394
1395 if (TM.getTargetTriple().isAMDGCN() &&
1398
1401
1402 // This can be disabled by passing ::Disable here or on the command line
1403 // with --expand-variadics-override=disable.
1405
1406 // Function calls are not supported, so make sure we inline everything.
1409
1410 // Handle uses of OpenCL image2d_t, image3d_t and sampler_t arguments.
1411 if (TM.getTargetTriple().getArch() == Triple::r600)
1413
1414 // Make enqueued block runtime handles externally visible.
1416
1417 // Lower special LDS accesses.
1420
1421 // Lower LDS accesses to global memory pass if address sanitizer is enabled.
1422 if (EnableSwLowerLDS)
1424
1425 // Runs before PromoteAlloca so the latter can account for function uses
1428 }
1429
1430 // Run atomic optimizer before Atomic Expand
1431 if ((TM.getTargetTriple().isAMDGCN()) &&
1432 (TM.getOptLevel() >= CodeGenOptLevel::Less) &&
1435 }
1436
1438
1439 if (TM.getOptLevel() > CodeGenOptLevel::None) {
1441
1444
1448 AAResults &AAR) {
1449 if (auto *WrapperPass = P.getAnalysisIfAvailable<AMDGPUAAWrapperPass>())
1450 AAR.addAAResult(WrapperPass->getResult());
1451 }));
1452 }
1453
1454 if (TM.getTargetTriple().isAMDGCN()) {
1455 // TODO: May want to move later or split into an early and late one.
1457 }
1458
1459 // Try to hoist loop invariant parts of divisions AMDGPUCodeGenPrepare may
1460 // have expanded.
1461 if (TM.getOptLevel() > CodeGenOptLevel::Less)
1463 }
1464
1466
1467 // EarlyCSE is not always strong enough to clean up what LSR produces. For
1468 // example, GVN can combine
1469 //
1470 // %0 = add %a, %b
1471 // %1 = add %b, %a
1472 //
1473 // and
1474 //
1475 // %0 = shl nsw %a, 2
1476 // %1 = shl %a, 2
1477 //
1478 // but EarlyCSE can do neither of them.
1481}
1482
1484 if (TM->getTargetTriple().isAMDGCN() &&
1485 TM->getOptLevel() > CodeGenOptLevel::None)
1487
1488 if (TM->getTargetTriple().isAMDGCN() && EnableLowerKernelArguments)
1490
1492
1495
1496 if (TM->getTargetTriple().isAMDGCN()) {
1497 // This lowering has been placed after codegenprepare to take advantage of
1498 // address mode matching (which is why it isn't put with the LDS lowerings).
1499 // It could be placed anywhere before uniformity annotations (an analysis
1500 // that it changes by splitting up fat pointers into their components)
1501 // but has been put before switch lowering and CFG flattening so that those
1502 // passes can run on the more optimized control flow this pass creates in
1503 // many cases.
1506 }
1507
1508 // LowerSwitch pass may introduce unreachable blocks that can
1509 // cause unexpected behavior for subsequent passes. Placing it
1510 // here seems better that these blocks would get cleaned up by
1511 // UnreachableBlockElim inserted next in the pass flow.
1513}
1514
1516 if (TM->getOptLevel() > CodeGenOptLevel::None)
1518 return false;
1519}
1520
1525
1527 // Do nothing. GC is not supported.
1528 return false;
1529}
1530
1531//===----------------------------------------------------------------------===//
1532// GCN Legacy Pass Setup
1533//===----------------------------------------------------------------------===//
1534
1535bool GCNPassConfig::addPreISel() {
1537
1538 if (TM->getOptLevel() > CodeGenOptLevel::None)
1539 addPass(createSinkingPass());
1540
1541 if (TM->getOptLevel() > CodeGenOptLevel::None)
1543
1544 // Merge divergent exit nodes. StructurizeCFG won't recognize the multi-exit
1545 // regions formed by them.
1547 addPass(createFixIrreduciblePass());
1548 addPass(createUnifyLoopExitsPass());
1549 addPass(createStructurizeCFGPass(false)); // true -> SkipUniformRegions
1550
1553 // TODO: Move this right after structurizeCFG to avoid extra divergence
1554 // analysis. This depends on stopping SIAnnotateControlFlow from making
1555 // control flow modifications.
1557
1558 // SDAG requires LCSSA, GlobalISel does not. Disable LCSSA for -global-isel
1559 // with -new-reg-bank-select and without any of the fallback options.
1561 !isGlobalISelAbortEnabled() || !NewRegBankSelect)
1562 addPass(createLCSSAPass());
1563
1564 if (TM->getOptLevel() > CodeGenOptLevel::Less)
1566
1567 return false;
1568}
1569
1570void GCNPassConfig::addMachineSSAOptimization() {
1572
1573 // We want to fold operands after PeepholeOptimizer has run (or as part of
1574 // it), because it will eliminate extra copies making it easier to fold the
1575 // real source operand. We want to eliminate dead instructions after, so that
1576 // we see fewer uses of the copies. We then need to clean up the dead
1577 // instructions leftover after the operands are folded as well.
1578 //
1579 // XXX - Can we get away without running DeadMachineInstructionElim again?
1580 addPass(&SIFoldOperandsLegacyID);
1581 if (EnableDPPCombine)
1582 addPass(&GCNDPPCombineLegacyID);
1584 if (isPassEnabled(EnableSDWAPeephole)) {
1585 addPass(&SIPeepholeSDWALegacyID);
1586 addPass(&EarlyMachineLICMID);
1587 addPass(&MachineCSELegacyID);
1588 addPass(&SIFoldOperandsLegacyID);
1589 }
1592}
1593
1594bool GCNPassConfig::addILPOpts() {
1596 addPass(&EarlyIfConverterLegacyID);
1597
1599 return false;
1600}
1601
1602bool GCNPassConfig::addInstSelector() {
1604 addPass(&SIFixSGPRCopiesLegacyID);
1606 return false;
1607}
1608
1609bool GCNPassConfig::addIRTranslator() {
1610 addPass(new IRTranslator(getOptLevel()));
1611 return false;
1612}
1613
1614void GCNPassConfig::addPreLegalizeMachineIR() {
1615 bool IsOptNone = getOptLevel() == CodeGenOptLevel::None;
1616 addPass(createAMDGPUPreLegalizeCombiner(IsOptNone));
1617 addPass(new Localizer());
1618}
1619
1620bool GCNPassConfig::addLegalizeMachineIR() {
1621 addPass(new Legalizer());
1622 return false;
1623}
1624
1625void GCNPassConfig::addPreRegBankSelect() {
1626 bool IsOptNone = getOptLevel() == CodeGenOptLevel::None;
1627 addPass(createAMDGPUPostLegalizeCombiner(IsOptNone));
1629}
1630
1631bool GCNPassConfig::addRegBankSelect() {
1632 if (NewRegBankSelect) {
1635 } else {
1636 addPass(new RegBankSelect());
1637 }
1638 return false;
1639}
1640
1641void GCNPassConfig::addPreGlobalInstructionSelect() {
1642 bool IsOptNone = getOptLevel() == CodeGenOptLevel::None;
1643 addPass(createAMDGPURegBankCombiner(IsOptNone));
1644}
1645
1646bool GCNPassConfig::addGlobalInstructionSelect() {
1647 addPass(new InstructionSelect(getOptLevel()));
1648 return false;
1649}
1650
1651void GCNPassConfig::addFastRegAlloc() {
1652 // FIXME: We have to disable the verifier here because of PHIElimination +
1653 // TwoAddressInstructions disabling it.
1654
1655 // This must be run immediately after phi elimination and before
1656 // TwoAddressInstructions, otherwise the processing of the tied operand of
1657 // SI_ELSE will introduce a copy of the tied operand source after the else.
1659
1661
1663}
1664
1665void GCNPassConfig::addPreRegAlloc() {
1666 if (getOptLevel() != CodeGenOptLevel::None)
1668}
1669
1670void GCNPassConfig::addOptimizedRegAlloc() {
1671 if (EnableDCEInRA)
1673
1674 // FIXME: when an instruction has a Killed operand, and the instruction is
1675 // inside a bundle, seems only the BUNDLE instruction appears as the Kills of
1676 // the register in LiveVariables, this would trigger a failure in verifier,
1677 // we should fix it and enable the verifier.
1678 if (OptVGPRLiveRange)
1680
1681 // This must be run immediately after phi elimination and before
1682 // TwoAddressInstructions, otherwise the processing of the tied operand of
1683 // SI_ELSE will introduce a copy of the tied operand source after the else.
1685
1688
1689 if (isPassEnabled(EnablePreRAOptimizations))
1691
1692 // Allow the scheduler to run before SIWholeQuadMode inserts exec manipulation
1693 // instructions that cause scheduling barriers.
1695
1696 if (OptExecMaskPreRA)
1698
1699 // This is not an essential optimization and it has a noticeable impact on
1700 // compilation time, so we only enable it from O2.
1701 if (TM->getOptLevel() > CodeGenOptLevel::Less)
1703
1705}
1706
1707bool GCNPassConfig::addPreRewrite() {
1709 addPass(&GCNNSAReassignID);
1710
1712 return true;
1713}
1714
1715FunctionPass *GCNPassConfig::createSGPRAllocPass(bool Optimized) {
1716 // Initialize the global default.
1717 llvm::call_once(InitializeDefaultSGPRRegisterAllocatorFlag,
1718 initializeDefaultSGPRRegisterAllocatorOnce);
1719
1720 RegisterRegAlloc::FunctionPassCtor Ctor = SGPRRegisterRegAlloc::getDefault();
1721 if (Ctor != useDefaultRegisterAllocator)
1722 return Ctor();
1723
1724 if (Optimized)
1725 return createGreedyRegisterAllocator(onlyAllocateSGPRs);
1726
1727 return createFastRegisterAllocator(onlyAllocateSGPRs, false);
1728}
1729
1730FunctionPass *GCNPassConfig::createVGPRAllocPass(bool Optimized) {
1731 // Initialize the global default.
1732 llvm::call_once(InitializeDefaultVGPRRegisterAllocatorFlag,
1733 initializeDefaultVGPRRegisterAllocatorOnce);
1734
1735 RegisterRegAlloc::FunctionPassCtor Ctor = VGPRRegisterRegAlloc::getDefault();
1736 if (Ctor != useDefaultRegisterAllocator)
1737 return Ctor();
1738
1739 if (Optimized)
1740 return createGreedyVGPRRegisterAllocator();
1741
1742 return createFastVGPRRegisterAllocator();
1743}
1744
1745FunctionPass *GCNPassConfig::createWWMRegAllocPass(bool Optimized) {
1746 // Initialize the global default.
1747 llvm::call_once(InitializeDefaultWWMRegisterAllocatorFlag,
1748 initializeDefaultWWMRegisterAllocatorOnce);
1749
1750 RegisterRegAlloc::FunctionPassCtor Ctor = WWMRegisterRegAlloc::getDefault();
1751 if (Ctor != useDefaultRegisterAllocator)
1752 return Ctor();
1753
1754 if (Optimized)
1755 return createGreedyWWMRegisterAllocator();
1756
1757 return createFastWWMRegisterAllocator();
1758}
1759
1760FunctionPass *GCNPassConfig::createRegAllocPass(bool Optimized) {
1761 llvm_unreachable("should not be used");
1762}
1763
1765 "-regalloc not supported with amdgcn. Use -sgpr-regalloc, -wwm-regalloc, "
1766 "and -vgpr-regalloc";
1767
1768bool GCNPassConfig::addRegAssignAndRewriteFast() {
1769 if (!usingDefaultRegAlloc())
1771
1772 addPass(&GCNPreRALongBranchRegID);
1773
1774 addPass(createSGPRAllocPass(false));
1775
1776 // Equivalent of PEI for SGPRs.
1777 addPass(&SILowerSGPRSpillsLegacyID);
1778
1779 // To Allocate wwm registers used in whole quad mode operations (for shaders).
1781
1782 // For allocating other wwm register operands.
1783 addPass(createWWMRegAllocPass(false));
1784
1785 addPass(&SILowerWWMCopiesLegacyID);
1787
1788 // For allocating per-thread VGPRs.
1789 addPass(createVGPRAllocPass(false));
1790
1791 return true;
1792}
1793
1794bool GCNPassConfig::addRegAssignAndRewriteOptimized() {
1795 if (!usingDefaultRegAlloc())
1797
1798 addPass(&GCNPreRALongBranchRegID);
1799
1800 addPass(createSGPRAllocPass(true));
1801
1802 // Commit allocated register changes. This is mostly necessary because too
1803 // many things rely on the use lists of the physical registers, such as the
1804 // verifier. This is only necessary with allocators which use LiveIntervals,
1805 // since FastRegAlloc does the replacements itself.
1806 addPass(createVirtRegRewriter(false));
1807
1808 // At this point, the sgpr-regalloc has been done and it is good to have the
1809 // stack slot coloring to try to optimize the SGPR spill stack indices before
1810 // attempting the custom SGPR spill lowering.
1811 addPass(&StackSlotColoringID);
1812
1813 // Equivalent of PEI for SGPRs.
1814 addPass(&SILowerSGPRSpillsLegacyID);
1815
1816 // To Allocate wwm registers used in whole quad mode operations (for shaders).
1818
1819 // For allocating other whole wave mode registers.
1820 addPass(createWWMRegAllocPass(true));
1821 addPass(&SILowerWWMCopiesLegacyID);
1822 addPass(createVirtRegRewriter(false));
1824
1825 // For allocating per-thread VGPRs.
1826 addPass(createVGPRAllocPass(true));
1827
1828 addPreRewrite();
1829 addPass(&VirtRegRewriterID);
1830
1832
1833 return true;
1834}
1835
1836void GCNPassConfig::addPostRegAlloc() {
1837 addPass(&SIFixVGPRCopiesID);
1838 if (getOptLevel() > CodeGenOptLevel::None)
1841}
1842
1843void GCNPassConfig::addPreSched2() {
1844 if (TM->getOptLevel() > CodeGenOptLevel::None)
1846 addPass(&SIPostRABundlerLegacyID);
1847}
1848
1849void GCNPassConfig::addPreEmitPass() {
1850 if (isPassEnabled(EnableVOPD, CodeGenOptLevel::Less))
1851 addPass(&GCNCreateVOPDID);
1852 addPass(createSIMemoryLegalizerPass());
1853 addPass(createSIInsertWaitcntsPass());
1854
1855 addPass(createSIModeRegisterPass());
1856
1857 if (getOptLevel() > CodeGenOptLevel::None)
1858 addPass(&SIInsertHardClausesID);
1859
1861 if (isPassEnabled(EnableSetWavePriority, CodeGenOptLevel::Less))
1863 if (getOptLevel() > CodeGenOptLevel::None)
1864 addPass(&SIPreEmitPeepholeID);
1865 // The hazard recognizer that runs as part of the post-ra scheduler does not
1866 // guarantee to be able handle all hazards correctly. This is because if there
1867 // are multiple scheduling regions in a basic block, the regions are scheduled
1868 // bottom up, so when we begin to schedule a region we don't know what
1869 // instructions were emitted directly before it.
1870 //
1871 // Here we add a stand-alone hazard recognizer pass which can handle all
1872 // cases.
1873 addPass(&PostRAHazardRecognizerID);
1874
1876
1878
1879 if (isPassEnabled(EnableInsertDelayAlu, CodeGenOptLevel::Less))
1880 addPass(&AMDGPUInsertDelayAluID);
1881
1882 addPass(&BranchRelaxationPassID);
1883}
1884
1885void GCNPassConfig::addPostBBSections() {
1886 // We run this later to avoid passes like livedebugvalues and BBSections
1887 // having to deal with the apparent multi-entry functions we may generate.
1889}
1890
1892 return new GCNPassConfig(*this, PM);
1893}
1894
1900
1907
1911
1918
1921 SMDiagnostic &Error, SMRange &SourceRange) const {
1922 const yaml::SIMachineFunctionInfo &YamlMFI =
1923 static_cast<const yaml::SIMachineFunctionInfo &>(MFI_);
1924 MachineFunction &MF = PFS.MF;
1926 const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>();
1927
1928 if (MFI->initializeBaseYamlFields(YamlMFI, MF, PFS, Error, SourceRange))
1929 return true;
1930
1931 if (MFI->Occupancy == 0) {
1932 // Fixup the subtarget dependent default value.
1933 MFI->Occupancy = ST.getOccupancyWithWorkGroupSizes(MF).second;
1934 }
1935
1936 auto parseRegister = [&](const yaml::StringValue &RegName, Register &RegVal) {
1937 Register TempReg;
1938 if (parseNamedRegisterReference(PFS, TempReg, RegName.Value, Error)) {
1939 SourceRange = RegName.SourceRange;
1940 return true;
1941 }
1942 RegVal = TempReg;
1943
1944 return false;
1945 };
1946
1947 auto parseOptionalRegister = [&](const yaml::StringValue &RegName,
1948 Register &RegVal) {
1949 return !RegName.Value.empty() && parseRegister(RegName, RegVal);
1950 };
1951
1952 if (parseOptionalRegister(YamlMFI.VGPRForAGPRCopy, MFI->VGPRForAGPRCopy))
1953 return true;
1954
1955 if (parseOptionalRegister(YamlMFI.SGPRForEXECCopy, MFI->SGPRForEXECCopy))
1956 return true;
1957
1958 if (parseOptionalRegister(YamlMFI.LongBranchReservedReg,
1959 MFI->LongBranchReservedReg))
1960 return true;
1961
1962 auto diagnoseRegisterClass = [&](const yaml::StringValue &RegName) {
1963 // Create a diagnostic for a the register string literal.
1964 const MemoryBuffer &Buffer =
1965 *PFS.SM->getMemoryBuffer(PFS.SM->getMainFileID());
1966 Error = SMDiagnostic(*PFS.SM, SMLoc(), Buffer.getBufferIdentifier(), 1,
1967 RegName.Value.size(), SourceMgr::DK_Error,
1968 "incorrect register class for field", RegName.Value,
1969 {}, {});
1970 SourceRange = RegName.SourceRange;
1971 return true;
1972 };
1973
1974 if (parseRegister(YamlMFI.ScratchRSrcReg, MFI->ScratchRSrcReg) ||
1975 parseRegister(YamlMFI.FrameOffsetReg, MFI->FrameOffsetReg) ||
1976 parseRegister(YamlMFI.StackPtrOffsetReg, MFI->StackPtrOffsetReg))
1977 return true;
1978
1979 if (MFI->ScratchRSrcReg != AMDGPU::PRIVATE_RSRC_REG &&
1980 !AMDGPU::SGPR_128RegClass.contains(MFI->ScratchRSrcReg)) {
1981 return diagnoseRegisterClass(YamlMFI.ScratchRSrcReg);
1982 }
1983
1984 if (MFI->FrameOffsetReg != AMDGPU::FP_REG &&
1985 !AMDGPU::SGPR_32RegClass.contains(MFI->FrameOffsetReg)) {
1986 return diagnoseRegisterClass(YamlMFI.FrameOffsetReg);
1987 }
1988
1989 if (MFI->StackPtrOffsetReg != AMDGPU::SP_REG &&
1990 !AMDGPU::SGPR_32RegClass.contains(MFI->StackPtrOffsetReg)) {
1991 return diagnoseRegisterClass(YamlMFI.StackPtrOffsetReg);
1992 }
1993
1994 for (const auto &YamlReg : YamlMFI.WWMReservedRegs) {
1995 Register ParsedReg;
1996 if (parseRegister(YamlReg, ParsedReg))
1997 return true;
1998
1999 MFI->reserveWWMRegister(ParsedReg);
2000 }
2001
2002 for (const auto &[_, Info] : PFS.VRegInfosNamed) {
2003 MFI->setFlag(Info->VReg, Info->Flags);
2004 }
2005 for (const auto &[_, Info] : PFS.VRegInfos) {
2006 MFI->setFlag(Info->VReg, Info->Flags);
2007 }
2008
2009 for (const auto &YamlRegStr : YamlMFI.SpillPhysVGPRS) {
2010 Register ParsedReg;
2011 if (parseRegister(YamlRegStr, ParsedReg))
2012 return true;
2013 MFI->SpillPhysVGPRs.push_back(ParsedReg);
2014 }
2015
2016 auto parseAndCheckArgument = [&](const std::optional<yaml::SIArgument> &A,
2017 const TargetRegisterClass &RC,
2018 ArgDescriptor &Arg, unsigned UserSGPRs,
2019 unsigned SystemSGPRs) {
2020 // Skip parsing if it's not present.
2021 if (!A)
2022 return false;
2023
2024 if (A->IsRegister) {
2025 Register Reg;
2026 if (parseNamedRegisterReference(PFS, Reg, A->RegisterName.Value, Error)) {
2027 SourceRange = A->RegisterName.SourceRange;
2028 return true;
2029 }
2030 if (!RC.contains(Reg))
2031 return diagnoseRegisterClass(A->RegisterName);
2033 } else
2034 Arg = ArgDescriptor::createStack(A->StackOffset);
2035 // Check and apply the optional mask.
2036 if (A->Mask)
2037 Arg = ArgDescriptor::createArg(Arg, *A->Mask);
2038
2039 MFI->NumUserSGPRs += UserSGPRs;
2040 MFI->NumSystemSGPRs += SystemSGPRs;
2041 return false;
2042 };
2043
2044 if (YamlMFI.ArgInfo &&
2045 (parseAndCheckArgument(YamlMFI.ArgInfo->PrivateSegmentBuffer,
2046 AMDGPU::SGPR_128RegClass,
2047 MFI->ArgInfo.PrivateSegmentBuffer, 4, 0) ||
2048 parseAndCheckArgument(YamlMFI.ArgInfo->DispatchPtr,
2049 AMDGPU::SReg_64RegClass, MFI->ArgInfo.DispatchPtr,
2050 2, 0) ||
2051 parseAndCheckArgument(YamlMFI.ArgInfo->QueuePtr, AMDGPU::SReg_64RegClass,
2052 MFI->ArgInfo.QueuePtr, 2, 0) ||
2053 parseAndCheckArgument(YamlMFI.ArgInfo->KernargSegmentPtr,
2054 AMDGPU::SReg_64RegClass,
2055 MFI->ArgInfo.KernargSegmentPtr, 2, 0) ||
2056 parseAndCheckArgument(YamlMFI.ArgInfo->DispatchID,
2057 AMDGPU::SReg_64RegClass, MFI->ArgInfo.DispatchID,
2058 2, 0) ||
2059 parseAndCheckArgument(YamlMFI.ArgInfo->FlatScratchInit,
2060 AMDGPU::SReg_64RegClass,
2061 MFI->ArgInfo.FlatScratchInit, 2, 0) ||
2062 parseAndCheckArgument(YamlMFI.ArgInfo->PrivateSegmentSize,
2063 AMDGPU::SGPR_32RegClass,
2064 MFI->ArgInfo.PrivateSegmentSize, 0, 0) ||
2065 parseAndCheckArgument(YamlMFI.ArgInfo->LDSKernelId,
2066 AMDGPU::SGPR_32RegClass,
2067 MFI->ArgInfo.LDSKernelId, 0, 1) ||
2068 parseAndCheckArgument(YamlMFI.ArgInfo->WorkGroupIDX,
2069 AMDGPU::SGPR_32RegClass, MFI->ArgInfo.WorkGroupIDX,
2070 0, 1) ||
2071 parseAndCheckArgument(YamlMFI.ArgInfo->WorkGroupIDY,
2072 AMDGPU::SGPR_32RegClass, MFI->ArgInfo.WorkGroupIDY,
2073 0, 1) ||
2074 parseAndCheckArgument(YamlMFI.ArgInfo->WorkGroupIDZ,
2075 AMDGPU::SGPR_32RegClass, MFI->ArgInfo.WorkGroupIDZ,
2076 0, 1) ||
2077 parseAndCheckArgument(YamlMFI.ArgInfo->WorkGroupInfo,
2078 AMDGPU::SGPR_32RegClass,
2079 MFI->ArgInfo.WorkGroupInfo, 0, 1) ||
2080 parseAndCheckArgument(YamlMFI.ArgInfo->PrivateSegmentWaveByteOffset,
2081 AMDGPU::SGPR_32RegClass,
2082 MFI->ArgInfo.PrivateSegmentWaveByteOffset, 0, 1) ||
2083 parseAndCheckArgument(YamlMFI.ArgInfo->ImplicitArgPtr,
2084 AMDGPU::SReg_64RegClass,
2085 MFI->ArgInfo.ImplicitArgPtr, 0, 0) ||
2086 parseAndCheckArgument(YamlMFI.ArgInfo->ImplicitBufferPtr,
2087 AMDGPU::SReg_64RegClass,
2088 MFI->ArgInfo.ImplicitBufferPtr, 2, 0) ||
2089 parseAndCheckArgument(YamlMFI.ArgInfo->WorkItemIDX,
2090 AMDGPU::VGPR_32RegClass,
2091 MFI->ArgInfo.WorkItemIDX, 0, 0) ||
2092 parseAndCheckArgument(YamlMFI.ArgInfo->WorkItemIDY,
2093 AMDGPU::VGPR_32RegClass,
2094 MFI->ArgInfo.WorkItemIDY, 0, 0) ||
2095 parseAndCheckArgument(YamlMFI.ArgInfo->WorkItemIDZ,
2096 AMDGPU::VGPR_32RegClass,
2097 MFI->ArgInfo.WorkItemIDZ, 0, 0)))
2098 return true;
2099
2100 // Parse FirstKernArgPreloadReg separately, since it's a Register,
2101 // not ArgDescriptor.
2102 if (YamlMFI.ArgInfo && YamlMFI.ArgInfo->FirstKernArgPreloadReg) {
2103 const yaml::SIArgument &A = *YamlMFI.ArgInfo->FirstKernArgPreloadReg;
2104
2105 if (!A.IsRegister) {
2106 // For stack arguments, we don't have RegisterName.SourceRange,
2107 // but we should have some location info from the YAML parser
2108 const MemoryBuffer &Buffer =
2109 *PFS.SM->getMemoryBuffer(PFS.SM->getMainFileID());
2110 // Create a minimal valid source range
2112 SMRange Range(Loc, Loc);
2113
2115 *PFS.SM, Loc, Buffer.getBufferIdentifier(), 1, 0, SourceMgr::DK_Error,
2116 "firstKernArgPreloadReg must be a register, not a stack location", "",
2117 {}, {});
2118
2119 SourceRange = Range;
2120 return true;
2121 }
2122
2123 Register Reg;
2124 if (parseNamedRegisterReference(PFS, Reg, A.RegisterName.Value, Error)) {
2125 SourceRange = A.RegisterName.SourceRange;
2126 return true;
2127 }
2128
2129 if (!AMDGPU::SGPR_32RegClass.contains(Reg))
2130 return diagnoseRegisterClass(A.RegisterName);
2131
2132 MFI->ArgInfo.FirstKernArgPreloadReg = Reg;
2133 MFI->NumUserSGPRs += YamlMFI.NumKernargPreloadSGPRs;
2134 }
2135
2136 if (ST.hasFeature(AMDGPU::FeatureDX10ClampAndIEEEMode)) {
2137 MFI->Mode.IEEE = YamlMFI.Mode.IEEE;
2138 MFI->Mode.DX10Clamp = YamlMFI.Mode.DX10Clamp;
2139 }
2140
2141 // FIXME: Move proper support for denormal-fp-math into base MachineFunction
2142 MFI->Mode.FP32Denormals.Input = YamlMFI.Mode.FP32InputDenormals
2145 MFI->Mode.FP32Denormals.Output = YamlMFI.Mode.FP32OutputDenormals
2148
2155
2156 if (YamlMFI.HasInitWholeWave)
2157 MFI->setInitWholeWave();
2158
2159 return false;
2160}
2161
2162//===----------------------------------------------------------------------===//
2163// AMDGPU CodeGen Pass Builder interface.
2164//===----------------------------------------------------------------------===//
2165
2166AMDGPUCodeGenPassBuilder::AMDGPUCodeGenPassBuilder(
2167 GCNTargetMachine &TM, const CGPassBuilderOption &Opts,
2169 : CodeGenPassBuilder(TM, Opts, PIC) {
2170 Opt.MISchedPostRA = true;
2171 Opt.RequiresCodeGenSCCOrder = true;
2172 // Exceptions and StackMaps are not supported, so these passes will never do
2173 // anything.
2174 // Garbage collection is not supported.
2175 disablePass<StackMapLivenessPass, FuncletLayoutPass, PatchableFunctionPass,
2177}
2178
2179void AMDGPUCodeGenPassBuilder::addIRPasses(PassManagerWrapper &PMW) const {
2180 if (RemoveIncompatibleFunctions && TM.getTargetTriple().isAMDGCN()) {
2181 flushFPMsToMPM(PMW);
2182 addModulePass(AMDGPURemoveIncompatibleFunctionsPass(TM), PMW);
2183 }
2184
2185 flushFPMsToMPM(PMW);
2186
2187 if (TM.getTargetTriple().isAMDGCN())
2188 addModulePass(AMDGPUPrintfRuntimeBindingPass(), PMW);
2189
2190 if (LowerCtorDtor)
2191 addModulePass(AMDGPUCtorDtorLoweringPass(), PMW);
2192
2193 if (isPassEnabled(EnableImageIntrinsicOptimizer))
2194 addFunctionPass(AMDGPUImageIntrinsicOptimizerPass(TM), PMW);
2195
2197 addFunctionPass(AMDGPUUniformIntrinsicCombinePass(), PMW);
2198 // This can be disabled by passing ::Disable here or on the command line
2199 // with --expand-variadics-override=disable.
2200 flushFPMsToMPM(PMW);
2202
2203 addModulePass(AMDGPUAlwaysInlinePass(), PMW);
2204 addModulePass(AlwaysInlinerPass(), PMW);
2205
2206 addModulePass(AMDGPUExportKernelRuntimeHandlesPass(), PMW);
2207
2209 addModulePass(AMDGPULowerExecSyncPass(), PMW);
2210
2211 if (EnableSwLowerLDS)
2212 addModulePass(AMDGPUSwLowerLDSPass(TM), PMW);
2213
2214 // Runs before PromoteAlloca so the latter can account for function uses
2216 addModulePass(AMDGPULowerModuleLDSPass(TM), PMW);
2217
2218 // Run atomic optimizer before Atomic Expand
2219 if (TM.getOptLevel() >= CodeGenOptLevel::Less &&
2221 addFunctionPass(
2223
2224 addFunctionPass(AtomicExpandPass(TM), PMW);
2225
2226 if (TM.getOptLevel() > CodeGenOptLevel::None) {
2227 addFunctionPass(AMDGPUPromoteAllocaPass(TM), PMW);
2228 if (isPassEnabled(EnableScalarIRPasses))
2229 addStraightLineScalarOptimizationPasses(PMW);
2230
2231 // TODO: Handle EnableAMDGPUAliasAnalysis
2232
2233 // TODO: May want to move later or split into an early and late one.
2234 addFunctionPass(AMDGPUCodeGenPreparePass(TM), PMW);
2235
2236 // Try to hoist loop invariant parts of divisions AMDGPUCodeGenPrepare may
2237 // have expanded.
2238 if (TM.getOptLevel() > CodeGenOptLevel::Less) {
2240 /*UseMemorySSA=*/true),
2241 PMW);
2242 }
2243 }
2244
2245 Base::addIRPasses(PMW);
2246
2247 // EarlyCSE is not always strong enough to clean up what LSR produces. For
2248 // example, GVN can combine
2249 //
2250 // %0 = add %a, %b
2251 // %1 = add %b, %a
2252 //
2253 // and
2254 //
2255 // %0 = shl nsw %a, 2
2256 // %1 = shl %a, 2
2257 //
2258 // but EarlyCSE can do neither of them.
2259 if (isPassEnabled(EnableScalarIRPasses))
2260 addEarlyCSEOrGVNPass(PMW);
2261}
2262
2263void AMDGPUCodeGenPassBuilder::addCodeGenPrepare(
2264 PassManagerWrapper &PMW) const {
2265 if (TM.getOptLevel() > CodeGenOptLevel::None) {
2266 flushFPMsToMPM(PMW);
2267 addModulePass(AMDGPUPreloadKernelArgumentsPass(TM), PMW);
2268 }
2269
2271 addFunctionPass(AMDGPULowerKernelArgumentsPass(TM), PMW);
2272
2273 Base::addCodeGenPrepare(PMW);
2274
2275 if (isPassEnabled(EnableLoadStoreVectorizer))
2276 addFunctionPass(LoadStoreVectorizerPass(), PMW);
2277
2278 // This lowering has been placed after codegenprepare to take advantage of
2279 // address mode matching (which is why it isn't put with the LDS lowerings).
2280 // It could be placed anywhere before uniformity annotations (an analysis
2281 // that it changes by splitting up fat pointers into their components)
2282 // but has been put before switch lowering and CFG flattening so that those
2283 // passes can run on the more optimized control flow this pass creates in
2284 // many cases.
2285 flushFPMsToMPM(PMW);
2286 addModulePass(AMDGPULowerBufferFatPointersPass(TM), PMW);
2287 flushFPMsToMPM(PMW);
2288 requireCGSCCOrder(PMW);
2289
2290 addModulePass(AMDGPULowerIntrinsicsPass(TM), PMW);
2291
2292 // LowerSwitch pass may introduce unreachable blocks that can cause unexpected
2293 // behavior for subsequent passes. Placing it here seems better that these
2294 // blocks would get cleaned up by UnreachableBlockElim inserted next in the
2295 // pass flow.
2296 addFunctionPass(LowerSwitchPass(), PMW);
2297}
2298
2299void AMDGPUCodeGenPassBuilder::addPreISel(PassManagerWrapper &PMW) const {
2300
2301 if (TM.getOptLevel() > CodeGenOptLevel::None) {
2302 addFunctionPass(FlattenCFGPass(), PMW);
2303 addFunctionPass(SinkingPass(), PMW);
2304 addFunctionPass(AMDGPULateCodeGenPreparePass(TM), PMW);
2305 }
2306
2307 // Merge divergent exit nodes. StructurizeCFG won't recognize the multi-exit
2308 // regions formed by them.
2309
2310 addFunctionPass(AMDGPUUnifyDivergentExitNodesPass(), PMW);
2311 addFunctionPass(FixIrreduciblePass(), PMW);
2312 addFunctionPass(UnifyLoopExitsPass(), PMW);
2313 addFunctionPass(StructurizeCFGPass(/*SkipUniformRegions=*/false), PMW);
2314
2315 addFunctionPass(AMDGPUAnnotateUniformValuesPass(), PMW);
2316
2317 addFunctionPass(SIAnnotateControlFlowPass(TM), PMW);
2318
2319 // TODO: Move this right after structurizeCFG to avoid extra divergence
2320 // analysis. This depends on stopping SIAnnotateControlFlow from making
2321 // control flow modifications.
2322 addFunctionPass(AMDGPURewriteUndefForPHIPass(), PMW);
2323
2325 !isGlobalISelAbortEnabled() || !NewRegBankSelect)
2326 addFunctionPass(LCSSAPass(), PMW);
2327
2328 if (TM.getOptLevel() > CodeGenOptLevel::Less) {
2329 flushFPMsToMPM(PMW);
2330 addModulePass(AMDGPUPerfHintAnalysisPass(TM), PMW);
2331 }
2332
2333 // FIXME: Why isn't this queried as required from AMDGPUISelDAGToDAG, and why
2334 // isn't this in addInstSelector?
2336 /*Force=*/true);
2337}
2338
2339void AMDGPUCodeGenPassBuilder::addILPOpts(PassManagerWrapper &PMW) const {
2341 addMachineFunctionPass(EarlyIfConverterPass(), PMW);
2342
2343 Base::addILPOpts(PMW);
2344}
2345
2346void AMDGPUCodeGenPassBuilder::addAsmPrinterBegin(
2347 PassManagerWrapper &PMW, CreateMCStreamer CreateStreamer) const {
2348 // TODO: Add AsmPrinterBegin
2349}
2350
2351void AMDGPUCodeGenPassBuilder::addAsmPrinter(
2352 PassManagerWrapper &PMW, CreateMCStreamer CreateStreamer) const {
2353 // TODO: Add AsmPrinter.
2354}
2355
2356void AMDGPUCodeGenPassBuilder::addAsmPrinterEnd(
2357 PassManagerWrapper &PMW, CreateMCStreamer CreateStreamer) const {
2358 // TODO: Add AsmPrinterEnd
2359}
2360
2361Error AMDGPUCodeGenPassBuilder::addInstSelector(PassManagerWrapper &PMW) const {
2362 addMachineFunctionPass(AMDGPUISelDAGToDAGPass(TM), PMW);
2363 addMachineFunctionPass(SIFixSGPRCopiesPass(), PMW);
2364 addMachineFunctionPass(SILowerI1CopiesPass(), PMW);
2365 return Error::success();
2366}
2367
2368void AMDGPUCodeGenPassBuilder::addPreRewrite(PassManagerWrapper &PMW) const {
2369 if (EnableRegReassign) {
2370 addMachineFunctionPass(GCNNSAReassignPass(), PMW);
2371 }
2372
2373 addMachineFunctionPass(AMDGPURewriteAGPRCopyMFMAPass(), PMW);
2374}
2375
2376void AMDGPUCodeGenPassBuilder::addMachineSSAOptimization(
2377 PassManagerWrapper &PMW) const {
2378 Base::addMachineSSAOptimization(PMW);
2379
2380 addMachineFunctionPass(SIFoldOperandsPass(), PMW);
2381 if (EnableDPPCombine) {
2382 addMachineFunctionPass(GCNDPPCombinePass(), PMW);
2383 }
2384 addMachineFunctionPass(SILoadStoreOptimizerPass(), PMW);
2385 if (isPassEnabled(EnableSDWAPeephole)) {
2386 addMachineFunctionPass(SIPeepholeSDWAPass(), PMW);
2387 addMachineFunctionPass(EarlyMachineLICMPass(), PMW);
2388 addMachineFunctionPass(MachineCSEPass(), PMW);
2389 addMachineFunctionPass(SIFoldOperandsPass(), PMW);
2390 }
2391 addMachineFunctionPass(DeadMachineInstructionElimPass(), PMW);
2392 addMachineFunctionPass(SIShrinkInstructionsPass(), PMW);
2393}
2394
2395Error AMDGPUCodeGenPassBuilder::addFastRegAlloc(PassManagerWrapper &PMW) const {
2396 insertPass<PHIEliminationPass>(SILowerControlFlowPass());
2397
2398 insertPass<TwoAddressInstructionPass>(SIWholeQuadModePass());
2399
2400 return Base::addFastRegAlloc(PMW);
2401}
2402
2403Error AMDGPUCodeGenPassBuilder::addRegAssignmentFast(
2404 PassManagerWrapper &PMW) const {
2405 if (auto Err = validateRegAllocOptions())
2406 return Err;
2407
2408 addMachineFunctionPass(GCNPreRALongBranchRegPass(), PMW);
2409
2410 // SGPR allocation - default to fast at -O0.
2411 if (SGPRRegAllocNPM == RegAllocType::Greedy)
2412 addMachineFunctionPass(RAGreedyPass({onlyAllocateSGPRs, "sgpr"}), PMW);
2413 else
2414 addMachineFunctionPass(RegAllocFastPass({onlyAllocateSGPRs, "sgpr", false}),
2415 PMW);
2416
2417 // Equivalent of PEI for SGPRs.
2418 addMachineFunctionPass(SILowerSGPRSpillsPass(), PMW);
2419
2420 // To Allocate wwm registers used in whole quad mode operations (for shaders).
2421 addMachineFunctionPass(SIPreAllocateWWMRegsPass(), PMW);
2422
2423 // WWM allocation - default to fast at -O0.
2424 if (WWMRegAllocNPM == RegAllocType::Greedy)
2425 addMachineFunctionPass(RAGreedyPass({onlyAllocateWWMRegs, "wwm"}), PMW);
2426 else
2427 addMachineFunctionPass(
2428 RegAllocFastPass({onlyAllocateWWMRegs, "wwm", false}), PMW);
2429
2430 addMachineFunctionPass(SILowerWWMCopiesPass(), PMW);
2431 addMachineFunctionPass(AMDGPUReserveWWMRegsPass(), PMW);
2432
2433 // VGPR allocation - default to fast at -O0.
2434 if (VGPRRegAllocNPM == RegAllocType::Greedy)
2435 addMachineFunctionPass(RAGreedyPass({onlyAllocateVGPRs, "vgpr"}), PMW);
2436 else
2437 addMachineFunctionPass(RegAllocFastPass({onlyAllocateVGPRs, "vgpr"}), PMW);
2438
2439 return Error::success();
2440}
2441
2442Error AMDGPUCodeGenPassBuilder::addOptimizedRegAlloc(
2443 PassManagerWrapper &PMW) const {
2444 if (EnableDCEInRA)
2445 insertPass<DetectDeadLanesPass>(DeadMachineInstructionElimPass());
2446
2447 // FIXME: when an instruction has a Killed operand, and the instruction is
2448 // inside a bundle, seems only the BUNDLE instruction appears as the Kills of
2449 // the register in LiveVariables, this would trigger a failure in verifier,
2450 // we should fix it and enable the verifier.
2451 if (OptVGPRLiveRange)
2452 insertPass<RequireAnalysisPass<LiveVariablesAnalysis, MachineFunction>>(
2454
2455 // This must be run immediately after phi elimination and before
2456 // TwoAddressInstructions, otherwise the processing of the tied operand of
2457 // SI_ELSE will introduce a copy of the tied operand source after the else.
2458 insertPass<PHIEliminationPass>(SILowerControlFlowPass());
2459
2461 insertPass<RenameIndependentSubregsPass>(GCNRewritePartialRegUsesPass());
2462
2463 if (isPassEnabled(EnablePreRAOptimizations))
2464 insertPass<MachineSchedulerPass>(GCNPreRAOptimizationsPass());
2465
2466 // Allow the scheduler to run before SIWholeQuadMode inserts exec manipulation
2467 // instructions that cause scheduling barriers.
2468 insertPass<MachineSchedulerPass>(SIWholeQuadModePass());
2469
2470 if (OptExecMaskPreRA)
2471 insertPass<MachineSchedulerPass>(SIOptimizeExecMaskingPreRAPass());
2472
2473 // This is not an essential optimization and it has a noticeable impact on
2474 // compilation time, so we only enable it from O2.
2475 if (TM.getOptLevel() > CodeGenOptLevel::Less)
2476 insertPass<MachineSchedulerPass>(SIFormMemoryClausesPass());
2477
2478 return Base::addOptimizedRegAlloc(PMW);
2479}
2480
2481void AMDGPUCodeGenPassBuilder::addPreRegAlloc(PassManagerWrapper &PMW) const {
2482 if (getOptLevel() != CodeGenOptLevel::None)
2483 addMachineFunctionPass(AMDGPUPrepareAGPRAllocPass(), PMW);
2484}
2485
2486Error AMDGPUCodeGenPassBuilder::addRegAssignmentOptimized(
2487 PassManagerWrapper &PMW) const {
2488 if (auto Err = validateRegAllocOptions())
2489 return Err;
2490
2491 addMachineFunctionPass(GCNPreRALongBranchRegPass(), PMW);
2492
2493 // SGPR allocation - default to greedy at -O1 and above.
2494 if (SGPRRegAllocNPM == RegAllocType::Fast)
2495 addMachineFunctionPass(RegAllocFastPass({onlyAllocateSGPRs, "sgpr", false}),
2496 PMW);
2497 else
2498 addMachineFunctionPass(RAGreedyPass({onlyAllocateSGPRs, "sgpr"}), PMW);
2499
2500 // Commit allocated register changes. This is mostly necessary because too
2501 // many things rely on the use lists of the physical registers, such as the
2502 // verifier. This is only necessary with allocators which use LiveIntervals,
2503 // since FastRegAlloc does the replacements itself.
2504 addMachineFunctionPass(VirtRegRewriterPass(false), PMW);
2505
2506 // At this point, the sgpr-regalloc has been done and it is good to have the
2507 // stack slot coloring to try to optimize the SGPR spill stack indices before
2508 // attempting the custom SGPR spill lowering.
2509 addMachineFunctionPass(StackSlotColoringPass(), PMW);
2510
2511 // Equivalent of PEI for SGPRs.
2512 addMachineFunctionPass(SILowerSGPRSpillsPass(), PMW);
2513
2514 // To Allocate wwm registers used in whole quad mode operations (for shaders).
2515 addMachineFunctionPass(SIPreAllocateWWMRegsPass(), PMW);
2516
2517 // WWM allocation - default to greedy at -O1 and above.
2518 if (WWMRegAllocNPM == RegAllocType::Fast)
2519 addMachineFunctionPass(
2520 RegAllocFastPass({onlyAllocateWWMRegs, "wwm", false}), PMW);
2521 else
2522 addMachineFunctionPass(RAGreedyPass({onlyAllocateWWMRegs, "wwm"}), PMW);
2523 addMachineFunctionPass(SILowerWWMCopiesPass(), PMW);
2524 addMachineFunctionPass(VirtRegRewriterPass(false), PMW);
2525 addMachineFunctionPass(AMDGPUReserveWWMRegsPass(), PMW);
2526
2527 // VGPR allocation - default to greedy at -O1 and above.
2528 if (VGPRRegAllocNPM == RegAllocType::Fast)
2529 addMachineFunctionPass(RegAllocFastPass({onlyAllocateVGPRs, "vgpr"}), PMW);
2530 else
2531 addMachineFunctionPass(RAGreedyPass({onlyAllocateVGPRs, "vgpr"}), PMW);
2532
2533 addPreRewrite(PMW);
2534 addMachineFunctionPass(VirtRegRewriterPass(true), PMW);
2535
2536 addMachineFunctionPass(AMDGPUMarkLastScratchLoadPass(), PMW);
2537 return Error::success();
2538}
2539
2540void AMDGPUCodeGenPassBuilder::addPostRegAlloc(PassManagerWrapper &PMW) const {
2541 addMachineFunctionPass(SIFixVGPRCopiesPass(), PMW);
2542 if (TM.getOptLevel() > CodeGenOptLevel::None)
2543 addMachineFunctionPass(SIOptimizeExecMaskingPass(), PMW);
2544 Base::addPostRegAlloc(PMW);
2545}
2546
2547void AMDGPUCodeGenPassBuilder::addPreSched2(PassManagerWrapper &PMW) const {
2548 if (TM.getOptLevel() > CodeGenOptLevel::None)
2549 addMachineFunctionPass(SIShrinkInstructionsPass(), PMW);
2550 addMachineFunctionPass(SIPostRABundlerPass(), PMW);
2551}
2552
2553void AMDGPUCodeGenPassBuilder::addPostBBSections(
2554 PassManagerWrapper &PMW) const {
2555 // We run this later to avoid passes like livedebugvalues and BBSections
2556 // having to deal with the apparent multi-entry functions we may generate.
2557 addMachineFunctionPass(AMDGPUPreloadKernArgPrologPass(), PMW);
2558}
2559
2560void AMDGPUCodeGenPassBuilder::addPreEmitPass(PassManagerWrapper &PMW) const {
2561 if (isPassEnabled(EnableVOPD, CodeGenOptLevel::Less)) {
2562 addMachineFunctionPass(GCNCreateVOPDPass(), PMW);
2563 }
2564
2565 addMachineFunctionPass(SIMemoryLegalizerPass(), PMW);
2566 addMachineFunctionPass(SIInsertWaitcntsPass(), PMW);
2567
2568 addMachineFunctionPass(SIModeRegisterPass(), PMW);
2569
2570 if (TM.getOptLevel() > CodeGenOptLevel::None)
2571 addMachineFunctionPass(SIInsertHardClausesPass(), PMW);
2572
2573 addMachineFunctionPass(SILateBranchLoweringPass(), PMW);
2574
2575 if (isPassEnabled(EnableSetWavePriority, CodeGenOptLevel::Less))
2576 addMachineFunctionPass(AMDGPUSetWavePriorityPass(), PMW);
2577
2578 if (TM.getOptLevel() > CodeGenOptLevel::None)
2579 addMachineFunctionPass(SIPreEmitPeepholePass(), PMW);
2580
2581 // The hazard recognizer that runs as part of the post-ra scheduler does not
2582 // guarantee to be able handle all hazards correctly. This is because if there
2583 // are multiple scheduling regions in a basic block, the regions are scheduled
2584 // bottom up, so when we begin to schedule a region we don't know what
2585 // instructions were emitted directly before it.
2586 //
2587 // Here we add a stand-alone hazard recognizer pass which can handle all
2588 // cases.
2589 addMachineFunctionPass(PostRAHazardRecognizerPass(), PMW);
2590 addMachineFunctionPass(AMDGPUWaitSGPRHazardsPass(), PMW);
2591 addMachineFunctionPass(AMDGPULowerVGPREncodingPass(), PMW);
2592
2593 if (isPassEnabled(EnableInsertDelayAlu, CodeGenOptLevel::Less)) {
2594 addMachineFunctionPass(AMDGPUInsertDelayAluPass(), PMW);
2595 }
2596
2597 addMachineFunctionPass(BranchRelaxationPass(), PMW);
2598}
2599
2600bool AMDGPUCodeGenPassBuilder::isPassEnabled(const cl::opt<bool> &Opt,
2601 CodeGenOptLevel Level) const {
2602 if (Opt.getNumOccurrences())
2603 return Opt;
2604 if (TM.getOptLevel() < Level)
2605 return false;
2606 return Opt;
2607}
2608
2609void AMDGPUCodeGenPassBuilder::addEarlyCSEOrGVNPass(
2610 PassManagerWrapper &PMW) const {
2611 if (TM.getOptLevel() == CodeGenOptLevel::Aggressive)
2612 addFunctionPass(GVNPass(), PMW);
2613 else
2614 addFunctionPass(EarlyCSEPass(), PMW);
2615}
2616
2617void AMDGPUCodeGenPassBuilder::addStraightLineScalarOptimizationPasses(
2618 PassManagerWrapper &PMW) const {
2620 addFunctionPass(LoopDataPrefetchPass(), PMW);
2621
2622 addFunctionPass(SeparateConstOffsetFromGEPPass(), PMW);
2623
2624 // ReassociateGEPs exposes more opportunities for SLSR. See
2625 // the example in reassociate-geps-and-slsr.ll.
2626 addFunctionPass(StraightLineStrengthReducePass(), PMW);
2627
2628 // SeparateConstOffsetFromGEP and SLSR creates common expressions which GVN or
2629 // EarlyCSE can reuse.
2630 addEarlyCSEOrGVNPass(PMW);
2631
2632 // Run NaryReassociate after EarlyCSE/GVN to be more effective.
2633 addFunctionPass(NaryReassociatePass(), PMW);
2634
2635 // NaryReassociate on GEPs creates redundant common expressions, so run
2636 // EarlyCSE after it.
2637 addFunctionPass(EarlyCSEPass(), PMW);
2638}
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.
#define X(NUM, ENUM, NAME)
Definition ELF.h:849
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 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
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".
ArrayRef - Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition ArrayRef.h:40
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,...
const TargetRegisterClass * getRegClass(Register Reg) const
Return the register class of the specified virtual register.
void addDelegate(Delegate *delegate)
const MachineFunction & getMF() const
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:347
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.
@ 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:3412
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:178
DenseMap< Register, VRegInfo * > VRegInfos
Definition MIParser.h:177
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.