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 SI+ GPUs. 12 // 13 //===----------------------------------------------------------------------===// 14 15 #include "AMDGPUTargetMachine.h" 16 #include "AMDGPU.h" 17 #include "AMDGPUAliasAnalysis.h" 18 #include "AMDGPUCtorDtorLowering.h" 19 #include "AMDGPUExportClustering.h" 20 #include "AMDGPUIGroupLP.h" 21 #include "AMDGPUMacroFusion.h" 22 #include "AMDGPURegBankSelect.h" 23 #include "AMDGPUTargetObjectFile.h" 24 #include "AMDGPUTargetTransformInfo.h" 25 #include "AMDGPUUnifyDivergentExitNodes.h" 26 #include "GCNIterativeScheduler.h" 27 #include "GCNSchedStrategy.h" 28 #include "GCNVOPDUtils.h" 29 #include "R600.h" 30 #include "R600MachineFunctionInfo.h" 31 #include "R600TargetMachine.h" 32 #include "SIMachineFunctionInfo.h" 33 #include "SIMachineScheduler.h" 34 #include "TargetInfo/AMDGPUTargetInfo.h" 35 #include "Utils/AMDGPUBaseInfo.h" 36 #include "llvm/Analysis/CGSCCPassManager.h" 37 #include "llvm/CodeGen/GlobalISel/CSEInfo.h" 38 #include "llvm/CodeGen/GlobalISel/IRTranslator.h" 39 #include "llvm/CodeGen/GlobalISel/InstructionSelect.h" 40 #include "llvm/CodeGen/GlobalISel/Legalizer.h" 41 #include "llvm/CodeGen/GlobalISel/Localizer.h" 42 #include "llvm/CodeGen/GlobalISel/RegBankSelect.h" 43 #include "llvm/CodeGen/MIRParser/MIParser.h" 44 #include "llvm/CodeGen/Passes.h" 45 #include "llvm/CodeGen/RegAllocRegistry.h" 46 #include "llvm/CodeGen/TargetPassConfig.h" 47 #include "llvm/IR/IntrinsicsAMDGPU.h" 48 #include "llvm/IR/PassManager.h" 49 #include "llvm/IR/PatternMatch.h" 50 #include "llvm/InitializePasses.h" 51 #include "llvm/MC/TargetRegistry.h" 52 #include "llvm/Passes/PassBuilder.h" 53 #include "llvm/Transforms/HipStdPar/HipStdPar.h" 54 #include "llvm/Transforms/IPO.h" 55 #include "llvm/Transforms/IPO/AlwaysInliner.h" 56 #include "llvm/Transforms/IPO/GlobalDCE.h" 57 #include "llvm/Transforms/IPO/Internalize.h" 58 #include "llvm/Transforms/Scalar.h" 59 #include "llvm/Transforms/Scalar/GVN.h" 60 #include "llvm/Transforms/Scalar/InferAddressSpaces.h" 61 #include "llvm/Transforms/Utils.h" 62 #include "llvm/Transforms/Utils/SimplifyLibCalls.h" 63 #include "llvm/Transforms/Vectorize/LoadStoreVectorizer.h" 64 #include <optional> 65 66 using namespace llvm; 67 using namespace llvm::PatternMatch; 68 69 namespace { 70 class SGPRRegisterRegAlloc : public RegisterRegAllocBase<SGPRRegisterRegAlloc> { 71 public: 72 SGPRRegisterRegAlloc(const char *N, const char *D, FunctionPassCtor C) 73 : RegisterRegAllocBase(N, D, C) {} 74 }; 75 76 class VGPRRegisterRegAlloc : public RegisterRegAllocBase<VGPRRegisterRegAlloc> { 77 public: 78 VGPRRegisterRegAlloc(const char *N, const char *D, FunctionPassCtor C) 79 : RegisterRegAllocBase(N, D, C) {} 80 }; 81 82 static bool onlyAllocateSGPRs(const TargetRegisterInfo &TRI, 83 const TargetRegisterClass &RC) { 84 return static_cast<const SIRegisterInfo &>(TRI).isSGPRClass(&RC); 85 } 86 87 static bool onlyAllocateVGPRs(const TargetRegisterInfo &TRI, 88 const TargetRegisterClass &RC) { 89 return !static_cast<const SIRegisterInfo &>(TRI).isSGPRClass(&RC); 90 } 91 92 93 /// -{sgpr|vgpr}-regalloc=... command line option. 94 static FunctionPass *useDefaultRegisterAllocator() { return nullptr; } 95 96 /// A dummy default pass factory indicates whether the register allocator is 97 /// overridden on the command line. 98 static llvm::once_flag InitializeDefaultSGPRRegisterAllocatorFlag; 99 static llvm::once_flag InitializeDefaultVGPRRegisterAllocatorFlag; 100 101 static SGPRRegisterRegAlloc 102 defaultSGPRRegAlloc("default", 103 "pick SGPR register allocator based on -O option", 104 useDefaultRegisterAllocator); 105 106 static cl::opt<SGPRRegisterRegAlloc::FunctionPassCtor, false, 107 RegisterPassParser<SGPRRegisterRegAlloc>> 108 SGPRRegAlloc("sgpr-regalloc", cl::Hidden, cl::init(&useDefaultRegisterAllocator), 109 cl::desc("Register allocator to use for SGPRs")); 110 111 static cl::opt<VGPRRegisterRegAlloc::FunctionPassCtor, false, 112 RegisterPassParser<VGPRRegisterRegAlloc>> 113 VGPRRegAlloc("vgpr-regalloc", cl::Hidden, cl::init(&useDefaultRegisterAllocator), 114 cl::desc("Register allocator to use for VGPRs")); 115 116 117 static void initializeDefaultSGPRRegisterAllocatorOnce() { 118 RegisterRegAlloc::FunctionPassCtor Ctor = SGPRRegisterRegAlloc::getDefault(); 119 120 if (!Ctor) { 121 Ctor = SGPRRegAlloc; 122 SGPRRegisterRegAlloc::setDefault(SGPRRegAlloc); 123 } 124 } 125 126 static void initializeDefaultVGPRRegisterAllocatorOnce() { 127 RegisterRegAlloc::FunctionPassCtor Ctor = VGPRRegisterRegAlloc::getDefault(); 128 129 if (!Ctor) { 130 Ctor = VGPRRegAlloc; 131 VGPRRegisterRegAlloc::setDefault(VGPRRegAlloc); 132 } 133 } 134 135 static FunctionPass *createBasicSGPRRegisterAllocator() { 136 return createBasicRegisterAllocator(onlyAllocateSGPRs); 137 } 138 139 static FunctionPass *createGreedySGPRRegisterAllocator() { 140 return createGreedyRegisterAllocator(onlyAllocateSGPRs); 141 } 142 143 static FunctionPass *createFastSGPRRegisterAllocator() { 144 return createFastRegisterAllocator(onlyAllocateSGPRs, false); 145 } 146 147 static FunctionPass *createBasicVGPRRegisterAllocator() { 148 return createBasicRegisterAllocator(onlyAllocateVGPRs); 149 } 150 151 static FunctionPass *createGreedyVGPRRegisterAllocator() { 152 return createGreedyRegisterAllocator(onlyAllocateVGPRs); 153 } 154 155 static FunctionPass *createFastVGPRRegisterAllocator() { 156 return createFastRegisterAllocator(onlyAllocateVGPRs, true); 157 } 158 159 static SGPRRegisterRegAlloc basicRegAllocSGPR( 160 "basic", "basic register allocator", createBasicSGPRRegisterAllocator); 161 static SGPRRegisterRegAlloc greedyRegAllocSGPR( 162 "greedy", "greedy register allocator", createGreedySGPRRegisterAllocator); 163 164 static SGPRRegisterRegAlloc fastRegAllocSGPR( 165 "fast", "fast register allocator", createFastSGPRRegisterAllocator); 166 167 168 static VGPRRegisterRegAlloc basicRegAllocVGPR( 169 "basic", "basic register allocator", createBasicVGPRRegisterAllocator); 170 static VGPRRegisterRegAlloc greedyRegAllocVGPR( 171 "greedy", "greedy register allocator", createGreedyVGPRRegisterAllocator); 172 173 static VGPRRegisterRegAlloc fastRegAllocVGPR( 174 "fast", "fast register allocator", createFastVGPRRegisterAllocator); 175 } 176 177 static cl::opt<bool> 178 EnableEarlyIfConversion("amdgpu-early-ifcvt", cl::Hidden, 179 cl::desc("Run early if-conversion"), 180 cl::init(false)); 181 182 static cl::opt<bool> 183 OptExecMaskPreRA("amdgpu-opt-exec-mask-pre-ra", cl::Hidden, 184 cl::desc("Run pre-RA exec mask optimizations"), 185 cl::init(true)); 186 187 static cl::opt<bool> 188 LowerCtorDtor("amdgpu-lower-global-ctor-dtor", 189 cl::desc("Lower GPU ctor / dtors to globals on the device."), 190 cl::init(true), cl::Hidden); 191 192 // Option to disable vectorizer for tests. 193 static cl::opt<bool> EnableLoadStoreVectorizer( 194 "amdgpu-load-store-vectorizer", 195 cl::desc("Enable load store vectorizer"), 196 cl::init(true), 197 cl::Hidden); 198 199 // Option to control global loads scalarization 200 static cl::opt<bool> ScalarizeGlobal( 201 "amdgpu-scalarize-global-loads", 202 cl::desc("Enable global load scalarization"), 203 cl::init(true), 204 cl::Hidden); 205 206 // Option to run internalize pass. 207 static cl::opt<bool> InternalizeSymbols( 208 "amdgpu-internalize-symbols", 209 cl::desc("Enable elimination of non-kernel functions and unused globals"), 210 cl::init(false), 211 cl::Hidden); 212 213 // Option to inline all early. 214 static cl::opt<bool> EarlyInlineAll( 215 "amdgpu-early-inline-all", 216 cl::desc("Inline all functions early"), 217 cl::init(false), 218 cl::Hidden); 219 220 static cl::opt<bool> RemoveIncompatibleFunctions( 221 "amdgpu-enable-remove-incompatible-functions", cl::Hidden, 222 cl::desc("Enable removal of functions when they" 223 "use features not supported by the target GPU"), 224 cl::init(true)); 225 226 static cl::opt<bool> EnableSDWAPeephole( 227 "amdgpu-sdwa-peephole", 228 cl::desc("Enable SDWA peepholer"), 229 cl::init(true)); 230 231 static cl::opt<bool> EnableDPPCombine( 232 "amdgpu-dpp-combine", 233 cl::desc("Enable DPP combiner"), 234 cl::init(true)); 235 236 // Enable address space based alias analysis 237 static cl::opt<bool> EnableAMDGPUAliasAnalysis("enable-amdgpu-aa", cl::Hidden, 238 cl::desc("Enable AMDGPU Alias Analysis"), 239 cl::init(true)); 240 241 // Option to run late CFG structurizer 242 static cl::opt<bool, true> LateCFGStructurize( 243 "amdgpu-late-structurize", 244 cl::desc("Enable late CFG structurization"), 245 cl::location(AMDGPUTargetMachine::EnableLateStructurizeCFG), 246 cl::Hidden); 247 248 // Enable lib calls simplifications 249 static cl::opt<bool> EnableLibCallSimplify( 250 "amdgpu-simplify-libcall", 251 cl::desc("Enable amdgpu library simplifications"), 252 cl::init(true), 253 cl::Hidden); 254 255 static cl::opt<bool> EnableLowerKernelArguments( 256 "amdgpu-ir-lower-kernel-arguments", 257 cl::desc("Lower kernel argument loads in IR pass"), 258 cl::init(true), 259 cl::Hidden); 260 261 static cl::opt<bool> EnableRegReassign( 262 "amdgpu-reassign-regs", 263 cl::desc("Enable register reassign optimizations on gfx10+"), 264 cl::init(true), 265 cl::Hidden); 266 267 static cl::opt<bool> OptVGPRLiveRange( 268 "amdgpu-opt-vgpr-liverange", 269 cl::desc("Enable VGPR liverange optimizations for if-else structure"), 270 cl::init(true), cl::Hidden); 271 272 static cl::opt<ScanOptions> AMDGPUAtomicOptimizerStrategy( 273 "amdgpu-atomic-optimizer-strategy", 274 cl::desc("Select DPP or Iterative strategy for scan"), 275 cl::init(ScanOptions::Iterative), 276 cl::values( 277 clEnumValN(ScanOptions::DPP, "DPP", "Use DPP operations for scan"), 278 clEnumValN(ScanOptions::Iterative, "Iterative", 279 "Use Iterative approach for scan"), 280 clEnumValN(ScanOptions::None, "None", "Disable atomic optimizer"))); 281 282 // Enable Mode register optimization 283 static cl::opt<bool> EnableSIModeRegisterPass( 284 "amdgpu-mode-register", 285 cl::desc("Enable mode register pass"), 286 cl::init(true), 287 cl::Hidden); 288 289 // Enable GFX11.5+ s_singleuse_vdst insertion 290 static cl::opt<bool> 291 EnableInsertSingleUseVDST("amdgpu-enable-single-use-vdst", 292 cl::desc("Enable s_singleuse_vdst insertion"), 293 cl::init(false), cl::Hidden); 294 295 // Enable GFX11+ s_delay_alu insertion 296 static cl::opt<bool> 297 EnableInsertDelayAlu("amdgpu-enable-delay-alu", 298 cl::desc("Enable s_delay_alu insertion"), 299 cl::init(true), cl::Hidden); 300 301 // Enable GFX11+ VOPD 302 static cl::opt<bool> 303 EnableVOPD("amdgpu-enable-vopd", 304 cl::desc("Enable VOPD, dual issue of VALU in wave32"), 305 cl::init(true), cl::Hidden); 306 307 // Option is used in lit tests to prevent deadcoding of patterns inspected. 308 static cl::opt<bool> 309 EnableDCEInRA("amdgpu-dce-in-ra", 310 cl::init(true), cl::Hidden, 311 cl::desc("Enable machine DCE inside regalloc")); 312 313 static cl::opt<bool> EnableSetWavePriority("amdgpu-set-wave-priority", 314 cl::desc("Adjust wave priority"), 315 cl::init(false), cl::Hidden); 316 317 static cl::opt<bool> EnableScalarIRPasses( 318 "amdgpu-scalar-ir-passes", 319 cl::desc("Enable scalar IR passes"), 320 cl::init(true), 321 cl::Hidden); 322 323 static cl::opt<bool> EnableStructurizerWorkarounds( 324 "amdgpu-enable-structurizer-workarounds", 325 cl::desc("Enable workarounds for the StructurizeCFG pass"), cl::init(true), 326 cl::Hidden); 327 328 static cl::opt<bool, true> EnableLowerModuleLDS( 329 "amdgpu-enable-lower-module-lds", cl::desc("Enable lower module lds pass"), 330 cl::location(AMDGPUTargetMachine::EnableLowerModuleLDS), cl::init(true), 331 cl::Hidden); 332 333 static cl::opt<bool> EnablePreRAOptimizations( 334 "amdgpu-enable-pre-ra-optimizations", 335 cl::desc("Enable Pre-RA optimizations pass"), cl::init(true), 336 cl::Hidden); 337 338 static cl::opt<bool> EnablePromoteKernelArguments( 339 "amdgpu-enable-promote-kernel-arguments", 340 cl::desc("Enable promotion of flat kernel pointer arguments to global"), 341 cl::Hidden, cl::init(true)); 342 343 static cl::opt<bool> EnableImageIntrinsicOptimizer( 344 "amdgpu-enable-image-intrinsic-optimizer", 345 cl::desc("Enable image intrinsic optimizer pass"), cl::init(true), 346 cl::Hidden); 347 348 static cl::opt<bool> 349 EnableLoopPrefetch("amdgpu-loop-prefetch", 350 cl::desc("Enable loop data prefetch on AMDGPU"), 351 cl::Hidden, cl::init(false)); 352 353 static cl::opt<bool> EnableMaxIlpSchedStrategy( 354 "amdgpu-enable-max-ilp-scheduling-strategy", 355 cl::desc("Enable scheduling strategy to maximize ILP for a single wave."), 356 cl::Hidden, cl::init(false)); 357 358 static cl::opt<bool> EnableRewritePartialRegUses( 359 "amdgpu-enable-rewrite-partial-reg-uses", 360 cl::desc("Enable rewrite partial reg uses pass"), cl::init(true), 361 cl::Hidden); 362 363 static cl::opt<bool> EnableHipStdPar( 364 "amdgpu-enable-hipstdpar", 365 cl::desc("Enable HIP Standard Parallelism Offload support"), cl::init(false), 366 cl::Hidden); 367 368 extern "C" LLVM_EXTERNAL_VISIBILITY void LLVMInitializeAMDGPUTarget() { 369 // Register the target 370 RegisterTargetMachine<R600TargetMachine> X(getTheR600Target()); 371 RegisterTargetMachine<GCNTargetMachine> Y(getTheGCNTarget()); 372 373 PassRegistry *PR = PassRegistry::getPassRegistry(); 374 initializeR600ClauseMergePassPass(*PR); 375 initializeR600ControlFlowFinalizerPass(*PR); 376 initializeR600PacketizerPass(*PR); 377 initializeR600ExpandSpecialInstrsPassPass(*PR); 378 initializeR600VectorRegMergerPass(*PR); 379 initializeGlobalISel(*PR); 380 initializeAMDGPUDAGToDAGISelPass(*PR); 381 initializeGCNDPPCombinePass(*PR); 382 initializeSILowerI1CopiesPass(*PR); 383 initializeAMDGPUGlobalISelDivergenceLoweringPass(*PR); 384 initializeSILowerWWMCopiesPass(*PR); 385 initializeSILowerSGPRSpillsPass(*PR); 386 initializeSIFixSGPRCopiesPass(*PR); 387 initializeSIFixVGPRCopiesPass(*PR); 388 initializeSIFoldOperandsPass(*PR); 389 initializeSIPeepholeSDWAPass(*PR); 390 initializeSIShrinkInstructionsPass(*PR); 391 initializeSIOptimizeExecMaskingPreRAPass(*PR); 392 initializeSIOptimizeVGPRLiveRangePass(*PR); 393 initializeSILoadStoreOptimizerPass(*PR); 394 initializeAMDGPUCtorDtorLoweringLegacyPass(*PR); 395 initializeAMDGPUAlwaysInlinePass(*PR); 396 initializeAMDGPUAttributorLegacyPass(*PR); 397 initializeAMDGPUAnnotateKernelFeaturesPass(*PR); 398 initializeAMDGPUAnnotateUniformValuesPass(*PR); 399 initializeAMDGPUArgumentUsageInfoPass(*PR); 400 initializeAMDGPUAtomicOptimizerPass(*PR); 401 initializeAMDGPULowerKernelArgumentsPass(*PR); 402 initializeAMDGPUPromoteKernelArgumentsPass(*PR); 403 initializeAMDGPULowerKernelAttributesPass(*PR); 404 initializeAMDGPUOpenCLEnqueuedBlockLoweringPass(*PR); 405 initializeAMDGPUPostLegalizerCombinerPass(*PR); 406 initializeAMDGPUPreLegalizerCombinerPass(*PR); 407 initializeAMDGPURegBankCombinerPass(*PR); 408 initializeAMDGPURegBankSelectPass(*PR); 409 initializeAMDGPUPromoteAllocaPass(*PR); 410 initializeAMDGPUPromoteAllocaToVectorPass(*PR); 411 initializeAMDGPUCodeGenPreparePass(*PR); 412 initializeAMDGPULateCodeGenPreparePass(*PR); 413 initializeAMDGPURemoveIncompatibleFunctionsPass(*PR); 414 initializeAMDGPULowerModuleLDSLegacyPass(*PR); 415 initializeAMDGPURewriteOutArgumentsPass(*PR); 416 initializeAMDGPURewriteUndefForPHILegacyPass(*PR); 417 initializeAMDGPUUnifyMetadataPass(*PR); 418 initializeSIAnnotateControlFlowPass(*PR); 419 initializeAMDGPUInsertSingleUseVDSTPass(*PR); 420 initializeAMDGPUInsertDelayAluPass(*PR); 421 initializeSIInsertHardClausesPass(*PR); 422 initializeSIInsertWaitcntsPass(*PR); 423 initializeSIModeRegisterPass(*PR); 424 initializeSIWholeQuadModePass(*PR); 425 initializeSILowerControlFlowPass(*PR); 426 initializeSIPreEmitPeepholePass(*PR); 427 initializeSILateBranchLoweringPass(*PR); 428 initializeSIMemoryLegalizerPass(*PR); 429 initializeSIOptimizeExecMaskingPass(*PR); 430 initializeSIPreAllocateWWMRegsPass(*PR); 431 initializeSIFormMemoryClausesPass(*PR); 432 initializeSIPostRABundlerPass(*PR); 433 initializeGCNCreateVOPDPass(*PR); 434 initializeAMDGPUUnifyDivergentExitNodesPass(*PR); 435 initializeAMDGPUAAWrapperPassPass(*PR); 436 initializeAMDGPUExternalAAWrapperPass(*PR); 437 initializeAMDGPUImageIntrinsicOptimizerPass(*PR); 438 initializeAMDGPUPrintfRuntimeBindingPass(*PR); 439 initializeAMDGPUResourceUsageAnalysisPass(*PR); 440 initializeGCNNSAReassignPass(*PR); 441 initializeGCNPreRAOptimizationsPass(*PR); 442 initializeGCNPreRALongBranchRegPass(*PR); 443 initializeGCNRewritePartialRegUsesPass(*PR); 444 initializeGCNRegPressurePrinterPass(*PR); 445 } 446 447 static std::unique_ptr<TargetLoweringObjectFile> createTLOF(const Triple &TT) { 448 return std::make_unique<AMDGPUTargetObjectFile>(); 449 } 450 451 static ScheduleDAGInstrs *createSIMachineScheduler(MachineSchedContext *C) { 452 return new SIScheduleDAGMI(C); 453 } 454 455 static ScheduleDAGInstrs * 456 createGCNMaxOccupancyMachineScheduler(MachineSchedContext *C) { 457 const GCNSubtarget &ST = C->MF->getSubtarget<GCNSubtarget>(); 458 ScheduleDAGMILive *DAG = 459 new GCNScheduleDAGMILive(C, std::make_unique<GCNMaxOccupancySchedStrategy>(C)); 460 DAG->addMutation(createLoadClusterDAGMutation(DAG->TII, DAG->TRI)); 461 if (ST.shouldClusterStores()) 462 DAG->addMutation(createStoreClusterDAGMutation(DAG->TII, DAG->TRI)); 463 DAG->addMutation(createIGroupLPDAGMutation(/*IsPostRA=*/false)); 464 DAG->addMutation(createAMDGPUMacroFusionDAGMutation()); 465 DAG->addMutation(createAMDGPUExportClusteringDAGMutation()); 466 return DAG; 467 } 468 469 static ScheduleDAGInstrs * 470 createGCNMaxILPMachineScheduler(MachineSchedContext *C) { 471 ScheduleDAGMILive *DAG = 472 new GCNScheduleDAGMILive(C, std::make_unique<GCNMaxILPSchedStrategy>(C)); 473 DAG->addMutation(createIGroupLPDAGMutation(/*IsPostRA=*/false)); 474 return DAG; 475 } 476 477 static ScheduleDAGInstrs * 478 createIterativeGCNMaxOccupancyMachineScheduler(MachineSchedContext *C) { 479 const GCNSubtarget &ST = C->MF->getSubtarget<GCNSubtarget>(); 480 auto DAG = new GCNIterativeScheduler(C, 481 GCNIterativeScheduler::SCHEDULE_LEGACYMAXOCCUPANCY); 482 DAG->addMutation(createLoadClusterDAGMutation(DAG->TII, DAG->TRI)); 483 if (ST.shouldClusterStores()) 484 DAG->addMutation(createStoreClusterDAGMutation(DAG->TII, DAG->TRI)); 485 return DAG; 486 } 487 488 static ScheduleDAGInstrs *createMinRegScheduler(MachineSchedContext *C) { 489 return new GCNIterativeScheduler(C, 490 GCNIterativeScheduler::SCHEDULE_MINREGFORCED); 491 } 492 493 static ScheduleDAGInstrs * 494 createIterativeILPMachineScheduler(MachineSchedContext *C) { 495 const GCNSubtarget &ST = C->MF->getSubtarget<GCNSubtarget>(); 496 auto DAG = new GCNIterativeScheduler(C, 497 GCNIterativeScheduler::SCHEDULE_ILP); 498 DAG->addMutation(createLoadClusterDAGMutation(DAG->TII, DAG->TRI)); 499 if (ST.shouldClusterStores()) 500 DAG->addMutation(createStoreClusterDAGMutation(DAG->TII, DAG->TRI)); 501 DAG->addMutation(createAMDGPUMacroFusionDAGMutation()); 502 return DAG; 503 } 504 505 static MachineSchedRegistry 506 SISchedRegistry("si", "Run SI's custom scheduler", 507 createSIMachineScheduler); 508 509 static MachineSchedRegistry 510 GCNMaxOccupancySchedRegistry("gcn-max-occupancy", 511 "Run GCN scheduler to maximize occupancy", 512 createGCNMaxOccupancyMachineScheduler); 513 514 static MachineSchedRegistry 515 GCNMaxILPSchedRegistry("gcn-max-ilp", "Run GCN scheduler to maximize ilp", 516 createGCNMaxILPMachineScheduler); 517 518 static MachineSchedRegistry IterativeGCNMaxOccupancySchedRegistry( 519 "gcn-iterative-max-occupancy-experimental", 520 "Run GCN scheduler to maximize occupancy (experimental)", 521 createIterativeGCNMaxOccupancyMachineScheduler); 522 523 static MachineSchedRegistry GCNMinRegSchedRegistry( 524 "gcn-iterative-minreg", 525 "Run GCN iterative scheduler for minimal register usage (experimental)", 526 createMinRegScheduler); 527 528 static MachineSchedRegistry GCNILPSchedRegistry( 529 "gcn-iterative-ilp", 530 "Run GCN iterative scheduler for ILP scheduling (experimental)", 531 createIterativeILPMachineScheduler); 532 533 static StringRef computeDataLayout(const Triple &TT) { 534 if (TT.getArch() == Triple::r600) { 535 // 32-bit pointers. 536 return "e-p:32:32-i64:64-v16:16-v24:32-v32:32-v48:64-v96:128" 537 "-v192:256-v256:256-v512:512-v1024:1024-v2048:2048-n32:64-S32-A5-G1"; 538 } 539 540 // 32-bit private, local, and region pointers. 64-bit global, constant and 541 // flat. 160-bit non-integral fat buffer pointers that include a 128-bit 542 // buffer descriptor and a 32-bit offset, which are indexed by 32-bit values 543 // (address space 7), and 128-bit non-integral buffer resourcees (address 544 // space 8) which cannot be non-trivilally accessed by LLVM memory operations 545 // like getelementptr. 546 return "e-p:64:64-p1:64:64-p2:32:32-p3:32:32-p4:64:64-p5:32:32-p6:32:32" 547 "-p7:160:256:256:32-p8:128:128-p9:192:256:256:32-i64:64-v16:16-v24:32-" 548 "v32:32-v48:64-v96:" 549 "128-v192:256-v256:256-v512:512-v1024:1024-v2048:2048-n32:64-S32-A5-" 550 "G1-ni:7:8:9"; 551 } 552 553 LLVM_READNONE 554 static StringRef getGPUOrDefault(const Triple &TT, StringRef GPU) { 555 if (!GPU.empty()) 556 return GPU; 557 558 // Need to default to a target with flat support for HSA. 559 if (TT.getArch() == Triple::amdgcn) 560 return TT.getOS() == Triple::AMDHSA ? "generic-hsa" : "generic"; 561 562 return "r600"; 563 } 564 565 static Reloc::Model getEffectiveRelocModel(std::optional<Reloc::Model> RM) { 566 // The AMDGPU toolchain only supports generating shared objects, so we 567 // must always use PIC. 568 return Reloc::PIC_; 569 } 570 571 AMDGPUTargetMachine::AMDGPUTargetMachine(const Target &T, const Triple &TT, 572 StringRef CPU, StringRef FS, 573 TargetOptions Options, 574 std::optional<Reloc::Model> RM, 575 std::optional<CodeModel::Model> CM, 576 CodeGenOptLevel OptLevel) 577 : LLVMTargetMachine(T, computeDataLayout(TT), TT, getGPUOrDefault(TT, CPU), 578 FS, Options, getEffectiveRelocModel(RM), 579 getEffectiveCodeModel(CM, CodeModel::Small), OptLevel), 580 TLOF(createTLOF(getTargetTriple())) { 581 initAsmInfo(); 582 if (TT.getArch() == Triple::amdgcn) { 583 if (getMCSubtargetInfo()->checkFeatures("+wavefrontsize64")) 584 MRI.reset(llvm::createGCNMCRegisterInfo(AMDGPUDwarfFlavour::Wave64)); 585 else if (getMCSubtargetInfo()->checkFeatures("+wavefrontsize32")) 586 MRI.reset(llvm::createGCNMCRegisterInfo(AMDGPUDwarfFlavour::Wave32)); 587 } 588 } 589 590 bool AMDGPUTargetMachine::EnableLateStructurizeCFG = false; 591 bool AMDGPUTargetMachine::EnableFunctionCalls = false; 592 bool AMDGPUTargetMachine::EnableLowerModuleLDS = true; 593 594 AMDGPUTargetMachine::~AMDGPUTargetMachine() = default; 595 596 StringRef AMDGPUTargetMachine::getGPUName(const Function &F) const { 597 Attribute GPUAttr = F.getFnAttribute("target-cpu"); 598 return GPUAttr.isValid() ? GPUAttr.getValueAsString() : getTargetCPU(); 599 } 600 601 StringRef AMDGPUTargetMachine::getFeatureString(const Function &F) const { 602 Attribute FSAttr = F.getFnAttribute("target-features"); 603 604 return FSAttr.isValid() ? FSAttr.getValueAsString() 605 : getTargetFeatureString(); 606 } 607 608 /// Predicate for Internalize pass. 609 static bool mustPreserveGV(const GlobalValue &GV) { 610 if (const Function *F = dyn_cast<Function>(&GV)) 611 return F->isDeclaration() || F->getName().starts_with("__asan_") || 612 F->getName().starts_with("__sanitizer_") || 613 AMDGPU::isEntryFunctionCC(F->getCallingConv()); 614 615 GV.removeDeadConstantUsers(); 616 return !GV.use_empty(); 617 } 618 619 void AMDGPUTargetMachine::registerDefaultAliasAnalyses(AAManager &AAM) { 620 AAM.registerFunctionAnalysis<AMDGPUAA>(); 621 } 622 623 void AMDGPUTargetMachine::registerPassBuilderCallbacks(PassBuilder &PB) { 624 PB.registerPipelineParsingCallback( 625 [this](StringRef PassName, ModulePassManager &PM, 626 ArrayRef<PassBuilder::PipelineElement>) { 627 if (PassName == "amdgpu-attributor") { 628 PM.addPass(AMDGPUAttributorPass(*this)); 629 return true; 630 } 631 if (PassName == "amdgpu-unify-metadata") { 632 PM.addPass(AMDGPUUnifyMetadataPass()); 633 return true; 634 } 635 if (PassName == "amdgpu-printf-runtime-binding") { 636 PM.addPass(AMDGPUPrintfRuntimeBindingPass()); 637 return true; 638 } 639 if (PassName == "amdgpu-always-inline") { 640 PM.addPass(AMDGPUAlwaysInlinePass()); 641 return true; 642 } 643 if (PassName == "amdgpu-lower-module-lds") { 644 PM.addPass(AMDGPULowerModuleLDSPass(*this)); 645 return true; 646 } 647 if (PassName == "amdgpu-lower-ctor-dtor") { 648 PM.addPass(AMDGPUCtorDtorLoweringPass()); 649 return true; 650 } 651 return false; 652 }); 653 PB.registerPipelineParsingCallback( 654 [this](StringRef PassName, FunctionPassManager &PM, 655 ArrayRef<PassBuilder::PipelineElement>) { 656 if (PassName == "amdgpu-simplifylib") { 657 PM.addPass(AMDGPUSimplifyLibCallsPass()); 658 return true; 659 } 660 if (PassName == "amdgpu-image-intrinsic-opt") { 661 PM.addPass(AMDGPUImageIntrinsicOptimizerPass(*this)); 662 return true; 663 } 664 if (PassName == "amdgpu-usenative") { 665 PM.addPass(AMDGPUUseNativeCallsPass()); 666 return true; 667 } 668 if (PassName == "amdgpu-promote-alloca") { 669 PM.addPass(AMDGPUPromoteAllocaPass(*this)); 670 return true; 671 } 672 if (PassName == "amdgpu-promote-alloca-to-vector") { 673 PM.addPass(AMDGPUPromoteAllocaToVectorPass(*this)); 674 return true; 675 } 676 if (PassName == "amdgpu-lower-kernel-attributes") { 677 PM.addPass(AMDGPULowerKernelAttributesPass()); 678 return true; 679 } 680 if (PassName == "amdgpu-promote-kernel-arguments") { 681 PM.addPass(AMDGPUPromoteKernelArgumentsPass()); 682 return true; 683 } 684 if (PassName == "amdgpu-unify-divergent-exit-nodes") { 685 PM.addPass(AMDGPUUnifyDivergentExitNodesPass()); 686 return true; 687 } 688 if (PassName == "amdgpu-atomic-optimizer") { 689 PM.addPass( 690 AMDGPUAtomicOptimizerPass(*this, AMDGPUAtomicOptimizerStrategy)); 691 return true; 692 } 693 if (PassName == "amdgpu-codegenprepare") { 694 PM.addPass(AMDGPUCodeGenPreparePass(*this)); 695 return true; 696 } 697 if (PassName == "amdgpu-lower-kernel-arguments") { 698 PM.addPass(AMDGPULowerKernelArgumentsPass(*this)); 699 return true; 700 } 701 if (PassName == "amdgpu-rewrite-undef-for-phi") { 702 PM.addPass(AMDGPURewriteUndefForPHIPass()); 703 return true; 704 } 705 return false; 706 }); 707 708 PB.registerAnalysisRegistrationCallback([](FunctionAnalysisManager &FAM) { 709 FAM.registerPass([&] { return AMDGPUAA(); }); 710 }); 711 712 PB.registerParseAACallback([](StringRef AAName, AAManager &AAM) { 713 if (AAName == "amdgpu-aa") { 714 AAM.registerFunctionAnalysis<AMDGPUAA>(); 715 return true; 716 } 717 return false; 718 }); 719 720 PB.registerPipelineStartEPCallback( 721 [](ModulePassManager &PM, OptimizationLevel Level) { 722 FunctionPassManager FPM; 723 FPM.addPass(AMDGPUUseNativeCallsPass()); 724 if (EnableLibCallSimplify && Level != OptimizationLevel::O0) 725 FPM.addPass(AMDGPUSimplifyLibCallsPass()); 726 PM.addPass(createModuleToFunctionPassAdaptor(std::move(FPM))); 727 if (EnableHipStdPar) 728 PM.addPass(HipStdParAcceleratorCodeSelectionPass()); 729 }); 730 731 PB.registerPipelineEarlySimplificationEPCallback( 732 [](ModulePassManager &PM, OptimizationLevel Level) { 733 PM.addPass(AMDGPUPrintfRuntimeBindingPass()); 734 735 if (Level == OptimizationLevel::O0) 736 return; 737 738 PM.addPass(AMDGPUUnifyMetadataPass()); 739 740 if (InternalizeSymbols) { 741 PM.addPass(InternalizePass(mustPreserveGV)); 742 PM.addPass(GlobalDCEPass()); 743 } 744 745 if (EarlyInlineAll && !EnableFunctionCalls) 746 PM.addPass(AMDGPUAlwaysInlinePass()); 747 }); 748 749 PB.registerCGSCCOptimizerLateEPCallback( 750 [this](CGSCCPassManager &PM, OptimizationLevel Level) { 751 if (Level == OptimizationLevel::O0) 752 return; 753 754 FunctionPassManager FPM; 755 756 // Add promote kernel arguments pass to the opt pipeline right before 757 // infer address spaces which is needed to do actual address space 758 // rewriting. 759 if (Level.getSpeedupLevel() > OptimizationLevel::O1.getSpeedupLevel() && 760 EnablePromoteKernelArguments) 761 FPM.addPass(AMDGPUPromoteKernelArgumentsPass()); 762 763 // Add infer address spaces pass to the opt pipeline after inlining 764 // but before SROA to increase SROA opportunities. 765 FPM.addPass(InferAddressSpacesPass()); 766 767 // This should run after inlining to have any chance of doing 768 // anything, and before other cleanup optimizations. 769 FPM.addPass(AMDGPULowerKernelAttributesPass()); 770 771 if (Level != OptimizationLevel::O0) { 772 // Promote alloca to vector before SROA and loop unroll. If we 773 // manage to eliminate allocas before unroll we may choose to unroll 774 // less. 775 FPM.addPass(AMDGPUPromoteAllocaToVectorPass(*this)); 776 } 777 778 PM.addPass(createCGSCCToFunctionPassAdaptor(std::move(FPM))); 779 }); 780 } 781 782 int64_t AMDGPUTargetMachine::getNullPointerValue(unsigned AddrSpace) { 783 return (AddrSpace == AMDGPUAS::LOCAL_ADDRESS || 784 AddrSpace == AMDGPUAS::PRIVATE_ADDRESS || 785 AddrSpace == AMDGPUAS::REGION_ADDRESS) 786 ? -1 787 : 0; 788 } 789 790 bool AMDGPUTargetMachine::isNoopAddrSpaceCast(unsigned SrcAS, 791 unsigned DestAS) const { 792 return AMDGPU::isFlatGlobalAddrSpace(SrcAS) && 793 AMDGPU::isFlatGlobalAddrSpace(DestAS); 794 } 795 796 unsigned AMDGPUTargetMachine::getAssumedAddrSpace(const Value *V) const { 797 const auto *LD = dyn_cast<LoadInst>(V); 798 if (!LD) 799 return AMDGPUAS::UNKNOWN_ADDRESS_SPACE; 800 801 // It must be a generic pointer loaded. 802 assert(V->getType()->isPointerTy() && 803 V->getType()->getPointerAddressSpace() == AMDGPUAS::FLAT_ADDRESS); 804 805 const auto *Ptr = LD->getPointerOperand(); 806 if (Ptr->getType()->getPointerAddressSpace() != AMDGPUAS::CONSTANT_ADDRESS) 807 return AMDGPUAS::UNKNOWN_ADDRESS_SPACE; 808 // For a generic pointer loaded from the constant memory, it could be assumed 809 // as a global pointer since the constant memory is only populated on the 810 // host side. As implied by the offload programming model, only global 811 // pointers could be referenced on the host side. 812 return AMDGPUAS::GLOBAL_ADDRESS; 813 } 814 815 std::pair<const Value *, unsigned> 816 AMDGPUTargetMachine::getPredicatedAddrSpace(const Value *V) const { 817 if (auto *II = dyn_cast<IntrinsicInst>(V)) { 818 switch (II->getIntrinsicID()) { 819 case Intrinsic::amdgcn_is_shared: 820 return std::pair(II->getArgOperand(0), AMDGPUAS::LOCAL_ADDRESS); 821 case Intrinsic::amdgcn_is_private: 822 return std::pair(II->getArgOperand(0), AMDGPUAS::PRIVATE_ADDRESS); 823 default: 824 break; 825 } 826 return std::pair(nullptr, -1); 827 } 828 // Check the global pointer predication based on 829 // (!is_share(p) && !is_private(p)). Note that logic 'and' is commutative and 830 // the order of 'is_shared' and 'is_private' is not significant. 831 Value *Ptr; 832 if (match( 833 const_cast<Value *>(V), 834 m_c_And(m_Not(m_Intrinsic<Intrinsic::amdgcn_is_shared>(m_Value(Ptr))), 835 m_Not(m_Intrinsic<Intrinsic::amdgcn_is_private>( 836 m_Deferred(Ptr)))))) 837 return std::pair(Ptr, AMDGPUAS::GLOBAL_ADDRESS); 838 839 return std::pair(nullptr, -1); 840 } 841 842 unsigned 843 AMDGPUTargetMachine::getAddressSpaceForPseudoSourceKind(unsigned Kind) const { 844 switch (Kind) { 845 case PseudoSourceValue::Stack: 846 case PseudoSourceValue::FixedStack: 847 return AMDGPUAS::PRIVATE_ADDRESS; 848 case PseudoSourceValue::ConstantPool: 849 case PseudoSourceValue::GOT: 850 case PseudoSourceValue::JumpTable: 851 case PseudoSourceValue::GlobalValueCallEntry: 852 case PseudoSourceValue::ExternalSymbolCallEntry: 853 return AMDGPUAS::CONSTANT_ADDRESS; 854 } 855 return AMDGPUAS::FLAT_ADDRESS; 856 } 857 858 //===----------------------------------------------------------------------===// 859 // GCN Target Machine (SI+) 860 //===----------------------------------------------------------------------===// 861 862 GCNTargetMachine::GCNTargetMachine(const Target &T, const Triple &TT, 863 StringRef CPU, StringRef FS, 864 TargetOptions Options, 865 std::optional<Reloc::Model> RM, 866 std::optional<CodeModel::Model> CM, 867 CodeGenOptLevel OL, bool JIT) 868 : AMDGPUTargetMachine(T, TT, CPU, FS, Options, RM, CM, OL) {} 869 870 const TargetSubtargetInfo * 871 GCNTargetMachine::getSubtargetImpl(const Function &F) const { 872 StringRef GPU = getGPUName(F); 873 StringRef FS = getFeatureString(F); 874 875 SmallString<128> SubtargetKey(GPU); 876 SubtargetKey.append(FS); 877 878 auto &I = SubtargetMap[SubtargetKey]; 879 if (!I) { 880 // This needs to be done before we create a new subtarget since any 881 // creation will depend on the TM and the code generation flags on the 882 // function that reside in TargetOptions. 883 resetTargetOptions(F); 884 I = std::make_unique<GCNSubtarget>(TargetTriple, GPU, FS, *this); 885 } 886 887 I->setScalarizeGlobalBehavior(ScalarizeGlobal); 888 889 return I.get(); 890 } 891 892 TargetTransformInfo 893 GCNTargetMachine::getTargetTransformInfo(const Function &F) const { 894 return TargetTransformInfo(GCNTTIImpl(this, F)); 895 } 896 897 //===----------------------------------------------------------------------===// 898 // AMDGPU Pass Setup 899 //===----------------------------------------------------------------------===// 900 901 std::unique_ptr<CSEConfigBase> llvm::AMDGPUPassConfig::getCSEConfig() const { 902 return getStandardCSEConfigForOpt(TM->getOptLevel()); 903 } 904 905 namespace { 906 907 class GCNPassConfig final : public AMDGPUPassConfig { 908 public: 909 GCNPassConfig(LLVMTargetMachine &TM, PassManagerBase &PM) 910 : AMDGPUPassConfig(TM, PM) { 911 // It is necessary to know the register usage of the entire call graph. We 912 // allow calls without EnableAMDGPUFunctionCalls if they are marked 913 // noinline, so this is always required. 914 setRequiresCodeGenSCCOrder(true); 915 substitutePass(&PostRASchedulerID, &PostMachineSchedulerID); 916 } 917 918 GCNTargetMachine &getGCNTargetMachine() const { 919 return getTM<GCNTargetMachine>(); 920 } 921 922 ScheduleDAGInstrs * 923 createMachineScheduler(MachineSchedContext *C) const override; 924 925 ScheduleDAGInstrs * 926 createPostMachineScheduler(MachineSchedContext *C) const override { 927 ScheduleDAGMI *DAG = new GCNPostScheduleDAGMILive( 928 C, std::make_unique<PostGenericScheduler>(C), 929 /*RemoveKillFlags=*/true); 930 const GCNSubtarget &ST = C->MF->getSubtarget<GCNSubtarget>(); 931 DAG->addMutation(createLoadClusterDAGMutation(DAG->TII, DAG->TRI)); 932 if (ST.shouldClusterStores()) 933 DAG->addMutation(createStoreClusterDAGMutation(DAG->TII, DAG->TRI)); 934 DAG->addMutation(ST.createFillMFMAShadowMutation(DAG->TII)); 935 DAG->addMutation(createIGroupLPDAGMutation(/*IsPostRA=*/true)); 936 if (isPassEnabled(EnableVOPD, CodeGenOptLevel::Less)) 937 DAG->addMutation(createVOPDPairingMutation()); 938 return DAG; 939 } 940 941 bool addPreISel() override; 942 void addMachineSSAOptimization() override; 943 bool addILPOpts() override; 944 bool addInstSelector() override; 945 bool addIRTranslator() override; 946 void addPreLegalizeMachineIR() override; 947 bool addLegalizeMachineIR() override; 948 void addPreRegBankSelect() override; 949 bool addRegBankSelect() override; 950 void addPreGlobalInstructionSelect() override; 951 bool addGlobalInstructionSelect() override; 952 void addFastRegAlloc() override; 953 void addOptimizedRegAlloc() override; 954 955 FunctionPass *createSGPRAllocPass(bool Optimized); 956 FunctionPass *createVGPRAllocPass(bool Optimized); 957 FunctionPass *createRegAllocPass(bool Optimized) override; 958 959 bool addRegAssignAndRewriteFast() override; 960 bool addRegAssignAndRewriteOptimized() override; 961 962 void addPreRegAlloc() override; 963 bool addPreRewrite() override; 964 void addPostRegAlloc() override; 965 void addPreSched2() override; 966 void addPreEmitPass() override; 967 }; 968 969 } // end anonymous namespace 970 971 AMDGPUPassConfig::AMDGPUPassConfig(LLVMTargetMachine &TM, PassManagerBase &PM) 972 : TargetPassConfig(TM, PM) { 973 // Exceptions and StackMaps are not supported, so these passes will never do 974 // anything. 975 disablePass(&StackMapLivenessID); 976 disablePass(&FuncletLayoutID); 977 // Garbage collection is not supported. 978 disablePass(&GCLoweringID); 979 disablePass(&ShadowStackGCLoweringID); 980 } 981 982 void AMDGPUPassConfig::addEarlyCSEOrGVNPass() { 983 if (getOptLevel() == CodeGenOptLevel::Aggressive) 984 addPass(createGVNPass()); 985 else 986 addPass(createEarlyCSEPass()); 987 } 988 989 void AMDGPUPassConfig::addStraightLineScalarOptimizationPasses() { 990 if (isPassEnabled(EnableLoopPrefetch, CodeGenOptLevel::Aggressive)) 991 addPass(createLoopDataPrefetchPass()); 992 addPass(createSeparateConstOffsetFromGEPPass()); 993 // ReassociateGEPs exposes more opportunities for SLSR. See 994 // the example in reassociate-geps-and-slsr.ll. 995 addPass(createStraightLineStrengthReducePass()); 996 // SeparateConstOffsetFromGEP and SLSR creates common expressions which GVN or 997 // EarlyCSE can reuse. 998 addEarlyCSEOrGVNPass(); 999 // Run NaryReassociate after EarlyCSE/GVN to be more effective. 1000 addPass(createNaryReassociatePass()); 1001 // NaryReassociate on GEPs creates redundant common expressions, so run 1002 // EarlyCSE after it. 1003 addPass(createEarlyCSEPass()); 1004 } 1005 1006 void AMDGPUPassConfig::addIRPasses() { 1007 const AMDGPUTargetMachine &TM = getAMDGPUTargetMachine(); 1008 1009 Triple::ArchType Arch = TM.getTargetTriple().getArch(); 1010 if (RemoveIncompatibleFunctions && Arch == Triple::amdgcn) 1011 addPass(createAMDGPURemoveIncompatibleFunctionsPass(&TM)); 1012 1013 // There is no reason to run these. 1014 disablePass(&StackMapLivenessID); 1015 disablePass(&FuncletLayoutID); 1016 disablePass(&PatchableFunctionID); 1017 1018 addPass(createAMDGPUPrintfRuntimeBinding()); 1019 if (LowerCtorDtor) 1020 addPass(createAMDGPUCtorDtorLoweringLegacyPass()); 1021 1022 if (isPassEnabled(EnableImageIntrinsicOptimizer)) 1023 addPass(createAMDGPUImageIntrinsicOptimizerPass(&TM)); 1024 1025 // Function calls are not supported, so make sure we inline everything. 1026 addPass(createAMDGPUAlwaysInlinePass()); 1027 addPass(createAlwaysInlinerLegacyPass()); 1028 1029 // Handle uses of OpenCL image2d_t, image3d_t and sampler_t arguments. 1030 if (Arch == Triple::r600) 1031 addPass(createR600OpenCLImageTypeLoweringPass()); 1032 1033 // Replace OpenCL enqueued block function pointers with global variables. 1034 addPass(createAMDGPUOpenCLEnqueuedBlockLoweringPass()); 1035 1036 // Runs before PromoteAlloca so the latter can account for function uses 1037 if (EnableLowerModuleLDS) { 1038 addPass(createAMDGPULowerModuleLDSLegacyPass(&TM)); 1039 } 1040 1041 // AMDGPUAttributor infers lack of llvm.amdgcn.lds.kernel.id calls, so run 1042 // after their introduction 1043 if (TM.getOptLevel() > CodeGenOptLevel::None) 1044 addPass(createAMDGPUAttributorLegacyPass()); 1045 1046 if (TM.getOptLevel() > CodeGenOptLevel::None) 1047 addPass(createInferAddressSpacesPass()); 1048 1049 // Run atomic optimizer before Atomic Expand 1050 if ((TM.getTargetTriple().getArch() == Triple::amdgcn) && 1051 (TM.getOptLevel() >= CodeGenOptLevel::Less) && 1052 (AMDGPUAtomicOptimizerStrategy != ScanOptions::None)) { 1053 addPass(createAMDGPUAtomicOptimizerPass(AMDGPUAtomicOptimizerStrategy)); 1054 } 1055 1056 addPass(createAtomicExpandPass()); 1057 1058 if (TM.getOptLevel() > CodeGenOptLevel::None) { 1059 addPass(createAMDGPUPromoteAlloca()); 1060 1061 if (isPassEnabled(EnableScalarIRPasses)) 1062 addStraightLineScalarOptimizationPasses(); 1063 1064 if (EnableAMDGPUAliasAnalysis) { 1065 addPass(createAMDGPUAAWrapperPass()); 1066 addPass(createExternalAAWrapperPass([](Pass &P, Function &, 1067 AAResults &AAR) { 1068 if (auto *WrapperPass = P.getAnalysisIfAvailable<AMDGPUAAWrapperPass>()) 1069 AAR.addAAResult(WrapperPass->getResult()); 1070 })); 1071 } 1072 1073 if (TM.getTargetTriple().getArch() == Triple::amdgcn) { 1074 // TODO: May want to move later or split into an early and late one. 1075 addPass(createAMDGPUCodeGenPreparePass()); 1076 } 1077 1078 // Try to hoist loop invariant parts of divisions AMDGPUCodeGenPrepare may 1079 // have expanded. 1080 if (TM.getOptLevel() > CodeGenOptLevel::Less) 1081 addPass(createLICMPass()); 1082 } 1083 1084 TargetPassConfig::addIRPasses(); 1085 1086 // EarlyCSE is not always strong enough to clean up what LSR produces. For 1087 // example, GVN can combine 1088 // 1089 // %0 = add %a, %b 1090 // %1 = add %b, %a 1091 // 1092 // and 1093 // 1094 // %0 = shl nsw %a, 2 1095 // %1 = shl %a, 2 1096 // 1097 // but EarlyCSE can do neither of them. 1098 if (isPassEnabled(EnableScalarIRPasses)) 1099 addEarlyCSEOrGVNPass(); 1100 } 1101 1102 void AMDGPUPassConfig::addCodeGenPrepare() { 1103 if (TM->getTargetTriple().getArch() == Triple::amdgcn) { 1104 // FIXME: This pass adds 2 hacky attributes that can be replaced with an 1105 // analysis, and should be removed. 1106 addPass(createAMDGPUAnnotateKernelFeaturesPass()); 1107 } 1108 1109 if (TM->getTargetTriple().getArch() == Triple::amdgcn && 1110 EnableLowerKernelArguments) 1111 addPass(createAMDGPULowerKernelArgumentsPass()); 1112 1113 TargetPassConfig::addCodeGenPrepare(); 1114 1115 if (isPassEnabled(EnableLoadStoreVectorizer)) 1116 addPass(createLoadStoreVectorizerPass()); 1117 1118 // LowerSwitch pass may introduce unreachable blocks that can 1119 // cause unexpected behavior for subsequent passes. Placing it 1120 // here seems better that these blocks would get cleaned up by 1121 // UnreachableBlockElim inserted next in the pass flow. 1122 addPass(createLowerSwitchPass()); 1123 } 1124 1125 bool AMDGPUPassConfig::addPreISel() { 1126 if (TM->getOptLevel() > CodeGenOptLevel::None) 1127 addPass(createFlattenCFGPass()); 1128 return false; 1129 } 1130 1131 bool AMDGPUPassConfig::addInstSelector() { 1132 addPass(createAMDGPUISelDag(getAMDGPUTargetMachine(), getOptLevel())); 1133 return false; 1134 } 1135 1136 bool AMDGPUPassConfig::addGCPasses() { 1137 // Do nothing. GC is not supported. 1138 return false; 1139 } 1140 1141 llvm::ScheduleDAGInstrs * 1142 AMDGPUPassConfig::createMachineScheduler(MachineSchedContext *C) const { 1143 const GCNSubtarget &ST = C->MF->getSubtarget<GCNSubtarget>(); 1144 ScheduleDAGMILive *DAG = createGenericSchedLive(C); 1145 DAG->addMutation(createLoadClusterDAGMutation(DAG->TII, DAG->TRI)); 1146 if (ST.shouldClusterStores()) 1147 DAG->addMutation(createStoreClusterDAGMutation(DAG->TII, DAG->TRI)); 1148 return DAG; 1149 } 1150 1151 MachineFunctionInfo *R600TargetMachine::createMachineFunctionInfo( 1152 BumpPtrAllocator &Allocator, const Function &F, 1153 const TargetSubtargetInfo *STI) const { 1154 return R600MachineFunctionInfo::create<R600MachineFunctionInfo>( 1155 Allocator, F, static_cast<const R600Subtarget *>(STI)); 1156 } 1157 1158 //===----------------------------------------------------------------------===// 1159 // GCN Pass Setup 1160 //===----------------------------------------------------------------------===// 1161 1162 ScheduleDAGInstrs *GCNPassConfig::createMachineScheduler( 1163 MachineSchedContext *C) const { 1164 const GCNSubtarget &ST = C->MF->getSubtarget<GCNSubtarget>(); 1165 if (ST.enableSIScheduler()) 1166 return createSIMachineScheduler(C); 1167 1168 if (EnableMaxIlpSchedStrategy) 1169 return createGCNMaxILPMachineScheduler(C); 1170 1171 return createGCNMaxOccupancyMachineScheduler(C); 1172 } 1173 1174 bool GCNPassConfig::addPreISel() { 1175 AMDGPUPassConfig::addPreISel(); 1176 1177 if (TM->getOptLevel() > CodeGenOptLevel::None) 1178 addPass(createAMDGPULateCodeGenPreparePass()); 1179 1180 if (TM->getOptLevel() > CodeGenOptLevel::None) 1181 addPass(createSinkingPass()); 1182 1183 // Merge divergent exit nodes. StructurizeCFG won't recognize the multi-exit 1184 // regions formed by them. 1185 addPass(&AMDGPUUnifyDivergentExitNodesID); 1186 if (!LateCFGStructurize) { 1187 if (EnableStructurizerWorkarounds) { 1188 addPass(createFixIrreduciblePass()); 1189 addPass(createUnifyLoopExitsPass()); 1190 } 1191 addPass(createStructurizeCFGPass(false)); // true -> SkipUniformRegions 1192 } 1193 addPass(createAMDGPUAnnotateUniformValues()); 1194 if (!LateCFGStructurize) { 1195 addPass(createSIAnnotateControlFlowPass()); 1196 // TODO: Move this right after structurizeCFG to avoid extra divergence 1197 // analysis. This depends on stopping SIAnnotateControlFlow from making 1198 // control flow modifications. 1199 addPass(createAMDGPURewriteUndefForPHILegacyPass()); 1200 } 1201 addPass(createLCSSAPass()); 1202 1203 if (TM->getOptLevel() > CodeGenOptLevel::Less) 1204 addPass(&AMDGPUPerfHintAnalysisID); 1205 1206 return false; 1207 } 1208 1209 void GCNPassConfig::addMachineSSAOptimization() { 1210 TargetPassConfig::addMachineSSAOptimization(); 1211 1212 // We want to fold operands after PeepholeOptimizer has run (or as part of 1213 // it), because it will eliminate extra copies making it easier to fold the 1214 // real source operand. We want to eliminate dead instructions after, so that 1215 // we see fewer uses of the copies. We then need to clean up the dead 1216 // instructions leftover after the operands are folded as well. 1217 // 1218 // XXX - Can we get away without running DeadMachineInstructionElim again? 1219 addPass(&SIFoldOperandsID); 1220 if (EnableDPPCombine) 1221 addPass(&GCNDPPCombineID); 1222 addPass(&SILoadStoreOptimizerID); 1223 if (isPassEnabled(EnableSDWAPeephole)) { 1224 addPass(&SIPeepholeSDWAID); 1225 addPass(&EarlyMachineLICMID); 1226 addPass(&MachineCSEID); 1227 addPass(&SIFoldOperandsID); 1228 } 1229 addPass(&DeadMachineInstructionElimID); 1230 addPass(createSIShrinkInstructionsPass()); 1231 } 1232 1233 bool GCNPassConfig::addILPOpts() { 1234 if (EnableEarlyIfConversion) 1235 addPass(&EarlyIfConverterID); 1236 1237 TargetPassConfig::addILPOpts(); 1238 return false; 1239 } 1240 1241 bool GCNPassConfig::addInstSelector() { 1242 AMDGPUPassConfig::addInstSelector(); 1243 addPass(&SIFixSGPRCopiesID); 1244 addPass(createSILowerI1CopiesPass()); 1245 return false; 1246 } 1247 1248 bool GCNPassConfig::addIRTranslator() { 1249 addPass(new IRTranslator(getOptLevel())); 1250 return false; 1251 } 1252 1253 void GCNPassConfig::addPreLegalizeMachineIR() { 1254 bool IsOptNone = getOptLevel() == CodeGenOptLevel::None; 1255 addPass(createAMDGPUPreLegalizeCombiner(IsOptNone)); 1256 addPass(new Localizer()); 1257 } 1258 1259 bool GCNPassConfig::addLegalizeMachineIR() { 1260 addPass(new Legalizer()); 1261 return false; 1262 } 1263 1264 void GCNPassConfig::addPreRegBankSelect() { 1265 bool IsOptNone = getOptLevel() == CodeGenOptLevel::None; 1266 addPass(createAMDGPUPostLegalizeCombiner(IsOptNone)); 1267 addPass(createAMDGPUGlobalISelDivergenceLoweringPass()); 1268 } 1269 1270 bool GCNPassConfig::addRegBankSelect() { 1271 addPass(new AMDGPURegBankSelect()); 1272 return false; 1273 } 1274 1275 void GCNPassConfig::addPreGlobalInstructionSelect() { 1276 bool IsOptNone = getOptLevel() == CodeGenOptLevel::None; 1277 addPass(createAMDGPURegBankCombiner(IsOptNone)); 1278 } 1279 1280 bool GCNPassConfig::addGlobalInstructionSelect() { 1281 addPass(new InstructionSelect(getOptLevel())); 1282 return false; 1283 } 1284 1285 void GCNPassConfig::addPreRegAlloc() { 1286 if (LateCFGStructurize) { 1287 addPass(createAMDGPUMachineCFGStructurizerPass()); 1288 } 1289 } 1290 1291 void GCNPassConfig::addFastRegAlloc() { 1292 // FIXME: We have to disable the verifier here because of PHIElimination + 1293 // TwoAddressInstructions disabling it. 1294 1295 // This must be run immediately after phi elimination and before 1296 // TwoAddressInstructions, otherwise the processing of the tied operand of 1297 // SI_ELSE will introduce a copy of the tied operand source after the else. 1298 insertPass(&PHIEliminationID, &SILowerControlFlowID); 1299 1300 insertPass(&TwoAddressInstructionPassID, &SIWholeQuadModeID); 1301 1302 TargetPassConfig::addFastRegAlloc(); 1303 } 1304 1305 void GCNPassConfig::addOptimizedRegAlloc() { 1306 // Allow the scheduler to run before SIWholeQuadMode inserts exec manipulation 1307 // instructions that cause scheduling barriers. 1308 insertPass(&MachineSchedulerID, &SIWholeQuadModeID); 1309 1310 if (OptExecMaskPreRA) 1311 insertPass(&MachineSchedulerID, &SIOptimizeExecMaskingPreRAID); 1312 1313 if (EnableRewritePartialRegUses) 1314 insertPass(&RenameIndependentSubregsID, &GCNRewritePartialRegUsesID); 1315 1316 if (isPassEnabled(EnablePreRAOptimizations)) 1317 insertPass(&RenameIndependentSubregsID, &GCNPreRAOptimizationsID); 1318 1319 // This is not an essential optimization and it has a noticeable impact on 1320 // compilation time, so we only enable it from O2. 1321 if (TM->getOptLevel() > CodeGenOptLevel::Less) 1322 insertPass(&MachineSchedulerID, &SIFormMemoryClausesID); 1323 1324 // FIXME: when an instruction has a Killed operand, and the instruction is 1325 // inside a bundle, seems only the BUNDLE instruction appears as the Kills of 1326 // the register in LiveVariables, this would trigger a failure in verifier, 1327 // we should fix it and enable the verifier. 1328 if (OptVGPRLiveRange) 1329 insertPass(&LiveVariablesID, &SIOptimizeVGPRLiveRangeID); 1330 // This must be run immediately after phi elimination and before 1331 // TwoAddressInstructions, otherwise the processing of the tied operand of 1332 // SI_ELSE will introduce a copy of the tied operand source after the else. 1333 insertPass(&PHIEliminationID, &SILowerControlFlowID); 1334 1335 if (EnableDCEInRA) 1336 insertPass(&DetectDeadLanesID, &DeadMachineInstructionElimID); 1337 1338 TargetPassConfig::addOptimizedRegAlloc(); 1339 } 1340 1341 bool GCNPassConfig::addPreRewrite() { 1342 addPass(&SILowerWWMCopiesID); 1343 if (EnableRegReassign) 1344 addPass(&GCNNSAReassignID); 1345 return true; 1346 } 1347 1348 FunctionPass *GCNPassConfig::createSGPRAllocPass(bool Optimized) { 1349 // Initialize the global default. 1350 llvm::call_once(InitializeDefaultSGPRRegisterAllocatorFlag, 1351 initializeDefaultSGPRRegisterAllocatorOnce); 1352 1353 RegisterRegAlloc::FunctionPassCtor Ctor = SGPRRegisterRegAlloc::getDefault(); 1354 if (Ctor != useDefaultRegisterAllocator) 1355 return Ctor(); 1356 1357 if (Optimized) 1358 return createGreedyRegisterAllocator(onlyAllocateSGPRs); 1359 1360 return createFastRegisterAllocator(onlyAllocateSGPRs, false); 1361 } 1362 1363 FunctionPass *GCNPassConfig::createVGPRAllocPass(bool Optimized) { 1364 // Initialize the global default. 1365 llvm::call_once(InitializeDefaultVGPRRegisterAllocatorFlag, 1366 initializeDefaultVGPRRegisterAllocatorOnce); 1367 1368 RegisterRegAlloc::FunctionPassCtor Ctor = VGPRRegisterRegAlloc::getDefault(); 1369 if (Ctor != useDefaultRegisterAllocator) 1370 return Ctor(); 1371 1372 if (Optimized) 1373 return createGreedyVGPRRegisterAllocator(); 1374 1375 return createFastVGPRRegisterAllocator(); 1376 } 1377 1378 FunctionPass *GCNPassConfig::createRegAllocPass(bool Optimized) { 1379 llvm_unreachable("should not be used"); 1380 } 1381 1382 static const char RegAllocOptNotSupportedMessage[] = 1383 "-regalloc not supported with amdgcn. Use -sgpr-regalloc and -vgpr-regalloc"; 1384 1385 bool GCNPassConfig::addRegAssignAndRewriteFast() { 1386 if (!usingDefaultRegAlloc()) 1387 report_fatal_error(RegAllocOptNotSupportedMessage); 1388 1389 addPass(&GCNPreRALongBranchRegID); 1390 1391 addPass(createSGPRAllocPass(false)); 1392 1393 // Equivalent of PEI for SGPRs. 1394 addPass(&SILowerSGPRSpillsID); 1395 addPass(&SIPreAllocateWWMRegsID); 1396 1397 addPass(createVGPRAllocPass(false)); 1398 1399 addPass(&SILowerWWMCopiesID); 1400 return true; 1401 } 1402 1403 bool GCNPassConfig::addRegAssignAndRewriteOptimized() { 1404 if (!usingDefaultRegAlloc()) 1405 report_fatal_error(RegAllocOptNotSupportedMessage); 1406 1407 addPass(&GCNPreRALongBranchRegID); 1408 1409 addPass(createSGPRAllocPass(true)); 1410 1411 // Commit allocated register changes. This is mostly necessary because too 1412 // many things rely on the use lists of the physical registers, such as the 1413 // verifier. This is only necessary with allocators which use LiveIntervals, 1414 // since FastRegAlloc does the replacements itself. 1415 addPass(createVirtRegRewriter(false)); 1416 1417 // Equivalent of PEI for SGPRs. 1418 addPass(&SILowerSGPRSpillsID); 1419 addPass(&SIPreAllocateWWMRegsID); 1420 1421 addPass(createVGPRAllocPass(true)); 1422 1423 addPreRewrite(); 1424 addPass(&VirtRegRewriterID); 1425 1426 return true; 1427 } 1428 1429 void GCNPassConfig::addPostRegAlloc() { 1430 addPass(&SIFixVGPRCopiesID); 1431 if (getOptLevel() > CodeGenOptLevel::None) 1432 addPass(&SIOptimizeExecMaskingID); 1433 TargetPassConfig::addPostRegAlloc(); 1434 } 1435 1436 void GCNPassConfig::addPreSched2() { 1437 if (TM->getOptLevel() > CodeGenOptLevel::None) 1438 addPass(createSIShrinkInstructionsPass()); 1439 addPass(&SIPostRABundlerID); 1440 } 1441 1442 void GCNPassConfig::addPreEmitPass() { 1443 if (isPassEnabled(EnableVOPD, CodeGenOptLevel::Less)) 1444 addPass(&GCNCreateVOPDID); 1445 addPass(createSIMemoryLegalizerPass()); 1446 addPass(createSIInsertWaitcntsPass()); 1447 1448 addPass(createSIModeRegisterPass()); 1449 1450 if (getOptLevel() > CodeGenOptLevel::None) 1451 addPass(&SIInsertHardClausesID); 1452 1453 addPass(&SILateBranchLoweringPassID); 1454 if (isPassEnabled(EnableSetWavePriority, CodeGenOptLevel::Less)) 1455 addPass(createAMDGPUSetWavePriorityPass()); 1456 if (getOptLevel() > CodeGenOptLevel::None) 1457 addPass(&SIPreEmitPeepholeID); 1458 // The hazard recognizer that runs as part of the post-ra scheduler does not 1459 // guarantee to be able handle all hazards correctly. This is because if there 1460 // are multiple scheduling regions in a basic block, the regions are scheduled 1461 // bottom up, so when we begin to schedule a region we don't know what 1462 // instructions were emitted directly before it. 1463 // 1464 // Here we add a stand-alone hazard recognizer pass which can handle all 1465 // cases. 1466 addPass(&PostRAHazardRecognizerID); 1467 1468 if (isPassEnabled(EnableInsertSingleUseVDST, CodeGenOptLevel::Less)) 1469 addPass(&AMDGPUInsertSingleUseVDSTID); 1470 1471 if (isPassEnabled(EnableInsertDelayAlu, CodeGenOptLevel::Less)) 1472 addPass(&AMDGPUInsertDelayAluID); 1473 1474 addPass(&BranchRelaxationPassID); 1475 } 1476 1477 TargetPassConfig *GCNTargetMachine::createPassConfig(PassManagerBase &PM) { 1478 return new GCNPassConfig(*this, PM); 1479 } 1480 1481 void GCNTargetMachine::registerMachineRegisterInfoCallback( 1482 MachineFunction &MF) const { 1483 SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>(); 1484 MF.getRegInfo().addDelegate(MFI); 1485 } 1486 1487 MachineFunctionInfo *GCNTargetMachine::createMachineFunctionInfo( 1488 BumpPtrAllocator &Allocator, const Function &F, 1489 const TargetSubtargetInfo *STI) const { 1490 return SIMachineFunctionInfo::create<SIMachineFunctionInfo>( 1491 Allocator, F, static_cast<const GCNSubtarget *>(STI)); 1492 } 1493 1494 yaml::MachineFunctionInfo *GCNTargetMachine::createDefaultFuncInfoYAML() const { 1495 return new yaml::SIMachineFunctionInfo(); 1496 } 1497 1498 yaml::MachineFunctionInfo * 1499 GCNTargetMachine::convertFuncInfoToYAML(const MachineFunction &MF) const { 1500 const SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>(); 1501 return new yaml::SIMachineFunctionInfo( 1502 *MFI, *MF.getSubtarget<GCNSubtarget>().getRegisterInfo(), MF); 1503 } 1504 1505 bool GCNTargetMachine::parseMachineFunctionInfo( 1506 const yaml::MachineFunctionInfo &MFI_, PerFunctionMIParsingState &PFS, 1507 SMDiagnostic &Error, SMRange &SourceRange) const { 1508 const yaml::SIMachineFunctionInfo &YamlMFI = 1509 static_cast<const yaml::SIMachineFunctionInfo &>(MFI_); 1510 MachineFunction &MF = PFS.MF; 1511 SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>(); 1512 const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>(); 1513 1514 if (MFI->initializeBaseYamlFields(YamlMFI, MF, PFS, Error, SourceRange)) 1515 return true; 1516 1517 if (MFI->Occupancy == 0) { 1518 // Fixup the subtarget dependent default value. 1519 MFI->Occupancy = ST.computeOccupancy(MF.getFunction(), MFI->getLDSSize()); 1520 } 1521 1522 auto parseRegister = [&](const yaml::StringValue &RegName, Register &RegVal) { 1523 Register TempReg; 1524 if (parseNamedRegisterReference(PFS, TempReg, RegName.Value, Error)) { 1525 SourceRange = RegName.SourceRange; 1526 return true; 1527 } 1528 RegVal = TempReg; 1529 1530 return false; 1531 }; 1532 1533 auto parseOptionalRegister = [&](const yaml::StringValue &RegName, 1534 Register &RegVal) { 1535 return !RegName.Value.empty() && parseRegister(RegName, RegVal); 1536 }; 1537 1538 if (parseOptionalRegister(YamlMFI.VGPRForAGPRCopy, MFI->VGPRForAGPRCopy)) 1539 return true; 1540 1541 if (parseOptionalRegister(YamlMFI.SGPRForEXECCopy, MFI->SGPRForEXECCopy)) 1542 return true; 1543 1544 if (parseOptionalRegister(YamlMFI.LongBranchReservedReg, 1545 MFI->LongBranchReservedReg)) 1546 return true; 1547 1548 auto diagnoseRegisterClass = [&](const yaml::StringValue &RegName) { 1549 // Create a diagnostic for a the register string literal. 1550 const MemoryBuffer &Buffer = 1551 *PFS.SM->getMemoryBuffer(PFS.SM->getMainFileID()); 1552 Error = SMDiagnostic(*PFS.SM, SMLoc(), Buffer.getBufferIdentifier(), 1, 1553 RegName.Value.size(), SourceMgr::DK_Error, 1554 "incorrect register class for field", RegName.Value, 1555 std::nullopt, std::nullopt); 1556 SourceRange = RegName.SourceRange; 1557 return true; 1558 }; 1559 1560 if (parseRegister(YamlMFI.ScratchRSrcReg, MFI->ScratchRSrcReg) || 1561 parseRegister(YamlMFI.FrameOffsetReg, MFI->FrameOffsetReg) || 1562 parseRegister(YamlMFI.StackPtrOffsetReg, MFI->StackPtrOffsetReg)) 1563 return true; 1564 1565 if (MFI->ScratchRSrcReg != AMDGPU::PRIVATE_RSRC_REG && 1566 !AMDGPU::SGPR_128RegClass.contains(MFI->ScratchRSrcReg)) { 1567 return diagnoseRegisterClass(YamlMFI.ScratchRSrcReg); 1568 } 1569 1570 if (MFI->FrameOffsetReg != AMDGPU::FP_REG && 1571 !AMDGPU::SGPR_32RegClass.contains(MFI->FrameOffsetReg)) { 1572 return diagnoseRegisterClass(YamlMFI.FrameOffsetReg); 1573 } 1574 1575 if (MFI->StackPtrOffsetReg != AMDGPU::SP_REG && 1576 !AMDGPU::SGPR_32RegClass.contains(MFI->StackPtrOffsetReg)) { 1577 return diagnoseRegisterClass(YamlMFI.StackPtrOffsetReg); 1578 } 1579 1580 for (const auto &YamlReg : YamlMFI.WWMReservedRegs) { 1581 Register ParsedReg; 1582 if (parseRegister(YamlReg, ParsedReg)) 1583 return true; 1584 1585 MFI->reserveWWMRegister(ParsedReg); 1586 } 1587 1588 auto parseAndCheckArgument = [&](const std::optional<yaml::SIArgument> &A, 1589 const TargetRegisterClass &RC, 1590 ArgDescriptor &Arg, unsigned UserSGPRs, 1591 unsigned SystemSGPRs) { 1592 // Skip parsing if it's not present. 1593 if (!A) 1594 return false; 1595 1596 if (A->IsRegister) { 1597 Register Reg; 1598 if (parseNamedRegisterReference(PFS, Reg, A->RegisterName.Value, Error)) { 1599 SourceRange = A->RegisterName.SourceRange; 1600 return true; 1601 } 1602 if (!RC.contains(Reg)) 1603 return diagnoseRegisterClass(A->RegisterName); 1604 Arg = ArgDescriptor::createRegister(Reg); 1605 } else 1606 Arg = ArgDescriptor::createStack(A->StackOffset); 1607 // Check and apply the optional mask. 1608 if (A->Mask) 1609 Arg = ArgDescriptor::createArg(Arg, *A->Mask); 1610 1611 MFI->NumUserSGPRs += UserSGPRs; 1612 MFI->NumSystemSGPRs += SystemSGPRs; 1613 return false; 1614 }; 1615 1616 if (YamlMFI.ArgInfo && 1617 (parseAndCheckArgument(YamlMFI.ArgInfo->PrivateSegmentBuffer, 1618 AMDGPU::SGPR_128RegClass, 1619 MFI->ArgInfo.PrivateSegmentBuffer, 4, 0) || 1620 parseAndCheckArgument(YamlMFI.ArgInfo->DispatchPtr, 1621 AMDGPU::SReg_64RegClass, MFI->ArgInfo.DispatchPtr, 1622 2, 0) || 1623 parseAndCheckArgument(YamlMFI.ArgInfo->QueuePtr, AMDGPU::SReg_64RegClass, 1624 MFI->ArgInfo.QueuePtr, 2, 0) || 1625 parseAndCheckArgument(YamlMFI.ArgInfo->KernargSegmentPtr, 1626 AMDGPU::SReg_64RegClass, 1627 MFI->ArgInfo.KernargSegmentPtr, 2, 0) || 1628 parseAndCheckArgument(YamlMFI.ArgInfo->DispatchID, 1629 AMDGPU::SReg_64RegClass, MFI->ArgInfo.DispatchID, 1630 2, 0) || 1631 parseAndCheckArgument(YamlMFI.ArgInfo->FlatScratchInit, 1632 AMDGPU::SReg_64RegClass, 1633 MFI->ArgInfo.FlatScratchInit, 2, 0) || 1634 parseAndCheckArgument(YamlMFI.ArgInfo->PrivateSegmentSize, 1635 AMDGPU::SGPR_32RegClass, 1636 MFI->ArgInfo.PrivateSegmentSize, 0, 0) || 1637 parseAndCheckArgument(YamlMFI.ArgInfo->LDSKernelId, 1638 AMDGPU::SGPR_32RegClass, 1639 MFI->ArgInfo.LDSKernelId, 0, 1) || 1640 parseAndCheckArgument(YamlMFI.ArgInfo->WorkGroupIDX, 1641 AMDGPU::SGPR_32RegClass, MFI->ArgInfo.WorkGroupIDX, 1642 0, 1) || 1643 parseAndCheckArgument(YamlMFI.ArgInfo->WorkGroupIDY, 1644 AMDGPU::SGPR_32RegClass, MFI->ArgInfo.WorkGroupIDY, 1645 0, 1) || 1646 parseAndCheckArgument(YamlMFI.ArgInfo->WorkGroupIDZ, 1647 AMDGPU::SGPR_32RegClass, MFI->ArgInfo.WorkGroupIDZ, 1648 0, 1) || 1649 parseAndCheckArgument(YamlMFI.ArgInfo->WorkGroupInfo, 1650 AMDGPU::SGPR_32RegClass, 1651 MFI->ArgInfo.WorkGroupInfo, 0, 1) || 1652 parseAndCheckArgument(YamlMFI.ArgInfo->PrivateSegmentWaveByteOffset, 1653 AMDGPU::SGPR_32RegClass, 1654 MFI->ArgInfo.PrivateSegmentWaveByteOffset, 0, 1) || 1655 parseAndCheckArgument(YamlMFI.ArgInfo->ImplicitArgPtr, 1656 AMDGPU::SReg_64RegClass, 1657 MFI->ArgInfo.ImplicitArgPtr, 0, 0) || 1658 parseAndCheckArgument(YamlMFI.ArgInfo->ImplicitBufferPtr, 1659 AMDGPU::SReg_64RegClass, 1660 MFI->ArgInfo.ImplicitBufferPtr, 2, 0) || 1661 parseAndCheckArgument(YamlMFI.ArgInfo->WorkItemIDX, 1662 AMDGPU::VGPR_32RegClass, 1663 MFI->ArgInfo.WorkItemIDX, 0, 0) || 1664 parseAndCheckArgument(YamlMFI.ArgInfo->WorkItemIDY, 1665 AMDGPU::VGPR_32RegClass, 1666 MFI->ArgInfo.WorkItemIDY, 0, 0) || 1667 parseAndCheckArgument(YamlMFI.ArgInfo->WorkItemIDZ, 1668 AMDGPU::VGPR_32RegClass, 1669 MFI->ArgInfo.WorkItemIDZ, 0, 0))) 1670 return true; 1671 1672 if (ST.hasIEEEMode()) 1673 MFI->Mode.IEEE = YamlMFI.Mode.IEEE; 1674 if (ST.hasDX10ClampMode()) 1675 MFI->Mode.DX10Clamp = YamlMFI.Mode.DX10Clamp; 1676 1677 // FIXME: Move proper support for denormal-fp-math into base MachineFunction 1678 MFI->Mode.FP32Denormals.Input = YamlMFI.Mode.FP32InputDenormals 1679 ? DenormalMode::IEEE 1680 : DenormalMode::PreserveSign; 1681 MFI->Mode.FP32Denormals.Output = YamlMFI.Mode.FP32OutputDenormals 1682 ? DenormalMode::IEEE 1683 : DenormalMode::PreserveSign; 1684 1685 MFI->Mode.FP64FP16Denormals.Input = YamlMFI.Mode.FP64FP16InputDenormals 1686 ? DenormalMode::IEEE 1687 : DenormalMode::PreserveSign; 1688 MFI->Mode.FP64FP16Denormals.Output = YamlMFI.Mode.FP64FP16OutputDenormals 1689 ? DenormalMode::IEEE 1690 : DenormalMode::PreserveSign; 1691 1692 return false; 1693 } 1694