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