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