1 //===-- AMDGPUSubtarget.cpp - AMDGPU Subtarget Information ----------------===// 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 /// Implements the AMDGPU specific subclass of TargetSubtarget. 11 // 12 //===----------------------------------------------------------------------===// 13 14 #include "AMDGPUSubtarget.h" 15 #include "AMDGPUCallLowering.h" 16 #include "AMDGPUInstructionSelector.h" 17 #include "AMDGPULegalizerInfo.h" 18 #include "AMDGPURegisterBankInfo.h" 19 #include "AMDGPUTargetMachine.h" 20 #include "R600Subtarget.h" 21 #include "SIMachineFunctionInfo.h" 22 #include "Utils/AMDGPUBaseInfo.h" 23 #include "llvm/ADT/SmallString.h" 24 #include "llvm/CodeGen/GlobalISel/InlineAsmLowering.h" 25 #include "llvm/CodeGen/MachineScheduler.h" 26 #include "llvm/CodeGen/TargetFrameLowering.h" 27 #include "llvm/IR/IntrinsicsAMDGPU.h" 28 #include "llvm/IR/IntrinsicsR600.h" 29 #include "llvm/IR/MDBuilder.h" 30 #include "llvm/MC/MCSubtargetInfo.h" 31 #include <algorithm> 32 33 using namespace llvm; 34 35 #define DEBUG_TYPE "amdgpu-subtarget" 36 37 #define GET_SUBTARGETINFO_TARGET_DESC 38 #define GET_SUBTARGETINFO_CTOR 39 #define AMDGPUSubtarget GCNSubtarget 40 #include "AMDGPUGenSubtargetInfo.inc" 41 #undef AMDGPUSubtarget 42 43 static cl::opt<bool> DisablePowerSched( 44 "amdgpu-disable-power-sched", 45 cl::desc("Disable scheduling to minimize mAI power bursts"), 46 cl::init(false)); 47 48 static cl::opt<bool> EnableVGPRIndexMode( 49 "amdgpu-vgpr-index-mode", 50 cl::desc("Use GPR indexing mode instead of movrel for vector indexing"), 51 cl::init(false)); 52 53 static cl::opt<bool> UseAA("amdgpu-use-aa-in-codegen", 54 cl::desc("Enable the use of AA during codegen."), 55 cl::init(true)); 56 57 GCNSubtarget::~GCNSubtarget() = default; 58 59 GCNSubtarget & 60 GCNSubtarget::initializeSubtargetDependencies(const Triple &TT, 61 StringRef GPU, StringRef FS) { 62 // Determine default and user-specified characteristics 63 // 64 // We want to be able to turn these off, but making this a subtarget feature 65 // for SI has the unhelpful behavior that it unsets everything else if you 66 // disable it. 67 // 68 // Similarly we want enable-prt-strict-null to be on by default and not to 69 // unset everything else if it is disabled 70 71 SmallString<256> FullFS("+promote-alloca,+load-store-opt,+enable-ds128,"); 72 73 // Turn on features that HSA ABI requires. Also turn on FlatForGlobal by default 74 if (isAmdHsaOS()) 75 FullFS += "+flat-for-global,+unaligned-access-mode,+trap-handler,"; 76 77 FullFS += "+enable-prt-strict-null,"; // This is overridden by a disable in FS 78 79 // Disable mutually exclusive bits. 80 if (FS.contains_insensitive("+wavefrontsize")) { 81 if (!FS.contains_insensitive("wavefrontsize16")) 82 FullFS += "-wavefrontsize16,"; 83 if (!FS.contains_insensitive("wavefrontsize32")) 84 FullFS += "-wavefrontsize32,"; 85 if (!FS.contains_insensitive("wavefrontsize64")) 86 FullFS += "-wavefrontsize64,"; 87 } 88 89 FullFS += FS; 90 91 ParseSubtargetFeatures(GPU, /*TuneCPU*/ GPU, FullFS); 92 93 // Implement the "generic" processors, which acts as the default when no 94 // generation features are enabled (e.g for -mcpu=''). HSA OS defaults to 95 // the first amdgcn target that supports flat addressing. Other OSes defaults 96 // to the first amdgcn target. 97 if (Gen == AMDGPUSubtarget::INVALID) { 98 Gen = TT.getOS() == Triple::AMDHSA ? AMDGPUSubtarget::SEA_ISLANDS 99 : AMDGPUSubtarget::SOUTHERN_ISLANDS; 100 } 101 102 // We don't support FP64 for EG/NI atm. 103 assert(!hasFP64() || (getGeneration() >= AMDGPUSubtarget::SOUTHERN_ISLANDS)); 104 105 // Targets must either support 64-bit offsets for MUBUF instructions, and/or 106 // support flat operations, otherwise they cannot access a 64-bit global 107 // address space 108 assert(hasAddr64() || hasFlat()); 109 // Unless +-flat-for-global is specified, turn on FlatForGlobal for targets 110 // that do not support ADDR64 variants of MUBUF instructions. Such targets 111 // cannot use a 64 bit offset with a MUBUF instruction to access the global 112 // address space 113 if (!hasAddr64() && !FS.contains("flat-for-global") && !FlatForGlobal) { 114 ToggleFeature(AMDGPU::FeatureFlatForGlobal); 115 FlatForGlobal = true; 116 } 117 // Unless +-flat-for-global is specified, use MUBUF instructions for global 118 // address space access if flat operations are not available. 119 if (!hasFlat() && !FS.contains("flat-for-global") && FlatForGlobal) { 120 ToggleFeature(AMDGPU::FeatureFlatForGlobal); 121 FlatForGlobal = false; 122 } 123 124 // Set defaults if needed. 125 if (MaxPrivateElementSize == 0) 126 MaxPrivateElementSize = 4; 127 128 if (LDSBankCount == 0) 129 LDSBankCount = 32; 130 131 if (TT.getArch() == Triple::amdgcn) { 132 if (LocalMemorySize == 0) 133 LocalMemorySize = 32768; 134 135 // Do something sensible for unspecified target. 136 if (!HasMovrel && !HasVGPRIndexMode) 137 HasMovrel = true; 138 } 139 140 // Don't crash on invalid devices. 141 if (WavefrontSizeLog2 == 0) 142 WavefrontSizeLog2 = 5; 143 144 HasFminFmaxLegacy = getGeneration() < AMDGPUSubtarget::VOLCANIC_ISLANDS; 145 HasSMulHi = getGeneration() >= AMDGPUSubtarget::GFX9; 146 147 TargetID.setTargetIDFromFeaturesString(FS); 148 149 LLVM_DEBUG(dbgs() << "xnack setting for subtarget: " 150 << TargetID.getXnackSetting() << '\n'); 151 LLVM_DEBUG(dbgs() << "sramecc setting for subtarget: " 152 << TargetID.getSramEccSetting() << '\n'); 153 154 return *this; 155 } 156 157 AMDGPUSubtarget::AMDGPUSubtarget(const Triple &TT) : TargetTriple(TT) {} 158 159 GCNSubtarget::GCNSubtarget(const Triple &TT, StringRef GPU, StringRef FS, 160 const GCNTargetMachine &TM) 161 : // clang-format off 162 AMDGPUGenSubtargetInfo(TT, GPU, /*TuneCPU*/ GPU, FS), 163 AMDGPUSubtarget(TT), 164 TargetTriple(TT), 165 TargetID(*this), 166 InstrItins(getInstrItineraryForCPU(GPU)), 167 InstrInfo(initializeSubtargetDependencies(TT, GPU, FS)), 168 TLInfo(TM, *this), 169 FrameLowering(TargetFrameLowering::StackGrowsUp, getStackAlignment(), 0) { 170 // clang-format on 171 MaxWavesPerEU = AMDGPU::IsaInfo::getMaxWavesPerEU(this); 172 CallLoweringInfo.reset(new AMDGPUCallLowering(*getTargetLowering())); 173 InlineAsmLoweringInfo.reset(new InlineAsmLowering(getTargetLowering())); 174 Legalizer.reset(new AMDGPULegalizerInfo(*this, TM)); 175 RegBankInfo.reset(new AMDGPURegisterBankInfo(*this)); 176 InstSelector.reset(new AMDGPUInstructionSelector( 177 *this, *static_cast<AMDGPURegisterBankInfo *>(RegBankInfo.get()), TM)); 178 } 179 180 unsigned GCNSubtarget::getConstantBusLimit(unsigned Opcode) const { 181 if (getGeneration() < GFX10) 182 return 1; 183 184 switch (Opcode) { 185 case AMDGPU::V_LSHLREV_B64_e64: 186 case AMDGPU::V_LSHLREV_B64_gfx10: 187 case AMDGPU::V_LSHLREV_B64_e64_gfx11: 188 case AMDGPU::V_LSHL_B64_e64: 189 case AMDGPU::V_LSHRREV_B64_e64: 190 case AMDGPU::V_LSHRREV_B64_gfx10: 191 case AMDGPU::V_LSHRREV_B64_e64_gfx11: 192 case AMDGPU::V_LSHR_B64_e64: 193 case AMDGPU::V_ASHRREV_I64_e64: 194 case AMDGPU::V_ASHRREV_I64_gfx10: 195 case AMDGPU::V_ASHRREV_I64_e64_gfx11: 196 case AMDGPU::V_ASHR_I64_e64: 197 return 1; 198 } 199 200 return 2; 201 } 202 203 /// This list was mostly derived from experimentation. 204 bool GCNSubtarget::zeroesHigh16BitsOfDest(unsigned Opcode) const { 205 switch (Opcode) { 206 case AMDGPU::V_CVT_F16_F32_e32: 207 case AMDGPU::V_CVT_F16_F32_e64: 208 case AMDGPU::V_CVT_F16_U16_e32: 209 case AMDGPU::V_CVT_F16_U16_e64: 210 case AMDGPU::V_CVT_F16_I16_e32: 211 case AMDGPU::V_CVT_F16_I16_e64: 212 case AMDGPU::V_RCP_F16_e64: 213 case AMDGPU::V_RCP_F16_e32: 214 case AMDGPU::V_RSQ_F16_e64: 215 case AMDGPU::V_RSQ_F16_e32: 216 case AMDGPU::V_SQRT_F16_e64: 217 case AMDGPU::V_SQRT_F16_e32: 218 case AMDGPU::V_LOG_F16_e64: 219 case AMDGPU::V_LOG_F16_e32: 220 case AMDGPU::V_EXP_F16_e64: 221 case AMDGPU::V_EXP_F16_e32: 222 case AMDGPU::V_SIN_F16_e64: 223 case AMDGPU::V_SIN_F16_e32: 224 case AMDGPU::V_COS_F16_e64: 225 case AMDGPU::V_COS_F16_e32: 226 case AMDGPU::V_FLOOR_F16_e64: 227 case AMDGPU::V_FLOOR_F16_e32: 228 case AMDGPU::V_CEIL_F16_e64: 229 case AMDGPU::V_CEIL_F16_e32: 230 case AMDGPU::V_TRUNC_F16_e64: 231 case AMDGPU::V_TRUNC_F16_e32: 232 case AMDGPU::V_RNDNE_F16_e64: 233 case AMDGPU::V_RNDNE_F16_e32: 234 case AMDGPU::V_FRACT_F16_e64: 235 case AMDGPU::V_FRACT_F16_e32: 236 case AMDGPU::V_FREXP_MANT_F16_e64: 237 case AMDGPU::V_FREXP_MANT_F16_e32: 238 case AMDGPU::V_FREXP_EXP_I16_F16_e64: 239 case AMDGPU::V_FREXP_EXP_I16_F16_e32: 240 case AMDGPU::V_LDEXP_F16_e64: 241 case AMDGPU::V_LDEXP_F16_e32: 242 case AMDGPU::V_LSHLREV_B16_e64: 243 case AMDGPU::V_LSHLREV_B16_e32: 244 case AMDGPU::V_LSHRREV_B16_e64: 245 case AMDGPU::V_LSHRREV_B16_e32: 246 case AMDGPU::V_ASHRREV_I16_e64: 247 case AMDGPU::V_ASHRREV_I16_e32: 248 case AMDGPU::V_ADD_U16_e64: 249 case AMDGPU::V_ADD_U16_e32: 250 case AMDGPU::V_SUB_U16_e64: 251 case AMDGPU::V_SUB_U16_e32: 252 case AMDGPU::V_SUBREV_U16_e64: 253 case AMDGPU::V_SUBREV_U16_e32: 254 case AMDGPU::V_MUL_LO_U16_e64: 255 case AMDGPU::V_MUL_LO_U16_e32: 256 case AMDGPU::V_ADD_F16_e64: 257 case AMDGPU::V_ADD_F16_e32: 258 case AMDGPU::V_SUB_F16_e64: 259 case AMDGPU::V_SUB_F16_e32: 260 case AMDGPU::V_SUBREV_F16_e64: 261 case AMDGPU::V_SUBREV_F16_e32: 262 case AMDGPU::V_MUL_F16_e64: 263 case AMDGPU::V_MUL_F16_e32: 264 case AMDGPU::V_MAX_F16_e64: 265 case AMDGPU::V_MAX_F16_e32: 266 case AMDGPU::V_MIN_F16_e64: 267 case AMDGPU::V_MIN_F16_e32: 268 case AMDGPU::V_MAX_U16_e64: 269 case AMDGPU::V_MAX_U16_e32: 270 case AMDGPU::V_MIN_U16_e64: 271 case AMDGPU::V_MIN_U16_e32: 272 case AMDGPU::V_MAX_I16_e64: 273 case AMDGPU::V_MAX_I16_e32: 274 case AMDGPU::V_MIN_I16_e64: 275 case AMDGPU::V_MIN_I16_e32: 276 case AMDGPU::V_MAD_F16_e64: 277 case AMDGPU::V_MAD_U16_e64: 278 case AMDGPU::V_MAD_I16_e64: 279 case AMDGPU::V_FMA_F16_e64: 280 case AMDGPU::V_DIV_FIXUP_F16_e64: 281 // On gfx10, all 16-bit instructions preserve the high bits. 282 return getGeneration() <= AMDGPUSubtarget::GFX9; 283 case AMDGPU::V_MADAK_F16: 284 case AMDGPU::V_MADMK_F16: 285 case AMDGPU::V_MAC_F16_e64: 286 case AMDGPU::V_MAC_F16_e32: 287 case AMDGPU::V_FMAMK_F16: 288 case AMDGPU::V_FMAAK_F16: 289 case AMDGPU::V_FMAC_F16_e64: 290 case AMDGPU::V_FMAC_F16_e32: 291 // In gfx9, the preferred handling of the unused high 16-bits changed. Most 292 // instructions maintain the legacy behavior of 0ing. Some instructions 293 // changed to preserving the high bits. 294 return getGeneration() == AMDGPUSubtarget::VOLCANIC_ISLANDS; 295 case AMDGPU::V_MAD_MIXLO_F16: 296 case AMDGPU::V_MAD_MIXHI_F16: 297 default: 298 return false; 299 } 300 } 301 302 unsigned AMDGPUSubtarget::getMaxLocalMemSizeWithWaveCount(unsigned NWaves, 303 const Function &F) const { 304 if (NWaves == 1) 305 return getLocalMemorySize(); 306 unsigned WorkGroupSize = getFlatWorkGroupSizes(F).second; 307 unsigned WorkGroupsPerCu = getMaxWorkGroupsPerCU(WorkGroupSize); 308 if (!WorkGroupsPerCu) 309 return 0; 310 unsigned MaxWaves = getMaxWavesPerEU(); 311 return getLocalMemorySize() * MaxWaves / WorkGroupsPerCu / NWaves; 312 } 313 314 // FIXME: Should return min,max range. 315 unsigned AMDGPUSubtarget::getOccupancyWithLocalMemSize(uint32_t Bytes, 316 const Function &F) const { 317 const unsigned MaxWorkGroupSize = getFlatWorkGroupSizes(F).second; 318 const unsigned MaxWorkGroupsPerCu = getMaxWorkGroupsPerCU(MaxWorkGroupSize); 319 if (!MaxWorkGroupsPerCu) 320 return 0; 321 322 const unsigned WaveSize = getWavefrontSize(); 323 324 // FIXME: Do we need to account for alignment requirement of LDS rounding the 325 // size up? 326 // Compute restriction based on LDS usage 327 unsigned NumGroups = getLocalMemorySize() / (Bytes ? Bytes : 1u); 328 329 // This can be queried with more LDS than is possible, so just assume the 330 // worst. 331 if (NumGroups == 0) 332 return 1; 333 334 NumGroups = std::min(MaxWorkGroupsPerCu, NumGroups); 335 336 // Round to the number of waves. 337 const unsigned MaxGroupNumWaves = (MaxWorkGroupSize + WaveSize - 1) / WaveSize; 338 unsigned MaxWaves = NumGroups * MaxGroupNumWaves; 339 340 // Clamp to the maximum possible number of waves. 341 MaxWaves = std::min(MaxWaves, getMaxWavesPerEU()); 342 343 // FIXME: Needs to be a multiple of the group size? 344 //MaxWaves = MaxGroupNumWaves * (MaxWaves / MaxGroupNumWaves); 345 346 assert(MaxWaves > 0 && MaxWaves <= getMaxWavesPerEU() && 347 "computed invalid occupancy"); 348 return MaxWaves; 349 } 350 351 unsigned 352 AMDGPUSubtarget::getOccupancyWithLocalMemSize(const MachineFunction &MF) const { 353 const auto *MFI = MF.getInfo<SIMachineFunctionInfo>(); 354 return getOccupancyWithLocalMemSize(MFI->getLDSSize(), MF.getFunction()); 355 } 356 357 std::pair<unsigned, unsigned> 358 AMDGPUSubtarget::getDefaultFlatWorkGroupSize(CallingConv::ID CC) const { 359 switch (CC) { 360 case CallingConv::AMDGPU_VS: 361 case CallingConv::AMDGPU_LS: 362 case CallingConv::AMDGPU_HS: 363 case CallingConv::AMDGPU_ES: 364 case CallingConv::AMDGPU_GS: 365 case CallingConv::AMDGPU_PS: 366 return std::make_pair(1, getWavefrontSize()); 367 default: 368 return std::make_pair(1u, getMaxFlatWorkGroupSize()); 369 } 370 } 371 372 std::pair<unsigned, unsigned> AMDGPUSubtarget::getFlatWorkGroupSizes( 373 const Function &F) const { 374 // Default minimum/maximum flat work group sizes. 375 std::pair<unsigned, unsigned> Default = 376 getDefaultFlatWorkGroupSize(F.getCallingConv()); 377 378 // Requested minimum/maximum flat work group sizes. 379 std::pair<unsigned, unsigned> Requested = AMDGPU::getIntegerPairAttribute( 380 F, "amdgpu-flat-work-group-size", Default); 381 382 // Make sure requested minimum is less than requested maximum. 383 if (Requested.first > Requested.second) 384 return Default; 385 386 // Make sure requested values do not violate subtarget's specifications. 387 if (Requested.first < getMinFlatWorkGroupSize()) 388 return Default; 389 if (Requested.second > getMaxFlatWorkGroupSize()) 390 return Default; 391 392 return Requested; 393 } 394 395 std::pair<unsigned, unsigned> AMDGPUSubtarget::getWavesPerEU( 396 const Function &F, std::pair<unsigned, unsigned> FlatWorkGroupSizes) const { 397 // Default minimum/maximum number of waves per execution unit. 398 std::pair<unsigned, unsigned> Default(1, getMaxWavesPerEU()); 399 400 // If minimum/maximum flat work group sizes were explicitly requested using 401 // "amdgpu-flat-work-group-size" attribute, then set default minimum/maximum 402 // number of waves per execution unit to values implied by requested 403 // minimum/maximum flat work group sizes. 404 unsigned MinImpliedByFlatWorkGroupSize = 405 getWavesPerEUForWorkGroup(FlatWorkGroupSizes.second); 406 Default.first = MinImpliedByFlatWorkGroupSize; 407 408 // Requested minimum/maximum number of waves per execution unit. 409 std::pair<unsigned, unsigned> Requested = AMDGPU::getIntegerPairAttribute( 410 F, "amdgpu-waves-per-eu", Default, true); 411 412 // Make sure requested minimum is less than requested maximum. 413 if (Requested.second && Requested.first > Requested.second) 414 return Default; 415 416 // Make sure requested values do not violate subtarget's specifications. 417 if (Requested.first < getMinWavesPerEU() || 418 Requested.second > getMaxWavesPerEU()) 419 return Default; 420 421 // Make sure requested values are compatible with values implied by requested 422 // minimum/maximum flat work group sizes. 423 if (Requested.first < MinImpliedByFlatWorkGroupSize) 424 return Default; 425 426 return Requested; 427 } 428 429 static unsigned getReqdWorkGroupSize(const Function &Kernel, unsigned Dim) { 430 auto Node = Kernel.getMetadata("reqd_work_group_size"); 431 if (Node && Node->getNumOperands() == 3) 432 return mdconst::extract<ConstantInt>(Node->getOperand(Dim))->getZExtValue(); 433 return std::numeric_limits<unsigned>::max(); 434 } 435 436 bool AMDGPUSubtarget::isMesaKernel(const Function &F) const { 437 return isMesa3DOS() && !AMDGPU::isShader(F.getCallingConv()); 438 } 439 440 unsigned AMDGPUSubtarget::getMaxWorkitemID(const Function &Kernel, 441 unsigned Dimension) const { 442 unsigned ReqdSize = getReqdWorkGroupSize(Kernel, Dimension); 443 if (ReqdSize != std::numeric_limits<unsigned>::max()) 444 return ReqdSize - 1; 445 return getFlatWorkGroupSizes(Kernel).second - 1; 446 } 447 448 bool AMDGPUSubtarget::makeLIDRangeMetadata(Instruction *I) const { 449 Function *Kernel = I->getParent()->getParent(); 450 unsigned MinSize = 0; 451 unsigned MaxSize = getFlatWorkGroupSizes(*Kernel).second; 452 bool IdQuery = false; 453 454 // If reqd_work_group_size is present it narrows value down. 455 if (auto *CI = dyn_cast<CallInst>(I)) { 456 const Function *F = CI->getCalledFunction(); 457 if (F) { 458 unsigned Dim = UINT_MAX; 459 switch (F->getIntrinsicID()) { 460 case Intrinsic::amdgcn_workitem_id_x: 461 case Intrinsic::r600_read_tidig_x: 462 IdQuery = true; 463 LLVM_FALLTHROUGH; 464 case Intrinsic::r600_read_local_size_x: 465 Dim = 0; 466 break; 467 case Intrinsic::amdgcn_workitem_id_y: 468 case Intrinsic::r600_read_tidig_y: 469 IdQuery = true; 470 LLVM_FALLTHROUGH; 471 case Intrinsic::r600_read_local_size_y: 472 Dim = 1; 473 break; 474 case Intrinsic::amdgcn_workitem_id_z: 475 case Intrinsic::r600_read_tidig_z: 476 IdQuery = true; 477 LLVM_FALLTHROUGH; 478 case Intrinsic::r600_read_local_size_z: 479 Dim = 2; 480 break; 481 default: 482 break; 483 } 484 485 if (Dim <= 3) { 486 unsigned ReqdSize = getReqdWorkGroupSize(*Kernel, Dim); 487 if (ReqdSize != std::numeric_limits<unsigned>::max()) 488 MinSize = MaxSize = ReqdSize; 489 } 490 } 491 } 492 493 if (!MaxSize) 494 return false; 495 496 // Range metadata is [Lo, Hi). For ID query we need to pass max size 497 // as Hi. For size query we need to pass Hi + 1. 498 if (IdQuery) 499 MinSize = 0; 500 else 501 ++MaxSize; 502 503 MDBuilder MDB(I->getContext()); 504 MDNode *MaxWorkGroupSizeRange = MDB.createRange(APInt(32, MinSize), 505 APInt(32, MaxSize)); 506 I->setMetadata(LLVMContext::MD_range, MaxWorkGroupSizeRange); 507 return true; 508 } 509 510 unsigned AMDGPUSubtarget::getImplicitArgNumBytes(const Function &F) const { 511 assert(AMDGPU::isKernel(F.getCallingConv())); 512 513 // We don't allocate the segment if we know the implicit arguments weren't 514 // used, even if the ABI implies we need them. 515 if (F.hasFnAttribute("amdgpu-no-implicitarg-ptr")) 516 return 0; 517 518 if (isMesaKernel(F)) 519 return 16; 520 521 // Assume all implicit inputs are used by default 522 unsigned NBytes = (AMDGPU::getAmdhsaCodeObjectVersion() >= 5) ? 256 : 56; 523 return AMDGPU::getIntegerAttribute(F, "amdgpu-implicitarg-num-bytes", NBytes); 524 } 525 526 uint64_t AMDGPUSubtarget::getExplicitKernArgSize(const Function &F, 527 Align &MaxAlign) const { 528 assert(F.getCallingConv() == CallingConv::AMDGPU_KERNEL || 529 F.getCallingConv() == CallingConv::SPIR_KERNEL); 530 531 const DataLayout &DL = F.getParent()->getDataLayout(); 532 uint64_t ExplicitArgBytes = 0; 533 MaxAlign = Align(1); 534 535 for (const Argument &Arg : F.args()) { 536 const bool IsByRef = Arg.hasByRefAttr(); 537 Type *ArgTy = IsByRef ? Arg.getParamByRefType() : Arg.getType(); 538 MaybeAlign Alignment = IsByRef ? Arg.getParamAlign() : None; 539 if (!Alignment) 540 Alignment = DL.getABITypeAlign(ArgTy); 541 542 uint64_t AllocSize = DL.getTypeAllocSize(ArgTy); 543 ExplicitArgBytes = alignTo(ExplicitArgBytes, Alignment) + AllocSize; 544 MaxAlign = max(MaxAlign, Alignment); 545 } 546 547 return ExplicitArgBytes; 548 } 549 550 unsigned AMDGPUSubtarget::getKernArgSegmentSize(const Function &F, 551 Align &MaxAlign) const { 552 uint64_t ExplicitArgBytes = getExplicitKernArgSize(F, MaxAlign); 553 554 unsigned ExplicitOffset = getExplicitKernelArgOffset(F); 555 556 uint64_t TotalSize = ExplicitOffset + ExplicitArgBytes; 557 unsigned ImplicitBytes = getImplicitArgNumBytes(F); 558 if (ImplicitBytes != 0) { 559 const Align Alignment = getAlignmentForImplicitArgPtr(); 560 TotalSize = alignTo(ExplicitArgBytes, Alignment) + ImplicitBytes; 561 MaxAlign = std::max(MaxAlign, Alignment); 562 } 563 564 // Being able to dereference past the end is useful for emitting scalar loads. 565 return alignTo(TotalSize, 4); 566 } 567 568 AMDGPUDwarfFlavour AMDGPUSubtarget::getAMDGPUDwarfFlavour() const { 569 return getWavefrontSize() == 32 ? AMDGPUDwarfFlavour::Wave32 570 : AMDGPUDwarfFlavour::Wave64; 571 } 572 573 void GCNSubtarget::overrideSchedPolicy(MachineSchedPolicy &Policy, 574 unsigned NumRegionInstrs) const { 575 // Track register pressure so the scheduler can try to decrease 576 // pressure once register usage is above the threshold defined by 577 // SIRegisterInfo::getRegPressureSetLimit() 578 Policy.ShouldTrackPressure = true; 579 580 // Enabling both top down and bottom up scheduling seems to give us less 581 // register spills than just using one of these approaches on its own. 582 Policy.OnlyTopDown = false; 583 Policy.OnlyBottomUp = false; 584 585 // Enabling ShouldTrackLaneMasks crashes the SI Machine Scheduler. 586 if (!enableSIScheduler()) 587 Policy.ShouldTrackLaneMasks = true; 588 } 589 590 bool GCNSubtarget::hasMadF16() const { 591 return InstrInfo.pseudoToMCOpcode(AMDGPU::V_MAD_F16_e64) != -1; 592 } 593 594 bool GCNSubtarget::useVGPRIndexMode() const { 595 return !hasMovrel() || (EnableVGPRIndexMode && hasVGPRIndexMode()); 596 } 597 598 bool GCNSubtarget::useAA() const { return UseAA; } 599 600 unsigned GCNSubtarget::getOccupancyWithNumSGPRs(unsigned SGPRs) const { 601 if (getGeneration() >= AMDGPUSubtarget::GFX10) 602 return getMaxWavesPerEU(); 603 604 if (getGeneration() >= AMDGPUSubtarget::VOLCANIC_ISLANDS) { 605 if (SGPRs <= 80) 606 return 10; 607 if (SGPRs <= 88) 608 return 9; 609 if (SGPRs <= 100) 610 return 8; 611 return 7; 612 } 613 if (SGPRs <= 48) 614 return 10; 615 if (SGPRs <= 56) 616 return 9; 617 if (SGPRs <= 64) 618 return 8; 619 if (SGPRs <= 72) 620 return 7; 621 if (SGPRs <= 80) 622 return 6; 623 return 5; 624 } 625 626 unsigned GCNSubtarget::getOccupancyWithNumVGPRs(unsigned VGPRs) const { 627 unsigned MaxWaves = getMaxWavesPerEU(); 628 unsigned Granule = getVGPRAllocGranule(); 629 if (VGPRs < Granule) 630 return MaxWaves; 631 unsigned RoundedRegs = ((VGPRs + Granule - 1) / Granule) * Granule; 632 return std::min(std::max(getTotalNumVGPRs() / RoundedRegs, 1u), MaxWaves); 633 } 634 635 unsigned 636 GCNSubtarget::getBaseReservedNumSGPRs(const bool HasFlatScratch) const { 637 if (getGeneration() >= AMDGPUSubtarget::GFX10) 638 return 2; // VCC. FLAT_SCRATCH and XNACK are no longer in SGPRs. 639 640 if (HasFlatScratch || HasArchitectedFlatScratch) { 641 if (getGeneration() >= AMDGPUSubtarget::VOLCANIC_ISLANDS) 642 return 6; // FLAT_SCRATCH, XNACK, VCC (in that order). 643 if (getGeneration() == AMDGPUSubtarget::SEA_ISLANDS) 644 return 4; // FLAT_SCRATCH, VCC (in that order). 645 } 646 647 if (isXNACKEnabled()) 648 return 4; // XNACK, VCC (in that order). 649 return 2; // VCC. 650 } 651 652 unsigned GCNSubtarget::getReservedNumSGPRs(const MachineFunction &MF) const { 653 const SIMachineFunctionInfo &MFI = *MF.getInfo<SIMachineFunctionInfo>(); 654 return getBaseReservedNumSGPRs(MFI.hasFlatScratchInit()); 655 } 656 657 unsigned GCNSubtarget::getReservedNumSGPRs(const Function &F) const { 658 // In principle we do not need to reserve SGPR pair used for flat_scratch if 659 // we know flat instructions do not access the stack anywhere in the 660 // program. For now assume it's needed if we have flat instructions. 661 const bool KernelUsesFlatScratch = hasFlatAddressSpace(); 662 return getBaseReservedNumSGPRs(KernelUsesFlatScratch); 663 } 664 665 unsigned GCNSubtarget::computeOccupancy(const Function &F, unsigned LDSSize, 666 unsigned NumSGPRs, 667 unsigned NumVGPRs) const { 668 unsigned Occupancy = 669 std::min(getMaxWavesPerEU(), 670 getOccupancyWithLocalMemSize(LDSSize, F)); 671 if (NumSGPRs) 672 Occupancy = std::min(Occupancy, getOccupancyWithNumSGPRs(NumSGPRs)); 673 if (NumVGPRs) 674 Occupancy = std::min(Occupancy, getOccupancyWithNumVGPRs(NumVGPRs)); 675 return Occupancy; 676 } 677 678 unsigned GCNSubtarget::getBaseMaxNumSGPRs( 679 const Function &F, std::pair<unsigned, unsigned> WavesPerEU, 680 unsigned PreloadedSGPRs, unsigned ReservedNumSGPRs) const { 681 // Compute maximum number of SGPRs function can use using default/requested 682 // minimum number of waves per execution unit. 683 unsigned MaxNumSGPRs = getMaxNumSGPRs(WavesPerEU.first, false); 684 unsigned MaxAddressableNumSGPRs = getMaxNumSGPRs(WavesPerEU.first, true); 685 686 // Check if maximum number of SGPRs was explicitly requested using 687 // "amdgpu-num-sgpr" attribute. 688 if (F.hasFnAttribute("amdgpu-num-sgpr")) { 689 unsigned Requested = AMDGPU::getIntegerAttribute( 690 F, "amdgpu-num-sgpr", MaxNumSGPRs); 691 692 // Make sure requested value does not violate subtarget's specifications. 693 if (Requested && (Requested <= ReservedNumSGPRs)) 694 Requested = 0; 695 696 // If more SGPRs are required to support the input user/system SGPRs, 697 // increase to accommodate them. 698 // 699 // FIXME: This really ends up using the requested number of SGPRs + number 700 // of reserved special registers in total. Theoretically you could re-use 701 // the last input registers for these special registers, but this would 702 // require a lot of complexity to deal with the weird aliasing. 703 unsigned InputNumSGPRs = PreloadedSGPRs; 704 if (Requested && Requested < InputNumSGPRs) 705 Requested = InputNumSGPRs; 706 707 // Make sure requested value is compatible with values implied by 708 // default/requested minimum/maximum number of waves per execution unit. 709 if (Requested && Requested > getMaxNumSGPRs(WavesPerEU.first, false)) 710 Requested = 0; 711 if (WavesPerEU.second && 712 Requested && Requested < getMinNumSGPRs(WavesPerEU.second)) 713 Requested = 0; 714 715 if (Requested) 716 MaxNumSGPRs = Requested; 717 } 718 719 if (hasSGPRInitBug()) 720 MaxNumSGPRs = AMDGPU::IsaInfo::FIXED_NUM_SGPRS_FOR_INIT_BUG; 721 722 return std::min(MaxNumSGPRs - ReservedNumSGPRs, MaxAddressableNumSGPRs); 723 } 724 725 unsigned GCNSubtarget::getMaxNumSGPRs(const MachineFunction &MF) const { 726 const Function &F = MF.getFunction(); 727 const SIMachineFunctionInfo &MFI = *MF.getInfo<SIMachineFunctionInfo>(); 728 return getBaseMaxNumSGPRs(F, MFI.getWavesPerEU(), MFI.getNumPreloadedSGPRs(), 729 getReservedNumSGPRs(MF)); 730 } 731 732 static unsigned getMaxNumPreloadedSGPRs() { 733 // Max number of user SGPRs 734 unsigned MaxUserSGPRs = 4 + // private segment buffer 735 2 + // Dispatch ptr 736 2 + // queue ptr 737 2 + // kernel segment ptr 738 2 + // dispatch ID 739 2 + // flat scratch init 740 2; // Implicit buffer ptr 741 // Max number of system SGPRs 742 unsigned MaxSystemSGPRs = 1 + // WorkGroupIDX 743 1 + // WorkGroupIDY 744 1 + // WorkGroupIDZ 745 1 + // WorkGroupInfo 746 1; // private segment wave byte offset 747 return MaxUserSGPRs + MaxSystemSGPRs; 748 } 749 750 unsigned GCNSubtarget::getMaxNumSGPRs(const Function &F) const { 751 return getBaseMaxNumSGPRs(F, getWavesPerEU(F), getMaxNumPreloadedSGPRs(), 752 getReservedNumSGPRs(F)); 753 } 754 755 unsigned GCNSubtarget::getBaseMaxNumVGPRs( 756 const Function &F, std::pair<unsigned, unsigned> WavesPerEU) const { 757 // Compute maximum number of VGPRs function can use using default/requested 758 // minimum number of waves per execution unit. 759 unsigned MaxNumVGPRs = getMaxNumVGPRs(WavesPerEU.first); 760 761 // Check if maximum number of VGPRs was explicitly requested using 762 // "amdgpu-num-vgpr" attribute. 763 if (F.hasFnAttribute("amdgpu-num-vgpr")) { 764 unsigned Requested = AMDGPU::getIntegerAttribute( 765 F, "amdgpu-num-vgpr", MaxNumVGPRs); 766 767 if (hasGFX90AInsts()) 768 Requested *= 2; 769 770 // Make sure requested value is compatible with values implied by 771 // default/requested minimum/maximum number of waves per execution unit. 772 if (Requested && Requested > getMaxNumVGPRs(WavesPerEU.first)) 773 Requested = 0; 774 if (WavesPerEU.second && 775 Requested && Requested < getMinNumVGPRs(WavesPerEU.second)) 776 Requested = 0; 777 778 if (Requested) 779 MaxNumVGPRs = Requested; 780 } 781 782 return MaxNumVGPRs; 783 } 784 785 unsigned GCNSubtarget::getMaxNumVGPRs(const Function &F) const { 786 return getBaseMaxNumVGPRs(F, getWavesPerEU(F)); 787 } 788 789 unsigned GCNSubtarget::getMaxNumVGPRs(const MachineFunction &MF) const { 790 const Function &F = MF.getFunction(); 791 const SIMachineFunctionInfo &MFI = *MF.getInfo<SIMachineFunctionInfo>(); 792 return getBaseMaxNumVGPRs(F, MFI.getWavesPerEU()); 793 } 794 795 void GCNSubtarget::adjustSchedDependency(SUnit *Def, int DefOpIdx, SUnit *Use, 796 int UseOpIdx, SDep &Dep) const { 797 if (Dep.getKind() != SDep::Kind::Data || !Dep.getReg() || 798 !Def->isInstr() || !Use->isInstr()) 799 return; 800 801 MachineInstr *DefI = Def->getInstr(); 802 MachineInstr *UseI = Use->getInstr(); 803 804 if (DefI->isBundle()) { 805 const SIRegisterInfo *TRI = getRegisterInfo(); 806 auto Reg = Dep.getReg(); 807 MachineBasicBlock::const_instr_iterator I(DefI->getIterator()); 808 MachineBasicBlock::const_instr_iterator E(DefI->getParent()->instr_end()); 809 unsigned Lat = 0; 810 for (++I; I != E && I->isBundledWithPred(); ++I) { 811 if (I->modifiesRegister(Reg, TRI)) 812 Lat = InstrInfo.getInstrLatency(getInstrItineraryData(), *I); 813 else if (Lat) 814 --Lat; 815 } 816 Dep.setLatency(Lat); 817 } else if (UseI->isBundle()) { 818 const SIRegisterInfo *TRI = getRegisterInfo(); 819 auto Reg = Dep.getReg(); 820 MachineBasicBlock::const_instr_iterator I(UseI->getIterator()); 821 MachineBasicBlock::const_instr_iterator E(UseI->getParent()->instr_end()); 822 unsigned Lat = InstrInfo.getInstrLatency(getInstrItineraryData(), *DefI); 823 for (++I; I != E && I->isBundledWithPred() && Lat; ++I) { 824 if (I->readsRegister(Reg, TRI)) 825 break; 826 --Lat; 827 } 828 Dep.setLatency(Lat); 829 } else if (Dep.getLatency() == 0 && Dep.getReg() == AMDGPU::VCC_LO) { 830 // Work around the fact that SIInstrInfo::fixImplicitOperands modifies 831 // implicit operands which come from the MCInstrDesc, which can fool 832 // ScheduleDAGInstrs::addPhysRegDataDeps into treating them as implicit 833 // pseudo operands. 834 Dep.setLatency(InstrInfo.getSchedModel().computeOperandLatency( 835 DefI, DefOpIdx, UseI, UseOpIdx)); 836 } 837 } 838 839 namespace { 840 struct FillMFMAShadowMutation : ScheduleDAGMutation { 841 const SIInstrInfo *TII; 842 843 ScheduleDAGMI *DAG; 844 845 FillMFMAShadowMutation(const SIInstrInfo *tii) : TII(tii) {} 846 847 bool isSALU(const SUnit *SU) const { 848 const MachineInstr *MI = SU->getInstr(); 849 return MI && TII->isSALU(*MI) && !MI->isTerminator(); 850 } 851 852 bool isVALU(const SUnit *SU) const { 853 const MachineInstr *MI = SU->getInstr(); 854 return MI && TII->isVALU(*MI); 855 } 856 857 bool canAddEdge(const SUnit *Succ, const SUnit *Pred) const { 858 if (Pred->NodeNum < Succ->NodeNum) 859 return true; 860 861 SmallVector<const SUnit*, 64> Succs({Succ}), Preds({Pred}); 862 863 for (unsigned I = 0; I < Succs.size(); ++I) { 864 for (const SDep &SI : Succs[I]->Succs) { 865 const SUnit *SU = SI.getSUnit(); 866 if (SU != Succs[I] && !llvm::is_contained(Succs, SU)) 867 Succs.push_back(SU); 868 } 869 } 870 871 SmallPtrSet<const SUnit*, 32> Visited; 872 while (!Preds.empty()) { 873 const SUnit *SU = Preds.pop_back_val(); 874 if (llvm::is_contained(Succs, SU)) 875 return false; 876 Visited.insert(SU); 877 for (const SDep &SI : SU->Preds) 878 if (SI.getSUnit() != SU && !Visited.count(SI.getSUnit())) 879 Preds.push_back(SI.getSUnit()); 880 } 881 882 return true; 883 } 884 885 // Link as many SALU instructions in chain as possible. Return the size 886 // of the chain. Links up to MaxChain instructions. 887 unsigned linkSALUChain(SUnit *From, SUnit *To, unsigned MaxChain, 888 SmallPtrSetImpl<SUnit *> &Visited) const { 889 SmallVector<SUnit *, 8> Worklist({To}); 890 unsigned Linked = 0; 891 892 while (!Worklist.empty() && MaxChain-- > 0) { 893 SUnit *SU = Worklist.pop_back_val(); 894 if (!Visited.insert(SU).second) 895 continue; 896 897 LLVM_DEBUG(dbgs() << "Inserting edge from\n" ; DAG->dumpNode(*From); 898 dbgs() << "to\n"; DAG->dumpNode(*SU); dbgs() << '\n'); 899 900 if (SU->addPred(SDep(From, SDep::Artificial), false)) 901 ++Linked; 902 903 for (SDep &SI : From->Succs) { 904 SUnit *SUv = SI.getSUnit(); 905 if (SUv != From && isVALU(SUv) && canAddEdge(SUv, SU)) 906 SUv->addPred(SDep(SU, SDep::Artificial), false); 907 } 908 909 for (SDep &SI : SU->Succs) { 910 SUnit *Succ = SI.getSUnit(); 911 if (Succ != SU && isSALU(Succ) && canAddEdge(From, Succ)) 912 Worklist.push_back(Succ); 913 } 914 } 915 916 return Linked; 917 } 918 919 void apply(ScheduleDAGInstrs *DAGInstrs) override { 920 const GCNSubtarget &ST = DAGInstrs->MF.getSubtarget<GCNSubtarget>(); 921 if (!ST.hasMAIInsts() || DisablePowerSched) 922 return; 923 DAG = static_cast<ScheduleDAGMI*>(DAGInstrs); 924 const TargetSchedModel *TSchedModel = DAGInstrs->getSchedModel(); 925 if (!TSchedModel || DAG->SUnits.empty()) 926 return; 927 928 // Scan for MFMA long latency instructions and try to add a dependency 929 // of available SALU instructions to give them a chance to fill MFMA 930 // shadow. That is desirable to fill MFMA shadow with SALU instructions 931 // rather than VALU to prevent power consumption bursts and throttle. 932 auto LastSALU = DAG->SUnits.begin(); 933 auto E = DAG->SUnits.end(); 934 SmallPtrSet<SUnit*, 32> Visited; 935 for (SUnit &SU : DAG->SUnits) { 936 MachineInstr &MAI = *SU.getInstr(); 937 if (!TII->isMAI(MAI) || 938 MAI.getOpcode() == AMDGPU::V_ACCVGPR_WRITE_B32_e64 || 939 MAI.getOpcode() == AMDGPU::V_ACCVGPR_READ_B32_e64) 940 continue; 941 942 unsigned Lat = TSchedModel->computeInstrLatency(&MAI) - 1; 943 944 LLVM_DEBUG(dbgs() << "Found MFMA: "; DAG->dumpNode(SU); 945 dbgs() << "Need " << Lat 946 << " instructions to cover latency.\n"); 947 948 // Find up to Lat independent scalar instructions as early as 949 // possible such that they can be scheduled after this MFMA. 950 for ( ; Lat && LastSALU != E; ++LastSALU) { 951 if (Visited.count(&*LastSALU)) 952 continue; 953 954 if (!isSALU(&*LastSALU) || !canAddEdge(&*LastSALU, &SU)) 955 continue; 956 957 Lat -= linkSALUChain(&SU, &*LastSALU, Lat, Visited); 958 } 959 } 960 } 961 }; 962 } // namespace 963 964 void GCNSubtarget::getPostRAMutations( 965 std::vector<std::unique_ptr<ScheduleDAGMutation>> &Mutations) const { 966 Mutations.push_back(std::make_unique<FillMFMAShadowMutation>(&InstrInfo)); 967 } 968 969 std::unique_ptr<ScheduleDAGMutation> 970 GCNSubtarget::createFillMFMAShadowMutation(const TargetInstrInfo *TII) const { 971 return std::make_unique<FillMFMAShadowMutation>(&InstrInfo); 972 } 973 974 const AMDGPUSubtarget &AMDGPUSubtarget::get(const MachineFunction &MF) { 975 if (MF.getTarget().getTargetTriple().getArch() == Triple::amdgcn) 976 return static_cast<const AMDGPUSubtarget&>(MF.getSubtarget<GCNSubtarget>()); 977 else 978 return static_cast<const AMDGPUSubtarget&>(MF.getSubtarget<R600Subtarget>()); 979 } 980 981 const AMDGPUSubtarget &AMDGPUSubtarget::get(const TargetMachine &TM, const Function &F) { 982 if (TM.getTargetTriple().getArch() == Triple::amdgcn) 983 return static_cast<const AMDGPUSubtarget&>(TM.getSubtarget<GCNSubtarget>(F)); 984 else 985 return static_cast<const AMDGPUSubtarget&>(TM.getSubtarget<R600Subtarget>(F)); 986 } 987