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/Module.h"
97#include "llvm/IR/PassManager.h"
106#include "llvm/Transforms/IPO.h"
131#include <optional>
132
133using namespace llvm;
134using namespace llvm::PatternMatch;
135
136namespace {
137//===----------------------------------------------------------------------===//
138// AMDGPU CodeGen Pass Builder interface.
139//===----------------------------------------------------------------------===//
140
141class AMDGPUCodeGenPassBuilder
142 : public CodeGenPassBuilder<AMDGPUCodeGenPassBuilder, GCNTargetMachine> {
143 using Base = CodeGenPassBuilder<AMDGPUCodeGenPassBuilder, GCNTargetMachine>;
144
145public:
146 AMDGPUCodeGenPassBuilder(GCNTargetMachine &TM,
147 const CGPassBuilderOption &Opts,
148 PassInstrumentationCallbacks *PIC);
149
150 void addIRPasses(PassManagerWrapper &PMW) const;
151 void addCodeGenPrepare(PassManagerWrapper &PMW) const;
152 void addPreISel(PassManagerWrapper &PMW) const;
153 void addILPOpts(PassManagerWrapper &PMWM) const;
154 void addAsmPrinterBegin(PassManagerWrapper &PMW) const;
155 void addAsmPrinter(PassManagerWrapper &PMW) const;
156 void addAsmPrinterEnd(PassManagerWrapper &PMW) const;
157 Error addInstSelector(PassManagerWrapper &PMW) const;
158 void addPreRewrite(PassManagerWrapper &PMW) const;
159 void addMachineSSAOptimization(PassManagerWrapper &PMW) const;
160 void addPostRegAlloc(PassManagerWrapper &PMW) const;
161 void addPreEmitPass(PassManagerWrapper &PMWM) const;
162 void addPreEmitRegAlloc(PassManagerWrapper &PMW) const;
163 Error addRegAssignmentFast(PassManagerWrapper &PMW) const;
164 Error addRegAssignmentOptimized(PassManagerWrapper &PMW) const;
165 void addPreRegAlloc(PassManagerWrapper &PMW) const;
166 Error addFastRegAlloc(PassManagerWrapper &PMW) const;
167 Error addOptimizedRegAlloc(PassManagerWrapper &PMW) const;
168 void addPreSched2(PassManagerWrapper &PMW) const;
169 void addPostBBSections(PassManagerWrapper &PMW) const;
170
171private:
172 Error validateRegAllocOptions() const;
173
174public:
175 /// Check if a pass is enabled given \p Opt option. The option always
176 /// overrides defaults if explicitly used. Otherwise its default will be used
177 /// given that a pass shall work at an optimization \p Level minimum.
178 bool isPassEnabled(const cl::opt<bool> &Opt,
179 CodeGenOptLevel Level = CodeGenOptLevel::Default) const;
180 void addEarlyCSEOrGVNPass(PassManagerWrapper &PMW) const;
181 void addStraightLineScalarOptimizationPasses(PassManagerWrapper &PMW) const;
182};
183
184class SGPRRegisterRegAlloc : public RegisterRegAllocBase<SGPRRegisterRegAlloc> {
185public:
186 SGPRRegisterRegAlloc(const char *N, const char *D, FunctionPassCtor C)
187 : RegisterRegAllocBase(N, D, C) {}
188};
189
190class VGPRRegisterRegAlloc : public RegisterRegAllocBase<VGPRRegisterRegAlloc> {
191public:
192 VGPRRegisterRegAlloc(const char *N, const char *D, FunctionPassCtor C)
193 : RegisterRegAllocBase(N, D, C) {}
194};
195
196class WWMRegisterRegAlloc : public RegisterRegAllocBase<WWMRegisterRegAlloc> {
197public:
198 WWMRegisterRegAlloc(const char *N, const char *D, FunctionPassCtor C)
199 : RegisterRegAllocBase(N, D, C) {}
200};
201
202static bool onlyAllocateSGPRs(const TargetRegisterInfo &TRI,
203 const MachineRegisterInfo &MRI,
204 const Register Reg) {
205 const TargetRegisterClass *RC = MRI.getRegClass(Reg);
206 return static_cast<const SIRegisterInfo &>(TRI).isSGPRClass(RC);
207}
208
209static bool onlyAllocateVGPRs(const TargetRegisterInfo &TRI,
210 const MachineRegisterInfo &MRI,
211 const Register Reg) {
212 const TargetRegisterClass *RC = MRI.getRegClass(Reg);
213 return !static_cast<const SIRegisterInfo &>(TRI).isSGPRClass(RC);
214}
215
216static bool onlyAllocateWWMRegs(const TargetRegisterInfo &TRI,
217 const MachineRegisterInfo &MRI,
218 const Register Reg) {
219 const SIMachineFunctionInfo *MFI =
221 const TargetRegisterClass *RC = MRI.getRegClass(Reg);
222 return !static_cast<const SIRegisterInfo &>(TRI).isSGPRClass(RC) &&
224}
225
226/// -{sgpr|wwm|vgpr}-regalloc=... command line option.
227static FunctionPass *useDefaultRegisterAllocator() { return nullptr; }
228
229/// A dummy default pass factory indicates whether the register allocator is
230/// overridden on the command line.
231static llvm::once_flag InitializeDefaultSGPRRegisterAllocatorFlag;
232static llvm::once_flag InitializeDefaultVGPRRegisterAllocatorFlag;
233static llvm::once_flag InitializeDefaultWWMRegisterAllocatorFlag;
234
235static SGPRRegisterRegAlloc
236defaultSGPRRegAlloc("default",
237 "pick SGPR register allocator based on -O option",
239
240static cl::opt<SGPRRegisterRegAlloc::FunctionPassCtor, false,
242SGPRRegAlloc("sgpr-regalloc", cl::Hidden, cl::init(&useDefaultRegisterAllocator),
243 cl::desc("Register allocator to use for SGPRs"));
244
245static cl::opt<VGPRRegisterRegAlloc::FunctionPassCtor, false,
247VGPRRegAlloc("vgpr-regalloc", cl::Hidden, cl::init(&useDefaultRegisterAllocator),
248 cl::desc("Register allocator to use for VGPRs"));
249
250static cl::opt<WWMRegisterRegAlloc::FunctionPassCtor, false,
252 WWMRegAlloc("wwm-regalloc", cl::Hidden,
254 cl::desc("Register allocator to use for WWM registers"));
255
256// New pass manager register allocator options for AMDGPU
258 "sgpr-regalloc-npm", cl::Hidden, cl::init(RegAllocType::Default),
259 cl::desc("Register allocator for SGPRs (new pass manager)"));
260
262 "vgpr-regalloc-npm", cl::Hidden, cl::init(RegAllocType::Default),
263 cl::desc("Register allocator for VGPRs (new pass manager)"));
264
266 "wwm-regalloc-npm", cl::Hidden, cl::init(RegAllocType::Default),
267 cl::desc("Register allocator for WWM registers (new pass manager)"));
268
269/// Check if the given RegAllocType is supported for AMDGPU NPM register
270/// allocation. Only Fast and Greedy are supported; Basic and PBQP are not.
271static Error checkRegAllocSupported(RegAllocType RAType, StringRef RegName) {
272 if (RAType == RegAllocType::Basic || RAType == RegAllocType::PBQP) {
274 Twine("unsupported register allocator '") +
275 (RAType == RegAllocType::Basic ? "basic" : "pbqp") + "' for " +
276 RegName + " registers",
278 }
279 return Error::success();
280}
281
282Error AMDGPUCodeGenPassBuilder::validateRegAllocOptions() const {
283 // 1. Generic --regalloc-npm is not supported for AMDGPU.
284 if (Opt.RegAlloc != RegAllocType::Unset) {
286 "-regalloc-npm not supported for amdgcn. Use -sgpr-regalloc-npm, "
287 "-vgpr-regalloc-npm, and -wwm-regalloc-npm",
289 }
290
291 // 2. Legacy PM regalloc options are not compatible with NPM.
292 if (SGPRRegAlloc.getNumOccurrences() > 0 ||
293 VGPRRegAlloc.getNumOccurrences() > 0 ||
294 WWMRegAlloc.getNumOccurrences() > 0) {
296 "-sgpr-regalloc, -vgpr-regalloc, and -wwm-regalloc are legacy PM "
297 "options. Use -sgpr-regalloc-npm, -vgpr-regalloc-npm, and "
298 "-wwm-regalloc-npm with the new pass manager",
300 }
301
302 // 3. Only Fast and Greedy allocators are supported for AMDGPU.
303 if (auto Err = checkRegAllocSupported(SGPRRegAllocNPM, "SGPR"))
304 return Err;
305 if (auto Err = checkRegAllocSupported(WWMRegAllocNPM, "WWM"))
306 return Err;
307 if (auto Err = checkRegAllocSupported(VGPRRegAllocNPM, "VGPR"))
308 return Err;
309
310 return Error::success();
311}
312
313static void initializeDefaultSGPRRegisterAllocatorOnce() {
314 RegisterRegAlloc::FunctionPassCtor Ctor = SGPRRegisterRegAlloc::getDefault();
315
316 if (!Ctor) {
317 Ctor = SGPRRegAlloc;
318 SGPRRegisterRegAlloc::setDefault(SGPRRegAlloc);
319 }
320}
321
322static void initializeDefaultVGPRRegisterAllocatorOnce() {
323 RegisterRegAlloc::FunctionPassCtor Ctor = VGPRRegisterRegAlloc::getDefault();
324
325 if (!Ctor) {
326 Ctor = VGPRRegAlloc;
327 VGPRRegisterRegAlloc::setDefault(VGPRRegAlloc);
328 }
329}
330
331static void initializeDefaultWWMRegisterAllocatorOnce() {
332 RegisterRegAlloc::FunctionPassCtor Ctor = WWMRegisterRegAlloc::getDefault();
333
334 if (!Ctor) {
335 Ctor = WWMRegAlloc;
336 WWMRegisterRegAlloc::setDefault(WWMRegAlloc);
337 }
338}
339
340static FunctionPass *createBasicSGPRRegisterAllocator() {
341 return createBasicRegisterAllocator(onlyAllocateSGPRs);
342}
343
344static FunctionPass *createGreedySGPRRegisterAllocator() {
345 return createGreedyRegisterAllocator(onlyAllocateSGPRs);
346}
347
348static FunctionPass *createFastSGPRRegisterAllocator() {
349 return createFastRegisterAllocator(onlyAllocateSGPRs, false);
350}
351
352static FunctionPass *createBasicVGPRRegisterAllocator() {
353 return createBasicRegisterAllocator(onlyAllocateVGPRs);
354}
355
356static FunctionPass *createGreedyVGPRRegisterAllocator() {
357 return createGreedyRegisterAllocator(onlyAllocateVGPRs);
358}
359
360static FunctionPass *createFastVGPRRegisterAllocator() {
361 return createFastRegisterAllocator(onlyAllocateVGPRs, true);
362}
363
364static FunctionPass *createBasicWWMRegisterAllocator() {
365 return createBasicRegisterAllocator(onlyAllocateWWMRegs);
366}
367
368static FunctionPass *createGreedyWWMRegisterAllocator() {
369 return createGreedyRegisterAllocator(onlyAllocateWWMRegs);
370}
371
372static FunctionPass *createFastWWMRegisterAllocator() {
373 return createFastRegisterAllocator(onlyAllocateWWMRegs, false);
374}
375
376static SGPRRegisterRegAlloc basicRegAllocSGPR(
377 "basic", "basic register allocator", createBasicSGPRRegisterAllocator);
378static SGPRRegisterRegAlloc greedyRegAllocSGPR(
379 "greedy", "greedy register allocator", createGreedySGPRRegisterAllocator);
380
381static SGPRRegisterRegAlloc fastRegAllocSGPR(
382 "fast", "fast register allocator", createFastSGPRRegisterAllocator);
383
384
385static VGPRRegisterRegAlloc basicRegAllocVGPR(
386 "basic", "basic register allocator", createBasicVGPRRegisterAllocator);
387static VGPRRegisterRegAlloc greedyRegAllocVGPR(
388 "greedy", "greedy register allocator", createGreedyVGPRRegisterAllocator);
389
390static VGPRRegisterRegAlloc fastRegAllocVGPR(
391 "fast", "fast register allocator", createFastVGPRRegisterAllocator);
392static WWMRegisterRegAlloc basicRegAllocWWMReg("basic",
393 "basic register allocator",
394 createBasicWWMRegisterAllocator);
395static WWMRegisterRegAlloc
396 greedyRegAllocWWMReg("greedy", "greedy register allocator",
397 createGreedyWWMRegisterAllocator);
398static WWMRegisterRegAlloc fastRegAllocWWMReg("fast", "fast register allocator",
399 createFastWWMRegisterAllocator);
400
402 return Phase == ThinOrFullLTOPhase::FullLTOPreLink ||
403 Phase == ThinOrFullLTOPhase::ThinLTOPreLink;
404}
405} // anonymous namespace
406
407static cl::opt<bool>
409 cl::desc("Run early if-conversion"),
410 cl::init(false));
411
412static cl::opt<bool>
413OptExecMaskPreRA("amdgpu-opt-exec-mask-pre-ra", cl::Hidden,
414 cl::desc("Run pre-RA exec mask optimizations"),
415 cl::init(true));
416
417static cl::opt<bool>
418 LowerCtorDtor("amdgpu-lower-global-ctor-dtor",
419 cl::desc("Lower GPU ctor / dtors to globals on the device."),
420 cl::init(true), cl::Hidden);
421
422// Option to disable vectorizer for tests.
424 "amdgpu-load-store-vectorizer",
425 cl::desc("Enable load store vectorizer"),
426 cl::init(true),
427 cl::Hidden);
428
429// Option to control global loads scalarization
431 "amdgpu-scalarize-global-loads",
432 cl::desc("Enable global load scalarization"),
433 cl::init(true),
434 cl::Hidden);
435
436// Option to run internalize pass.
438 "amdgpu-internalize-symbols",
439 cl::desc("Enable elimination of non-kernel functions and unused globals"),
440 cl::init(false),
441 cl::Hidden);
442
443// Option to inline all early.
445 "amdgpu-early-inline-all",
446 cl::desc("Inline all functions early"),
447 cl::init(false),
448 cl::Hidden);
449
451 "amdgpu-enable-remove-incompatible-functions", cl::Hidden,
452 cl::desc("Enable removal of functions when they"
453 "use features not supported by the target GPU"),
454 cl::init(true));
455
457 "amdgpu-sdwa-peephole",
458 cl::desc("Enable SDWA peepholer"),
459 cl::init(true));
460
462 "amdgpu-dpp-combine",
463 cl::desc("Enable DPP combiner"),
464 cl::init(true));
465
466// Enable address space based alias analysis
468 cl::desc("Enable AMDGPU Alias Analysis"),
469 cl::init(true));
470
471// Enable lib calls simplifications
473 "amdgpu-simplify-libcall",
474 cl::desc("Enable amdgpu library simplifications"),
475 cl::init(true),
476 cl::Hidden);
477
479 "amdgpu-ir-lower-kernel-arguments",
480 cl::desc("Lower kernel argument loads in IR pass"),
481 cl::init(true),
482 cl::Hidden);
483
485 "amdgpu-reassign-regs",
486 cl::desc("Enable register reassign optimizations on gfx10+"),
487 cl::init(true),
488 cl::Hidden);
489
491 "amdgpu-opt-vgpr-liverange",
492 cl::desc("Enable VGPR liverange optimizations for if-else structure"),
493 cl::init(true), cl::Hidden);
494
496 "amdgpu-atomic-optimizer-strategy",
497 cl::desc("Select DPP or Iterative strategy for scan"),
500 clEnumValN(ScanOptions::DPP, "DPP", "Use DPP operations for scan"),
502 "Use Iterative approach for scan"),
503 clEnumValN(ScanOptions::None, "None", "Disable atomic optimizer")));
504
505// Enable Mode register optimization
507 "amdgpu-mode-register",
508 cl::desc("Enable mode register pass"),
509 cl::init(true),
510 cl::Hidden);
511
512// Enable GFX11+ s_delay_alu insertion
513static cl::opt<bool>
514 EnableInsertDelayAlu("amdgpu-enable-delay-alu",
515 cl::desc("Enable s_delay_alu insertion"),
516 cl::init(true), cl::Hidden);
517
518// Enable GFX11+ VOPD
519static cl::opt<bool>
520 EnableVOPD("amdgpu-enable-vopd",
521 cl::desc("Enable VOPD, dual issue of VALU in wave32"),
522 cl::init(true), cl::Hidden);
523
524// Option is used in lit tests to prevent deadcoding of patterns inspected.
525static cl::opt<bool>
526EnableDCEInRA("amdgpu-dce-in-ra",
527 cl::init(true), cl::Hidden,
528 cl::desc("Enable machine DCE inside regalloc"));
529
530static cl::opt<bool> EnableSetWavePriority("amdgpu-set-wave-priority",
531 cl::desc("Adjust wave priority"),
532 cl::init(false), cl::Hidden);
533
535 "amdgpu-scalar-ir-passes",
536 cl::desc("Enable scalar IR passes"),
537 cl::init(true),
538 cl::Hidden);
539
541 "amdgpu-enable-lower-exec-sync",
542 cl::desc("Enable lowering of execution synchronization."), cl::init(true),
543 cl::Hidden);
544
545static cl::opt<bool>
546 EnableSwLowerLDS("amdgpu-enable-sw-lower-lds",
547 cl::desc("Enable lowering of lds to global memory pass "
548 "and asan instrument resulting IR."),
549 cl::init(true), cl::Hidden);
550
552 "amdgpu-enable-object-linking",
553 cl::desc("Enable object linking for cross-TU LDS and ABI support"),
555 cl::Hidden);
556
558 "amdgpu-enable-lower-module-lds", cl::desc("Enable lower module lds pass"),
560 cl::Hidden);
561
563 "amdgpu-enable-pre-ra-optimizations",
564 cl::desc("Enable Pre-RA optimizations pass"), cl::init(true),
565 cl::Hidden);
566
568 "amdgpu-enable-promote-kernel-arguments",
569 cl::desc("Enable promotion of flat kernel pointer arguments to global"),
570 cl::Hidden, cl::init(true));
571
573 "amdgpu-enable-image-intrinsic-optimizer",
574 cl::desc("Enable image intrinsic optimizer pass"), cl::init(true),
575 cl::Hidden);
576
577static cl::opt<bool>
578 EnableLoopPrefetch("amdgpu-loop-prefetch",
579 cl::desc("Enable loop data prefetch on AMDGPU"),
580 cl::Hidden, cl::init(false));
581
583 AMDGPUSchedStrategy("amdgpu-sched-strategy",
584 cl::desc("Select custom AMDGPU scheduling strategy."),
585 cl::Hidden, cl::init(""));
586
587// Scheduler selection is consulted both when creating the scheduler and from
588// overrideSchedPolicy(), so keep the attribute and global command line handling
589// in one helper.
591 Attribute SchedStrategyAttr = F.getFnAttribute("amdgpu-sched-strategy");
592 if (SchedStrategyAttr.isValid())
593 return SchedStrategyAttr.getValueAsString();
594
595 if (!AMDGPUSchedStrategy.empty())
596 return AMDGPUSchedStrategy;
597
598 return "";
599}
600
601static void
603 const GCNSubtarget &ST) {
604 if (ST.hasGFX1250Insts())
605 return;
606
607 F.getContext().diagnose(DiagnosticInfoUnsupported(
608 F, "'amdgpu-sched-strategy'='coexec' is only supported for gfx1250",
610}
611
612static bool useNoopPostScheduler(const Function &F) {
613 Attribute PostSchedStrategyAttr =
614 F.getFnAttribute("amdgpu-post-sched-strategy");
615 return PostSchedStrategyAttr.isValid() &&
616 PostSchedStrategyAttr.getValueAsString() == "nop";
617}
618
620 "amdgpu-enable-rewrite-partial-reg-uses",
621 cl::desc("Enable rewrite partial reg uses pass"), cl::init(true),
622 cl::Hidden);
623
625 "amdgpu-enable-hipstdpar",
626 cl::desc("Enable HIP Standard Parallelism Offload support"), cl::init(false),
627 cl::Hidden);
628
629static cl::opt<bool>
630 EnableAMDGPUAttributor("amdgpu-attributor-enable",
631 cl::desc("Enable AMDGPUAttributorPass"),
632 cl::init(true), cl::Hidden);
633
635 "amdgpu-link-time-closed-world",
636 cl::desc("Whether has closed-world assumption at link time"),
637 cl::init(false), cl::Hidden);
638
640 "amdgpu-enable-uniform-intrinsic-combine",
641 cl::desc("Enable/Disable the Uniform Intrinsic Combine Pass"),
642 cl::init(true), cl::Hidden);
643
645 // Register the target
648
734}
735
736static std::unique_ptr<TargetLoweringObjectFile> createTLOF(const Triple &TT) {
737 return std::make_unique<AMDGPUTargetObjectFile>();
738}
739
743
744static ScheduleDAGInstrs *
746 const GCNSubtarget &ST = C->MF->getSubtarget<GCNSubtarget>();
747 ScheduleDAGMILive *DAG =
748 new GCNScheduleDAGMILive(C, std::make_unique<GCNMaxOccupancySchedStrategy>(C));
749 DAG->addMutation(createLoadClusterDAGMutation(DAG->TII, DAG->TRI));
750 if (ST.shouldClusterStores())
751 DAG->addMutation(createStoreClusterDAGMutation(DAG->TII, DAG->TRI));
753 DAG->addMutation(createAMDGPUMacroFusionDAGMutation());
754 DAG->addMutation(createAMDGPUExportClusteringDAGMutation());
755 DAG->addMutation(createAMDGPUBarrierLatencyDAGMutation(C->MF));
756 DAG->addMutation(createAMDGPUHazardLatencyDAGMutation(C->MF));
757 return DAG;
758}
759
760static ScheduleDAGInstrs *
762 ScheduleDAGMILive *DAG =
763 new GCNScheduleDAGMILive(C, std::make_unique<GCNMaxILPSchedStrategy>(C));
765 return DAG;
766}
767
768static ScheduleDAGInstrs *
770 const GCNSubtarget &ST = C->MF->getSubtarget<GCNSubtarget>();
772 C, std::make_unique<GCNMaxMemoryClauseSchedStrategy>(C));
773 DAG->addMutation(createLoadClusterDAGMutation(DAG->TII, DAG->TRI));
774 if (ST.shouldClusterStores())
775 DAG->addMutation(createStoreClusterDAGMutation(DAG->TII, DAG->TRI));
776 DAG->addMutation(createAMDGPUExportClusteringDAGMutation());
777 DAG->addMutation(createAMDGPUBarrierLatencyDAGMutation(C->MF));
778 DAG->addMutation(createAMDGPUHazardLatencyDAGMutation(C->MF));
779 return DAG;
780}
781
782static ScheduleDAGInstrs *
784 const GCNSubtarget &ST = C->MF->getSubtarget<GCNSubtarget>();
785 auto *DAG = new GCNIterativeScheduler(
787 DAG->addMutation(createLoadClusterDAGMutation(DAG->TII, DAG->TRI));
788 if (ST.shouldClusterStores())
789 DAG->addMutation(createStoreClusterDAGMutation(DAG->TII, DAG->TRI));
791 return DAG;
792}
793
800
801static ScheduleDAGInstrs *
803 const GCNSubtarget &ST = C->MF->getSubtarget<GCNSubtarget>();
805 DAG->addMutation(createLoadClusterDAGMutation(DAG->TII, DAG->TRI));
806 if (ST.shouldClusterStores())
807 DAG->addMutation(createStoreClusterDAGMutation(DAG->TII, DAG->TRI));
808 DAG->addMutation(createAMDGPUMacroFusionDAGMutation());
810 return DAG;
811}
812
813static MachineSchedRegistry
814SISchedRegistry("si", "Run SI's custom scheduler",
816
819 "Run GCN scheduler to maximize occupancy",
821
823 GCNMaxILPSchedRegistry("gcn-max-ilp", "Run GCN scheduler to maximize ilp",
825
827 "gcn-max-memory-clause", "Run GCN scheduler to maximize memory clause",
829
831 "gcn-iterative-max-occupancy-experimental",
832 "Run GCN scheduler to maximize occupancy (experimental)",
834
836 "gcn-iterative-minreg",
837 "Run GCN iterative scheduler for minimal register usage (experimental)",
839
841 "gcn-iterative-ilp",
842 "Run GCN iterative scheduler for ILP scheduling (experimental)",
844
847 if (!GPU.empty())
848 return GPU;
849
850 // Need to default to a target with flat support for HSA.
851 if (TT.isAMDGCN())
852 return TT.getOS() == Triple::AMDHSA ? "generic-hsa" : "generic";
853
854 return "r600";
855}
856
858 // The AMDGPU toolchain only supports generating shared objects, so we
859 // must always use PIC.
860 return Reloc::PIC_;
861}
862
864 StringRef CPU, StringRef FS,
865 const TargetOptions &Options,
866 std::optional<Reloc::Model> RM,
867 std::optional<CodeModel::Model> CM,
870 T, TT.computeDataLayout(), TT, getGPUOrDefault(TT, CPU), FS, Options,
872 OptLevel),
874 initAsmInfo();
875 if (TT.isAMDGCN()) {
876 if (getMCSubtargetInfo().checkFeatures("+wavefrontsize64"))
878 else if (getMCSubtargetInfo().checkFeatures("+wavefrontsize32"))
880 }
881}
882
886
888
890 Attribute GPUAttr = F.getFnAttribute("target-cpu");
891 return GPUAttr.isValid() ? GPUAttr.getValueAsString() : getTargetCPU();
892}
893
895 Attribute FSAttr = F.getFnAttribute("target-features");
896
897 return FSAttr.isValid() ? FSAttr.getValueAsString()
899}
900
903 const GCNSubtarget &ST = C->MF->getSubtarget<GCNSubtarget>();
905 DAG->addMutation(createLoadClusterDAGMutation(DAG->TII, DAG->TRI));
906 if (ST.shouldClusterStores())
907 DAG->addMutation(createStoreClusterDAGMutation(DAG->TII, DAG->TRI));
908 return DAG;
909}
910
911/// Predicate for Internalize pass.
912static bool mustPreserveGV(const GlobalValue &GV) {
913 if (const Function *F = dyn_cast<Function>(&GV))
914 return F->isDeclaration() || F->getName().starts_with("__asan_") ||
915 F->getName().starts_with("__sanitizer_") ||
916 AMDGPU::isEntryFunctionCC(F->getCallingConv());
917
919 return !GV.use_empty();
920}
921
926
929 if (Params.empty())
931 Params.consume_front("strategy=");
932 auto Result = StringSwitch<std::optional<ScanOptions>>(Params)
933 .Case("dpp", ScanOptions::DPP)
934 .Cases({"iterative", ""}, ScanOptions::Iterative)
935 .Case("none", ScanOptions::None)
936 .Default(std::nullopt);
937 if (Result)
938 return *Result;
939 return make_error<StringError>("invalid parameter", inconvertibleErrorCode());
940}
941
945 while (!Params.empty()) {
946 StringRef ParamName;
947 std::tie(ParamName, Params) = Params.split(';');
948 if (ParamName == "closed-world") {
949 Result.IsClosedWorld = true;
950 } else {
952 formatv("invalid AMDGPUAttributor pass parameter '{0}' ", ParamName)
953 .str(),
955 }
956 }
957 return Result;
958}
959
961
962#define GET_PASS_REGISTRY "AMDGPUPassRegistry.def"
964
965 PB.registerPipelineParsingCallback(
966 [this](StringRef Name, CGSCCPassManager &PM,
968 if (Name == "amdgpu-attributor-cgscc" && getTargetTriple().isAMDGCN()) {
970 *static_cast<GCNTargetMachine *>(this)));
971 return true;
972 }
973 return false;
974 });
975
976 PB.registerScalarOptimizerLateEPCallback(
977 [](FunctionPassManager &FPM, OptimizationLevel Level) {
978 if (Level == OptimizationLevel::O0)
979 return;
980
982 });
983
984 PB.registerVectorizerEndEPCallback(
985 [](FunctionPassManager &FPM, OptimizationLevel Level) {
986 if (Level == OptimizationLevel::O0)
987 return;
988
990 });
991
992 PB.registerPipelineEarlySimplificationEPCallback(
993 [this](ModulePassManager &PM, OptimizationLevel Level,
995 if (!isLTOPreLink(Phase) && getTargetTriple().isAMDGCN()) {
996 // When we are not using -fgpu-rdc, we can run accelerator code
997 // selection relatively early, but still after linking to prevent
998 // eager removal of potentially reachable symbols.
999 if (EnableHipStdPar) {
1002 }
1003
1005 }
1006
1007 if (Level == OptimizationLevel::O0)
1008 return;
1009
1010 // We don't want to run internalization at per-module stage.
1013 PM.addPass(GlobalDCEPass());
1014 }
1015
1018 });
1019
1020 PB.registerPeepholeEPCallback(
1021 [](FunctionPassManager &FPM, OptimizationLevel Level) {
1022 if (Level == OptimizationLevel::O0)
1023 return;
1024
1028
1031 });
1032
1033 PB.registerCGSCCOptimizerLateEPCallback(
1034 [this](CGSCCPassManager &PM, OptimizationLevel Level) {
1035 if (Level == OptimizationLevel::O0)
1036 return;
1037
1039
1040 // Add promote kernel arguments pass to the opt pipeline right before
1041 // infer address spaces which is needed to do actual address space
1042 // rewriting.
1043 if (Level.getSpeedupLevel() > OptimizationLevel::O1.getSpeedupLevel() &&
1046
1047 // Add infer address spaces pass to the opt pipeline after inlining
1048 // but before SROA to increase SROA opportunities.
1050
1051 // This should run after inlining to have any chance of doing
1052 // anything, and before other cleanup optimizations.
1054
1055 // Promote alloca to vector before SROA and loop unroll. If we
1056 // manage to eliminate allocas before unroll we may choose to unroll
1057 // less.
1059
1060 PM.addPass(createCGSCCToFunctionPassAdaptor(std::move(FPM)));
1061 });
1062
1063 // FIXME: Why is AMDGPUAttributor not in CGSCC?
1064 PB.registerOptimizerLastEPCallback([this](ModulePassManager &MPM,
1065 OptimizationLevel Level,
1067 if (Level != OptimizationLevel::O0) {
1068 if (!isLTOPreLink(Phase)) {
1069 if (EnableAMDGPUAttributor && getTargetTriple().isAMDGCN()) {
1071 MPM.addPass(AMDGPUAttributorPass(*this, Opts, Phase));
1072 }
1073 }
1074 }
1075 });
1076
1077 PB.registerFullLinkTimeOptimizationLastEPCallback(
1078 [this](ModulePassManager &PM, OptimizationLevel Level) {
1079 // When we are using -fgpu-rdc, we can only run accelerator code
1080 // selection after linking to prevent, otherwise we end up removing
1081 // potentially reachable symbols that were exported as external in other
1082 // modules.
1083 if (EnableHipStdPar) {
1086 }
1087 // We want to support the -lto-partitions=N option as "best effort".
1088 // For that, we need to lower LDS earlier in the pipeline before the
1089 // module is partitioned for codegen.
1092 if (EnableSwLowerLDS)
1096 if (Level != OptimizationLevel::O0) {
1097 // We only want to run this with O2 or higher since inliner and SROA
1098 // don't run in O1.
1099 if (Level != OptimizationLevel::O1) {
1100 PM.addPass(
1102 }
1103 // Do we really need internalization in LTO?
1104 if (InternalizeSymbols) {
1106 PM.addPass(GlobalDCEPass());
1107 }
1108 if (EnableAMDGPUAttributor && getTargetTriple().isAMDGCN()) {
1111 Opt.IsClosedWorld = true;
1114 }
1115 }
1116 if (!NoKernelInfoEndLTO) {
1118 FPM.addPass(KernelInfoPrinter(this));
1119 PM.addPass(createModuleToFunctionPassAdaptor(std::move(FPM)));
1120 }
1121 });
1122
1123 PB.registerRegClassFilterParsingCallback(
1124 [](StringRef FilterName) -> RegAllocFilterFunc {
1125 if (FilterName == "sgpr")
1126 return onlyAllocateSGPRs;
1127 if (FilterName == "vgpr")
1128 return onlyAllocateVGPRs;
1129 if (FilterName == "wwm")
1130 return onlyAllocateWWMRegs;
1131 return nullptr;
1132 });
1133}
1134
1136 unsigned DestAS) const {
1137 return AMDGPU::isFlatGlobalAddrSpace(SrcAS) &&
1139}
1140
1142 if (auto *Arg = dyn_cast<Argument>(V);
1143 Arg &&
1144 AMDGPU::isModuleEntryFunctionCC(Arg->getParent()->getCallingConv()) &&
1145 !Arg->hasByRefAttr())
1147
1148 const auto *LD = dyn_cast<LoadInst>(V);
1149 if (!LD) // TODO: Handle invariant load like constant.
1151
1152 // It must be a generic pointer loaded.
1153 assert(V->getType()->getPointerAddressSpace() == AMDGPUAS::FLAT_ADDRESS);
1154
1155 const auto *Ptr = LD->getPointerOperand();
1156 if (Ptr->getType()->getPointerAddressSpace() != AMDGPUAS::CONSTANT_ADDRESS)
1158 // For a generic pointer loaded from the constant memory, it could be assumed
1159 // as a global pointer since the constant memory is only populated on the
1160 // host side. As implied by the offload programming model, only global
1161 // pointers could be referenced on the host side.
1163}
1164
1165std::pair<const Value *, unsigned>
1167 if (auto *II = dyn_cast<IntrinsicInst>(V)) {
1168 switch (II->getIntrinsicID()) {
1169 case Intrinsic::amdgcn_is_shared:
1170 return std::pair(II->getArgOperand(0), AMDGPUAS::LOCAL_ADDRESS);
1171 case Intrinsic::amdgcn_is_private:
1172 return std::pair(II->getArgOperand(0), AMDGPUAS::PRIVATE_ADDRESS);
1173 default:
1174 break;
1175 }
1176 return std::pair(nullptr, -1);
1177 }
1178 // Check the global pointer predication based on
1179 // (!is_share(p) && !is_private(p)). Note that logic 'and' is commutative and
1180 // the order of 'is_shared' and 'is_private' is not significant.
1181 Value *Ptr;
1182 if (match(
1183 const_cast<Value *>(V),
1186 m_Deferred(Ptr))))))
1187 return std::pair(Ptr, AMDGPUAS::GLOBAL_ADDRESS);
1188
1189 return std::pair(nullptr, -1);
1190}
1191
1192unsigned
1207
1209 Module &M, unsigned NumParts,
1210 function_ref<void(std::unique_ptr<Module> MPart)> ModuleCallback) {
1211 // FIXME(?): Would be better to use an already existing Analysis/PassManager,
1212 // but all current users of this API don't have one ready and would need to
1213 // create one anyway. Let's hide the boilerplate for now to keep it simple.
1214
1219
1220 PassBuilder PB(this);
1221 PB.registerModuleAnalyses(MAM);
1222 PB.registerFunctionAnalyses(FAM);
1223 PB.crossRegisterProxies(LAM, FAM, CGAM, MAM);
1224
1226 MPM.addPass(AMDGPUSplitModulePass(NumParts, ModuleCallback));
1227 MPM.run(M, MAM);
1228 return true;
1229}
1230
1231//===----------------------------------------------------------------------===//
1232// GCN Target Machine (SI+)
1233//===----------------------------------------------------------------------===//
1234
1236 StringRef CPU, StringRef FS,
1237 const TargetOptions &Options,
1238 std::optional<Reloc::Model> RM,
1239 std::optional<CodeModel::Model> CM,
1240 CodeGenOptLevel OL, bool JIT)
1241 : AMDGPUTargetMachine(T, TT, CPU, FS, Options, RM, CM, OL) {}
1242
1243enum class OOBFlagValue {
1244 Any = 0,
1247};
1248
1249/// Returns the OOB mode encoded by a module flag.
1250/// An absent flag defaults to Any.
1251static OOBFlagValue getOOBFlagValue(const Module &M, StringRef FlagName) {
1252 const auto *Flag =
1253 mdconst::dyn_extract_or_null<ConstantInt>(M.getModuleFlag(FlagName));
1254 if (!Flag)
1255 return OOBFlagValue::Any;
1256 return static_cast<OOBFlagValue>(Flag->getZExtValue());
1257}
1258
1259const TargetSubtargetInfo *
1261 StringRef GPU = getGPUName(F);
1263
1264 const Module &M = *F.getParent();
1267 bool BufRelaxed = BufOOB == OOBFlagValue::Relaxed;
1268 bool TBufRelaxed = TBufOOB == OOBFlagValue::Relaxed;
1269 SmallString<128> SubtargetKey(GPU);
1270 SubtargetKey.append(FS);
1271 if (BufRelaxed)
1272 SubtargetKey.append(",buf-oob=1");
1273 if (TBufRelaxed)
1274 SubtargetKey.append(",tbuf-oob=1");
1275
1276 auto &I = SubtargetMap[SubtargetKey];
1277 if (!I) {
1278 I = std::make_unique<GCNSubtarget>(TargetTriple, GPU, FS, *this, BufRelaxed,
1279 TBufRelaxed);
1280 }
1281
1282 I->setScalarizeGlobalBehavior(ScalarizeGlobal);
1283
1284 return I.get();
1285}
1286
1289 return TargetTransformInfo(std::make_unique<GCNTTIImpl>(this, F));
1290}
1291
1294 raw_pwrite_stream *DwoOut, CodeGenFileType FileType,
1295 const CGPassBuilderOption &Opts, MCContext &Ctx,
1297 AMDGPUCodeGenPassBuilder CGPB(*this, Opts, PIC);
1298 return CGPB.buildPipeline(MPM, MAM, Out, DwoOut, FileType, Ctx);
1299}
1300
1303 const GCNSubtarget &ST = C->MF->getSubtarget<GCNSubtarget>();
1304 if (ST.enableSIScheduler())
1306
1307 StringRef SchedStrategy = AMDGPU::getSchedStrategy(C->MF->getFunction());
1308
1309 if (SchedStrategy == "max-ilp")
1311
1312 if (SchedStrategy == "max-memory-clause")
1314
1315 if (SchedStrategy == "iterative-ilp")
1317
1318 if (SchedStrategy == "iterative-minreg")
1319 return createMinRegScheduler(C);
1320
1321 if (SchedStrategy == "iterative-maxocc")
1323
1324 if (SchedStrategy == "coexec") {
1325 diagnoseUnsupportedCoExecSchedulerSelection(C->MF->getFunction(), ST);
1327 }
1328
1330}
1331
1334 if (useNoopPostScheduler(C->MF->getFunction()))
1336
1337 ScheduleDAGMI *DAG =
1338 new GCNPostScheduleDAGMILive(C, std::make_unique<PostGenericScheduler>(C),
1339 /*RemoveKillFlags=*/true);
1340 const GCNSubtarget &ST = C->MF->getSubtarget<GCNSubtarget>();
1342 if (ST.shouldClusterStores())
1345 if ((EnableVOPD.getNumOccurrences() ||
1347 EnableVOPD)
1352 return DAG;
1353}
1354//===----------------------------------------------------------------------===//
1355// AMDGPU Legacy Pass Setup
1356//===----------------------------------------------------------------------===//
1357
1358std::unique_ptr<CSEConfigBase> llvm::AMDGPUPassConfig::getCSEConfig() const {
1359 return getStandardCSEConfigForOpt(TM->getOptLevel());
1360}
1361
1362namespace {
1363
1364class GCNPassConfig final : public AMDGPUPassConfig {
1365public:
1366 GCNPassConfig(TargetMachine &TM, PassManagerBase &PM)
1367 : AMDGPUPassConfig(TM, PM) {
1368 substitutePass(&PostRASchedulerID, &PostMachineSchedulerID);
1369 }
1370
1371 GCNTargetMachine &getGCNTargetMachine() const {
1372 return getTM<GCNTargetMachine>();
1373 }
1374
1375 bool addPreISel() override;
1376 void addMachineSSAOptimization() override;
1377 bool addILPOpts() override;
1378 bool addInstSelector() override;
1379 bool addIRTranslator() override;
1380 void addPreLegalizeMachineIR() override;
1381 bool addLegalizeMachineIR() override;
1382 void addPreRegBankSelect() override;
1383 bool addRegBankSelect() override;
1384 void addPreGlobalInstructionSelect() override;
1385 bool addGlobalInstructionSelect() override;
1386 void addPreRegAlloc() override;
1387 void addFastRegAlloc() override;
1388 void addOptimizedRegAlloc() override;
1389
1390 FunctionPass *createSGPRAllocPass(bool Optimized);
1391 FunctionPass *createVGPRAllocPass(bool Optimized);
1392 FunctionPass *createWWMRegAllocPass(bool Optimized);
1393 FunctionPass *createRegAllocPass(bool Optimized) override;
1394
1395 bool addRegAssignAndRewriteFast() override;
1396 bool addRegAssignAndRewriteOptimized() override;
1397
1398 bool addPreRewrite() override;
1399 void addPostRegAlloc() override;
1400 void addPreSched2() override;
1401 void addPreEmitPass() override;
1402 void addPostBBSections() override;
1403};
1404
1405} // end anonymous namespace
1406
1408 : TargetPassConfig(TM, PM) {
1409 // Exceptions and StackMaps are not supported, so these passes will never do
1410 // anything.
1413 // Garbage collection is not supported.
1416}
1417
1424
1429 // ReassociateGEPs exposes more opportunities for SLSR. See
1430 // the example in reassociate-geps-and-slsr.ll.
1432 // SeparateConstOffsetFromGEP and SLSR creates common expressions which GVN or
1433 // EarlyCSE can reuse.
1435 // Run NaryReassociate after EarlyCSE/GVN to be more effective.
1437 // NaryReassociate on GEPs creates redundant common expressions, so run
1438 // EarlyCSE after it.
1440}
1441
1444
1445 if (RemoveIncompatibleFunctions && TM.getTargetTriple().isAMDGCN())
1447
1448 // There is no reason to run these.
1452
1453 if (TM.getTargetTriple().isAMDGCN())
1455
1456 if (LowerCtorDtor)
1458
1459 if (TM.getTargetTriple().isAMDGCN() &&
1462
1465
1466 // This can be disabled by passing ::Disable here or on the command line
1467 // with --expand-variadics-override=disable.
1469
1470 // Function calls are not supported, so make sure we inline everything.
1473
1474 // Handle uses of OpenCL image2d_t, image3d_t and sampler_t arguments.
1475 if (TM.getTargetTriple().getArch() == Triple::r600)
1477
1478 // Make enqueued block runtime handles externally visible.
1480
1481 // Lower special LDS accesses.
1484
1485 // Lower LDS accesses to global memory pass if address sanitizer is enabled.
1486 if (EnableSwLowerLDS)
1488
1489 // Runs before PromoteAlloca so the latter can account for function uses
1492 }
1493
1494 // Run atomic optimizer before Atomic Expand
1495 if ((TM.getTargetTriple().isAMDGCN()) &&
1496 (TM.getOptLevel() >= CodeGenOptLevel::Less) &&
1499 }
1500
1502
1503 if (TM.getOptLevel() > CodeGenOptLevel::None) {
1505
1508
1512 AAResults &AAR) {
1513 if (auto *WrapperPass = P.getAnalysisIfAvailable<AMDGPUAAWrapperPass>())
1514 AAR.addAAResult(WrapperPass->getResult());
1515 }));
1516 }
1517
1518 if (TM.getTargetTriple().isAMDGCN()) {
1519 // TODO: May want to move later or split into an early and late one.
1521 }
1522
1523 // Try to hoist loop invariant parts of divisions AMDGPUCodeGenPrepare may
1524 // have expanded.
1525 if (TM.getOptLevel() > CodeGenOptLevel::Less)
1527 }
1528
1530
1531 // EarlyCSE is not always strong enough to clean up what LSR produces. For
1532 // example, GVN can combine
1533 //
1534 // %0 = add %a, %b
1535 // %1 = add %b, %a
1536 //
1537 // and
1538 //
1539 // %0 = shl nsw %a, 2
1540 // %1 = shl %a, 2
1541 //
1542 // but EarlyCSE can do neither of them.
1545}
1546
1548 if (TM->getTargetTriple().isAMDGCN() &&
1549 TM->getOptLevel() > CodeGenOptLevel::None)
1551
1552 if (TM->getTargetTriple().isAMDGCN() && EnableLowerKernelArguments)
1554
1556
1559
1560 if (TM->getTargetTriple().isAMDGCN()) {
1561 // This lowering has been placed after codegenprepare to take advantage of
1562 // address mode matching (which is why it isn't put with the LDS lowerings).
1563 // It could be placed anywhere before uniformity annotations (an analysis
1564 // that it changes by splitting up fat pointers into their components)
1565 // but has been put before switch lowering and CFG flattening so that those
1566 // passes can run on the more optimized control flow this pass creates in
1567 // many cases.
1570 }
1571
1572 // LowerSwitch pass may introduce unreachable blocks that can
1573 // cause unexpected behavior for subsequent passes. Placing it
1574 // here seems better that these blocks would get cleaned up by
1575 // UnreachableBlockElim inserted next in the pass flow.
1577}
1578
1580 if (TM->getOptLevel() > CodeGenOptLevel::None)
1582 return false;
1583}
1584
1589
1591 // Do nothing. GC is not supported.
1592 return false;
1593}
1594
1595//===----------------------------------------------------------------------===//
1596// GCN Legacy Pass Setup
1597//===----------------------------------------------------------------------===//
1598
1599bool GCNPassConfig::addPreISel() {
1601
1602 if (TM->getOptLevel() > CodeGenOptLevel::None) {
1603 addPass(createSinkingPass());
1605 }
1606
1607 // Merge divergent exit nodes. StructurizeCFG won't recognize the multi-exit
1608 // regions formed by them.
1610 addPass(createFixIrreduciblePass());
1611 addPass(createUnifyLoopExitsPass());
1612 addPass(createStructurizeCFGPass(false)); // true -> SkipUniformRegions
1613
1616 // TODO: Move this right after structurizeCFG to avoid extra divergence
1617 // analysis. This depends on stopping SIAnnotateControlFlow from making
1618 // control flow modifications.
1620
1621 // SDAG requires LCSSA, GlobalISel does not. Disable LCSSA for -global-isel
1622 // without any of the fallback options.
1625 !isGlobalISelAbortEnabled())
1626 addPass(createLCSSAPass());
1627
1628 if (TM->getOptLevel() > CodeGenOptLevel::Less)
1630
1631 return false;
1632}
1633
1634void GCNPassConfig::addMachineSSAOptimization() {
1636
1637 // We want to fold operands after PeepholeOptimizer has run (or as part of
1638 // it), because it will eliminate extra copies making it easier to fold the
1639 // real source operand. We want to eliminate dead instructions after, so that
1640 // we see fewer uses of the copies. We then need to clean up the dead
1641 // instructions leftover after the operands are folded as well.
1642 //
1643 // XXX - Can we get away without running DeadMachineInstructionElim again?
1644 addPass(&SIFoldOperandsLegacyID);
1645 if (EnableDPPCombine)
1646 addPass(&GCNDPPCombineLegacyID);
1648 if (isPassEnabled(EnableSDWAPeephole)) {
1649 addPass(&SIPeepholeSDWALegacyID);
1650 addPass(&EarlyMachineLICMID);
1651 addPass(&MachineCSELegacyID);
1652 addPass(&SIFoldOperandsLegacyID);
1653 }
1656}
1657
1658bool GCNPassConfig::addILPOpts() {
1660 addPass(&EarlyIfConverterLegacyID);
1661
1663 return false;
1664}
1665
1666bool GCNPassConfig::addInstSelector() {
1668 addPass(&SIFixSGPRCopiesLegacyID);
1670 return false;
1671}
1672
1673bool GCNPassConfig::addIRTranslator() {
1674 addPass(new IRTranslator(getOptLevel()));
1675 return false;
1676}
1677
1678void GCNPassConfig::addPreLegalizeMachineIR() {
1679 bool IsOptNone = getOptLevel() == CodeGenOptLevel::None;
1680 addPass(createAMDGPUPreLegalizeCombiner(IsOptNone));
1681 addPass(new Localizer());
1682}
1683
1684bool GCNPassConfig::addLegalizeMachineIR() {
1685 addPass(new Legalizer());
1686 return false;
1687}
1688
1689void GCNPassConfig::addPreRegBankSelect() {
1690 bool IsOptNone = getOptLevel() == CodeGenOptLevel::None;
1691 addPass(createAMDGPUPostLegalizeCombiner(IsOptNone));
1693}
1694
1695bool GCNPassConfig::addRegBankSelect() {
1698 return false;
1699}
1700
1701void GCNPassConfig::addPreGlobalInstructionSelect() {
1702 bool IsOptNone = getOptLevel() == CodeGenOptLevel::None;
1703 addPass(createAMDGPURegBankCombiner(IsOptNone));
1704}
1705
1706bool GCNPassConfig::addGlobalInstructionSelect() {
1707 addPass(new InstructionSelect(getOptLevel()));
1708 return false;
1709}
1710
1711void GCNPassConfig::addFastRegAlloc() {
1712 // FIXME: We have to disable the verifier here because of PHIElimination +
1713 // TwoAddressInstructions disabling it.
1714
1715 // This must be run immediately after phi elimination and before
1716 // TwoAddressInstructions, otherwise the processing of the tied operand of
1717 // SI_ELSE will introduce a copy of the tied operand source after the else.
1719
1721
1723}
1724
1725void GCNPassConfig::addPreRegAlloc() {
1726 if (getOptLevel() != CodeGenOptLevel::None)
1728}
1729
1730void GCNPassConfig::addOptimizedRegAlloc() {
1731 if (EnableDCEInRA)
1733
1734 // FIXME: when an instruction has a Killed operand, and the instruction is
1735 // inside a bundle, seems only the BUNDLE instruction appears as the Kills of
1736 // the register in LiveVariables, this would trigger a failure in verifier,
1737 // we should fix it and enable the verifier.
1738 if (OptVGPRLiveRange)
1740
1741 // This must be run immediately after phi elimination and before
1742 // TwoAddressInstructions, otherwise the processing of the tied operand of
1743 // SI_ELSE will introduce a copy of the tied operand source after the else.
1745
1748
1749 if (isPassEnabled(EnablePreRAOptimizations))
1751
1752 // Allow the scheduler to run before SIWholeQuadMode inserts exec manipulation
1753 // instructions that cause scheduling barriers.
1755
1756 if (OptExecMaskPreRA)
1758
1759 // This is not an essential optimization and it has a noticeable impact on
1760 // compilation time, so we only enable it from O2.
1761 if (TM->getOptLevel() > CodeGenOptLevel::Less)
1763
1765}
1766
1767bool GCNPassConfig::addPreRewrite() {
1769 addPass(&GCNNSAReassignID);
1770
1772 return true;
1773}
1774
1775FunctionPass *GCNPassConfig::createSGPRAllocPass(bool Optimized) {
1776 // Initialize the global default.
1777 llvm::call_once(InitializeDefaultSGPRRegisterAllocatorFlag,
1778 initializeDefaultSGPRRegisterAllocatorOnce);
1779
1780 RegisterRegAlloc::FunctionPassCtor Ctor = SGPRRegisterRegAlloc::getDefault();
1781 if (Ctor != useDefaultRegisterAllocator)
1782 return Ctor();
1783
1784 if (Optimized)
1785 return createGreedyRegisterAllocator(onlyAllocateSGPRs);
1786
1787 return createFastRegisterAllocator(onlyAllocateSGPRs, false);
1788}
1789
1790FunctionPass *GCNPassConfig::createVGPRAllocPass(bool Optimized) {
1791 // Initialize the global default.
1792 llvm::call_once(InitializeDefaultVGPRRegisterAllocatorFlag,
1793 initializeDefaultVGPRRegisterAllocatorOnce);
1794
1795 RegisterRegAlloc::FunctionPassCtor Ctor = VGPRRegisterRegAlloc::getDefault();
1796 if (Ctor != useDefaultRegisterAllocator)
1797 return Ctor();
1798
1799 if (Optimized)
1800 return createGreedyVGPRRegisterAllocator();
1801
1802 return createFastVGPRRegisterAllocator();
1803}
1804
1805FunctionPass *GCNPassConfig::createWWMRegAllocPass(bool Optimized) {
1806 // Initialize the global default.
1807 llvm::call_once(InitializeDefaultWWMRegisterAllocatorFlag,
1808 initializeDefaultWWMRegisterAllocatorOnce);
1809
1810 RegisterRegAlloc::FunctionPassCtor Ctor = WWMRegisterRegAlloc::getDefault();
1811 if (Ctor != useDefaultRegisterAllocator)
1812 return Ctor();
1813
1814 if (Optimized)
1815 return createGreedyWWMRegisterAllocator();
1816
1817 return createFastWWMRegisterAllocator();
1818}
1819
1820FunctionPass *GCNPassConfig::createRegAllocPass(bool Optimized) {
1821 llvm_unreachable("should not be used");
1822}
1823
1825 "-regalloc not supported with amdgcn. Use -sgpr-regalloc, -wwm-regalloc, "
1826 "and -vgpr-regalloc";
1827
1828bool GCNPassConfig::addRegAssignAndRewriteFast() {
1829 if (!usingDefaultRegAlloc())
1831
1832 addPass(&GCNPreRALongBranchRegID);
1833
1834 addPass(createSGPRAllocPass(false));
1835
1836 // Equivalent of PEI for SGPRs.
1837 addPass(&SILowerSGPRSpillsLegacyID);
1838
1839 // To Allocate wwm registers used in whole quad mode operations (for shaders).
1841
1842 // For allocating other wwm register operands.
1843 addPass(createWWMRegAllocPass(false));
1844
1845 addPass(&SILowerWWMCopiesLegacyID);
1847
1848 // For allocating per-thread VGPRs.
1849 addPass(createVGPRAllocPass(false));
1850
1851 return true;
1852}
1853
1854bool GCNPassConfig::addRegAssignAndRewriteOptimized() {
1855 if (!usingDefaultRegAlloc())
1857
1858 addPass(&GCNPreRALongBranchRegID);
1859
1860 addPass(createSGPRAllocPass(true));
1861
1862 // Commit allocated register changes. This is mostly necessary because too
1863 // many things rely on the use lists of the physical registers, such as the
1864 // verifier. This is only necessary with allocators which use LiveIntervals,
1865 // since FastRegAlloc does the replacements itself.
1866 addPass(createVirtRegRewriter(false));
1867
1868 // At this point, the sgpr-regalloc has been done and it is good to have the
1869 // stack slot coloring to try to optimize the SGPR spill stack indices before
1870 // attempting the custom SGPR spill lowering.
1871 addPass(&StackSlotColoringID);
1872
1873 // Equivalent of PEI for SGPRs.
1874 addPass(&SILowerSGPRSpillsLegacyID);
1875
1876 // To Allocate wwm registers used in whole quad mode operations (for shaders).
1878
1879 // For allocating other whole wave mode registers.
1880 addPass(createWWMRegAllocPass(true));
1881 addPass(&SILowerWWMCopiesLegacyID);
1882 addPass(createVirtRegRewriter(false));
1884
1885 // For allocating per-thread VGPRs.
1886 addPass(createVGPRAllocPass(true));
1887
1888 addPreRewrite();
1889 addPass(&VirtRegRewriterID);
1890
1892
1893 return true;
1894}
1895
1896void GCNPassConfig::addPostRegAlloc() {
1897 addPass(&SIFixVGPRCopiesID);
1898 if (getOptLevel() > CodeGenOptLevel::None)
1901}
1902
1903void GCNPassConfig::addPreSched2() {
1904 if (TM->getOptLevel() > CodeGenOptLevel::None)
1906 addPass(&SIPostRABundlerLegacyID);
1907}
1908
1909void GCNPassConfig::addPreEmitPass() {
1910 if (isPassEnabled(EnableVOPD, CodeGenOptLevel::Less))
1911 addPass(&GCNCreateVOPDID);
1912 addPass(createSIMemoryLegalizerPass());
1913 addPass(createSIInsertWaitcntsPass());
1914
1915 addPass(createSIModeRegisterPass());
1916
1917 if (getOptLevel() > CodeGenOptLevel::None)
1918 addPass(&SIInsertHardClausesID);
1919
1921 if (isPassEnabled(EnableSetWavePriority, CodeGenOptLevel::Less))
1923 if (getOptLevel() > CodeGenOptLevel::None)
1924 addPass(&SIPreEmitPeepholeID);
1925 // The hazard recognizer that runs as part of the post-ra scheduler does not
1926 // guarantee to be able handle all hazards correctly. This is because if there
1927 // are multiple scheduling regions in a basic block, the regions are scheduled
1928 // bottom up, so when we begin to schedule a region we don't know what
1929 // instructions were emitted directly before it.
1930 //
1931 // Here we add a stand-alone hazard recognizer pass which can handle all
1932 // cases.
1933 addPass(&PostRAHazardRecognizerID);
1934
1936
1938
1939 if (isPassEnabled(EnableInsertDelayAlu, CodeGenOptLevel::Less))
1940 addPass(&AMDGPUInsertDelayAluID);
1941
1942 addPass(&BranchRelaxationPassID);
1943}
1944
1945void GCNPassConfig::addPostBBSections() {
1946 // We run this later to avoid passes like livedebugvalues and BBSections
1947 // having to deal with the apparent multi-entry functions we may generate.
1949}
1950
1952 return new GCNPassConfig(*this, PM);
1953}
1954
1960
1967
1971
1978
1981 SMDiagnostic &Error, SMRange &SourceRange) const {
1982 const yaml::SIMachineFunctionInfo &YamlMFI =
1983 static_cast<const yaml::SIMachineFunctionInfo &>(MFI_);
1984 MachineFunction &MF = PFS.MF;
1986 const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>();
1987
1988 if (MFI->initializeBaseYamlFields(YamlMFI, MF, PFS, Error, SourceRange))
1989 return true;
1990
1991 if (MFI->Occupancy == 0) {
1992 // Fixup the subtarget dependent default value.
1993 MFI->Occupancy = ST.getOccupancyWithWorkGroupSizes(MF).second;
1994 }
1995
1996 auto parseRegister = [&](const yaml::StringValue &RegName, Register &RegVal) {
1997 Register TempReg;
1998 if (parseNamedRegisterReference(PFS, TempReg, RegName.Value, Error)) {
1999 SourceRange = RegName.SourceRange;
2000 return true;
2001 }
2002 RegVal = TempReg;
2003
2004 return false;
2005 };
2006
2007 auto parseOptionalRegister = [&](const yaml::StringValue &RegName,
2008 Register &RegVal) {
2009 return !RegName.Value.empty() && parseRegister(RegName, RegVal);
2010 };
2011
2012 if (parseOptionalRegister(YamlMFI.VGPRForAGPRCopy, MFI->VGPRForAGPRCopy))
2013 return true;
2014
2015 if (parseOptionalRegister(YamlMFI.SGPRForEXECCopy, MFI->SGPRForEXECCopy))
2016 return true;
2017
2018 if (parseOptionalRegister(YamlMFI.LongBranchReservedReg,
2019 MFI->LongBranchReservedReg))
2020 return true;
2021
2022 auto diagnoseRegisterClass = [&](const yaml::StringValue &RegName) {
2023 // Create a diagnostic for a the register string literal.
2024 const MemoryBuffer &Buffer =
2025 *PFS.SM->getMemoryBuffer(PFS.SM->getMainFileID());
2026 Error = SMDiagnostic(*PFS.SM, SMLoc(), Buffer.getBufferIdentifier(), 1,
2027 RegName.Value.size(), SourceMgr::DK_Error,
2028 "incorrect register class for field", RegName.Value,
2029 {}, {});
2030 SourceRange = RegName.SourceRange;
2031 return true;
2032 };
2033
2034 if (parseRegister(YamlMFI.ScratchRSrcReg, MFI->ScratchRSrcReg) ||
2035 parseRegister(YamlMFI.FrameOffsetReg, MFI->FrameOffsetReg) ||
2036 parseRegister(YamlMFI.StackPtrOffsetReg, MFI->StackPtrOffsetReg))
2037 return true;
2038
2039 if (MFI->ScratchRSrcReg != AMDGPU::PRIVATE_RSRC_REG &&
2040 !AMDGPU::SGPR_128RegClass.contains(MFI->ScratchRSrcReg)) {
2041 return diagnoseRegisterClass(YamlMFI.ScratchRSrcReg);
2042 }
2043
2044 if (MFI->FrameOffsetReg != AMDGPU::FP_REG &&
2045 !AMDGPU::SGPR_32RegClass.contains(MFI->FrameOffsetReg)) {
2046 return diagnoseRegisterClass(YamlMFI.FrameOffsetReg);
2047 }
2048
2049 if (MFI->StackPtrOffsetReg != AMDGPU::SP_REG &&
2050 !AMDGPU::SGPR_32RegClass.contains(MFI->StackPtrOffsetReg)) {
2051 return diagnoseRegisterClass(YamlMFI.StackPtrOffsetReg);
2052 }
2053
2054 for (const auto &YamlReg : YamlMFI.WWMReservedRegs) {
2055 Register ParsedReg;
2056 if (parseRegister(YamlReg, ParsedReg))
2057 return true;
2058
2059 MFI->reserveWWMRegister(ParsedReg);
2060 }
2061
2062 for (const auto &[_, Info] : PFS.VRegInfosNamed) {
2063 MFI->setFlag(Info->VReg, Info->Flags);
2064 }
2065 for (const auto &[_, Info] : PFS.VRegInfos) {
2066 MFI->setFlag(Info->VReg, Info->Flags);
2067 }
2068
2069 for (const auto &YamlRegStr : YamlMFI.SpillPhysVGPRS) {
2070 Register ParsedReg;
2071 if (parseRegister(YamlRegStr, ParsedReg))
2072 return true;
2073 MFI->SpillPhysVGPRs.push_back(ParsedReg);
2074 }
2075
2076 auto parseAndCheckArgument = [&](const std::optional<yaml::SIArgument> &A,
2077 const TargetRegisterClass &RC,
2078 ArgDescriptor &Arg, unsigned UserSGPRs,
2079 unsigned SystemSGPRs) {
2080 // Skip parsing if it's not present.
2081 if (!A)
2082 return false;
2083
2084 if (A->IsRegister) {
2085 Register Reg;
2086 if (parseNamedRegisterReference(PFS, Reg, A->RegisterName.Value, Error)) {
2087 SourceRange = A->RegisterName.SourceRange;
2088 return true;
2089 }
2090 if (!RC.contains(Reg))
2091 return diagnoseRegisterClass(A->RegisterName);
2093 } else
2094 Arg = ArgDescriptor::createStack(A->StackOffset);
2095 // Check and apply the optional mask.
2096 if (A->Mask)
2097 Arg = ArgDescriptor::createArg(Arg, *A->Mask);
2098
2099 MFI->NumUserSGPRs += UserSGPRs;
2100 MFI->NumSystemSGPRs += SystemSGPRs;
2101 return false;
2102 };
2103
2104 if (YamlMFI.ArgInfo &&
2105 (parseAndCheckArgument(YamlMFI.ArgInfo->PrivateSegmentBuffer,
2106 AMDGPU::SGPR_128RegClass,
2107 MFI->ArgInfo.PrivateSegmentBuffer, 4, 0) ||
2108 parseAndCheckArgument(YamlMFI.ArgInfo->DispatchPtr,
2109 AMDGPU::SReg_64RegClass, MFI->ArgInfo.DispatchPtr,
2110 2, 0) ||
2111 parseAndCheckArgument(YamlMFI.ArgInfo->QueuePtr, AMDGPU::SReg_64RegClass,
2112 MFI->ArgInfo.QueuePtr, 2, 0) ||
2113 parseAndCheckArgument(YamlMFI.ArgInfo->KernargSegmentPtr,
2114 AMDGPU::SReg_64RegClass,
2115 MFI->ArgInfo.KernargSegmentPtr, 2, 0) ||
2116 parseAndCheckArgument(YamlMFI.ArgInfo->DispatchID,
2117 AMDGPU::SReg_64RegClass, MFI->ArgInfo.DispatchID,
2118 2, 0) ||
2119 parseAndCheckArgument(YamlMFI.ArgInfo->FlatScratchInit,
2120 AMDGPU::SReg_64RegClass,
2121 MFI->ArgInfo.FlatScratchInit, 2, 0) ||
2122 parseAndCheckArgument(YamlMFI.ArgInfo->PrivateSegmentSize,
2123 AMDGPU::SGPR_32RegClass,
2124 MFI->ArgInfo.PrivateSegmentSize, 0, 0) ||
2125 parseAndCheckArgument(YamlMFI.ArgInfo->LDSKernelId,
2126 AMDGPU::SGPR_32RegClass,
2127 MFI->ArgInfo.LDSKernelId, 0, 1) ||
2128 parseAndCheckArgument(YamlMFI.ArgInfo->WorkGroupIDX,
2129 AMDGPU::SGPR_32RegClass, MFI->ArgInfo.WorkGroupIDX,
2130 0, 1) ||
2131 parseAndCheckArgument(YamlMFI.ArgInfo->WorkGroupIDY,
2132 AMDGPU::SGPR_32RegClass, MFI->ArgInfo.WorkGroupIDY,
2133 0, 1) ||
2134 parseAndCheckArgument(YamlMFI.ArgInfo->WorkGroupIDZ,
2135 AMDGPU::SGPR_32RegClass, MFI->ArgInfo.WorkGroupIDZ,
2136 0, 1) ||
2137 parseAndCheckArgument(YamlMFI.ArgInfo->WorkGroupInfo,
2138 AMDGPU::SGPR_32RegClass,
2139 MFI->ArgInfo.WorkGroupInfo, 0, 1) ||
2140 parseAndCheckArgument(YamlMFI.ArgInfo->PrivateSegmentWaveByteOffset,
2141 AMDGPU::SGPR_32RegClass,
2142 MFI->ArgInfo.PrivateSegmentWaveByteOffset, 0, 1) ||
2143 parseAndCheckArgument(YamlMFI.ArgInfo->ImplicitArgPtr,
2144 AMDGPU::SReg_64RegClass,
2145 MFI->ArgInfo.ImplicitArgPtr, 0, 0) ||
2146 parseAndCheckArgument(YamlMFI.ArgInfo->ImplicitBufferPtr,
2147 AMDGPU::SReg_64RegClass,
2148 MFI->ArgInfo.ImplicitBufferPtr, 2, 0) ||
2149 parseAndCheckArgument(YamlMFI.ArgInfo->WorkItemIDX,
2150 AMDGPU::VGPR_32RegClass,
2151 MFI->ArgInfo.WorkItemIDX, 0, 0) ||
2152 parseAndCheckArgument(YamlMFI.ArgInfo->WorkItemIDY,
2153 AMDGPU::VGPR_32RegClass,
2154 MFI->ArgInfo.WorkItemIDY, 0, 0) ||
2155 parseAndCheckArgument(YamlMFI.ArgInfo->WorkItemIDZ,
2156 AMDGPU::VGPR_32RegClass,
2157 MFI->ArgInfo.WorkItemIDZ, 0, 0)))
2158 return true;
2159
2160 // Parse FirstKernArgPreloadReg separately, since it's a Register,
2161 // not ArgDescriptor.
2162 if (YamlMFI.ArgInfo && YamlMFI.ArgInfo->FirstKernArgPreloadReg) {
2163 const yaml::SIArgument &A = *YamlMFI.ArgInfo->FirstKernArgPreloadReg;
2164
2165 if (!A.IsRegister) {
2166 // For stack arguments, we don't have RegisterName.SourceRange,
2167 // but we should have some location info from the YAML parser
2168 const MemoryBuffer &Buffer =
2169 *PFS.SM->getMemoryBuffer(PFS.SM->getMainFileID());
2170 // Create a minimal valid source range
2172 SMRange Range(Loc, Loc);
2173
2175 *PFS.SM, Loc, Buffer.getBufferIdentifier(), 1, 0, SourceMgr::DK_Error,
2176 "firstKernArgPreloadReg must be a register, not a stack location", "",
2177 {}, {});
2178
2179 SourceRange = Range;
2180 return true;
2181 }
2182
2183 Register Reg;
2184 if (parseNamedRegisterReference(PFS, Reg, A.RegisterName.Value, Error)) {
2185 SourceRange = A.RegisterName.SourceRange;
2186 return true;
2187 }
2188
2189 if (!AMDGPU::SGPR_32RegClass.contains(Reg))
2190 return diagnoseRegisterClass(A.RegisterName);
2191
2192 MFI->ArgInfo.FirstKernArgPreloadReg = Reg;
2193 MFI->NumUserSGPRs += YamlMFI.NumKernargPreloadSGPRs;
2194 }
2195
2196 if (ST.hasFeature(AMDGPU::FeatureDX10ClampAndIEEEMode)) {
2197 MFI->Mode.IEEE = YamlMFI.Mode.IEEE;
2198 MFI->Mode.DX10Clamp = YamlMFI.Mode.DX10Clamp;
2199 }
2200
2201 // FIXME: Move proper support for denormal-fp-math into base MachineFunction
2202 MFI->Mode.FP32Denormals.Input = YamlMFI.Mode.FP32InputDenormals
2205 MFI->Mode.FP32Denormals.Output = YamlMFI.Mode.FP32OutputDenormals
2208
2215
2216 if (YamlMFI.HasInitWholeWave)
2217 MFI->setInitWholeWave();
2218
2219 return false;
2220}
2221
2222//===----------------------------------------------------------------------===//
2223// AMDGPU CodeGen Pass Builder interface.
2224//===----------------------------------------------------------------------===//
2225
2226AMDGPUCodeGenPassBuilder::AMDGPUCodeGenPassBuilder(
2227 GCNTargetMachine &TM, const CGPassBuilderOption &Opts,
2229 : CodeGenPassBuilder(TM, Opts, PIC) {
2230 Opt.MISchedPostRA = true;
2231 Opt.RequiresCodeGenSCCOrder = true;
2232 // Exceptions and StackMaps are not supported, so these passes will never do
2233 // anything.
2234 // Garbage collection is not supported.
2235 disablePass<StackMapLivenessPass, FuncletLayoutPass, PatchableFunctionPass,
2237}
2238
2239void AMDGPUCodeGenPassBuilder::addIRPasses(PassManagerWrapper &PMW) const {
2240 if (RemoveIncompatibleFunctions && TM.getTargetTriple().isAMDGCN()) {
2241 flushFPMsToMPM(PMW);
2242 addModulePass(AMDGPURemoveIncompatibleFunctionsPass(TM), PMW);
2243 }
2244
2245 flushFPMsToMPM(PMW);
2246
2247 if (TM.getTargetTriple().isAMDGCN())
2248 addModulePass(AMDGPUPrintfRuntimeBindingPass(), PMW);
2249
2250 if (LowerCtorDtor)
2251 addModulePass(AMDGPUCtorDtorLoweringPass(), PMW);
2252
2253 if (isPassEnabled(EnableImageIntrinsicOptimizer))
2254 addFunctionPass(AMDGPUImageIntrinsicOptimizerPass(TM), PMW);
2255
2257 addFunctionPass(AMDGPUUniformIntrinsicCombinePass(), PMW);
2258 // This can be disabled by passing ::Disable here or on the command line
2259 // with --expand-variadics-override=disable.
2260 flushFPMsToMPM(PMW);
2262
2263 addModulePass(AMDGPUAlwaysInlinePass(), PMW);
2264 addModulePass(AlwaysInlinerPass(), PMW);
2265
2266 addModulePass(AMDGPUExportKernelRuntimeHandlesPass(), PMW);
2267
2269 addModulePass(AMDGPULowerExecSyncPass(), PMW);
2270
2271 if (EnableSwLowerLDS)
2272 addModulePass(AMDGPUSwLowerLDSPass(), PMW);
2273
2274 // Runs before PromoteAlloca so the latter can account for function uses
2276 addModulePass(AMDGPULowerModuleLDSPass(TM), PMW);
2277
2278 // Run atomic optimizer before Atomic Expand
2279 if (TM.getOptLevel() >= CodeGenOptLevel::Less &&
2281 addFunctionPass(
2283
2284 addFunctionPass(AtomicExpandPass(TM), PMW);
2285
2286 if (TM.getOptLevel() > CodeGenOptLevel::None) {
2287 addFunctionPass(AMDGPUPromoteAllocaPass(TM), PMW);
2288 if (isPassEnabled(EnableScalarIRPasses))
2289 addStraightLineScalarOptimizationPasses(PMW);
2290
2291 // TODO: Handle EnableAMDGPUAliasAnalysis
2292
2293 // TODO: May want to move later or split into an early and late one.
2294 addFunctionPass(AMDGPUCodeGenPreparePass(TM), PMW);
2295
2296 // Try to hoist loop invariant parts of divisions AMDGPUCodeGenPrepare may
2297 // have expanded.
2298 if (TM.getOptLevel() > CodeGenOptLevel::Less) {
2300 /*UseMemorySSA=*/true),
2301 PMW);
2302 }
2303 }
2304
2305 Base::addIRPasses(PMW);
2306
2307 // EarlyCSE is not always strong enough to clean up what LSR produces. For
2308 // example, GVN can combine
2309 //
2310 // %0 = add %a, %b
2311 // %1 = add %b, %a
2312 //
2313 // and
2314 //
2315 // %0 = shl nsw %a, 2
2316 // %1 = shl %a, 2
2317 //
2318 // but EarlyCSE can do neither of them.
2319 if (isPassEnabled(EnableScalarIRPasses))
2320 addEarlyCSEOrGVNPass(PMW);
2321}
2322
2323void AMDGPUCodeGenPassBuilder::addCodeGenPrepare(
2324 PassManagerWrapper &PMW) const {
2325 if (TM.getOptLevel() > CodeGenOptLevel::None) {
2326 flushFPMsToMPM(PMW);
2327 addModulePass(AMDGPUPreloadKernelArgumentsPass(TM), PMW);
2328 }
2329
2331 addFunctionPass(AMDGPULowerKernelArgumentsPass(TM), PMW);
2332
2333 Base::addCodeGenPrepare(PMW);
2334
2335 if (isPassEnabled(EnableLoadStoreVectorizer))
2336 addFunctionPass(LoadStoreVectorizerPass(), PMW);
2337
2338 // This lowering has been placed after codegenprepare to take advantage of
2339 // address mode matching (which is why it isn't put with the LDS lowerings).
2340 // It could be placed anywhere before uniformity annotations (an analysis
2341 // that it changes by splitting up fat pointers into their components)
2342 // but has been put before switch lowering and CFG flattening so that those
2343 // passes can run on the more optimized control flow this pass creates in
2344 // many cases.
2345 flushFPMsToMPM(PMW);
2346 addModulePass(AMDGPULowerBufferFatPointersPass(TM), PMW);
2347 flushFPMsToMPM(PMW);
2348 requireCGSCCOrder(PMW);
2349
2350 addModulePass(AMDGPULowerIntrinsicsPass(TM), PMW);
2351
2352 // LowerSwitch pass may introduce unreachable blocks that can cause unexpected
2353 // behavior for subsequent passes. Placing it here seems better that these
2354 // blocks would get cleaned up by UnreachableBlockElim inserted next in the
2355 // pass flow.
2356 addFunctionPass(LowerSwitchPass(), PMW);
2357}
2358
2359void AMDGPUCodeGenPassBuilder::addPreISel(PassManagerWrapper &PMW) const {
2360
2361 if (TM.getOptLevel() > CodeGenOptLevel::None) {
2362 addFunctionPass(FlattenCFGPass(), PMW);
2363 addFunctionPass(SinkingPass(), PMW);
2364 addFunctionPass(AMDGPULateCodeGenPreparePass(TM), PMW);
2365 }
2366
2367 // Merge divergent exit nodes. StructurizeCFG won't recognize the multi-exit
2368 // regions formed by them.
2369
2370 addFunctionPass(AMDGPUUnifyDivergentExitNodesPass(), PMW);
2371 addFunctionPass(FixIrreduciblePass(), PMW);
2372 addFunctionPass(UnifyLoopExitsPass(), PMW);
2373 addFunctionPass(StructurizeCFGPass(/*SkipUniformRegions=*/false), PMW);
2374
2375 addFunctionPass(AMDGPUAnnotateUniformValuesPass(), PMW);
2376
2377 addFunctionPass(SIAnnotateControlFlowPass(TM), PMW);
2378
2379 // TODO: Move this right after structurizeCFG to avoid extra divergence
2380 // analysis. This depends on stopping SIAnnotateControlFlow from making
2381 // control flow modifications.
2382 addFunctionPass(AMDGPURewriteUndefForPHIPass(), PMW);
2383
2386 !isGlobalISelAbortEnabled())
2387 addFunctionPass(LCSSAPass(), PMW);
2388
2389 if (TM.getOptLevel() > CodeGenOptLevel::Less) {
2390 flushFPMsToMPM(PMW);
2391 addModulePass(AMDGPUPerfHintAnalysisPass(TM), PMW);
2392 }
2393
2394 // FIXME: Why isn't this queried as required from AMDGPUISelDAGToDAG, and why
2395 // isn't this in addInstSelector?
2397 /*Force=*/true);
2398}
2399
2400void AMDGPUCodeGenPassBuilder::addILPOpts(PassManagerWrapper &PMW) const {
2402 addMachineFunctionPass(EarlyIfConverterPass(), PMW);
2403
2404 Base::addILPOpts(PMW);
2405}
2406
2407void AMDGPUCodeGenPassBuilder::addAsmPrinterBegin(
2408 PassManagerWrapper &PMW) const {
2409 // TODO: Add AsmPrinterBegin
2410}
2411
2412void AMDGPUCodeGenPassBuilder::addAsmPrinter(PassManagerWrapper &PMW) const {
2413 // TODO: Add AsmPrinter.
2414}
2415
2416void AMDGPUCodeGenPassBuilder::addAsmPrinterEnd(PassManagerWrapper &PMW) const {
2417 // TODO: Add AsmPrinterEnd
2418}
2419
2420Error AMDGPUCodeGenPassBuilder::addInstSelector(PassManagerWrapper &PMW) const {
2421 addMachineFunctionPass(AMDGPUISelDAGToDAGPass(TM), PMW);
2422 addMachineFunctionPass(SIFixSGPRCopiesPass(), PMW);
2423 addMachineFunctionPass(SILowerI1CopiesPass(), PMW);
2424 return Error::success();
2425}
2426
2427void AMDGPUCodeGenPassBuilder::addPreRewrite(PassManagerWrapper &PMW) const {
2428 if (EnableRegReassign) {
2429 addMachineFunctionPass(GCNNSAReassignPass(), PMW);
2430 }
2431
2432 addMachineFunctionPass(AMDGPURewriteAGPRCopyMFMAPass(), PMW);
2433}
2434
2435void AMDGPUCodeGenPassBuilder::addMachineSSAOptimization(
2436 PassManagerWrapper &PMW) const {
2437 Base::addMachineSSAOptimization(PMW);
2438
2439 addMachineFunctionPass(SIFoldOperandsPass(), PMW);
2440 if (EnableDPPCombine) {
2441 addMachineFunctionPass(GCNDPPCombinePass(), PMW);
2442 }
2443 addMachineFunctionPass(SILoadStoreOptimizerPass(), PMW);
2444 if (isPassEnabled(EnableSDWAPeephole)) {
2445 addMachineFunctionPass(SIPeepholeSDWAPass(), PMW);
2446 addMachineFunctionPass(EarlyMachineLICMPass(), PMW);
2447 addMachineFunctionPass(MachineCSEPass(), PMW);
2448 addMachineFunctionPass(SIFoldOperandsPass(), PMW);
2449 }
2450 addMachineFunctionPass(DeadMachineInstructionElimPass(), PMW);
2451 addMachineFunctionPass(SIShrinkInstructionsPass(), PMW);
2452}
2453
2454Error AMDGPUCodeGenPassBuilder::addFastRegAlloc(PassManagerWrapper &PMW) const {
2455 insertPass<PHIEliminationPass>(SILowerControlFlowPass());
2456
2457 insertPass<TwoAddressInstructionPass>(SIWholeQuadModePass());
2458
2459 return Base::addFastRegAlloc(PMW);
2460}
2461
2462Error AMDGPUCodeGenPassBuilder::addRegAssignmentFast(
2463 PassManagerWrapper &PMW) const {
2464 if (auto Err = validateRegAllocOptions())
2465 return Err;
2466
2467 addMachineFunctionPass(GCNPreRALongBranchRegPass(), PMW);
2468
2469 // SGPR allocation - default to fast at -O0.
2470 if (SGPRRegAllocNPM == RegAllocType::Greedy)
2471 addMachineFunctionPass(RAGreedyPass({onlyAllocateSGPRs, "sgpr"}), PMW);
2472 else
2473 addMachineFunctionPass(RegAllocFastPass({onlyAllocateSGPRs, "sgpr", false}),
2474 PMW);
2475
2476 // Equivalent of PEI for SGPRs.
2477 addMachineFunctionPass(SILowerSGPRSpillsPass(), PMW);
2478
2479 // To Allocate wwm registers used in whole quad mode operations (for shaders).
2480 addMachineFunctionPass(SIPreAllocateWWMRegsPass(), PMW);
2481
2482 // WWM allocation - default to fast at -O0.
2483 if (WWMRegAllocNPM == RegAllocType::Greedy)
2484 addMachineFunctionPass(RAGreedyPass({onlyAllocateWWMRegs, "wwm"}), PMW);
2485 else
2486 addMachineFunctionPass(
2487 RegAllocFastPass({onlyAllocateWWMRegs, "wwm", false}), PMW);
2488
2489 addMachineFunctionPass(SILowerWWMCopiesPass(), PMW);
2490 addMachineFunctionPass(AMDGPUReserveWWMRegsPass(), PMW);
2491
2492 // VGPR allocation - default to fast at -O0.
2493 if (VGPRRegAllocNPM == RegAllocType::Greedy)
2494 addMachineFunctionPass(RAGreedyPass({onlyAllocateVGPRs, "vgpr"}), PMW);
2495 else
2496 addMachineFunctionPass(RegAllocFastPass({onlyAllocateVGPRs, "vgpr"}), PMW);
2497
2498 return Error::success();
2499}
2500
2501Error AMDGPUCodeGenPassBuilder::addOptimizedRegAlloc(
2502 PassManagerWrapper &PMW) const {
2503 if (EnableDCEInRA)
2504 insertPass<DetectDeadLanesPass>(DeadMachineInstructionElimPass());
2505
2506 // FIXME: when an instruction has a Killed operand, and the instruction is
2507 // inside a bundle, seems only the BUNDLE instruction appears as the Kills of
2508 // the register in LiveVariables, this would trigger a failure in verifier,
2509 // we should fix it and enable the verifier.
2510 if (OptVGPRLiveRange)
2511 insertPass<RequireAnalysisPass<LiveVariablesAnalysis, MachineFunction>>(
2513
2514 // This must be run immediately after phi elimination and before
2515 // TwoAddressInstructions, otherwise the processing of the tied operand of
2516 // SI_ELSE will introduce a copy of the tied operand source after the else.
2517 insertPass<PHIEliminationPass>(SILowerControlFlowPass());
2518
2520 insertPass<RenameIndependentSubregsPass>(GCNRewritePartialRegUsesPass());
2521
2522 if (isPassEnabled(EnablePreRAOptimizations))
2523 insertPass<MachineSchedulerPass>(GCNPreRAOptimizationsPass());
2524
2525 // Allow the scheduler to run before SIWholeQuadMode inserts exec manipulation
2526 // instructions that cause scheduling barriers.
2527 insertPass<MachineSchedulerPass>(SIWholeQuadModePass());
2528
2529 if (OptExecMaskPreRA)
2530 insertPass<MachineSchedulerPass>(SIOptimizeExecMaskingPreRAPass());
2531
2532 // This is not an essential optimization and it has a noticeable impact on
2533 // compilation time, so we only enable it from O2.
2534 if (TM.getOptLevel() > CodeGenOptLevel::Less)
2535 insertPass<MachineSchedulerPass>(SIFormMemoryClausesPass());
2536
2537 return Base::addOptimizedRegAlloc(PMW);
2538}
2539
2540void AMDGPUCodeGenPassBuilder::addPreRegAlloc(PassManagerWrapper &PMW) const {
2541 if (getOptLevel() != CodeGenOptLevel::None)
2542 addMachineFunctionPass(AMDGPUPrepareAGPRAllocPass(), PMW);
2543}
2544
2545Error AMDGPUCodeGenPassBuilder::addRegAssignmentOptimized(
2546 PassManagerWrapper &PMW) const {
2547 if (auto Err = validateRegAllocOptions())
2548 return Err;
2549
2550 addMachineFunctionPass(GCNPreRALongBranchRegPass(), PMW);
2551
2552 // SGPR allocation - default to greedy at -O1 and above.
2553 if (SGPRRegAllocNPM == RegAllocType::Fast)
2554 addMachineFunctionPass(RegAllocFastPass({onlyAllocateSGPRs, "sgpr", false}),
2555 PMW);
2556 else
2557 addMachineFunctionPass(RAGreedyPass({onlyAllocateSGPRs, "sgpr"}), PMW);
2558
2559 // Commit allocated register changes. This is mostly necessary because too
2560 // many things rely on the use lists of the physical registers, such as the
2561 // verifier. This is only necessary with allocators which use LiveIntervals,
2562 // since FastRegAlloc does the replacements itself.
2563 addMachineFunctionPass(VirtRegRewriterPass(false), PMW);
2564
2565 // At this point, the sgpr-regalloc has been done and it is good to have the
2566 // stack slot coloring to try to optimize the SGPR spill stack indices before
2567 // attempting the custom SGPR spill lowering.
2568 addMachineFunctionPass(StackSlotColoringPass(), PMW);
2569
2570 // Equivalent of PEI for SGPRs.
2571 addMachineFunctionPass(SILowerSGPRSpillsPass(), PMW);
2572
2573 // To Allocate wwm registers used in whole quad mode operations (for shaders).
2574 addMachineFunctionPass(SIPreAllocateWWMRegsPass(), PMW);
2575
2576 // WWM allocation - default to greedy at -O1 and above.
2577 if (WWMRegAllocNPM == RegAllocType::Fast)
2578 addMachineFunctionPass(
2579 RegAllocFastPass({onlyAllocateWWMRegs, "wwm", false}), PMW);
2580 else
2581 addMachineFunctionPass(RAGreedyPass({onlyAllocateWWMRegs, "wwm"}), PMW);
2582 addMachineFunctionPass(SILowerWWMCopiesPass(), PMW);
2583 addMachineFunctionPass(VirtRegRewriterPass(false), PMW);
2584 addMachineFunctionPass(AMDGPUReserveWWMRegsPass(), PMW);
2585
2586 // VGPR allocation - default to greedy at -O1 and above.
2587 if (VGPRRegAllocNPM == RegAllocType::Fast)
2588 addMachineFunctionPass(RegAllocFastPass({onlyAllocateVGPRs, "vgpr"}), PMW);
2589 else
2590 addMachineFunctionPass(RAGreedyPass({onlyAllocateVGPRs, "vgpr"}), PMW);
2591
2592 addPreRewrite(PMW);
2593 addMachineFunctionPass(VirtRegRewriterPass(true), PMW);
2594
2595 addMachineFunctionPass(AMDGPUMarkLastScratchLoadPass(), PMW);
2596 return Error::success();
2597}
2598
2599void AMDGPUCodeGenPassBuilder::addPostRegAlloc(PassManagerWrapper &PMW) const {
2600 addMachineFunctionPass(SIFixVGPRCopiesPass(), PMW);
2601 if (TM.getOptLevel() > CodeGenOptLevel::None)
2602 addMachineFunctionPass(SIOptimizeExecMaskingPass(), PMW);
2603 Base::addPostRegAlloc(PMW);
2604}
2605
2606void AMDGPUCodeGenPassBuilder::addPreSched2(PassManagerWrapper &PMW) const {
2607 if (TM.getOptLevel() > CodeGenOptLevel::None)
2608 addMachineFunctionPass(SIShrinkInstructionsPass(), PMW);
2609 addMachineFunctionPass(SIPostRABundlerPass(), PMW);
2610}
2611
2612void AMDGPUCodeGenPassBuilder::addPostBBSections(
2613 PassManagerWrapper &PMW) const {
2614 // We run this later to avoid passes like livedebugvalues and BBSections
2615 // having to deal with the apparent multi-entry functions we may generate.
2616 addMachineFunctionPass(AMDGPUPreloadKernArgPrologPass(), PMW);
2617}
2618
2619void AMDGPUCodeGenPassBuilder::addPreEmitPass(PassManagerWrapper &PMW) const {
2620 if (isPassEnabled(EnableVOPD, CodeGenOptLevel::Less)) {
2621 addMachineFunctionPass(GCNCreateVOPDPass(), PMW);
2622 }
2623
2624 addMachineFunctionPass(SIMemoryLegalizerPass(), PMW);
2625 addMachineFunctionPass(SIInsertWaitcntsPass(), PMW);
2626
2627 addMachineFunctionPass(SIModeRegisterPass(), PMW);
2628
2629 if (TM.getOptLevel() > CodeGenOptLevel::None)
2630 addMachineFunctionPass(SIInsertHardClausesPass(), PMW);
2631
2632 addMachineFunctionPass(SILateBranchLoweringPass(), PMW);
2633
2634 if (isPassEnabled(EnableSetWavePriority, CodeGenOptLevel::Less))
2635 addMachineFunctionPass(AMDGPUSetWavePriorityPass(), PMW);
2636
2637 if (TM.getOptLevel() > CodeGenOptLevel::None)
2638 addMachineFunctionPass(SIPreEmitPeepholePass(), PMW);
2639
2640 // The hazard recognizer that runs as part of the post-ra scheduler does not
2641 // guarantee to be able handle all hazards correctly. This is because if there
2642 // are multiple scheduling regions in a basic block, the regions are scheduled
2643 // bottom up, so when we begin to schedule a region we don't know what
2644 // instructions were emitted directly before it.
2645 //
2646 // Here we add a stand-alone hazard recognizer pass which can handle all
2647 // cases.
2648 addMachineFunctionPass(PostRAHazardRecognizerPass(), PMW);
2649 addMachineFunctionPass(AMDGPUWaitSGPRHazardsPass(), PMW);
2650 addMachineFunctionPass(AMDGPULowerVGPREncodingPass(), PMW);
2651
2652 if (isPassEnabled(EnableInsertDelayAlu, CodeGenOptLevel::Less)) {
2653 addMachineFunctionPass(AMDGPUInsertDelayAluPass(), PMW);
2654 }
2655
2656 addMachineFunctionPass(BranchRelaxationPass(), PMW);
2657}
2658
2659bool AMDGPUCodeGenPassBuilder::isPassEnabled(const cl::opt<bool> &Opt,
2660 CodeGenOptLevel Level) const {
2661 if (Opt.getNumOccurrences())
2662 return Opt;
2663 if (TM.getOptLevel() < Level)
2664 return false;
2665 return Opt;
2666}
2667
2668void AMDGPUCodeGenPassBuilder::addEarlyCSEOrGVNPass(
2669 PassManagerWrapper &PMW) const {
2670 if (TM.getOptLevel() == CodeGenOptLevel::Aggressive)
2671 addFunctionPass(GVNPass(), PMW);
2672 else
2673 addFunctionPass(EarlyCSEPass(), PMW);
2674}
2675
2676void AMDGPUCodeGenPassBuilder::addStraightLineScalarOptimizationPasses(
2677 PassManagerWrapper &PMW) const {
2679 addFunctionPass(LoopDataPrefetchPass(), PMW);
2680
2681 addFunctionPass(SeparateConstOffsetFromGEPPass(), PMW);
2682
2683 // ReassociateGEPs exposes more opportunities for SLSR. See
2684 // the example in reassociate-geps-and-slsr.ll.
2685 addFunctionPass(StraightLineStrengthReducePass(), PMW);
2686
2687 // SeparateConstOffsetFromGEP and SLSR creates common expressions which GVN or
2688 // EarlyCSE can reuse.
2689 addEarlyCSEOrGVNPass(PMW);
2690
2691 // Run NaryReassociate after EarlyCSE/GVN to be more effective.
2692 addFunctionPass(NaryReassociatePass(), PMW);
2693
2694 // NaryReassociate on GEPs creates redundant common expressions, so run
2695 // EarlyCSE after it.
2696 addFunctionPass(EarlyCSEPass(), PMW);
2697}
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 OOBFlagValue getOOBFlagValue(const Module &M, StringRef FlagName)
Returns the OOB mode encoded by a module flag.
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 > 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:854
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:317
#define LLVM_ABI
Definition Compiler.h:215
#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.
Module.h This file contains the declarations for the Module class.
This header defines various interfaces for pass management in LLVM.
#define RegName(no)
This file provides the interface for LLVM's Loop Data Prefetching Pass.
This header provides classes for managing a pipeline of passes over loops in LLVM IR.
#define F(x, y, z)
Definition MD5.cpp:54
#define I(x, y, z)
Definition MD5.cpp:57
Register Reg
Register const TargetRegisterInfo * TRI
#define T
ConstantRange Range(APInt(BitWidth, Low), APInt(BitWidth, High))
uint64_t IntrinsicInst * II
#define P(N)
CGSCCAnalysisManager CGAM
LoopAnalysisManager LAM
FunctionAnalysisManager FAM
ModuleAnalysisManager MAM
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:484
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".
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:131
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
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:303
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:151
const MemoryBuffer * getMemoryBuffer(unsigned i) const
Definition SourceMgr.h:144
Represent a constant reference to a string, i.e.
Definition StringRef.h:56
std::pair< StringRef, StringRef > split(char Separator) const
Split into two substrings around the first occurrence of a separator character.
Definition StringRef.h:736
constexpr bool empty() const
Check if the string is empty.
Definition StringRef.h:141
bool consume_front(char Prefix)
Returns true if this StringRef has the given prefix and removes that prefix.
Definition StringRef.h:661
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
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.
constexpr StringLiteral BufferFlag("amdgpu.buffer.oob.mode")
constexpr StringLiteral TBufferFlag("amdgpu.tbuffer.oob.mode")
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)
std::enable_if_t< detail::IsValidPointer< X, Y >::value, X * > dyn_extract_or_null(Y &&MD)
Extract a Value from Metadata, if any, allowing null.
Definition Metadata.h:709
This is an optimization pass for GlobalISel generic memory operations.
ScheduleDAGMILive * createSchedLive(MachineSchedContext *C)
Create the standard converging machine scheduler.
LLVM_ABI FunctionPass * createFlattenCFGPass()
ModulePass * createAMDGPUSwLowerLDSLegacyPass()
std::unique_ptr< ScheduleDAGMutation > createAMDGPUBarrierLatencyDAGMutation(MachineFunction *MF)
LLVM_ABI FunctionPass * createFastRegisterAllocator()
FastRegisterAllocation Pass - This pass register allocates as fast as possible.
LLVM_ABI char & EarlyMachineLICMID
This pass performs loop invariant code motion on machine instructions.
ImmutablePass * createAMDGPUAAWrapperPass()
LLVM_ABI char & PostRAHazardRecognizerID
PostRAHazardRecognizer - This pass runs the post-ra hazard recognizer.
std::function< bool(const TargetRegisterInfo &TRI, const MachineRegisterInfo &MRI, const Register Reg)> RegAllocFilterFunc
Filter function for register classes during regalloc.
FunctionPass * createAMDGPUSetWavePriorityPass()
LLVM_ABI Pass * createLCSSAPass()
Definition LCSSA.cpp: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 &)
FunctionPass * createSIAnnotateControlFlowLegacyPass()
Create the annotation pass.
FunctionPass * createSIModeRegisterPass()
void initializeGCNPreRAOptimizationsLegacyPass(PassRegistry &)
void initializeSILowerWWMCopiesLegacyPass(PassRegistry &)
LLVM_ABI FunctionPass * createGreedyRegisterAllocator()
Greedy register allocation pass - This pass implements a global register allocator for optimized buil...
void initializeAMDGPUAAWrapperPassPass(PassRegistry &)
void initializeSIShrinkInstructionsLegacyPass(PassRegistry &)
ModulePass * createAMDGPULowerBufferFatPointersPass()
void initializeR600ClauseMergePassPass(PassRegistry &)
ModulePass * createAMDGPUCtorDtorLoweringLegacyPass()
decltype(auto) dyn_cast(const From &Val)
dyn_cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:643
ModuleToFunctionPassAdaptor createModuleToFunctionPassAdaptor(FunctionPassT &&Pass, bool EagerlyInvalidate=false)
A function to deduce a function pass type and wrap it in the templated adaptor.
void initializeGCNRewritePartialRegUsesLegacyPass(llvm::PassRegistry &)
void initializeAMDGPURewriteUndefForPHILegacyPass(PassRegistry &)
char & GCNRewritePartialRegUsesID
void initializeAMDGPUSwLowerLDSLegacyPass(PassRegistry &)
LLVM_ABI std::error_code inconvertibleErrorCode()
The value returned by this function can be returned from convertToErrorCode for Error values where no...
Definition Error.cpp:94
void initializeAMDGPULowerVGPREncodingLegacyPass(PassRegistry &)
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 &)
LLVM_ABI ModulePass * createExpandVariadicsPass(ExpandVariadicsMode)
char & SILateBranchLoweringPassID
FunctionToLoopPassAdaptor createFunctionToLoopPassAdaptor(LoopPassT &&Pass, bool UseMemorySSA=false)
A function to deduce a loop pass type and wrap it in the templated adaptor.
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()
Definition GVN.cpp:4043
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:390
FunctionPass * createAMDGPUImageIntrinsicOptimizerPass(const TargetMachine *)
void initializeAMDGPULowerBufferFatPointersPass(PassRegistry &)
void initializeAMDGPUUnifyDivergentExitNodesLegacyPass(PassRegistry &)
FunctionPass * createSIInsertWaitcntsPass()
FunctionPass * createAMDGPUAnnotateUniformValuesLegacy()
LLVM_ABI FunctionPass * createEarlyCSEPass(bool UseMemorySSA=false)
void initializeSIWholeQuadModeLegacyPass(PassRegistry &)
LLVM_ABI char & PHIEliminationID
PHIElimination - This pass eliminates machine instruction PHI nodes by inserting copy instructions.
LLVM_ABI llvm::cl::opt< bool > NoKernelInfoEndLTO
LLVM_ABI bool parseNamedRegisterReference(PerFunctionMIParsingState &PFS, Register &Reg, StringRef Src, SMDiagnostic &Error)
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:179
DenseMap< Register, VRegInfo * > VRegInfos
Definition MIParser.h:178
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.