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 "R600Subtarget.h"
20#include "SIMachineFunctionInfo.h"
21#include "Utils/AMDGPUBaseInfo.h"
22#include "llvm/CodeGen/MachineScheduler.h"
23#include "llvm/CodeGen/TargetFrameLowering.h"
24#include "llvm/IR/DiagnosticInfo.h"
25#include "llvm/IR/IntrinsicsAMDGPU.h"
26#include "llvm/IR/IntrinsicsR600.h"
27#include "llvm/IR/MDBuilder.h"
28#include <algorithm>
29
30using namespace llvm;
31
32#define DEBUG_TYPE "amdgpu-subtarget"
33
34// Returns the maximum per-workgroup LDS allocation size (in bytes) that still
35// allows the given function to achieve an occupancy of NWaves waves per
36// SIMD / EU, taking into account only the function's *maximum* workgroup size.
37unsigned
38AMDGPUSubtarget::getMaxLocalMemSizeWithWaveCount(unsigned NWaves,
39 const Function &F) const {
40 const unsigned WaveSize = getWavefrontSize();
41 const unsigned WorkGroupSize = getFlatWorkGroupSizes(F).second;
42 const unsigned WavesPerWorkgroup =
43 std::max(a: 1u, b: (WorkGroupSize + WaveSize - 1) / WaveSize);
44
45 const unsigned WorkGroupsPerCU =
46 std::max(a: 1u, b: (NWaves * getNumWorkGroupSIMDs()) / WavesPerWorkgroup);
47
48 const unsigned Granularity = std::max(a: LDSAllocationGranularity, b: 1u);
49 return alignDown(Value: getLocalMemorySize() / WorkGroupsPerCU, Align: Granularity);
50}
51
52std::pair<unsigned, unsigned> AMDGPUSubtarget::getOccupancyWithWorkGroupSizes(
53 uint32_t LDSBytes, std::pair<unsigned, unsigned> FlatWorkGroupSizes) const {
54
55 // LDS granularity accounted for by aligning the queried LDS size to the
56 // allocation block size.
57 const unsigned Granularity = std::max(a: LDSAllocationGranularity, b: 1u);
58 LDSBytes = alignTo(Value: LDSBytes, Align: Granularity);
59 const unsigned MaxWGsLDS = getLocalMemorySize() / std::max(a: LDSBytes, b: 1u);
60
61 // Queried LDS size may be larger than available on a CU, in which case we
62 // consider the only achievable occupancy to be 1, in line with what we
63 // consider the occupancy to be when the number of requested registers in a
64 // particular bank is higher than the number of available ones in that bank.
65 if (!MaxWGsLDS)
66 return {1, 1};
67
68 const unsigned WaveSize = getWavefrontSize(), WavesPerEU = getMaxWavesPerEU();
69
70 auto PropsFromWGSize = [=](unsigned WGSize)
71 -> std::tuple<const unsigned, const unsigned, unsigned> {
72 unsigned WavesPerWG = divideCeil(Numerator: WGSize, Denominator: WaveSize);
73 unsigned WGsPerCU = std::min(a: getMaxWorkGroupsPerCU(FlatWorkGroupSize: WGSize), b: MaxWGsLDS);
74 return {WavesPerWG, WGsPerCU, WavesPerWG * WGsPerCU};
75 };
76
77 // The maximum group size will generally yield the minimum number of
78 // workgroups, maximum number of waves, and minimum occupancy. The opposite is
79 // generally true for the minimum group size. LDS or barrier ressource
80 // limitations can flip those minimums/maximums.
81 const auto [MinWGSize, MaxWGSize] = FlatWorkGroupSizes;
82 auto [MinWavesPerWG, MaxWGsPerCU, MaxWavesPerCU] = PropsFromWGSize(MinWGSize);
83 auto [MaxWavesPerWG, MinWGsPerCU, MinWavesPerCU] = PropsFromWGSize(MaxWGSize);
84
85 // It is possible that we end up with flipped minimum and maximum number of
86 // waves per CU when the number of minimum/maximum concurrent groups on the CU
87 // is limited by LDS usage or barrier resources.
88 if (MinWavesPerCU >= MaxWavesPerCU) {
89 std::swap(a&: MinWavesPerCU, b&: MaxWavesPerCU);
90 } else {
91 const unsigned WaveSlotsPerCU = WavesPerEU * getNumWorkGroupSIMDs();
92
93 // Look for a potential smaller group size than the maximum which decreases
94 // the concurrent number of waves on the CU for the same number of
95 // concurrent workgroups on the CU.
96 unsigned MinWavesPerCUForWGSize =
97 divideCeil(Numerator: WaveSlotsPerCU, Denominator: MinWGsPerCU + 1) * MinWGsPerCU;
98 if (MinWavesPerCU > MinWavesPerCUForWGSize) {
99 unsigned ExcessSlots = MinWavesPerCU - MinWavesPerCUForWGSize;
100 if (unsigned ExcessSlotsPerWG = ExcessSlots / MinWGsPerCU) {
101 // There may exist a smaller group size than the maximum that achieves
102 // the minimum number of waves per CU. This group size is the largest
103 // possible size that requires MaxWavesPerWG - E waves where E is
104 // maximized under the following constraints.
105 // 1. 0 <= E <= ExcessSlotsPerWG
106 // 2. (MaxWavesPerWG - E) * WaveSize >= MinWGSize
107 MinWavesPerCU -= MinWGsPerCU * std::min(a: ExcessSlotsPerWG,
108 b: MaxWavesPerWG - MinWavesPerWG);
109 }
110 }
111
112 // Look for a potential larger group size than the minimum which increases
113 // the concurrent number of waves on the CU for the same number of
114 // concurrent workgroups on the CU.
115 unsigned LeftoverSlots = WaveSlotsPerCU - MaxWGsPerCU * MinWavesPerWG;
116 if (unsigned LeftoverSlotsPerWG = LeftoverSlots / MaxWGsPerCU) {
117 // There may exist a larger group size than the minimum that achieves the
118 // maximum number of waves per CU. This group size is the smallest
119 // possible size that requires MinWavesPerWG + L waves where L is
120 // maximized under the following constraints.
121 // 1. 0 <= L <= LeftoverSlotsPerWG
122 // 2. (MinWavesPerWG + L - 1) * WaveSize <= MaxWGSize
123 MaxWavesPerCU += MaxWGsPerCU * std::min(a: LeftoverSlotsPerWG,
124 b: ((MaxWGSize - 1) / WaveSize) + 1 -
125 MinWavesPerWG);
126 }
127 }
128
129 // Return the minimum/maximum number of waves on any EU, assuming that all
130 // wavefronts are spread across all EUs as evenly as possible.
131 return {std::clamp(val: MinWavesPerCU / getNumWorkGroupSIMDs(), lo: 1U, hi: WavesPerEU),
132 std::clamp(val: divideCeil(Numerator: MaxWavesPerCU, Denominator: getNumWorkGroupSIMDs()), lo: 1U,
133 hi: WavesPerEU)};
134}
135
136std::pair<unsigned, unsigned> AMDGPUSubtarget::getOccupancyWithWorkGroupSizes(
137 const MachineFunction &MF) const {
138 const auto *MFI = MF.getInfo<SIMachineFunctionInfo>();
139 return getOccupancyWithWorkGroupSizes(LDSBytes: MFI->getLDSSize(), F: MF.getFunction());
140}
141
142std::pair<unsigned, unsigned>
143AMDGPUSubtarget::getDefaultFlatWorkGroupSize(CallingConv::ID CC) const {
144 switch (CC) {
145 case CallingConv::AMDGPU_VS:
146 case CallingConv::AMDGPU_LS:
147 case CallingConv::AMDGPU_HS:
148 case CallingConv::AMDGPU_ES:
149 case CallingConv::AMDGPU_GS:
150 case CallingConv::AMDGPU_PS:
151 return std::pair(1, getWavefrontSize());
152 default:
153 return std::pair(1u, getMaxFlatWorkGroupSize());
154 }
155}
156
157std::pair<unsigned, unsigned> AMDGPUSubtarget::getFlatWorkGroupSizes(
158 const Function &F) const {
159 // Default minimum/maximum flat work group sizes.
160 std::pair<unsigned, unsigned> Default =
161 getDefaultFlatWorkGroupSize(CC: F.getCallingConv());
162
163 // Requested minimum/maximum flat work group sizes.
164 std::pair<unsigned, unsigned> Requested = AMDGPU::getIntegerPairAttribute(
165 F, Name: "amdgpu-flat-work-group-size", Default);
166
167 // Make sure requested minimum is less than requested maximum.
168 if (Requested.first > Requested.second)
169 return Default;
170
171 // Make sure requested values do not violate subtarget's specifications.
172 if (Requested.first < getMinFlatWorkGroupSize())
173 return Default;
174 if (Requested.second > getMaxFlatWorkGroupSize())
175 return Default;
176
177 return Requested;
178}
179
180std::pair<unsigned, unsigned> AMDGPUSubtarget::getEffectiveWavesPerEU(
181 std::pair<unsigned, unsigned> RequestedWavesPerEU,
182 std::pair<unsigned, unsigned> FlatWorkGroupSizes, unsigned LDSBytes) const {
183 // Default minimum/maximum number of waves per EU. The range of flat workgroup
184 // sizes limits the achievable maximum, and we aim to support enough waves per
185 // EU so that we can concurrently execute all waves of a single workgroup of
186 // maximum size on a CU.
187 std::pair<unsigned, unsigned> Default = {
188 getWavesPerEUForWorkGroup(FlatWorkGroupSize: FlatWorkGroupSizes.second),
189 getOccupancyWithWorkGroupSizes(LDSBytes, FlatWorkGroupSizes).second};
190 Default.first = std::min(a: Default.first, b: Default.second);
191
192 // Make sure requested minimum is within the default range and lower than the
193 // requested maximum. The latter must not violate target specification.
194 if (RequestedWavesPerEU.first < Default.first ||
195 RequestedWavesPerEU.first > Default.second ||
196 RequestedWavesPerEU.first > RequestedWavesPerEU.second ||
197 RequestedWavesPerEU.second > getMaxWavesPerEU())
198 return Default;
199
200 // We cannot exceed maximum occupancy implied by flat workgroup size and LDS.
201 RequestedWavesPerEU.second =
202 std::min(a: RequestedWavesPerEU.second, b: Default.second);
203 return RequestedWavesPerEU;
204}
205
206std::pair<unsigned, unsigned>
207AMDGPUSubtarget::getWavesPerEU(const Function &F) const {
208 // Default/requested minimum/maximum flat work group sizes.
209 std::pair<unsigned, unsigned> FlatWorkGroupSizes = getFlatWorkGroupSizes(F);
210 // Minimum number of bytes allocated in the LDS.
211 unsigned LDSBytes =
212 AMDGPU::getIntegerPairAttribute(F, Name: "amdgpu-lds-size", Default: {0, UINT32_MAX},
213 /*OnlyFirstRequired=*/true)
214 .first;
215 return getWavesPerEU(FlatWorkGroupSizes, LDSBytes, F);
216}
217
218std::pair<unsigned, unsigned>
219AMDGPUSubtarget::getWavesPerEU(std::pair<unsigned, unsigned> FlatWorkGroupSizes,
220 unsigned LDSBytes, const Function &F) const {
221 // Default minimum/maximum number of waves per execution unit.
222 std::pair<unsigned, unsigned> Default(1, getMaxWavesPerEU());
223
224 // Requested minimum/maximum number of waves per execution unit.
225 std::pair<unsigned, unsigned> Requested =
226 AMDGPU::getIntegerPairAttribute(F, Name: "amdgpu-waves-per-eu", Default, OnlyFirstRequired: true);
227 return getEffectiveWavesPerEU(RequestedWavesPerEU: Requested, FlatWorkGroupSizes, LDSBytes);
228}
229
230std::optional<unsigned>
231AMDGPUSubtarget::getReqdWorkGroupSize(const Function &Kernel,
232 unsigned Dim) const {
233 auto *Node = Kernel.getMetadata(Kind: "reqd_work_group_size");
234 if (Node && Node->getNumOperands() == 3)
235 return mdconst::extract<ConstantInt>(MD: Node->getOperand(I: Dim))->getZExtValue();
236 return std::nullopt;
237}
238
239bool AMDGPUSubtarget::hasWavefrontsEvenlySplittingXDim(
240 const Function &F, bool RequiresUniformYZ) const {
241 auto *Node = F.getMetadata(Kind: "reqd_work_group_size");
242 if (!Node || Node->getNumOperands() != 3)
243 return false;
244 unsigned XLen =
245 mdconst::extract<ConstantInt>(MD: Node->getOperand(I: 0))->getZExtValue();
246 unsigned YLen =
247 mdconst::extract<ConstantInt>(MD: Node->getOperand(I: 1))->getZExtValue();
248 unsigned ZLen =
249 mdconst::extract<ConstantInt>(MD: Node->getOperand(I: 2))->getZExtValue();
250
251 bool Is1D = YLen <= 1 && ZLen <= 1;
252 bool IsXLargeEnough =
253 isPowerOf2_32(Value: XLen) && (!RequiresUniformYZ || XLen >= getWavefrontSize());
254 return Is1D || IsXLargeEnough;
255}
256
257bool AMDGPUSubtarget::isMesaKernel(const Function &F) const {
258 return isMesa3DOS() && !AMDGPU::isShader(CC: F.getCallingConv());
259}
260
261unsigned AMDGPUSubtarget::getMaxWorkitemID(const Function &Kernel,
262 unsigned Dimension) const {
263 std::optional<unsigned> ReqdSize = getReqdWorkGroupSize(Kernel, Dim: Dimension);
264 if (ReqdSize)
265 return *ReqdSize - 1;
266 return getFlatWorkGroupSizes(F: Kernel).second - 1;
267}
268
269bool AMDGPUSubtarget::isSingleLaneExecution(const Function &Func) const {
270 for (int I = 0; I < 3; ++I) {
271 if (getMaxWorkitemID(Kernel: Func, Dimension: I) > 0)
272 return false;
273 }
274
275 // If the function may call the WWM intrinsic, just return false as
276 // all threads will be active at some point
277 if (!Func.hasFnAttribute(Kind: "amdgpu-no-wwm"))
278 return false;
279
280 return true;
281}
282
283bool AMDGPUSubtarget::makeLIDRangeMetadata(Instruction *I) const {
284 Function *Kernel = I->getFunction();
285 unsigned MinSize = 0;
286 unsigned MaxSize = getFlatWorkGroupSizes(F: *Kernel).second;
287 bool IdQuery = false;
288
289 // If reqd_work_group_size is present it narrows value down.
290 if (auto *CI = dyn_cast<CallInst>(Val: I)) {
291 const Function *F = CI->getCalledFunction();
292 if (F) {
293 unsigned Dim = UINT_MAX;
294 switch (F->getIntrinsicID()) {
295 case Intrinsic::amdgcn_workitem_id_x:
296 case Intrinsic::r600_read_tidig_x:
297 IdQuery = true;
298 [[fallthrough]];
299 case Intrinsic::r600_read_local_size_x:
300 Dim = 0;
301 break;
302 case Intrinsic::amdgcn_workitem_id_y:
303 case Intrinsic::r600_read_tidig_y:
304 IdQuery = true;
305 [[fallthrough]];
306 case Intrinsic::r600_read_local_size_y:
307 Dim = 1;
308 break;
309 case Intrinsic::amdgcn_workitem_id_z:
310 case Intrinsic::r600_read_tidig_z:
311 IdQuery = true;
312 [[fallthrough]];
313 case Intrinsic::r600_read_local_size_z:
314 Dim = 2;
315 break;
316 default:
317 break;
318 }
319
320 if (Dim <= 3) {
321 std::optional<unsigned> ReqdSize = getReqdWorkGroupSize(Kernel: *Kernel, Dim);
322 if (ReqdSize)
323 MinSize = MaxSize = *ReqdSize;
324 }
325 }
326 }
327
328 if (!MaxSize)
329 return false;
330
331 // Range metadata is [Lo, Hi). For ID query we need to pass max size
332 // as Hi. For size query we need to pass Hi + 1.
333 if (IdQuery)
334 MinSize = 0;
335 else
336 ++MaxSize;
337
338 APInt Lower{32, MinSize};
339 APInt Upper{32, MaxSize};
340 if (auto *CI = dyn_cast<CallBase>(Val: I)) {
341 ConstantRange Range(Lower, Upper);
342 CI->addRangeRetAttr(CR: Range);
343 } else {
344 MDBuilder MDB(I->getContext());
345 MDNode *MaxWorkGroupSizeRange = MDB.createRange(Lo: Lower, Hi: Upper);
346 I->setMetadata(KindID: LLVMContext::MD_range, Node: MaxWorkGroupSizeRange);
347 }
348 return true;
349}
350
351unsigned AMDGPUSubtarget::getImplicitArgNumBytes(const Function &F) const {
352
353 // We don't allocate the segment if we know the implicit arguments weren't
354 // used, even if the ABI implies we need them.
355 if (F.hasFnAttribute(Kind: "amdgpu-no-implicitarg-ptr"))
356 return 0;
357
358 if (isMesaKernel(F))
359 return 16;
360
361 // Assume all implicit inputs are used by default
362 const Module *M = F.getParent();
363 unsigned NBytes =
364 AMDGPU::getAMDHSACodeObjectVersion(M: *M) >= AMDGPU::AMDHSA_COV5 ? 256 : 56;
365 return F.getFnAttributeAsParsedInteger(Kind: "amdgpu-implicitarg-num-bytes",
366 Default: NBytes);
367}
368
369uint64_t AMDGPUSubtarget::getExplicitKernArgSize(const Function &F,
370 Align &MaxAlign) const {
371 assert(F.getCallingConv() == CallingConv::AMDGPU_KERNEL ||
372 F.getCallingConv() == CallingConv::SPIR_KERNEL);
373
374 const DataLayout &DL = F.getDataLayout();
375 uint64_t ExplicitArgBytes = 0;
376 MaxAlign = Align(1);
377
378 for (const Argument &Arg : F.args()) {
379 if (Arg.hasAttribute(Kind: "amdgpu-hidden-argument"))
380 continue;
381
382 const bool IsByRef = Arg.hasByRefAttr();
383 Type *ArgTy = IsByRef ? Arg.getParamByRefType() : Arg.getType();
384 Align Alignment = DL.getValueOrABITypeAlignment(
385 Alignment: IsByRef ? Arg.getParamAlign() : std::nullopt, Ty: ArgTy);
386 uint64_t AllocSize = DL.getTypeAllocSize(Ty: ArgTy);
387 ExplicitArgBytes = alignTo(Size: ExplicitArgBytes, A: Alignment) + AllocSize;
388 MaxAlign = std::max(a: MaxAlign, b: Alignment);
389 }
390
391 return ExplicitArgBytes;
392}
393
394unsigned AMDGPUSubtarget::getKernArgSegmentSize(const Function &F,
395 Align &MaxAlign) const {
396 if (F.getCallingConv() != CallingConv::AMDGPU_KERNEL &&
397 F.getCallingConv() != CallingConv::SPIR_KERNEL)
398 return 0;
399
400 uint64_t ExplicitArgBytes = getExplicitKernArgSize(F, MaxAlign);
401
402 unsigned ExplicitOffset = getExplicitKernelArgOffset();
403
404 uint64_t TotalSize = ExplicitOffset + ExplicitArgBytes;
405 unsigned ImplicitBytes = getImplicitArgNumBytes(F);
406 if (ImplicitBytes != 0) {
407 const Align Alignment = getAlignmentForImplicitArgPtr();
408 TotalSize = alignTo(Size: ExplicitArgBytes, A: Alignment) + ImplicitBytes;
409 MaxAlign = std::max(a: MaxAlign, b: Alignment);
410 }
411
412 // Being able to dereference past the end is useful for emitting scalar loads.
413 return alignTo(Value: TotalSize, Align: 4);
414}
415
416AMDGPUDwarfFlavour AMDGPUSubtarget::getAMDGPUDwarfFlavour() const {
417 return getWavefrontSize() == 32 ? AMDGPUDwarfFlavour::Wave32
418 : AMDGPUDwarfFlavour::Wave64;
419}
420
421const AMDGPUSubtarget &AMDGPUSubtarget::get(const MachineFunction &MF) {
422 if (MF.getTarget().getTargetTriple().isAMDGCN())
423 return static_cast<const AMDGPUSubtarget&>(MF.getSubtarget<GCNSubtarget>());
424 return static_cast<const AMDGPUSubtarget &>(MF.getSubtarget<R600Subtarget>());
425}
426
427const AMDGPUSubtarget &AMDGPUSubtarget::get(const TargetMachine &TM, const Function &F) {
428 if (TM.getTargetTriple().isAMDGCN())
429 return static_cast<const AMDGPUSubtarget&>(TM.getSubtarget<GCNSubtarget>(F));
430 return static_cast<const AMDGPUSubtarget &>(
431 TM.getSubtarget<R600Subtarget>(F));
432}
433