]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - contrib/llvm/lib/Target/AMDGPU/AMDGPUTargetMachine.cpp
Merge llvm, clang, lld and lldb trunk r300890, and update build glue.
[FreeBSD/FreeBSD.git] / contrib / llvm / lib / Target / AMDGPU / AMDGPUTargetMachine.cpp
1 //===-- AMDGPUTargetMachine.cpp - TargetMachine for hw codegen targets-----===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 /// \file
11 /// \brief The AMDGPU target machine contains all of the hardware specific
12 /// information  needed to emit code for R600 and SI GPUs.
13 //
14 //===----------------------------------------------------------------------===//
15
16 #include "AMDGPUTargetMachine.h"
17 #include "AMDGPU.h"
18 #include "AMDGPUAliasAnalysis.h"
19 #include "AMDGPUCallLowering.h"
20 #include "AMDGPUInstructionSelector.h"
21 #include "AMDGPULegalizerInfo.h"
22 #ifdef LLVM_BUILD_GLOBAL_ISEL
23 #include "AMDGPURegisterBankInfo.h"
24 #endif
25 #include "AMDGPUTargetObjectFile.h"
26 #include "AMDGPUTargetTransformInfo.h"
27 #include "GCNIterativeScheduler.h"
28 #include "GCNSchedStrategy.h"
29 #include "R600MachineScheduler.h"
30 #include "SIMachineScheduler.h"
31 #include "llvm/CodeGen/GlobalISel/InstructionSelect.h"
32 #include "llvm/CodeGen/GlobalISel/IRTranslator.h"
33 #include "llvm/CodeGen/GlobalISel/Legalizer.h"
34 #include "llvm/CodeGen/GlobalISel/RegBankSelect.h"
35 #include "llvm/CodeGen/Passes.h"
36 #include "llvm/CodeGen/TargetPassConfig.h"
37 #include "llvm/Support/TargetRegistry.h"
38 #include "llvm/Transforms/IPO.h"
39 #include "llvm/Transforms/IPO/AlwaysInliner.h"
40 #include "llvm/Transforms/IPO/PassManagerBuilder.h"
41 #include "llvm/Transforms/Scalar.h"
42 #include "llvm/Transforms/Scalar/GVN.h"
43 #include "llvm/Transforms/Vectorize.h"
44 #include "llvm/IR/Attributes.h"
45 #include "llvm/IR/Function.h"
46 #include "llvm/IR/LegacyPassManager.h"
47 #include "llvm/Pass.h"
48 #include "llvm/Support/CommandLine.h"
49 #include "llvm/Support/Compiler.h"
50 #include "llvm/Target/TargetLoweringObjectFile.h"
51 #include <memory>
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> EnableR600IfConvert(
72   "r600-if-convert",
73   cl::desc("Use if conversion pass"),
74   cl::ReallyHidden,
75   cl::init(true));
76
77 // Option to disable vectorizer for tests.
78 static cl::opt<bool> EnableLoadStoreVectorizer(
79   "amdgpu-load-store-vectorizer",
80   cl::desc("Enable load store vectorizer"),
81   cl::init(true),
82   cl::Hidden);
83
84 // Option to to control global loads scalarization
85 static cl::opt<bool> ScalarizeGlobal(
86   "amdgpu-scalarize-global-loads",
87   cl::desc("Enable global load scalarization"),
88   cl::init(false),
89   cl::Hidden);
90
91 // Option to run internalize pass.
92 static cl::opt<bool> InternalizeSymbols(
93   "amdgpu-internalize-symbols",
94   cl::desc("Enable elimination of non-kernel functions and unused globals"),
95   cl::init(false),
96   cl::Hidden);
97
98 // Option to inline all early.
99 static cl::opt<bool> EarlyInlineAll(
100   "amdgpu-early-inline-all",
101   cl::desc("Inline all functions early"),
102   cl::init(false),
103   cl::Hidden);
104
105 static cl::opt<bool> EnableSDWAPeephole(
106   "amdgpu-sdwa-peephole",
107   cl::desc("Enable SDWA peepholer"),
108   cl::init(true));
109
110 // Enable address space based alias analysis
111 static cl::opt<bool> EnableAMDGPUAliasAnalysis("enable-amdgpu-aa", cl::Hidden,
112   cl::desc("Enable AMDGPU Alias Analysis"),
113   cl::init(true));
114
115 // Option to enable new waitcnt insertion pass.
116 static cl::opt<bool> EnableSIInsertWaitcntsPass(
117   "enable-si-insert-waitcnts",
118   cl::desc("Use new waitcnt insertion pass"),
119   cl::init(false));
120
121 extern "C" void LLVMInitializeAMDGPUTarget() {
122   // Register the target
123   RegisterTargetMachine<R600TargetMachine> X(getTheAMDGPUTarget());
124   RegisterTargetMachine<GCNTargetMachine> Y(getTheGCNTarget());
125
126   PassRegistry *PR = PassRegistry::getPassRegistry();
127   initializeSILowerI1CopiesPass(*PR);
128   initializeSIFixSGPRCopiesPass(*PR);
129   initializeSIFixVGPRCopiesPass(*PR);
130   initializeSIFoldOperandsPass(*PR);
131   initializeSIPeepholeSDWAPass(*PR);
132   initializeSIShrinkInstructionsPass(*PR);
133   initializeSIFixControlFlowLiveIntervalsPass(*PR);
134   initializeSILoadStoreOptimizerPass(*PR);
135   initializeAMDGPUAnnotateKernelFeaturesPass(*PR);
136   initializeAMDGPUAnnotateUniformValuesPass(*PR);
137   initializeAMDGPULowerIntrinsicsPass(*PR);
138   initializeAMDGPUPromoteAllocaPass(*PR);
139   initializeAMDGPUCodeGenPreparePass(*PR);
140   initializeAMDGPUUnifyMetadataPass(*PR);
141   initializeSIAnnotateControlFlowPass(*PR);
142   initializeSIInsertWaitsPass(*PR);
143   initializeSIInsertWaitcntsPass(*PR);
144   initializeSIWholeQuadModePass(*PR);
145   initializeSILowerControlFlowPass(*PR);
146   initializeSIInsertSkipsPass(*PR);
147   initializeSIDebuggerInsertNopsPass(*PR);
148   initializeSIOptimizeExecMaskingPass(*PR);
149   initializeAMDGPUUnifyDivergentExitNodesPass(*PR);
150   initializeAMDGPUAAWrapperPassPass(*PR);
151 }
152
153 static std::unique_ptr<TargetLoweringObjectFile> createTLOF(const Triple &TT) {
154   return llvm::make_unique<AMDGPUTargetObjectFile>();
155 }
156
157 static ScheduleDAGInstrs *createR600MachineScheduler(MachineSchedContext *C) {
158   return new ScheduleDAGMILive(C, llvm::make_unique<R600SchedStrategy>());
159 }
160
161 static ScheduleDAGInstrs *createSIMachineScheduler(MachineSchedContext *C) {
162   return new SIScheduleDAGMI(C);
163 }
164
165 static ScheduleDAGInstrs *
166 createGCNMaxOccupancyMachineScheduler(MachineSchedContext *C) {
167   ScheduleDAGMILive *DAG =
168     new GCNScheduleDAGMILive(C, make_unique<GCNMaxOccupancySchedStrategy>(C));
169   DAG->addMutation(createLoadClusterDAGMutation(DAG->TII, DAG->TRI));
170   DAG->addMutation(createStoreClusterDAGMutation(DAG->TII, DAG->TRI));
171   return DAG;
172 }
173
174 static ScheduleDAGInstrs *
175 createIterativeGCNMaxOccupancyMachineScheduler(MachineSchedContext *C) {
176   auto DAG = new GCNIterativeScheduler(C,
177     GCNIterativeScheduler::SCHEDULE_LEGACYMAXOCCUPANCY);
178   DAG->addMutation(createLoadClusterDAGMutation(DAG->TII, DAG->TRI));
179   DAG->addMutation(createStoreClusterDAGMutation(DAG->TII, DAG->TRI));
180   return DAG;
181 }
182
183 static ScheduleDAGInstrs *createMinRegScheduler(MachineSchedContext *C) {
184   return new GCNIterativeScheduler(C,
185     GCNIterativeScheduler::SCHEDULE_MINREGFORCED);
186 }
187
188 static MachineSchedRegistry
189 R600SchedRegistry("r600", "Run R600's custom scheduler",
190                    createR600MachineScheduler);
191
192 static MachineSchedRegistry
193 SISchedRegistry("si", "Run SI's custom scheduler",
194                 createSIMachineScheduler);
195
196 static MachineSchedRegistry
197 GCNMaxOccupancySchedRegistry("gcn-max-occupancy",
198                              "Run GCN scheduler to maximize occupancy",
199                              createGCNMaxOccupancyMachineScheduler);
200
201 static MachineSchedRegistry
202 IterativeGCNMaxOccupancySchedRegistry("gcn-max-occupancy-experimental",
203   "Run GCN scheduler to maximize occupancy (experimental)",
204   createIterativeGCNMaxOccupancyMachineScheduler);
205
206 static MachineSchedRegistry
207 GCNMinRegSchedRegistry("gcn-minreg",
208   "Run GCN iterative scheduler for minimal register usage (experimental)",
209   createMinRegScheduler);
210
211 static StringRef computeDataLayout(const Triple &TT) {
212   if (TT.getArch() == Triple::r600) {
213     // 32-bit pointers.
214     return "e-p:32:32-i64:64-v16:16-v24:32-v32:32-v48:64-v96:128"
215             "-v192:256-v256:256-v512:512-v1024:1024-v2048:2048-n32:64";
216   }
217
218   // 32-bit private, local, and region pointers. 64-bit global, constant and
219   // flat.
220   if (TT.getEnvironmentName() == "amdgiz" ||
221       TT.getEnvironmentName() == "amdgizcl")
222     return "e-p:64:64-p1:64:64-p2:64:64-p3:32:32-p4:32:32-p5:32:32"
223          "-i64:64-v16:16-v24:32-v32:32-v48:64-v96:128"
224          "-v192:256-v256:256-v512:512-v1024:1024-v2048:2048-n32:64-A5";
225   return "e-p:32:32-p1:64:64-p2:64:64-p3:32:32-p4:64:64-p5:32:32"
226       "-i64:64-v16:16-v24:32-v32:32-v48:64-v96:128"
227       "-v192:256-v256:256-v512:512-v1024:1024-v2048:2048-n32:64";
228 }
229
230 LLVM_READNONE
231 static StringRef getGPUOrDefault(const Triple &TT, StringRef GPU) {
232   if (!GPU.empty())
233     return GPU;
234
235   // HSA only supports CI+, so change the default GPU to a CI for HSA.
236   if (TT.getArch() == Triple::amdgcn)
237     return (TT.getOS() == Triple::AMDHSA) ? "kaveri" : "tahiti";
238
239   return "r600";
240 }
241
242 static Reloc::Model getEffectiveRelocModel(Optional<Reloc::Model> RM) {
243   // The AMDGPU toolchain only supports generating shared objects, so we
244   // must always use PIC.
245   return Reloc::PIC_;
246 }
247
248 AMDGPUTargetMachine::AMDGPUTargetMachine(const Target &T, const Triple &TT,
249                                          StringRef CPU, StringRef FS,
250                                          TargetOptions Options,
251                                          Optional<Reloc::Model> RM,
252                                          CodeModel::Model CM,
253                                          CodeGenOpt::Level OptLevel)
254   : LLVMTargetMachine(T, computeDataLayout(TT), TT, getGPUOrDefault(TT, CPU),
255                       FS, Options, getEffectiveRelocModel(RM), CM, OptLevel),
256     TLOF(createTLOF(getTargetTriple())) {
257   AS = AMDGPU::getAMDGPUAS(TT);
258   initAsmInfo();
259 }
260
261 AMDGPUTargetMachine::~AMDGPUTargetMachine() = default;
262
263 StringRef AMDGPUTargetMachine::getGPUName(const Function &F) const {
264   Attribute GPUAttr = F.getFnAttribute("target-cpu");
265   return GPUAttr.hasAttribute(Attribute::None) ?
266     getTargetCPU() : GPUAttr.getValueAsString();
267 }
268
269 StringRef AMDGPUTargetMachine::getFeatureString(const Function &F) const {
270   Attribute FSAttr = F.getFnAttribute("target-features");
271
272   return FSAttr.hasAttribute(Attribute::None) ?
273     getTargetFeatureString() :
274     FSAttr.getValueAsString();
275 }
276
277 static ImmutablePass *createAMDGPUExternalAAWrapperPass() {
278   return createExternalAAWrapperPass([](Pass &P, Function &, AAResults &AAR) {
279       if (auto *WrapperPass = P.getAnalysisIfAvailable<AMDGPUAAWrapperPass>())
280         AAR.addAAResult(WrapperPass->getResult());
281       });
282 }
283
284 void AMDGPUTargetMachine::adjustPassManager(PassManagerBuilder &Builder) {
285   Builder.DivergentTarget = true;
286
287   bool Internalize = InternalizeSymbols &&
288                      (getOptLevel() > CodeGenOpt::None) &&
289                      (getTargetTriple().getArch() == Triple::amdgcn);
290   bool EarlyInline = EarlyInlineAll &&
291                      (getOptLevel() > CodeGenOpt::None);
292   bool AMDGPUAA = EnableAMDGPUAliasAnalysis && getOptLevel() > CodeGenOpt::None;
293
294   Builder.addExtension(
295     PassManagerBuilder::EP_ModuleOptimizerEarly,
296     [Internalize, EarlyInline, AMDGPUAA](const PassManagerBuilder &,
297                                          legacy::PassManagerBase &PM) {
298       if (AMDGPUAA) {
299         PM.add(createAMDGPUAAWrapperPass());
300         PM.add(createAMDGPUExternalAAWrapperPass());
301       }
302       PM.add(createAMDGPUUnifyMetadataPass());
303       if (Internalize) {
304         PM.add(createInternalizePass([=](const GlobalValue &GV) -> bool {
305           if (const Function *F = dyn_cast<Function>(&GV)) {
306             if (F->isDeclaration())
307                 return true;
308             switch (F->getCallingConv()) {
309             default:
310               return false;
311             case CallingConv::AMDGPU_VS:
312             case CallingConv::AMDGPU_GS:
313             case CallingConv::AMDGPU_PS:
314             case CallingConv::AMDGPU_CS:
315             case CallingConv::AMDGPU_KERNEL:
316             case CallingConv::SPIR_KERNEL:
317               return true;
318             }
319           }
320           return !GV.use_empty();
321         }));
322         PM.add(createGlobalDCEPass());
323       }
324       if (EarlyInline)
325         PM.add(createAMDGPUAlwaysInlinePass(false));
326   });
327
328   Builder.addExtension(
329     PassManagerBuilder::EP_EarlyAsPossible,
330     [AMDGPUAA](const PassManagerBuilder &, legacy::PassManagerBase &PM) {
331       if (AMDGPUAA) {
332         PM.add(createAMDGPUAAWrapperPass());
333         PM.add(createAMDGPUExternalAAWrapperPass());
334       }
335   });
336 }
337
338 //===----------------------------------------------------------------------===//
339 // R600 Target Machine (R600 -> Cayman)
340 //===----------------------------------------------------------------------===//
341
342 R600TargetMachine::R600TargetMachine(const Target &T, const Triple &TT,
343                                      StringRef CPU, StringRef FS,
344                                      TargetOptions Options,
345                                      Optional<Reloc::Model> RM,
346                                      CodeModel::Model CM, CodeGenOpt::Level OL)
347   : AMDGPUTargetMachine(T, TT, CPU, FS, Options, RM, CM, OL) {
348   setRequiresStructuredCFG(true);
349 }
350
351 const R600Subtarget *R600TargetMachine::getSubtargetImpl(
352   const Function &F) const {
353   StringRef GPU = getGPUName(F);
354   StringRef FS = getFeatureString(F);
355
356   SmallString<128> SubtargetKey(GPU);
357   SubtargetKey.append(FS);
358
359   auto &I = SubtargetMap[SubtargetKey];
360   if (!I) {
361     // This needs to be done before we create a new subtarget since any
362     // creation will depend on the TM and the code generation flags on the
363     // function that reside in TargetOptions.
364     resetTargetOptions(F);
365     I = llvm::make_unique<R600Subtarget>(TargetTriple, GPU, FS, *this);
366   }
367
368   return I.get();
369 }
370
371 //===----------------------------------------------------------------------===//
372 // GCN Target Machine (SI+)
373 //===----------------------------------------------------------------------===//
374
375 #ifdef LLVM_BUILD_GLOBAL_ISEL
376 namespace {
377
378 struct SIGISelActualAccessor : public GISelAccessor {
379   std::unique_ptr<AMDGPUCallLowering> CallLoweringInfo;
380   std::unique_ptr<InstructionSelector> InstSelector;
381   std::unique_ptr<LegalizerInfo> Legalizer;
382   std::unique_ptr<RegisterBankInfo> RegBankInfo;
383   const AMDGPUCallLowering *getCallLowering() const override {
384     return CallLoweringInfo.get();
385   }
386   const InstructionSelector *getInstructionSelector() const override {
387     return InstSelector.get();
388   }
389   const LegalizerInfo *getLegalizerInfo() const override {
390     return Legalizer.get();
391   }
392   const RegisterBankInfo *getRegBankInfo() const override {
393     return RegBankInfo.get();
394   }
395 };
396
397 } // end anonymous namespace
398 #endif
399
400 GCNTargetMachine::GCNTargetMachine(const Target &T, const Triple &TT,
401                                    StringRef CPU, StringRef FS,
402                                    TargetOptions Options,
403                                    Optional<Reloc::Model> RM,
404                                    CodeModel::Model CM, CodeGenOpt::Level OL)
405   : AMDGPUTargetMachine(T, TT, CPU, FS, Options, RM, CM, OL) {}
406
407 const SISubtarget *GCNTargetMachine::getSubtargetImpl(const Function &F) const {
408   StringRef GPU = getGPUName(F);
409   StringRef FS = getFeatureString(F);
410
411   SmallString<128> SubtargetKey(GPU);
412   SubtargetKey.append(FS);
413
414   auto &I = SubtargetMap[SubtargetKey];
415   if (!I) {
416     // This needs to be done before we create a new subtarget since any
417     // creation will depend on the TM and the code generation flags on the
418     // function that reside in TargetOptions.
419     resetTargetOptions(F);
420     I = llvm::make_unique<SISubtarget>(TargetTriple, GPU, FS, *this);
421
422 #ifndef LLVM_BUILD_GLOBAL_ISEL
423     GISelAccessor *GISel = new GISelAccessor();
424 #else
425     SIGISelActualAccessor *GISel = new SIGISelActualAccessor();
426     GISel->CallLoweringInfo.reset(
427       new AMDGPUCallLowering(*I->getTargetLowering()));
428     GISel->Legalizer.reset(new AMDGPULegalizerInfo());
429
430     GISel->RegBankInfo.reset(new AMDGPURegisterBankInfo(*I->getRegisterInfo()));
431     GISel->InstSelector.reset(new AMDGPUInstructionSelector(*I,
432                                 *static_cast<AMDGPURegisterBankInfo*>(GISel->RegBankInfo.get())));
433 #endif
434
435     I->setGISelAccessor(*GISel);
436   }
437
438   I->setScalarizeGlobalBehavior(ScalarizeGlobal);
439
440   return I.get();
441 }
442
443 //===----------------------------------------------------------------------===//
444 // AMDGPU Pass Setup
445 //===----------------------------------------------------------------------===//
446
447 namespace {
448
449 class AMDGPUPassConfig : public TargetPassConfig {
450 public:
451   AMDGPUPassConfig(TargetMachine *TM, PassManagerBase &PM)
452     : TargetPassConfig(TM, PM) {
453     // Exceptions and StackMaps are not supported, so these passes will never do
454     // anything.
455     disablePass(&StackMapLivenessID);
456     disablePass(&FuncletLayoutID);
457   }
458
459   AMDGPUTargetMachine &getAMDGPUTargetMachine() const {
460     return getTM<AMDGPUTargetMachine>();
461   }
462
463   ScheduleDAGInstrs *
464   createMachineScheduler(MachineSchedContext *C) const override {
465     ScheduleDAGMILive *DAG = createGenericSchedLive(C);
466     DAG->addMutation(createLoadClusterDAGMutation(DAG->TII, DAG->TRI));
467     DAG->addMutation(createStoreClusterDAGMutation(DAG->TII, DAG->TRI));
468     return DAG;
469   }
470
471   void addEarlyCSEOrGVNPass();
472   void addStraightLineScalarOptimizationPasses();
473   void addIRPasses() override;
474   void addCodeGenPrepare() override;
475   bool addPreISel() override;
476   bool addInstSelector() override;
477   bool addGCPasses() override;
478 };
479
480 class R600PassConfig final : public AMDGPUPassConfig {
481 public:
482   R600PassConfig(TargetMachine *TM, PassManagerBase &PM)
483     : AMDGPUPassConfig(TM, PM) {}
484
485   ScheduleDAGInstrs *createMachineScheduler(
486     MachineSchedContext *C) const override {
487     return createR600MachineScheduler(C);
488   }
489
490   bool addPreISel() override;
491   void addPreRegAlloc() override;
492   void addPreSched2() override;
493   void addPreEmitPass() override;
494 };
495
496 class GCNPassConfig final : public AMDGPUPassConfig {
497 public:
498   GCNPassConfig(TargetMachine *TM, PassManagerBase &PM)
499     : AMDGPUPassConfig(TM, PM) {}
500
501   GCNTargetMachine &getGCNTargetMachine() const {
502     return getTM<GCNTargetMachine>();
503   }
504
505   ScheduleDAGInstrs *
506   createMachineScheduler(MachineSchedContext *C) const override;
507
508   bool addPreISel() override;
509   void addMachineSSAOptimization() override;
510   bool addILPOpts() override;
511   bool addInstSelector() override;
512 #ifdef LLVM_BUILD_GLOBAL_ISEL
513   bool addIRTranslator() override;
514   bool addLegalizeMachineIR() override;
515   bool addRegBankSelect() override;
516   bool addGlobalInstructionSelect() override;
517 #endif
518   void addFastRegAlloc(FunctionPass *RegAllocPass) override;
519   void addOptimizedRegAlloc(FunctionPass *RegAllocPass) override;
520   void addPreRegAlloc() override;
521   void addPostRegAlloc() override;
522   void addPreSched2() override;
523   void addPreEmitPass() override;
524 };
525
526 } // end anonymous namespace
527
528 TargetIRAnalysis AMDGPUTargetMachine::getTargetIRAnalysis() {
529   return TargetIRAnalysis([this](const Function &F) {
530     return TargetTransformInfo(AMDGPUTTIImpl(this, F));
531   });
532 }
533
534 void AMDGPUPassConfig::addEarlyCSEOrGVNPass() {
535   if (getOptLevel() == CodeGenOpt::Aggressive)
536     addPass(createGVNPass());
537   else
538     addPass(createEarlyCSEPass());
539 }
540
541 void AMDGPUPassConfig::addStraightLineScalarOptimizationPasses() {
542   addPass(createSeparateConstOffsetFromGEPPass());
543   addPass(createSpeculativeExecutionPass());
544   // ReassociateGEPs exposes more opportunites for SLSR. See
545   // the example in reassociate-geps-and-slsr.ll.
546   addPass(createStraightLineStrengthReducePass());
547   // SeparateConstOffsetFromGEP and SLSR creates common expressions which GVN or
548   // EarlyCSE can reuse.
549   addEarlyCSEOrGVNPass();
550   // Run NaryReassociate after EarlyCSE/GVN to be more effective.
551   addPass(createNaryReassociatePass());
552   // NaryReassociate on GEPs creates redundant common expressions, so run
553   // EarlyCSE after it.
554   addPass(createEarlyCSEPass());
555 }
556
557 void AMDGPUPassConfig::addIRPasses() {
558   const AMDGPUTargetMachine &TM = getAMDGPUTargetMachine();
559
560   // There is no reason to run these.
561   disablePass(&StackMapLivenessID);
562   disablePass(&FuncletLayoutID);
563   disablePass(&PatchableFunctionID);
564
565   addPass(createAMDGPULowerIntrinsicsPass(&TM));
566
567   // Function calls are not supported, so make sure we inline everything.
568   addPass(createAMDGPUAlwaysInlinePass());
569   addPass(createAlwaysInlinerLegacyPass());
570   // We need to add the barrier noop pass, otherwise adding the function
571   // inlining pass will cause all of the PassConfigs passes to be run
572   // one function at a time, which means if we have a nodule with two
573   // functions, then we will generate code for the first function
574   // without ever running any passes on the second.
575   addPass(createBarrierNoopPass());
576
577   if (TM.getTargetTriple().getArch() == Triple::amdgcn) {
578     // TODO: May want to move later or split into an early and late one.
579
580     addPass(createAMDGPUCodeGenPreparePass(
581               static_cast<const GCNTargetMachine *>(&TM)));
582   }
583
584   // Handle uses of OpenCL image2d_t, image3d_t and sampler_t arguments.
585   addPass(createAMDGPUOpenCLImageTypeLoweringPass());
586
587   if (TM.getOptLevel() > CodeGenOpt::None) {
588     addPass(createInferAddressSpacesPass());
589     addPass(createAMDGPUPromoteAlloca(&TM));
590
591     if (EnableSROA)
592       addPass(createSROAPass());
593
594     addStraightLineScalarOptimizationPasses();
595
596     if (EnableAMDGPUAliasAnalysis) {
597       addPass(createAMDGPUAAWrapperPass());
598       addPass(createExternalAAWrapperPass([](Pass &P, Function &,
599                                              AAResults &AAR) {
600         if (auto *WrapperPass = P.getAnalysisIfAvailable<AMDGPUAAWrapperPass>())
601           AAR.addAAResult(WrapperPass->getResult());
602         }));
603     }
604   }
605
606   TargetPassConfig::addIRPasses();
607
608   // EarlyCSE is not always strong enough to clean up what LSR produces. For
609   // example, GVN can combine
610   //
611   //   %0 = add %a, %b
612   //   %1 = add %b, %a
613   //
614   // and
615   //
616   //   %0 = shl nsw %a, 2
617   //   %1 = shl %a, 2
618   //
619   // but EarlyCSE can do neither of them.
620   if (getOptLevel() != CodeGenOpt::None)
621     addEarlyCSEOrGVNPass();
622 }
623
624 void AMDGPUPassConfig::addCodeGenPrepare() {
625   TargetPassConfig::addCodeGenPrepare();
626
627   if (EnableLoadStoreVectorizer)
628     addPass(createLoadStoreVectorizerPass());
629 }
630
631 bool AMDGPUPassConfig::addPreISel() {
632   addPass(createFlattenCFGPass());
633   return false;
634 }
635
636 bool AMDGPUPassConfig::addInstSelector() {
637   addPass(createAMDGPUISelDag(getAMDGPUTargetMachine(), getOptLevel()));
638   return false;
639 }
640
641 bool AMDGPUPassConfig::addGCPasses() {
642   // Do nothing. GC is not supported.
643   return false;
644 }
645
646 //===----------------------------------------------------------------------===//
647 // R600 Pass Setup
648 //===----------------------------------------------------------------------===//
649
650 bool R600PassConfig::addPreISel() {
651   AMDGPUPassConfig::addPreISel();
652
653   if (EnableR600StructurizeCFG)
654     addPass(createStructurizeCFGPass());
655   return false;
656 }
657
658 void R600PassConfig::addPreRegAlloc() {
659   addPass(createR600VectorRegMerger(*TM));
660 }
661
662 void R600PassConfig::addPreSched2() {
663   addPass(createR600EmitClauseMarkers(), false);
664   if (EnableR600IfConvert)
665     addPass(&IfConverterID, false);
666   addPass(createR600ClauseMergePass(*TM), false);
667 }
668
669 void R600PassConfig::addPreEmitPass() {
670   addPass(createAMDGPUCFGStructurizerPass(), false);
671   addPass(createR600ExpandSpecialInstrsPass(*TM), false);
672   addPass(&FinalizeMachineBundlesID, false);
673   addPass(createR600Packetizer(*TM), false);
674   addPass(createR600ControlFlowFinalizer(*TM), false);
675 }
676
677 TargetPassConfig *R600TargetMachine::createPassConfig(PassManagerBase &PM) {
678   return new R600PassConfig(this, PM);
679 }
680
681 //===----------------------------------------------------------------------===//
682 // GCN Pass Setup
683 //===----------------------------------------------------------------------===//
684
685 ScheduleDAGInstrs *GCNPassConfig::createMachineScheduler(
686   MachineSchedContext *C) const {
687   const SISubtarget &ST = C->MF->getSubtarget<SISubtarget>();
688   if (ST.enableSIScheduler())
689     return createSIMachineScheduler(C);
690   return createGCNMaxOccupancyMachineScheduler(C);
691 }
692
693 bool GCNPassConfig::addPreISel() {
694   AMDGPUPassConfig::addPreISel();
695
696   // FIXME: We need to run a pass to propagate the attributes when calls are
697   // supported.
698   const AMDGPUTargetMachine &TM = getAMDGPUTargetMachine();
699   addPass(createAMDGPUAnnotateKernelFeaturesPass(&TM));
700
701   // Merge divergent exit nodes. StructurizeCFG won't recognize the multi-exit
702   // regions formed by them.
703   addPass(&AMDGPUUnifyDivergentExitNodesID);
704   addPass(createStructurizeCFGPass(true)); // true -> SkipUniformRegions
705   addPass(createSinkingPass());
706   addPass(createSITypeRewriter());
707   addPass(createAMDGPUAnnotateUniformValues());
708   addPass(createSIAnnotateControlFlowPass());
709
710   return false;
711 }
712
713 void GCNPassConfig::addMachineSSAOptimization() {
714   TargetPassConfig::addMachineSSAOptimization();
715
716   // We want to fold operands after PeepholeOptimizer has run (or as part of
717   // it), because it will eliminate extra copies making it easier to fold the
718   // real source operand. We want to eliminate dead instructions after, so that
719   // we see fewer uses of the copies. We then need to clean up the dead
720   // instructions leftover after the operands are folded as well.
721   //
722   // XXX - Can we get away without running DeadMachineInstructionElim again?
723   addPass(&SIFoldOperandsID);
724   addPass(&DeadMachineInstructionElimID);
725   addPass(&SILoadStoreOptimizerID);
726   addPass(createSIShrinkInstructionsPass());
727   if (EnableSDWAPeephole) {
728     addPass(&SIPeepholeSDWAID);
729     addPass(&DeadMachineInstructionElimID);
730   }
731 }
732
733 bool GCNPassConfig::addILPOpts() {
734   if (EnableEarlyIfConversion)
735     addPass(&EarlyIfConverterID);
736
737   TargetPassConfig::addILPOpts();
738   return false;
739 }
740
741 bool GCNPassConfig::addInstSelector() {
742   AMDGPUPassConfig::addInstSelector();
743   addPass(createSILowerI1CopiesPass());
744   addPass(&SIFixSGPRCopiesID);
745   return false;
746 }
747
748 #ifdef LLVM_BUILD_GLOBAL_ISEL
749 bool GCNPassConfig::addIRTranslator() {
750   addPass(new IRTranslator());
751   return false;
752 }
753
754 bool GCNPassConfig::addLegalizeMachineIR() {
755   addPass(new Legalizer());
756   return false;
757 }
758
759 bool GCNPassConfig::addRegBankSelect() {
760   addPass(new RegBankSelect());
761   return false;
762 }
763
764 bool GCNPassConfig::addGlobalInstructionSelect() {
765   addPass(new InstructionSelect());
766   return false;
767 }
768
769 #endif
770
771 void GCNPassConfig::addPreRegAlloc() {
772   addPass(createSIWholeQuadModePass());
773 }
774
775 void GCNPassConfig::addFastRegAlloc(FunctionPass *RegAllocPass) {
776   // FIXME: We have to disable the verifier here because of PHIElimination +
777   // TwoAddressInstructions disabling it.
778
779   // This must be run immediately after phi elimination and before
780   // TwoAddressInstructions, otherwise the processing of the tied operand of
781   // SI_ELSE will introduce a copy of the tied operand source after the else.
782   insertPass(&PHIEliminationID, &SILowerControlFlowID, false);
783
784   TargetPassConfig::addFastRegAlloc(RegAllocPass);
785 }
786
787 void GCNPassConfig::addOptimizedRegAlloc(FunctionPass *RegAllocPass) {
788   // This needs to be run directly before register allocation because earlier
789   // passes might recompute live intervals.
790   insertPass(&MachineSchedulerID, &SIFixControlFlowLiveIntervalsID);
791
792   // This must be run immediately after phi elimination and before
793   // TwoAddressInstructions, otherwise the processing of the tied operand of
794   // SI_ELSE will introduce a copy of the tied operand source after the else.
795   insertPass(&PHIEliminationID, &SILowerControlFlowID, false);
796
797   TargetPassConfig::addOptimizedRegAlloc(RegAllocPass);
798 }
799
800 void GCNPassConfig::addPostRegAlloc() {
801   addPass(&SIFixVGPRCopiesID);
802   addPass(&SIOptimizeExecMaskingID);
803   TargetPassConfig::addPostRegAlloc();
804 }
805
806 void GCNPassConfig::addPreSched2() {
807 }
808
809 void GCNPassConfig::addPreEmitPass() {
810   // The hazard recognizer that runs as part of the post-ra scheduler does not
811   // guarantee to be able handle all hazards correctly. This is because if there
812   // are multiple scheduling regions in a basic block, the regions are scheduled
813   // bottom up, so when we begin to schedule a region we don't know what
814   // instructions were emitted directly before it.
815   //
816   // Here we add a stand-alone hazard recognizer pass which can handle all
817   // cases.
818   addPass(&PostRAHazardRecognizerID);
819
820   if (EnableSIInsertWaitcntsPass)
821     addPass(createSIInsertWaitcntsPass());
822   else
823     addPass(createSIInsertWaitsPass());
824   addPass(createSIShrinkInstructionsPass());
825   addPass(&SIInsertSkipsPassID);
826   addPass(createSIDebuggerInsertNopsPass());
827   addPass(&BranchRelaxationPassID);
828 }
829
830 TargetPassConfig *GCNTargetMachine::createPassConfig(PassManagerBase &PM) {
831   return new GCNPassConfig(this, PM);
832 }
833