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 "AMDGPUCallLowering.h" 19 #include "AMDGPUTargetObjectFile.h" 20 #include "AMDGPUTargetTransformInfo.h" 21 #include "R600ISelLowering.h" 22 #include "R600InstrInfo.h" 23 #include "R600MachineScheduler.h" 24 #include "SIISelLowering.h" 25 #include "SIInstrInfo.h" 26 #include "SIMachineScheduler.h" 27 #include "llvm/CodeGen/GlobalISel/IRTranslator.h" 28 #include "llvm/CodeGen/Passes.h" 29 #include "llvm/CodeGen/TargetPassConfig.h" 30 #include "llvm/Support/TargetRegistry.h" 31 #include "llvm/Transforms/IPO.h" 32 #include "llvm/Transforms/IPO/AlwaysInliner.h" 33 #include "llvm/Transforms/Scalar.h" 34 #include "llvm/Transforms/Scalar/GVN.h" 35 #include "llvm/Transforms/Vectorize.h" 36 37 using namespace llvm; 38 39 static cl::opt<bool> EnableR600StructurizeCFG( 40 "r600-ir-structurize", 41 cl::desc("Use StructurizeCFG IR pass"), 42 cl::init(true)); 43 44 static cl::opt<bool> EnableSROA( 45 "amdgpu-sroa", 46 cl::desc("Run SROA after promote alloca pass"), 47 cl::ReallyHidden, 48 cl::init(true)); 49 50 static cl::opt<bool> EnableR600IfConvert( 51 "r600-if-convert", 52 cl::desc("Use if conversion pass"), 53 cl::ReallyHidden, 54 cl::init(true)); 55 56 // Option to disable vectorizer for tests. 57 static cl::opt<bool> EnableLoadStoreVectorizer( 58 "amdgpu-load-store-vectorizer", 59 cl::desc("Enable load store vectorizer"), 60 cl::init(false), 61 cl::Hidden); 62 63 extern "C" void LLVMInitializeAMDGPUTarget() { 64 // Register the target 65 RegisterTargetMachine<R600TargetMachine> X(TheAMDGPUTarget); 66 RegisterTargetMachine<GCNTargetMachine> Y(TheGCNTarget); 67 68 PassRegistry *PR = PassRegistry::getPassRegistry(); 69 initializeSILowerI1CopiesPass(*PR); 70 initializeSIFixSGPRCopiesPass(*PR); 71 initializeSIFoldOperandsPass(*PR); 72 initializeSIShrinkInstructionsPass(*PR); 73 initializeSIFixControlFlowLiveIntervalsPass(*PR); 74 initializeSILoadStoreOptimizerPass(*PR); 75 initializeAMDGPUAnnotateKernelFeaturesPass(*PR); 76 initializeAMDGPUAnnotateUniformValuesPass(*PR); 77 initializeAMDGPUPromoteAllocaPass(*PR); 78 initializeAMDGPUCodeGenPreparePass(*PR); 79 initializeSIAnnotateControlFlowPass(*PR); 80 initializeSIInsertWaitsPass(*PR); 81 initializeSIWholeQuadModePass(*PR); 82 initializeSILowerControlFlowPass(*PR); 83 initializeSIDebuggerInsertNopsPass(*PR); 84 } 85 86 static std::unique_ptr<TargetLoweringObjectFile> createTLOF(const Triple &TT) { 87 return make_unique<AMDGPUTargetObjectFile>(); 88 } 89 90 static ScheduleDAGInstrs *createR600MachineScheduler(MachineSchedContext *C) { 91 return new ScheduleDAGMILive(C, make_unique<R600SchedStrategy>()); 92 } 93 94 static ScheduleDAGInstrs *createSIMachineScheduler(MachineSchedContext *C) { 95 return new SIScheduleDAGMI(C); 96 } 97 98 static MachineSchedRegistry 99 R600SchedRegistry("r600", "Run R600's custom scheduler", 100 createR600MachineScheduler); 101 102 static MachineSchedRegistry 103 SISchedRegistry("si", "Run SI's custom scheduler", 104 createSIMachineScheduler); 105 106 static StringRef computeDataLayout(const Triple &TT) { 107 if (TT.getArch() == Triple::r600) { 108 // 32-bit pointers. 109 return "e-p:32:32-i64:64-v16:16-v24:32-v32:32-v48:64-v96:128" 110 "-v192:256-v256:256-v512:512-v1024:1024-v2048:2048-n32:64"; 111 } 112 113 // 32-bit private, local, and region pointers. 64-bit global, constant and 114 // flat. 115 return "e-p:32:32-p1:64:64-p2:64:64-p3:32:32-p4:64:64-p5:32:32" 116 "-i64:64-v16:16-v24:32-v32:32-v48:64-v96:128" 117 "-v192:256-v256:256-v512:512-v1024:1024-v2048:2048-n32:64"; 118 } 119 120 LLVM_READNONE 121 static StringRef getGPUOrDefault(const Triple &TT, StringRef GPU) { 122 if (!GPU.empty()) 123 return GPU; 124 125 // HSA only supports CI+, so change the default GPU to a CI for HSA. 126 if (TT.getArch() == Triple::amdgcn) 127 return (TT.getOS() == Triple::AMDHSA) ? "kaveri" : "tahiti"; 128 129 return "r600"; 130 } 131 132 static Reloc::Model getEffectiveRelocModel(Optional<Reloc::Model> RM) { 133 // The AMDGPU toolchain only supports generating shared objects, so we 134 // must always use PIC. 135 return Reloc::PIC_; 136 } 137 138 AMDGPUTargetMachine::AMDGPUTargetMachine(const Target &T, const Triple &TT, 139 StringRef CPU, StringRef FS, 140 TargetOptions Options, 141 Optional<Reloc::Model> RM, 142 CodeModel::Model CM, 143 CodeGenOpt::Level OptLevel) 144 : LLVMTargetMachine(T, computeDataLayout(TT), TT, getGPUOrDefault(TT, CPU), 145 FS, Options, getEffectiveRelocModel(RM), CM, OptLevel), 146 TLOF(createTLOF(getTargetTriple())), 147 IntrinsicInfo() { 148 setRequiresStructuredCFG(true); 149 initAsmInfo(); 150 } 151 152 AMDGPUTargetMachine::~AMDGPUTargetMachine() { } 153 154 StringRef AMDGPUTargetMachine::getGPUName(const Function &F) const { 155 Attribute GPUAttr = F.getFnAttribute("target-cpu"); 156 return GPUAttr.hasAttribute(Attribute::None) ? 157 getTargetCPU() : GPUAttr.getValueAsString(); 158 } 159 160 StringRef AMDGPUTargetMachine::getFeatureString(const Function &F) const { 161 Attribute FSAttr = F.getFnAttribute("target-features"); 162 163 return FSAttr.hasAttribute(Attribute::None) ? 164 getTargetFeatureString() : 165 FSAttr.getValueAsString(); 166 } 167 168 //===----------------------------------------------------------------------===// 169 // R600 Target Machine (R600 -> Cayman) 170 //===----------------------------------------------------------------------===// 171 172 R600TargetMachine::R600TargetMachine(const Target &T, const Triple &TT, 173 StringRef CPU, StringRef FS, 174 TargetOptions Options, 175 Optional<Reloc::Model> RM, 176 CodeModel::Model CM, CodeGenOpt::Level OL) 177 : AMDGPUTargetMachine(T, TT, CPU, FS, Options, RM, CM, OL) {} 178 179 const R600Subtarget *R600TargetMachine::getSubtargetImpl( 180 const Function &F) const { 181 StringRef GPU = getGPUName(F); 182 StringRef FS = getFeatureString(F); 183 184 SmallString<128> SubtargetKey(GPU); 185 SubtargetKey.append(FS); 186 187 auto &I = SubtargetMap[SubtargetKey]; 188 if (!I) { 189 // This needs to be done before we create a new subtarget since any 190 // creation will depend on the TM and the code generation flags on the 191 // function that reside in TargetOptions. 192 resetTargetOptions(F); 193 I = llvm::make_unique<R600Subtarget>(TargetTriple, GPU, FS, *this); 194 } 195 196 return I.get(); 197 } 198 199 //===----------------------------------------------------------------------===// 200 // GCN Target Machine (SI+) 201 //===----------------------------------------------------------------------===// 202 203 #ifdef LLVM_BUILD_GLOBAL_ISEL 204 namespace { 205 struct SIGISelActualAccessor : public GISelAccessor { 206 std::unique_ptr<AMDGPUCallLowering> CallLoweringInfo; 207 const AMDGPUCallLowering *getCallLowering() const override { 208 return CallLoweringInfo.get(); 209 } 210 }; 211 } // End anonymous namespace. 212 #endif 213 214 GCNTargetMachine::GCNTargetMachine(const Target &T, const Triple &TT, 215 StringRef CPU, StringRef FS, 216 TargetOptions Options, 217 Optional<Reloc::Model> RM, 218 CodeModel::Model CM, CodeGenOpt::Level OL) 219 : AMDGPUTargetMachine(T, TT, CPU, FS, Options, RM, CM, OL) {} 220 221 const SISubtarget *GCNTargetMachine::getSubtargetImpl(const Function &F) const { 222 StringRef GPU = getGPUName(F); 223 StringRef FS = getFeatureString(F); 224 225 SmallString<128> SubtargetKey(GPU); 226 SubtargetKey.append(FS); 227 228 auto &I = SubtargetMap[SubtargetKey]; 229 if (!I) { 230 // This needs to be done before we create a new subtarget since any 231 // creation will depend on the TM and the code generation flags on the 232 // function that reside in TargetOptions. 233 resetTargetOptions(F); 234 I = llvm::make_unique<SISubtarget>(TargetTriple, GPU, FS, *this); 235 236 #ifndef LLVM_BUILD_GLOBAL_ISEL 237 GISelAccessor *GISel = new GISelAccessor(); 238 #else 239 SIGISelActualAccessor *GISel = new SIGISelActualAccessor(); 240 GISel->CallLoweringInfo.reset( 241 new AMDGPUCallLowering(*I->getTargetLowering())); 242 #endif 243 244 I->setGISelAccessor(*GISel); 245 } 246 247 return I.get(); 248 } 249 250 //===----------------------------------------------------------------------===// 251 // AMDGPU Pass Setup 252 //===----------------------------------------------------------------------===// 253 254 namespace { 255 256 class AMDGPUPassConfig : public TargetPassConfig { 257 public: 258 AMDGPUPassConfig(TargetMachine *TM, PassManagerBase &PM) 259 : TargetPassConfig(TM, PM) { 260 261 // Exceptions and StackMaps are not supported, so these passes will never do 262 // anything. 263 disablePass(&StackMapLivenessID); 264 disablePass(&FuncletLayoutID); 265 } 266 267 AMDGPUTargetMachine &getAMDGPUTargetMachine() const { 268 return getTM<AMDGPUTargetMachine>(); 269 } 270 271 void addEarlyCSEOrGVNPass(); 272 void addStraightLineScalarOptimizationPasses(); 273 void addIRPasses() override; 274 void addCodeGenPrepare() override; 275 bool addPreISel() override; 276 bool addInstSelector() override; 277 bool addGCPasses() override; 278 }; 279 280 class R600PassConfig final : public AMDGPUPassConfig { 281 public: 282 R600PassConfig(TargetMachine *TM, PassManagerBase &PM) 283 : AMDGPUPassConfig(TM, PM) { } 284 285 ScheduleDAGInstrs *createMachineScheduler( 286 MachineSchedContext *C) const override { 287 return createR600MachineScheduler(C); 288 } 289 290 bool addPreISel() override; 291 void addPreRegAlloc() override; 292 void addPreSched2() override; 293 void addPreEmitPass() override; 294 }; 295 296 class GCNPassConfig final : public AMDGPUPassConfig { 297 public: 298 GCNPassConfig(TargetMachine *TM, PassManagerBase &PM) 299 : AMDGPUPassConfig(TM, PM) { } 300 301 GCNTargetMachine &getGCNTargetMachine() const { 302 return getTM<GCNTargetMachine>(); 303 } 304 305 ScheduleDAGInstrs * 306 createMachineScheduler(MachineSchedContext *C) const override; 307 308 void addIRPasses() override; 309 bool addPreISel() override; 310 void addMachineSSAOptimization() override; 311 bool addInstSelector() override; 312 #ifdef LLVM_BUILD_GLOBAL_ISEL 313 bool addIRTranslator() override; 314 bool addLegalizeMachineIR() override; 315 bool addRegBankSelect() override; 316 bool addGlobalInstructionSelect() override; 317 #endif 318 void addFastRegAlloc(FunctionPass *RegAllocPass) override; 319 void addOptimizedRegAlloc(FunctionPass *RegAllocPass) override; 320 void addPreRegAlloc() override; 321 void addPreSched2() override; 322 void addPreEmitPass() override; 323 }; 324 325 } // End of anonymous namespace 326 327 TargetIRAnalysis AMDGPUTargetMachine::getTargetIRAnalysis() { 328 return TargetIRAnalysis([this](const Function &F) { 329 return TargetTransformInfo(AMDGPUTTIImpl(this, F)); 330 }); 331 } 332 333 void AMDGPUPassConfig::addEarlyCSEOrGVNPass() { 334 if (getOptLevel() == CodeGenOpt::Aggressive) 335 addPass(createGVNPass()); 336 else 337 addPass(createEarlyCSEPass()); 338 } 339 340 void AMDGPUPassConfig::addStraightLineScalarOptimizationPasses() { 341 addPass(createSeparateConstOffsetFromGEPPass()); 342 addPass(createSpeculativeExecutionPass()); 343 // ReassociateGEPs exposes more opportunites for SLSR. See 344 // the example in reassociate-geps-and-slsr.ll. 345 addPass(createStraightLineStrengthReducePass()); 346 // SeparateConstOffsetFromGEP and SLSR creates common expressions which GVN or 347 // EarlyCSE can reuse. 348 addEarlyCSEOrGVNPass(); 349 // Run NaryReassociate after EarlyCSE/GVN to be more effective. 350 addPass(createNaryReassociatePass()); 351 // NaryReassociate on GEPs creates redundant common expressions, so run 352 // EarlyCSE after it. 353 addPass(createEarlyCSEPass()); 354 } 355 356 void AMDGPUPassConfig::addIRPasses() { 357 // There is no reason to run these. 358 disablePass(&StackMapLivenessID); 359 disablePass(&FuncletLayoutID); 360 disablePass(&PatchableFunctionID); 361 362 // Function calls are not supported, so make sure we inline everything. 363 addPass(createAMDGPUAlwaysInlinePass()); 364 addPass(createAlwaysInlinerLegacyPass()); 365 // We need to add the barrier noop pass, otherwise adding the function 366 // inlining pass will cause all of the PassConfigs passes to be run 367 // one function at a time, which means if we have a nodule with two 368 // functions, then we will generate code for the first function 369 // without ever running any passes on the second. 370 addPass(createBarrierNoopPass()); 371 372 // Handle uses of OpenCL image2d_t, image3d_t and sampler_t arguments. 373 addPass(createAMDGPUOpenCLImageTypeLoweringPass()); 374 375 const AMDGPUTargetMachine &TM = getAMDGPUTargetMachine(); 376 if (TM.getOptLevel() > CodeGenOpt::None) { 377 addPass(createAMDGPUPromoteAlloca(&TM)); 378 379 if (EnableSROA) 380 addPass(createSROAPass()); 381 } 382 383 addStraightLineScalarOptimizationPasses(); 384 385 TargetPassConfig::addIRPasses(); 386 387 // EarlyCSE is not always strong enough to clean up what LSR produces. For 388 // example, GVN can combine 389 // 390 // %0 = add %a, %b 391 // %1 = add %b, %a 392 // 393 // and 394 // 395 // %0 = shl nsw %a, 2 396 // %1 = shl %a, 2 397 // 398 // but EarlyCSE can do neither of them. 399 if (getOptLevel() != CodeGenOpt::None) 400 addEarlyCSEOrGVNPass(); 401 } 402 403 void AMDGPUPassConfig::addCodeGenPrepare() { 404 TargetPassConfig::addCodeGenPrepare(); 405 406 if (EnableLoadStoreVectorizer) 407 addPass(createLoadStoreVectorizerPass()); 408 } 409 410 bool AMDGPUPassConfig::addPreISel() { 411 addPass(createFlattenCFGPass()); 412 return false; 413 } 414 415 bool AMDGPUPassConfig::addInstSelector() { 416 addPass(createAMDGPUISelDag(getAMDGPUTargetMachine())); 417 return false; 418 } 419 420 bool AMDGPUPassConfig::addGCPasses() { 421 // Do nothing. GC is not supported. 422 return false; 423 } 424 425 //===----------------------------------------------------------------------===// 426 // R600 Pass Setup 427 //===----------------------------------------------------------------------===// 428 429 bool R600PassConfig::addPreISel() { 430 AMDGPUPassConfig::addPreISel(); 431 432 if (EnableR600StructurizeCFG) 433 addPass(createStructurizeCFGPass()); 434 return false; 435 } 436 437 void R600PassConfig::addPreRegAlloc() { 438 addPass(createR600VectorRegMerger(*TM)); 439 } 440 441 void R600PassConfig::addPreSched2() { 442 addPass(createR600EmitClauseMarkers(), false); 443 if (EnableR600IfConvert) 444 addPass(&IfConverterID, false); 445 addPass(createR600ClauseMergePass(*TM), false); 446 } 447 448 void R600PassConfig::addPreEmitPass() { 449 addPass(createAMDGPUCFGStructurizerPass(), false); 450 addPass(createR600ExpandSpecialInstrsPass(*TM), false); 451 addPass(&FinalizeMachineBundlesID, false); 452 addPass(createR600Packetizer(*TM), false); 453 addPass(createR600ControlFlowFinalizer(*TM), false); 454 } 455 456 TargetPassConfig *R600TargetMachine::createPassConfig(PassManagerBase &PM) { 457 return new R600PassConfig(this, PM); 458 } 459 460 //===----------------------------------------------------------------------===// 461 // GCN Pass Setup 462 //===----------------------------------------------------------------------===// 463 464 ScheduleDAGInstrs *GCNPassConfig::createMachineScheduler( 465 MachineSchedContext *C) const { 466 const SISubtarget &ST = C->MF->getSubtarget<SISubtarget>(); 467 if (ST.enableSIScheduler()) 468 return createSIMachineScheduler(C); 469 return nullptr; 470 } 471 472 bool GCNPassConfig::addPreISel() { 473 AMDGPUPassConfig::addPreISel(); 474 475 // FIXME: We need to run a pass to propagate the attributes when calls are 476 // supported. 477 addPass(&AMDGPUAnnotateKernelFeaturesID); 478 addPass(createStructurizeCFGPass(true)); // true -> SkipUniformRegions 479 addPass(createSinkingPass()); 480 addPass(createSITypeRewriter()); 481 addPass(createAMDGPUAnnotateUniformValues()); 482 addPass(createSIAnnotateControlFlowPass()); 483 484 return false; 485 } 486 487 void GCNPassConfig::addMachineSSAOptimization() { 488 TargetPassConfig::addMachineSSAOptimization(); 489 490 // We want to fold operands after PeepholeOptimizer has run (or as part of 491 // it), because it will eliminate extra copies making it easier to fold the 492 // real source operand. We want to eliminate dead instructions after, so that 493 // we see fewer uses of the copies. We then need to clean up the dead 494 // instructions leftover after the operands are folded as well. 495 // 496 // XXX - Can we get away without running DeadMachineInstructionElim again? 497 addPass(&SIFoldOperandsID); 498 addPass(&DeadMachineInstructionElimID); 499 } 500 501 void GCNPassConfig::addIRPasses() { 502 // TODO: May want to move later or split into an early and late one. 503 addPass(createAMDGPUCodeGenPreparePass(&getGCNTargetMachine())); 504 505 AMDGPUPassConfig::addIRPasses(); 506 } 507 508 bool GCNPassConfig::addInstSelector() { 509 AMDGPUPassConfig::addInstSelector(); 510 addPass(createSILowerI1CopiesPass()); 511 addPass(&SIFixSGPRCopiesID); 512 return false; 513 } 514 515 #ifdef LLVM_BUILD_GLOBAL_ISEL 516 bool GCNPassConfig::addIRTranslator() { 517 addPass(new IRTranslator()); 518 return false; 519 } 520 521 bool GCNPassConfig::addLegalizeMachineIR() { 522 return false; 523 } 524 525 bool GCNPassConfig::addRegBankSelect() { 526 return false; 527 } 528 529 bool GCNPassConfig::addGlobalInstructionSelect() { 530 return false; 531 } 532 #endif 533 534 void GCNPassConfig::addPreRegAlloc() { 535 // This needs to be run directly before register allocation because 536 // earlier passes might recompute live intervals. 537 // TODO: handle CodeGenOpt::None; fast RA ignores spill weights set by the pass 538 if (getOptLevel() > CodeGenOpt::None) { 539 insertPass(&MachineSchedulerID, &SIFixControlFlowLiveIntervalsID); 540 } 541 542 if (getOptLevel() > CodeGenOpt::None) { 543 // Don't do this with no optimizations since it throws away debug info by 544 // merging nonadjacent loads. 545 546 // This should be run after scheduling, but before register allocation. It 547 // also need extra copies to the address operand to be eliminated. 548 549 // FIXME: Move pre-RA and remove extra reg coalescer run. 550 insertPass(&MachineSchedulerID, &SILoadStoreOptimizerID); 551 insertPass(&MachineSchedulerID, &RegisterCoalescerID); 552 } 553 554 addPass(createSIShrinkInstructionsPass()); 555 addPass(createSIWholeQuadModePass()); 556 } 557 558 void GCNPassConfig::addFastRegAlloc(FunctionPass *RegAllocPass) { 559 TargetPassConfig::addFastRegAlloc(RegAllocPass); 560 } 561 562 void GCNPassConfig::addOptimizedRegAlloc(FunctionPass *RegAllocPass) { 563 TargetPassConfig::addOptimizedRegAlloc(RegAllocPass); 564 } 565 566 void GCNPassConfig::addPreSched2() { 567 } 568 569 void GCNPassConfig::addPreEmitPass() { 570 // The hazard recognizer that runs as part of the post-ra scheduler does not 571 // guarantee to be able handle all hazards correctly. This is because if there 572 // are multiple scheduling regions in a basic block, the regions are scheduled 573 // bottom up, so when we begin to schedule a region we don't know what 574 // instructions were emitted directly before it. 575 // 576 // Here we add a stand-alone hazard recognizer pass which can handle all 577 // cases. 578 addPass(&PostRAHazardRecognizerID); 579 580 addPass(createSIInsertWaitsPass()); 581 addPass(createSIShrinkInstructionsPass()); 582 addPass(createSILowerControlFlowPass()); 583 addPass(createSIDebuggerInsertNopsPass()); 584 } 585 586 TargetPassConfig *GCNTargetMachine::createPassConfig(PassManagerBase &PM) { 587 return new GCNPassConfig(this, PM); 588 } 589