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 /// The AMDGPU target machine contains all of the hardware specific
11 /// information  needed to emit code for SI+ GPUs.
12 //
13 //===----------------------------------------------------------------------===//
14 
15 #include "AMDGPUTargetMachine.h"
16 #include "AMDGPU.h"
17 #include "AMDGPUAliasAnalysis.h"
18 #include "AMDGPUExportClustering.h"
19 #include "AMDGPUMacroFusion.h"
20 #include "AMDGPUTargetObjectFile.h"
21 #include "AMDGPUTargetTransformInfo.h"
22 #include "GCNIterativeScheduler.h"
23 #include "GCNSchedStrategy.h"
24 #include "R600.h"
25 #include "R600TargetMachine.h"
26 #include "SIMachineFunctionInfo.h"
27 #include "SIMachineScheduler.h"
28 #include "TargetInfo/AMDGPUTargetInfo.h"
29 #include "llvm/Analysis/CGSCCPassManager.h"
30 #include "llvm/CodeGen/GlobalISel/IRTranslator.h"
31 #include "llvm/CodeGen/GlobalISel/InstructionSelect.h"
32 #include "llvm/CodeGen/GlobalISel/Legalizer.h"
33 #include "llvm/CodeGen/GlobalISel/Localizer.h"
34 #include "llvm/CodeGen/GlobalISel/RegBankSelect.h"
35 #include "llvm/CodeGen/MIRParser/MIParser.h"
36 #include "llvm/CodeGen/Passes.h"
37 #include "llvm/CodeGen/RegAllocRegistry.h"
38 #include "llvm/CodeGen/TargetPassConfig.h"
39 #include "llvm/IR/LegacyPassManager.h"
40 #include "llvm/IR/PassManager.h"
41 #include "llvm/InitializePasses.h"
42 #include "llvm/MC/TargetRegistry.h"
43 #include "llvm/Passes/PassBuilder.h"
44 #include "llvm/Transforms/IPO.h"
45 #include "llvm/Transforms/IPO/AlwaysInliner.h"
46 #include "llvm/Transforms/IPO/GlobalDCE.h"
47 #include "llvm/Transforms/IPO/Internalize.h"
48 #include "llvm/Transforms/IPO/PassManagerBuilder.h"
49 #include "llvm/Transforms/Scalar.h"
50 #include "llvm/Transforms/Scalar/GVN.h"
51 #include "llvm/Transforms/Scalar/InferAddressSpaces.h"
52 #include "llvm/Transforms/Utils.h"
53 #include "llvm/Transforms/Utils/SimplifyLibCalls.h"
54 #include "llvm/Transforms/Vectorize.h"
55 
56 using namespace llvm;
57 
58 namespace {
59 class SGPRRegisterRegAlloc : public RegisterRegAllocBase<SGPRRegisterRegAlloc> {
60 public:
61   SGPRRegisterRegAlloc(const char *N, const char *D, FunctionPassCtor C)
62     : RegisterRegAllocBase(N, D, C) {}
63 };
64 
65 class VGPRRegisterRegAlloc : public RegisterRegAllocBase<VGPRRegisterRegAlloc> {
66 public:
67   VGPRRegisterRegAlloc(const char *N, const char *D, FunctionPassCtor C)
68     : RegisterRegAllocBase(N, D, C) {}
69 };
70 
71 static bool onlyAllocateSGPRs(const TargetRegisterInfo &TRI,
72                               const TargetRegisterClass &RC) {
73   return static_cast<const SIRegisterInfo &>(TRI).isSGPRClass(&RC);
74 }
75 
76 static bool onlyAllocateVGPRs(const TargetRegisterInfo &TRI,
77                               const TargetRegisterClass &RC) {
78   return !static_cast<const SIRegisterInfo &>(TRI).isSGPRClass(&RC);
79 }
80 
81 
82 /// -{sgpr|vgpr}-regalloc=... command line option.
83 static FunctionPass *useDefaultRegisterAllocator() { return nullptr; }
84 
85 /// A dummy default pass factory indicates whether the register allocator is
86 /// overridden on the command line.
87 static llvm::once_flag InitializeDefaultSGPRRegisterAllocatorFlag;
88 static llvm::once_flag InitializeDefaultVGPRRegisterAllocatorFlag;
89 
90 static SGPRRegisterRegAlloc
91 defaultSGPRRegAlloc("default",
92                     "pick SGPR register allocator based on -O option",
93                     useDefaultRegisterAllocator);
94 
95 static cl::opt<SGPRRegisterRegAlloc::FunctionPassCtor, false,
96                RegisterPassParser<SGPRRegisterRegAlloc>>
97 SGPRRegAlloc("sgpr-regalloc", cl::Hidden, cl::init(&useDefaultRegisterAllocator),
98              cl::desc("Register allocator to use for SGPRs"));
99 
100 static cl::opt<VGPRRegisterRegAlloc::FunctionPassCtor, false,
101                RegisterPassParser<VGPRRegisterRegAlloc>>
102 VGPRRegAlloc("vgpr-regalloc", cl::Hidden, cl::init(&useDefaultRegisterAllocator),
103              cl::desc("Register allocator to use for VGPRs"));
104 
105 
106 static void initializeDefaultSGPRRegisterAllocatorOnce() {
107   RegisterRegAlloc::FunctionPassCtor Ctor = SGPRRegisterRegAlloc::getDefault();
108 
109   if (!Ctor) {
110     Ctor = SGPRRegAlloc;
111     SGPRRegisterRegAlloc::setDefault(SGPRRegAlloc);
112   }
113 }
114 
115 static void initializeDefaultVGPRRegisterAllocatorOnce() {
116   RegisterRegAlloc::FunctionPassCtor Ctor = VGPRRegisterRegAlloc::getDefault();
117 
118   if (!Ctor) {
119     Ctor = VGPRRegAlloc;
120     VGPRRegisterRegAlloc::setDefault(VGPRRegAlloc);
121   }
122 }
123 
124 static FunctionPass *createBasicSGPRRegisterAllocator() {
125   return createBasicRegisterAllocator(onlyAllocateSGPRs);
126 }
127 
128 static FunctionPass *createGreedySGPRRegisterAllocator() {
129   return createGreedyRegisterAllocator(onlyAllocateSGPRs);
130 }
131 
132 static FunctionPass *createFastSGPRRegisterAllocator() {
133   return createFastRegisterAllocator(onlyAllocateSGPRs, false);
134 }
135 
136 static FunctionPass *createBasicVGPRRegisterAllocator() {
137   return createBasicRegisterAllocator(onlyAllocateVGPRs);
138 }
139 
140 static FunctionPass *createGreedyVGPRRegisterAllocator() {
141   return createGreedyRegisterAllocator(onlyAllocateVGPRs);
142 }
143 
144 static FunctionPass *createFastVGPRRegisterAllocator() {
145   return createFastRegisterAllocator(onlyAllocateVGPRs, true);
146 }
147 
148 static SGPRRegisterRegAlloc basicRegAllocSGPR(
149   "basic", "basic register allocator", createBasicSGPRRegisterAllocator);
150 static SGPRRegisterRegAlloc greedyRegAllocSGPR(
151   "greedy", "greedy register allocator", createGreedySGPRRegisterAllocator);
152 
153 static SGPRRegisterRegAlloc fastRegAllocSGPR(
154   "fast", "fast register allocator", createFastSGPRRegisterAllocator);
155 
156 
157 static VGPRRegisterRegAlloc basicRegAllocVGPR(
158   "basic", "basic register allocator", createBasicVGPRRegisterAllocator);
159 static VGPRRegisterRegAlloc greedyRegAllocVGPR(
160   "greedy", "greedy register allocator", createGreedyVGPRRegisterAllocator);
161 
162 static VGPRRegisterRegAlloc fastRegAllocVGPR(
163   "fast", "fast register allocator", createFastVGPRRegisterAllocator);
164 }
165 
166 static cl::opt<bool> EnableSROA(
167   "amdgpu-sroa",
168   cl::desc("Run SROA after promote alloca pass"),
169   cl::ReallyHidden,
170   cl::init(true));
171 
172 static cl::opt<bool>
173 EnableEarlyIfConversion("amdgpu-early-ifcvt", cl::Hidden,
174                         cl::desc("Run early if-conversion"),
175                         cl::init(false));
176 
177 static cl::opt<bool>
178 OptExecMaskPreRA("amdgpu-opt-exec-mask-pre-ra", cl::Hidden,
179             cl::desc("Run pre-RA exec mask optimizations"),
180             cl::init(true));
181 
182 // Option to disable vectorizer for tests.
183 static cl::opt<bool> EnableLoadStoreVectorizer(
184   "amdgpu-load-store-vectorizer",
185   cl::desc("Enable load store vectorizer"),
186   cl::init(true),
187   cl::Hidden);
188 
189 // Option to control global loads scalarization
190 static cl::opt<bool> ScalarizeGlobal(
191   "amdgpu-scalarize-global-loads",
192   cl::desc("Enable global load scalarization"),
193   cl::init(true),
194   cl::Hidden);
195 
196 // Option to run internalize pass.
197 static cl::opt<bool> InternalizeSymbols(
198   "amdgpu-internalize-symbols",
199   cl::desc("Enable elimination of non-kernel functions and unused globals"),
200   cl::init(false),
201   cl::Hidden);
202 
203 // Option to inline all early.
204 static cl::opt<bool> EarlyInlineAll(
205   "amdgpu-early-inline-all",
206   cl::desc("Inline all functions early"),
207   cl::init(false),
208   cl::Hidden);
209 
210 static cl::opt<bool> EnableSDWAPeephole(
211   "amdgpu-sdwa-peephole",
212   cl::desc("Enable SDWA peepholer"),
213   cl::init(true));
214 
215 static cl::opt<bool> EnableDPPCombine(
216   "amdgpu-dpp-combine",
217   cl::desc("Enable DPP combiner"),
218   cl::init(true));
219 
220 // Enable address space based alias analysis
221 static cl::opt<bool> EnableAMDGPUAliasAnalysis("enable-amdgpu-aa", cl::Hidden,
222   cl::desc("Enable AMDGPU Alias Analysis"),
223   cl::init(true));
224 
225 // Option to run late CFG structurizer
226 static cl::opt<bool, true> LateCFGStructurize(
227   "amdgpu-late-structurize",
228   cl::desc("Enable late CFG structurization"),
229   cl::location(AMDGPUTargetMachine::EnableLateStructurizeCFG),
230   cl::Hidden);
231 
232 static cl::opt<bool, true> EnableAMDGPUFixedFunctionABIOpt(
233   "amdgpu-fixed-function-abi",
234   cl::desc("Enable all implicit function arguments"),
235   cl::location(AMDGPUTargetMachine::EnableFixedFunctionABI),
236   cl::init(false),
237   cl::Hidden);
238 
239 // Enable lib calls simplifications
240 static cl::opt<bool> EnableLibCallSimplify(
241   "amdgpu-simplify-libcall",
242   cl::desc("Enable amdgpu library simplifications"),
243   cl::init(true),
244   cl::Hidden);
245 
246 static cl::opt<bool> EnableLowerKernelArguments(
247   "amdgpu-ir-lower-kernel-arguments",
248   cl::desc("Lower kernel argument loads in IR pass"),
249   cl::init(true),
250   cl::Hidden);
251 
252 static cl::opt<bool> EnableRegReassign(
253   "amdgpu-reassign-regs",
254   cl::desc("Enable register reassign optimizations on gfx10+"),
255   cl::init(true),
256   cl::Hidden);
257 
258 static cl::opt<bool> OptVGPRLiveRange(
259     "amdgpu-opt-vgpr-liverange",
260     cl::desc("Enable VGPR liverange optimizations for if-else structure"),
261     cl::init(true), cl::Hidden);
262 
263 // Enable atomic optimization
264 static cl::opt<bool> EnableAtomicOptimizations(
265   "amdgpu-atomic-optimizations",
266   cl::desc("Enable atomic optimizations"),
267   cl::init(false),
268   cl::Hidden);
269 
270 // Enable Mode register optimization
271 static cl::opt<bool> EnableSIModeRegisterPass(
272   "amdgpu-mode-register",
273   cl::desc("Enable mode register pass"),
274   cl::init(true),
275   cl::Hidden);
276 
277 // Option is used in lit tests to prevent deadcoding of patterns inspected.
278 static cl::opt<bool>
279 EnableDCEInRA("amdgpu-dce-in-ra",
280     cl::init(true), cl::Hidden,
281     cl::desc("Enable machine DCE inside regalloc"));
282 
283 static cl::opt<bool> EnableScalarIRPasses(
284   "amdgpu-scalar-ir-passes",
285   cl::desc("Enable scalar IR passes"),
286   cl::init(true),
287   cl::Hidden);
288 
289 static cl::opt<bool> EnableStructurizerWorkarounds(
290     "amdgpu-enable-structurizer-workarounds",
291     cl::desc("Enable workarounds for the StructurizeCFG pass"), cl::init(true),
292     cl::Hidden);
293 
294 static cl::opt<bool> EnableLDSReplaceWithPointer(
295     "amdgpu-enable-lds-replace-with-pointer",
296     cl::desc("Enable LDS replace with pointer pass"), cl::init(false),
297     cl::Hidden);
298 
299 static cl::opt<bool, true> EnableLowerModuleLDS(
300     "amdgpu-enable-lower-module-lds", cl::desc("Enable lower module lds pass"),
301     cl::location(AMDGPUTargetMachine::EnableLowerModuleLDS), cl::init(true),
302     cl::Hidden);
303 
304 static cl::opt<bool> EnablePreRAOptimizations(
305     "amdgpu-enable-pre-ra-optimizations",
306     cl::desc("Enable Pre-RA optimizations pass"), cl::init(true),
307     cl::Hidden);
308 
309 static cl::opt<bool> EnablePromoteKernelArguments(
310     "amdgpu-enable-promote-kernel-arguments",
311     cl::desc("Enable promotion of flat kernel pointer arguments to global"),
312     cl::Hidden, cl::init(true));
313 
314 extern "C" LLVM_EXTERNAL_VISIBILITY void LLVMInitializeAMDGPUTarget() {
315   // Register the target
316   RegisterTargetMachine<R600TargetMachine> X(getTheAMDGPUTarget());
317   RegisterTargetMachine<GCNTargetMachine> Y(getTheGCNTarget());
318 
319   PassRegistry *PR = PassRegistry::getPassRegistry();
320   initializeR600ClauseMergePassPass(*PR);
321   initializeR600ControlFlowFinalizerPass(*PR);
322   initializeR600PacketizerPass(*PR);
323   initializeR600ExpandSpecialInstrsPassPass(*PR);
324   initializeR600VectorRegMergerPass(*PR);
325   initializeGlobalISel(*PR);
326   initializeAMDGPUDAGToDAGISelPass(*PR);
327   initializeGCNDPPCombinePass(*PR);
328   initializeSILowerI1CopiesPass(*PR);
329   initializeSILowerSGPRSpillsPass(*PR);
330   initializeSIFixSGPRCopiesPass(*PR);
331   initializeSIFixVGPRCopiesPass(*PR);
332   initializeSIFoldOperandsPass(*PR);
333   initializeSIPeepholeSDWAPass(*PR);
334   initializeSIShrinkInstructionsPass(*PR);
335   initializeSIOptimizeExecMaskingPreRAPass(*PR);
336   initializeSIOptimizeVGPRLiveRangePass(*PR);
337   initializeSILoadStoreOptimizerPass(*PR);
338   initializeAMDGPUFixFunctionBitcastsPass(*PR);
339   initializeAMDGPUCtorDtorLoweringPass(*PR);
340   initializeAMDGPUAlwaysInlinePass(*PR);
341   initializeAMDGPUAttributorPass(*PR);
342   initializeAMDGPUAnnotateKernelFeaturesPass(*PR);
343   initializeAMDGPUAnnotateUniformValuesPass(*PR);
344   initializeAMDGPUArgumentUsageInfoPass(*PR);
345   initializeAMDGPUAtomicOptimizerPass(*PR);
346   initializeAMDGPULowerKernelArgumentsPass(*PR);
347   initializeAMDGPUPromoteKernelArgumentsPass(*PR);
348   initializeAMDGPULowerKernelAttributesPass(*PR);
349   initializeAMDGPULowerIntrinsicsPass(*PR);
350   initializeAMDGPUOpenCLEnqueuedBlockLoweringPass(*PR);
351   initializeAMDGPUPostLegalizerCombinerPass(*PR);
352   initializeAMDGPUPreLegalizerCombinerPass(*PR);
353   initializeAMDGPURegBankCombinerPass(*PR);
354   initializeAMDGPUPromoteAllocaPass(*PR);
355   initializeAMDGPUPromoteAllocaToVectorPass(*PR);
356   initializeAMDGPUCodeGenPreparePass(*PR);
357   initializeAMDGPULateCodeGenPreparePass(*PR);
358   initializeAMDGPUPropagateAttributesEarlyPass(*PR);
359   initializeAMDGPUPropagateAttributesLatePass(*PR);
360   initializeAMDGPUReplaceLDSUseWithPointerPass(*PR);
361   initializeAMDGPULowerModuleLDSPass(*PR);
362   initializeAMDGPURewriteOutArgumentsPass(*PR);
363   initializeAMDGPUUnifyMetadataPass(*PR);
364   initializeSIAnnotateControlFlowPass(*PR);
365   initializeSIInsertHardClausesPass(*PR);
366   initializeSIInsertWaitcntsPass(*PR);
367   initializeSIModeRegisterPass(*PR);
368   initializeSIWholeQuadModePass(*PR);
369   initializeSILowerControlFlowPass(*PR);
370   initializeSIPreEmitPeepholePass(*PR);
371   initializeSILateBranchLoweringPass(*PR);
372   initializeSIMemoryLegalizerPass(*PR);
373   initializeSIOptimizeExecMaskingPass(*PR);
374   initializeSIPreAllocateWWMRegsPass(*PR);
375   initializeSIFormMemoryClausesPass(*PR);
376   initializeSIPostRABundlerPass(*PR);
377   initializeAMDGPUUnifyDivergentExitNodesPass(*PR);
378   initializeAMDGPUAAWrapperPassPass(*PR);
379   initializeAMDGPUExternalAAWrapperPass(*PR);
380   initializeAMDGPUUseNativeCallsPass(*PR);
381   initializeAMDGPUSimplifyLibCallsPass(*PR);
382   initializeAMDGPUPrintfRuntimeBindingPass(*PR);
383   initializeAMDGPUResourceUsageAnalysisPass(*PR);
384   initializeGCNNSAReassignPass(*PR);
385   initializeGCNPreRAOptimizationsPass(*PR);
386 }
387 
388 static std::unique_ptr<TargetLoweringObjectFile> createTLOF(const Triple &TT) {
389   return std::make_unique<AMDGPUTargetObjectFile>();
390 }
391 
392 static ScheduleDAGInstrs *createSIMachineScheduler(MachineSchedContext *C) {
393   return new SIScheduleDAGMI(C);
394 }
395 
396 static ScheduleDAGInstrs *
397 createGCNMaxOccupancyMachineScheduler(MachineSchedContext *C) {
398   ScheduleDAGMILive *DAG =
399     new GCNScheduleDAGMILive(C, std::make_unique<GCNMaxOccupancySchedStrategy>(C));
400   DAG->addMutation(createLoadClusterDAGMutation(DAG->TII, DAG->TRI));
401   DAG->addMutation(createAMDGPUMacroFusionDAGMutation());
402   DAG->addMutation(createAMDGPUExportClusteringDAGMutation());
403   return DAG;
404 }
405 
406 static ScheduleDAGInstrs *
407 createIterativeGCNMaxOccupancyMachineScheduler(MachineSchedContext *C) {
408   auto DAG = new GCNIterativeScheduler(C,
409     GCNIterativeScheduler::SCHEDULE_LEGACYMAXOCCUPANCY);
410   DAG->addMutation(createLoadClusterDAGMutation(DAG->TII, DAG->TRI));
411   return DAG;
412 }
413 
414 static ScheduleDAGInstrs *createMinRegScheduler(MachineSchedContext *C) {
415   return new GCNIterativeScheduler(C,
416     GCNIterativeScheduler::SCHEDULE_MINREGFORCED);
417 }
418 
419 static ScheduleDAGInstrs *
420 createIterativeILPMachineScheduler(MachineSchedContext *C) {
421   auto DAG = new GCNIterativeScheduler(C,
422     GCNIterativeScheduler::SCHEDULE_ILP);
423   DAG->addMutation(createLoadClusterDAGMutation(DAG->TII, DAG->TRI));
424   DAG->addMutation(createAMDGPUMacroFusionDAGMutation());
425   return DAG;
426 }
427 
428 static MachineSchedRegistry
429 SISchedRegistry("si", "Run SI's custom scheduler",
430                 createSIMachineScheduler);
431 
432 static MachineSchedRegistry
433 GCNMaxOccupancySchedRegistry("gcn-max-occupancy",
434                              "Run GCN scheduler to maximize occupancy",
435                              createGCNMaxOccupancyMachineScheduler);
436 
437 static MachineSchedRegistry
438 IterativeGCNMaxOccupancySchedRegistry("gcn-max-occupancy-experimental",
439   "Run GCN scheduler to maximize occupancy (experimental)",
440   createIterativeGCNMaxOccupancyMachineScheduler);
441 
442 static MachineSchedRegistry
443 GCNMinRegSchedRegistry("gcn-minreg",
444   "Run GCN iterative scheduler for minimal register usage (experimental)",
445   createMinRegScheduler);
446 
447 static MachineSchedRegistry
448 GCNILPSchedRegistry("gcn-ilp",
449   "Run GCN iterative scheduler for ILP scheduling (experimental)",
450   createIterativeILPMachineScheduler);
451 
452 static StringRef computeDataLayout(const Triple &TT) {
453   if (TT.getArch() == Triple::r600) {
454     // 32-bit pointers.
455     return "e-p:32:32-i64:64-v16:16-v24:32-v32:32-v48:64-v96:128"
456            "-v192:256-v256:256-v512:512-v1024:1024-v2048:2048-n32:64-S32-A5-G1";
457   }
458 
459   // 32-bit private, local, and region pointers. 64-bit global, constant and
460   // flat, non-integral buffer fat pointers.
461   return "e-p:64:64-p1:64:64-p2:32:32-p3:32:32-p4:64:64-p5:32:32-p6:32:32"
462          "-i64:64-v16:16-v24:32-v32:32-v48:64-v96:128"
463          "-v192:256-v256:256-v512:512-v1024:1024-v2048:2048-n32:64-S32-A5-G1"
464          "-ni:7";
465 }
466 
467 LLVM_READNONE
468 static StringRef getGPUOrDefault(const Triple &TT, StringRef GPU) {
469   if (!GPU.empty())
470     return GPU;
471 
472   // Need to default to a target with flat support for HSA.
473   if (TT.getArch() == Triple::amdgcn)
474     return TT.getOS() == Triple::AMDHSA ? "generic-hsa" : "generic";
475 
476   return "r600";
477 }
478 
479 static Reloc::Model getEffectiveRelocModel(Optional<Reloc::Model> RM) {
480   // The AMDGPU toolchain only supports generating shared objects, so we
481   // must always use PIC.
482   return Reloc::PIC_;
483 }
484 
485 AMDGPUTargetMachine::AMDGPUTargetMachine(const Target &T, const Triple &TT,
486                                          StringRef CPU, StringRef FS,
487                                          TargetOptions Options,
488                                          Optional<Reloc::Model> RM,
489                                          Optional<CodeModel::Model> CM,
490                                          CodeGenOpt::Level OptLevel)
491     : LLVMTargetMachine(T, computeDataLayout(TT), TT, getGPUOrDefault(TT, CPU),
492                         FS, Options, getEffectiveRelocModel(RM),
493                         getEffectiveCodeModel(CM, CodeModel::Small), OptLevel),
494       TLOF(createTLOF(getTargetTriple())) {
495   initAsmInfo();
496   if (TT.getArch() == Triple::amdgcn) {
497     if (getMCSubtargetInfo()->checkFeatures("+wavefrontsize64"))
498       MRI.reset(llvm::createGCNMCRegisterInfo(AMDGPUDwarfFlavour::Wave64));
499     else if (getMCSubtargetInfo()->checkFeatures("+wavefrontsize32"))
500       MRI.reset(llvm::createGCNMCRegisterInfo(AMDGPUDwarfFlavour::Wave32));
501   }
502 }
503 
504 bool AMDGPUTargetMachine::EnableLateStructurizeCFG = false;
505 bool AMDGPUTargetMachine::EnableFunctionCalls = false;
506 bool AMDGPUTargetMachine::EnableFixedFunctionABI = false;
507 bool AMDGPUTargetMachine::EnableLowerModuleLDS = true;
508 
509 AMDGPUTargetMachine::~AMDGPUTargetMachine() = default;
510 
511 StringRef AMDGPUTargetMachine::getGPUName(const Function &F) const {
512   Attribute GPUAttr = F.getFnAttribute("target-cpu");
513   return GPUAttr.isValid() ? GPUAttr.getValueAsString() : getTargetCPU();
514 }
515 
516 StringRef AMDGPUTargetMachine::getFeatureString(const Function &F) const {
517   Attribute FSAttr = F.getFnAttribute("target-features");
518 
519   return FSAttr.isValid() ? FSAttr.getValueAsString()
520                           : getTargetFeatureString();
521 }
522 
523 /// Predicate for Internalize pass.
524 static bool mustPreserveGV(const GlobalValue &GV) {
525   if (const Function *F = dyn_cast<Function>(&GV))
526     return F->isDeclaration() || F->getName().startswith("__asan_") ||
527            F->getName().startswith("__sanitizer_") ||
528            AMDGPU::isEntryFunctionCC(F->getCallingConv());
529 
530   GV.removeDeadConstantUsers();
531   return !GV.use_empty();
532 }
533 
534 void AMDGPUTargetMachine::adjustPassManager(PassManagerBuilder &Builder) {
535   Builder.DivergentTarget = true;
536 
537   bool EnableOpt = getOptLevel() > CodeGenOpt::None;
538   bool Internalize = InternalizeSymbols;
539   bool EarlyInline = EarlyInlineAll && EnableOpt && !EnableFunctionCalls;
540   bool AMDGPUAA = EnableAMDGPUAliasAnalysis && EnableOpt;
541   bool LibCallSimplify = EnableLibCallSimplify && EnableOpt;
542   bool PromoteKernelArguments =
543       EnablePromoteKernelArguments && getOptLevel() > CodeGenOpt::Less;
544 
545   if (EnableFunctionCalls) {
546     delete Builder.Inliner;
547     Builder.Inliner = createFunctionInliningPass();
548   }
549 
550   Builder.addExtension(
551     PassManagerBuilder::EP_ModuleOptimizerEarly,
552     [Internalize, EarlyInline, AMDGPUAA, this](const PassManagerBuilder &,
553                                                legacy::PassManagerBase &PM) {
554       if (AMDGPUAA) {
555         PM.add(createAMDGPUAAWrapperPass());
556         PM.add(createAMDGPUExternalAAWrapperPass());
557       }
558       PM.add(createAMDGPUUnifyMetadataPass());
559       PM.add(createAMDGPUPrintfRuntimeBinding());
560       if (Internalize)
561         PM.add(createInternalizePass(mustPreserveGV));
562       PM.add(createAMDGPUPropagateAttributesLatePass(this));
563       if (Internalize)
564         PM.add(createGlobalDCEPass());
565       if (EarlyInline)
566         PM.add(createAMDGPUAlwaysInlinePass(false));
567   });
568 
569   Builder.addExtension(
570     PassManagerBuilder::EP_EarlyAsPossible,
571     [AMDGPUAA, LibCallSimplify, this](const PassManagerBuilder &,
572                                       legacy::PassManagerBase &PM) {
573       if (AMDGPUAA) {
574         PM.add(createAMDGPUAAWrapperPass());
575         PM.add(createAMDGPUExternalAAWrapperPass());
576       }
577       PM.add(llvm::createAMDGPUPropagateAttributesEarlyPass(this));
578       PM.add(llvm::createAMDGPUUseNativeCallsPass());
579       if (LibCallSimplify)
580         PM.add(llvm::createAMDGPUSimplifyLibCallsPass(this));
581   });
582 
583   Builder.addExtension(
584     PassManagerBuilder::EP_CGSCCOptimizerLate,
585     [EnableOpt, PromoteKernelArguments](const PassManagerBuilder &,
586                                         legacy::PassManagerBase &PM) {
587       // Add promote kernel arguments pass to the opt pipeline right before
588       // infer address spaces which is needed to do actual address space
589       // rewriting.
590       if (PromoteKernelArguments)
591         PM.add(createAMDGPUPromoteKernelArgumentsPass());
592 
593       // Add infer address spaces pass to the opt pipeline after inlining
594       // but before SROA to increase SROA opportunities.
595       PM.add(createInferAddressSpacesPass());
596 
597       // This should run after inlining to have any chance of doing anything,
598       // and before other cleanup optimizations.
599       PM.add(createAMDGPULowerKernelAttributesPass());
600 
601       // Promote alloca to vector before SROA and loop unroll. If we manage
602       // to eliminate allocas before unroll we may choose to unroll less.
603       if (EnableOpt)
604         PM.add(createAMDGPUPromoteAllocaToVector());
605   });
606 }
607 
608 void AMDGPUTargetMachine::registerDefaultAliasAnalyses(AAManager &AAM) {
609   AAM.registerFunctionAnalysis<AMDGPUAA>();
610 }
611 
612 void AMDGPUTargetMachine::registerPassBuilderCallbacks(PassBuilder &PB) {
613   PB.registerPipelineParsingCallback(
614       [this](StringRef PassName, ModulePassManager &PM,
615              ArrayRef<PassBuilder::PipelineElement>) {
616         if (PassName == "amdgpu-propagate-attributes-late") {
617           PM.addPass(AMDGPUPropagateAttributesLatePass(*this));
618           return true;
619         }
620         if (PassName == "amdgpu-unify-metadata") {
621           PM.addPass(AMDGPUUnifyMetadataPass());
622           return true;
623         }
624         if (PassName == "amdgpu-printf-runtime-binding") {
625           PM.addPass(AMDGPUPrintfRuntimeBindingPass());
626           return true;
627         }
628         if (PassName == "amdgpu-always-inline") {
629           PM.addPass(AMDGPUAlwaysInlinePass());
630           return true;
631         }
632         if (PassName == "amdgpu-replace-lds-use-with-pointer") {
633           PM.addPass(AMDGPUReplaceLDSUseWithPointerPass());
634           return true;
635         }
636         if (PassName == "amdgpu-lower-module-lds") {
637           PM.addPass(AMDGPULowerModuleLDSPass());
638           return true;
639         }
640         return false;
641       });
642   PB.registerPipelineParsingCallback(
643       [this](StringRef PassName, FunctionPassManager &PM,
644              ArrayRef<PassBuilder::PipelineElement>) {
645         if (PassName == "amdgpu-simplifylib") {
646           PM.addPass(AMDGPUSimplifyLibCallsPass(*this));
647           return true;
648         }
649         if (PassName == "amdgpu-usenative") {
650           PM.addPass(AMDGPUUseNativeCallsPass());
651           return true;
652         }
653         if (PassName == "amdgpu-promote-alloca") {
654           PM.addPass(AMDGPUPromoteAllocaPass(*this));
655           return true;
656         }
657         if (PassName == "amdgpu-promote-alloca-to-vector") {
658           PM.addPass(AMDGPUPromoteAllocaToVectorPass(*this));
659           return true;
660         }
661         if (PassName == "amdgpu-lower-kernel-attributes") {
662           PM.addPass(AMDGPULowerKernelAttributesPass());
663           return true;
664         }
665         if (PassName == "amdgpu-propagate-attributes-early") {
666           PM.addPass(AMDGPUPropagateAttributesEarlyPass(*this));
667           return true;
668         }
669         if (PassName == "amdgpu-promote-kernel-arguments") {
670           PM.addPass(AMDGPUPromoteKernelArgumentsPass());
671           return true;
672         }
673         return false;
674       });
675 
676   PB.registerAnalysisRegistrationCallback([](FunctionAnalysisManager &FAM) {
677     FAM.registerPass([&] { return AMDGPUAA(); });
678   });
679 
680   PB.registerParseAACallback([](StringRef AAName, AAManager &AAM) {
681     if (AAName == "amdgpu-aa") {
682       AAM.registerFunctionAnalysis<AMDGPUAA>();
683       return true;
684     }
685     return false;
686   });
687 
688   PB.registerPipelineStartEPCallback(
689       [this](ModulePassManager &PM, OptimizationLevel Level) {
690         FunctionPassManager FPM;
691         FPM.addPass(AMDGPUPropagateAttributesEarlyPass(*this));
692         FPM.addPass(AMDGPUUseNativeCallsPass());
693         if (EnableLibCallSimplify && Level != OptimizationLevel::O0)
694           FPM.addPass(AMDGPUSimplifyLibCallsPass(*this));
695         PM.addPass(createModuleToFunctionPassAdaptor(std::move(FPM)));
696       });
697 
698   PB.registerPipelineEarlySimplificationEPCallback(
699       [this](ModulePassManager &PM, OptimizationLevel Level) {
700         if (Level == OptimizationLevel::O0)
701           return;
702 
703         PM.addPass(AMDGPUUnifyMetadataPass());
704         PM.addPass(AMDGPUPrintfRuntimeBindingPass());
705 
706         if (InternalizeSymbols) {
707           PM.addPass(InternalizePass(mustPreserveGV));
708         }
709         PM.addPass(AMDGPUPropagateAttributesLatePass(*this));
710         if (InternalizeSymbols) {
711           PM.addPass(GlobalDCEPass());
712         }
713         if (EarlyInlineAll && !EnableFunctionCalls)
714           PM.addPass(AMDGPUAlwaysInlinePass());
715       });
716 
717   PB.registerCGSCCOptimizerLateEPCallback(
718       [this](CGSCCPassManager &PM, OptimizationLevel Level) {
719         if (Level == OptimizationLevel::O0)
720           return;
721 
722         FunctionPassManager FPM;
723 
724         // Add promote kernel arguments pass to the opt pipeline right before
725         // infer address spaces which is needed to do actual address space
726         // rewriting.
727         if (Level.getSpeedupLevel() > OptimizationLevel::O1.getSpeedupLevel() &&
728             EnablePromoteKernelArguments)
729           FPM.addPass(AMDGPUPromoteKernelArgumentsPass());
730 
731         // Add infer address spaces pass to the opt pipeline after inlining
732         // but before SROA to increase SROA opportunities.
733         FPM.addPass(InferAddressSpacesPass());
734 
735         // This should run after inlining to have any chance of doing
736         // anything, and before other cleanup optimizations.
737         FPM.addPass(AMDGPULowerKernelAttributesPass());
738 
739         if (Level != OptimizationLevel::O0) {
740           // Promote alloca to vector before SROA and loop unroll. If we
741           // manage to eliminate allocas before unroll we may choose to unroll
742           // less.
743           FPM.addPass(AMDGPUPromoteAllocaToVectorPass(*this));
744         }
745 
746         PM.addPass(createCGSCCToFunctionPassAdaptor(std::move(FPM)));
747       });
748 }
749 
750 int64_t AMDGPUTargetMachine::getNullPointerValue(unsigned AddrSpace) {
751   return (AddrSpace == AMDGPUAS::LOCAL_ADDRESS ||
752           AddrSpace == AMDGPUAS::PRIVATE_ADDRESS ||
753           AddrSpace == AMDGPUAS::REGION_ADDRESS)
754              ? -1
755              : 0;
756 }
757 
758 bool AMDGPUTargetMachine::isNoopAddrSpaceCast(unsigned SrcAS,
759                                               unsigned DestAS) const {
760   return AMDGPU::isFlatGlobalAddrSpace(SrcAS) &&
761          AMDGPU::isFlatGlobalAddrSpace(DestAS);
762 }
763 
764 unsigned AMDGPUTargetMachine::getAssumedAddrSpace(const Value *V) const {
765   const auto *LD = dyn_cast<LoadInst>(V);
766   if (!LD)
767     return AMDGPUAS::UNKNOWN_ADDRESS_SPACE;
768 
769   // It must be a generic pointer loaded.
770   assert(V->getType()->isPointerTy() &&
771          V->getType()->getPointerAddressSpace() == AMDGPUAS::FLAT_ADDRESS);
772 
773   const auto *Ptr = LD->getPointerOperand();
774   if (Ptr->getType()->getPointerAddressSpace() != AMDGPUAS::CONSTANT_ADDRESS)
775     return AMDGPUAS::UNKNOWN_ADDRESS_SPACE;
776   // For a generic pointer loaded from the constant memory, it could be assumed
777   // as a global pointer since the constant memory is only populated on the
778   // host side. As implied by the offload programming model, only global
779   // pointers could be referenced on the host side.
780   return AMDGPUAS::GLOBAL_ADDRESS;
781 }
782 
783 //===----------------------------------------------------------------------===//
784 // GCN Target Machine (SI+)
785 //===----------------------------------------------------------------------===//
786 
787 GCNTargetMachine::GCNTargetMachine(const Target &T, const Triple &TT,
788                                    StringRef CPU, StringRef FS,
789                                    TargetOptions Options,
790                                    Optional<Reloc::Model> RM,
791                                    Optional<CodeModel::Model> CM,
792                                    CodeGenOpt::Level OL, bool JIT)
793     : AMDGPUTargetMachine(T, TT, CPU, FS, Options, RM, CM, OL) {}
794 
795 const TargetSubtargetInfo *
796 GCNTargetMachine::getSubtargetImpl(const Function &F) const {
797   StringRef GPU = getGPUName(F);
798   StringRef FS = getFeatureString(F);
799 
800   SmallString<128> SubtargetKey(GPU);
801   SubtargetKey.append(FS);
802 
803   auto &I = SubtargetMap[SubtargetKey];
804   if (!I) {
805     // This needs to be done before we create a new subtarget since any
806     // creation will depend on the TM and the code generation flags on the
807     // function that reside in TargetOptions.
808     resetTargetOptions(F);
809     I = std::make_unique<GCNSubtarget>(TargetTriple, GPU, FS, *this);
810   }
811 
812   I->setScalarizeGlobalBehavior(ScalarizeGlobal);
813 
814   return I.get();
815 }
816 
817 TargetTransformInfo
818 GCNTargetMachine::getTargetTransformInfo(const Function &F) {
819   return TargetTransformInfo(GCNTTIImpl(this, F));
820 }
821 
822 //===----------------------------------------------------------------------===//
823 // AMDGPU Pass Setup
824 //===----------------------------------------------------------------------===//
825 
826 std::unique_ptr<CSEConfigBase> llvm::AMDGPUPassConfig::getCSEConfig() const {
827   return getStandardCSEConfigForOpt(TM->getOptLevel());
828 }
829 
830 namespace {
831 
832 class GCNPassConfig final : public AMDGPUPassConfig {
833 public:
834   GCNPassConfig(LLVMTargetMachine &TM, PassManagerBase &PM)
835     : AMDGPUPassConfig(TM, PM) {
836     // It is necessary to know the register usage of the entire call graph.  We
837     // allow calls without EnableAMDGPUFunctionCalls if they are marked
838     // noinline, so this is always required.
839     setRequiresCodeGenSCCOrder(true);
840     substitutePass(&PostRASchedulerID, &PostMachineSchedulerID);
841   }
842 
843   GCNTargetMachine &getGCNTargetMachine() const {
844     return getTM<GCNTargetMachine>();
845   }
846 
847   ScheduleDAGInstrs *
848   createMachineScheduler(MachineSchedContext *C) const override;
849 
850   ScheduleDAGInstrs *
851   createPostMachineScheduler(MachineSchedContext *C) const override {
852     ScheduleDAGMI *DAG = createGenericSchedPostRA(C);
853     const GCNSubtarget &ST = C->MF->getSubtarget<GCNSubtarget>();
854     DAG->addMutation(createLoadClusterDAGMutation(DAG->TII, DAG->TRI));
855     DAG->addMutation(ST.createFillMFMAShadowMutation(DAG->TII));
856     return DAG;
857   }
858 
859   bool addPreISel() override;
860   void addMachineSSAOptimization() override;
861   bool addILPOpts() override;
862   bool addInstSelector() override;
863   bool addIRTranslator() override;
864   void addPreLegalizeMachineIR() override;
865   bool addLegalizeMachineIR() override;
866   void addPreRegBankSelect() override;
867   bool addRegBankSelect() override;
868   void addPreGlobalInstructionSelect() override;
869   bool addGlobalInstructionSelect() override;
870   void addFastRegAlloc() override;
871   void addOptimizedRegAlloc() override;
872 
873   FunctionPass *createSGPRAllocPass(bool Optimized);
874   FunctionPass *createVGPRAllocPass(bool Optimized);
875   FunctionPass *createRegAllocPass(bool Optimized) override;
876 
877   bool addRegAssignAndRewriteFast() override;
878   bool addRegAssignAndRewriteOptimized() override;
879 
880   void addPreRegAlloc() override;
881   bool addPreRewrite() override;
882   void addPostRegAlloc() override;
883   void addPreSched2() override;
884   void addPreEmitPass() override;
885 };
886 
887 } // end anonymous namespace
888 
889 AMDGPUPassConfig::AMDGPUPassConfig(LLVMTargetMachine &TM, PassManagerBase &PM)
890     : TargetPassConfig(TM, PM) {
891   // Exceptions and StackMaps are not supported, so these passes will never do
892   // anything.
893   disablePass(&StackMapLivenessID);
894   disablePass(&FuncletLayoutID);
895   // Garbage collection is not supported.
896   disablePass(&GCLoweringID);
897   disablePass(&ShadowStackGCLoweringID);
898 }
899 
900 void AMDGPUPassConfig::addEarlyCSEOrGVNPass() {
901   if (getOptLevel() == CodeGenOpt::Aggressive)
902     addPass(createGVNPass());
903   else
904     addPass(createEarlyCSEPass());
905 }
906 
907 void AMDGPUPassConfig::addStraightLineScalarOptimizationPasses() {
908   addPass(createLICMPass());
909   addPass(createSeparateConstOffsetFromGEPPass());
910   addPass(createSpeculativeExecutionPass());
911   // ReassociateGEPs exposes more opportunities for SLSR. See
912   // the example in reassociate-geps-and-slsr.ll.
913   addPass(createStraightLineStrengthReducePass());
914   // SeparateConstOffsetFromGEP and SLSR creates common expressions which GVN or
915   // EarlyCSE can reuse.
916   addEarlyCSEOrGVNPass();
917   // Run NaryReassociate after EarlyCSE/GVN to be more effective.
918   addPass(createNaryReassociatePass());
919   // NaryReassociate on GEPs creates redundant common expressions, so run
920   // EarlyCSE after it.
921   addPass(createEarlyCSEPass());
922 }
923 
924 void AMDGPUPassConfig::addIRPasses() {
925   const AMDGPUTargetMachine &TM = getAMDGPUTargetMachine();
926 
927   // There is no reason to run these.
928   disablePass(&StackMapLivenessID);
929   disablePass(&FuncletLayoutID);
930   disablePass(&PatchableFunctionID);
931 
932   addPass(createAMDGPUPrintfRuntimeBinding());
933   addPass(createAMDGPUCtorDtorLoweringPass());
934 
935   // This must occur before inlining, as the inliner will not look through
936   // bitcast calls.
937   addPass(createAMDGPUFixFunctionBitcastsPass());
938 
939   // A call to propagate attributes pass in the backend in case opt was not run.
940   addPass(createAMDGPUPropagateAttributesEarlyPass(&TM));
941 
942   addPass(createAMDGPULowerIntrinsicsPass());
943 
944   // Function calls are not supported, so make sure we inline everything.
945   addPass(createAMDGPUAlwaysInlinePass());
946   addPass(createAlwaysInlinerLegacyPass());
947   // We need to add the barrier noop pass, otherwise adding the function
948   // inlining pass will cause all of the PassConfigs passes to be run
949   // one function at a time, which means if we have a nodule with two
950   // functions, then we will generate code for the first function
951   // without ever running any passes on the second.
952   addPass(createBarrierNoopPass());
953 
954   // Handle uses of OpenCL image2d_t, image3d_t and sampler_t arguments.
955   if (TM.getTargetTriple().getArch() == Triple::r600)
956     addPass(createR600OpenCLImageTypeLoweringPass());
957 
958   // Replace OpenCL enqueued block function pointers with global variables.
959   addPass(createAMDGPUOpenCLEnqueuedBlockLoweringPass());
960 
961   // Can increase LDS used by kernel so runs before PromoteAlloca
962   if (EnableLowerModuleLDS) {
963     // The pass "amdgpu-replace-lds-use-with-pointer" need to be run before the
964     // pass "amdgpu-lower-module-lds", and also it required to be run only if
965     // "amdgpu-lower-module-lds" pass is enabled.
966     if (EnableLDSReplaceWithPointer)
967       addPass(createAMDGPUReplaceLDSUseWithPointerPass());
968 
969     addPass(createAMDGPULowerModuleLDSPass());
970   }
971 
972   if (TM.getOptLevel() > CodeGenOpt::None)
973     addPass(createInferAddressSpacesPass());
974 
975   addPass(createAtomicExpandPass());
976 
977   if (TM.getOptLevel() > CodeGenOpt::None) {
978     addPass(createAMDGPUPromoteAlloca());
979 
980     if (EnableSROA)
981       addPass(createSROAPass());
982     if (isPassEnabled(EnableScalarIRPasses))
983       addStraightLineScalarOptimizationPasses();
984 
985     if (EnableAMDGPUAliasAnalysis) {
986       addPass(createAMDGPUAAWrapperPass());
987       addPass(createExternalAAWrapperPass([](Pass &P, Function &,
988                                              AAResults &AAR) {
989         if (auto *WrapperPass = P.getAnalysisIfAvailable<AMDGPUAAWrapperPass>())
990           AAR.addAAResult(WrapperPass->getResult());
991         }));
992     }
993 
994     if (TM.getTargetTriple().getArch() == Triple::amdgcn) {
995       // TODO: May want to move later or split into an early and late one.
996       addPass(createAMDGPUCodeGenPreparePass());
997     }
998   }
999 
1000   TargetPassConfig::addIRPasses();
1001 
1002   // EarlyCSE is not always strong enough to clean up what LSR produces. For
1003   // example, GVN can combine
1004   //
1005   //   %0 = add %a, %b
1006   //   %1 = add %b, %a
1007   //
1008   // and
1009   //
1010   //   %0 = shl nsw %a, 2
1011   //   %1 = shl %a, 2
1012   //
1013   // but EarlyCSE can do neither of them.
1014   if (isPassEnabled(EnableScalarIRPasses))
1015     addEarlyCSEOrGVNPass();
1016 }
1017 
1018 void AMDGPUPassConfig::addCodeGenPrepare() {
1019   if (TM->getTargetTriple().getArch() == Triple::amdgcn) {
1020     addPass(createAMDGPUAttributorPass());
1021 
1022     // FIXME: This pass adds 2 hacky attributes that can be replaced with an
1023     // analysis, and should be removed.
1024     addPass(createAMDGPUAnnotateKernelFeaturesPass());
1025   }
1026 
1027   if (TM->getTargetTriple().getArch() == Triple::amdgcn &&
1028       EnableLowerKernelArguments)
1029     addPass(createAMDGPULowerKernelArgumentsPass());
1030 
1031   TargetPassConfig::addCodeGenPrepare();
1032 
1033   if (isPassEnabled(EnableLoadStoreVectorizer))
1034     addPass(createLoadStoreVectorizerPass());
1035 
1036   // LowerSwitch pass may introduce unreachable blocks that can
1037   // cause unexpected behavior for subsequent passes. Placing it
1038   // here seems better that these blocks would get cleaned up by
1039   // UnreachableBlockElim inserted next in the pass flow.
1040   addPass(createLowerSwitchPass());
1041 }
1042 
1043 bool AMDGPUPassConfig::addPreISel() {
1044   if (TM->getOptLevel() > CodeGenOpt::None)
1045     addPass(createFlattenCFGPass());
1046   return false;
1047 }
1048 
1049 bool AMDGPUPassConfig::addInstSelector() {
1050   addPass(createAMDGPUISelDag(&getAMDGPUTargetMachine(), getOptLevel()));
1051   return false;
1052 }
1053 
1054 bool AMDGPUPassConfig::addGCPasses() {
1055   // Do nothing. GC is not supported.
1056   return false;
1057 }
1058 
1059 llvm::ScheduleDAGInstrs *
1060 AMDGPUPassConfig::createMachineScheduler(MachineSchedContext *C) const {
1061   ScheduleDAGMILive *DAG = createGenericSchedLive(C);
1062   DAG->addMutation(createLoadClusterDAGMutation(DAG->TII, DAG->TRI));
1063   return DAG;
1064 }
1065 
1066 //===----------------------------------------------------------------------===//
1067 // GCN Pass Setup
1068 //===----------------------------------------------------------------------===//
1069 
1070 ScheduleDAGInstrs *GCNPassConfig::createMachineScheduler(
1071   MachineSchedContext *C) const {
1072   const GCNSubtarget &ST = C->MF->getSubtarget<GCNSubtarget>();
1073   if (ST.enableSIScheduler())
1074     return createSIMachineScheduler(C);
1075   return createGCNMaxOccupancyMachineScheduler(C);
1076 }
1077 
1078 bool GCNPassConfig::addPreISel() {
1079   AMDGPUPassConfig::addPreISel();
1080 
1081   if (TM->getOptLevel() > CodeGenOpt::None)
1082     addPass(createAMDGPULateCodeGenPreparePass());
1083 
1084   if (isPassEnabled(EnableAtomicOptimizations, CodeGenOpt::Less)) {
1085     addPass(createAMDGPUAtomicOptimizerPass());
1086   }
1087 
1088   if (TM->getOptLevel() > CodeGenOpt::None)
1089     addPass(createSinkingPass());
1090 
1091   // Merge divergent exit nodes. StructurizeCFG won't recognize the multi-exit
1092   // regions formed by them.
1093   addPass(&AMDGPUUnifyDivergentExitNodesID);
1094   if (!LateCFGStructurize) {
1095     if (EnableStructurizerWorkarounds) {
1096       addPass(createFixIrreduciblePass());
1097       addPass(createUnifyLoopExitsPass());
1098     }
1099     addPass(createStructurizeCFGPass(false)); // true -> SkipUniformRegions
1100   }
1101   addPass(createAMDGPUAnnotateUniformValues());
1102   if (!LateCFGStructurize) {
1103     addPass(createSIAnnotateControlFlowPass());
1104   }
1105   addPass(createLCSSAPass());
1106 
1107   if (TM->getOptLevel() > CodeGenOpt::Less)
1108     addPass(&AMDGPUPerfHintAnalysisID);
1109 
1110   return false;
1111 }
1112 
1113 void GCNPassConfig::addMachineSSAOptimization() {
1114   TargetPassConfig::addMachineSSAOptimization();
1115 
1116   // We want to fold operands after PeepholeOptimizer has run (or as part of
1117   // it), because it will eliminate extra copies making it easier to fold the
1118   // real source operand. We want to eliminate dead instructions after, so that
1119   // we see fewer uses of the copies. We then need to clean up the dead
1120   // instructions leftover after the operands are folded as well.
1121   //
1122   // XXX - Can we get away without running DeadMachineInstructionElim again?
1123   addPass(&SIFoldOperandsID);
1124   if (EnableDPPCombine)
1125     addPass(&GCNDPPCombineID);
1126   addPass(&SILoadStoreOptimizerID);
1127   if (isPassEnabled(EnableSDWAPeephole)) {
1128     addPass(&SIPeepholeSDWAID);
1129     addPass(&EarlyMachineLICMID);
1130     addPass(&MachineCSEID);
1131     addPass(&SIFoldOperandsID);
1132   }
1133   addPass(&DeadMachineInstructionElimID);
1134   addPass(createSIShrinkInstructionsPass());
1135 }
1136 
1137 bool GCNPassConfig::addILPOpts() {
1138   if (EnableEarlyIfConversion)
1139     addPass(&EarlyIfConverterID);
1140 
1141   TargetPassConfig::addILPOpts();
1142   return false;
1143 }
1144 
1145 bool GCNPassConfig::addInstSelector() {
1146   AMDGPUPassConfig::addInstSelector();
1147   addPass(&SIFixSGPRCopiesID);
1148   addPass(createSILowerI1CopiesPass());
1149   return false;
1150 }
1151 
1152 bool GCNPassConfig::addIRTranslator() {
1153   addPass(new IRTranslator(getOptLevel()));
1154   return false;
1155 }
1156 
1157 void GCNPassConfig::addPreLegalizeMachineIR() {
1158   bool IsOptNone = getOptLevel() == CodeGenOpt::None;
1159   addPass(createAMDGPUPreLegalizeCombiner(IsOptNone));
1160   addPass(new Localizer());
1161 }
1162 
1163 bool GCNPassConfig::addLegalizeMachineIR() {
1164   addPass(new Legalizer());
1165   return false;
1166 }
1167 
1168 void GCNPassConfig::addPreRegBankSelect() {
1169   bool IsOptNone = getOptLevel() == CodeGenOpt::None;
1170   addPass(createAMDGPUPostLegalizeCombiner(IsOptNone));
1171 }
1172 
1173 bool GCNPassConfig::addRegBankSelect() {
1174   addPass(new RegBankSelect());
1175   return false;
1176 }
1177 
1178 void GCNPassConfig::addPreGlobalInstructionSelect() {
1179   bool IsOptNone = getOptLevel() == CodeGenOpt::None;
1180   addPass(createAMDGPURegBankCombiner(IsOptNone));
1181 }
1182 
1183 bool GCNPassConfig::addGlobalInstructionSelect() {
1184   addPass(new InstructionSelect(getOptLevel()));
1185   return false;
1186 }
1187 
1188 void GCNPassConfig::addPreRegAlloc() {
1189   if (LateCFGStructurize) {
1190     addPass(createAMDGPUMachineCFGStructurizerPass());
1191   }
1192 }
1193 
1194 void GCNPassConfig::addFastRegAlloc() {
1195   // FIXME: We have to disable the verifier here because of PHIElimination +
1196   // TwoAddressInstructions disabling it.
1197 
1198   // This must be run immediately after phi elimination and before
1199   // TwoAddressInstructions, otherwise the processing of the tied operand of
1200   // SI_ELSE will introduce a copy of the tied operand source after the else.
1201   insertPass(&PHIEliminationID, &SILowerControlFlowID, false);
1202 
1203   insertPass(&TwoAddressInstructionPassID, &SIWholeQuadModeID);
1204   insertPass(&TwoAddressInstructionPassID, &SIPreAllocateWWMRegsID);
1205 
1206   TargetPassConfig::addFastRegAlloc();
1207 }
1208 
1209 void GCNPassConfig::addOptimizedRegAlloc() {
1210   // Allow the scheduler to run before SIWholeQuadMode inserts exec manipulation
1211   // instructions that cause scheduling barriers.
1212   insertPass(&MachineSchedulerID, &SIWholeQuadModeID);
1213   insertPass(&MachineSchedulerID, &SIPreAllocateWWMRegsID);
1214 
1215   if (OptExecMaskPreRA)
1216     insertPass(&MachineSchedulerID, &SIOptimizeExecMaskingPreRAID);
1217 
1218   if (isPassEnabled(EnablePreRAOptimizations))
1219     insertPass(&RenameIndependentSubregsID, &GCNPreRAOptimizationsID);
1220 
1221   // This is not an essential optimization and it has a noticeable impact on
1222   // compilation time, so we only enable it from O2.
1223   if (TM->getOptLevel() > CodeGenOpt::Less)
1224     insertPass(&MachineSchedulerID, &SIFormMemoryClausesID);
1225 
1226   // FIXME: when an instruction has a Killed operand, and the instruction is
1227   // inside a bundle, seems only the BUNDLE instruction appears as the Kills of
1228   // the register in LiveVariables, this would trigger a failure in verifier,
1229   // we should fix it and enable the verifier.
1230   if (OptVGPRLiveRange)
1231     insertPass(&LiveVariablesID, &SIOptimizeVGPRLiveRangeID, false);
1232   // This must be run immediately after phi elimination and before
1233   // TwoAddressInstructions, otherwise the processing of the tied operand of
1234   // SI_ELSE will introduce a copy of the tied operand source after the else.
1235   insertPass(&PHIEliminationID, &SILowerControlFlowID, false);
1236 
1237   if (EnableDCEInRA)
1238     insertPass(&DetectDeadLanesID, &DeadMachineInstructionElimID);
1239 
1240   TargetPassConfig::addOptimizedRegAlloc();
1241 }
1242 
1243 bool GCNPassConfig::addPreRewrite() {
1244   if (EnableRegReassign)
1245     addPass(&GCNNSAReassignID);
1246   return true;
1247 }
1248 
1249 FunctionPass *GCNPassConfig::createSGPRAllocPass(bool Optimized) {
1250   // Initialize the global default.
1251   llvm::call_once(InitializeDefaultSGPRRegisterAllocatorFlag,
1252                   initializeDefaultSGPRRegisterAllocatorOnce);
1253 
1254   RegisterRegAlloc::FunctionPassCtor Ctor = SGPRRegisterRegAlloc::getDefault();
1255   if (Ctor != useDefaultRegisterAllocator)
1256     return Ctor();
1257 
1258   if (Optimized)
1259     return createGreedyRegisterAllocator(onlyAllocateSGPRs);
1260 
1261   return createFastRegisterAllocator(onlyAllocateSGPRs, false);
1262 }
1263 
1264 FunctionPass *GCNPassConfig::createVGPRAllocPass(bool Optimized) {
1265   // Initialize the global default.
1266   llvm::call_once(InitializeDefaultVGPRRegisterAllocatorFlag,
1267                   initializeDefaultVGPRRegisterAllocatorOnce);
1268 
1269   RegisterRegAlloc::FunctionPassCtor Ctor = VGPRRegisterRegAlloc::getDefault();
1270   if (Ctor != useDefaultRegisterAllocator)
1271     return Ctor();
1272 
1273   if (Optimized)
1274     return createGreedyVGPRRegisterAllocator();
1275 
1276   return createFastVGPRRegisterAllocator();
1277 }
1278 
1279 FunctionPass *GCNPassConfig::createRegAllocPass(bool Optimized) {
1280   llvm_unreachable("should not be used");
1281 }
1282 
1283 static const char RegAllocOptNotSupportedMessage[] =
1284   "-regalloc not supported with amdgcn. Use -sgpr-regalloc and -vgpr-regalloc";
1285 
1286 bool GCNPassConfig::addRegAssignAndRewriteFast() {
1287   if (!usingDefaultRegAlloc())
1288     report_fatal_error(RegAllocOptNotSupportedMessage);
1289 
1290   addPass(createSGPRAllocPass(false));
1291 
1292   // Equivalent of PEI for SGPRs.
1293   addPass(&SILowerSGPRSpillsID);
1294 
1295   addPass(createVGPRAllocPass(false));
1296   return true;
1297 }
1298 
1299 bool GCNPassConfig::addRegAssignAndRewriteOptimized() {
1300   if (!usingDefaultRegAlloc())
1301     report_fatal_error(RegAllocOptNotSupportedMessage);
1302 
1303   addPass(createSGPRAllocPass(true));
1304 
1305   // Commit allocated register changes. This is mostly necessary because too
1306   // many things rely on the use lists of the physical registers, such as the
1307   // verifier. This is only necessary with allocators which use LiveIntervals,
1308   // since FastRegAlloc does the replacements itself.
1309   addPass(createVirtRegRewriter(false));
1310 
1311   // Equivalent of PEI for SGPRs.
1312   addPass(&SILowerSGPRSpillsID);
1313 
1314   addPass(createVGPRAllocPass(true));
1315 
1316   addPreRewrite();
1317   addPass(&VirtRegRewriterID);
1318 
1319   return true;
1320 }
1321 
1322 void GCNPassConfig::addPostRegAlloc() {
1323   addPass(&SIFixVGPRCopiesID);
1324   if (getOptLevel() > CodeGenOpt::None)
1325     addPass(&SIOptimizeExecMaskingID);
1326   TargetPassConfig::addPostRegAlloc();
1327 }
1328 
1329 void GCNPassConfig::addPreSched2() {
1330   addPass(&SIPostRABundlerID);
1331 }
1332 
1333 void GCNPassConfig::addPreEmitPass() {
1334   addPass(createSIMemoryLegalizerPass());
1335   addPass(createSIInsertWaitcntsPass());
1336 
1337   if (TM->getOptLevel() > CodeGenOpt::None)
1338     addPass(createSIShrinkInstructionsPass());
1339 
1340   addPass(createSIModeRegisterPass());
1341 
1342   if (getOptLevel() > CodeGenOpt::None)
1343     addPass(&SIInsertHardClausesID);
1344 
1345   addPass(&SILateBranchLoweringPassID);
1346   if (getOptLevel() > CodeGenOpt::None)
1347     addPass(&SIPreEmitPeepholeID);
1348   // The hazard recognizer that runs as part of the post-ra scheduler does not
1349   // guarantee to be able handle all hazards correctly. This is because if there
1350   // are multiple scheduling regions in a basic block, the regions are scheduled
1351   // bottom up, so when we begin to schedule a region we don't know what
1352   // instructions were emitted directly before it.
1353   //
1354   // Here we add a stand-alone hazard recognizer pass which can handle all
1355   // cases.
1356   addPass(&PostRAHazardRecognizerID);
1357   addPass(&BranchRelaxationPassID);
1358 }
1359 
1360 TargetPassConfig *GCNTargetMachine::createPassConfig(PassManagerBase &PM) {
1361   return new GCNPassConfig(*this, PM);
1362 }
1363 
1364 yaml::MachineFunctionInfo *GCNTargetMachine::createDefaultFuncInfoYAML() const {
1365   return new yaml::SIMachineFunctionInfo();
1366 }
1367 
1368 yaml::MachineFunctionInfo *
1369 GCNTargetMachine::convertFuncInfoToYAML(const MachineFunction &MF) const {
1370   const SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
1371   return new yaml::SIMachineFunctionInfo(
1372       *MFI, *MF.getSubtarget().getRegisterInfo(), MF);
1373 }
1374 
1375 bool GCNTargetMachine::parseMachineFunctionInfo(
1376     const yaml::MachineFunctionInfo &MFI_, PerFunctionMIParsingState &PFS,
1377     SMDiagnostic &Error, SMRange &SourceRange) const {
1378   const yaml::SIMachineFunctionInfo &YamlMFI =
1379       reinterpret_cast<const yaml::SIMachineFunctionInfo &>(MFI_);
1380   MachineFunction &MF = PFS.MF;
1381   SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
1382 
1383   if (MFI->initializeBaseYamlFields(YamlMFI, MF, PFS, Error, SourceRange))
1384     return true;
1385 
1386   if (MFI->Occupancy == 0) {
1387     // Fixup the subtarget dependent default value.
1388     const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>();
1389     MFI->Occupancy = ST.computeOccupancy(MF.getFunction(), MFI->getLDSSize());
1390   }
1391 
1392   auto parseRegister = [&](const yaml::StringValue &RegName, Register &RegVal) {
1393     Register TempReg;
1394     if (parseNamedRegisterReference(PFS, TempReg, RegName.Value, Error)) {
1395       SourceRange = RegName.SourceRange;
1396       return true;
1397     }
1398     RegVal = TempReg;
1399 
1400     return false;
1401   };
1402 
1403   auto diagnoseRegisterClass = [&](const yaml::StringValue &RegName) {
1404     // Create a diagnostic for a the register string literal.
1405     const MemoryBuffer &Buffer =
1406         *PFS.SM->getMemoryBuffer(PFS.SM->getMainFileID());
1407     Error = SMDiagnostic(*PFS.SM, SMLoc(), Buffer.getBufferIdentifier(), 1,
1408                          RegName.Value.size(), SourceMgr::DK_Error,
1409                          "incorrect register class for field", RegName.Value,
1410                          None, None);
1411     SourceRange = RegName.SourceRange;
1412     return true;
1413   };
1414 
1415   if (parseRegister(YamlMFI.ScratchRSrcReg, MFI->ScratchRSrcReg) ||
1416       parseRegister(YamlMFI.FrameOffsetReg, MFI->FrameOffsetReg) ||
1417       parseRegister(YamlMFI.StackPtrOffsetReg, MFI->StackPtrOffsetReg))
1418     return true;
1419 
1420   if (MFI->ScratchRSrcReg != AMDGPU::PRIVATE_RSRC_REG &&
1421       !AMDGPU::SGPR_128RegClass.contains(MFI->ScratchRSrcReg)) {
1422     return diagnoseRegisterClass(YamlMFI.ScratchRSrcReg);
1423   }
1424 
1425   if (MFI->FrameOffsetReg != AMDGPU::FP_REG &&
1426       !AMDGPU::SGPR_32RegClass.contains(MFI->FrameOffsetReg)) {
1427     return diagnoseRegisterClass(YamlMFI.FrameOffsetReg);
1428   }
1429 
1430   if (MFI->StackPtrOffsetReg != AMDGPU::SP_REG &&
1431       !AMDGPU::SGPR_32RegClass.contains(MFI->StackPtrOffsetReg)) {
1432     return diagnoseRegisterClass(YamlMFI.StackPtrOffsetReg);
1433   }
1434 
1435   auto parseAndCheckArgument = [&](const Optional<yaml::SIArgument> &A,
1436                                    const TargetRegisterClass &RC,
1437                                    ArgDescriptor &Arg, unsigned UserSGPRs,
1438                                    unsigned SystemSGPRs) {
1439     // Skip parsing if it's not present.
1440     if (!A)
1441       return false;
1442 
1443     if (A->IsRegister) {
1444       Register Reg;
1445       if (parseNamedRegisterReference(PFS, Reg, A->RegisterName.Value, Error)) {
1446         SourceRange = A->RegisterName.SourceRange;
1447         return true;
1448       }
1449       if (!RC.contains(Reg))
1450         return diagnoseRegisterClass(A->RegisterName);
1451       Arg = ArgDescriptor::createRegister(Reg);
1452     } else
1453       Arg = ArgDescriptor::createStack(A->StackOffset);
1454     // Check and apply the optional mask.
1455     if (A->Mask)
1456       Arg = ArgDescriptor::createArg(Arg, A->Mask.getValue());
1457 
1458     MFI->NumUserSGPRs += UserSGPRs;
1459     MFI->NumSystemSGPRs += SystemSGPRs;
1460     return false;
1461   };
1462 
1463   if (YamlMFI.ArgInfo &&
1464       (parseAndCheckArgument(YamlMFI.ArgInfo->PrivateSegmentBuffer,
1465                              AMDGPU::SGPR_128RegClass,
1466                              MFI->ArgInfo.PrivateSegmentBuffer, 4, 0) ||
1467        parseAndCheckArgument(YamlMFI.ArgInfo->DispatchPtr,
1468                              AMDGPU::SReg_64RegClass, MFI->ArgInfo.DispatchPtr,
1469                              2, 0) ||
1470        parseAndCheckArgument(YamlMFI.ArgInfo->QueuePtr, AMDGPU::SReg_64RegClass,
1471                              MFI->ArgInfo.QueuePtr, 2, 0) ||
1472        parseAndCheckArgument(YamlMFI.ArgInfo->KernargSegmentPtr,
1473                              AMDGPU::SReg_64RegClass,
1474                              MFI->ArgInfo.KernargSegmentPtr, 2, 0) ||
1475        parseAndCheckArgument(YamlMFI.ArgInfo->DispatchID,
1476                              AMDGPU::SReg_64RegClass, MFI->ArgInfo.DispatchID,
1477                              2, 0) ||
1478        parseAndCheckArgument(YamlMFI.ArgInfo->FlatScratchInit,
1479                              AMDGPU::SReg_64RegClass,
1480                              MFI->ArgInfo.FlatScratchInit, 2, 0) ||
1481        parseAndCheckArgument(YamlMFI.ArgInfo->PrivateSegmentSize,
1482                              AMDGPU::SGPR_32RegClass,
1483                              MFI->ArgInfo.PrivateSegmentSize, 0, 0) ||
1484        parseAndCheckArgument(YamlMFI.ArgInfo->WorkGroupIDX,
1485                              AMDGPU::SGPR_32RegClass, MFI->ArgInfo.WorkGroupIDX,
1486                              0, 1) ||
1487        parseAndCheckArgument(YamlMFI.ArgInfo->WorkGroupIDY,
1488                              AMDGPU::SGPR_32RegClass, MFI->ArgInfo.WorkGroupIDY,
1489                              0, 1) ||
1490        parseAndCheckArgument(YamlMFI.ArgInfo->WorkGroupIDZ,
1491                              AMDGPU::SGPR_32RegClass, MFI->ArgInfo.WorkGroupIDZ,
1492                              0, 1) ||
1493        parseAndCheckArgument(YamlMFI.ArgInfo->WorkGroupInfo,
1494                              AMDGPU::SGPR_32RegClass,
1495                              MFI->ArgInfo.WorkGroupInfo, 0, 1) ||
1496        parseAndCheckArgument(YamlMFI.ArgInfo->PrivateSegmentWaveByteOffset,
1497                              AMDGPU::SGPR_32RegClass,
1498                              MFI->ArgInfo.PrivateSegmentWaveByteOffset, 0, 1) ||
1499        parseAndCheckArgument(YamlMFI.ArgInfo->ImplicitArgPtr,
1500                              AMDGPU::SReg_64RegClass,
1501                              MFI->ArgInfo.ImplicitArgPtr, 0, 0) ||
1502        parseAndCheckArgument(YamlMFI.ArgInfo->ImplicitBufferPtr,
1503                              AMDGPU::SReg_64RegClass,
1504                              MFI->ArgInfo.ImplicitBufferPtr, 2, 0) ||
1505        parseAndCheckArgument(YamlMFI.ArgInfo->WorkItemIDX,
1506                              AMDGPU::VGPR_32RegClass,
1507                              MFI->ArgInfo.WorkItemIDX, 0, 0) ||
1508        parseAndCheckArgument(YamlMFI.ArgInfo->WorkItemIDY,
1509                              AMDGPU::VGPR_32RegClass,
1510                              MFI->ArgInfo.WorkItemIDY, 0, 0) ||
1511        parseAndCheckArgument(YamlMFI.ArgInfo->WorkItemIDZ,
1512                              AMDGPU::VGPR_32RegClass,
1513                              MFI->ArgInfo.WorkItemIDZ, 0, 0)))
1514     return true;
1515 
1516   MFI->Mode.IEEE = YamlMFI.Mode.IEEE;
1517   MFI->Mode.DX10Clamp = YamlMFI.Mode.DX10Clamp;
1518   MFI->Mode.FP32InputDenormals = YamlMFI.Mode.FP32InputDenormals;
1519   MFI->Mode.FP32OutputDenormals = YamlMFI.Mode.FP32OutputDenormals;
1520   MFI->Mode.FP64FP16InputDenormals = YamlMFI.Mode.FP64FP16InputDenormals;
1521   MFI->Mode.FP64FP16OutputDenormals = YamlMFI.Mode.FP64FP16OutputDenormals;
1522 
1523   return false;
1524 }
1525