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