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 R600 and SI GPUs.
12 //
13 //===----------------------------------------------------------------------===//
14 
15 #include "AMDGPUTargetMachine.h"
16 #include "AMDGPU.h"
17 #include "AMDGPUAliasAnalysis.h"
18 #include "AMDGPUCallLowering.h"
19 #include "AMDGPUInstructionSelector.h"
20 #include "AMDGPULegalizerInfo.h"
21 #include "AMDGPUMacroFusion.h"
22 #include "AMDGPUTargetObjectFile.h"
23 #include "AMDGPUTargetTransformInfo.h"
24 #include "GCNIterativeScheduler.h"
25 #include "GCNSchedStrategy.h"
26 #include "R600MachineScheduler.h"
27 #include "SIMachineFunctionInfo.h"
28 #include "SIMachineScheduler.h"
29 #include "TargetInfo/AMDGPUTargetInfo.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/RegBankSelect.h"
34 #include "llvm/CodeGen/MIRParser/MIParser.h"
35 #include "llvm/CodeGen/Passes.h"
36 #include "llvm/CodeGen/TargetPassConfig.h"
37 #include "llvm/IR/Attributes.h"
38 #include "llvm/IR/Function.h"
39 #include "llvm/IR/LegacyPassManager.h"
40 #include "llvm/Pass.h"
41 #include "llvm/Support/CommandLine.h"
42 #include "llvm/Support/Compiler.h"
43 #include "llvm/Support/TargetRegistry.h"
44 #include "llvm/Target/TargetLoweringObjectFile.h"
45 #include "llvm/Transforms/IPO.h"
46 #include "llvm/Transforms/IPO/AlwaysInliner.h"
47 #include "llvm/Transforms/IPO/PassManagerBuilder.h"
48 #include "llvm/Transforms/Scalar.h"
49 #include "llvm/Transforms/Scalar/GVN.h"
50 #include "llvm/Transforms/Utils.h"
51 #include "llvm/Transforms/Vectorize.h"
52 #include <memory>
53 
54 using namespace llvm;
55 
56 static cl::opt<bool> EnableR600StructurizeCFG(
57   "r600-ir-structurize",
58   cl::desc("Use StructurizeCFG IR pass"),
59   cl::init(true));
60 
61 static cl::opt<bool> EnableSROA(
62   "amdgpu-sroa",
63   cl::desc("Run SROA after promote alloca pass"),
64   cl::ReallyHidden,
65   cl::init(true));
66 
67 static cl::opt<bool>
68 EnableEarlyIfConversion("amdgpu-early-ifcvt", cl::Hidden,
69                         cl::desc("Run early if-conversion"),
70                         cl::init(false));
71 
72 static cl::opt<bool>
73 OptExecMaskPreRA("amdgpu-opt-exec-mask-pre-ra", cl::Hidden,
74             cl::desc("Run pre-RA exec mask optimizations"),
75             cl::init(true));
76 
77 static cl::opt<bool> EnableR600IfConvert(
78   "r600-if-convert",
79   cl::desc("Use if conversion pass"),
80   cl::ReallyHidden,
81   cl::init(true));
82 
83 // Option to disable vectorizer for tests.
84 static cl::opt<bool> EnableLoadStoreVectorizer(
85   "amdgpu-load-store-vectorizer",
86   cl::desc("Enable load store vectorizer"),
87   cl::init(true),
88   cl::Hidden);
89 
90 // Option to control global loads scalarization
91 static cl::opt<bool> ScalarizeGlobal(
92   "amdgpu-scalarize-global-loads",
93   cl::desc("Enable global load scalarization"),
94   cl::init(true),
95   cl::Hidden);
96 
97 // Option to run internalize pass.
98 static cl::opt<bool> InternalizeSymbols(
99   "amdgpu-internalize-symbols",
100   cl::desc("Enable elimination of non-kernel functions and unused globals"),
101   cl::init(false),
102   cl::Hidden);
103 
104 // Option to inline all early.
105 static cl::opt<bool> EarlyInlineAll(
106   "amdgpu-early-inline-all",
107   cl::desc("Inline all functions early"),
108   cl::init(false),
109   cl::Hidden);
110 
111 static cl::opt<bool> EnableSDWAPeephole(
112   "amdgpu-sdwa-peephole",
113   cl::desc("Enable SDWA peepholer"),
114   cl::init(true));
115 
116 static cl::opt<bool> EnableDPPCombine(
117   "amdgpu-dpp-combine",
118   cl::desc("Enable DPP combiner"),
119   cl::init(true));
120 
121 // Enable address space based alias analysis
122 static cl::opt<bool> EnableAMDGPUAliasAnalysis("enable-amdgpu-aa", cl::Hidden,
123   cl::desc("Enable AMDGPU Alias Analysis"),
124   cl::init(true));
125 
126 // Option to run late CFG structurizer
127 static cl::opt<bool, true> LateCFGStructurize(
128   "amdgpu-late-structurize",
129   cl::desc("Enable late CFG structurization"),
130   cl::location(AMDGPUTargetMachine::EnableLateStructurizeCFG),
131   cl::Hidden);
132 
133 static cl::opt<bool, true> EnableAMDGPUFunctionCallsOpt(
134   "amdgpu-function-calls",
135   cl::desc("Enable AMDGPU function call support"),
136   cl::location(AMDGPUTargetMachine::EnableFunctionCalls),
137   cl::init(true),
138   cl::Hidden);
139 
140 // Enable lib calls simplifications
141 static cl::opt<bool> EnableLibCallSimplify(
142   "amdgpu-simplify-libcall",
143   cl::desc("Enable amdgpu library simplifications"),
144   cl::init(true),
145   cl::Hidden);
146 
147 static cl::opt<bool> EnableLowerKernelArguments(
148   "amdgpu-ir-lower-kernel-arguments",
149   cl::desc("Lower kernel argument loads in IR pass"),
150   cl::init(true),
151   cl::Hidden);
152 
153 static cl::opt<bool> EnableRegReassign(
154   "amdgpu-reassign-regs",
155   cl::desc("Enable register reassign optimizations on gfx10+"),
156   cl::init(true),
157   cl::Hidden);
158 
159 // Enable atomic optimization
160 static cl::opt<bool> EnableAtomicOptimizations(
161   "amdgpu-atomic-optimizations",
162   cl::desc("Enable atomic optimizations"),
163   cl::init(false),
164   cl::Hidden);
165 
166 // Enable Mode register optimization
167 static cl::opt<bool> EnableSIModeRegisterPass(
168   "amdgpu-mode-register",
169   cl::desc("Enable mode register pass"),
170   cl::init(true),
171   cl::Hidden);
172 
173 // Option is used in lit tests to prevent deadcoding of patterns inspected.
174 static cl::opt<bool>
175 EnableDCEInRA("amdgpu-dce-in-ra",
176     cl::init(true), cl::Hidden,
177     cl::desc("Enable machine DCE inside regalloc"));
178 
179 static cl::opt<bool> EnableScalarIRPasses(
180   "amdgpu-scalar-ir-passes",
181   cl::desc("Enable scalar IR passes"),
182   cl::init(true),
183   cl::Hidden);
184 
185 extern "C" void LLVMInitializeAMDGPUTarget() {
186   // Register the target
187   RegisterTargetMachine<R600TargetMachine> X(getTheAMDGPUTarget());
188   RegisterTargetMachine<GCNTargetMachine> Y(getTheGCNTarget());
189 
190   PassRegistry *PR = PassRegistry::getPassRegistry();
191   initializeR600ClauseMergePassPass(*PR);
192   initializeR600ControlFlowFinalizerPass(*PR);
193   initializeR600PacketizerPass(*PR);
194   initializeR600ExpandSpecialInstrsPassPass(*PR);
195   initializeR600VectorRegMergerPass(*PR);
196   initializeGlobalISel(*PR);
197   initializeAMDGPUDAGToDAGISelPass(*PR);
198   initializeGCNDPPCombinePass(*PR);
199   initializeSILowerI1CopiesPass(*PR);
200   initializeSIFixSGPRCopiesPass(*PR);
201   initializeSIFixVGPRCopiesPass(*PR);
202   initializeSIFixupVectorISelPass(*PR);
203   initializeSIFoldOperandsPass(*PR);
204   initializeSIPeepholeSDWAPass(*PR);
205   initializeSIShrinkInstructionsPass(*PR);
206   initializeSIOptimizeExecMaskingPreRAPass(*PR);
207   initializeSILoadStoreOptimizerPass(*PR);
208   initializeAMDGPUFixFunctionBitcastsPass(*PR);
209   initializeAMDGPUAlwaysInlinePass(*PR);
210   initializeAMDGPUAnnotateKernelFeaturesPass(*PR);
211   initializeAMDGPUAnnotateUniformValuesPass(*PR);
212   initializeAMDGPUArgumentUsageInfoPass(*PR);
213   initializeAMDGPUAtomicOptimizerPass(*PR);
214   initializeAMDGPULowerKernelArgumentsPass(*PR);
215   initializeAMDGPULowerKernelAttributesPass(*PR);
216   initializeAMDGPULowerIntrinsicsPass(*PR);
217   initializeAMDGPUOpenCLEnqueuedBlockLoweringPass(*PR);
218   initializeAMDGPUPromoteAllocaPass(*PR);
219   initializeAMDGPUCodeGenPreparePass(*PR);
220   initializeAMDGPUPropagateAttributesEarlyPass(*PR);
221   initializeAMDGPUPropagateAttributesLatePass(*PR);
222   initializeAMDGPURewriteOutArgumentsPass(*PR);
223   initializeAMDGPUUnifyMetadataPass(*PR);
224   initializeSIAnnotateControlFlowPass(*PR);
225   initializeSIInsertWaitcntsPass(*PR);
226   initializeSIModeRegisterPass(*PR);
227   initializeSIWholeQuadModePass(*PR);
228   initializeSILowerControlFlowPass(*PR);
229   initializeSIInsertSkipsPass(*PR);
230   initializeSIMemoryLegalizerPass(*PR);
231   initializeSIOptimizeExecMaskingPass(*PR);
232   initializeSIPreAllocateWWMRegsPass(*PR);
233   initializeSIFormMemoryClausesPass(*PR);
234   initializeAMDGPUUnifyDivergentExitNodesPass(*PR);
235   initializeAMDGPUAAWrapperPassPass(*PR);
236   initializeAMDGPUExternalAAWrapperPass(*PR);
237   initializeAMDGPUUseNativeCallsPass(*PR);
238   initializeAMDGPUSimplifyLibCallsPass(*PR);
239   initializeAMDGPUInlinerPass(*PR);
240   initializeGCNRegBankReassignPass(*PR);
241   initializeGCNNSAReassignPass(*PR);
242 }
243 
244 static std::unique_ptr<TargetLoweringObjectFile> createTLOF(const Triple &TT) {
245   return llvm::make_unique<AMDGPUTargetObjectFile>();
246 }
247 
248 static ScheduleDAGInstrs *createR600MachineScheduler(MachineSchedContext *C) {
249   return new ScheduleDAGMILive(C, llvm::make_unique<R600SchedStrategy>());
250 }
251 
252 static ScheduleDAGInstrs *createSIMachineScheduler(MachineSchedContext *C) {
253   return new SIScheduleDAGMI(C);
254 }
255 
256 static ScheduleDAGInstrs *
257 createGCNMaxOccupancyMachineScheduler(MachineSchedContext *C) {
258   ScheduleDAGMILive *DAG =
259     new GCNScheduleDAGMILive(C, make_unique<GCNMaxOccupancySchedStrategy>(C));
260   DAG->addMutation(createLoadClusterDAGMutation(DAG->TII, DAG->TRI));
261   DAG->addMutation(createStoreClusterDAGMutation(DAG->TII, DAG->TRI));
262   DAG->addMutation(createAMDGPUMacroFusionDAGMutation());
263   return DAG;
264 }
265 
266 static ScheduleDAGInstrs *
267 createIterativeGCNMaxOccupancyMachineScheduler(MachineSchedContext *C) {
268   auto DAG = new GCNIterativeScheduler(C,
269     GCNIterativeScheduler::SCHEDULE_LEGACYMAXOCCUPANCY);
270   DAG->addMutation(createLoadClusterDAGMutation(DAG->TII, DAG->TRI));
271   DAG->addMutation(createStoreClusterDAGMutation(DAG->TII, DAG->TRI));
272   return DAG;
273 }
274 
275 static ScheduleDAGInstrs *createMinRegScheduler(MachineSchedContext *C) {
276   return new GCNIterativeScheduler(C,
277     GCNIterativeScheduler::SCHEDULE_MINREGFORCED);
278 }
279 
280 static ScheduleDAGInstrs *
281 createIterativeILPMachineScheduler(MachineSchedContext *C) {
282   auto DAG = new GCNIterativeScheduler(C,
283     GCNIterativeScheduler::SCHEDULE_ILP);
284   DAG->addMutation(createLoadClusterDAGMutation(DAG->TII, DAG->TRI));
285   DAG->addMutation(createStoreClusterDAGMutation(DAG->TII, DAG->TRI));
286   DAG->addMutation(createAMDGPUMacroFusionDAGMutation());
287   return DAG;
288 }
289 
290 static MachineSchedRegistry
291 R600SchedRegistry("r600", "Run R600's custom scheduler",
292                    createR600MachineScheduler);
293 
294 static MachineSchedRegistry
295 SISchedRegistry("si", "Run SI's custom scheduler",
296                 createSIMachineScheduler);
297 
298 static MachineSchedRegistry
299 GCNMaxOccupancySchedRegistry("gcn-max-occupancy",
300                              "Run GCN scheduler to maximize occupancy",
301                              createGCNMaxOccupancyMachineScheduler);
302 
303 static MachineSchedRegistry
304 IterativeGCNMaxOccupancySchedRegistry("gcn-max-occupancy-experimental",
305   "Run GCN scheduler to maximize occupancy (experimental)",
306   createIterativeGCNMaxOccupancyMachineScheduler);
307 
308 static MachineSchedRegistry
309 GCNMinRegSchedRegistry("gcn-minreg",
310   "Run GCN iterative scheduler for minimal register usage (experimental)",
311   createMinRegScheduler);
312 
313 static MachineSchedRegistry
314 GCNILPSchedRegistry("gcn-ilp",
315   "Run GCN iterative scheduler for ILP scheduling (experimental)",
316   createIterativeILPMachineScheduler);
317 
318 static StringRef computeDataLayout(const Triple &TT) {
319   if (TT.getArch() == Triple::r600) {
320     // 32-bit pointers.
321       return "e-p:32:32-i64:64-v16:16-v24:32-v32:32-v48:64-v96:128"
322              "-v192:256-v256:256-v512:512-v1024:1024-v2048:2048-n32:64-S32-A5";
323   }
324 
325   // 32-bit private, local, and region pointers. 64-bit global, constant and
326   // flat, non-integral buffer fat pointers.
327     return "e-p:64:64-p1:64:64-p2:32:32-p3:32:32-p4:64:64-p5:32:32-p6:32:32"
328          "-i64:64-v16:16-v24:32-v32:32-v48:64-v96:128"
329          "-v192:256-v256:256-v512:512-v1024:1024-v2048:2048-n32:64-S32-A5"
330          "-ni:7";
331 }
332 
333 LLVM_READNONE
334 static StringRef getGPUOrDefault(const Triple &TT, StringRef GPU) {
335   if (!GPU.empty())
336     return GPU;
337 
338   // Need to default to a target with flat support for HSA.
339   if (TT.getArch() == Triple::amdgcn)
340     return TT.getOS() == Triple::AMDHSA ? "generic-hsa" : "generic";
341 
342   return "r600";
343 }
344 
345 static Reloc::Model getEffectiveRelocModel(Optional<Reloc::Model> RM) {
346   // The AMDGPU toolchain only supports generating shared objects, so we
347   // must always use PIC.
348   return Reloc::PIC_;
349 }
350 
351 AMDGPUTargetMachine::AMDGPUTargetMachine(const Target &T, const Triple &TT,
352                                          StringRef CPU, StringRef FS,
353                                          TargetOptions Options,
354                                          Optional<Reloc::Model> RM,
355                                          Optional<CodeModel::Model> CM,
356                                          CodeGenOpt::Level OptLevel)
357     : LLVMTargetMachine(T, computeDataLayout(TT), TT, getGPUOrDefault(TT, CPU),
358                         FS, Options, getEffectiveRelocModel(RM),
359                         getEffectiveCodeModel(CM, CodeModel::Small), OptLevel),
360       TLOF(createTLOF(getTargetTriple())) {
361   initAsmInfo();
362 }
363 
364 bool AMDGPUTargetMachine::EnableLateStructurizeCFG = false;
365 bool AMDGPUTargetMachine::EnableFunctionCalls = false;
366 
367 AMDGPUTargetMachine::~AMDGPUTargetMachine() = default;
368 
369 StringRef AMDGPUTargetMachine::getGPUName(const Function &F) const {
370   Attribute GPUAttr = F.getFnAttribute("target-cpu");
371   return GPUAttr.hasAttribute(Attribute::None) ?
372     getTargetCPU() : GPUAttr.getValueAsString();
373 }
374 
375 StringRef AMDGPUTargetMachine::getFeatureString(const Function &F) const {
376   Attribute FSAttr = F.getFnAttribute("target-features");
377 
378   return FSAttr.hasAttribute(Attribute::None) ?
379     getTargetFeatureString() :
380     FSAttr.getValueAsString();
381 }
382 
383 /// Predicate for Internalize pass.
384 static bool mustPreserveGV(const GlobalValue &GV) {
385   if (const Function *F = dyn_cast<Function>(&GV))
386     return F->isDeclaration() || AMDGPU::isEntryFunctionCC(F->getCallingConv());
387 
388   return !GV.use_empty();
389 }
390 
391 void AMDGPUTargetMachine::adjustPassManager(PassManagerBuilder &Builder) {
392   Builder.DivergentTarget = true;
393 
394   bool EnableOpt = getOptLevel() > CodeGenOpt::None;
395   bool Internalize = InternalizeSymbols;
396   bool EarlyInline = EarlyInlineAll && EnableOpt && !EnableFunctionCalls;
397   bool AMDGPUAA = EnableAMDGPUAliasAnalysis && EnableOpt;
398   bool LibCallSimplify = EnableLibCallSimplify && EnableOpt;
399 
400   if (EnableFunctionCalls) {
401     delete Builder.Inliner;
402     Builder.Inliner = createAMDGPUFunctionInliningPass();
403   }
404 
405   Builder.addExtension(
406     PassManagerBuilder::EP_ModuleOptimizerEarly,
407     [Internalize, EarlyInline, AMDGPUAA, this](const PassManagerBuilder &,
408                                                legacy::PassManagerBase &PM) {
409       if (AMDGPUAA) {
410         PM.add(createAMDGPUAAWrapperPass());
411         PM.add(createAMDGPUExternalAAWrapperPass());
412       }
413       PM.add(createAMDGPUUnifyMetadataPass());
414       PM.add(createAMDGPUPropagateAttributesLatePass(this));
415       if (Internalize) {
416         PM.add(createInternalizePass(mustPreserveGV));
417         PM.add(createGlobalDCEPass());
418       }
419       if (EarlyInline)
420         PM.add(createAMDGPUAlwaysInlinePass(false));
421   });
422 
423   const auto &Opt = Options;
424   Builder.addExtension(
425     PassManagerBuilder::EP_EarlyAsPossible,
426     [AMDGPUAA, LibCallSimplify, &Opt, this](const PassManagerBuilder &,
427                                             legacy::PassManagerBase &PM) {
428       if (AMDGPUAA) {
429         PM.add(createAMDGPUAAWrapperPass());
430         PM.add(createAMDGPUExternalAAWrapperPass());
431       }
432       PM.add(llvm::createAMDGPUPropagateAttributesEarlyPass(this));
433       PM.add(llvm::createAMDGPUUseNativeCallsPass());
434       if (LibCallSimplify)
435         PM.add(llvm::createAMDGPUSimplifyLibCallsPass(Opt, this));
436   });
437 
438   Builder.addExtension(
439     PassManagerBuilder::EP_CGSCCOptimizerLate,
440     [](const PassManagerBuilder &, legacy::PassManagerBase &PM) {
441       // Add infer address spaces pass to the opt pipeline after inlining
442       // but before SROA to increase SROA opportunities.
443       PM.add(createInferAddressSpacesPass());
444 
445       // This should run after inlining to have any chance of doing anything,
446       // and before other cleanup optimizations.
447       PM.add(createAMDGPULowerKernelAttributesPass());
448   });
449 }
450 
451 //===----------------------------------------------------------------------===//
452 // R600 Target Machine (R600 -> Cayman)
453 //===----------------------------------------------------------------------===//
454 
455 R600TargetMachine::R600TargetMachine(const Target &T, const Triple &TT,
456                                      StringRef CPU, StringRef FS,
457                                      TargetOptions Options,
458                                      Optional<Reloc::Model> RM,
459                                      Optional<CodeModel::Model> CM,
460                                      CodeGenOpt::Level OL, bool JIT)
461     : AMDGPUTargetMachine(T, TT, CPU, FS, Options, RM, CM, OL) {
462   setRequiresStructuredCFG(true);
463 
464   // Override the default since calls aren't supported for r600.
465   if (EnableFunctionCalls &&
466       EnableAMDGPUFunctionCallsOpt.getNumOccurrences() == 0)
467     EnableFunctionCalls = false;
468 }
469 
470 const R600Subtarget *R600TargetMachine::getSubtargetImpl(
471   const Function &F) const {
472   StringRef GPU = getGPUName(F);
473   StringRef FS = getFeatureString(F);
474 
475   SmallString<128> SubtargetKey(GPU);
476   SubtargetKey.append(FS);
477 
478   auto &I = SubtargetMap[SubtargetKey];
479   if (!I) {
480     // This needs to be done before we create a new subtarget since any
481     // creation will depend on the TM and the code generation flags on the
482     // function that reside in TargetOptions.
483     resetTargetOptions(F);
484     I = llvm::make_unique<R600Subtarget>(TargetTriple, GPU, FS, *this);
485   }
486 
487   return I.get();
488 }
489 
490 TargetTransformInfo
491 R600TargetMachine::getTargetTransformInfo(const Function &F) {
492   return TargetTransformInfo(R600TTIImpl(this, F));
493 }
494 
495 //===----------------------------------------------------------------------===//
496 // GCN Target Machine (SI+)
497 //===----------------------------------------------------------------------===//
498 
499 GCNTargetMachine::GCNTargetMachine(const Target &T, const Triple &TT,
500                                    StringRef CPU, StringRef FS,
501                                    TargetOptions Options,
502                                    Optional<Reloc::Model> RM,
503                                    Optional<CodeModel::Model> CM,
504                                    CodeGenOpt::Level OL, bool JIT)
505     : AMDGPUTargetMachine(T, TT, CPU, FS, Options, RM, CM, OL) {}
506 
507 const GCNSubtarget *GCNTargetMachine::getSubtargetImpl(const Function &F) const {
508   StringRef GPU = getGPUName(F);
509   StringRef FS = getFeatureString(F);
510 
511   SmallString<128> SubtargetKey(GPU);
512   SubtargetKey.append(FS);
513 
514   auto &I = SubtargetMap[SubtargetKey];
515   if (!I) {
516     // This needs to be done before we create a new subtarget since any
517     // creation will depend on the TM and the code generation flags on the
518     // function that reside in TargetOptions.
519     resetTargetOptions(F);
520     I = llvm::make_unique<GCNSubtarget>(TargetTriple, GPU, FS, *this);
521   }
522 
523   I->setScalarizeGlobalBehavior(ScalarizeGlobal);
524 
525   return I.get();
526 }
527 
528 TargetTransformInfo
529 GCNTargetMachine::getTargetTransformInfo(const Function &F) {
530   return TargetTransformInfo(GCNTTIImpl(this, F));
531 }
532 
533 //===----------------------------------------------------------------------===//
534 // AMDGPU Pass Setup
535 //===----------------------------------------------------------------------===//
536 
537 namespace {
538 
539 class AMDGPUPassConfig : public TargetPassConfig {
540 public:
541   AMDGPUPassConfig(LLVMTargetMachine &TM, PassManagerBase &PM)
542     : TargetPassConfig(TM, PM) {
543     // Exceptions and StackMaps are not supported, so these passes will never do
544     // anything.
545     disablePass(&StackMapLivenessID);
546     disablePass(&FuncletLayoutID);
547   }
548 
549   AMDGPUTargetMachine &getAMDGPUTargetMachine() const {
550     return getTM<AMDGPUTargetMachine>();
551   }
552 
553   ScheduleDAGInstrs *
554   createMachineScheduler(MachineSchedContext *C) const override {
555     ScheduleDAGMILive *DAG = createGenericSchedLive(C);
556     DAG->addMutation(createLoadClusterDAGMutation(DAG->TII, DAG->TRI));
557     DAG->addMutation(createStoreClusterDAGMutation(DAG->TII, DAG->TRI));
558     return DAG;
559   }
560 
561   void addEarlyCSEOrGVNPass();
562   void addStraightLineScalarOptimizationPasses();
563   void addIRPasses() override;
564   void addCodeGenPrepare() override;
565   bool addPreISel() override;
566   bool addInstSelector() override;
567   bool addGCPasses() override;
568 
569   std::unique_ptr<CSEConfigBase> getCSEConfig() const override;
570 };
571 
572 std::unique_ptr<CSEConfigBase> AMDGPUPassConfig::getCSEConfig() const {
573   return getStandardCSEConfigForOpt(TM->getOptLevel());
574 }
575 
576 class R600PassConfig final : public AMDGPUPassConfig {
577 public:
578   R600PassConfig(LLVMTargetMachine &TM, PassManagerBase &PM)
579     : AMDGPUPassConfig(TM, PM) {}
580 
581   ScheduleDAGInstrs *createMachineScheduler(
582     MachineSchedContext *C) const override {
583     return createR600MachineScheduler(C);
584   }
585 
586   bool addPreISel() override;
587   bool addInstSelector() override;
588   void addPreRegAlloc() override;
589   void addPreSched2() override;
590   void addPreEmitPass() override;
591 };
592 
593 class GCNPassConfig final : public AMDGPUPassConfig {
594 public:
595   GCNPassConfig(LLVMTargetMachine &TM, PassManagerBase &PM)
596     : AMDGPUPassConfig(TM, PM) {
597     // It is necessary to know the register usage of the entire call graph.  We
598     // allow calls without EnableAMDGPUFunctionCalls if they are marked
599     // noinline, so this is always required.
600     setRequiresCodeGenSCCOrder(true);
601   }
602 
603   GCNTargetMachine &getGCNTargetMachine() const {
604     return getTM<GCNTargetMachine>();
605   }
606 
607   ScheduleDAGInstrs *
608   createMachineScheduler(MachineSchedContext *C) const override;
609 
610   bool addPreISel() override;
611   void addMachineSSAOptimization() override;
612   bool addILPOpts() override;
613   bool addInstSelector() override;
614   bool addIRTranslator() override;
615   bool addLegalizeMachineIR() override;
616   bool addRegBankSelect() override;
617   bool addGlobalInstructionSelect() override;
618   void addFastRegAlloc() override;
619   void addOptimizedRegAlloc() override;
620   void addPreRegAlloc() override;
621   bool addPreRewrite() override;
622   void addPostRegAlloc() override;
623   void addPreSched2() override;
624   void addPreEmitPass() override;
625 };
626 
627 } // end anonymous namespace
628 
629 void AMDGPUPassConfig::addEarlyCSEOrGVNPass() {
630   if (getOptLevel() == CodeGenOpt::Aggressive)
631     addPass(createGVNPass());
632   else
633     addPass(createEarlyCSEPass());
634 }
635 
636 void AMDGPUPassConfig::addStraightLineScalarOptimizationPasses() {
637   addPass(createLICMPass());
638   addPass(createSeparateConstOffsetFromGEPPass());
639   addPass(createSpeculativeExecutionPass());
640   // ReassociateGEPs exposes more opportunites for SLSR. See
641   // the example in reassociate-geps-and-slsr.ll.
642   addPass(createStraightLineStrengthReducePass());
643   // SeparateConstOffsetFromGEP and SLSR creates common expressions which GVN or
644   // EarlyCSE can reuse.
645   addEarlyCSEOrGVNPass();
646   // Run NaryReassociate after EarlyCSE/GVN to be more effective.
647   addPass(createNaryReassociatePass());
648   // NaryReassociate on GEPs creates redundant common expressions, so run
649   // EarlyCSE after it.
650   addPass(createEarlyCSEPass());
651 }
652 
653 void AMDGPUPassConfig::addIRPasses() {
654   const AMDGPUTargetMachine &TM = getAMDGPUTargetMachine();
655 
656   // There is no reason to run these.
657   disablePass(&StackMapLivenessID);
658   disablePass(&FuncletLayoutID);
659   disablePass(&PatchableFunctionID);
660 
661   // This must occur before inlining, as the inliner will not look through
662   // bitcast calls.
663   addPass(createAMDGPUFixFunctionBitcastsPass());
664 
665   // A call to propagate attributes pass in the backend in case opt was not run.
666   addPass(createAMDGPUPropagateAttributesEarlyPass(&TM));
667 
668   addPass(createAtomicExpandPass());
669 
670 
671   addPass(createAMDGPULowerIntrinsicsPass());
672 
673   // Function calls are not supported, so make sure we inline everything.
674   addPass(createAMDGPUAlwaysInlinePass());
675   addPass(createAlwaysInlinerLegacyPass());
676   // We need to add the barrier noop pass, otherwise adding the function
677   // inlining pass will cause all of the PassConfigs passes to be run
678   // one function at a time, which means if we have a nodule with two
679   // functions, then we will generate code for the first function
680   // without ever running any passes on the second.
681   addPass(createBarrierNoopPass());
682 
683   if (TM.getTargetTriple().getArch() == Triple::amdgcn) {
684     // TODO: May want to move later or split into an early and late one.
685 
686     addPass(createAMDGPUCodeGenPreparePass());
687   }
688 
689   // Handle uses of OpenCL image2d_t, image3d_t and sampler_t arguments.
690   if (TM.getTargetTriple().getArch() == Triple::r600)
691     addPass(createR600OpenCLImageTypeLoweringPass());
692 
693   // Replace OpenCL enqueued block function pointers with global variables.
694   addPass(createAMDGPUOpenCLEnqueuedBlockLoweringPass());
695 
696   if (TM.getOptLevel() > CodeGenOpt::None) {
697     addPass(createInferAddressSpacesPass());
698     addPass(createAMDGPUPromoteAlloca());
699 
700     if (EnableSROA)
701       addPass(createSROAPass());
702 
703     if (EnableScalarIRPasses)
704       addStraightLineScalarOptimizationPasses();
705 
706     if (EnableAMDGPUAliasAnalysis) {
707       addPass(createAMDGPUAAWrapperPass());
708       addPass(createExternalAAWrapperPass([](Pass &P, Function &,
709                                              AAResults &AAR) {
710         if (auto *WrapperPass = P.getAnalysisIfAvailable<AMDGPUAAWrapperPass>())
711           AAR.addAAResult(WrapperPass->getResult());
712         }));
713     }
714   }
715 
716   TargetPassConfig::addIRPasses();
717 
718   // EarlyCSE is not always strong enough to clean up what LSR produces. For
719   // example, GVN can combine
720   //
721   //   %0 = add %a, %b
722   //   %1 = add %b, %a
723   //
724   // and
725   //
726   //   %0 = shl nsw %a, 2
727   //   %1 = shl %a, 2
728   //
729   // but EarlyCSE can do neither of them.
730   if (getOptLevel() != CodeGenOpt::None && EnableScalarIRPasses)
731     addEarlyCSEOrGVNPass();
732 }
733 
734 void AMDGPUPassConfig::addCodeGenPrepare() {
735   if (TM->getTargetTriple().getArch() == Triple::amdgcn)
736     addPass(createAMDGPUAnnotateKernelFeaturesPass());
737 
738   if (TM->getTargetTriple().getArch() == Triple::amdgcn &&
739       EnableLowerKernelArguments)
740     addPass(createAMDGPULowerKernelArgumentsPass());
741 
742   TargetPassConfig::addCodeGenPrepare();
743 
744   if (EnableLoadStoreVectorizer)
745     addPass(createLoadStoreVectorizerPass());
746 }
747 
748 bool AMDGPUPassConfig::addPreISel() {
749   addPass(createLowerSwitchPass());
750   addPass(createFlattenCFGPass());
751   return false;
752 }
753 
754 bool AMDGPUPassConfig::addInstSelector() {
755   // Defer the verifier until FinalizeISel.
756   addPass(createAMDGPUISelDag(&getAMDGPUTargetMachine(), getOptLevel()), false);
757   return false;
758 }
759 
760 bool AMDGPUPassConfig::addGCPasses() {
761   // Do nothing. GC is not supported.
762   return false;
763 }
764 
765 //===----------------------------------------------------------------------===//
766 // R600 Pass Setup
767 //===----------------------------------------------------------------------===//
768 
769 bool R600PassConfig::addPreISel() {
770   AMDGPUPassConfig::addPreISel();
771 
772   if (EnableR600StructurizeCFG)
773     addPass(createStructurizeCFGPass());
774   return false;
775 }
776 
777 bool R600PassConfig::addInstSelector() {
778   addPass(createR600ISelDag(&getAMDGPUTargetMachine(), getOptLevel()));
779   return false;
780 }
781 
782 void R600PassConfig::addPreRegAlloc() {
783   addPass(createR600VectorRegMerger());
784 }
785 
786 void R600PassConfig::addPreSched2() {
787   addPass(createR600EmitClauseMarkers(), false);
788   if (EnableR600IfConvert)
789     addPass(&IfConverterID, false);
790   addPass(createR600ClauseMergePass(), false);
791 }
792 
793 void R600PassConfig::addPreEmitPass() {
794   addPass(createAMDGPUCFGStructurizerPass(), false);
795   addPass(createR600ExpandSpecialInstrsPass(), false);
796   addPass(&FinalizeMachineBundlesID, false);
797   addPass(createR600Packetizer(), false);
798   addPass(createR600ControlFlowFinalizer(), false);
799 }
800 
801 TargetPassConfig *R600TargetMachine::createPassConfig(PassManagerBase &PM) {
802   return new R600PassConfig(*this, PM);
803 }
804 
805 //===----------------------------------------------------------------------===//
806 // GCN Pass Setup
807 //===----------------------------------------------------------------------===//
808 
809 ScheduleDAGInstrs *GCNPassConfig::createMachineScheduler(
810   MachineSchedContext *C) const {
811   const GCNSubtarget &ST = C->MF->getSubtarget<GCNSubtarget>();
812   if (ST.enableSIScheduler())
813     return createSIMachineScheduler(C);
814   return createGCNMaxOccupancyMachineScheduler(C);
815 }
816 
817 bool GCNPassConfig::addPreISel() {
818   AMDGPUPassConfig::addPreISel();
819 
820   if (EnableAtomicOptimizations) {
821     addPass(createAMDGPUAtomicOptimizerPass());
822   }
823 
824   // FIXME: We need to run a pass to propagate the attributes when calls are
825   // supported.
826 
827   // Merge divergent exit nodes. StructurizeCFG won't recognize the multi-exit
828   // regions formed by them.
829   addPass(&AMDGPUUnifyDivergentExitNodesID);
830   if (!LateCFGStructurize) {
831     addPass(createStructurizeCFGPass(true)); // true -> SkipUniformRegions
832   }
833   addPass(createSinkingPass());
834   addPass(createAMDGPUAnnotateUniformValues());
835   if (!LateCFGStructurize) {
836     addPass(createSIAnnotateControlFlowPass());
837   }
838 
839   return false;
840 }
841 
842 void GCNPassConfig::addMachineSSAOptimization() {
843   TargetPassConfig::addMachineSSAOptimization();
844 
845   // We want to fold operands after PeepholeOptimizer has run (or as part of
846   // it), because it will eliminate extra copies making it easier to fold the
847   // real source operand. We want to eliminate dead instructions after, so that
848   // we see fewer uses of the copies. We then need to clean up the dead
849   // instructions leftover after the operands are folded as well.
850   //
851   // XXX - Can we get away without running DeadMachineInstructionElim again?
852   addPass(&SIFoldOperandsID);
853   if (EnableDPPCombine)
854     addPass(&GCNDPPCombineID);
855   addPass(&DeadMachineInstructionElimID);
856   addPass(&SILoadStoreOptimizerID);
857   if (EnableSDWAPeephole) {
858     addPass(&SIPeepholeSDWAID);
859     addPass(&EarlyMachineLICMID);
860     addPass(&MachineCSEID);
861     addPass(&SIFoldOperandsID);
862     addPass(&DeadMachineInstructionElimID);
863   }
864   addPass(createSIShrinkInstructionsPass());
865 }
866 
867 bool GCNPassConfig::addILPOpts() {
868   if (EnableEarlyIfConversion)
869     addPass(&EarlyIfConverterID);
870 
871   TargetPassConfig::addILPOpts();
872   return false;
873 }
874 
875 bool GCNPassConfig::addInstSelector() {
876   AMDGPUPassConfig::addInstSelector();
877   addPass(&SIFixSGPRCopiesID);
878   addPass(createSILowerI1CopiesPass());
879   addPass(createSIFixupVectorISelPass());
880   addPass(createSIAddIMGInitPass());
881   return false;
882 }
883 
884 bool GCNPassConfig::addIRTranslator() {
885   addPass(new IRTranslator());
886   return false;
887 }
888 
889 bool GCNPassConfig::addLegalizeMachineIR() {
890   addPass(new Legalizer());
891   return false;
892 }
893 
894 bool GCNPassConfig::addRegBankSelect() {
895   addPass(new RegBankSelect());
896   return false;
897 }
898 
899 bool GCNPassConfig::addGlobalInstructionSelect() {
900   addPass(new InstructionSelect());
901   return false;
902 }
903 
904 void GCNPassConfig::addPreRegAlloc() {
905   if (LateCFGStructurize) {
906     addPass(createAMDGPUMachineCFGStructurizerPass());
907   }
908   addPass(createSIWholeQuadModePass());
909 }
910 
911 void GCNPassConfig::addFastRegAlloc() {
912   // FIXME: We have to disable the verifier here because of PHIElimination +
913   // TwoAddressInstructions disabling it.
914 
915   // This must be run immediately after phi elimination and before
916   // TwoAddressInstructions, otherwise the processing of the tied operand of
917   // SI_ELSE will introduce a copy of the tied operand source after the else.
918   insertPass(&PHIEliminationID, &SILowerControlFlowID, false);
919 
920   // This must be run just after RegisterCoalescing.
921   insertPass(&RegisterCoalescerID, &SIPreAllocateWWMRegsID, false);
922 
923   TargetPassConfig::addFastRegAlloc();
924 }
925 
926 void GCNPassConfig::addOptimizedRegAlloc() {
927   if (OptExecMaskPreRA) {
928     insertPass(&MachineSchedulerID, &SIOptimizeExecMaskingPreRAID);
929     insertPass(&SIOptimizeExecMaskingPreRAID, &SIFormMemoryClausesID);
930   } else {
931     insertPass(&MachineSchedulerID, &SIFormMemoryClausesID);
932   }
933 
934   // This must be run immediately after phi elimination and before
935   // TwoAddressInstructions, otherwise the processing of the tied operand of
936   // SI_ELSE will introduce a copy of the tied operand source after the else.
937   insertPass(&PHIEliminationID, &SILowerControlFlowID, false);
938 
939   // This must be run just after RegisterCoalescing.
940   insertPass(&RegisterCoalescerID, &SIPreAllocateWWMRegsID, false);
941 
942   if (EnableDCEInRA)
943     insertPass(&RenameIndependentSubregsID, &DeadMachineInstructionElimID);
944 
945   TargetPassConfig::addOptimizedRegAlloc();
946 }
947 
948 bool GCNPassConfig::addPreRewrite() {
949   if (EnableRegReassign) {
950     addPass(&GCNNSAReassignID);
951     addPass(&GCNRegBankReassignID);
952   }
953   return true;
954 }
955 
956 void GCNPassConfig::addPostRegAlloc() {
957   addPass(&SIFixVGPRCopiesID);
958   if (getOptLevel() > CodeGenOpt::None)
959     addPass(&SIOptimizeExecMaskingID);
960   TargetPassConfig::addPostRegAlloc();
961 }
962 
963 void GCNPassConfig::addPreSched2() {
964 }
965 
966 void GCNPassConfig::addPreEmitPass() {
967   addPass(createSIMemoryLegalizerPass());
968   addPass(createSIInsertWaitcntsPass());
969   addPass(createSIShrinkInstructionsPass());
970   addPass(createSIModeRegisterPass());
971 
972   // The hazard recognizer that runs as part of the post-ra scheduler does not
973   // guarantee to be able handle all hazards correctly. This is because if there
974   // are multiple scheduling regions in a basic block, the regions are scheduled
975   // bottom up, so when we begin to schedule a region we don't know what
976   // instructions were emitted directly before it.
977   //
978   // Here we add a stand-alone hazard recognizer pass which can handle all
979   // cases.
980   //
981   // FIXME: This stand-alone pass will emit indiv. S_NOP 0, as needed. It would
982   // be better for it to emit S_NOP <N> when possible.
983   addPass(&PostRAHazardRecognizerID);
984 
985   addPass(&SIInsertSkipsPassID);
986   addPass(&BranchRelaxationPassID);
987 }
988 
989 TargetPassConfig *GCNTargetMachine::createPassConfig(PassManagerBase &PM) {
990   return new GCNPassConfig(*this, PM);
991 }
992 
993 yaml::MachineFunctionInfo *GCNTargetMachine::createDefaultFuncInfoYAML() const {
994   return new yaml::SIMachineFunctionInfo();
995 }
996 
997 yaml::MachineFunctionInfo *
998 GCNTargetMachine::convertFuncInfoToYAML(const MachineFunction &MF) const {
999   const SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
1000   return new yaml::SIMachineFunctionInfo(*MFI,
1001                                          *MF.getSubtarget().getRegisterInfo());
1002 }
1003 
1004 bool GCNTargetMachine::parseMachineFunctionInfo(
1005     const yaml::MachineFunctionInfo &MFI_, PerFunctionMIParsingState &PFS,
1006     SMDiagnostic &Error, SMRange &SourceRange) const {
1007   const yaml::SIMachineFunctionInfo &YamlMFI =
1008       reinterpret_cast<const yaml::SIMachineFunctionInfo &>(MFI_);
1009   MachineFunction &MF = PFS.MF;
1010   SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
1011 
1012   MFI->initializeBaseYamlFields(YamlMFI);
1013 
1014   auto parseRegister = [&](const yaml::StringValue &RegName, unsigned &RegVal) {
1015     if (parseNamedRegisterReference(PFS, RegVal, RegName.Value, Error)) {
1016       SourceRange = RegName.SourceRange;
1017       return true;
1018     }
1019 
1020     return false;
1021   };
1022 
1023   auto diagnoseRegisterClass = [&](const yaml::StringValue &RegName) {
1024     // Create a diagnostic for a the register string literal.
1025     const MemoryBuffer &Buffer =
1026         *PFS.SM->getMemoryBuffer(PFS.SM->getMainFileID());
1027     Error = SMDiagnostic(*PFS.SM, SMLoc(), Buffer.getBufferIdentifier(), 1,
1028                          RegName.Value.size(), SourceMgr::DK_Error,
1029                          "incorrect register class for field", RegName.Value,
1030                          None, None);
1031     SourceRange = RegName.SourceRange;
1032     return true;
1033   };
1034 
1035   if (parseRegister(YamlMFI.ScratchRSrcReg, MFI->ScratchRSrcReg) ||
1036       parseRegister(YamlMFI.ScratchWaveOffsetReg, MFI->ScratchWaveOffsetReg) ||
1037       parseRegister(YamlMFI.FrameOffsetReg, MFI->FrameOffsetReg) ||
1038       parseRegister(YamlMFI.StackPtrOffsetReg, MFI->StackPtrOffsetReg))
1039     return true;
1040 
1041   if (MFI->ScratchRSrcReg != AMDGPU::PRIVATE_RSRC_REG &&
1042       !AMDGPU::SReg_128RegClass.contains(MFI->ScratchRSrcReg)) {
1043     return diagnoseRegisterClass(YamlMFI.ScratchRSrcReg);
1044   }
1045 
1046   if (MFI->ScratchWaveOffsetReg != AMDGPU::SCRATCH_WAVE_OFFSET_REG &&
1047       !AMDGPU::SGPR_32RegClass.contains(MFI->ScratchWaveOffsetReg)) {
1048     return diagnoseRegisterClass(YamlMFI.ScratchWaveOffsetReg);
1049   }
1050 
1051   if (MFI->FrameOffsetReg != AMDGPU::FP_REG &&
1052       !AMDGPU::SGPR_32RegClass.contains(MFI->FrameOffsetReg)) {
1053     return diagnoseRegisterClass(YamlMFI.FrameOffsetReg);
1054   }
1055 
1056   if (MFI->StackPtrOffsetReg != AMDGPU::SP_REG &&
1057       !AMDGPU::SGPR_32RegClass.contains(MFI->StackPtrOffsetReg)) {
1058     return diagnoseRegisterClass(YamlMFI.StackPtrOffsetReg);
1059   }
1060 
1061   return false;
1062 }
1063