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"
25#include "AMDGPUHazardLatency.h"
26#include "AMDGPUIGroupLP.h"
27#include "AMDGPUISelDAGToDAG.h"
29#include "AMDGPUMacroFusion.h"
37#include "AMDGPUSplitModule.h"
42#include "GCNDPPCombine.h"
44#include "GCNNSAReassign.h"
48#include "GCNSchedStrategy.h"
49#include "GCNVOPDUtils.h"
50#include "R600.h"
51#include "R600TargetMachine.h"
52#include "SIFixSGPRCopies.h"
53#include "SIFixVGPRCopies.h"
54#include "SIFoldOperands.h"
55#include "SIFormMemoryClauses.h"
57#include "SILowerControlFlow.h"
58#include "SILowerSGPRSpills.h"
59#include "SILowerWWMCopies.h"
61#include "SIMachineScheduler.h"
65#include "SIPeepholeSDWA.h"
66#include "SIPostRABundler.h"
69#include "SIWholeQuadMode.h"
90#include "llvm/CodeGen/Passes.h"
95#include "llvm/IR/IntrinsicsAMDGPU.h"
96#include "llvm/IR/PassManager.h"
105#include "llvm/Transforms/IPO.h"
130#include <optional>
131
132using namespace llvm;
133using namespace llvm::PatternMatch;
134
135namespace {
136//===----------------------------------------------------------------------===//
137// AMDGPU CodeGen Pass Builder interface.
138//===----------------------------------------------------------------------===//
139
140class AMDGPUCodeGenPassBuilder
141 : public CodeGenPassBuilder<AMDGPUCodeGenPassBuilder, GCNTargetMachine> {
142 using Base = CodeGenPassBuilder<AMDGPUCodeGenPassBuilder, GCNTargetMachine>;
143
144public:
145 AMDGPUCodeGenPassBuilder(GCNTargetMachine &TM,
146 const CGPassBuilderOption &Opts,
147 PassInstrumentationCallbacks *PIC);
148
149 void addIRPasses(PassManagerWrapper &PMW) const;
150 void addCodeGenPrepare(PassManagerWrapper &PMW) const;
151 void addPreISel(PassManagerWrapper &PMW) const;
152 void addILPOpts(PassManagerWrapper &PMWM) const;
153 void addAsmPrinterBegin(PassManagerWrapper &PMW) const;
154 void addAsmPrinter(PassManagerWrapper &PMW) const;
155 void addAsmPrinterEnd(PassManagerWrapper &PMW) const;
156 Error addInstSelector(PassManagerWrapper &PMW) const;
157 void addPreRewrite(PassManagerWrapper &PMW) const;
158 void addMachineSSAOptimization(PassManagerWrapper &PMW) const;
159 void addPostRegAlloc(PassManagerWrapper &PMW) const;
160 void addPreEmitPass(PassManagerWrapper &PMWM) const;
161 void addPreEmitRegAlloc(PassManagerWrapper &PMW) const;
162 Error addRegAssignmentFast(PassManagerWrapper &PMW) const;
163 Error addRegAssignmentOptimized(PassManagerWrapper &PMW) const;
164 void addPreRegAlloc(PassManagerWrapper &PMW) const;
165 Error addFastRegAlloc(PassManagerWrapper &PMW) const;
166 Error addOptimizedRegAlloc(PassManagerWrapper &PMW) const;
167 void addPreSched2(PassManagerWrapper &PMW) const;
168 void addPostBBSections(PassManagerWrapper &PMW) const;
169
170private:
171 Error validateRegAllocOptions() const;
172
173public:
174 /// Check if a pass is enabled given \p Opt option. The option always
175 /// overrides defaults if explicitly used. Otherwise its default will be used
176 /// given that a pass shall work at an optimization \p Level minimum.
177 bool isPassEnabled(const cl::opt<bool> &Opt,
178 CodeGenOptLevel Level = CodeGenOptLevel::Default) const;
179 void addEarlyCSEOrGVNPass(PassManagerWrapper &PMW) const;
180 void addStraightLineScalarOptimizationPasses(PassManagerWrapper &PMW) const;
181};
182
183class SGPRRegisterRegAlloc : public RegisterRegAllocBase<SGPRRegisterRegAlloc> {
184public:
185 SGPRRegisterRegAlloc(const char *N, const char *D, FunctionPassCtor C)
186 : RegisterRegAllocBase(N, D, C) {}
187};
188
189class VGPRRegisterRegAlloc : public RegisterRegAllocBase<VGPRRegisterRegAlloc> {
190public:
191 VGPRRegisterRegAlloc(const char *N, const char *D, FunctionPassCtor C)
192 : RegisterRegAllocBase(N, D, C) {}
193};
194
195class WWMRegisterRegAlloc : public RegisterRegAllocBase<WWMRegisterRegAlloc> {
196public:
197 WWMRegisterRegAlloc(const char *N, const char *D, FunctionPassCtor C)
198 : RegisterRegAllocBase(N, D, C) {}
199};
200
201static bool onlyAllocateSGPRs(const TargetRegisterInfo &TRI,
202 const MachineRegisterInfo &MRI,
203 const Register Reg) {
204 const TargetRegisterClass *RC = MRI.getRegClass(Reg);
205 return static_cast<const SIRegisterInfo &>(TRI).isSGPRClass(RC);
206}
207
208static bool onlyAllocateVGPRs(const TargetRegisterInfo &TRI,
209 const MachineRegisterInfo &MRI,
210 const Register Reg) {
211 const TargetRegisterClass *RC = MRI.getRegClass(Reg);
212 return !static_cast<const SIRegisterInfo &>(TRI).isSGPRClass(RC);
213}
214
215static bool onlyAllocateWWMRegs(const TargetRegisterInfo &TRI,
216 const MachineRegisterInfo &MRI,
217 const Register Reg) {
218 const SIMachineFunctionInfo *MFI =
220 const TargetRegisterClass *RC = MRI.getRegClass(Reg);
221 return !static_cast<const SIRegisterInfo &>(TRI).isSGPRClass(RC) &&
223}
224
225/// -{sgpr|wwm|vgpr}-regalloc=... command line option.
226static FunctionPass *useDefaultRegisterAllocator() { return nullptr; }
227
228/// A dummy default pass factory indicates whether the register allocator is
229/// overridden on the command line.
230static llvm::once_flag InitializeDefaultSGPRRegisterAllocatorFlag;
231static llvm::once_flag InitializeDefaultVGPRRegisterAllocatorFlag;
232static llvm::once_flag InitializeDefaultWWMRegisterAllocatorFlag;
233
234static SGPRRegisterRegAlloc
235defaultSGPRRegAlloc("default",
236 "pick SGPR register allocator based on -O option",
238
239static cl::opt<SGPRRegisterRegAlloc::FunctionPassCtor, false,
241SGPRRegAlloc("sgpr-regalloc", cl::Hidden, cl::init(&useDefaultRegisterAllocator),
242 cl::desc("Register allocator to use for SGPRs"));
243
244static cl::opt<VGPRRegisterRegAlloc::FunctionPassCtor, false,
246VGPRRegAlloc("vgpr-regalloc", cl::Hidden, cl::init(&useDefaultRegisterAllocator),
247 cl::desc("Register allocator to use for VGPRs"));
248
249static cl::opt<WWMRegisterRegAlloc::FunctionPassCtor, false,
251 WWMRegAlloc("wwm-regalloc", cl::Hidden,
253 cl::desc("Register allocator to use for WWM registers"));
254
255// New pass manager register allocator options for AMDGPU
257 "sgpr-regalloc-npm", cl::Hidden, cl::init(RegAllocType::Default),
258 cl::desc("Register allocator for SGPRs (new pass manager)"));
259
261 "vgpr-regalloc-npm", cl::Hidden, cl::init(RegAllocType::Default),
262 cl::desc("Register allocator for VGPRs (new pass manager)"));
263
265 "wwm-regalloc-npm", cl::Hidden, cl::init(RegAllocType::Default),
266 cl::desc("Register allocator for WWM registers (new pass manager)"));
267
268/// Check if the given RegAllocType is supported for AMDGPU NPM register
269/// allocation. Only Fast and Greedy are supported; Basic and PBQP are not.
270static Error checkRegAllocSupported(RegAllocType RAType, StringRef RegName) {
271 if (RAType == RegAllocType::Basic || RAType == RegAllocType::PBQP) {
273 Twine("unsupported register allocator '") +
274 (RAType == RegAllocType::Basic ? "basic" : "pbqp") + "' for " +
275 RegName + " registers",
277 }
278 return Error::success();
279}
280
281Error AMDGPUCodeGenPassBuilder::validateRegAllocOptions() const {
282 // 1. Generic --regalloc-npm is not supported for AMDGPU.
283 if (Opt.RegAlloc != RegAllocType::Unset) {
285 "-regalloc-npm not supported for amdgcn. Use -sgpr-regalloc-npm, "
286 "-vgpr-regalloc-npm, and -wwm-regalloc-npm",
288 }
289
290 // 2. Legacy PM regalloc options are not compatible with NPM.
291 if (SGPRRegAlloc.getNumOccurrences() > 0 ||
292 VGPRRegAlloc.getNumOccurrences() > 0 ||
293 WWMRegAlloc.getNumOccurrences() > 0) {
295 "-sgpr-regalloc, -vgpr-regalloc, and -wwm-regalloc are legacy PM "
296 "options. Use -sgpr-regalloc-npm, -vgpr-regalloc-npm, and "
297 "-wwm-regalloc-npm with the new pass manager",
299 }
300
301 // 3. Only Fast and Greedy allocators are supported for AMDGPU.
302 if (auto Err = checkRegAllocSupported(SGPRRegAllocNPM, "SGPR"))
303 return Err;
304 if (auto Err = checkRegAllocSupported(WWMRegAllocNPM, "WWM"))
305 return Err;
306 if (auto Err = checkRegAllocSupported(VGPRRegAllocNPM, "VGPR"))
307 return Err;
308
309 return Error::success();
310}
311
312static void initializeDefaultSGPRRegisterAllocatorOnce() {
313 RegisterRegAlloc::FunctionPassCtor Ctor = SGPRRegisterRegAlloc::getDefault();
314
315 if (!Ctor) {
316 Ctor = SGPRRegAlloc;
317 SGPRRegisterRegAlloc::setDefault(SGPRRegAlloc);
318 }
319}
320
321static void initializeDefaultVGPRRegisterAllocatorOnce() {
322 RegisterRegAlloc::FunctionPassCtor Ctor = VGPRRegisterRegAlloc::getDefault();
323
324 if (!Ctor) {
325 Ctor = VGPRRegAlloc;
326 VGPRRegisterRegAlloc::setDefault(VGPRRegAlloc);
327 }
328}
329
330static void initializeDefaultWWMRegisterAllocatorOnce() {
331 RegisterRegAlloc::FunctionPassCtor Ctor = WWMRegisterRegAlloc::getDefault();
332
333 if (!Ctor) {
334 Ctor = WWMRegAlloc;
335 WWMRegisterRegAlloc::setDefault(WWMRegAlloc);
336 }
337}
338
339static FunctionPass *createBasicSGPRRegisterAllocator() {
340 return createBasicRegisterAllocator(onlyAllocateSGPRs);
341}
342
343static FunctionPass *createGreedySGPRRegisterAllocator() {
344 return createGreedyRegisterAllocator(onlyAllocateSGPRs);
345}
346
347static FunctionPass *createFastSGPRRegisterAllocator() {
348 return createFastRegisterAllocator(onlyAllocateSGPRs, false);
349}
350
351static FunctionPass *createBasicVGPRRegisterAllocator() {
352 return createBasicRegisterAllocator(onlyAllocateVGPRs);
353}
354
355static FunctionPass *createGreedyVGPRRegisterAllocator() {
356 return createGreedyRegisterAllocator(onlyAllocateVGPRs);
357}
358
359static FunctionPass *createFastVGPRRegisterAllocator() {
360 return createFastRegisterAllocator(onlyAllocateVGPRs, true);
361}
362
363static FunctionPass *createBasicWWMRegisterAllocator() {
364 return createBasicRegisterAllocator(onlyAllocateWWMRegs);
365}
366
367static FunctionPass *createGreedyWWMRegisterAllocator() {
368 return createGreedyRegisterAllocator(onlyAllocateWWMRegs);
369}
370
371static FunctionPass *createFastWWMRegisterAllocator() {
372 return createFastRegisterAllocator(onlyAllocateWWMRegs, false);
373}
374
375static SGPRRegisterRegAlloc basicRegAllocSGPR(
376 "basic", "basic register allocator", createBasicSGPRRegisterAllocator);
377static SGPRRegisterRegAlloc greedyRegAllocSGPR(
378 "greedy", "greedy register allocator", createGreedySGPRRegisterAllocator);
379
380static SGPRRegisterRegAlloc fastRegAllocSGPR(
381 "fast", "fast register allocator", createFastSGPRRegisterAllocator);
382
383
384static VGPRRegisterRegAlloc basicRegAllocVGPR(
385 "basic", "basic register allocator", createBasicVGPRRegisterAllocator);
386static VGPRRegisterRegAlloc greedyRegAllocVGPR(
387 "greedy", "greedy register allocator", createGreedyVGPRRegisterAllocator);
388
389static VGPRRegisterRegAlloc fastRegAllocVGPR(
390 "fast", "fast register allocator", createFastVGPRRegisterAllocator);
391static WWMRegisterRegAlloc basicRegAllocWWMReg("basic",
392 "basic register allocator",
393 createBasicWWMRegisterAllocator);
394static WWMRegisterRegAlloc
395 greedyRegAllocWWMReg("greedy", "greedy register allocator",
396 createGreedyWWMRegisterAllocator);
397static WWMRegisterRegAlloc fastRegAllocWWMReg("fast", "fast register allocator",
398 createFastWWMRegisterAllocator);
399
401 return Phase == ThinOrFullLTOPhase::FullLTOPreLink ||
402 Phase == ThinOrFullLTOPhase::ThinLTOPreLink;
403}
404} // anonymous namespace
405
406static cl::opt<bool>
408 cl::desc("Run early if-conversion"),
409 cl::init(false));
410
411static cl::opt<bool>
412OptExecMaskPreRA("amdgpu-opt-exec-mask-pre-ra", cl::Hidden,
413 cl::desc("Run pre-RA exec mask optimizations"),
414 cl::init(true));
415
416static cl::opt<bool>
417 LowerCtorDtor("amdgpu-lower-global-ctor-dtor",
418 cl::desc("Lower GPU ctor / dtors to globals on the device."),
419 cl::init(true), cl::Hidden);
420
421// Option to disable vectorizer for tests.
423 "amdgpu-load-store-vectorizer",
424 cl::desc("Enable load store vectorizer"),
425 cl::init(true),
426 cl::Hidden);
427
428// Option to control global loads scalarization
430 "amdgpu-scalarize-global-loads",
431 cl::desc("Enable global load scalarization"),
432 cl::init(true),
433 cl::Hidden);
434
435// Option to run internalize pass.
437 "amdgpu-internalize-symbols",
438 cl::desc("Enable elimination of non-kernel functions and unused globals"),
439 cl::init(false),
440 cl::Hidden);
441
442// Option to inline all early.
444 "amdgpu-early-inline-all",
445 cl::desc("Inline all functions early"),
446 cl::init(false),
447 cl::Hidden);
448
450 "amdgpu-enable-remove-incompatible-functions", cl::Hidden,
451 cl::desc("Enable removal of functions when they"
452 "use features not supported by the target GPU"),
453 cl::init(true));
454
456 "amdgpu-sdwa-peephole",
457 cl::desc("Enable SDWA peepholer"),
458 cl::init(true));
459
461 "amdgpu-dpp-combine",
462 cl::desc("Enable DPP combiner"),
463 cl::init(true));
464
465// Enable address space based alias analysis
467 cl::desc("Enable AMDGPU Alias Analysis"),
468 cl::init(true));
469
470// Enable lib calls simplifications
472 "amdgpu-simplify-libcall",
473 cl::desc("Enable amdgpu library simplifications"),
474 cl::init(true),
475 cl::Hidden);
476
478 "amdgpu-ir-lower-kernel-arguments",
479 cl::desc("Lower kernel argument loads in IR pass"),
480 cl::init(true),
481 cl::Hidden);
482
484 "amdgpu-reassign-regs",
485 cl::desc("Enable register reassign optimizations on gfx10+"),
486 cl::init(true),
487 cl::Hidden);
488
490 "amdgpu-opt-vgpr-liverange",
491 cl::desc("Enable VGPR liverange optimizations for if-else structure"),
492 cl::init(true), cl::Hidden);
493
495 "amdgpu-atomic-optimizer-strategy",
496 cl::desc("Select DPP or Iterative strategy for scan"),
499 clEnumValN(ScanOptions::DPP, "DPP", "Use DPP operations for scan"),
501 "Use Iterative approach for scan"),
502 clEnumValN(ScanOptions::None, "None", "Disable atomic optimizer")));
503
504// Enable Mode register optimization
506 "amdgpu-mode-register",
507 cl::desc("Enable mode register pass"),
508 cl::init(true),
509 cl::Hidden);
510
511// Enable GFX11+ s_delay_alu insertion
512static cl::opt<bool>
513 EnableInsertDelayAlu("amdgpu-enable-delay-alu",
514 cl::desc("Enable s_delay_alu insertion"),
515 cl::init(true), cl::Hidden);
516
517// Enable GFX11+ VOPD
518static cl::opt<bool>
519 EnableVOPD("amdgpu-enable-vopd",
520 cl::desc("Enable VOPD, dual issue of VALU in wave32"),
521 cl::init(true), cl::Hidden);
522
523// Option is used in lit tests to prevent deadcoding of patterns inspected.
524static cl::opt<bool>
525EnableDCEInRA("amdgpu-dce-in-ra",
526 cl::init(true), cl::Hidden,
527 cl::desc("Enable machine DCE inside regalloc"));
528
529static cl::opt<bool> EnableSetWavePriority("amdgpu-set-wave-priority",
530 cl::desc("Adjust wave priority"),
531 cl::init(false), cl::Hidden);
532
534 "amdgpu-scalar-ir-passes",
535 cl::desc("Enable scalar IR passes"),
536 cl::init(true),
537 cl::Hidden);
538
540 "amdgpu-enable-lower-exec-sync",
541 cl::desc("Enable lowering of execution synchronization."), cl::init(true),
542 cl::Hidden);
543
544static cl::opt<bool>
545 EnableSwLowerLDS("amdgpu-enable-sw-lower-lds",
546 cl::desc("Enable lowering of lds to global memory pass "
547 "and asan instrument resulting IR."),
548 cl::init(true), cl::Hidden);
549
551 "amdgpu-enable-object-linking",
552 cl::desc("Enable object linking for cross-TU LDS and ABI support"),
554 cl::Hidden);
555
557 "amdgpu-enable-lower-module-lds", cl::desc("Enable lower module lds pass"),
559 cl::Hidden);
560
562 "amdgpu-enable-pre-ra-optimizations",
563 cl::desc("Enable Pre-RA optimizations pass"), cl::init(true),
564 cl::Hidden);
565
567 "amdgpu-enable-promote-kernel-arguments",
568 cl::desc("Enable promotion of flat kernel pointer arguments to global"),
569 cl::Hidden, cl::init(true));
570
572 "amdgpu-enable-image-intrinsic-optimizer",
573 cl::desc("Enable image intrinsic optimizer pass"), cl::init(true),
574 cl::Hidden);
575
576static cl::opt<bool>
577 EnableLoopPrefetch("amdgpu-loop-prefetch",
578 cl::desc("Enable loop data prefetch on AMDGPU"),
579 cl::Hidden, cl::init(false));
580
582 AMDGPUSchedStrategy("amdgpu-sched-strategy",
583 cl::desc("Select custom AMDGPU scheduling strategy."),
584 cl::Hidden, cl::init(""));
585
586// Scheduler selection is consulted both when creating the scheduler and from
587// overrideSchedPolicy(), so keep the attribute and global command line handling
588// in one helper.
590 Attribute SchedStrategyAttr = F.getFnAttribute("amdgpu-sched-strategy");
591 if (SchedStrategyAttr.isValid())
592 return SchedStrategyAttr.getValueAsString();
593
594 if (!AMDGPUSchedStrategy.empty())
595 return AMDGPUSchedStrategy;
596
597 return "";
598}
599
600static void
602 const GCNSubtarget &ST) {
603 if (ST.hasGFX1250Insts())
604 return;
605
606 F.getContext().diagnose(DiagnosticInfoUnsupported(
607 F, "'amdgpu-sched-strategy'='coexec' is only supported for gfx1250",
609}
610
611static bool useNoopPostScheduler(const Function &F) {
612 Attribute PostSchedStrategyAttr =
613 F.getFnAttribute("amdgpu-post-sched-strategy");
614 return PostSchedStrategyAttr.isValid() &&
615 PostSchedStrategyAttr.getValueAsString() == "nop";
616}
617
619 "amdgpu-enable-rewrite-partial-reg-uses",
620 cl::desc("Enable rewrite partial reg uses pass"), cl::init(true),
621 cl::Hidden);
622
624 "amdgpu-enable-hipstdpar",
625 cl::desc("Enable HIP Standard Parallelism Offload support"), cl::init(false),
626 cl::Hidden);
627
628static cl::opt<bool>
629 EnableAMDGPUAttributor("amdgpu-attributor-enable",
630 cl::desc("Enable AMDGPUAttributorPass"),
631 cl::init(true), cl::Hidden);
632
634 "new-reg-bank-select",
635 cl::desc("Run amdgpu-regbankselect and amdgpu-regbanklegalize instead of "
636 "regbankselect"),
637 cl::init(false), cl::Hidden);
638
640 "amdgpu-link-time-closed-world",
641 cl::desc("Whether has closed-world assumption at link time"),
642 cl::init(false), cl::Hidden);
643
645 "amdgpu-enable-uniform-intrinsic-combine",
646 cl::desc("Enable/Disable the Uniform Intrinsic Combine Pass"),
647 cl::init(true), cl::Hidden);
648
650 // Register the target
653
739}
740
741static std::unique_ptr<TargetLoweringObjectFile> createTLOF(const Triple &TT) {
742 return std::make_unique<AMDGPUTargetObjectFile>();
743}
744
748
749static ScheduleDAGInstrs *
751 const GCNSubtarget &ST = C->MF->getSubtarget<GCNSubtarget>();
752 ScheduleDAGMILive *DAG =
753 new GCNScheduleDAGMILive(C, std::make_unique<GCNMaxOccupancySchedStrategy>(C));
754 DAG->addMutation(createLoadClusterDAGMutation(DAG->TII, DAG->TRI));
755 if (ST.shouldClusterStores())
756 DAG->addMutation(createStoreClusterDAGMutation(DAG->TII, DAG->TRI));
758 DAG->addMutation(createAMDGPUMacroFusionDAGMutation());
759 DAG->addMutation(createAMDGPUExportClusteringDAGMutation());
760 DAG->addMutation(createAMDGPUBarrierLatencyDAGMutation(C->MF));
761 DAG->addMutation(createAMDGPUHazardLatencyDAGMutation(C->MF));
762 return DAG;
763}
764
765static ScheduleDAGInstrs *
767 ScheduleDAGMILive *DAG =
768 new GCNScheduleDAGMILive(C, std::make_unique<GCNMaxILPSchedStrategy>(C));
770 return DAG;
771}
772
773static ScheduleDAGInstrs *
775 const GCNSubtarget &ST = C->MF->getSubtarget<GCNSubtarget>();
777 C, std::make_unique<GCNMaxMemoryClauseSchedStrategy>(C));
778 DAG->addMutation(createLoadClusterDAGMutation(DAG->TII, DAG->TRI));
779 if (ST.shouldClusterStores())
780 DAG->addMutation(createStoreClusterDAGMutation(DAG->TII, DAG->TRI));
781 DAG->addMutation(createAMDGPUExportClusteringDAGMutation());
782 DAG->addMutation(createAMDGPUBarrierLatencyDAGMutation(C->MF));
783 DAG->addMutation(createAMDGPUHazardLatencyDAGMutation(C->MF));
784 return DAG;
785}
786
787static ScheduleDAGInstrs *
789 const GCNSubtarget &ST = C->MF->getSubtarget<GCNSubtarget>();
790 auto *DAG = new GCNIterativeScheduler(
792 DAG->addMutation(createLoadClusterDAGMutation(DAG->TII, DAG->TRI));
793 if (ST.shouldClusterStores())
794 DAG->addMutation(createStoreClusterDAGMutation(DAG->TII, DAG->TRI));
796 return DAG;
797}
798
805
806static ScheduleDAGInstrs *
808 const GCNSubtarget &ST = C->MF->getSubtarget<GCNSubtarget>();
810 DAG->addMutation(createLoadClusterDAGMutation(DAG->TII, DAG->TRI));
811 if (ST.shouldClusterStores())
812 DAG->addMutation(createStoreClusterDAGMutation(DAG->TII, DAG->TRI));
813 DAG->addMutation(createAMDGPUMacroFusionDAGMutation());
815 return DAG;
816}
817
818static MachineSchedRegistry
819SISchedRegistry("si", "Run SI's custom scheduler",
821
824 "Run GCN scheduler to maximize occupancy",
826
828 GCNMaxILPSchedRegistry("gcn-max-ilp", "Run GCN scheduler to maximize ilp",
830
832 "gcn-max-memory-clause", "Run GCN scheduler to maximize memory clause",
834
836 "gcn-iterative-max-occupancy-experimental",
837 "Run GCN scheduler to maximize occupancy (experimental)",
839
841 "gcn-iterative-minreg",
842 "Run GCN iterative scheduler for minimal register usage (experimental)",
844
846 "gcn-iterative-ilp",
847 "Run GCN iterative scheduler for ILP scheduling (experimental)",
849
852 if (!GPU.empty())
853 return GPU;
854
855 // Need to default to a target with flat support for HSA.
856 if (TT.isAMDGCN())
857 return TT.getOS() == Triple::AMDHSA ? "generic-hsa" : "generic";
858
859 return "r600";
860}
861
863 // The AMDGPU toolchain only supports generating shared objects, so we
864 // must always use PIC.
865 return Reloc::PIC_;
866}
867
869 StringRef CPU, StringRef FS,
870 const TargetOptions &Options,
871 std::optional<Reloc::Model> RM,
872 std::optional<CodeModel::Model> CM,
875 T, TT.computeDataLayout(), TT, getGPUOrDefault(TT, CPU), FS, Options,
877 OptLevel),
879 initAsmInfo();
880 if (TT.isAMDGCN()) {
881 if (getMCSubtargetInfo()->checkFeatures("+wavefrontsize64"))
883 else if (getMCSubtargetInfo()->checkFeatures("+wavefrontsize32"))
885 }
886}
887
891
893
895 Attribute GPUAttr = F.getFnAttribute("target-cpu");
896 return GPUAttr.isValid() ? GPUAttr.getValueAsString() : getTargetCPU();
897}
898
900 Attribute FSAttr = F.getFnAttribute("target-features");
901
902 return FSAttr.isValid() ? FSAttr.getValueAsString()
904}
905
908 const GCNSubtarget &ST = C->MF->getSubtarget<GCNSubtarget>();
910 DAG->addMutation(createLoadClusterDAGMutation(DAG->TII, DAG->TRI));
911 if (ST.shouldClusterStores())
912 DAG->addMutation(createStoreClusterDAGMutation(DAG->TII, DAG->TRI));
913 return DAG;
914}
915
916/// Predicate for Internalize pass.
917static bool mustPreserveGV(const GlobalValue &GV) {
918 if (const Function *F = dyn_cast<Function>(&GV))
919 return F->isDeclaration() || F->getName().starts_with("__asan_") ||
920 F->getName().starts_with("__sanitizer_") ||
921 AMDGPU::isEntryFunctionCC(F->getCallingConv());
922
924 return !GV.use_empty();
925}
926
931
934 if (Params.empty())
936 Params.consume_front("strategy=");
937 auto Result = StringSwitch<std::optional<ScanOptions>>(Params)
938 .Case("dpp", ScanOptions::DPP)
939 .Cases({"iterative", ""}, ScanOptions::Iterative)
940 .Case("none", ScanOptions::None)
941 .Default(std::nullopt);
942 if (Result)
943 return *Result;
944 return make_error<StringError>("invalid parameter", inconvertibleErrorCode());
945}
946
950 while (!Params.empty()) {
951 StringRef ParamName;
952 std::tie(ParamName, Params) = Params.split(';');
953 if (ParamName == "closed-world") {
954 Result.IsClosedWorld = true;
955 } else {
957 formatv("invalid AMDGPUAttributor pass parameter '{0}' ", ParamName)
958 .str(),
960 }
961 }
962 return Result;
963}
964
966
967#define GET_PASS_REGISTRY "AMDGPUPassRegistry.def"
969
970 PB.registerPipelineParsingCallback(
971 [this](StringRef Name, CGSCCPassManager &PM,
973 if (Name == "amdgpu-attributor-cgscc" && getTargetTriple().isAMDGCN()) {
975 *static_cast<GCNTargetMachine *>(this)));
976 return true;
977 }
978 return false;
979 });
980
981 PB.registerScalarOptimizerLateEPCallback(
982 [](FunctionPassManager &FPM, OptimizationLevel Level) {
983 if (Level == OptimizationLevel::O0)
984 return;
985
987 });
988
989 PB.registerVectorizerEndEPCallback(
990 [](FunctionPassManager &FPM, OptimizationLevel Level) {
991 if (Level == OptimizationLevel::O0)
992 return;
993
995 });
996
997 PB.registerPipelineEarlySimplificationEPCallback(
998 [this](ModulePassManager &PM, OptimizationLevel Level,
1000 if (!isLTOPreLink(Phase) && getTargetTriple().isAMDGCN()) {
1001 // When we are not using -fgpu-rdc, we can run accelerator code
1002 // selection relatively early, but still after linking to prevent
1003 // eager removal of potentially reachable symbols.
1004 if (EnableHipStdPar) {
1007 }
1008
1010 }
1011
1012 if (Level == OptimizationLevel::O0)
1013 return;
1014
1015 // We don't want to run internalization at per-module stage.
1018 PM.addPass(GlobalDCEPass());
1019 }
1020
1023 });
1024
1025 PB.registerPeepholeEPCallback(
1026 [](FunctionPassManager &FPM, OptimizationLevel Level) {
1027 if (Level == OptimizationLevel::O0)
1028 return;
1029
1033
1036 });
1037
1038 PB.registerCGSCCOptimizerLateEPCallback(
1039 [this](CGSCCPassManager &PM, OptimizationLevel Level) {
1040 if (Level == OptimizationLevel::O0)
1041 return;
1042
1044
1045 // Add promote kernel arguments pass to the opt pipeline right before
1046 // infer address spaces which is needed to do actual address space
1047 // rewriting.
1048 if (Level.getSpeedupLevel() > OptimizationLevel::O1.getSpeedupLevel() &&
1051
1052 // Add infer address spaces pass to the opt pipeline after inlining
1053 // but before SROA to increase SROA opportunities.
1055
1056 // This should run after inlining to have any chance of doing
1057 // anything, and before other cleanup optimizations.
1059
1060 // Promote alloca to vector before SROA and loop unroll. If we
1061 // manage to eliminate allocas before unroll we may choose to unroll
1062 // less.
1064
1065 PM.addPass(createCGSCCToFunctionPassAdaptor(std::move(FPM)));
1066 });
1067
1068 // FIXME: Why is AMDGPUAttributor not in CGSCC?
1069 PB.registerOptimizerLastEPCallback([this](ModulePassManager &MPM,
1070 OptimizationLevel Level,
1072 if (Level != OptimizationLevel::O0) {
1073 if (!isLTOPreLink(Phase)) {
1074 if (EnableAMDGPUAttributor && getTargetTriple().isAMDGCN()) {
1076 MPM.addPass(AMDGPUAttributorPass(*this, Opts, Phase));
1077 }
1078 }
1079 }
1080 });
1081
1082 PB.registerFullLinkTimeOptimizationLastEPCallback(
1083 [this](ModulePassManager &PM, OptimizationLevel Level) {
1084 // When we are using -fgpu-rdc, we can only run accelerator code
1085 // selection after linking to prevent, otherwise we end up removing
1086 // potentially reachable symbols that were exported as external in other
1087 // modules.
1088 if (EnableHipStdPar) {
1091 }
1092 // We want to support the -lto-partitions=N option as "best effort".
1093 // For that, we need to lower LDS earlier in the pipeline before the
1094 // module is partitioned for codegen.
1097 if (EnableSwLowerLDS)
1098 PM.addPass(AMDGPUSwLowerLDSPass(*this));
1101 if (Level != OptimizationLevel::O0) {
1102 // We only want to run this with O2 or higher since inliner and SROA
1103 // don't run in O1.
1104 if (Level != OptimizationLevel::O1) {
1105 PM.addPass(
1107 }
1108 // Do we really need internalization in LTO?
1109 if (InternalizeSymbols) {
1111 PM.addPass(GlobalDCEPass());
1112 }
1113 if (EnableAMDGPUAttributor && getTargetTriple().isAMDGCN()) {
1116 Opt.IsClosedWorld = true;
1119 }
1120 }
1121 if (!NoKernelInfoEndLTO) {
1123 FPM.addPass(KernelInfoPrinter(this));
1124 PM.addPass(createModuleToFunctionPassAdaptor(std::move(FPM)));
1125 }
1126 });
1127
1128 PB.registerRegClassFilterParsingCallback(
1129 [](StringRef FilterName) -> RegAllocFilterFunc {
1130 if (FilterName == "sgpr")
1131 return onlyAllocateSGPRs;
1132 if (FilterName == "vgpr")
1133 return onlyAllocateVGPRs;
1134 if (FilterName == "wwm")
1135 return onlyAllocateWWMRegs;
1136 return nullptr;
1137 });
1138}
1139
1141 unsigned DestAS) const {
1142 return AMDGPU::isFlatGlobalAddrSpace(SrcAS) &&
1144}
1145
1147 if (auto *Arg = dyn_cast<Argument>(V);
1148 Arg &&
1149 AMDGPU::isModuleEntryFunctionCC(Arg->getParent()->getCallingConv()) &&
1150 !Arg->hasByRefAttr())
1152
1153 const auto *LD = dyn_cast<LoadInst>(V);
1154 if (!LD) // TODO: Handle invariant load like constant.
1156
1157 // It must be a generic pointer loaded.
1158 assert(V->getType()->getPointerAddressSpace() == AMDGPUAS::FLAT_ADDRESS);
1159
1160 const auto *Ptr = LD->getPointerOperand();
1161 if (Ptr->getType()->getPointerAddressSpace() != AMDGPUAS::CONSTANT_ADDRESS)
1163 // For a generic pointer loaded from the constant memory, it could be assumed
1164 // as a global pointer since the constant memory is only populated on the
1165 // host side. As implied by the offload programming model, only global
1166 // pointers could be referenced on the host side.
1168}
1169
1170std::pair<const Value *, unsigned>
1172 if (auto *II = dyn_cast<IntrinsicInst>(V)) {
1173 switch (II->getIntrinsicID()) {
1174 case Intrinsic::amdgcn_is_shared:
1175 return std::pair(II->getArgOperand(0), AMDGPUAS::LOCAL_ADDRESS);
1176 case Intrinsic::amdgcn_is_private:
1177 return std::pair(II->getArgOperand(0), AMDGPUAS::PRIVATE_ADDRESS);
1178 default:
1179 break;
1180 }
1181 return std::pair(nullptr, -1);
1182 }
1183 // Check the global pointer predication based on
1184 // (!is_share(p) && !is_private(p)). Note that logic 'and' is commutative and
1185 // the order of 'is_shared' and 'is_private' is not significant.
1186 Value *Ptr;
1187 if (match(
1188 const_cast<Value *>(V),
1191 m_Deferred(Ptr))))))
1192 return std::pair(Ptr, AMDGPUAS::GLOBAL_ADDRESS);
1193
1194 return std::pair(nullptr, -1);
1195}
1196
1197unsigned
1212
1214 Module &M, unsigned NumParts,
1215 function_ref<void(std::unique_ptr<Module> MPart)> ModuleCallback) {
1216 // FIXME(?): Would be better to use an already existing Analysis/PassManager,
1217 // but all current users of this API don't have one ready and would need to
1218 // create one anyway. Let's hide the boilerplate for now to keep it simple.
1219
1224
1225 PassBuilder PB(this);
1226 PB.registerModuleAnalyses(MAM);
1227 PB.registerFunctionAnalyses(FAM);
1228 PB.crossRegisterProxies(LAM, FAM, CGAM, MAM);
1229
1231 MPM.addPass(AMDGPUSplitModulePass(NumParts, ModuleCallback));
1232 MPM.run(M, MAM);
1233 return true;
1234}
1235
1236//===----------------------------------------------------------------------===//
1237// GCN Target Machine (SI+)
1238//===----------------------------------------------------------------------===//
1239
1241 StringRef CPU, StringRef FS,
1242 const TargetOptions &Options,
1243 std::optional<Reloc::Model> RM,
1244 std::optional<CodeModel::Model> CM,
1245 CodeGenOptLevel OL, bool JIT)
1246 : AMDGPUTargetMachine(T, TT, CPU, FS, Options, RM, CM, OL) {}
1247
1248const TargetSubtargetInfo *
1250 StringRef GPU = getGPUName(F);
1252
1253 SmallString<128> SubtargetKey(GPU);
1254 SubtargetKey.append(FS);
1255
1256 auto &I = SubtargetMap[SubtargetKey];
1257 if (!I) {
1258 // This needs to be done before we create a new subtarget since any
1259 // creation will depend on the TM and the code generation flags on the
1260 // function that reside in TargetOptions.
1262 I = std::make_unique<GCNSubtarget>(TargetTriple, GPU, FS, *this);
1263 }
1264
1265 I->setScalarizeGlobalBehavior(ScalarizeGlobal);
1266
1267 return I.get();
1268}
1269
1272 return TargetTransformInfo(std::make_unique<GCNTTIImpl>(this, F));
1273}
1274
1277 raw_pwrite_stream *DwoOut, CodeGenFileType FileType,
1278 const CGPassBuilderOption &Opts, MCContext &Ctx,
1280 AMDGPUCodeGenPassBuilder CGPB(*this, Opts, PIC);
1281 return CGPB.buildPipeline(MPM, MAM, Out, DwoOut, FileType, Ctx);
1282}
1283
1286 const GCNSubtarget &ST = C->MF->getSubtarget<GCNSubtarget>();
1287 if (ST.enableSIScheduler())
1289
1290 StringRef SchedStrategy = AMDGPU::getSchedStrategy(C->MF->getFunction());
1291
1292 if (SchedStrategy == "max-ilp")
1294
1295 if (SchedStrategy == "max-memory-clause")
1297
1298 if (SchedStrategy == "iterative-ilp")
1300
1301 if (SchedStrategy == "iterative-minreg")
1302 return createMinRegScheduler(C);
1303
1304 if (SchedStrategy == "iterative-maxocc")
1306
1307 if (SchedStrategy == "coexec") {
1308 diagnoseUnsupportedCoExecSchedulerSelection(C->MF->getFunction(), ST);
1310 }
1311
1313}
1314
1317 if (useNoopPostScheduler(C->MF->getFunction()))
1319
1320 ScheduleDAGMI *DAG =
1321 new GCNPostScheduleDAGMILive(C, std::make_unique<PostGenericScheduler>(C),
1322 /*RemoveKillFlags=*/true);
1323 const GCNSubtarget &ST = C->MF->getSubtarget<GCNSubtarget>();
1325 if (ST.shouldClusterStores())
1328 if ((EnableVOPD.getNumOccurrences() ||
1330 EnableVOPD)
1335 return DAG;
1336}
1337//===----------------------------------------------------------------------===//
1338// AMDGPU Legacy Pass Setup
1339//===----------------------------------------------------------------------===//
1340
1341std::unique_ptr<CSEConfigBase> llvm::AMDGPUPassConfig::getCSEConfig() const {
1342 return getStandardCSEConfigForOpt(TM->getOptLevel());
1343}
1344
1345namespace {
1346
1347class GCNPassConfig final : public AMDGPUPassConfig {
1348public:
1349 GCNPassConfig(TargetMachine &TM, PassManagerBase &PM)
1350 : AMDGPUPassConfig(TM, PM) {
1351 substitutePass(&PostRASchedulerID, &PostMachineSchedulerID);
1352 }
1353
1354 GCNTargetMachine &getGCNTargetMachine() const {
1355 return getTM<GCNTargetMachine>();
1356 }
1357
1358 bool addPreISel() override;
1359 void addMachineSSAOptimization() override;
1360 bool addILPOpts() override;
1361 bool addInstSelector() override;
1362 bool addIRTranslator() override;
1363 void addPreLegalizeMachineIR() override;
1364 bool addLegalizeMachineIR() override;
1365 void addPreRegBankSelect() override;
1366 bool addRegBankSelect() override;
1367 void addPreGlobalInstructionSelect() override;
1368 bool addGlobalInstructionSelect() override;
1369 void addPreRegAlloc() override;
1370 void addFastRegAlloc() override;
1371 void addOptimizedRegAlloc() override;
1372
1373 FunctionPass *createSGPRAllocPass(bool Optimized);
1374 FunctionPass *createVGPRAllocPass(bool Optimized);
1375 FunctionPass *createWWMRegAllocPass(bool Optimized);
1376 FunctionPass *createRegAllocPass(bool Optimized) override;
1377
1378 bool addRegAssignAndRewriteFast() override;
1379 bool addRegAssignAndRewriteOptimized() override;
1380
1381 bool addPreRewrite() override;
1382 void addPostRegAlloc() override;
1383 void addPreSched2() override;
1384 void addPreEmitPass() override;
1385 void addPostBBSections() override;
1386};
1387
1388} // end anonymous namespace
1389
1391 : TargetPassConfig(TM, PM) {
1392 // Exceptions and StackMaps are not supported, so these passes will never do
1393 // anything.
1396 // Garbage collection is not supported.
1399}
1400
1407
1412 // ReassociateGEPs exposes more opportunities for SLSR. See
1413 // the example in reassociate-geps-and-slsr.ll.
1415 // SeparateConstOffsetFromGEP and SLSR creates common expressions which GVN or
1416 // EarlyCSE can reuse.
1418 // Run NaryReassociate after EarlyCSE/GVN to be more effective.
1420 // NaryReassociate on GEPs creates redundant common expressions, so run
1421 // EarlyCSE after it.
1423}
1424
1427
1428 if (RemoveIncompatibleFunctions && TM.getTargetTriple().isAMDGCN())
1430
1431 // There is no reason to run these.
1435
1436 if (TM.getTargetTriple().isAMDGCN())
1438
1439 if (LowerCtorDtor)
1441
1442 if (TM.getTargetTriple().isAMDGCN() &&
1445
1448
1449 // This can be disabled by passing ::Disable here or on the command line
1450 // with --expand-variadics-override=disable.
1452
1453 // Function calls are not supported, so make sure we inline everything.
1456
1457 // Handle uses of OpenCL image2d_t, image3d_t and sampler_t arguments.
1458 if (TM.getTargetTriple().getArch() == Triple::r600)
1460
1461 // Make enqueued block runtime handles externally visible.
1463
1464 // Lower special LDS accesses.
1467
1468 // Lower LDS accesses to global memory pass if address sanitizer is enabled.
1469 if (EnableSwLowerLDS)
1471
1472 // Runs before PromoteAlloca so the latter can account for function uses
1475 }
1476
1477 // Run atomic optimizer before Atomic Expand
1478 if ((TM.getTargetTriple().isAMDGCN()) &&
1479 (TM.getOptLevel() >= CodeGenOptLevel::Less) &&
1482 }
1483
1485
1486 if (TM.getOptLevel() > CodeGenOptLevel::None) {
1488
1491
1495 AAResults &AAR) {
1496 if (auto *WrapperPass = P.getAnalysisIfAvailable<AMDGPUAAWrapperPass>())
1497 AAR.addAAResult(WrapperPass->getResult());
1498 }));
1499 }
1500
1501 if (TM.getTargetTriple().isAMDGCN()) {
1502 // TODO: May want to move later or split into an early and late one.
1504 }
1505
1506 // Try to hoist loop invariant parts of divisions AMDGPUCodeGenPrepare may
1507 // have expanded.
1508 if (TM.getOptLevel() > CodeGenOptLevel::Less)
1510 }
1511
1513
1514 // EarlyCSE is not always strong enough to clean up what LSR produces. For
1515 // example, GVN can combine
1516 //
1517 // %0 = add %a, %b
1518 // %1 = add %b, %a
1519 //
1520 // and
1521 //
1522 // %0 = shl nsw %a, 2
1523 // %1 = shl %a, 2
1524 //
1525 // but EarlyCSE can do neither of them.
1528}
1529
1531 if (TM->getTargetTriple().isAMDGCN() &&
1532 TM->getOptLevel() > CodeGenOptLevel::None)
1534
1535 if (TM->getTargetTriple().isAMDGCN() && EnableLowerKernelArguments)
1537
1539
1542
1543 if (TM->getTargetTriple().isAMDGCN()) {
1544 // This lowering has been placed after codegenprepare to take advantage of
1545 // address mode matching (which is why it isn't put with the LDS lowerings).
1546 // It could be placed anywhere before uniformity annotations (an analysis
1547 // that it changes by splitting up fat pointers into their components)
1548 // but has been put before switch lowering and CFG flattening so that those
1549 // passes can run on the more optimized control flow this pass creates in
1550 // many cases.
1553 }
1554
1555 // LowerSwitch pass may introduce unreachable blocks that can
1556 // cause unexpected behavior for subsequent passes. Placing it
1557 // here seems better that these blocks would get cleaned up by
1558 // UnreachableBlockElim inserted next in the pass flow.
1560}
1561
1563 if (TM->getOptLevel() > CodeGenOptLevel::None)
1565 return false;
1566}
1567
1572
1574 // Do nothing. GC is not supported.
1575 return false;
1576}
1577
1578//===----------------------------------------------------------------------===//
1579// GCN Legacy Pass Setup
1580//===----------------------------------------------------------------------===//
1581
1582bool GCNPassConfig::addPreISel() {
1584
1585 if (TM->getOptLevel() > CodeGenOptLevel::None) {
1586 addPass(createSinkingPass());
1588 }
1589
1590 // Merge divergent exit nodes. StructurizeCFG won't recognize the multi-exit
1591 // regions formed by them.
1593 addPass(createFixIrreduciblePass());
1594 addPass(createUnifyLoopExitsPass());
1595 addPass(createStructurizeCFGPass(false)); // true -> SkipUniformRegions
1596
1599 // TODO: Move this right after structurizeCFG to avoid extra divergence
1600 // analysis. This depends on stopping SIAnnotateControlFlow from making
1601 // control flow modifications.
1603
1604 // SDAG requires LCSSA, GlobalISel does not. Disable LCSSA for -global-isel
1605 // with -new-reg-bank-select and without any of the fallback options.
1607 !isGlobalISelAbortEnabled() || !NewRegBankSelect)
1608 addPass(createLCSSAPass());
1609
1610 if (TM->getOptLevel() > CodeGenOptLevel::Less)
1612
1613 return false;
1614}
1615
1616void GCNPassConfig::addMachineSSAOptimization() {
1618
1619 // We want to fold operands after PeepholeOptimizer has run (or as part of
1620 // it), because it will eliminate extra copies making it easier to fold the
1621 // real source operand. We want to eliminate dead instructions after, so that
1622 // we see fewer uses of the copies. We then need to clean up the dead
1623 // instructions leftover after the operands are folded as well.
1624 //
1625 // XXX - Can we get away without running DeadMachineInstructionElim again?
1626 addPass(&SIFoldOperandsLegacyID);
1627 if (EnableDPPCombine)
1628 addPass(&GCNDPPCombineLegacyID);
1630 if (isPassEnabled(EnableSDWAPeephole)) {
1631 addPass(&SIPeepholeSDWALegacyID);
1632 addPass(&EarlyMachineLICMID);
1633 addPass(&MachineCSELegacyID);
1634 addPass(&SIFoldOperandsLegacyID);
1635 }
1638}
1639
1640bool GCNPassConfig::addILPOpts() {
1642 addPass(&EarlyIfConverterLegacyID);
1643
1645 return false;
1646}
1647
1648bool GCNPassConfig::addInstSelector() {
1650 addPass(&SIFixSGPRCopiesLegacyID);
1652 return false;
1653}
1654
1655bool GCNPassConfig::addIRTranslator() {
1656 addPass(new IRTranslator(getOptLevel()));
1657 return false;
1658}
1659
1660void GCNPassConfig::addPreLegalizeMachineIR() {
1661 bool IsOptNone = getOptLevel() == CodeGenOptLevel::None;
1662 addPass(createAMDGPUPreLegalizeCombiner(IsOptNone));
1663 addPass(new Localizer());
1664}
1665
1666bool GCNPassConfig::addLegalizeMachineIR() {
1667 addPass(new Legalizer());
1668 return false;
1669}
1670
1671void GCNPassConfig::addPreRegBankSelect() {
1672 bool IsOptNone = getOptLevel() == CodeGenOptLevel::None;
1673 addPass(createAMDGPUPostLegalizeCombiner(IsOptNone));
1675}
1676
1677bool GCNPassConfig::addRegBankSelect() {
1678 if (NewRegBankSelect) {
1681 } else {
1682 addPass(new RegBankSelect());
1683 }
1684 return false;
1685}
1686
1687void GCNPassConfig::addPreGlobalInstructionSelect() {
1688 bool IsOptNone = getOptLevel() == CodeGenOptLevel::None;
1689 addPass(createAMDGPURegBankCombiner(IsOptNone));
1690}
1691
1692bool GCNPassConfig::addGlobalInstructionSelect() {
1693 addPass(new InstructionSelect(getOptLevel()));
1694 return false;
1695}
1696
1697void GCNPassConfig::addFastRegAlloc() {
1698 // FIXME: We have to disable the verifier here because of PHIElimination +
1699 // TwoAddressInstructions disabling it.
1700
1701 // This must be run immediately after phi elimination and before
1702 // TwoAddressInstructions, otherwise the processing of the tied operand of
1703 // SI_ELSE will introduce a copy of the tied operand source after the else.
1705
1707
1709}
1710
1711void GCNPassConfig::addPreRegAlloc() {
1712 if (getOptLevel() != CodeGenOptLevel::None)
1714}
1715
1716void GCNPassConfig::addOptimizedRegAlloc() {
1717 if (EnableDCEInRA)
1719
1720 // FIXME: when an instruction has a Killed operand, and the instruction is
1721 // inside a bundle, seems only the BUNDLE instruction appears as the Kills of
1722 // the register in LiveVariables, this would trigger a failure in verifier,
1723 // we should fix it and enable the verifier.
1724 if (OptVGPRLiveRange)
1726
1727 // This must be run immediately after phi elimination and before
1728 // TwoAddressInstructions, otherwise the processing of the tied operand of
1729 // SI_ELSE will introduce a copy of the tied operand source after the else.
1731
1734
1735 if (isPassEnabled(EnablePreRAOptimizations))
1737
1738 // Allow the scheduler to run before SIWholeQuadMode inserts exec manipulation
1739 // instructions that cause scheduling barriers.
1741
1742 if (OptExecMaskPreRA)
1744
1745 // This is not an essential optimization and it has a noticeable impact on
1746 // compilation time, so we only enable it from O2.
1747 if (TM->getOptLevel() > CodeGenOptLevel::Less)
1749
1751}
1752
1753bool GCNPassConfig::addPreRewrite() {
1755 addPass(&GCNNSAReassignID);
1756
1758 return true;
1759}
1760
1761FunctionPass *GCNPassConfig::createSGPRAllocPass(bool Optimized) {
1762 // Initialize the global default.
1763 llvm::call_once(InitializeDefaultSGPRRegisterAllocatorFlag,
1764 initializeDefaultSGPRRegisterAllocatorOnce);
1765
1766 RegisterRegAlloc::FunctionPassCtor Ctor = SGPRRegisterRegAlloc::getDefault();
1767 if (Ctor != useDefaultRegisterAllocator)
1768 return Ctor();
1769
1770 if (Optimized)
1771 return createGreedyRegisterAllocator(onlyAllocateSGPRs);
1772
1773 return createFastRegisterAllocator(onlyAllocateSGPRs, false);
1774}
1775
1776FunctionPass *GCNPassConfig::createVGPRAllocPass(bool Optimized) {
1777 // Initialize the global default.
1778 llvm::call_once(InitializeDefaultVGPRRegisterAllocatorFlag,
1779 initializeDefaultVGPRRegisterAllocatorOnce);
1780
1781 RegisterRegAlloc::FunctionPassCtor Ctor = VGPRRegisterRegAlloc::getDefault();
1782 if (Ctor != useDefaultRegisterAllocator)
1783 return Ctor();
1784
1785 if (Optimized)
1786 return createGreedyVGPRRegisterAllocator();
1787
1788 return createFastVGPRRegisterAllocator();
1789}
1790
1791FunctionPass *GCNPassConfig::createWWMRegAllocPass(bool Optimized) {
1792 // Initialize the global default.
1793 llvm::call_once(InitializeDefaultWWMRegisterAllocatorFlag,
1794 initializeDefaultWWMRegisterAllocatorOnce);
1795
1796 RegisterRegAlloc::FunctionPassCtor Ctor = WWMRegisterRegAlloc::getDefault();
1797 if (Ctor != useDefaultRegisterAllocator)
1798 return Ctor();
1799
1800 if (Optimized)
1801 return createGreedyWWMRegisterAllocator();
1802
1803 return createFastWWMRegisterAllocator();
1804}
1805
1806FunctionPass *GCNPassConfig::createRegAllocPass(bool Optimized) {
1807 llvm_unreachable("should not be used");
1808}
1809
1811 "-regalloc not supported with amdgcn. Use -sgpr-regalloc, -wwm-regalloc, "
1812 "and -vgpr-regalloc";
1813
1814bool GCNPassConfig::addRegAssignAndRewriteFast() {
1815 if (!usingDefaultRegAlloc())
1817
1818 addPass(&GCNPreRALongBranchRegID);
1819
1820 addPass(createSGPRAllocPass(false));
1821
1822 // Equivalent of PEI for SGPRs.
1823 addPass(&SILowerSGPRSpillsLegacyID);
1824
1825 // To Allocate wwm registers used in whole quad mode operations (for shaders).
1827
1828 // For allocating other wwm register operands.
1829 addPass(createWWMRegAllocPass(false));
1830
1831 addPass(&SILowerWWMCopiesLegacyID);
1833
1834 // For allocating per-thread VGPRs.
1835 addPass(createVGPRAllocPass(false));
1836
1837 return true;
1838}
1839
1840bool GCNPassConfig::addRegAssignAndRewriteOptimized() {
1841 if (!usingDefaultRegAlloc())
1843
1844 addPass(&GCNPreRALongBranchRegID);
1845
1846 addPass(createSGPRAllocPass(true));
1847
1848 // Commit allocated register changes. This is mostly necessary because too
1849 // many things rely on the use lists of the physical registers, such as the
1850 // verifier. This is only necessary with allocators which use LiveIntervals,
1851 // since FastRegAlloc does the replacements itself.
1852 addPass(createVirtRegRewriter(false));
1853
1854 // At this point, the sgpr-regalloc has been done and it is good to have the
1855 // stack slot coloring to try to optimize the SGPR spill stack indices before
1856 // attempting the custom SGPR spill lowering.
1857 addPass(&StackSlotColoringID);
1858
1859 // Equivalent of PEI for SGPRs.
1860 addPass(&SILowerSGPRSpillsLegacyID);
1861
1862 // To Allocate wwm registers used in whole quad mode operations (for shaders).
1864
1865 // For allocating other whole wave mode registers.
1866 addPass(createWWMRegAllocPass(true));
1867 addPass(&SILowerWWMCopiesLegacyID);
1868 addPass(createVirtRegRewriter(false));
1870
1871 // For allocating per-thread VGPRs.
1872 addPass(createVGPRAllocPass(true));
1873
1874 addPreRewrite();
1875 addPass(&VirtRegRewriterID);
1876
1878
1879 return true;
1880}
1881
1882void GCNPassConfig::addPostRegAlloc() {
1883 addPass(&SIFixVGPRCopiesID);
1884 if (getOptLevel() > CodeGenOptLevel::None)
1887}
1888
1889void GCNPassConfig::addPreSched2() {
1890 if (TM->getOptLevel() > CodeGenOptLevel::None)
1892 addPass(&SIPostRABundlerLegacyID);
1893}
1894
1895void GCNPassConfig::addPreEmitPass() {
1896 if (isPassEnabled(EnableVOPD, CodeGenOptLevel::Less))
1897 addPass(&GCNCreateVOPDID);
1898 addPass(createSIMemoryLegalizerPass());
1899 addPass(createSIInsertWaitcntsPass());
1900
1901 addPass(createSIModeRegisterPass());
1902
1903 if (getOptLevel() > CodeGenOptLevel::None)
1904 addPass(&SIInsertHardClausesID);
1905
1907 if (isPassEnabled(EnableSetWavePriority, CodeGenOptLevel::Less))
1909 if (getOptLevel() > CodeGenOptLevel::None)
1910 addPass(&SIPreEmitPeepholeID);
1911 // The hazard recognizer that runs as part of the post-ra scheduler does not
1912 // guarantee to be able handle all hazards correctly. This is because if there
1913 // are multiple scheduling regions in a basic block, the regions are scheduled
1914 // bottom up, so when we begin to schedule a region we don't know what
1915 // instructions were emitted directly before it.
1916 //
1917 // Here we add a stand-alone hazard recognizer pass which can handle all
1918 // cases.
1919 addPass(&PostRAHazardRecognizerID);
1920
1922
1924
1925 if (isPassEnabled(EnableInsertDelayAlu, CodeGenOptLevel::Less))
1926 addPass(&AMDGPUInsertDelayAluID);
1927
1928 addPass(&BranchRelaxationPassID);
1929}
1930
1931void GCNPassConfig::addPostBBSections() {
1932 // We run this later to avoid passes like livedebugvalues and BBSections
1933 // having to deal with the apparent multi-entry functions we may generate.
1935}
1936
1938 return new GCNPassConfig(*this, PM);
1939}
1940
1946
1953
1957
1964
1967 SMDiagnostic &Error, SMRange &SourceRange) const {
1968 const yaml::SIMachineFunctionInfo &YamlMFI =
1969 static_cast<const yaml::SIMachineFunctionInfo &>(MFI_);
1970 MachineFunction &MF = PFS.MF;
1972 const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>();
1973
1974 if (MFI->initializeBaseYamlFields(YamlMFI, MF, PFS, Error, SourceRange))
1975 return true;
1976
1977 if (MFI->Occupancy == 0) {
1978 // Fixup the subtarget dependent default value.
1979 MFI->Occupancy = ST.getOccupancyWithWorkGroupSizes(MF).second;
1980 }
1981
1982 auto parseRegister = [&](const yaml::StringValue &RegName, Register &RegVal) {
1983 Register TempReg;
1984 if (parseNamedRegisterReference(PFS, TempReg, RegName.Value, Error)) {
1985 SourceRange = RegName.SourceRange;
1986 return true;
1987 }
1988 RegVal = TempReg;
1989
1990 return false;
1991 };
1992
1993 auto parseOptionalRegister = [&](const yaml::StringValue &RegName,
1994 Register &RegVal) {
1995 return !RegName.Value.empty() && parseRegister(RegName, RegVal);
1996 };
1997
1998 if (parseOptionalRegister(YamlMFI.VGPRForAGPRCopy, MFI->VGPRForAGPRCopy))
1999 return true;
2000
2001 if (parseOptionalRegister(YamlMFI.SGPRForEXECCopy, MFI->SGPRForEXECCopy))
2002 return true;
2003
2004 if (parseOptionalRegister(YamlMFI.LongBranchReservedReg,
2005 MFI->LongBranchReservedReg))
2006 return true;
2007
2008 auto diagnoseRegisterClass = [&](const yaml::StringValue &RegName) {
2009 // Create a diagnostic for a the register string literal.
2010 const MemoryBuffer &Buffer =
2011 *PFS.SM->getMemoryBuffer(PFS.SM->getMainFileID());
2012 Error = SMDiagnostic(*PFS.SM, SMLoc(), Buffer.getBufferIdentifier(), 1,
2013 RegName.Value.size(), SourceMgr::DK_Error,
2014 "incorrect register class for field", RegName.Value,
2015 {}, {});
2016 SourceRange = RegName.SourceRange;
2017 return true;
2018 };
2019
2020 if (parseRegister(YamlMFI.ScratchRSrcReg, MFI->ScratchRSrcReg) ||
2021 parseRegister(YamlMFI.FrameOffsetReg, MFI->FrameOffsetReg) ||
2022 parseRegister(YamlMFI.StackPtrOffsetReg, MFI->StackPtrOffsetReg))
2023 return true;
2024
2025 if (MFI->ScratchRSrcReg != AMDGPU::PRIVATE_RSRC_REG &&
2026 !AMDGPU::SGPR_128RegClass.contains(MFI->ScratchRSrcReg)) {
2027 return diagnoseRegisterClass(YamlMFI.ScratchRSrcReg);
2028 }
2029
2030 if (MFI->FrameOffsetReg != AMDGPU::FP_REG &&
2031 !AMDGPU::SGPR_32RegClass.contains(MFI->FrameOffsetReg)) {
2032 return diagnoseRegisterClass(YamlMFI.FrameOffsetReg);
2033 }
2034
2035 if (MFI->StackPtrOffsetReg != AMDGPU::SP_REG &&
2036 !AMDGPU::SGPR_32RegClass.contains(MFI->StackPtrOffsetReg)) {
2037 return diagnoseRegisterClass(YamlMFI.StackPtrOffsetReg);
2038 }
2039
2040 for (const auto &YamlReg : YamlMFI.WWMReservedRegs) {
2041 Register ParsedReg;
2042 if (parseRegister(YamlReg, ParsedReg))
2043 return true;
2044
2045 MFI->reserveWWMRegister(ParsedReg);
2046 }
2047
2048 for (const auto &[_, Info] : PFS.VRegInfosNamed) {
2049 MFI->setFlag(Info->VReg, Info->Flags);
2050 }
2051 for (const auto &[_, Info] : PFS.VRegInfos) {
2052 MFI->setFlag(Info->VReg, Info->Flags);
2053 }
2054
2055 for (const auto &YamlRegStr : YamlMFI.SpillPhysVGPRS) {
2056 Register ParsedReg;
2057 if (parseRegister(YamlRegStr, ParsedReg))
2058 return true;
2059 MFI->SpillPhysVGPRs.push_back(ParsedReg);
2060 }
2061
2062 auto parseAndCheckArgument = [&](const std::optional<yaml::SIArgument> &A,
2063 const TargetRegisterClass &RC,
2064 ArgDescriptor &Arg, unsigned UserSGPRs,
2065 unsigned SystemSGPRs) {
2066 // Skip parsing if it's not present.
2067 if (!A)
2068 return false;
2069
2070 if (A->IsRegister) {
2071 Register Reg;
2072 if (parseNamedRegisterReference(PFS, Reg, A->RegisterName.Value, Error)) {
2073 SourceRange = A->RegisterName.SourceRange;
2074 return true;
2075 }
2076 if (!RC.contains(Reg))
2077 return diagnoseRegisterClass(A->RegisterName);
2079 } else
2080 Arg = ArgDescriptor::createStack(A->StackOffset);
2081 // Check and apply the optional mask.
2082 if (A->Mask)
2083 Arg = ArgDescriptor::createArg(Arg, *A->Mask);
2084
2085 MFI->NumUserSGPRs += UserSGPRs;
2086 MFI->NumSystemSGPRs += SystemSGPRs;
2087 return false;
2088 };
2089
2090 if (YamlMFI.ArgInfo &&
2091 (parseAndCheckArgument(YamlMFI.ArgInfo->PrivateSegmentBuffer,
2092 AMDGPU::SGPR_128RegClass,
2093 MFI->ArgInfo.PrivateSegmentBuffer, 4, 0) ||
2094 parseAndCheckArgument(YamlMFI.ArgInfo->DispatchPtr,
2095 AMDGPU::SReg_64RegClass, MFI->ArgInfo.DispatchPtr,
2096 2, 0) ||
2097 parseAndCheckArgument(YamlMFI.ArgInfo->QueuePtr, AMDGPU::SReg_64RegClass,
2098 MFI->ArgInfo.QueuePtr, 2, 0) ||
2099 parseAndCheckArgument(YamlMFI.ArgInfo->KernargSegmentPtr,
2100 AMDGPU::SReg_64RegClass,
2101 MFI->ArgInfo.KernargSegmentPtr, 2, 0) ||
2102 parseAndCheckArgument(YamlMFI.ArgInfo->DispatchID,
2103 AMDGPU::SReg_64RegClass, MFI->ArgInfo.DispatchID,
2104 2, 0) ||
2105 parseAndCheckArgument(YamlMFI.ArgInfo->FlatScratchInit,
2106 AMDGPU::SReg_64RegClass,
2107 MFI->ArgInfo.FlatScratchInit, 2, 0) ||
2108 parseAndCheckArgument(YamlMFI.ArgInfo->PrivateSegmentSize,
2109 AMDGPU::SGPR_32RegClass,
2110 MFI->ArgInfo.PrivateSegmentSize, 0, 0) ||
2111 parseAndCheckArgument(YamlMFI.ArgInfo->LDSKernelId,
2112 AMDGPU::SGPR_32RegClass,
2113 MFI->ArgInfo.LDSKernelId, 0, 1) ||
2114 parseAndCheckArgument(YamlMFI.ArgInfo->WorkGroupIDX,
2115 AMDGPU::SGPR_32RegClass, MFI->ArgInfo.WorkGroupIDX,
2116 0, 1) ||
2117 parseAndCheckArgument(YamlMFI.ArgInfo->WorkGroupIDY,
2118 AMDGPU::SGPR_32RegClass, MFI->ArgInfo.WorkGroupIDY,
2119 0, 1) ||
2120 parseAndCheckArgument(YamlMFI.ArgInfo->WorkGroupIDZ,
2121 AMDGPU::SGPR_32RegClass, MFI->ArgInfo.WorkGroupIDZ,
2122 0, 1) ||
2123 parseAndCheckArgument(YamlMFI.ArgInfo->WorkGroupInfo,
2124 AMDGPU::SGPR_32RegClass,
2125 MFI->ArgInfo.WorkGroupInfo, 0, 1) ||
2126 parseAndCheckArgument(YamlMFI.ArgInfo->PrivateSegmentWaveByteOffset,
2127 AMDGPU::SGPR_32RegClass,
2128 MFI->ArgInfo.PrivateSegmentWaveByteOffset, 0, 1) ||
2129 parseAndCheckArgument(YamlMFI.ArgInfo->ImplicitArgPtr,
2130 AMDGPU::SReg_64RegClass,
2131 MFI->ArgInfo.ImplicitArgPtr, 0, 0) ||
2132 parseAndCheckArgument(YamlMFI.ArgInfo->ImplicitBufferPtr,
2133 AMDGPU::SReg_64RegClass,
2134 MFI->ArgInfo.ImplicitBufferPtr, 2, 0) ||
2135 parseAndCheckArgument(YamlMFI.ArgInfo->WorkItemIDX,
2136 AMDGPU::VGPR_32RegClass,
2137 MFI->ArgInfo.WorkItemIDX, 0, 0) ||
2138 parseAndCheckArgument(YamlMFI.ArgInfo->WorkItemIDY,
2139 AMDGPU::VGPR_32RegClass,
2140 MFI->ArgInfo.WorkItemIDY, 0, 0) ||
2141 parseAndCheckArgument(YamlMFI.ArgInfo->WorkItemIDZ,
2142 AMDGPU::VGPR_32RegClass,
2143 MFI->ArgInfo.WorkItemIDZ, 0, 0)))
2144 return true;
2145
2146 // Parse FirstKernArgPreloadReg separately, since it's a Register,
2147 // not ArgDescriptor.
2148 if (YamlMFI.ArgInfo && YamlMFI.ArgInfo->FirstKernArgPreloadReg) {
2149 const yaml::SIArgument &A = *YamlMFI.ArgInfo->FirstKernArgPreloadReg;
2150
2151 if (!A.IsRegister) {
2152 // For stack arguments, we don't have RegisterName.SourceRange,
2153 // but we should have some location info from the YAML parser
2154 const MemoryBuffer &Buffer =
2155 *PFS.SM->getMemoryBuffer(PFS.SM->getMainFileID());
2156 // Create a minimal valid source range
2158 SMRange Range(Loc, Loc);
2159
2161 *PFS.SM, Loc, Buffer.getBufferIdentifier(), 1, 0, SourceMgr::DK_Error,
2162 "firstKernArgPreloadReg must be a register, not a stack location", "",
2163 {}, {});
2164
2165 SourceRange = Range;
2166 return true;
2167 }
2168
2169 Register Reg;
2170 if (parseNamedRegisterReference(PFS, Reg, A.RegisterName.Value, Error)) {
2171 SourceRange = A.RegisterName.SourceRange;
2172 return true;
2173 }
2174
2175 if (!AMDGPU::SGPR_32RegClass.contains(Reg))
2176 return diagnoseRegisterClass(A.RegisterName);
2177
2178 MFI->ArgInfo.FirstKernArgPreloadReg = Reg;
2179 MFI->NumUserSGPRs += YamlMFI.NumKernargPreloadSGPRs;
2180 }
2181
2182 if (ST.hasFeature(AMDGPU::FeatureDX10ClampAndIEEEMode)) {
2183 MFI->Mode.IEEE = YamlMFI.Mode.IEEE;
2184 MFI->Mode.DX10Clamp = YamlMFI.Mode.DX10Clamp;
2185 }
2186
2187 // FIXME: Move proper support for denormal-fp-math into base MachineFunction
2188 MFI->Mode.FP32Denormals.Input = YamlMFI.Mode.FP32InputDenormals
2191 MFI->Mode.FP32Denormals.Output = YamlMFI.Mode.FP32OutputDenormals
2194
2201
2202 if (YamlMFI.HasInitWholeWave)
2203 MFI->setInitWholeWave();
2204
2205 return false;
2206}
2207
2208//===----------------------------------------------------------------------===//
2209// AMDGPU CodeGen Pass Builder interface.
2210//===----------------------------------------------------------------------===//
2211
2212AMDGPUCodeGenPassBuilder::AMDGPUCodeGenPassBuilder(
2213 GCNTargetMachine &TM, const CGPassBuilderOption &Opts,
2215 : CodeGenPassBuilder(TM, Opts, PIC) {
2216 Opt.MISchedPostRA = true;
2217 Opt.RequiresCodeGenSCCOrder = true;
2218 // Exceptions and StackMaps are not supported, so these passes will never do
2219 // anything.
2220 // Garbage collection is not supported.
2221 disablePass<StackMapLivenessPass, FuncletLayoutPass, PatchableFunctionPass,
2223}
2224
2225void AMDGPUCodeGenPassBuilder::addIRPasses(PassManagerWrapper &PMW) const {
2226 if (RemoveIncompatibleFunctions && TM.getTargetTriple().isAMDGCN()) {
2227 flushFPMsToMPM(PMW);
2228 addModulePass(AMDGPURemoveIncompatibleFunctionsPass(TM), PMW);
2229 }
2230
2231 flushFPMsToMPM(PMW);
2232
2233 if (TM.getTargetTriple().isAMDGCN())
2234 addModulePass(AMDGPUPrintfRuntimeBindingPass(), PMW);
2235
2236 if (LowerCtorDtor)
2237 addModulePass(AMDGPUCtorDtorLoweringPass(), PMW);
2238
2239 if (isPassEnabled(EnableImageIntrinsicOptimizer))
2240 addFunctionPass(AMDGPUImageIntrinsicOptimizerPass(TM), PMW);
2241
2243 addFunctionPass(AMDGPUUniformIntrinsicCombinePass(), PMW);
2244 // This can be disabled by passing ::Disable here or on the command line
2245 // with --expand-variadics-override=disable.
2246 flushFPMsToMPM(PMW);
2248
2249 addModulePass(AMDGPUAlwaysInlinePass(), PMW);
2250 addModulePass(AlwaysInlinerPass(), PMW);
2251
2252 addModulePass(AMDGPUExportKernelRuntimeHandlesPass(), PMW);
2253
2255 addModulePass(AMDGPULowerExecSyncPass(), PMW);
2256
2257 if (EnableSwLowerLDS)
2258 addModulePass(AMDGPUSwLowerLDSPass(TM), PMW);
2259
2260 // Runs before PromoteAlloca so the latter can account for function uses
2262 addModulePass(AMDGPULowerModuleLDSPass(TM), PMW);
2263
2264 // Run atomic optimizer before Atomic Expand
2265 if (TM.getOptLevel() >= CodeGenOptLevel::Less &&
2267 addFunctionPass(
2269
2270 addFunctionPass(AtomicExpandPass(TM), PMW);
2271
2272 if (TM.getOptLevel() > CodeGenOptLevel::None) {
2273 addFunctionPass(AMDGPUPromoteAllocaPass(TM), PMW);
2274 if (isPassEnabled(EnableScalarIRPasses))
2275 addStraightLineScalarOptimizationPasses(PMW);
2276
2277 // TODO: Handle EnableAMDGPUAliasAnalysis
2278
2279 // TODO: May want to move later or split into an early and late one.
2280 addFunctionPass(AMDGPUCodeGenPreparePass(TM), PMW);
2281
2282 // Try to hoist loop invariant parts of divisions AMDGPUCodeGenPrepare may
2283 // have expanded.
2284 if (TM.getOptLevel() > CodeGenOptLevel::Less) {
2286 /*UseMemorySSA=*/true),
2287 PMW);
2288 }
2289 }
2290
2291 Base::addIRPasses(PMW);
2292
2293 // EarlyCSE is not always strong enough to clean up what LSR produces. For
2294 // example, GVN can combine
2295 //
2296 // %0 = add %a, %b
2297 // %1 = add %b, %a
2298 //
2299 // and
2300 //
2301 // %0 = shl nsw %a, 2
2302 // %1 = shl %a, 2
2303 //
2304 // but EarlyCSE can do neither of them.
2305 if (isPassEnabled(EnableScalarIRPasses))
2306 addEarlyCSEOrGVNPass(PMW);
2307}
2308
2309void AMDGPUCodeGenPassBuilder::addCodeGenPrepare(
2310 PassManagerWrapper &PMW) const {
2311 if (TM.getOptLevel() > CodeGenOptLevel::None) {
2312 flushFPMsToMPM(PMW);
2313 addModulePass(AMDGPUPreloadKernelArgumentsPass(TM), PMW);
2314 }
2315
2317 addFunctionPass(AMDGPULowerKernelArgumentsPass(TM), PMW);
2318
2319 Base::addCodeGenPrepare(PMW);
2320
2321 if (isPassEnabled(EnableLoadStoreVectorizer))
2322 addFunctionPass(LoadStoreVectorizerPass(), PMW);
2323
2324 // This lowering has been placed after codegenprepare to take advantage of
2325 // address mode matching (which is why it isn't put with the LDS lowerings).
2326 // It could be placed anywhere before uniformity annotations (an analysis
2327 // that it changes by splitting up fat pointers into their components)
2328 // but has been put before switch lowering and CFG flattening so that those
2329 // passes can run on the more optimized control flow this pass creates in
2330 // many cases.
2331 flushFPMsToMPM(PMW);
2332 addModulePass(AMDGPULowerBufferFatPointersPass(TM), PMW);
2333 flushFPMsToMPM(PMW);
2334 requireCGSCCOrder(PMW);
2335
2336 addModulePass(AMDGPULowerIntrinsicsPass(TM), PMW);
2337
2338 // LowerSwitch pass may introduce unreachable blocks that can cause unexpected
2339 // behavior for subsequent passes. Placing it here seems better that these
2340 // blocks would get cleaned up by UnreachableBlockElim inserted next in the
2341 // pass flow.
2342 addFunctionPass(LowerSwitchPass(), PMW);
2343}
2344
2345void AMDGPUCodeGenPassBuilder::addPreISel(PassManagerWrapper &PMW) const {
2346
2347 if (TM.getOptLevel() > CodeGenOptLevel::None) {
2348 addFunctionPass(FlattenCFGPass(), PMW);
2349 addFunctionPass(SinkingPass(), PMW);
2350 addFunctionPass(AMDGPULateCodeGenPreparePass(TM), PMW);
2351 }
2352
2353 // Merge divergent exit nodes. StructurizeCFG won't recognize the multi-exit
2354 // regions formed by them.
2355
2356 addFunctionPass(AMDGPUUnifyDivergentExitNodesPass(), PMW);
2357 addFunctionPass(FixIrreduciblePass(), PMW);
2358 addFunctionPass(UnifyLoopExitsPass(), PMW);
2359 addFunctionPass(StructurizeCFGPass(/*SkipUniformRegions=*/false), PMW);
2360
2361 addFunctionPass(AMDGPUAnnotateUniformValuesPass(), PMW);
2362
2363 addFunctionPass(SIAnnotateControlFlowPass(TM), PMW);
2364
2365 // TODO: Move this right after structurizeCFG to avoid extra divergence
2366 // analysis. This depends on stopping SIAnnotateControlFlow from making
2367 // control flow modifications.
2368 addFunctionPass(AMDGPURewriteUndefForPHIPass(), PMW);
2369
2371 !isGlobalISelAbortEnabled() || !NewRegBankSelect)
2372 addFunctionPass(LCSSAPass(), PMW);
2373
2374 if (TM.getOptLevel() > CodeGenOptLevel::Less) {
2375 flushFPMsToMPM(PMW);
2376 addModulePass(AMDGPUPerfHintAnalysisPass(TM), PMW);
2377 }
2378
2379 // FIXME: Why isn't this queried as required from AMDGPUISelDAGToDAG, and why
2380 // isn't this in addInstSelector?
2382 /*Force=*/true);
2383}
2384
2385void AMDGPUCodeGenPassBuilder::addILPOpts(PassManagerWrapper &PMW) const {
2387 addMachineFunctionPass(EarlyIfConverterPass(), PMW);
2388
2389 Base::addILPOpts(PMW);
2390}
2391
2392void AMDGPUCodeGenPassBuilder::addAsmPrinterBegin(
2393 PassManagerWrapper &PMW) const {
2394 // TODO: Add AsmPrinterBegin
2395}
2396
2397void AMDGPUCodeGenPassBuilder::addAsmPrinter(PassManagerWrapper &PMW) const {
2398 // TODO: Add AsmPrinter.
2399}
2400
2401void AMDGPUCodeGenPassBuilder::addAsmPrinterEnd(PassManagerWrapper &PMW) const {
2402 // TODO: Add AsmPrinterEnd
2403}
2404
2405Error AMDGPUCodeGenPassBuilder::addInstSelector(PassManagerWrapper &PMW) const {
2406 addMachineFunctionPass(AMDGPUISelDAGToDAGPass(TM), PMW);
2407 addMachineFunctionPass(SIFixSGPRCopiesPass(), PMW);
2408 addMachineFunctionPass(SILowerI1CopiesPass(), PMW);
2409 return Error::success();
2410}
2411
2412void AMDGPUCodeGenPassBuilder::addPreRewrite(PassManagerWrapper &PMW) const {
2413 if (EnableRegReassign) {
2414 addMachineFunctionPass(GCNNSAReassignPass(), PMW);
2415 }
2416
2417 addMachineFunctionPass(AMDGPURewriteAGPRCopyMFMAPass(), PMW);
2418}
2419
2420void AMDGPUCodeGenPassBuilder::addMachineSSAOptimization(
2421 PassManagerWrapper &PMW) const {
2422 Base::addMachineSSAOptimization(PMW);
2423
2424 addMachineFunctionPass(SIFoldOperandsPass(), PMW);
2425 if (EnableDPPCombine) {
2426 addMachineFunctionPass(GCNDPPCombinePass(), PMW);
2427 }
2428 addMachineFunctionPass(SILoadStoreOptimizerPass(), PMW);
2429 if (isPassEnabled(EnableSDWAPeephole)) {
2430 addMachineFunctionPass(SIPeepholeSDWAPass(), PMW);
2431 addMachineFunctionPass(EarlyMachineLICMPass(), PMW);
2432 addMachineFunctionPass(MachineCSEPass(), PMW);
2433 addMachineFunctionPass(SIFoldOperandsPass(), PMW);
2434 }
2435 addMachineFunctionPass(DeadMachineInstructionElimPass(), PMW);
2436 addMachineFunctionPass(SIShrinkInstructionsPass(), PMW);
2437}
2438
2439Error AMDGPUCodeGenPassBuilder::addFastRegAlloc(PassManagerWrapper &PMW) const {
2440 insertPass<PHIEliminationPass>(SILowerControlFlowPass());
2441
2442 insertPass<TwoAddressInstructionPass>(SIWholeQuadModePass());
2443
2444 return Base::addFastRegAlloc(PMW);
2445}
2446
2447Error AMDGPUCodeGenPassBuilder::addRegAssignmentFast(
2448 PassManagerWrapper &PMW) const {
2449 if (auto Err = validateRegAllocOptions())
2450 return Err;
2451
2452 addMachineFunctionPass(GCNPreRALongBranchRegPass(), PMW);
2453
2454 // SGPR allocation - default to fast at -O0.
2455 if (SGPRRegAllocNPM == RegAllocType::Greedy)
2456 addMachineFunctionPass(RAGreedyPass({onlyAllocateSGPRs, "sgpr"}), PMW);
2457 else
2458 addMachineFunctionPass(RegAllocFastPass({onlyAllocateSGPRs, "sgpr", false}),
2459 PMW);
2460
2461 // Equivalent of PEI for SGPRs.
2462 addMachineFunctionPass(SILowerSGPRSpillsPass(), PMW);
2463
2464 // To Allocate wwm registers used in whole quad mode operations (for shaders).
2465 addMachineFunctionPass(SIPreAllocateWWMRegsPass(), PMW);
2466
2467 // WWM allocation - default to fast at -O0.
2468 if (WWMRegAllocNPM == RegAllocType::Greedy)
2469 addMachineFunctionPass(RAGreedyPass({onlyAllocateWWMRegs, "wwm"}), PMW);
2470 else
2471 addMachineFunctionPass(
2472 RegAllocFastPass({onlyAllocateWWMRegs, "wwm", false}), PMW);
2473
2474 addMachineFunctionPass(SILowerWWMCopiesPass(), PMW);
2475 addMachineFunctionPass(AMDGPUReserveWWMRegsPass(), PMW);
2476
2477 // VGPR allocation - default to fast at -O0.
2478 if (VGPRRegAllocNPM == RegAllocType::Greedy)
2479 addMachineFunctionPass(RAGreedyPass({onlyAllocateVGPRs, "vgpr"}), PMW);
2480 else
2481 addMachineFunctionPass(RegAllocFastPass({onlyAllocateVGPRs, "vgpr"}), PMW);
2482
2483 return Error::success();
2484}
2485
2486Error AMDGPUCodeGenPassBuilder::addOptimizedRegAlloc(
2487 PassManagerWrapper &PMW) const {
2488 if (EnableDCEInRA)
2489 insertPass<DetectDeadLanesPass>(DeadMachineInstructionElimPass());
2490
2491 // FIXME: when an instruction has a Killed operand, and the instruction is
2492 // inside a bundle, seems only the BUNDLE instruction appears as the Kills of
2493 // the register in LiveVariables, this would trigger a failure in verifier,
2494 // we should fix it and enable the verifier.
2495 if (OptVGPRLiveRange)
2496 insertPass<RequireAnalysisPass<LiveVariablesAnalysis, MachineFunction>>(
2498
2499 // This must be run immediately after phi elimination and before
2500 // TwoAddressInstructions, otherwise the processing of the tied operand of
2501 // SI_ELSE will introduce a copy of the tied operand source after the else.
2502 insertPass<PHIEliminationPass>(SILowerControlFlowPass());
2503
2505 insertPass<RenameIndependentSubregsPass>(GCNRewritePartialRegUsesPass());
2506
2507 if (isPassEnabled(EnablePreRAOptimizations))
2508 insertPass<MachineSchedulerPass>(GCNPreRAOptimizationsPass());
2509
2510 // Allow the scheduler to run before SIWholeQuadMode inserts exec manipulation
2511 // instructions that cause scheduling barriers.
2512 insertPass<MachineSchedulerPass>(SIWholeQuadModePass());
2513
2514 if (OptExecMaskPreRA)
2515 insertPass<MachineSchedulerPass>(SIOptimizeExecMaskingPreRAPass());
2516
2517 // This is not an essential optimization and it has a noticeable impact on
2518 // compilation time, so we only enable it from O2.
2519 if (TM.getOptLevel() > CodeGenOptLevel::Less)
2520 insertPass<MachineSchedulerPass>(SIFormMemoryClausesPass());
2521
2522 return Base::addOptimizedRegAlloc(PMW);
2523}
2524
2525void AMDGPUCodeGenPassBuilder::addPreRegAlloc(PassManagerWrapper &PMW) const {
2526 if (getOptLevel() != CodeGenOptLevel::None)
2527 addMachineFunctionPass(AMDGPUPrepareAGPRAllocPass(), PMW);
2528}
2529
2530Error AMDGPUCodeGenPassBuilder::addRegAssignmentOptimized(
2531 PassManagerWrapper &PMW) const {
2532 if (auto Err = validateRegAllocOptions())
2533 return Err;
2534
2535 addMachineFunctionPass(GCNPreRALongBranchRegPass(), PMW);
2536
2537 // SGPR allocation - default to greedy at -O1 and above.
2538 if (SGPRRegAllocNPM == RegAllocType::Fast)
2539 addMachineFunctionPass(RegAllocFastPass({onlyAllocateSGPRs, "sgpr", false}),
2540 PMW);
2541 else
2542 addMachineFunctionPass(RAGreedyPass({onlyAllocateSGPRs, "sgpr"}), PMW);
2543
2544 // Commit allocated register changes. This is mostly necessary because too
2545 // many things rely on the use lists of the physical registers, such as the
2546 // verifier. This is only necessary with allocators which use LiveIntervals,
2547 // since FastRegAlloc does the replacements itself.
2548 addMachineFunctionPass(VirtRegRewriterPass(false), PMW);
2549
2550 // At this point, the sgpr-regalloc has been done and it is good to have the
2551 // stack slot coloring to try to optimize the SGPR spill stack indices before
2552 // attempting the custom SGPR spill lowering.
2553 addMachineFunctionPass(StackSlotColoringPass(), PMW);
2554
2555 // Equivalent of PEI for SGPRs.
2556 addMachineFunctionPass(SILowerSGPRSpillsPass(), PMW);
2557
2558 // To Allocate wwm registers used in whole quad mode operations (for shaders).
2559 addMachineFunctionPass(SIPreAllocateWWMRegsPass(), PMW);
2560
2561 // WWM allocation - default to greedy at -O1 and above.
2562 if (WWMRegAllocNPM == RegAllocType::Fast)
2563 addMachineFunctionPass(
2564 RegAllocFastPass({onlyAllocateWWMRegs, "wwm", false}), PMW);
2565 else
2566 addMachineFunctionPass(RAGreedyPass({onlyAllocateWWMRegs, "wwm"}), PMW);
2567 addMachineFunctionPass(SILowerWWMCopiesPass(), PMW);
2568 addMachineFunctionPass(VirtRegRewriterPass(false), PMW);
2569 addMachineFunctionPass(AMDGPUReserveWWMRegsPass(), PMW);
2570
2571 // VGPR allocation - default to greedy at -O1 and above.
2572 if (VGPRRegAllocNPM == RegAllocType::Fast)
2573 addMachineFunctionPass(RegAllocFastPass({onlyAllocateVGPRs, "vgpr"}), PMW);
2574 else
2575 addMachineFunctionPass(RAGreedyPass({onlyAllocateVGPRs, "vgpr"}), PMW);
2576
2577 addPreRewrite(PMW);
2578 addMachineFunctionPass(VirtRegRewriterPass(true), PMW);
2579
2580 addMachineFunctionPass(AMDGPUMarkLastScratchLoadPass(), PMW);
2581 return Error::success();
2582}
2583
2584void AMDGPUCodeGenPassBuilder::addPostRegAlloc(PassManagerWrapper &PMW) const {
2585 addMachineFunctionPass(SIFixVGPRCopiesPass(), PMW);
2586 if (TM.getOptLevel() > CodeGenOptLevel::None)
2587 addMachineFunctionPass(SIOptimizeExecMaskingPass(), PMW);
2588 Base::addPostRegAlloc(PMW);
2589}
2590
2591void AMDGPUCodeGenPassBuilder::addPreSched2(PassManagerWrapper &PMW) const {
2592 if (TM.getOptLevel() > CodeGenOptLevel::None)
2593 addMachineFunctionPass(SIShrinkInstructionsPass(), PMW);
2594 addMachineFunctionPass(SIPostRABundlerPass(), PMW);
2595}
2596
2597void AMDGPUCodeGenPassBuilder::addPostBBSections(
2598 PassManagerWrapper &PMW) const {
2599 // We run this later to avoid passes like livedebugvalues and BBSections
2600 // having to deal with the apparent multi-entry functions we may generate.
2601 addMachineFunctionPass(AMDGPUPreloadKernArgPrologPass(), PMW);
2602}
2603
2604void AMDGPUCodeGenPassBuilder::addPreEmitPass(PassManagerWrapper &PMW) const {
2605 if (isPassEnabled(EnableVOPD, CodeGenOptLevel::Less)) {
2606 addMachineFunctionPass(GCNCreateVOPDPass(), PMW);
2607 }
2608
2609 addMachineFunctionPass(SIMemoryLegalizerPass(), PMW);
2610 addMachineFunctionPass(SIInsertWaitcntsPass(), PMW);
2611
2612 addMachineFunctionPass(SIModeRegisterPass(), PMW);
2613
2614 if (TM.getOptLevel() > CodeGenOptLevel::None)
2615 addMachineFunctionPass(SIInsertHardClausesPass(), PMW);
2616
2617 addMachineFunctionPass(SILateBranchLoweringPass(), PMW);
2618
2619 if (isPassEnabled(EnableSetWavePriority, CodeGenOptLevel::Less))
2620 addMachineFunctionPass(AMDGPUSetWavePriorityPass(), PMW);
2621
2622 if (TM.getOptLevel() > CodeGenOptLevel::None)
2623 addMachineFunctionPass(SIPreEmitPeepholePass(), PMW);
2624
2625 // The hazard recognizer that runs as part of the post-ra scheduler does not
2626 // guarantee to be able handle all hazards correctly. This is because if there
2627 // are multiple scheduling regions in a basic block, the regions are scheduled
2628 // bottom up, so when we begin to schedule a region we don't know what
2629 // instructions were emitted directly before it.
2630 //
2631 // Here we add a stand-alone hazard recognizer pass which can handle all
2632 // cases.
2633 addMachineFunctionPass(PostRAHazardRecognizerPass(), PMW);
2634 addMachineFunctionPass(AMDGPUWaitSGPRHazardsPass(), PMW);
2635 addMachineFunctionPass(AMDGPULowerVGPREncodingPass(), PMW);
2636
2637 if (isPassEnabled(EnableInsertDelayAlu, CodeGenOptLevel::Less)) {
2638 addMachineFunctionPass(AMDGPUInsertDelayAluPass(), PMW);
2639 }
2640
2641 addMachineFunctionPass(BranchRelaxationPass(), PMW);
2642}
2643
2644bool AMDGPUCodeGenPassBuilder::isPassEnabled(const cl::opt<bool> &Opt,
2645 CodeGenOptLevel Level) const {
2646 if (Opt.getNumOccurrences())
2647 return Opt;
2648 if (TM.getOptLevel() < Level)
2649 return false;
2650 return Opt;
2651}
2652
2653void AMDGPUCodeGenPassBuilder::addEarlyCSEOrGVNPass(
2654 PassManagerWrapper &PMW) const {
2655 if (TM.getOptLevel() == CodeGenOptLevel::Aggressive)
2656 addFunctionPass(GVNPass(), PMW);
2657 else
2658 addFunctionPass(EarlyCSEPass(), PMW);
2659}
2660
2661void AMDGPUCodeGenPassBuilder::addStraightLineScalarOptimizationPasses(
2662 PassManagerWrapper &PMW) const {
2664 addFunctionPass(LoopDataPrefetchPass(), PMW);
2665
2666 addFunctionPass(SeparateConstOffsetFromGEPPass(), PMW);
2667
2668 // ReassociateGEPs exposes more opportunities for SLSR. See
2669 // the example in reassociate-geps-and-slsr.ll.
2670 addFunctionPass(StraightLineStrengthReducePass(), PMW);
2671
2672 // SeparateConstOffsetFromGEP and SLSR creates common expressions which GVN or
2673 // EarlyCSE can reuse.
2674 addEarlyCSEOrGVNPass(PMW);
2675
2676 // Run NaryReassociate after EarlyCSE/GVN to be more effective.
2677 addFunctionPass(NaryReassociatePass(), PMW);
2678
2679 // NaryReassociate on GEPs creates redundant common expressions, so run
2680 // EarlyCSE after it.
2681 addFunctionPass(EarlyCSEPass(), PMW);
2682}
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.
Coexecution-focused scheduling strategy for AMDGPU.
Defines an instruction selector for the AMDGPU target.
Analyzes if a function potentially memory bound and if a kernel kernel may benefit from limiting numb...
Analyzes how many registers and other resources are used by functions.
static cl::opt< 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 cl::opt< bool, true > EnableObjectLinking("amdgpu-enable-object-linking", cl::desc("Enable object linking for cross-TU LDS and ABI support"), cl::location(AMDGPUTargetMachine::EnableObjectLinking), cl::init(false), cl::Hidden)
static ScheduleDAGInstrs * createGCNMaxILPMachineScheduler(MachineSchedContext *C)
static 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 void diagnoseUnsupportedCoExecSchedulerSelection(const Function &F, const GCNSubtarget &ST)
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 bool useNoopPostScheduler(const Function &F)
static ScheduleDAGInstrs * createGCNMaxMemoryClauseMachineScheduler(MachineSchedContext *C)
static cl::opt< bool > EnableSIModeRegisterPass("amdgpu-mode-register", cl::desc("Enable mode register pass"), cl::init(true), cl::Hidden)
static cl::opt< std::string > AMDGPUSchedStrategy("amdgpu-sched-strategy", cl::desc("Select custom AMDGPU scheduling strategy."), cl::Hidden, cl::init(""))
static cl::opt< bool > EnableDPPCombine("amdgpu-dpp-combine", cl::desc("Enable DPP combiner"), cl::init(true))
static MachineSchedRegistry IterativeGCNMaxOccupancySchedRegistry("gcn-iterative-max-occupancy-experimental", "Run GCN scheduler to maximize occupancy (experimental)", createIterativeGCNMaxOccupancyMachineScheduler)
static cl::opt< bool > EnableSetWavePriority("amdgpu-set-wave-priority", cl::desc("Adjust wave priority"), cl::init(false), cl::Hidden)
static cl::opt< bool > LowerCtorDtor("amdgpu-lower-global-ctor-dtor", cl::desc("Lower GPU ctor / dtors to globals on the device."), cl::init(true), cl::Hidden)
static cl::opt< bool > OptExecMaskPreRA("amdgpu-opt-exec-mask-pre-ra", cl::Hidden, cl::desc("Run pre-RA exec mask optimizations"), cl::init(true))
static cl::opt< bool > EnablePromoteKernelArguments("amdgpu-enable-promote-kernel-arguments", cl::desc("Enable promotion of flat kernel pointer arguments to global"), cl::Hidden, cl::init(true))
LLVM_ABI LLVM_EXTERNAL_VISIBILITY void LLVMInitializeAMDGPUTarget()
static cl::opt< bool > EnableRewritePartialRegUses("amdgpu-enable-rewrite-partial-reg-uses", cl::desc("Enable rewrite partial reg uses pass"), cl::init(true), cl::Hidden)
static cl::opt< bool > EnableLibCallSimplify("amdgpu-simplify-libcall", cl::desc("Enable amdgpu library simplifications"), cl::init(true), cl::Hidden)
static MachineSchedRegistry GCNMaxILPSchedRegistry("gcn-max-ilp", "Run GCN scheduler to maximize ilp", createGCNMaxILPMachineScheduler)
static cl::opt< bool > InternalizeSymbols("amdgpu-internalize-symbols", cl::desc("Enable elimination of non-kernel functions and unused globals"), cl::init(false), cl::Hidden)
static cl::opt< bool > EnableAMDGPUAttributor("amdgpu-attributor-enable", cl::desc("Enable AMDGPUAttributorPass"), cl::init(true), cl::Hidden)
static LLVM_READNONE StringRef getGPUOrDefault(const Triple &TT, StringRef GPU)
Expected< AMDGPUAttributorOptions > parseAMDGPUAttributorPassOptions(StringRef Params)
static cl::opt< bool > EnableAMDGPUAliasAnalysis("enable-amdgpu-aa", cl::Hidden, cl::desc("Enable AMDGPU Alias Analysis"), cl::init(true))
static Expected< ScanOptions > parseAMDGPUAtomicOptimizerStrategy(StringRef Params)
static ScheduleDAGInstrs * createMinRegScheduler(MachineSchedContext *C)
static cl::opt< bool > EnableHipStdPar("amdgpu-enable-hipstdpar", cl::desc("Enable HIP Standard Parallelism Offload support"), cl::init(false), cl::Hidden)
static cl::opt< bool > EnableInsertDelayAlu("amdgpu-enable-delay-alu", cl::desc("Enable s_delay_alu insertion"), cl::init(true), cl::Hidden)
static ScheduleDAGInstrs * createIterativeGCNMaxOccupancyMachineScheduler(MachineSchedContext *C)
static cl::opt< bool > EnableLoadStoreVectorizer("amdgpu-load-store-vectorizer", cl::desc("Enable load store vectorizer"), cl::init(true), cl::Hidden)
static bool mustPreserveGV(const GlobalValue &GV)
Predicate for Internalize pass.
static cl::opt< bool > EnableLoopPrefetch("amdgpu-loop-prefetch", cl::desc("Enable loop data prefetch on AMDGPU"), cl::Hidden, cl::init(false))
static cl::opt< bool > NewRegBankSelect("new-reg-bank-select", cl::desc("Run amdgpu-regbankselect and amdgpu-regbanklegalize instead of " "regbankselect"), cl::init(false), cl::Hidden)
static cl::opt< bool > RemoveIncompatibleFunctions("amdgpu-enable-remove-incompatible-functions", cl::Hidden, cl::desc("Enable removal of functions when they" "use features not supported by the target GPU"), cl::init(true))
static cl::opt< bool > EnableScalarIRPasses("amdgpu-scalar-ir-passes", cl::desc("Enable scalar IR passes"), cl::init(true), cl::Hidden)
static cl::opt< bool > EnableRegReassign("amdgpu-reassign-regs", cl::desc("Enable register reassign optimizations on gfx10+"), cl::init(true), cl::Hidden)
static cl::opt< bool > OptVGPRLiveRange("amdgpu-opt-vgpr-liverange", cl::desc("Enable VGPR liverange optimizations for if-else structure"), cl::init(true), cl::Hidden)
static ScheduleDAGInstrs * createSIMachineScheduler(MachineSchedContext *C)
static cl::opt< bool > EnablePreRAOptimizations("amdgpu-enable-pre-ra-optimizations", cl::desc("Enable Pre-RA optimizations pass"), cl::init(true), cl::Hidden)
static cl::opt< ScanOptions > AMDGPUAtomicOptimizerStrategy("amdgpu-atomic-optimizer-strategy", cl::desc("Select DPP or Iterative strategy for scan"), cl::init(ScanOptions::Iterative), cl::values(clEnumValN(ScanOptions::DPP, "DPP", "Use DPP operations for scan"), clEnumValN(ScanOptions::Iterative, "Iterative", "Use Iterative approach for scan"), clEnumValN(ScanOptions::None, "None", "Disable atomic optimizer")))
static cl::opt< bool > EnableVOPD("amdgpu-enable-vopd", cl::desc("Enable VOPD, dual issue of VALU in wave32"), cl::init(true), cl::Hidden)
static ScheduleDAGInstrs * createGCNMaxOccupancyMachineScheduler(MachineSchedContext *C)
static cl::opt< bool > EnableLowerExecSync("amdgpu-enable-lower-exec-sync", cl::desc("Enable lowering of execution synchronization."), cl::init(true), cl::Hidden)
static MachineSchedRegistry GCNILPSchedRegistry("gcn-iterative-ilp", "Run GCN iterative scheduler for ILP scheduling (experimental)", createIterativeILPMachineScheduler)
static cl::opt< bool > ScalarizeGlobal("amdgpu-scalarize-global-loads", cl::desc("Enable global load scalarization"), cl::init(true), cl::Hidden)
static const char RegAllocOptNotSupportedMessage[]
static MachineSchedRegistry GCNMaxOccupancySchedRegistry("gcn-max-occupancy", "Run GCN scheduler to maximize occupancy", createGCNMaxOccupancyMachineScheduler)
The AMDGPU TargetMachine interface definition for hw codegen targets.
This file declares the AMDGPU-specific subclass of TargetLoweringObjectFile.
This file a TargetTransformInfoImplBase conforming object specific to the AMDGPU target machine.
Provides passes to inlining "always_inline" functions.
#define X(NUM, ENUM, NAME)
Definition ELF.h:851
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:483
static TableGen::Emitter::Opt Y("gen-skeleton-entry", EmitSkeleton, "Generate example skeleton entry")
static FunctionPass * useDefaultRegisterAllocator()
-regalloc=... command line option.
static cl::opt< cl::boolOrDefault > EnableGlobalISelOption("global-isel", cl::Hidden, cl::desc("Enable the \"global\" instruction selector"))
Target-Independent Code Generator Pass Configuration Options pass.
LLVM IR instance of the generic uniformity analysis.
static std::unique_ptr< TargetLoweringObjectFile > createTLOF()
A manager for alias analyses.
void registerFunctionAnalysis()
Register a specific AA result.
void addAAResult(AAResultT &AAResult)
Register a specific AA result.
Legacy wrapper pass to provide the AMDGPUAAResult object.
Analysis pass providing a never-invalidated alias analysis result.
Lower llvm.global_ctors and llvm.global_dtors to special kernels.
AMDGPUTargetMachine & getAMDGPUTargetMachine() const
std::unique_ptr< CSEConfigBase > getCSEConfig() const override
Returns the CSEConfig object to use for the current optimization level.
bool isPassEnabled(const cl::opt< bool > &Opt, CodeGenOptLevel Level=CodeGenOptLevel::Default) const
Check if a pass is enabled given Opt option.
bool addPreISel() override
Methods with trivial inline returns are convenient points in the common codegen pass pipeline where t...
bool addInstSelector() override
addInstSelector - This method should install an instruction selector pass, which converts from LLVM c...
bool addGCPasses() override
addGCPasses - Add late codegen passes that analyze code for garbage collection.
AMDGPUPassConfig(TargetMachine &TM, PassManagerBase &PM)
void addIRPasses() override
Add common target configurable passes that perform LLVM IR to IR transforms following machine indepen...
void addCodeGenPrepare() override
Add pass to prepare the LLVM IR for code generation.
Splits the module M into N linkable partitions.
std::unique_ptr< TargetLoweringObjectFile > TLOF
unsigned getAddressSpaceForPseudoSourceKind(unsigned Kind) const override
getAddressSpaceForPseudoSourceKind - Given the kind of memory (e.g.
const TargetSubtargetInfo * getSubtargetImpl() const
void registerDefaultAliasAnalyses(AAManager &) override
Allow the target to register alias analyses with the AAManager for use with the new pass manager.
std::pair< const Value *, unsigned > getPredicatedAddrSpace(const Value *V) const override
If the specified predicate checks whether a generic pointer falls within a specified address space,...
StringRef getFeatureString(const Function &F) const
ScheduleDAGInstrs * createMachineScheduler(MachineSchedContext *C) const override
Create an instance of ScheduleDAGInstrs to be run within the standard MachineScheduler pass for this ...
AMDGPUTargetMachine(const Target &T, const Triple &TT, StringRef CPU, StringRef FS, const TargetOptions &Options, std::optional< Reloc::Model > RM, std::optional< CodeModel::Model > CM, CodeGenOptLevel OL)
bool isNoopAddrSpaceCast(unsigned SrcAS, unsigned DestAS) const override
Returns true if a cast between SrcAS and DestAS is a noop.
void registerPassBuilderCallbacks(PassBuilder &PB) override
Allow the target to modify the pass pipeline.
StringRef getGPUName(const Function &F) const
unsigned getAssumedAddrSpace(const Value *V) const override
If the specified generic pointer could be assumed as a pointer to a specific address space,...
bool splitModule(Module &M, unsigned NumParts, function_ref< void(std::unique_ptr< Module > MPart)> ModuleCallback) override
Entry point for module splitting.
Inlines functions marked as "always_inline".
ArrayRef - Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition ArrayRef.h:40
Functions, function parameters, and return types can have attributes to indicate how they should be t...
Definition Attributes.h:105
LLVM_ABI StringRef getValueAsString() const
Return the attribute's value as a string.
bool isValid() const
Return true if the attribute is any kind of attribute.
Definition Attributes.h:261
This class provides access to building LLVM's passes.
CodeGenTargetMachineImpl(const Target &T, StringRef DataLayoutString, const Triple &TT, StringRef CPU, StringRef FS, const TargetOptions &Options, Reloc::Model RM, CodeModel::Model CM, CodeGenOptLevel OL)
LLVM_ABI void removeDeadConstantUsers() const
If there are any dead constant users dangling off of this constant, remove them.
Diagnostic information for unsupported feature in backend.
Lightweight error class with error context and mandatory checking.
Definition Error.h:159
static ErrorSuccess success()
Create a success value.
Definition Error.h:336
Tagged union holding either a T or a Error.
Definition Error.h:485
FunctionPass class - This class is used to implement most global optimizations.
Definition Pass.h: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...
Error buildCodeGenPipeline(ModulePassManager &MPM, ModuleAnalysisManager &MAM, raw_pwrite_stream &Out, raw_pwrite_stream *DwoOut, CodeGenFileType FileType, const CGPassBuilderOption &Opts, MCContext &Ctx, PassInstrumentationCallbacks *PIC) override
TargetPassConfig * createPassConfig(PassManagerBase &PM) override
Create a pass configuration object to be used by addPassToEmitX methods for generating a pipeline of ...
GCNTargetMachine(const Target &T, const Triple &TT, StringRef CPU, StringRef FS, const TargetOptions &Options, std::optional< Reloc::Model > RM, std::optional< CodeModel::Model > CM, CodeGenOptLevel OL, bool JIT)
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:346
int getNumOccurrences() const
An efficient, type-erasing, non-owning reference to a callable.
PassManagerBase - An abstract interface to allow code to add passes to a pass manager without having ...
An abstract base class for streams implementations that also support a pwrite operation.
Interfaces for registering analysis passes, producing common pass manager configurations,...
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
@ 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.
StringRef getSchedStrategy(const Function &F)
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)
match_deferred< Value > m_Deferred(Value *const &V)
Like m_Specific(), but works if the specific value to match is determined as part of the same match()...
IntrinsicID_match m_Intrinsic()
Match intrinsic calls like this: m_Intrinsic<Intrinsic::fabs>(m_Value(X))
auto 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.
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 initializeAMDGPUNextUseAnalysisLegacyPassPass(PassRegistry &)
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.
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 &)
ScheduleDAGInstrs * createGCNNoopPostMachineScheduler(MachineSchedContext *C)
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 &)
ScheduleDAGInstrs * createGCNCoExecMachineScheduler(MachineSchedContext *C)
void initializeSIPreAllocateWWMRegsLegacyPass(PassRegistry &)
void initializeSIFixVGPRCopiesLegacyPass(PassRegistry &)
Target & getTheGCNTarget()
The target for GCN GPUs.
void initializeSIFixSGPRCopiesLegacyPass(PassRegistry &)
void initializeAMDGPUAtomicOptimizerPass(PassRegistry &)
void initializeAMDGPULowerIntrinsicsLegacyPass(PassRegistry &)
LLVM_ABI FunctionPass * createGVNPass()
Create a legacy GVN pass.
Definition GVN.cpp:3398
void initializeAMDGPURewriteAGPRCopyMFMALegacyPass(PassRegistry &)
void initializeAMDGPUNextUseAnalysisPrinterLegacyPassPass(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 initializeAMDGPULowerBufferFatPointersPass(PassRegistry &)
void initializeAMDGPUUnifyDivergentExitNodesLegacyPass(PassRegistry &)
FunctionPass * createSIInsertWaitcntsPass()
FunctionPass * createAMDGPUAnnotateUniformValuesLegacy()
LLVM_ABI FunctionPass * createEarlyCSEPass(bool UseMemorySSA=false)
void initializeSIWholeQuadModeLegacyPass(PassRegistry &)
LLVM_ABI char & PHIEliminationID
PHIElimination - This pass eliminates machine instruction PHI nodes by inserting copy instructions.
LLVM_ABI llvm::cl::opt< bool > NoKernelInfoEndLTO
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.