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