OSDN Git Service

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