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 return !GV.use_empty(); 435 } 436 437 void AMDGPUTargetMachine::adjustPassManager(PassManagerBuilder &Builder) { 438 Builder.DivergentTarget = true; 439 440 bool EnableOpt = getOptLevel() > CodeGenOpt::None; 441 bool Internalize = InternalizeSymbols; 442 bool EarlyInline = EarlyInlineAll && EnableOpt && !EnableFunctionCalls; 443 bool AMDGPUAA = EnableAMDGPUAliasAnalysis && EnableOpt; 444 bool LibCallSimplify = EnableLibCallSimplify && EnableOpt; 445 446 if (EnableFunctionCalls) { 447 delete Builder.Inliner; 448 Builder.Inliner = createFunctionInliningPass(); 449 } 450 451 Builder.addExtension( 452 PassManagerBuilder::EP_ModuleOptimizerEarly, 453 [Internalize, EarlyInline, AMDGPUAA, this](const PassManagerBuilder &, 454 legacy::PassManagerBase &PM) { 455 if (AMDGPUAA) { 456 PM.add(createAMDGPUAAWrapperPass()); 457 PM.add(createAMDGPUExternalAAWrapperPass()); 458 } 459 PM.add(createAMDGPUUnifyMetadataPass()); 460 PM.add(createAMDGPUPrintfRuntimeBinding()); 461 if (Internalize) 462 PM.add(createInternalizePass(mustPreserveGV)); 463 PM.add(createAMDGPUPropagateAttributesLatePass(this)); 464 if (Internalize) 465 PM.add(createGlobalDCEPass()); 466 if (EarlyInline) 467 PM.add(createAMDGPUAlwaysInlinePass(false)); 468 }); 469 470 Builder.addExtension( 471 PassManagerBuilder::EP_EarlyAsPossible, 472 [AMDGPUAA, LibCallSimplify, this](const PassManagerBuilder &, 473 legacy::PassManagerBase &PM) { 474 if (AMDGPUAA) { 475 PM.add(createAMDGPUAAWrapperPass()); 476 PM.add(createAMDGPUExternalAAWrapperPass()); 477 } 478 PM.add(llvm::createAMDGPUPropagateAttributesEarlyPass(this)); 479 PM.add(llvm::createAMDGPUUseNativeCallsPass()); 480 if (LibCallSimplify) 481 PM.add(llvm::createAMDGPUSimplifyLibCallsPass(this)); 482 }); 483 484 Builder.addExtension( 485 PassManagerBuilder::EP_CGSCCOptimizerLate, 486 [EnableOpt](const PassManagerBuilder &, legacy::PassManagerBase &PM) { 487 // Add infer address spaces pass to the opt pipeline after inlining 488 // but before SROA to increase SROA opportunities. 489 PM.add(createInferAddressSpacesPass()); 490 491 // This should run after inlining to have any chance of doing anything, 492 // and before other cleanup optimizations. 493 PM.add(createAMDGPULowerKernelAttributesPass()); 494 495 // Promote alloca to vector before SROA and loop unroll. If we manage 496 // to eliminate allocas before unroll we may choose to unroll less. 497 if (EnableOpt) 498 PM.add(createAMDGPUPromoteAllocaToVector()); 499 }); 500 } 501 502 void AMDGPUTargetMachine::registerDefaultAliasAnalyses(AAManager &AAM) { 503 AAM.registerFunctionAnalysis<AMDGPUAA>(); 504 } 505 506 void AMDGPUTargetMachine::registerPassBuilderCallbacks(PassBuilder &PB) { 507 PB.registerPipelineParsingCallback( 508 [this](StringRef PassName, ModulePassManager &PM, 509 ArrayRef<PassBuilder::PipelineElement>) { 510 if (PassName == "amdgpu-propagate-attributes-late") { 511 PM.addPass(AMDGPUPropagateAttributesLatePass(*this)); 512 return true; 513 } 514 if (PassName == "amdgpu-unify-metadata") { 515 PM.addPass(AMDGPUUnifyMetadataPass()); 516 return true; 517 } 518 if (PassName == "amdgpu-printf-runtime-binding") { 519 PM.addPass(AMDGPUPrintfRuntimeBindingPass()); 520 return true; 521 } 522 if (PassName == "amdgpu-always-inline") { 523 PM.addPass(AMDGPUAlwaysInlinePass()); 524 return true; 525 } 526 if (PassName == "amdgpu-replace-lds-use-with-pointer") { 527 PM.addPass(AMDGPUReplaceLDSUseWithPointerPass()); 528 return true; 529 } 530 if (PassName == "amdgpu-lower-module-lds") { 531 PM.addPass(AMDGPULowerModuleLDSPass()); 532 return true; 533 } 534 return false; 535 }); 536 PB.registerPipelineParsingCallback( 537 [this](StringRef PassName, FunctionPassManager &PM, 538 ArrayRef<PassBuilder::PipelineElement>) { 539 if (PassName == "amdgpu-simplifylib") { 540 PM.addPass(AMDGPUSimplifyLibCallsPass(*this)); 541 return true; 542 } 543 if (PassName == "amdgpu-usenative") { 544 PM.addPass(AMDGPUUseNativeCallsPass()); 545 return true; 546 } 547 if (PassName == "amdgpu-promote-alloca") { 548 PM.addPass(AMDGPUPromoteAllocaPass(*this)); 549 return true; 550 } 551 if (PassName == "amdgpu-promote-alloca-to-vector") { 552 PM.addPass(AMDGPUPromoteAllocaToVectorPass(*this)); 553 return true; 554 } 555 if (PassName == "amdgpu-lower-kernel-attributes") { 556 PM.addPass(AMDGPULowerKernelAttributesPass()); 557 return true; 558 } 559 if (PassName == "amdgpu-propagate-attributes-early") { 560 PM.addPass(AMDGPUPropagateAttributesEarlyPass(*this)); 561 return true; 562 } 563 return false; 564 }); 565 566 PB.registerAnalysisRegistrationCallback([](FunctionAnalysisManager &FAM) { 567 FAM.registerPass([&] { return AMDGPUAA(); }); 568 }); 569 570 PB.registerParseAACallback([](StringRef AAName, AAManager &AAM) { 571 if (AAName == "amdgpu-aa") { 572 AAM.registerFunctionAnalysis<AMDGPUAA>(); 573 return true; 574 } 575 return false; 576 }); 577 578 PB.registerPipelineStartEPCallback( 579 [this](ModulePassManager &PM, PassBuilder::OptimizationLevel Level) { 580 FunctionPassManager FPM; 581 FPM.addPass(AMDGPUPropagateAttributesEarlyPass(*this)); 582 FPM.addPass(AMDGPUUseNativeCallsPass()); 583 if (EnableLibCallSimplify && 584 Level != PassBuilder::OptimizationLevel::O0) 585 FPM.addPass(AMDGPUSimplifyLibCallsPass(*this)); 586 PM.addPass(createModuleToFunctionPassAdaptor(std::move(FPM))); 587 }); 588 589 PB.registerPipelineEarlySimplificationEPCallback( 590 [this](ModulePassManager &PM, PassBuilder::OptimizationLevel Level) { 591 if (Level == PassBuilder::OptimizationLevel::O0) 592 return; 593 594 PM.addPass(AMDGPUUnifyMetadataPass()); 595 PM.addPass(AMDGPUPrintfRuntimeBindingPass()); 596 597 if (InternalizeSymbols) { 598 // Global variables may have dead uses which need to be removed. 599 // Otherwise these useless global variables will not get internalized. 600 PM.addPass(GlobalDCEPass()); 601 PM.addPass(InternalizePass(mustPreserveGV)); 602 } 603 PM.addPass(AMDGPUPropagateAttributesLatePass(*this)); 604 if (InternalizeSymbols) { 605 PM.addPass(GlobalDCEPass()); 606 } 607 if (EarlyInlineAll && !EnableFunctionCalls) 608 PM.addPass(AMDGPUAlwaysInlinePass()); 609 }); 610 611 PB.registerCGSCCOptimizerLateEPCallback( 612 [this](CGSCCPassManager &PM, PassBuilder::OptimizationLevel Level) { 613 if (Level == PassBuilder::OptimizationLevel::O0) 614 return; 615 616 FunctionPassManager FPM; 617 618 // Add infer address spaces pass to the opt pipeline after inlining 619 // but before SROA to increase SROA opportunities. 620 FPM.addPass(InferAddressSpacesPass()); 621 622 // This should run after inlining to have any chance of doing 623 // anything, and before other cleanup optimizations. 624 FPM.addPass(AMDGPULowerKernelAttributesPass()); 625 626 if (Level != PassBuilder::OptimizationLevel::O0) { 627 // Promote alloca to vector before SROA and loop unroll. If we 628 // manage to eliminate allocas before unroll we may choose to unroll 629 // less. 630 FPM.addPass(AMDGPUPromoteAllocaToVectorPass(*this)); 631 } 632 633 PM.addPass(createCGSCCToFunctionPassAdaptor(std::move(FPM))); 634 }); 635 } 636 637 //===----------------------------------------------------------------------===// 638 // R600 Target Machine (R600 -> Cayman) 639 //===----------------------------------------------------------------------===// 640 641 R600TargetMachine::R600TargetMachine(const Target &T, const Triple &TT, 642 StringRef CPU, StringRef FS, 643 TargetOptions Options, 644 Optional<Reloc::Model> RM, 645 Optional<CodeModel::Model> CM, 646 CodeGenOpt::Level OL, bool JIT) 647 : AMDGPUTargetMachine(T, TT, CPU, FS, Options, RM, CM, OL) { 648 setRequiresStructuredCFG(true); 649 650 // Override the default since calls aren't supported for r600. 651 if (EnableFunctionCalls && 652 EnableAMDGPUFunctionCallsOpt.getNumOccurrences() == 0) 653 EnableFunctionCalls = false; 654 } 655 656 const R600Subtarget *R600TargetMachine::getSubtargetImpl( 657 const Function &F) const { 658 StringRef GPU = getGPUName(F); 659 StringRef FS = getFeatureString(F); 660 661 SmallString<128> SubtargetKey(GPU); 662 SubtargetKey.append(FS); 663 664 auto &I = SubtargetMap[SubtargetKey]; 665 if (!I) { 666 // This needs to be done before we create a new subtarget since any 667 // creation will depend on the TM and the code generation flags on the 668 // function that reside in TargetOptions. 669 resetTargetOptions(F); 670 I = std::make_unique<R600Subtarget>(TargetTriple, GPU, FS, *this); 671 } 672 673 return I.get(); 674 } 675 676 int64_t AMDGPUTargetMachine::getNullPointerValue(unsigned AddrSpace) { 677 return (AddrSpace == AMDGPUAS::LOCAL_ADDRESS || 678 AddrSpace == AMDGPUAS::PRIVATE_ADDRESS || 679 AddrSpace == AMDGPUAS::REGION_ADDRESS) 680 ? -1 681 : 0; 682 } 683 684 bool AMDGPUTargetMachine::isNoopAddrSpaceCast(unsigned SrcAS, 685 unsigned DestAS) const { 686 return AMDGPU::isFlatGlobalAddrSpace(SrcAS) && 687 AMDGPU::isFlatGlobalAddrSpace(DestAS); 688 } 689 690 unsigned AMDGPUTargetMachine::getAssumedAddrSpace(const Value *V) const { 691 const auto *LD = dyn_cast<LoadInst>(V); 692 if (!LD) 693 return AMDGPUAS::UNKNOWN_ADDRESS_SPACE; 694 695 // It must be a generic pointer loaded. 696 assert(V->getType()->isPointerTy() && 697 V->getType()->getPointerAddressSpace() == AMDGPUAS::FLAT_ADDRESS); 698 699 const auto *Ptr = LD->getPointerOperand(); 700 if (Ptr->getType()->getPointerAddressSpace() != AMDGPUAS::CONSTANT_ADDRESS) 701 return AMDGPUAS::UNKNOWN_ADDRESS_SPACE; 702 // For a generic pointer loaded from the constant memory, it could be assumed 703 // as a global pointer since the constant memory is only populated on the 704 // host side. As implied by the offload programming model, only global 705 // pointers could be referenced on the host side. 706 return AMDGPUAS::GLOBAL_ADDRESS; 707 } 708 709 TargetTransformInfo 710 R600TargetMachine::getTargetTransformInfo(const Function &F) { 711 return TargetTransformInfo(R600TTIImpl(this, F)); 712 } 713 714 //===----------------------------------------------------------------------===// 715 // GCN Target Machine (SI+) 716 //===----------------------------------------------------------------------===// 717 718 GCNTargetMachine::GCNTargetMachine(const Target &T, const Triple &TT, 719 StringRef CPU, StringRef FS, 720 TargetOptions Options, 721 Optional<Reloc::Model> RM, 722 Optional<CodeModel::Model> CM, 723 CodeGenOpt::Level OL, bool JIT) 724 : AMDGPUTargetMachine(T, TT, CPU, FS, Options, RM, CM, OL) {} 725 726 const GCNSubtarget *GCNTargetMachine::getSubtargetImpl(const Function &F) const { 727 StringRef GPU = getGPUName(F); 728 StringRef FS = getFeatureString(F); 729 730 SmallString<128> SubtargetKey(GPU); 731 SubtargetKey.append(FS); 732 733 auto &I = SubtargetMap[SubtargetKey]; 734 if (!I) { 735 // This needs to be done before we create a new subtarget since any 736 // creation will depend on the TM and the code generation flags on the 737 // function that reside in TargetOptions. 738 resetTargetOptions(F); 739 I = std::make_unique<GCNSubtarget>(TargetTriple, GPU, FS, *this); 740 } 741 742 I->setScalarizeGlobalBehavior(ScalarizeGlobal); 743 744 return I.get(); 745 } 746 747 TargetTransformInfo 748 GCNTargetMachine::getTargetTransformInfo(const Function &F) { 749 return TargetTransformInfo(GCNTTIImpl(this, F)); 750 } 751 752 //===----------------------------------------------------------------------===// 753 // AMDGPU Pass Setup 754 //===----------------------------------------------------------------------===// 755 756 namespace { 757 758 class AMDGPUPassConfig : public TargetPassConfig { 759 public: 760 AMDGPUPassConfig(LLVMTargetMachine &TM, PassManagerBase &PM) 761 : TargetPassConfig(TM, PM) { 762 // Exceptions and StackMaps are not supported, so these passes will never do 763 // anything. 764 disablePass(&StackMapLivenessID); 765 disablePass(&FuncletLayoutID); 766 // Garbage collection is not supported. 767 disablePass(&GCLoweringID); 768 disablePass(&ShadowStackGCLoweringID); 769 } 770 771 AMDGPUTargetMachine &getAMDGPUTargetMachine() const { 772 return getTM<AMDGPUTargetMachine>(); 773 } 774 775 ScheduleDAGInstrs * 776 createMachineScheduler(MachineSchedContext *C) const override { 777 ScheduleDAGMILive *DAG = createGenericSchedLive(C); 778 DAG->addMutation(createLoadClusterDAGMutation(DAG->TII, DAG->TRI)); 779 return DAG; 780 } 781 782 void addEarlyCSEOrGVNPass(); 783 void addStraightLineScalarOptimizationPasses(); 784 void addIRPasses() override; 785 void addCodeGenPrepare() override; 786 bool addPreISel() override; 787 bool addInstSelector() override; 788 bool addGCPasses() override; 789 790 std::unique_ptr<CSEConfigBase> getCSEConfig() const override; 791 792 /// Check if a pass is enabled given \p Opt option. The option always 793 /// overrides defaults if explicitely used. Otherwise its default will 794 /// be used given that a pass shall work at an optimization \p Level 795 /// minimum. 796 bool isPassEnabled(const cl::opt<bool> &Opt, 797 CodeGenOpt::Level Level = CodeGenOpt::Default) const { 798 if (Opt.getNumOccurrences()) 799 return Opt; 800 if (TM->getOptLevel() < Level) 801 return false; 802 return Opt; 803 } 804 }; 805 806 std::unique_ptr<CSEConfigBase> AMDGPUPassConfig::getCSEConfig() const { 807 return getStandardCSEConfigForOpt(TM->getOptLevel()); 808 } 809 810 class R600PassConfig final : public AMDGPUPassConfig { 811 public: 812 R600PassConfig(LLVMTargetMachine &TM, PassManagerBase &PM) 813 : AMDGPUPassConfig(TM, PM) {} 814 815 ScheduleDAGInstrs *createMachineScheduler( 816 MachineSchedContext *C) const override { 817 return createR600MachineScheduler(C); 818 } 819 820 bool addPreISel() override; 821 bool addInstSelector() override; 822 void addPreRegAlloc() override; 823 void addPreSched2() override; 824 void addPreEmitPass() override; 825 }; 826 827 class GCNPassConfig final : public AMDGPUPassConfig { 828 public: 829 GCNPassConfig(LLVMTargetMachine &TM, PassManagerBase &PM) 830 : AMDGPUPassConfig(TM, PM) { 831 // It is necessary to know the register usage of the entire call graph. We 832 // allow calls without EnableAMDGPUFunctionCalls if they are marked 833 // noinline, so this is always required. 834 setRequiresCodeGenSCCOrder(true); 835 } 836 837 GCNTargetMachine &getGCNTargetMachine() const { 838 return getTM<GCNTargetMachine>(); 839 } 840 841 ScheduleDAGInstrs * 842 createMachineScheduler(MachineSchedContext *C) const override; 843 844 bool addPreISel() override; 845 void addMachineSSAOptimization() override; 846 bool addILPOpts() override; 847 bool addInstSelector() override; 848 bool addIRTranslator() override; 849 void addPreLegalizeMachineIR() override; 850 bool addLegalizeMachineIR() override; 851 void addPreRegBankSelect() override; 852 bool addRegBankSelect() override; 853 void addPreGlobalInstructionSelect() override; 854 bool addGlobalInstructionSelect() override; 855 void addFastRegAlloc() override; 856 void addOptimizedRegAlloc() override; 857 void addPreRegAlloc() override; 858 bool addPreRewrite() override; 859 void addPostRegAlloc() override; 860 void addPreSched2() override; 861 void addPreEmitPass() override; 862 }; 863 864 } // end anonymous namespace 865 866 void AMDGPUPassConfig::addEarlyCSEOrGVNPass() { 867 if (getOptLevel() == CodeGenOpt::Aggressive) 868 addPass(createGVNPass()); 869 else 870 addPass(createEarlyCSEPass()); 871 } 872 873 void AMDGPUPassConfig::addStraightLineScalarOptimizationPasses() { 874 addPass(createLICMPass()); 875 addPass(createSeparateConstOffsetFromGEPPass()); 876 addPass(createSpeculativeExecutionPass()); 877 // ReassociateGEPs exposes more opportunites for SLSR. See 878 // the example in reassociate-geps-and-slsr.ll. 879 addPass(createStraightLineStrengthReducePass()); 880 // SeparateConstOffsetFromGEP and SLSR creates common expressions which GVN or 881 // EarlyCSE can reuse. 882 addEarlyCSEOrGVNPass(); 883 // Run NaryReassociate after EarlyCSE/GVN to be more effective. 884 addPass(createNaryReassociatePass()); 885 // NaryReassociate on GEPs creates redundant common expressions, so run 886 // EarlyCSE after it. 887 addPass(createEarlyCSEPass()); 888 } 889 890 void AMDGPUPassConfig::addIRPasses() { 891 const AMDGPUTargetMachine &TM = getAMDGPUTargetMachine(); 892 893 // There is no reason to run these. 894 disablePass(&StackMapLivenessID); 895 disablePass(&FuncletLayoutID); 896 disablePass(&PatchableFunctionID); 897 898 addPass(createAMDGPUPrintfRuntimeBinding()); 899 900 // This must occur before inlining, as the inliner will not look through 901 // bitcast calls. 902 addPass(createAMDGPUFixFunctionBitcastsPass()); 903 904 // A call to propagate attributes pass in the backend in case opt was not run. 905 addPass(createAMDGPUPropagateAttributesEarlyPass(&TM)); 906 907 addPass(createAMDGPULowerIntrinsicsPass()); 908 909 // Function calls are not supported, so make sure we inline everything. 910 addPass(createAMDGPUAlwaysInlinePass()); 911 addPass(createAlwaysInlinerLegacyPass()); 912 // We need to add the barrier noop pass, otherwise adding the function 913 // inlining pass will cause all of the PassConfigs passes to be run 914 // one function at a time, which means if we have a nodule with two 915 // functions, then we will generate code for the first function 916 // without ever running any passes on the second. 917 addPass(createBarrierNoopPass()); 918 919 // Handle uses of OpenCL image2d_t, image3d_t and sampler_t arguments. 920 if (TM.getTargetTriple().getArch() == Triple::r600) 921 addPass(createR600OpenCLImageTypeLoweringPass()); 922 923 // Replace OpenCL enqueued block function pointers with global variables. 924 addPass(createAMDGPUOpenCLEnqueuedBlockLoweringPass()); 925 926 // Can increase LDS used by kernel so runs before PromoteAlloca 927 if (EnableLowerModuleLDS) { 928 // The pass "amdgpu-replace-lds-use-with-pointer" need to be run before the 929 // pass "amdgpu-lower-module-lds", and also it required to be run only if 930 // "amdgpu-lower-module-lds" pass is enabled. 931 if (EnableLDSReplaceWithPointer) 932 addPass(createAMDGPUReplaceLDSUseWithPointerPass()); 933 934 addPass(createAMDGPULowerModuleLDSPass()); 935 } 936 937 if (TM.getOptLevel() > CodeGenOpt::None) 938 addPass(createInferAddressSpacesPass()); 939 940 addPass(createAtomicExpandPass()); 941 942 if (TM.getOptLevel() > CodeGenOpt::None) { 943 addPass(createAMDGPUPromoteAlloca()); 944 945 if (EnableSROA) 946 addPass(createSROAPass()); 947 if (isPassEnabled(EnableScalarIRPasses)) 948 addStraightLineScalarOptimizationPasses(); 949 950 if (EnableAMDGPUAliasAnalysis) { 951 addPass(createAMDGPUAAWrapperPass()); 952 addPass(createExternalAAWrapperPass([](Pass &P, Function &, 953 AAResults &AAR) { 954 if (auto *WrapperPass = P.getAnalysisIfAvailable<AMDGPUAAWrapperPass>()) 955 AAR.addAAResult(WrapperPass->getResult()); 956 })); 957 } 958 959 if (TM.getTargetTriple().getArch() == Triple::amdgcn) { 960 // TODO: May want to move later or split into an early and late one. 961 addPass(createAMDGPUCodeGenPreparePass()); 962 } 963 } 964 965 TargetPassConfig::addIRPasses(); 966 967 // EarlyCSE is not always strong enough to clean up what LSR produces. For 968 // example, GVN can combine 969 // 970 // %0 = add %a, %b 971 // %1 = add %b, %a 972 // 973 // and 974 // 975 // %0 = shl nsw %a, 2 976 // %1 = shl %a, 2 977 // 978 // but EarlyCSE can do neither of them. 979 if (isPassEnabled(EnableScalarIRPasses)) 980 addEarlyCSEOrGVNPass(); 981 } 982 983 void AMDGPUPassConfig::addCodeGenPrepare() { 984 if (TM->getTargetTriple().getArch() == Triple::amdgcn) 985 addPass(createAMDGPUAnnotateKernelFeaturesPass()); 986 987 if (TM->getTargetTriple().getArch() == Triple::amdgcn && 988 EnableLowerKernelArguments) 989 addPass(createAMDGPULowerKernelArgumentsPass()); 990 991 addPass(&AMDGPUPerfHintAnalysisID); 992 993 TargetPassConfig::addCodeGenPrepare(); 994 995 if (isPassEnabled(EnableLoadStoreVectorizer)) 996 addPass(createLoadStoreVectorizerPass()); 997 998 // LowerSwitch pass may introduce unreachable blocks that can 999 // cause unexpected behavior for subsequent passes. Placing it 1000 // here seems better that these blocks would get cleaned up by 1001 // UnreachableBlockElim inserted next in the pass flow. 1002 addPass(createLowerSwitchPass()); 1003 } 1004 1005 bool AMDGPUPassConfig::addPreISel() { 1006 addPass(createFlattenCFGPass()); 1007 return false; 1008 } 1009 1010 bool AMDGPUPassConfig::addInstSelector() { 1011 // Defer the verifier until FinalizeISel. 1012 addPass(createAMDGPUISelDag(&getAMDGPUTargetMachine(), getOptLevel()), false); 1013 return false; 1014 } 1015 1016 bool AMDGPUPassConfig::addGCPasses() { 1017 // Do nothing. GC is not supported. 1018 return false; 1019 } 1020 1021 //===----------------------------------------------------------------------===// 1022 // R600 Pass Setup 1023 //===----------------------------------------------------------------------===// 1024 1025 bool R600PassConfig::addPreISel() { 1026 AMDGPUPassConfig::addPreISel(); 1027 1028 if (EnableR600StructurizeCFG) 1029 addPass(createStructurizeCFGPass()); 1030 return false; 1031 } 1032 1033 bool R600PassConfig::addInstSelector() { 1034 addPass(createR600ISelDag(&getAMDGPUTargetMachine(), getOptLevel())); 1035 return false; 1036 } 1037 1038 void R600PassConfig::addPreRegAlloc() { 1039 addPass(createR600VectorRegMerger()); 1040 } 1041 1042 void R600PassConfig::addPreSched2() { 1043 addPass(createR600EmitClauseMarkers(), false); 1044 if (EnableR600IfConvert) 1045 addPass(&IfConverterID, false); 1046 addPass(createR600ClauseMergePass(), false); 1047 } 1048 1049 void R600PassConfig::addPreEmitPass() { 1050 addPass(createAMDGPUCFGStructurizerPass(), false); 1051 addPass(createR600ExpandSpecialInstrsPass(), false); 1052 addPass(&FinalizeMachineBundlesID, false); 1053 addPass(createR600Packetizer(), false); 1054 addPass(createR600ControlFlowFinalizer(), false); 1055 } 1056 1057 TargetPassConfig *R600TargetMachine::createPassConfig(PassManagerBase &PM) { 1058 return new R600PassConfig(*this, PM); 1059 } 1060 1061 //===----------------------------------------------------------------------===// 1062 // GCN Pass Setup 1063 //===----------------------------------------------------------------------===// 1064 1065 ScheduleDAGInstrs *GCNPassConfig::createMachineScheduler( 1066 MachineSchedContext *C) const { 1067 const GCNSubtarget &ST = C->MF->getSubtarget<GCNSubtarget>(); 1068 if (ST.enableSIScheduler()) 1069 return createSIMachineScheduler(C); 1070 return createGCNMaxOccupancyMachineScheduler(C); 1071 } 1072 1073 bool GCNPassConfig::addPreISel() { 1074 AMDGPUPassConfig::addPreISel(); 1075 1076 if (TM->getOptLevel() > CodeGenOpt::None) 1077 addPass(createAMDGPULateCodeGenPreparePass()); 1078 1079 if (EnableAtomicOptimizations) { 1080 addPass(createAMDGPUAtomicOptimizerPass()); 1081 } 1082 1083 // FIXME: We need to run a pass to propagate the attributes when calls are 1084 // supported. 1085 1086 addPass(createSinkingPass()); 1087 // Merge divergent exit nodes. StructurizeCFG won't recognize the multi-exit 1088 // regions formed by them. 1089 addPass(&AMDGPUUnifyDivergentExitNodesID); 1090 if (!LateCFGStructurize) { 1091 if (EnableStructurizerWorkarounds) { 1092 addPass(createFixIrreduciblePass()); 1093 addPass(createUnifyLoopExitsPass()); 1094 } 1095 addPass(createStructurizeCFGPass(false)); // true -> SkipUniformRegions 1096 } 1097 addPass(createAMDGPUAnnotateUniformValues()); 1098 if (!LateCFGStructurize) { 1099 addPass(createSIAnnotateControlFlowPass()); 1100 } 1101 addPass(createLCSSAPass()); 1102 1103 return false; 1104 } 1105 1106 void GCNPassConfig::addMachineSSAOptimization() { 1107 TargetPassConfig::addMachineSSAOptimization(); 1108 1109 // We want to fold operands after PeepholeOptimizer has run (or as part of 1110 // it), because it will eliminate extra copies making it easier to fold the 1111 // real source operand. We want to eliminate dead instructions after, so that 1112 // we see fewer uses of the copies. We then need to clean up the dead 1113 // instructions leftover after the operands are folded as well. 1114 // 1115 // XXX - Can we get away without running DeadMachineInstructionElim again? 1116 addPass(&SIFoldOperandsID); 1117 if (EnableDPPCombine) 1118 addPass(&GCNDPPCombineID); 1119 addPass(&SILoadStoreOptimizerID); 1120 if (isPassEnabled(EnableSDWAPeephole)) { 1121 addPass(&SIPeepholeSDWAID); 1122 addPass(&EarlyMachineLICMID); 1123 addPass(&MachineCSEID); 1124 addPass(&SIFoldOperandsID); 1125 } 1126 addPass(&DeadMachineInstructionElimID); 1127 addPass(createSIShrinkInstructionsPass()); 1128 } 1129 1130 bool GCNPassConfig::addILPOpts() { 1131 if (EnableEarlyIfConversion) 1132 addPass(&EarlyIfConverterID); 1133 1134 TargetPassConfig::addILPOpts(); 1135 return false; 1136 } 1137 1138 bool GCNPassConfig::addInstSelector() { 1139 AMDGPUPassConfig::addInstSelector(); 1140 addPass(&SIFixSGPRCopiesID); 1141 addPass(createSILowerI1CopiesPass()); 1142 return false; 1143 } 1144 1145 bool GCNPassConfig::addIRTranslator() { 1146 addPass(new IRTranslator(getOptLevel())); 1147 return false; 1148 } 1149 1150 void GCNPassConfig::addPreLegalizeMachineIR() { 1151 bool IsOptNone = getOptLevel() == CodeGenOpt::None; 1152 addPass(createAMDGPUPreLegalizeCombiner(IsOptNone)); 1153 addPass(new Localizer()); 1154 } 1155 1156 bool GCNPassConfig::addLegalizeMachineIR() { 1157 addPass(new Legalizer()); 1158 return false; 1159 } 1160 1161 void GCNPassConfig::addPreRegBankSelect() { 1162 bool IsOptNone = getOptLevel() == CodeGenOpt::None; 1163 addPass(createAMDGPUPostLegalizeCombiner(IsOptNone)); 1164 } 1165 1166 bool GCNPassConfig::addRegBankSelect() { 1167 addPass(new RegBankSelect()); 1168 return false; 1169 } 1170 1171 void GCNPassConfig::addPreGlobalInstructionSelect() { 1172 bool IsOptNone = getOptLevel() == CodeGenOpt::None; 1173 addPass(createAMDGPURegBankCombiner(IsOptNone)); 1174 } 1175 1176 bool GCNPassConfig::addGlobalInstructionSelect() { 1177 addPass(new InstructionSelect(getOptLevel())); 1178 return false; 1179 } 1180 1181 void GCNPassConfig::addPreRegAlloc() { 1182 if (LateCFGStructurize) { 1183 addPass(createAMDGPUMachineCFGStructurizerPass()); 1184 } 1185 } 1186 1187 void GCNPassConfig::addFastRegAlloc() { 1188 // FIXME: We have to disable the verifier here because of PHIElimination + 1189 // TwoAddressInstructions disabling it. 1190 1191 // This must be run immediately after phi elimination and before 1192 // TwoAddressInstructions, otherwise the processing of the tied operand of 1193 // SI_ELSE will introduce a copy of the tied operand source after the else. 1194 insertPass(&PHIEliminationID, &SILowerControlFlowID, false); 1195 1196 insertPass(&TwoAddressInstructionPassID, &SIWholeQuadModeID); 1197 insertPass(&TwoAddressInstructionPassID, &SIPreAllocateWWMRegsID); 1198 1199 TargetPassConfig::addFastRegAlloc(); 1200 } 1201 1202 void GCNPassConfig::addOptimizedRegAlloc() { 1203 // Allow the scheduler to run before SIWholeQuadMode inserts exec manipulation 1204 // instructions that cause scheduling barriers. 1205 insertPass(&MachineSchedulerID, &SIWholeQuadModeID); 1206 insertPass(&MachineSchedulerID, &SIPreAllocateWWMRegsID); 1207 1208 if (OptExecMaskPreRA) 1209 insertPass(&MachineSchedulerID, &SIOptimizeExecMaskingPreRAID); 1210 1211 if (isPassEnabled(EnablePreRAOptimizations)) 1212 insertPass(&RenameIndependentSubregsID, &GCNPreRAOptimizationsID); 1213 1214 // This is not an essential optimization and it has a noticeable impact on 1215 // compilation time, so we only enable it from O2. 1216 if (TM->getOptLevel() > CodeGenOpt::Less) 1217 insertPass(&MachineSchedulerID, &SIFormMemoryClausesID); 1218 1219 // FIXME: when an instruction has a Killed operand, and the instruction is 1220 // inside a bundle, seems only the BUNDLE instruction appears as the Kills of 1221 // the register in LiveVariables, this would trigger a failure in verifier, 1222 // we should fix it and enable the verifier. 1223 if (OptVGPRLiveRange) 1224 insertPass(&LiveVariablesID, &SIOptimizeVGPRLiveRangeID, false); 1225 // This must be run immediately after phi elimination and before 1226 // TwoAddressInstructions, otherwise the processing of the tied operand of 1227 // SI_ELSE will introduce a copy of the tied operand source after the else. 1228 insertPass(&PHIEliminationID, &SILowerControlFlowID, false); 1229 1230 if (EnableDCEInRA) 1231 insertPass(&DetectDeadLanesID, &DeadMachineInstructionElimID); 1232 1233 TargetPassConfig::addOptimizedRegAlloc(); 1234 } 1235 1236 bool GCNPassConfig::addPreRewrite() { 1237 if (EnableRegReassign) 1238 addPass(&GCNNSAReassignID); 1239 return true; 1240 } 1241 1242 void GCNPassConfig::addPostRegAlloc() { 1243 addPass(&SIFixVGPRCopiesID); 1244 if (getOptLevel() > CodeGenOpt::None) 1245 addPass(&SIOptimizeExecMaskingID); 1246 TargetPassConfig::addPostRegAlloc(); 1247 1248 // Equivalent of PEI for SGPRs. 1249 addPass(&SILowerSGPRSpillsID); 1250 } 1251 1252 void GCNPassConfig::addPreSched2() { 1253 addPass(&SIPostRABundlerID); 1254 } 1255 1256 void GCNPassConfig::addPreEmitPass() { 1257 addPass(createSIMemoryLegalizerPass()); 1258 addPass(createSIInsertWaitcntsPass()); 1259 addPass(createSIShrinkInstructionsPass()); 1260 addPass(createSIModeRegisterPass()); 1261 1262 if (getOptLevel() > CodeGenOpt::None) 1263 addPass(&SIInsertHardClausesID); 1264 1265 addPass(&SILateBranchLoweringPassID); 1266 if (getOptLevel() > CodeGenOpt::None) 1267 addPass(&SIPreEmitPeepholeID); 1268 // The hazard recognizer that runs as part of the post-ra scheduler does not 1269 // guarantee to be able handle all hazards correctly. This is because if there 1270 // are multiple scheduling regions in a basic block, the regions are scheduled 1271 // bottom up, so when we begin to schedule a region we don't know what 1272 // instructions were emitted directly before it. 1273 // 1274 // Here we add a stand-alone hazard recognizer pass which can handle all 1275 // cases. 1276 addPass(&PostRAHazardRecognizerID); 1277 addPass(&BranchRelaxationPassID); 1278 } 1279 1280 TargetPassConfig *GCNTargetMachine::createPassConfig(PassManagerBase &PM) { 1281 return new GCNPassConfig(*this, PM); 1282 } 1283 1284 yaml::MachineFunctionInfo *GCNTargetMachine::createDefaultFuncInfoYAML() const { 1285 return new yaml::SIMachineFunctionInfo(); 1286 } 1287 1288 yaml::MachineFunctionInfo * 1289 GCNTargetMachine::convertFuncInfoToYAML(const MachineFunction &MF) const { 1290 const SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>(); 1291 return new yaml::SIMachineFunctionInfo( 1292 *MFI, *MF.getSubtarget().getRegisterInfo(), MF); 1293 } 1294 1295 bool GCNTargetMachine::parseMachineFunctionInfo( 1296 const yaml::MachineFunctionInfo &MFI_, PerFunctionMIParsingState &PFS, 1297 SMDiagnostic &Error, SMRange &SourceRange) const { 1298 const yaml::SIMachineFunctionInfo &YamlMFI = 1299 reinterpret_cast<const yaml::SIMachineFunctionInfo &>(MFI_); 1300 MachineFunction &MF = PFS.MF; 1301 SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>(); 1302 1303 if (MFI->initializeBaseYamlFields(YamlMFI, MF, PFS, Error, SourceRange)) 1304 return true; 1305 1306 if (MFI->Occupancy == 0) { 1307 // Fixup the subtarget dependent default value. 1308 const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>(); 1309 MFI->Occupancy = ST.computeOccupancy(MF.getFunction(), MFI->getLDSSize()); 1310 } 1311 1312 auto parseRegister = [&](const yaml::StringValue &RegName, Register &RegVal) { 1313 Register TempReg; 1314 if (parseNamedRegisterReference(PFS, TempReg, RegName.Value, Error)) { 1315 SourceRange = RegName.SourceRange; 1316 return true; 1317 } 1318 RegVal = TempReg; 1319 1320 return false; 1321 }; 1322 1323 auto diagnoseRegisterClass = [&](const yaml::StringValue &RegName) { 1324 // Create a diagnostic for a the register string literal. 1325 const MemoryBuffer &Buffer = 1326 *PFS.SM->getMemoryBuffer(PFS.SM->getMainFileID()); 1327 Error = SMDiagnostic(*PFS.SM, SMLoc(), Buffer.getBufferIdentifier(), 1, 1328 RegName.Value.size(), SourceMgr::DK_Error, 1329 "incorrect register class for field", RegName.Value, 1330 None, None); 1331 SourceRange = RegName.SourceRange; 1332 return true; 1333 }; 1334 1335 if (parseRegister(YamlMFI.ScratchRSrcReg, MFI->ScratchRSrcReg) || 1336 parseRegister(YamlMFI.FrameOffsetReg, MFI->FrameOffsetReg) || 1337 parseRegister(YamlMFI.StackPtrOffsetReg, MFI->StackPtrOffsetReg)) 1338 return true; 1339 1340 if (MFI->ScratchRSrcReg != AMDGPU::PRIVATE_RSRC_REG && 1341 !AMDGPU::SGPR_128RegClass.contains(MFI->ScratchRSrcReg)) { 1342 return diagnoseRegisterClass(YamlMFI.ScratchRSrcReg); 1343 } 1344 1345 if (MFI->FrameOffsetReg != AMDGPU::FP_REG && 1346 !AMDGPU::SGPR_32RegClass.contains(MFI->FrameOffsetReg)) { 1347 return diagnoseRegisterClass(YamlMFI.FrameOffsetReg); 1348 } 1349 1350 if (MFI->StackPtrOffsetReg != AMDGPU::SP_REG && 1351 !AMDGPU::SGPR_32RegClass.contains(MFI->StackPtrOffsetReg)) { 1352 return diagnoseRegisterClass(YamlMFI.StackPtrOffsetReg); 1353 } 1354 1355 auto parseAndCheckArgument = [&](const Optional<yaml::SIArgument> &A, 1356 const TargetRegisterClass &RC, 1357 ArgDescriptor &Arg, unsigned UserSGPRs, 1358 unsigned SystemSGPRs) { 1359 // Skip parsing if it's not present. 1360 if (!A) 1361 return false; 1362 1363 if (A->IsRegister) { 1364 Register Reg; 1365 if (parseNamedRegisterReference(PFS, Reg, A->RegisterName.Value, Error)) { 1366 SourceRange = A->RegisterName.SourceRange; 1367 return true; 1368 } 1369 if (!RC.contains(Reg)) 1370 return diagnoseRegisterClass(A->RegisterName); 1371 Arg = ArgDescriptor::createRegister(Reg); 1372 } else 1373 Arg = ArgDescriptor::createStack(A->StackOffset); 1374 // Check and apply the optional mask. 1375 if (A->Mask) 1376 Arg = ArgDescriptor::createArg(Arg, A->Mask.getValue()); 1377 1378 MFI->NumUserSGPRs += UserSGPRs; 1379 MFI->NumSystemSGPRs += SystemSGPRs; 1380 return false; 1381 }; 1382 1383 if (YamlMFI.ArgInfo && 1384 (parseAndCheckArgument(YamlMFI.ArgInfo->PrivateSegmentBuffer, 1385 AMDGPU::SGPR_128RegClass, 1386 MFI->ArgInfo.PrivateSegmentBuffer, 4, 0) || 1387 parseAndCheckArgument(YamlMFI.ArgInfo->DispatchPtr, 1388 AMDGPU::SReg_64RegClass, MFI->ArgInfo.DispatchPtr, 1389 2, 0) || 1390 parseAndCheckArgument(YamlMFI.ArgInfo->QueuePtr, AMDGPU::SReg_64RegClass, 1391 MFI->ArgInfo.QueuePtr, 2, 0) || 1392 parseAndCheckArgument(YamlMFI.ArgInfo->KernargSegmentPtr, 1393 AMDGPU::SReg_64RegClass, 1394 MFI->ArgInfo.KernargSegmentPtr, 2, 0) || 1395 parseAndCheckArgument(YamlMFI.ArgInfo->DispatchID, 1396 AMDGPU::SReg_64RegClass, MFI->ArgInfo.DispatchID, 1397 2, 0) || 1398 parseAndCheckArgument(YamlMFI.ArgInfo->FlatScratchInit, 1399 AMDGPU::SReg_64RegClass, 1400 MFI->ArgInfo.FlatScratchInit, 2, 0) || 1401 parseAndCheckArgument(YamlMFI.ArgInfo->PrivateSegmentSize, 1402 AMDGPU::SGPR_32RegClass, 1403 MFI->ArgInfo.PrivateSegmentSize, 0, 0) || 1404 parseAndCheckArgument(YamlMFI.ArgInfo->WorkGroupIDX, 1405 AMDGPU::SGPR_32RegClass, MFI->ArgInfo.WorkGroupIDX, 1406 0, 1) || 1407 parseAndCheckArgument(YamlMFI.ArgInfo->WorkGroupIDY, 1408 AMDGPU::SGPR_32RegClass, MFI->ArgInfo.WorkGroupIDY, 1409 0, 1) || 1410 parseAndCheckArgument(YamlMFI.ArgInfo->WorkGroupIDZ, 1411 AMDGPU::SGPR_32RegClass, MFI->ArgInfo.WorkGroupIDZ, 1412 0, 1) || 1413 parseAndCheckArgument(YamlMFI.ArgInfo->WorkGroupInfo, 1414 AMDGPU::SGPR_32RegClass, 1415 MFI->ArgInfo.WorkGroupInfo, 0, 1) || 1416 parseAndCheckArgument(YamlMFI.ArgInfo->PrivateSegmentWaveByteOffset, 1417 AMDGPU::SGPR_32RegClass, 1418 MFI->ArgInfo.PrivateSegmentWaveByteOffset, 0, 1) || 1419 parseAndCheckArgument(YamlMFI.ArgInfo->ImplicitArgPtr, 1420 AMDGPU::SReg_64RegClass, 1421 MFI->ArgInfo.ImplicitArgPtr, 0, 0) || 1422 parseAndCheckArgument(YamlMFI.ArgInfo->ImplicitBufferPtr, 1423 AMDGPU::SReg_64RegClass, 1424 MFI->ArgInfo.ImplicitBufferPtr, 2, 0) || 1425 parseAndCheckArgument(YamlMFI.ArgInfo->WorkItemIDX, 1426 AMDGPU::VGPR_32RegClass, 1427 MFI->ArgInfo.WorkItemIDX, 0, 0) || 1428 parseAndCheckArgument(YamlMFI.ArgInfo->WorkItemIDY, 1429 AMDGPU::VGPR_32RegClass, 1430 MFI->ArgInfo.WorkItemIDY, 0, 0) || 1431 parseAndCheckArgument(YamlMFI.ArgInfo->WorkItemIDZ, 1432 AMDGPU::VGPR_32RegClass, 1433 MFI->ArgInfo.WorkItemIDZ, 0, 0))) 1434 return true; 1435 1436 MFI->Mode.IEEE = YamlMFI.Mode.IEEE; 1437 MFI->Mode.DX10Clamp = YamlMFI.Mode.DX10Clamp; 1438 MFI->Mode.FP32InputDenormals = YamlMFI.Mode.FP32InputDenormals; 1439 MFI->Mode.FP32OutputDenormals = YamlMFI.Mode.FP32OutputDenormals; 1440 MFI->Mode.FP64FP16InputDenormals = YamlMFI.Mode.FP64FP16InputDenormals; 1441 MFI->Mode.FP64FP16OutputDenormals = YamlMFI.Mode.FP64FP16OutputDenormals; 1442 1443 return false; 1444 } 1445