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
1098int64_t AMDGPUTargetMachine::getNullPointerValue(unsigned AddrSpace) {
1099 return (AddrSpace == AMDGPUAS::LOCAL_ADDRESS ||
1100 AddrSpace == AMDGPUAS::PRIVATE_ADDRESS ||
1101 AddrSpace == AMDGPUAS::REGION_ADDRESS)
1102 ? -1
1103 : 0;
1104}
1105
1107 unsigned DestAS) const {
1108 return AMDGPU::isFlatGlobalAddrSpace(SrcAS) &&
1110}
1111
1113 if (auto *Arg = dyn_cast<Argument>(V);
1114 Arg &&
1115 AMDGPU::isModuleEntryFunctionCC(Arg->getParent()->getCallingConv()) &&
1116 !Arg->hasByRefAttr())
1118
1119 const auto *LD = dyn_cast<LoadInst>(V);
1120 if (!LD) // TODO: Handle invariant load like constant.
1122
1123 // It must be a generic pointer loaded.
1124 assert(V->getType()->getPointerAddressSpace() == AMDGPUAS::FLAT_ADDRESS);
1125
1126 const auto *Ptr = LD->getPointerOperand();
1127 if (Ptr->getType()->getPointerAddressSpace() != AMDGPUAS::CONSTANT_ADDRESS)
1129 // For a generic pointer loaded from the constant memory, it could be assumed
1130 // as a global pointer since the constant memory is only populated on the
1131 // host side. As implied by the offload programming model, only global
1132 // pointers could be referenced on the host side.
1134}
1135
1136std::pair<const Value *, unsigned>
1138 if (auto *II = dyn_cast<IntrinsicInst>(V)) {
1139 switch (II->getIntrinsicID()) {
1140 case Intrinsic::amdgcn_is_shared:
1141 return std::pair(II->getArgOperand(0), AMDGPUAS::LOCAL_ADDRESS);
1142 case Intrinsic::amdgcn_is_private:
1143 return std::pair(II->getArgOperand(0), AMDGPUAS::PRIVATE_ADDRESS);
1144 default:
1145 break;
1146 }
1147 return std::pair(nullptr, -1);
1148 }
1149 // Check the global pointer predication based on
1150 // (!is_share(p) && !is_private(p)). Note that logic 'and' is commutative and
1151 // the order of 'is_shared' and 'is_private' is not significant.
1152 Value *Ptr;
1153 if (match(
1154 const_cast<Value *>(V),
1157 m_Deferred(Ptr))))))
1158 return std::pair(Ptr, AMDGPUAS::GLOBAL_ADDRESS);
1159
1160 return std::pair(nullptr, -1);
1161}
1162
1163unsigned
1178
1180 Module &M, unsigned NumParts,
1181 function_ref<void(std::unique_ptr<Module> MPart)> ModuleCallback) {
1182 // FIXME(?): Would be better to use an already existing Analysis/PassManager,
1183 // but all current users of this API don't have one ready and would need to
1184 // create one anyway. Let's hide the boilerplate for now to keep it simple.
1185
1190
1191 PassBuilder PB(this);
1192 PB.registerModuleAnalyses(MAM);
1193 PB.registerFunctionAnalyses(FAM);
1194 PB.crossRegisterProxies(LAM, FAM, CGAM, MAM);
1195
1197 MPM.addPass(AMDGPUSplitModulePass(NumParts, ModuleCallback));
1198 MPM.run(M, MAM);
1199 return true;
1200}
1201
1202//===----------------------------------------------------------------------===//
1203// GCN Target Machine (SI+)
1204//===----------------------------------------------------------------------===//
1205
1207 StringRef CPU, StringRef FS,
1208 const TargetOptions &Options,
1209 std::optional<Reloc::Model> RM,
1210 std::optional<CodeModel::Model> CM,
1211 CodeGenOptLevel OL, bool JIT)
1212 : AMDGPUTargetMachine(T, TT, CPU, FS, Options, RM, CM, OL) {}
1213
1214const TargetSubtargetInfo *
1216 StringRef GPU = getGPUName(F);
1218
1219 SmallString<128> SubtargetKey(GPU);
1220 SubtargetKey.append(FS);
1221
1222 auto &I = SubtargetMap[SubtargetKey];
1223 if (!I) {
1224 // This needs to be done before we create a new subtarget since any
1225 // creation will depend on the TM and the code generation flags on the
1226 // function that reside in TargetOptions.
1228 I = std::make_unique<GCNSubtarget>(TargetTriple, GPU, FS, *this);
1229 }
1230
1231 I->setScalarizeGlobalBehavior(ScalarizeGlobal);
1232
1233 return I.get();
1234}
1235
1238 return TargetTransformInfo(std::make_unique<GCNTTIImpl>(this, F));
1239}
1240
1243 CodeGenFileType FileType, const CGPassBuilderOption &Opts, MCContext &Ctx,
1245 AMDGPUCodeGenPassBuilder CGPB(*this, Opts, PIC);
1246 return CGPB.buildPipeline(MPM, Out, DwoOut, FileType, Ctx);
1247}
1248
1251 const GCNSubtarget &ST = C->MF->getSubtarget<GCNSubtarget>();
1252 if (ST.enableSIScheduler())
1254
1255 Attribute SchedStrategyAttr =
1256 C->MF->getFunction().getFnAttribute("amdgpu-sched-strategy");
1257 StringRef SchedStrategy = SchedStrategyAttr.isValid()
1258 ? SchedStrategyAttr.getValueAsString()
1260
1261 if (SchedStrategy == "max-ilp")
1263
1264 if (SchedStrategy == "max-memory-clause")
1266
1267 if (SchedStrategy == "iterative-ilp")
1269
1270 if (SchedStrategy == "iterative-minreg")
1271 return createMinRegScheduler(C);
1272
1273 if (SchedStrategy == "iterative-maxocc")
1275
1277}
1278
1281 ScheduleDAGMI *DAG =
1282 new GCNPostScheduleDAGMILive(C, std::make_unique<PostGenericScheduler>(C),
1283 /*RemoveKillFlags=*/true);
1284 const GCNSubtarget &ST = C->MF->getSubtarget<GCNSubtarget>();
1286 if (ST.shouldClusterStores())
1289 if ((EnableVOPD.getNumOccurrences() ||
1291 EnableVOPD)
1296 return DAG;
1297}
1298//===----------------------------------------------------------------------===//
1299// AMDGPU Legacy Pass Setup
1300//===----------------------------------------------------------------------===//
1301
1302std::unique_ptr<CSEConfigBase> llvm::AMDGPUPassConfig::getCSEConfig() const {
1303 return getStandardCSEConfigForOpt(TM->getOptLevel());
1304}
1305
1306namespace {
1307
1308class GCNPassConfig final : public AMDGPUPassConfig {
1309public:
1310 GCNPassConfig(TargetMachine &TM, PassManagerBase &PM)
1311 : AMDGPUPassConfig(TM, PM) {
1312 substitutePass(&PostRASchedulerID, &PostMachineSchedulerID);
1313 }
1314
1315 GCNTargetMachine &getGCNTargetMachine() const {
1316 return getTM<GCNTargetMachine>();
1317 }
1318
1319 bool addPreISel() override;
1320 void addMachineSSAOptimization() override;
1321 bool addILPOpts() override;
1322 bool addInstSelector() override;
1323 bool addIRTranslator() override;
1324 void addPreLegalizeMachineIR() override;
1325 bool addLegalizeMachineIR() override;
1326 void addPreRegBankSelect() override;
1327 bool addRegBankSelect() override;
1328 void addPreGlobalInstructionSelect() override;
1329 bool addGlobalInstructionSelect() override;
1330 void addPreRegAlloc() override;
1331 void addFastRegAlloc() override;
1332 void addOptimizedRegAlloc() override;
1333
1334 FunctionPass *createSGPRAllocPass(bool Optimized);
1335 FunctionPass *createVGPRAllocPass(bool Optimized);
1336 FunctionPass *createWWMRegAllocPass(bool Optimized);
1337 FunctionPass *createRegAllocPass(bool Optimized) override;
1338
1339 bool addRegAssignAndRewriteFast() override;
1340 bool addRegAssignAndRewriteOptimized() override;
1341
1342 bool addPreRewrite() override;
1343 void addPostRegAlloc() override;
1344 void addPreSched2() override;
1345 void addPreEmitPass() override;
1346 void addPostBBSections() override;
1347};
1348
1349} // end anonymous namespace
1350
1352 : TargetPassConfig(TM, PM) {
1353 // Exceptions and StackMaps are not supported, so these passes will never do
1354 // anything.
1357 // Garbage collection is not supported.
1360}
1361
1368
1373 // ReassociateGEPs exposes more opportunities for SLSR. See
1374 // the example in reassociate-geps-and-slsr.ll.
1376 // SeparateConstOffsetFromGEP and SLSR creates common expressions which GVN or
1377 // EarlyCSE can reuse.
1379 // Run NaryReassociate after EarlyCSE/GVN to be more effective.
1381 // NaryReassociate on GEPs creates redundant common expressions, so run
1382 // EarlyCSE after it.
1384}
1385
1388
1389 if (RemoveIncompatibleFunctions && TM.getTargetTriple().isAMDGCN())
1391
1392 // There is no reason to run these.
1396
1397 if (TM.getTargetTriple().isAMDGCN())
1399
1400 if (LowerCtorDtor)
1402
1403 if (TM.getTargetTriple().isAMDGCN() &&
1406
1409
1410 // This can be disabled by passing ::Disable here or on the command line
1411 // with --expand-variadics-override=disable.
1413
1414 // Function calls are not supported, so make sure we inline everything.
1417
1418 // Handle uses of OpenCL image2d_t, image3d_t and sampler_t arguments.
1419 if (TM.getTargetTriple().getArch() == Triple::r600)
1421
1422 // Make enqueued block runtime handles externally visible.
1424
1425 // Lower special LDS accesses.
1428
1429 // Lower LDS accesses to global memory pass if address sanitizer is enabled.
1430 if (EnableSwLowerLDS)
1432
1433 // Runs before PromoteAlloca so the latter can account for function uses
1436 }
1437
1438 // Run atomic optimizer before Atomic Expand
1439 if ((TM.getTargetTriple().isAMDGCN()) &&
1440 (TM.getOptLevel() >= CodeGenOptLevel::Less) &&
1443 }
1444
1446
1447 if (TM.getOptLevel() > CodeGenOptLevel::None) {
1449
1452
1456 AAResults &AAR) {
1457 if (auto *WrapperPass = P.getAnalysisIfAvailable<AMDGPUAAWrapperPass>())
1458 AAR.addAAResult(WrapperPass->getResult());
1459 }));
1460 }
1461
1462 if (TM.getTargetTriple().isAMDGCN()) {
1463 // TODO: May want to move later or split into an early and late one.
1465 }
1466
1467 // Try to hoist loop invariant parts of divisions AMDGPUCodeGenPrepare may
1468 // have expanded.
1469 if (TM.getOptLevel() > CodeGenOptLevel::Less)
1471 }
1472
1474
1475 // EarlyCSE is not always strong enough to clean up what LSR produces. For
1476 // example, GVN can combine
1477 //
1478 // %0 = add %a, %b
1479 // %1 = add %b, %a
1480 //
1481 // and
1482 //
1483 // %0 = shl nsw %a, 2
1484 // %1 = shl %a, 2
1485 //
1486 // but EarlyCSE can do neither of them.
1489}
1490
1492 if (TM->getTargetTriple().isAMDGCN() &&
1493 TM->getOptLevel() > CodeGenOptLevel::None)
1495
1496 if (TM->getTargetTriple().isAMDGCN() && EnableLowerKernelArguments)
1498
1500
1503
1504 if (TM->getTargetTriple().isAMDGCN()) {
1505 // This lowering has been placed after codegenprepare to take advantage of
1506 // address mode matching (which is why it isn't put with the LDS lowerings).
1507 // It could be placed anywhere before uniformity annotations (an analysis
1508 // that it changes by splitting up fat pointers into their components)
1509 // but has been put before switch lowering and CFG flattening so that those
1510 // passes can run on the more optimized control flow this pass creates in
1511 // many cases.
1514 }
1515
1516 // LowerSwitch pass may introduce unreachable blocks that can
1517 // cause unexpected behavior for subsequent passes. Placing it
1518 // here seems better that these blocks would get cleaned up by
1519 // UnreachableBlockElim inserted next in the pass flow.
1521}
1522
1524 if (TM->getOptLevel() > CodeGenOptLevel::None)
1526 return false;
1527}
1528
1533
1535 // Do nothing. GC is not supported.
1536 return false;
1537}
1538
1539//===----------------------------------------------------------------------===//
1540// GCN Legacy Pass Setup
1541//===----------------------------------------------------------------------===//
1542
1543bool GCNPassConfig::addPreISel() {
1545
1546 if (TM->getOptLevel() > CodeGenOptLevel::None)
1547 addPass(createSinkingPass());
1548
1549 if (TM->getOptLevel() > CodeGenOptLevel::None)
1551
1552 // Merge divergent exit nodes. StructurizeCFG won't recognize the multi-exit
1553 // regions formed by them.
1555 addPass(createFixIrreduciblePass());
1556 addPass(createUnifyLoopExitsPass());
1557 addPass(createStructurizeCFGPass(false)); // true -> SkipUniformRegions
1558
1561 // TODO: Move this right after structurizeCFG to avoid extra divergence
1562 // analysis. This depends on stopping SIAnnotateControlFlow from making
1563 // control flow modifications.
1565
1566 // SDAG requires LCSSA, GlobalISel does not. Disable LCSSA for -global-isel
1567 // with -new-reg-bank-select and without any of the fallback options.
1569 !isGlobalISelAbortEnabled() || !NewRegBankSelect)
1570 addPass(createLCSSAPass());
1571
1572 if (TM->getOptLevel() > CodeGenOptLevel::Less)
1574
1575 return false;
1576}
1577
1578void GCNPassConfig::addMachineSSAOptimization() {
1580
1581 // We want to fold operands after PeepholeOptimizer has run (or as part of
1582 // it), because it will eliminate extra copies making it easier to fold the
1583 // real source operand. We want to eliminate dead instructions after, so that
1584 // we see fewer uses of the copies. We then need to clean up the dead
1585 // instructions leftover after the operands are folded as well.
1586 //
1587 // XXX - Can we get away without running DeadMachineInstructionElim again?
1588 addPass(&SIFoldOperandsLegacyID);
1589 if (EnableDPPCombine)
1590 addPass(&GCNDPPCombineLegacyID);
1592 if (isPassEnabled(EnableSDWAPeephole)) {
1593 addPass(&SIPeepholeSDWALegacyID);
1594 addPass(&EarlyMachineLICMID);
1595 addPass(&MachineCSELegacyID);
1596 addPass(&SIFoldOperandsLegacyID);
1597 }
1600}
1601
1602bool GCNPassConfig::addILPOpts() {
1604 addPass(&EarlyIfConverterLegacyID);
1605
1607 return false;
1608}
1609
1610bool GCNPassConfig::addInstSelector() {
1612 addPass(&SIFixSGPRCopiesLegacyID);
1614 return false;
1615}
1616
1617bool GCNPassConfig::addIRTranslator() {
1618 addPass(new IRTranslator(getOptLevel()));
1619 return false;
1620}
1621
1622void GCNPassConfig::addPreLegalizeMachineIR() {
1623 bool IsOptNone = getOptLevel() == CodeGenOptLevel::None;
1624 addPass(createAMDGPUPreLegalizeCombiner(IsOptNone));
1625 addPass(new Localizer());
1626}
1627
1628bool GCNPassConfig::addLegalizeMachineIR() {
1629 addPass(new Legalizer());
1630 return false;
1631}
1632
1633void GCNPassConfig::addPreRegBankSelect() {
1634 bool IsOptNone = getOptLevel() == CodeGenOptLevel::None;
1635 addPass(createAMDGPUPostLegalizeCombiner(IsOptNone));
1637}
1638
1639bool GCNPassConfig::addRegBankSelect() {
1640 if (NewRegBankSelect) {
1643 } else {
1644 addPass(new RegBankSelect());
1645 }
1646 return false;
1647}
1648
1649void GCNPassConfig::addPreGlobalInstructionSelect() {
1650 bool IsOptNone = getOptLevel() == CodeGenOptLevel::None;
1651 addPass(createAMDGPURegBankCombiner(IsOptNone));
1652}
1653
1654bool GCNPassConfig::addGlobalInstructionSelect() {
1655 addPass(new InstructionSelect(getOptLevel()));
1656 return false;
1657}
1658
1659void GCNPassConfig::addFastRegAlloc() {
1660 // FIXME: We have to disable the verifier here because of PHIElimination +
1661 // TwoAddressInstructions disabling it.
1662
1663 // This must be run immediately after phi elimination and before
1664 // TwoAddressInstructions, otherwise the processing of the tied operand of
1665 // SI_ELSE will introduce a copy of the tied operand source after the else.
1667
1669
1671}
1672
1673void GCNPassConfig::addPreRegAlloc() {
1674 if (getOptLevel() != CodeGenOptLevel::None)
1676}
1677
1678void GCNPassConfig::addOptimizedRegAlloc() {
1679 if (EnableDCEInRA)
1681
1682 // FIXME: when an instruction has a Killed operand, and the instruction is
1683 // inside a bundle, seems only the BUNDLE instruction appears as the Kills of
1684 // the register in LiveVariables, this would trigger a failure in verifier,
1685 // we should fix it and enable the verifier.
1686 if (OptVGPRLiveRange)
1688
1689 // This must be run immediately after phi elimination and before
1690 // TwoAddressInstructions, otherwise the processing of the tied operand of
1691 // SI_ELSE will introduce a copy of the tied operand source after the else.
1693
1696
1697 if (isPassEnabled(EnablePreRAOptimizations))
1699
1700 // Allow the scheduler to run before SIWholeQuadMode inserts exec manipulation
1701 // instructions that cause scheduling barriers.
1703
1704 if (OptExecMaskPreRA)
1706
1707 // This is not an essential optimization and it has a noticeable impact on
1708 // compilation time, so we only enable it from O2.
1709 if (TM->getOptLevel() > CodeGenOptLevel::Less)
1711
1713}
1714
1715bool GCNPassConfig::addPreRewrite() {
1717 addPass(&GCNNSAReassignID);
1718
1720 return true;
1721}
1722
1723FunctionPass *GCNPassConfig::createSGPRAllocPass(bool Optimized) {
1724 // Initialize the global default.
1725 llvm::call_once(InitializeDefaultSGPRRegisterAllocatorFlag,
1726 initializeDefaultSGPRRegisterAllocatorOnce);
1727
1728 RegisterRegAlloc::FunctionPassCtor Ctor = SGPRRegisterRegAlloc::getDefault();
1729 if (Ctor != useDefaultRegisterAllocator)
1730 return Ctor();
1731
1732 if (Optimized)
1733 return createGreedyRegisterAllocator(onlyAllocateSGPRs);
1734
1735 return createFastRegisterAllocator(onlyAllocateSGPRs, false);
1736}
1737
1738FunctionPass *GCNPassConfig::createVGPRAllocPass(bool Optimized) {
1739 // Initialize the global default.
1740 llvm::call_once(InitializeDefaultVGPRRegisterAllocatorFlag,
1741 initializeDefaultVGPRRegisterAllocatorOnce);
1742
1743 RegisterRegAlloc::FunctionPassCtor Ctor = VGPRRegisterRegAlloc::getDefault();
1744 if (Ctor != useDefaultRegisterAllocator)
1745 return Ctor();
1746
1747 if (Optimized)
1748 return createGreedyVGPRRegisterAllocator();
1749
1750 return createFastVGPRRegisterAllocator();
1751}
1752
1753FunctionPass *GCNPassConfig::createWWMRegAllocPass(bool Optimized) {
1754 // Initialize the global default.
1755 llvm::call_once(InitializeDefaultWWMRegisterAllocatorFlag,
1756 initializeDefaultWWMRegisterAllocatorOnce);
1757
1758 RegisterRegAlloc::FunctionPassCtor Ctor = WWMRegisterRegAlloc::getDefault();
1759 if (Ctor != useDefaultRegisterAllocator)
1760 return Ctor();
1761
1762 if (Optimized)
1763 return createGreedyWWMRegisterAllocator();
1764
1765 return createFastWWMRegisterAllocator();
1766}
1767
1768FunctionPass *GCNPassConfig::createRegAllocPass(bool Optimized) {
1769 llvm_unreachable("should not be used");
1770}
1771
1773 "-regalloc not supported with amdgcn. Use -sgpr-regalloc, -wwm-regalloc, "
1774 "and -vgpr-regalloc";
1775
1776bool GCNPassConfig::addRegAssignAndRewriteFast() {
1777 if (!usingDefaultRegAlloc())
1779
1780 addPass(&GCNPreRALongBranchRegID);
1781
1782 addPass(createSGPRAllocPass(false));
1783
1784 // Equivalent of PEI for SGPRs.
1785 addPass(&SILowerSGPRSpillsLegacyID);
1786
1787 // To Allocate wwm registers used in whole quad mode operations (for shaders).
1789
1790 // For allocating other wwm register operands.
1791 addPass(createWWMRegAllocPass(false));
1792
1793 addPass(&SILowerWWMCopiesLegacyID);
1795
1796 // For allocating per-thread VGPRs.
1797 addPass(createVGPRAllocPass(false));
1798
1799 return true;
1800}
1801
1802bool GCNPassConfig::addRegAssignAndRewriteOptimized() {
1803 if (!usingDefaultRegAlloc())
1805
1806 addPass(&GCNPreRALongBranchRegID);
1807
1808 addPass(createSGPRAllocPass(true));
1809
1810 // Commit allocated register changes. This is mostly necessary because too
1811 // many things rely on the use lists of the physical registers, such as the
1812 // verifier. This is only necessary with allocators which use LiveIntervals,
1813 // since FastRegAlloc does the replacements itself.
1814 addPass(createVirtRegRewriter(false));
1815
1816 // At this point, the sgpr-regalloc has been done and it is good to have the
1817 // stack slot coloring to try to optimize the SGPR spill stack indices before
1818 // attempting the custom SGPR spill lowering.
1819 addPass(&StackSlotColoringID);
1820
1821 // Equivalent of PEI for SGPRs.
1822 addPass(&SILowerSGPRSpillsLegacyID);
1823
1824 // To Allocate wwm registers used in whole quad mode operations (for shaders).
1826
1827 // For allocating other whole wave mode registers.
1828 addPass(createWWMRegAllocPass(true));
1829 addPass(&SILowerWWMCopiesLegacyID);
1830 addPass(createVirtRegRewriter(false));
1832
1833 // For allocating per-thread VGPRs.
1834 addPass(createVGPRAllocPass(true));
1835
1836 addPreRewrite();
1837 addPass(&VirtRegRewriterID);
1838
1840
1841 return true;
1842}
1843
1844void GCNPassConfig::addPostRegAlloc() {
1845 addPass(&SIFixVGPRCopiesID);
1846 if (getOptLevel() > CodeGenOptLevel::None)
1849}
1850
1851void GCNPassConfig::addPreSched2() {
1852 if (TM->getOptLevel() > CodeGenOptLevel::None)
1854 addPass(&SIPostRABundlerLegacyID);
1855}
1856
1857void GCNPassConfig::addPreEmitPass() {
1858 if (isPassEnabled(EnableVOPD, CodeGenOptLevel::Less))
1859 addPass(&GCNCreateVOPDID);
1860 addPass(createSIMemoryLegalizerPass());
1861 addPass(createSIInsertWaitcntsPass());
1862
1863 addPass(createSIModeRegisterPass());
1864
1865 if (getOptLevel() > CodeGenOptLevel::None)
1866 addPass(&SIInsertHardClausesID);
1867
1869 if (isPassEnabled(EnableSetWavePriority, CodeGenOptLevel::Less))
1871 if (getOptLevel() > CodeGenOptLevel::None)
1872 addPass(&SIPreEmitPeepholeID);
1873 // The hazard recognizer that runs as part of the post-ra scheduler does not
1874 // guarantee to be able handle all hazards correctly. This is because if there
1875 // are multiple scheduling regions in a basic block, the regions are scheduled
1876 // bottom up, so when we begin to schedule a region we don't know what
1877 // instructions were emitted directly before it.
1878 //
1879 // Here we add a stand-alone hazard recognizer pass which can handle all
1880 // cases.
1881 addPass(&PostRAHazardRecognizerID);
1882
1884
1886
1887 if (isPassEnabled(EnableInsertDelayAlu, CodeGenOptLevel::Less))
1888 addPass(&AMDGPUInsertDelayAluID);
1889
1890 addPass(&BranchRelaxationPassID);
1891}
1892
1893void GCNPassConfig::addPostBBSections() {
1894 // We run this later to avoid passes like livedebugvalues and BBSections
1895 // having to deal with the apparent multi-entry functions we may generate.
1897}
1898
1900 return new GCNPassConfig(*this, PM);
1901}
1902
1908
1915
1919
1926
1929 SMDiagnostic &Error, SMRange &SourceRange) const {
1930 const yaml::SIMachineFunctionInfo &YamlMFI =
1931 static_cast<const yaml::SIMachineFunctionInfo &>(MFI_);
1932 MachineFunction &MF = PFS.MF;
1934 const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>();
1935
1936 if (MFI->initializeBaseYamlFields(YamlMFI, MF, PFS, Error, SourceRange))
1937 return true;
1938
1939 if (MFI->Occupancy == 0) {
1940 // Fixup the subtarget dependent default value.
1941 MFI->Occupancy = ST.getOccupancyWithWorkGroupSizes(MF).second;
1942 }
1943
1944 auto parseRegister = [&](const yaml::StringValue &RegName, Register &RegVal) {
1945 Register TempReg;
1946 if (parseNamedRegisterReference(PFS, TempReg, RegName.Value, Error)) {
1947 SourceRange = RegName.SourceRange;
1948 return true;
1949 }
1950 RegVal = TempReg;
1951
1952 return false;
1953 };
1954
1955 auto parseOptionalRegister = [&](const yaml::StringValue &RegName,
1956 Register &RegVal) {
1957 return !RegName.Value.empty() && parseRegister(RegName, RegVal);
1958 };
1959
1960 if (parseOptionalRegister(YamlMFI.VGPRForAGPRCopy, MFI->VGPRForAGPRCopy))
1961 return true;
1962
1963 if (parseOptionalRegister(YamlMFI.SGPRForEXECCopy, MFI->SGPRForEXECCopy))
1964 return true;
1965
1966 if (parseOptionalRegister(YamlMFI.LongBranchReservedReg,
1967 MFI->LongBranchReservedReg))
1968 return true;
1969
1970 auto diagnoseRegisterClass = [&](const yaml::StringValue &RegName) {
1971 // Create a diagnostic for a the register string literal.
1972 const MemoryBuffer &Buffer =
1973 *PFS.SM->getMemoryBuffer(PFS.SM->getMainFileID());
1974 Error = SMDiagnostic(*PFS.SM, SMLoc(), Buffer.getBufferIdentifier(), 1,
1975 RegName.Value.size(), SourceMgr::DK_Error,
1976 "incorrect register class for field", RegName.Value,
1977 {}, {});
1978 SourceRange = RegName.SourceRange;
1979 return true;
1980 };
1981
1982 if (parseRegister(YamlMFI.ScratchRSrcReg, MFI->ScratchRSrcReg) ||
1983 parseRegister(YamlMFI.FrameOffsetReg, MFI->FrameOffsetReg) ||
1984 parseRegister(YamlMFI.StackPtrOffsetReg, MFI->StackPtrOffsetReg))
1985 return true;
1986
1987 if (MFI->ScratchRSrcReg != AMDGPU::PRIVATE_RSRC_REG &&
1988 !AMDGPU::SGPR_128RegClass.contains(MFI->ScratchRSrcReg)) {
1989 return diagnoseRegisterClass(YamlMFI.ScratchRSrcReg);
1990 }
1991
1992 if (MFI->FrameOffsetReg != AMDGPU::FP_REG &&
1993 !AMDGPU::SGPR_32RegClass.contains(MFI->FrameOffsetReg)) {
1994 return diagnoseRegisterClass(YamlMFI.FrameOffsetReg);
1995 }
1996
1997 if (MFI->StackPtrOffsetReg != AMDGPU::SP_REG &&
1998 !AMDGPU::SGPR_32RegClass.contains(MFI->StackPtrOffsetReg)) {
1999 return diagnoseRegisterClass(YamlMFI.StackPtrOffsetReg);
2000 }
2001
2002 for (const auto &YamlReg : YamlMFI.WWMReservedRegs) {
2003 Register ParsedReg;
2004 if (parseRegister(YamlReg, ParsedReg))
2005 return true;
2006
2007 MFI->reserveWWMRegister(ParsedReg);
2008 }
2009
2010 for (const auto &[_, Info] : PFS.VRegInfosNamed) {
2011 MFI->setFlag(Info->VReg, Info->Flags);
2012 }
2013 for (const auto &[_, Info] : PFS.VRegInfos) {
2014 MFI->setFlag(Info->VReg, Info->Flags);
2015 }
2016
2017 for (const auto &YamlRegStr : YamlMFI.SpillPhysVGPRS) {
2018 Register ParsedReg;
2019 if (parseRegister(YamlRegStr, ParsedReg))
2020 return true;
2021 MFI->SpillPhysVGPRs.push_back(ParsedReg);
2022 }
2023
2024 auto parseAndCheckArgument = [&](const std::optional<yaml::SIArgument> &A,
2025 const TargetRegisterClass &RC,
2026 ArgDescriptor &Arg, unsigned UserSGPRs,
2027 unsigned SystemSGPRs) {
2028 // Skip parsing if it's not present.
2029 if (!A)
2030 return false;
2031
2032 if (A->IsRegister) {
2033 Register Reg;
2034 if (parseNamedRegisterReference(PFS, Reg, A->RegisterName.Value, Error)) {
2035 SourceRange = A->RegisterName.SourceRange;
2036 return true;
2037 }
2038 if (!RC.contains(Reg))
2039 return diagnoseRegisterClass(A->RegisterName);
2041 } else
2042 Arg = ArgDescriptor::createStack(A->StackOffset);
2043 // Check and apply the optional mask.
2044 if (A->Mask)
2045 Arg = ArgDescriptor::createArg(Arg, *A->Mask);
2046
2047 MFI->NumUserSGPRs += UserSGPRs;
2048 MFI->NumSystemSGPRs += SystemSGPRs;
2049 return false;
2050 };
2051
2052 if (YamlMFI.ArgInfo &&
2053 (parseAndCheckArgument(YamlMFI.ArgInfo->PrivateSegmentBuffer,
2054 AMDGPU::SGPR_128RegClass,
2055 MFI->ArgInfo.PrivateSegmentBuffer, 4, 0) ||
2056 parseAndCheckArgument(YamlMFI.ArgInfo->DispatchPtr,
2057 AMDGPU::SReg_64RegClass, MFI->ArgInfo.DispatchPtr,
2058 2, 0) ||
2059 parseAndCheckArgument(YamlMFI.ArgInfo->QueuePtr, AMDGPU::SReg_64RegClass,
2060 MFI->ArgInfo.QueuePtr, 2, 0) ||
2061 parseAndCheckArgument(YamlMFI.ArgInfo->KernargSegmentPtr,
2062 AMDGPU::SReg_64RegClass,
2063 MFI->ArgInfo.KernargSegmentPtr, 2, 0) ||
2064 parseAndCheckArgument(YamlMFI.ArgInfo->DispatchID,
2065 AMDGPU::SReg_64RegClass, MFI->ArgInfo.DispatchID,
2066 2, 0) ||
2067 parseAndCheckArgument(YamlMFI.ArgInfo->FlatScratchInit,
2068 AMDGPU::SReg_64RegClass,
2069 MFI->ArgInfo.FlatScratchInit, 2, 0) ||
2070 parseAndCheckArgument(YamlMFI.ArgInfo->PrivateSegmentSize,
2071 AMDGPU::SGPR_32RegClass,
2072 MFI->ArgInfo.PrivateSegmentSize, 0, 0) ||
2073 parseAndCheckArgument(YamlMFI.ArgInfo->LDSKernelId,
2074 AMDGPU::SGPR_32RegClass,
2075 MFI->ArgInfo.LDSKernelId, 0, 1) ||
2076 parseAndCheckArgument(YamlMFI.ArgInfo->WorkGroupIDX,
2077 AMDGPU::SGPR_32RegClass, MFI->ArgInfo.WorkGroupIDX,
2078 0, 1) ||
2079 parseAndCheckArgument(YamlMFI.ArgInfo->WorkGroupIDY,
2080 AMDGPU::SGPR_32RegClass, MFI->ArgInfo.WorkGroupIDY,
2081 0, 1) ||
2082 parseAndCheckArgument(YamlMFI.ArgInfo->WorkGroupIDZ,
2083 AMDGPU::SGPR_32RegClass, MFI->ArgInfo.WorkGroupIDZ,
2084 0, 1) ||
2085 parseAndCheckArgument(YamlMFI.ArgInfo->WorkGroupInfo,
2086 AMDGPU::SGPR_32RegClass,
2087 MFI->ArgInfo.WorkGroupInfo, 0, 1) ||
2088 parseAndCheckArgument(YamlMFI.ArgInfo->PrivateSegmentWaveByteOffset,
2089 AMDGPU::SGPR_32RegClass,
2090 MFI->ArgInfo.PrivateSegmentWaveByteOffset, 0, 1) ||
2091 parseAndCheckArgument(YamlMFI.ArgInfo->ImplicitArgPtr,
2092 AMDGPU::SReg_64RegClass,
2093 MFI->ArgInfo.ImplicitArgPtr, 0, 0) ||
2094 parseAndCheckArgument(YamlMFI.ArgInfo->ImplicitBufferPtr,
2095 AMDGPU::SReg_64RegClass,
2096 MFI->ArgInfo.ImplicitBufferPtr, 2, 0) ||
2097 parseAndCheckArgument(YamlMFI.ArgInfo->WorkItemIDX,
2098 AMDGPU::VGPR_32RegClass,
2099 MFI->ArgInfo.WorkItemIDX, 0, 0) ||
2100 parseAndCheckArgument(YamlMFI.ArgInfo->WorkItemIDY,
2101 AMDGPU::VGPR_32RegClass,
2102 MFI->ArgInfo.WorkItemIDY, 0, 0) ||
2103 parseAndCheckArgument(YamlMFI.ArgInfo->WorkItemIDZ,
2104 AMDGPU::VGPR_32RegClass,
2105 MFI->ArgInfo.WorkItemIDZ, 0, 0)))
2106 return true;
2107
2108 // Parse FirstKernArgPreloadReg separately, since it's a Register,
2109 // not ArgDescriptor.
2110 if (YamlMFI.ArgInfo && YamlMFI.ArgInfo->FirstKernArgPreloadReg) {
2111 const yaml::SIArgument &A = *YamlMFI.ArgInfo->FirstKernArgPreloadReg;
2112
2113 if (!A.IsRegister) {
2114 // For stack arguments, we don't have RegisterName.SourceRange,
2115 // but we should have some location info from the YAML parser
2116 const MemoryBuffer &Buffer =
2117 *PFS.SM->getMemoryBuffer(PFS.SM->getMainFileID());
2118 // Create a minimal valid source range
2120 SMRange Range(Loc, Loc);
2121
2123 *PFS.SM, Loc, Buffer.getBufferIdentifier(), 1, 0, SourceMgr::DK_Error,
2124 "firstKernArgPreloadReg must be a register, not a stack location", "",
2125 {}, {});
2126
2127 SourceRange = Range;
2128 return true;
2129 }
2130
2131 Register Reg;
2132 if (parseNamedRegisterReference(PFS, Reg, A.RegisterName.Value, Error)) {
2133 SourceRange = A.RegisterName.SourceRange;
2134 return true;
2135 }
2136
2137 if (!AMDGPU::SGPR_32RegClass.contains(Reg))
2138 return diagnoseRegisterClass(A.RegisterName);
2139
2140 MFI->ArgInfo.FirstKernArgPreloadReg = Reg;
2141 MFI->NumUserSGPRs += YamlMFI.NumKernargPreloadSGPRs;
2142 }
2143
2144 if (ST.hasFeature(AMDGPU::FeatureDX10ClampAndIEEEMode)) {
2145 MFI->Mode.IEEE = YamlMFI.Mode.IEEE;
2146 MFI->Mode.DX10Clamp = YamlMFI.Mode.DX10Clamp;
2147 }
2148
2149 // FIXME: Move proper support for denormal-fp-math into base MachineFunction
2150 MFI->Mode.FP32Denormals.Input = YamlMFI.Mode.FP32InputDenormals
2153 MFI->Mode.FP32Denormals.Output = YamlMFI.Mode.FP32OutputDenormals
2156
2163
2164 if (YamlMFI.HasInitWholeWave)
2165 MFI->setInitWholeWave();
2166
2167 return false;
2168}
2169
2170//===----------------------------------------------------------------------===//
2171// AMDGPU CodeGen Pass Builder interface.
2172//===----------------------------------------------------------------------===//
2173
2174AMDGPUCodeGenPassBuilder::AMDGPUCodeGenPassBuilder(
2175 GCNTargetMachine &TM, const CGPassBuilderOption &Opts,
2177 : CodeGenPassBuilder(TM, Opts, PIC) {
2178 Opt.MISchedPostRA = true;
2179 Opt.RequiresCodeGenSCCOrder = true;
2180 // Exceptions and StackMaps are not supported, so these passes will never do
2181 // anything.
2182 // Garbage collection is not supported.
2183 disablePass<StackMapLivenessPass, FuncletLayoutPass, PatchableFunctionPass,
2185}
2186
2187void AMDGPUCodeGenPassBuilder::addIRPasses(PassManagerWrapper &PMW) const {
2188 if (RemoveIncompatibleFunctions && TM.getTargetTriple().isAMDGCN()) {
2189 flushFPMsToMPM(PMW);
2190 addModulePass(AMDGPURemoveIncompatibleFunctionsPass(TM), PMW);
2191 }
2192
2193 flushFPMsToMPM(PMW);
2194
2195 if (TM.getTargetTriple().isAMDGCN())
2196 addModulePass(AMDGPUPrintfRuntimeBindingPass(), PMW);
2197
2198 if (LowerCtorDtor)
2199 addModulePass(AMDGPUCtorDtorLoweringPass(), PMW);
2200
2201 if (isPassEnabled(EnableImageIntrinsicOptimizer))
2202 addFunctionPass(AMDGPUImageIntrinsicOptimizerPass(TM), PMW);
2203
2205 addFunctionPass(AMDGPUUniformIntrinsicCombinePass(), PMW);
2206 // This can be disabled by passing ::Disable here or on the command line
2207 // with --expand-variadics-override=disable.
2208 flushFPMsToMPM(PMW);
2210
2211 addModulePass(AMDGPUAlwaysInlinePass(), PMW);
2212 addModulePass(AlwaysInlinerPass(), PMW);
2213
2214 addModulePass(AMDGPUExportKernelRuntimeHandlesPass(), PMW);
2215
2217 addModulePass(AMDGPULowerExecSyncPass(), PMW);
2218
2219 if (EnableSwLowerLDS)
2220 addModulePass(AMDGPUSwLowerLDSPass(TM), PMW);
2221
2222 // Runs before PromoteAlloca so the latter can account for function uses
2224 addModulePass(AMDGPULowerModuleLDSPass(TM), PMW);
2225
2226 // Run atomic optimizer before Atomic Expand
2227 if (TM.getOptLevel() >= CodeGenOptLevel::Less &&
2229 addFunctionPass(
2231
2232 addFunctionPass(AtomicExpandPass(TM), PMW);
2233
2234 if (TM.getOptLevel() > CodeGenOptLevel::None) {
2235 addFunctionPass(AMDGPUPromoteAllocaPass(TM), PMW);
2236 if (isPassEnabled(EnableScalarIRPasses))
2237 addStraightLineScalarOptimizationPasses(PMW);
2238
2239 // TODO: Handle EnableAMDGPUAliasAnalysis
2240
2241 // TODO: May want to move later or split into an early and late one.
2242 addFunctionPass(AMDGPUCodeGenPreparePass(TM), PMW);
2243
2244 // Try to hoist loop invariant parts of divisions AMDGPUCodeGenPrepare may
2245 // have expanded.
2246 if (TM.getOptLevel() > CodeGenOptLevel::Less) {
2248 /*UseMemorySSA=*/true),
2249 PMW);
2250 }
2251 }
2252
2253 Base::addIRPasses(PMW);
2254
2255 // EarlyCSE is not always strong enough to clean up what LSR produces. For
2256 // example, GVN can combine
2257 //
2258 // %0 = add %a, %b
2259 // %1 = add %b, %a
2260 //
2261 // and
2262 //
2263 // %0 = shl nsw %a, 2
2264 // %1 = shl %a, 2
2265 //
2266 // but EarlyCSE can do neither of them.
2267 if (isPassEnabled(EnableScalarIRPasses))
2268 addEarlyCSEOrGVNPass(PMW);
2269}
2270
2271void AMDGPUCodeGenPassBuilder::addCodeGenPrepare(
2272 PassManagerWrapper &PMW) const {
2273 if (TM.getOptLevel() > CodeGenOptLevel::None) {
2274 flushFPMsToMPM(PMW);
2275 addModulePass(AMDGPUPreloadKernelArgumentsPass(TM), PMW);
2276 }
2277
2279 addFunctionPass(AMDGPULowerKernelArgumentsPass(TM), PMW);
2280
2281 Base::addCodeGenPrepare(PMW);
2282
2283 if (isPassEnabled(EnableLoadStoreVectorizer))
2284 addFunctionPass(LoadStoreVectorizerPass(), PMW);
2285
2286 // This lowering has been placed after codegenprepare to take advantage of
2287 // address mode matching (which is why it isn't put with the LDS lowerings).
2288 // It could be placed anywhere before uniformity annotations (an analysis
2289 // that it changes by splitting up fat pointers into their components)
2290 // but has been put before switch lowering and CFG flattening so that those
2291 // passes can run on the more optimized control flow this pass creates in
2292 // many cases.
2293 flushFPMsToMPM(PMW);
2294 addModulePass(AMDGPULowerBufferFatPointersPass(TM), PMW);
2295 flushFPMsToMPM(PMW);
2296 requireCGSCCOrder(PMW);
2297
2298 addModulePass(AMDGPULowerIntrinsicsPass(TM), PMW);
2299
2300 // LowerSwitch pass may introduce unreachable blocks that can cause unexpected
2301 // behavior for subsequent passes. Placing it here seems better that these
2302 // blocks would get cleaned up by UnreachableBlockElim inserted next in the
2303 // pass flow.
2304 addFunctionPass(LowerSwitchPass(), PMW);
2305}
2306
2307void AMDGPUCodeGenPassBuilder::addPreISel(PassManagerWrapper &PMW) const {
2308
2309 if (TM.getOptLevel() > CodeGenOptLevel::None) {
2310 addFunctionPass(FlattenCFGPass(), PMW);
2311 addFunctionPass(SinkingPass(), PMW);
2312 addFunctionPass(AMDGPULateCodeGenPreparePass(TM), PMW);
2313 }
2314
2315 // Merge divergent exit nodes. StructurizeCFG won't recognize the multi-exit
2316 // regions formed by them.
2317
2318 addFunctionPass(AMDGPUUnifyDivergentExitNodesPass(), PMW);
2319 addFunctionPass(FixIrreduciblePass(), PMW);
2320 addFunctionPass(UnifyLoopExitsPass(), PMW);
2321 addFunctionPass(StructurizeCFGPass(/*SkipUniformRegions=*/false), PMW);
2322
2323 addFunctionPass(AMDGPUAnnotateUniformValuesPass(), PMW);
2324
2325 addFunctionPass(SIAnnotateControlFlowPass(TM), PMW);
2326
2327 // TODO: Move this right after structurizeCFG to avoid extra divergence
2328 // analysis. This depends on stopping SIAnnotateControlFlow from making
2329 // control flow modifications.
2330 addFunctionPass(AMDGPURewriteUndefForPHIPass(), PMW);
2331
2333 !isGlobalISelAbortEnabled() || !NewRegBankSelect)
2334 addFunctionPass(LCSSAPass(), PMW);
2335
2336 if (TM.getOptLevel() > CodeGenOptLevel::Less) {
2337 flushFPMsToMPM(PMW);
2338 addModulePass(AMDGPUPerfHintAnalysisPass(TM), PMW);
2339 }
2340
2341 // FIXME: Why isn't this queried as required from AMDGPUISelDAGToDAG, and why
2342 // isn't this in addInstSelector?
2344 /*Force=*/true);
2345}
2346
2347void AMDGPUCodeGenPassBuilder::addILPOpts(PassManagerWrapper &PMW) const {
2349 addMachineFunctionPass(EarlyIfConverterPass(), PMW);
2350
2351 Base::addILPOpts(PMW);
2352}
2353
2354void AMDGPUCodeGenPassBuilder::addAsmPrinterBegin(
2355 PassManagerWrapper &PMW, CreateMCStreamer CreateStreamer) const {
2356 // TODO: Add AsmPrinterBegin
2357}
2358
2359void AMDGPUCodeGenPassBuilder::addAsmPrinter(
2360 PassManagerWrapper &PMW, CreateMCStreamer CreateStreamer) const {
2361 // TODO: Add AsmPrinter.
2362}
2363
2364void AMDGPUCodeGenPassBuilder::addAsmPrinterEnd(
2365 PassManagerWrapper &PMW, CreateMCStreamer CreateStreamer) const {
2366 // TODO: Add AsmPrinterEnd
2367}
2368
2369Error AMDGPUCodeGenPassBuilder::addInstSelector(PassManagerWrapper &PMW) const {
2370 addMachineFunctionPass(AMDGPUISelDAGToDAGPass(TM), PMW);
2371 addMachineFunctionPass(SIFixSGPRCopiesPass(), PMW);
2372 addMachineFunctionPass(SILowerI1CopiesPass(), PMW);
2373 return Error::success();
2374}
2375
2376void AMDGPUCodeGenPassBuilder::addPreRewrite(PassManagerWrapper &PMW) const {
2377 if (EnableRegReassign) {
2378 addMachineFunctionPass(GCNNSAReassignPass(), PMW);
2379 }
2380
2381 addMachineFunctionPass(AMDGPURewriteAGPRCopyMFMAPass(), PMW);
2382}
2383
2384void AMDGPUCodeGenPassBuilder::addMachineSSAOptimization(
2385 PassManagerWrapper &PMW) const {
2386 Base::addMachineSSAOptimization(PMW);
2387
2388 addMachineFunctionPass(SIFoldOperandsPass(), PMW);
2389 if (EnableDPPCombine) {
2390 addMachineFunctionPass(GCNDPPCombinePass(), PMW);
2391 }
2392 addMachineFunctionPass(SILoadStoreOptimizerPass(), PMW);
2393 if (isPassEnabled(EnableSDWAPeephole)) {
2394 addMachineFunctionPass(SIPeepholeSDWAPass(), PMW);
2395 addMachineFunctionPass(EarlyMachineLICMPass(), PMW);
2396 addMachineFunctionPass(MachineCSEPass(), PMW);
2397 addMachineFunctionPass(SIFoldOperandsPass(), PMW);
2398 }
2399 addMachineFunctionPass(DeadMachineInstructionElimPass(), PMW);
2400 addMachineFunctionPass(SIShrinkInstructionsPass(), PMW);
2401}
2402
2403Error AMDGPUCodeGenPassBuilder::addFastRegAlloc(PassManagerWrapper &PMW) const {
2404 insertPass<PHIEliminationPass>(SILowerControlFlowPass());
2405
2406 insertPass<TwoAddressInstructionPass>(SIWholeQuadModePass());
2407
2408 return Base::addFastRegAlloc(PMW);
2409}
2410
2411Error AMDGPUCodeGenPassBuilder::addRegAssignmentFast(
2412 PassManagerWrapper &PMW) const {
2413 if (auto Err = validateRegAllocOptions())
2414 return Err;
2415
2416 addMachineFunctionPass(GCNPreRALongBranchRegPass(), PMW);
2417
2418 // SGPR allocation - default to fast at -O0.
2419 if (SGPRRegAllocNPM == RegAllocType::Greedy)
2420 addMachineFunctionPass(RAGreedyPass({onlyAllocateSGPRs, "sgpr"}), PMW);
2421 else
2422 addMachineFunctionPass(RegAllocFastPass({onlyAllocateSGPRs, "sgpr", false}),
2423 PMW);
2424
2425 // Equivalent of PEI for SGPRs.
2426 addMachineFunctionPass(SILowerSGPRSpillsPass(), PMW);
2427
2428 // To Allocate wwm registers used in whole quad mode operations (for shaders).
2429 addMachineFunctionPass(SIPreAllocateWWMRegsPass(), PMW);
2430
2431 // WWM allocation - default to fast at -O0.
2432 if (WWMRegAllocNPM == RegAllocType::Greedy)
2433 addMachineFunctionPass(RAGreedyPass({onlyAllocateWWMRegs, "wwm"}), PMW);
2434 else
2435 addMachineFunctionPass(
2436 RegAllocFastPass({onlyAllocateWWMRegs, "wwm", false}), PMW);
2437
2438 addMachineFunctionPass(SILowerWWMCopiesPass(), PMW);
2439 addMachineFunctionPass(AMDGPUReserveWWMRegsPass(), PMW);
2440
2441 // VGPR allocation - default to fast at -O0.
2442 if (VGPRRegAllocNPM == RegAllocType::Greedy)
2443 addMachineFunctionPass(RAGreedyPass({onlyAllocateVGPRs, "vgpr"}), PMW);
2444 else
2445 addMachineFunctionPass(RegAllocFastPass({onlyAllocateVGPRs, "vgpr"}), PMW);
2446
2447 return Error::success();
2448}
2449
2450Error AMDGPUCodeGenPassBuilder::addOptimizedRegAlloc(
2451 PassManagerWrapper &PMW) const {
2452 if (EnableDCEInRA)
2453 insertPass<DetectDeadLanesPass>(DeadMachineInstructionElimPass());
2454
2455 // FIXME: when an instruction has a Killed operand, and the instruction is
2456 // inside a bundle, seems only the BUNDLE instruction appears as the Kills of
2457 // the register in LiveVariables, this would trigger a failure in verifier,
2458 // we should fix it and enable the verifier.
2459 if (OptVGPRLiveRange)
2460 insertPass<RequireAnalysisPass<LiveVariablesAnalysis, MachineFunction>>(
2462
2463 // This must be run immediately after phi elimination and before
2464 // TwoAddressInstructions, otherwise the processing of the tied operand of
2465 // SI_ELSE will introduce a copy of the tied operand source after the else.
2466 insertPass<PHIEliminationPass>(SILowerControlFlowPass());
2467
2469 insertPass<RenameIndependentSubregsPass>(GCNRewritePartialRegUsesPass());
2470
2471 if (isPassEnabled(EnablePreRAOptimizations))
2472 insertPass<MachineSchedulerPass>(GCNPreRAOptimizationsPass());
2473
2474 // Allow the scheduler to run before SIWholeQuadMode inserts exec manipulation
2475 // instructions that cause scheduling barriers.
2476 insertPass<MachineSchedulerPass>(SIWholeQuadModePass());
2477
2478 if (OptExecMaskPreRA)
2479 insertPass<MachineSchedulerPass>(SIOptimizeExecMaskingPreRAPass());
2480
2481 // This is not an essential optimization and it has a noticeable impact on
2482 // compilation time, so we only enable it from O2.
2483 if (TM.getOptLevel() > CodeGenOptLevel::Less)
2484 insertPass<MachineSchedulerPass>(SIFormMemoryClausesPass());
2485
2486 return Base::addOptimizedRegAlloc(PMW);
2487}
2488
2489void AMDGPUCodeGenPassBuilder::addPreRegAlloc(PassManagerWrapper &PMW) const {
2490 if (getOptLevel() != CodeGenOptLevel::None)
2491 addMachineFunctionPass(AMDGPUPrepareAGPRAllocPass(), PMW);
2492}
2493
2494Error AMDGPUCodeGenPassBuilder::addRegAssignmentOptimized(
2495 PassManagerWrapper &PMW) const {
2496 if (auto Err = validateRegAllocOptions())
2497 return Err;
2498
2499 addMachineFunctionPass(GCNPreRALongBranchRegPass(), PMW);
2500
2501 // SGPR allocation - default to greedy at -O1 and above.
2502 if (SGPRRegAllocNPM == RegAllocType::Fast)
2503 addMachineFunctionPass(RegAllocFastPass({onlyAllocateSGPRs, "sgpr", false}),
2504 PMW);
2505 else
2506 addMachineFunctionPass(RAGreedyPass({onlyAllocateSGPRs, "sgpr"}), PMW);
2507
2508 // Commit allocated register changes. This is mostly necessary because too
2509 // many things rely on the use lists of the physical registers, such as the
2510 // verifier. This is only necessary with allocators which use LiveIntervals,
2511 // since FastRegAlloc does the replacements itself.
2512 addMachineFunctionPass(VirtRegRewriterPass(false), PMW);
2513
2514 // At this point, the sgpr-regalloc has been done and it is good to have the
2515 // stack slot coloring to try to optimize the SGPR spill stack indices before
2516 // attempting the custom SGPR spill lowering.
2517 addMachineFunctionPass(StackSlotColoringPass(), PMW);
2518
2519 // Equivalent of PEI for SGPRs.
2520 addMachineFunctionPass(SILowerSGPRSpillsPass(), PMW);
2521
2522 // To Allocate wwm registers used in whole quad mode operations (for shaders).
2523 addMachineFunctionPass(SIPreAllocateWWMRegsPass(), PMW);
2524
2525 // WWM allocation - default to greedy at -O1 and above.
2526 if (WWMRegAllocNPM == RegAllocType::Fast)
2527 addMachineFunctionPass(
2528 RegAllocFastPass({onlyAllocateWWMRegs, "wwm", false}), PMW);
2529 else
2530 addMachineFunctionPass(RAGreedyPass({onlyAllocateWWMRegs, "wwm"}), PMW);
2531 addMachineFunctionPass(SILowerWWMCopiesPass(), PMW);
2532 addMachineFunctionPass(VirtRegRewriterPass(false), PMW);
2533 addMachineFunctionPass(AMDGPUReserveWWMRegsPass(), PMW);
2534
2535 // VGPR allocation - default to greedy at -O1 and above.
2536 if (VGPRRegAllocNPM == RegAllocType::Fast)
2537 addMachineFunctionPass(RegAllocFastPass({onlyAllocateVGPRs, "vgpr"}), PMW);
2538 else
2539 addMachineFunctionPass(RAGreedyPass({onlyAllocateVGPRs, "vgpr"}), PMW);
2540
2541 addPreRewrite(PMW);
2542 addMachineFunctionPass(VirtRegRewriterPass(true), PMW);
2543
2544 addMachineFunctionPass(AMDGPUMarkLastScratchLoadPass(), PMW);
2545 return Error::success();
2546}
2547
2548void AMDGPUCodeGenPassBuilder::addPostRegAlloc(PassManagerWrapper &PMW) const {
2549 addMachineFunctionPass(SIFixVGPRCopiesPass(), PMW);
2550 if (TM.getOptLevel() > CodeGenOptLevel::None)
2551 addMachineFunctionPass(SIOptimizeExecMaskingPass(), PMW);
2552 Base::addPostRegAlloc(PMW);
2553}
2554
2555void AMDGPUCodeGenPassBuilder::addPreSched2(PassManagerWrapper &PMW) const {
2556 if (TM.getOptLevel() > CodeGenOptLevel::None)
2557 addMachineFunctionPass(SIShrinkInstructionsPass(), PMW);
2558 addMachineFunctionPass(SIPostRABundlerPass(), PMW);
2559}
2560
2561void AMDGPUCodeGenPassBuilder::addPostBBSections(
2562 PassManagerWrapper &PMW) const {
2563 // We run this later to avoid passes like livedebugvalues and BBSections
2564 // having to deal with the apparent multi-entry functions we may generate.
2565 addMachineFunctionPass(AMDGPUPreloadKernArgPrologPass(), PMW);
2566}
2567
2568void AMDGPUCodeGenPassBuilder::addPreEmitPass(PassManagerWrapper &PMW) const {
2569 if (isPassEnabled(EnableVOPD, CodeGenOptLevel::Less)) {
2570 addMachineFunctionPass(GCNCreateVOPDPass(), PMW);
2571 }
2572
2573 addMachineFunctionPass(SIMemoryLegalizerPass(), PMW);
2574 addMachineFunctionPass(SIInsertWaitcntsPass(), PMW);
2575
2576 addMachineFunctionPass(SIModeRegisterPass(), PMW);
2577
2578 if (TM.getOptLevel() > CodeGenOptLevel::None)
2579 addMachineFunctionPass(SIInsertHardClausesPass(), PMW);
2580
2581 addMachineFunctionPass(SILateBranchLoweringPass(), PMW);
2582
2583 if (isPassEnabled(EnableSetWavePriority, CodeGenOptLevel::Less))
2584 addMachineFunctionPass(AMDGPUSetWavePriorityPass(), PMW);
2585
2586 if (TM.getOptLevel() > CodeGenOptLevel::None)
2587 addMachineFunctionPass(SIPreEmitPeepholePass(), PMW);
2588
2589 // The hazard recognizer that runs as part of the post-ra scheduler does not
2590 // guarantee to be able handle all hazards correctly. This is because if there
2591 // are multiple scheduling regions in a basic block, the regions are scheduled
2592 // bottom up, so when we begin to schedule a region we don't know what
2593 // instructions were emitted directly before it.
2594 //
2595 // Here we add a stand-alone hazard recognizer pass which can handle all
2596 // cases.
2597 addMachineFunctionPass(PostRAHazardRecognizerPass(), PMW);
2598 addMachineFunctionPass(AMDGPUWaitSGPRHazardsPass(), PMW);
2599 addMachineFunctionPass(AMDGPULowerVGPREncodingPass(), PMW);
2600
2601 if (isPassEnabled(EnableInsertDelayAlu, CodeGenOptLevel::Less)) {
2602 addMachineFunctionPass(AMDGPUInsertDelayAluPass(), PMW);
2603 }
2604
2605 addMachineFunctionPass(BranchRelaxationPass(), PMW);
2606}
2607
2608bool AMDGPUCodeGenPassBuilder::isPassEnabled(const cl::opt<bool> &Opt,
2609 CodeGenOptLevel Level) const {
2610 if (Opt.getNumOccurrences())
2611 return Opt;
2612 if (TM.getOptLevel() < Level)
2613 return false;
2614 return Opt;
2615}
2616
2617void AMDGPUCodeGenPassBuilder::addEarlyCSEOrGVNPass(
2618 PassManagerWrapper &PMW) const {
2619 if (TM.getOptLevel() == CodeGenOptLevel::Aggressive)
2620 addFunctionPass(GVNPass(), PMW);
2621 else
2622 addFunctionPass(EarlyCSEPass(), PMW);
2623}
2624
2625void AMDGPUCodeGenPassBuilder::addStraightLineScalarOptimizationPasses(
2626 PassManagerWrapper &PMW) const {
2628 addFunctionPass(LoopDataPrefetchPass(), PMW);
2629
2630 addFunctionPass(SeparateConstOffsetFromGEPPass(), PMW);
2631
2632 // ReassociateGEPs exposes more opportunities for SLSR. See
2633 // the example in reassociate-geps-and-slsr.ll.
2634 addFunctionPass(StraightLineStrengthReducePass(), PMW);
2635
2636 // SeparateConstOffsetFromGEP and SLSR creates common expressions which GVN or
2637 // EarlyCSE can reuse.
2638 addEarlyCSEOrGVNPass(PMW);
2639
2640 // Run NaryReassociate after EarlyCSE/GVN to be more effective.
2641 addFunctionPass(NaryReassociatePass(), PMW);
2642
2643 // NaryReassociate on GEPs creates redundant common expressions, so run
2644 // EarlyCSE after it.
2645 addFunctionPass(EarlyCSEPass(), PMW);
2646}
aarch64 falkor hwpf fix Falkor HW Prefetch Fix Late Phase
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
static cl::opt< bool > EnableEarlyIfConversion("aarch64-enable-early-ifcvt", cl::Hidden, cl::desc("Run early if-conversion"), cl::init(true))
static std::unique_ptr< TargetLoweringObjectFile > createTLOF(const Triple &TT)
This is the AMGPU address space based alias analysis pass.
Defines an instruction selector for the AMDGPU target.
Analyzes if a function potentially memory bound and if a kernel kernel may benefit from limiting numb...
Analyzes how many registers and other resources are used by functions.
static cl::opt< bool > EnableDCEInRA("amdgpu-dce-in-ra", cl::init(true), cl::Hidden, cl::desc("Enable machine DCE inside regalloc"))
static cl::opt< bool, true > EnableLowerModuleLDS("amdgpu-enable-lower-module-lds", cl::desc("Enable lower module lds pass"), cl::location(AMDGPUTargetMachine::EnableLowerModuleLDS), cl::init(true), cl::Hidden)
static MachineSchedRegistry GCNMaxMemoryClauseSchedRegistry("gcn-max-memory-clause", "Run GCN scheduler to maximize memory clause", createGCNMaxMemoryClauseMachineScheduler)
static Reloc::Model getEffectiveRelocModel()
static cl::opt< bool > EnableUniformIntrinsicCombine("amdgpu-enable-uniform-intrinsic-combine", cl::desc("Enable/Disable the Uniform Intrinsic Combine Pass"), cl::init(true), cl::Hidden)
static MachineSchedRegistry SISchedRegistry("si", "Run SI's custom scheduler", createSIMachineScheduler)
static ScheduleDAGInstrs * createIterativeILPMachineScheduler(MachineSchedContext *C)
static cl::opt< bool > EarlyInlineAll("amdgpu-early-inline-all", cl::desc("Inline all functions early"), cl::init(false), cl::Hidden)
static cl::opt< bool > EnableSwLowerLDS("amdgpu-enable-sw-lower-lds", cl::desc("Enable lowering of lds to global memory pass " "and asan instrument resulting IR."), cl::init(true), cl::Hidden)
static cl::opt< bool > EnableLowerKernelArguments("amdgpu-ir-lower-kernel-arguments", cl::desc("Lower kernel argument loads in IR pass"), cl::init(true), cl::Hidden)
static ScheduleDAGInstrs * createGCNMaxILPMachineScheduler(MachineSchedContext *C)
static cl::opt< bool > EnableSDWAPeephole("amdgpu-sdwa-peephole", cl::desc("Enable SDWA peepholer"), cl::init(true))
static MachineSchedRegistry GCNMinRegSchedRegistry("gcn-iterative-minreg", "Run GCN iterative scheduler for minimal register usage (experimental)", createMinRegScheduler)
static cl::opt< bool > EnableImageIntrinsicOptimizer("amdgpu-enable-image-intrinsic-optimizer", cl::desc("Enable image intrinsic optimizer pass"), cl::init(true), cl::Hidden)
static cl::opt< bool > HasClosedWorldAssumption("amdgpu-link-time-closed-world", cl::desc("Whether has closed-world assumption at link time"), cl::init(false), cl::Hidden)
static ScheduleDAGInstrs * createGCNMaxMemoryClauseMachineScheduler(MachineSchedContext *C)
static cl::opt< bool > EnableSIModeRegisterPass("amdgpu-mode-register", cl::desc("Enable mode register pass"), cl::init(true), cl::Hidden)
static cl::opt< std::string > AMDGPUSchedStrategy("amdgpu-sched-strategy", cl::desc("Select custom AMDGPU scheduling strategy."), cl::Hidden, cl::init(""))
static cl::opt< bool > EnableDPPCombine("amdgpu-dpp-combine", cl::desc("Enable DPP combiner"), cl::init(true))
static MachineSchedRegistry IterativeGCNMaxOccupancySchedRegistry("gcn-iterative-max-occupancy-experimental", "Run GCN scheduler to maximize occupancy (experimental)", createIterativeGCNMaxOccupancyMachineScheduler)
static cl::opt< bool > EnableSetWavePriority("amdgpu-set-wave-priority", cl::desc("Adjust wave priority"), cl::init(false), cl::Hidden)
static cl::opt< bool > LowerCtorDtor("amdgpu-lower-global-ctor-dtor", cl::desc("Lower GPU ctor / dtors to globals on the device."), cl::init(true), cl::Hidden)
static cl::opt< bool > OptExecMaskPreRA("amdgpu-opt-exec-mask-pre-ra", cl::Hidden, cl::desc("Run pre-RA exec mask optimizations"), cl::init(true))
static cl::opt< bool > EnablePromoteKernelArguments("amdgpu-enable-promote-kernel-arguments", cl::desc("Enable promotion of flat kernel pointer arguments to global"), cl::Hidden, cl::init(true))
LLVM_ABI LLVM_EXTERNAL_VISIBILITY void LLVMInitializeAMDGPUTarget()
static cl::opt< bool > EnableRewritePartialRegUses("amdgpu-enable-rewrite-partial-reg-uses", cl::desc("Enable rewrite partial reg uses pass"), cl::init(true), cl::Hidden)
static cl::opt< bool > EnableLibCallSimplify("amdgpu-simplify-libcall", cl::desc("Enable amdgpu library simplifications"), cl::init(true), cl::Hidden)
static MachineSchedRegistry GCNMaxILPSchedRegistry("gcn-max-ilp", "Run GCN scheduler to maximize ilp", createGCNMaxILPMachineScheduler)
static cl::opt< bool > InternalizeSymbols("amdgpu-internalize-symbols", cl::desc("Enable elimination of non-kernel functions and unused globals"), cl::init(false), cl::Hidden)
static cl::opt< bool > EnableAMDGPUAttributor("amdgpu-attributor-enable", cl::desc("Enable AMDGPUAttributorPass"), cl::init(true), cl::Hidden)
static LLVM_READNONE StringRef getGPUOrDefault(const Triple &TT, StringRef GPU)
Expected< AMDGPUAttributorOptions > parseAMDGPUAttributorPassOptions(StringRef Params)
static cl::opt< bool > EnableAMDGPUAliasAnalysis("enable-amdgpu-aa", cl::Hidden, cl::desc("Enable AMDGPU Alias Analysis"), cl::init(true))
static Expected< ScanOptions > parseAMDGPUAtomicOptimizerStrategy(StringRef Params)
static ScheduleDAGInstrs * createMinRegScheduler(MachineSchedContext *C)
static cl::opt< bool > EnableHipStdPar("amdgpu-enable-hipstdpar", cl::desc("Enable HIP Standard Parallelism Offload support"), cl::init(false), cl::Hidden)
static cl::opt< bool > EnableInsertDelayAlu("amdgpu-enable-delay-alu", cl::desc("Enable s_delay_alu insertion"), cl::init(true), cl::Hidden)
static ScheduleDAGInstrs * createIterativeGCNMaxOccupancyMachineScheduler(MachineSchedContext *C)
static cl::opt< bool > EnableLoadStoreVectorizer("amdgpu-load-store-vectorizer", cl::desc("Enable load store vectorizer"), cl::init(true), cl::Hidden)
static bool mustPreserveGV(const GlobalValue &GV)
Predicate for Internalize pass.
static cl::opt< bool > EnableLoopPrefetch("amdgpu-loop-prefetch", cl::desc("Enable loop data prefetch on AMDGPU"), cl::Hidden, cl::init(false))
static cl::opt< bool > NewRegBankSelect("new-reg-bank-select", cl::desc("Run amdgpu-regbankselect and amdgpu-regbanklegalize instead of " "regbankselect"), cl::init(false), cl::Hidden)
static cl::opt< bool > RemoveIncompatibleFunctions("amdgpu-enable-remove-incompatible-functions", cl::Hidden, cl::desc("Enable removal of functions when they" "use features not supported by the target GPU"), cl::init(true))
static cl::opt< bool > EnableScalarIRPasses("amdgpu-scalar-ir-passes", cl::desc("Enable scalar IR passes"), cl::init(true), cl::Hidden)
static cl::opt< bool > EnableRegReassign("amdgpu-reassign-regs", cl::desc("Enable register reassign optimizations on gfx10+"), cl::init(true), cl::Hidden)
static cl::opt< bool > OptVGPRLiveRange("amdgpu-opt-vgpr-liverange", cl::desc("Enable VGPR liverange optimizations for if-else structure"), cl::init(true), cl::Hidden)
static ScheduleDAGInstrs * createSIMachineScheduler(MachineSchedContext *C)
static cl::opt< bool > EnablePreRAOptimizations("amdgpu-enable-pre-ra-optimizations", cl::desc("Enable Pre-RA optimizations pass"), cl::init(true), cl::Hidden)
static cl::opt< ScanOptions > AMDGPUAtomicOptimizerStrategy("amdgpu-atomic-optimizer-strategy", cl::desc("Select DPP or Iterative strategy for scan"), cl::init(ScanOptions::Iterative), cl::values(clEnumValN(ScanOptions::DPP, "DPP", "Use DPP operations for scan"), clEnumValN(ScanOptions::Iterative, "Iterative", "Use Iterative approach for scan"), clEnumValN(ScanOptions::None, "None", "Disable atomic optimizer")))
static cl::opt< bool > EnableVOPD("amdgpu-enable-vopd", cl::desc("Enable VOPD, dual issue of VALU in wave32"), cl::init(true), cl::Hidden)
static ScheduleDAGInstrs * createGCNMaxOccupancyMachineScheduler(MachineSchedContext *C)
static cl::opt< bool > EnableLowerExecSync("amdgpu-enable-lower-exec-sync", cl::desc("Enable lowering of execution synchronization."), cl::init(true), cl::Hidden)
static MachineSchedRegistry GCNILPSchedRegistry("gcn-iterative-ilp", "Run GCN iterative scheduler for ILP scheduling (experimental)", createIterativeILPMachineScheduler)
static cl::opt< bool > ScalarizeGlobal("amdgpu-scalarize-global-loads", cl::desc("Enable global load scalarization"), cl::init(true), cl::Hidden)
static const char RegAllocOptNotSupportedMessage[]
static MachineSchedRegistry GCNMaxOccupancySchedRegistry("gcn-max-occupancy", "Run GCN scheduler to maximize occupancy", createGCNMaxOccupancyMachineScheduler)
The AMDGPU TargetMachine interface definition for hw codegen targets.
This file declares the AMDGPU-specific subclass of TargetLoweringObjectFile.
This file a TargetTransformInfoImplBase conforming object specific to the AMDGPU target machine.
Provides passes to inlining "always_inline" functions.
static GCRegistry::Add< ErlangGC > A("erlang", "erlang-compatible garbage collector")
static GCRegistry::Add< StatepointGC > D("statepoint-example", "an example strategy for statepoint")
This header provides classes for managing passes over SCCs of the call graph.
Provides analysis for continuously CSEing during GISel passes.
Interfaces for producing common pass manager configurations.
#define clEnumValN(ENUMVAL, FLAGNAME, DESC)
#define LLVM_READNONE
Definition Compiler.h:315
#define LLVM_ABI
Definition Compiler.h:213
#define LLVM_EXTERNAL_VISIBILITY
Definition Compiler.h:132
DXIL Legalizer
This file provides the interface for a simple, fast CSE pass.
This file defines the class GCNIterativeScheduler, which uses an iterative approach to find a best sc...
This file provides the interface for LLVM's Global Value Numbering pass which eliminates fully redund...
#define _
AcceleratorCodeSelection - Identify all functions reachable from a kernel, removing those that are un...
This file declares the IRTranslator pass.
This header defines various interfaces for pass management in LLVM.
#define RegName(no)
This file provides the interface for LLVM's Loop Data Prefetching Pass.
This header provides classes for managing a pipeline of passes over loops in LLVM IR.
#define F(x, y, z)
Definition MD5.cpp:54
#define I(x, y, z)
Definition MD5.cpp:57
Register Reg
Register const TargetRegisterInfo * TRI
#define T
ConstantRange Range(APInt(BitWidth, Low), APInt(BitWidth, High))
uint64_t IntrinsicInst * II
#define P(N)
CGSCCAnalysisManager CGAM
LoopAnalysisManager LAM
FunctionAnalysisManager FAM
ModuleAnalysisManager MAM
PassInstrumentationCallbacks PIC
PassBuilder PB(Machine, PassOpts->PTO, std::nullopt, &PIC)
static bool isLTOPreLink(ThinOrFullLTOPhase Phase)
The AMDGPU TargetMachine interface definition for hw codegen targets.
This file describes the interface of the MachineFunctionPass responsible for assigning the generic vi...
const GCNTargetMachine & getTM(const GCNSubtarget *STI)
SI Machine Scheduler interface.
static bool contains(SmallPtrSetImpl< ConstantExpr * > &Cache, ConstantExpr *Expr, Constant *C)
Definition Value.cpp:487
static TableGen::Emitter::Opt Y("gen-skeleton-entry", EmitSkeleton, "Generate example skeleton entry")
static TableGen::Emitter::OptClass< SkeletonEmitter > X("gen-skeleton-class", "Generate example skeleton class")
static FunctionPass * useDefaultRegisterAllocator()
-regalloc=... command line option.
static cl::opt< cl::boolOrDefault > EnableGlobalISelOption("global-isel", cl::Hidden, cl::desc("Enable the \"global\" instruction selector"))
Target-Independent Code Generator Pass Configuration Options pass.
LLVM IR instance of the generic uniformity analysis.
static std::unique_ptr< TargetLoweringObjectFile > createTLOF()
A manager for alias analyses.
void registerFunctionAnalysis()
Register a specific AA result.
void addAAResult(AAResultT &AAResult)
Register a specific AA result.
Legacy wrapper pass to provide the AMDGPUAAResult object.
Analysis pass providing a never-invalidated alias analysis result.
Lower llvm.global_ctors and llvm.global_dtors to special kernels.
AMDGPUTargetMachine & getAMDGPUTargetMachine() const
std::unique_ptr< CSEConfigBase > getCSEConfig() const override
Returns the CSEConfig object to use for the current optimization level.
bool isPassEnabled(const cl::opt< bool > &Opt, CodeGenOptLevel Level=CodeGenOptLevel::Default) const
Check if a pass is enabled given Opt option.
bool addPreISel() override
Methods with trivial inline returns are convenient points in the common codegen pass pipeline where t...
bool addInstSelector() override
addInstSelector - This method should install an instruction selector pass, which converts from LLVM c...
bool addGCPasses() override
addGCPasses - Add late codegen passes that analyze code for garbage collection.
AMDGPUPassConfig(TargetMachine &TM, PassManagerBase &PM)
void addIRPasses() override
Add common target configurable passes that perform LLVM IR to IR transforms following machine indepen...
void addCodeGenPrepare() override
Add pass to prepare the LLVM IR for code generation.
Splits the module M into N linkable partitions.
std::unique_ptr< TargetLoweringObjectFile > TLOF
static int64_t getNullPointerValue(unsigned AddrSpace)
Get the integer value of a null pointer in the given address space.
unsigned getAddressSpaceForPseudoSourceKind(unsigned Kind) const override
getAddressSpaceForPseudoSourceKind - Given the kind of memory (e.g.
const TargetSubtargetInfo * getSubtargetImpl() const
void registerDefaultAliasAnalyses(AAManager &) override
Allow the target to register alias analyses with the AAManager for use with the new pass manager.
std::pair< const Value *, unsigned > getPredicatedAddrSpace(const Value *V) const override
If the specified predicate checks whether a generic pointer falls within a specified address space,...
StringRef getFeatureString(const Function &F) const
ScheduleDAGInstrs * createMachineScheduler(MachineSchedContext *C) const override
Create an instance of ScheduleDAGInstrs to be run within the standard MachineScheduler pass for this ...
AMDGPUTargetMachine(const Target &T, const Triple &TT, StringRef CPU, StringRef FS, const TargetOptions &Options, std::optional< Reloc::Model > RM, std::optional< CodeModel::Model > CM, CodeGenOptLevel OL)
bool isNoopAddrSpaceCast(unsigned SrcAS, unsigned DestAS) const override
Returns true if a cast between SrcAS and DestAS is a noop.
void registerPassBuilderCallbacks(PassBuilder &PB) override
Allow the target to modify the pass pipeline.
StringRef getGPUName(const Function &F) const
unsigned getAssumedAddrSpace(const Value *V) const override
If the specified generic pointer could be assumed as a pointer to a specific address space,...
bool splitModule(Module &M, unsigned NumParts, function_ref< void(std::unique_ptr< Module > MPart)> ModuleCallback) override
Entry point for module splitting.
Inlines functions marked as "always_inline".
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.
@ REGION_ADDRESS
Address space for region memory. (GDS)
@ LOCAL_ADDRESS
Address space for local memory.
@ CONSTANT_ADDRESS
Address space for constant memory (VTX2).
@ FLAT_ADDRESS
Address space for flat memory.
@ GLOBAL_ADDRESS
Address space for global memory (RAT0, VTX0).
@ PRIVATE_ADDRESS
Address space for private memory.
bool isFlatGlobalAddrSpace(unsigned AS)
LLVM_READNONE constexpr bool isModuleEntryFunctionCC(CallingConv::ID CC)
LLVM_READNONE constexpr bool isEntryFunctionCC(CallingConv::ID CC)
@ C
The default llvm calling convention, compatible with C.
Definition CallingConv.h:34
BinaryOp_match< SrcTy, SpecificConstantMatch, TargetOpcode::G_XOR, true > m_Not(const SrcTy &&Src)
Matches a register not-ed by a G_XOR.
BinaryOp_match< LHS, RHS, Instruction::And, true > m_c_And(const LHS &L, const RHS &R)
Matches an And with LHS and RHS in either order.
bool match(Val *V, const Pattern &P)
IntrinsicID_match m_Intrinsic()
Match intrinsic calls like this: m_Intrinsic<Intrinsic::fabs>(m_Value(X))
deferredval_ty< Value > m_Deferred(Value *const &V)
Like m_Specific(), but works if the specific value to match is determined as part of the same match()...
class_match< Value > m_Value()
Match an arbitrary value and ignore it.
template class LLVM_TEMPLATE_ABI opt< bool >
ValuesClass values(OptsTy... Options)
Helper to build a ValuesClass by forwarding a variable number of arguments as an initializer list to ...
initializer< Ty > init(const Ty &Val)
LocationClass< Ty > location(Ty &L)
This is an optimization pass for GlobalISel generic memory operations.
Definition Types.h:26
ScheduleDAGMILive * createSchedLive(MachineSchedContext *C)
Create the standard converging machine scheduler.
LLVM_ABI FunctionPass * createFlattenCFGPass()
std::unique_ptr< ScheduleDAGMutation > createAMDGPUBarrierLatencyDAGMutation(MachineFunction *MF)
LLVM_ABI FunctionPass * createFastRegisterAllocator()
FastRegisterAllocation Pass - This pass register allocates as fast as possible.
LLVM_ABI char & EarlyMachineLICMID
This pass performs loop invariant code motion on machine instructions.
ImmutablePass * createAMDGPUAAWrapperPass()
LLVM_ABI char & PostRAHazardRecognizerID
PostRAHazardRecognizer - This pass runs the post-ra hazard recognizer.
std::function< bool(const TargetRegisterInfo &TRI, const MachineRegisterInfo &MRI, const Register Reg)> RegAllocFilterFunc
Filter function for register classes during regalloc.
FunctionPass * createAMDGPUSetWavePriorityPass()
LLVM_ABI Pass * createLCSSAPass()
Definition LCSSA.cpp:525
void initializeAMDGPUMarkLastScratchLoadLegacyPass(PassRegistry &)
void initializeAMDGPUInsertDelayAluLegacyPass(PassRegistry &)
void initializeSIOptimizeExecMaskingPreRALegacyPass(PassRegistry &)
char & GCNPreRAOptimizationsID
LLVM_ABI char & GCLoweringID
GCLowering Pass - Used by gc.root to perform its default lowering operations.
void initializeSIInsertHardClausesLegacyPass(PassRegistry &)
ModulePass * createExpandVariadicsPass(ExpandVariadicsMode)
FunctionPass * createSIAnnotateControlFlowLegacyPass()
Create the annotation pass.
FunctionPass * createSIModeRegisterPass()
void initializeGCNPreRAOptimizationsLegacyPass(PassRegistry &)
void initializeSILowerWWMCopiesLegacyPass(PassRegistry &)
LLVM_ABI FunctionPass * createGreedyRegisterAllocator()
Greedy register allocation pass - This pass implements a global register allocator for optimized buil...
void initializeAMDGPUAAWrapperPassPass(PassRegistry &)
void initializeSIShrinkInstructionsLegacyPass(PassRegistry &)
ModulePass * createAMDGPULowerBufferFatPointersPass()
void initializeR600ClauseMergePassPass(PassRegistry &)
ModulePass * createAMDGPUCtorDtorLoweringLegacyPass()
decltype(auto) dyn_cast(const From &Val)
dyn_cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:643
ModuleToFunctionPassAdaptor createModuleToFunctionPassAdaptor(FunctionPassT &&Pass, bool EagerlyInvalidate=false)
A function to deduce a function pass type and wrap it in the templated adaptor.
ModulePass * createAMDGPUSwLowerLDSLegacyPass(const AMDGPUTargetMachine *TM=nullptr)
void initializeGCNRewritePartialRegUsesLegacyPass(llvm::PassRegistry &)
void initializeAMDGPURewriteUndefForPHILegacyPass(PassRegistry &)
char & GCNRewritePartialRegUsesID
void initializeAMDGPUSwLowerLDSLegacyPass(PassRegistry &)
LLVM_ABI std::error_code inconvertibleErrorCode()
The value returned by this function can be returned from convertToErrorCode for Error values where no...
Definition Error.cpp:94
void initializeAMDGPULowerVGPREncodingLegacyPass(PassRegistry &)
char & AMDGPUWaitSGPRHazardsLegacyID
void initializeSILowerSGPRSpillsLegacyPass(PassRegistry &)
LLVM_ABI Pass * createLoadStoreVectorizerPass()
Create a legacy pass manager instance of the LoadStoreVectorizer pass.
std::unique_ptr< ScheduleDAGMutation > createIGroupLPDAGMutation(AMDGPU::SchedulingPhase Phase)
Phase specifes whether or not this is a reentry into the IGroupLPDAGMutation.
void initializeAMDGPUDAGToDAGISelLegacyPass(PassRegistry &)
FunctionPass * createAMDGPURegBankCombiner(bool IsOptNone)
LLVM_ABI FunctionPass * createNaryReassociatePass()
char & AMDGPUReserveWWMRegsLegacyID
void initializeAMDGPUWaitSGPRHazardsLegacyPass(PassRegistry &)
LLVM_ABI char & PatchableFunctionID
This pass implements the "patchable-function" attribute.
char & SIOptimizeExecMaskingLegacyID
LLVM_ABI char & PostRASchedulerID
PostRAScheduler - This pass performs post register allocation scheduling.
void initializeR600ExpandSpecialInstrsPassPass(PassRegistry &)
void initializeR600PacketizerPass(PassRegistry &)
std::unique_ptr< ScheduleDAGMutation > createVOPDPairingMutation()
ModulePass * createAMDGPUExportKernelRuntimeHandlesLegacyPass()
ModulePass * createAMDGPUAlwaysInlinePass(bool GlobalOpt=true)
void initializeAMDGPUAsmPrinterPass(PassRegistry &)
void initializeSIFoldOperandsLegacyPass(PassRegistry &)
char & SILoadStoreOptimizerLegacyID
void initializeAMDGPUGlobalISelDivergenceLoweringPass(PassRegistry &)
PassManager< LazyCallGraph::SCC, CGSCCAnalysisManager, LazyCallGraph &, CGSCCUpdateResult & > CGSCCPassManager
The CGSCC pass manager.
LLVM_ABI std::unique_ptr< CSEConfigBase > getStandardCSEConfigForOpt(CodeGenOptLevel Level)
Definition CSEInfo.cpp:85
Target & getTheR600Target()
The target for R600 GPUs.
LLVM_ABI char & MachineSchedulerID
MachineScheduler - This pass schedules machine instructions.
LLVM_ABI Pass * createStructurizeCFGPass(bool SkipUniformRegions=false)
When SkipUniformRegions is true the structizer will not structurize regions that only contain uniform...
LLVM_ABI char & PostMachineSchedulerID
PostMachineScheduler - This pass schedules machine instructions postRA.
LLVM_ABI Pass * createLICMPass()
Definition LICM.cpp:386
char & SIFormMemoryClausesID
void initializeSILoadStoreOptimizerLegacyPass(PassRegistry &)
void initializeAMDGPULowerModuleLDSLegacyPass(PassRegistry &)
AnalysisManager< LazyCallGraph::SCC, LazyCallGraph & > CGSCCAnalysisManager
The CGSCC analysis manager.
void initializeAMDGPUCtorDtorLoweringLegacyPass(PassRegistry &)
LLVM_ABI char & EarlyIfConverterLegacyID
EarlyIfConverter - This pass performs if-conversion on SSA form by inserting cmov instructions.
AnalysisManager< Loop, LoopStandardAnalysisResults & > LoopAnalysisManager
The loop analysis manager.
FunctionPass * createAMDGPUUniformIntrinsicCombineLegacyPass()
void initializeAMDGPURegBankCombinerPass(PassRegistry &)
ThinOrFullLTOPhase
This enumerates the LLVM full LTO or ThinLTO optimization phases.
Definition Pass.h:77
@ FullLTOPostLink
Full LTO postlink (backend compile) phase.
Definition Pass.h:87
char & AMDGPUUnifyDivergentExitNodesID
void initializeAMDGPUPrepareAGPRAllocLegacyPass(PassRegistry &)
FunctionPass * createAMDGPUAtomicOptimizerPass(ScanOptions ScanStrategy)
FunctionPass * createAMDGPUPreloadKernArgPrologLegacyPass()
char & SIOptimizeVGPRLiveRangeLegacyID
LLVM_ABI char & ShadowStackGCLoweringID
ShadowStackGCLowering - Implements the custom lowering mechanism used by the shadow stack GC.
char & GCNNSAReassignID
void initializeAMDGPURewriteOutArgumentsPass(PassRegistry &)
static Reloc::Model getEffectiveRelocModel(std::optional< Reloc::Model > RM)
void initializeAMDGPUExternalAAWrapperPass(PassRegistry &)
auto formatv(bool Validate, const char *Fmt, Ts &&...Vals)
void initializeAMDGPULowerKernelArgumentsPass(PassRegistry &)
void initializeSIModeRegisterLegacyPass(PassRegistry &)
CodeModel::Model getEffectiveCodeModel(std::optional< CodeModel::Model > CM, CodeModel::Model Default)
Helper method for getting the code model, returning Default if CM does not have a value.
void initializeAMDGPUPreloadKernelArgumentsLegacyPass(PassRegistry &)
char & SILateBranchLoweringPassID
FunctionToLoopPassAdaptor createFunctionToLoopPassAdaptor(LoopPassT &&Pass, bool UseMemorySSA=false)
A function to deduce a loop pass type and wrap it in the templated adaptor.
std::function< Expected< std::unique_ptr< MCStreamer > >(TargetMachine &)> CreateMCStreamer
LLVM_ABI char & BranchRelaxationPassID
BranchRelaxation - This pass replaces branches that need to jump further than is supported by a branc...
LLVM_ABI FunctionPass * createSinkingPass()
Definition Sink.cpp:275
CGSCCToFunctionPassAdaptor createCGSCCToFunctionPassAdaptor(FunctionPassT &&Pass, bool EagerlyInvalidate=false, bool NoRerun=false)
A function to deduce a function pass type and wrap it in the templated adaptor.
void initializeSIMemoryLegalizerLegacyPass(PassRegistry &)
ModulePass * createAMDGPULowerIntrinsicsLegacyPass()
void initializeR600MachineCFGStructurizerPass(PassRegistry &)
CodeGenFileType
These enums are meant to be passed into addPassesToEmitFile to indicate what type of file to emit,...
Definition CodeGen.h:111
char & GCNDPPCombineLegacyID
PassManager< Module > ModulePassManager
Convenience typedef for a pass manager over modules.
LLVM_ABI std::unique_ptr< ScheduleDAGMutation > createStoreClusterDAGMutation(const TargetInstrInfo *TII, const TargetRegisterInfo *TRI, bool ReorderWhileClustering=false)
If ReorderWhileClustering is set to true, no attempt will be made to reduce reordering due to store c...
LLVM_ABI FunctionPass * createLoopDataPrefetchPass()
FunctionPass * createAMDGPULowerKernelArgumentsPass()
char & AMDGPUInsertDelayAluID
std::unique_ptr< ScheduleDAGMutation > createAMDGPUMacroFusionDAGMutation()
Note that you have to add: DAG.addMutation(createAMDGPUMacroFusionDAGMutation()); to AMDGPUTargetMach...
LLVM_ABI char & StackMapLivenessID
StackMapLiveness - This pass analyses the register live-out set of stackmap/patchpoint intrinsics and...
void initializeGCNPreRALongBranchRegLegacyPass(PassRegistry &)
char & SILowerWWMCopiesLegacyID
LLVM_ABI FunctionPass * createUnifyLoopExitsPass()
char & SIOptimizeExecMaskingPreRAID
LLVM_ABI FunctionPass * createFixIrreduciblePass()
void initializeR600EmitClauseMarkersPass(PassRegistry &)
LLVM_ABI char & FuncletLayoutID
This pass lays out funclets contiguously.
LLVM_ABI char & DetectDeadLanesID
This pass adds dead/undef flags after analyzing subregister lanes.
void initializeAMDGPULowerExecSyncLegacyPass(PassRegistry &)
void initializeAMDGPUPostLegalizerCombinerPass(PassRegistry &)
void initializeAMDGPUExportKernelRuntimeHandlesLegacyPass(PassRegistry &)
CodeGenOptLevel
Code generation optimization level.
Definition CodeGen.h:82
void initializeSIInsertWaitcntsLegacyPass(PassRegistry &)
ModulePass * createAMDGPUPreloadKernelArgumentsLegacyPass(const TargetMachine *)
ModulePass * createAMDGPUPrintfRuntimeBinding()
LLVM_ABI char & StackSlotColoringID
StackSlotColoring - This pass performs stack slot coloring.
LLVM_ABI Pass * createAlwaysInlinerLegacyPass(bool InsertLifetime=true)
Create a legacy pass manager instance of a pass to inline and remove functions marked as "always_inli...
void initializeR600ControlFlowFinalizerPass(PassRegistry &)
void initializeAMDGPUImageIntrinsicOptimizerPass(PassRegistry &)
void initializeSILateBranchLoweringLegacyPass(PassRegistry &)
void initializeSILowerControlFlowLegacyPass(PassRegistry &)
void initializeSIFormMemoryClausesLegacyPass(PassRegistry &)
char & SIPreAllocateWWMRegsLegacyID
Error make_error(ArgTs &&... Args)
Make a Error instance representing failure using the given error info type.
Definition Error.h:340
ModulePass * createAMDGPULowerModuleLDSLegacyPass(const AMDGPUTargetMachine *TM=nullptr)
void initializeAMDGPUPreLegalizerCombinerPass(PassRegistry &)
FunctionPass * createAMDGPUPromoteAlloca()
LLVM_ABI FunctionPass * createSeparateConstOffsetFromGEPPass(bool LowerGEP=false)
void initializeAMDGPUReserveWWMRegsLegacyPass(PassRegistry &)
char & SIPreEmitPeepholeID
char & SIPostRABundlerLegacyID
ModulePass * createAMDGPURemoveIncompatibleFunctionsPass(const TargetMachine *)
void initializeGCNRegPressurePrinterPass(PassRegistry &)
void initializeSILowerI1CopiesLegacyPass(PassRegistry &)
char & SILowerSGPRSpillsLegacyID
LLVM_ABI FunctionPass * createBasicRegisterAllocator()
BasicRegisterAllocation Pass - This pass implements a degenerate global register allocator using the ...
LLVM_ABI void initializeGlobalISel(PassRegistry &)
Initialize all passes linked into the GlobalISel library.
char & SILowerControlFlowLegacyID
ModulePass * createR600OpenCLImageTypeLoweringPass()
FunctionPass * createAMDGPUCodeGenPreparePass()
void initializeSIAnnotateControlFlowLegacyPass(PassRegistry &)
FunctionPass * createAMDGPUISelDag(TargetMachine &TM, CodeGenOptLevel OptLevel)
This pass converts a legalized DAG into a AMDGPU-specific.
void initializeGCNCreateVOPDLegacyPass(PassRegistry &)
void initializeAMDGPUUniformIntrinsicCombineLegacyPass(PassRegistry &)
void initializeSIPreAllocateWWMRegsLegacyPass(PassRegistry &)
void initializeSIFixVGPRCopiesLegacyPass(PassRegistry &)
Target & getTheGCNTarget()
The target for GCN GPUs.
void initializeSIFixSGPRCopiesLegacyPass(PassRegistry &)
void initializeAMDGPUAtomicOptimizerPass(PassRegistry &)
void initializeAMDGPULowerIntrinsicsLegacyPass(PassRegistry &)
LLVM_ABI FunctionPass * createGVNPass()
Create a legacy GVN pass.
Definition GVN.cpp:3418
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.