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