LLVM 24.0.0git
VerifierAMDGPU.cpp
Go to the documentation of this file.
1//===-- VerifierAMDGPU.cpp - AMDGPU-specific IR verification ---------------==//
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// This file contains AMDGPU-specific IR verification logic that was extracted
10// from Verifier.cpp for code organization purposes only. These checks are
11// always compiled and linked as part of LLVMCore — this is not a target-
12// dependent IR verifier, which would require a different design.
13//
14// This file should only contain checks for AMDGPU-specific IR constructs
15// (e.g. amdgcn intrinsics, AMDGPU address spaces). It must not contain
16// checks for generic IR that might behave differently under AMDGPU.
17//
18//===----------------------------------------------------------------------===//
19
20#include "VerifierInternal.h"
22#include "llvm/IR/CallingConv.h"
23#include "llvm/IR/Constants.h"
25#include "llvm/IR/Function.h"
27#include "llvm/IR/IntrinsicsAMDGPU.h"
29
30using namespace llvm;
31
32#define Check(C, ...) \
33 do { \
34 if (!(C)) { \
35 VS.CheckFailed(__VA_ARGS__); \
36 return; \
37 } \
38 } while (false)
39
42 const MDNode *Op) {
43 StringRef FlagName = ID->getString();
44 if (!FlagName.consume_front("amdgpu."))
45 return;
46
47 if (FlagName == "buffer.oob.mode" || FlagName == "tbuffer.oob.mode") {
48 Check(MFB == Module::Max,
49 "'" + ID->getString() +
50 "' module flag must use 'max' merge behaviour");
53 Check(Value, "'" + ID->getString() +
54 "' module flag must have a constant integer value");
55 Check(Value->getZExtValue() <= 2,
56 "'" + ID->getString() + "' module flag must be 0, 1, or 2");
57 return;
58 }
59
60 if (FlagName == "xnack" || FlagName == "sramecc") {
61 Check(MFB == Module::Error,
62 "'" + ID->getString() +
63 "' module flag must use 'error' merge behaviour");
66 Check(Value, "'" + ID->getString() +
67 "' module flag must have a constant integer value");
68 Check(Value->getZExtValue() <= 1,
69 "'" + ID->getString() + "' module flag must be 0 or 1");
70 return;
71 }
72}
73
74// Verify that when a function has !reqd_work_group_size metadata, it also has
75// an amdgpu-flat-work-group-size attribute that matches the product of the
76// reqd_work_group_size operands.
78 const Function &F) {
79 // This is not required for other targets so we only check for AMDGPU.
80 if (!VS.TT.isAMDGPU())
81 return;
82
83 MDNode *ReqdWorkGroupSize = F.getMetadata("reqd_work_group_size");
84 if (!ReqdWorkGroupSize || ReqdWorkGroupSize->getNumOperands() != 3)
85 return;
86
87 uint64_t Product = 1;
88 for (const MDOperand &Op : ReqdWorkGroupSize->operands()) {
90 if (!C || C->getValue().getActiveBits() > 64)
91 return;
92 uint64_t Dim = C->getZExtValue();
93 if (Dim != 0 && Product > std::numeric_limits<uint64_t>::max() / Dim)
94 return;
95 Product *= Dim;
96 }
97
98 Attribute FlatWorkGroupSize = F.getFnAttribute("amdgpu-flat-work-group-size");
99 if (!FlatWorkGroupSize.isValid()) {
100 VS.CheckFailed("reqd_work_group_size requires amdgpu-flat-work-group-size",
101 &F, ReqdWorkGroupSize);
102 return;
103 }
104
105 if (!FlatWorkGroupSize.isStringAttribute()) {
106 VS.CheckFailed("amdgpu-flat-work-group-size must be a string attribute",
107 &F);
108 return;
109 }
110
111 StringRef AttrValue = FlatWorkGroupSize.getValueAsString();
112 std::pair<StringRef, StringRef> Values = AttrValue.split(',');
113 uint64_t Min = 0;
114 uint64_t Max = 0;
115 bool Parsed = !Values.second.contains(',') &&
116 llvm::to_integer(Values.first.trim(), Min) &&
117 llvm::to_integer(Values.second.trim(), Max);
118 if (!Parsed) {
119 VS.CheckFailed("amdgpu-flat-work-group-size must be a pair of unsigned "
120 "integers",
121 &F);
122 return;
123 }
124
125 if (Min != Product || Max != Product) {
126 VS.CheckFailed("amdgpu-flat-work-group-size must equal the product of "
127 "reqd_work_group_size operands",
128 &F, ReqdWorkGroupSize);
129 }
130}
131
136
138 // This is not required for other targets so we only check for AMDGPU.
139 if (!VS.TT.isAMDGPU())
140 return;
141
143 VS.CheckFailed("alloca on amdgpu must be in addrspace(5)", &AI);
144}
145
147 switch (ID) {
148 default:
149 return false;
150 case Intrinsic::amdgcn_kill:
151 return true;
152 }
153}
154
156 CallBase &Call) {
157 switch (ID) {
158 default:
159 return;
160 case Intrinsic::amdgcn_kill: {
161 if (auto *CBI = dyn_cast<CallBrInst>(&Call)) {
162 Check(CBI->getNumIndirectDests() == 1,
163 "callbr amdgcn_kill only supports one indirect dest");
164 // We assume that amdgcn_unreachable is only introduced by
165 // AMDGPUUnifyDivergentExitNodes, which replaces the block's original
166 // unreachable terminator by a call to amdgcn_unreachable + a return.
167 const Instruction *Term = CBI->getIndirectDest(0)->getTerminator();
168 const CallInst *CI =
169 Term ? dyn_cast_if_present<CallInst>(Term->getPrevNode()) : nullptr;
171 (CI && CI->getIntrinsicID() == Intrinsic::amdgcn_unreachable),
172 "callbr amdgcn_kill indirect dest needs to be unreachable");
173 }
174 break;
175 }
176 case Intrinsic::amdgcn_cs_chain: {
177 CallingConv::ID CallerCC = Call.getCaller()->getCallingConv();
178 switch (CallerCC) {
187 break;
188 default:
189 VS.CheckFailed("Intrinsic cannot be called from functions with this "
190 "calling convention",
191 &Call);
192 break;
193 }
194
195 Check(Call.paramHasAttr(2, Attribute::InReg),
196 "SGPR arguments must have the `inreg` attribute", &Call);
197 Check(!Call.paramHasAttr(3, Attribute::InReg),
198 "VGPR arguments must not have the `inreg` attribute", &Call);
199
200 ConstantInt *FlagsArg = cast<ConstantInt>(Call.getArgOperand(4));
201 Check(FlagsArg->getValue().ult(2),
202 "flags must be 0 or 1 for llvm.amdgcn.cs.chain", &Call);
203
204 Instruction *Next = Call.getNextNode();
205 bool IsAMDUnreachable = isa_and_nonnull<IntrinsicInst>(Next) &&
206 cast<IntrinsicInst>(Next)->getIntrinsicID() ==
207 Intrinsic::amdgcn_unreachable;
208 Check(Next && (isa<UnreachableInst>(Next) || IsAMDUnreachable),
209 "llvm.amdgcn.cs.chain must be followed by unreachable", &Call);
210 break;
211 }
212 case Intrinsic::amdgcn_init_exec_from_input: {
213 const Argument *Arg = dyn_cast<Argument>(Call.getOperand(0));
214 Check(Arg && Arg->hasInRegAttr(),
215 "only inreg arguments to the parent function are valid as inputs to "
216 "this intrinsic",
217 &Call);
218 break;
219 }
220 case Intrinsic::amdgcn_set_inactive_chain_arg: {
221 CallingConv::ID CallerCC = Call.getCaller()->getCallingConv();
222 switch (CallerCC) {
225 break;
226 default:
227 VS.CheckFailed("Intrinsic can only be used from functions with the "
228 "amdgpu_cs_chain or amdgpu_cs_chain_preserve "
229 "calling conventions",
230 &Call);
231 break;
232 }
233
234 unsigned InactiveIdx = 1;
235 Check(!Call.paramHasAttr(InactiveIdx, Attribute::InReg),
236 "Value for inactive lanes must not have the `inreg` attribute",
237 &Call);
238 Check(isa<Argument>(Call.getArgOperand(InactiveIdx)),
239 "Value for inactive lanes must be a function argument", &Call);
240 Check(!cast<Argument>(Call.getArgOperand(InactiveIdx))->hasInRegAttr(),
241 "Value for inactive lanes must be a VGPR function argument", &Call);
242 break;
243 }
244 case Intrinsic::amdgcn_call_whole_wave: {
245 Function *F = dyn_cast<Function>(Call.getArgOperand(0));
246 Check(F, "Indirect whole wave calls are not allowed", &Call);
247
248 CallingConv::ID CC = F->getCallingConv();
250 "Callee must have the amdgpu_gfx_whole_wave calling convention",
251 &Call);
252
253 Check(!F->isVarArg(), "Variadic whole wave calls are not allowed", &Call);
254
255 Check(Call.arg_size() == F->arg_size(),
256 "Call argument count must match callee argument count", &Call);
257
258 Check(F->arg_begin()->getType()->isIntegerTy(1),
259 "Callee must have i1 as its first argument", &Call);
260 for (auto [CallArg, FuncArg] :
261 drop_begin(zip_equal(Call.args(), F->args()))) {
262 Check(CallArg->getType() == FuncArg.getType(),
263 "Argument types must match", &Call);
264
265 Check(Call.paramHasAttr(FuncArg.getArgNo(), Attribute::InReg) ==
266 FuncArg.hasInRegAttr(),
267 "Argument inreg attributes must match", &Call);
268 }
269 break;
270 }
271 case Intrinsic::amdgcn_s_prefetch_data: {
272 Check(
274 Call.getArgOperand(0)->getType()->getPointerAddressSpace()),
275 "llvm.amdgcn.s.prefetch.data only supports global or constant memory");
276 break;
277 }
278 case Intrinsic::amdgcn_load_to_lds:
279 case Intrinsic::amdgcn_load_async_to_lds:
280 case Intrinsic::amdgcn_global_load_lds:
281 case Intrinsic::amdgcn_global_load_async_lds:
282 case Intrinsic::amdgcn_raw_buffer_load_lds:
283 case Intrinsic::amdgcn_raw_buffer_load_async_lds:
284 case Intrinsic::amdgcn_raw_ptr_buffer_load_lds:
285 case Intrinsic::amdgcn_raw_ptr_buffer_load_async_lds:
286 case Intrinsic::amdgcn_struct_buffer_load_lds:
287 case Intrinsic::amdgcn_struct_buffer_load_async_lds:
288 case Intrinsic::amdgcn_struct_ptr_buffer_load_lds:
289 case Intrinsic::amdgcn_struct_ptr_buffer_load_async_lds: {
290 uint64_t Size = cast<ConstantInt>(Call.getArgOperand(2))->getZExtValue();
291 Check(Size == 1 || Size == 2 || Size == 4 || Size == 12 || Size == 16,
292 "invalid data size for load-to-LDS intrinsic; must be 1, 2, 4, 12, "
293 "or 16",
294 &Call);
295 break;
296 }
297 case Intrinsic::amdgcn_mfma_scale_f32_16x16x128_f8f6f4:
298 case Intrinsic::amdgcn_mfma_scale_f32_32x32x64_f8f6f4: {
299 Value *Src0 = Call.getArgOperand(0);
300 Value *Src1 = Call.getArgOperand(1);
301
302 uint64_t CBSZ = cast<ConstantInt>(Call.getArgOperand(3))->getZExtValue();
303 uint64_t BLGP = cast<ConstantInt>(Call.getArgOperand(4))->getZExtValue();
304 Check(CBSZ <= 4, "invalid value for cbsz format", Call,
305 Call.getArgOperand(3));
306 Check(BLGP <= 4, "invalid value for blgp format", Call,
307 Call.getArgOperand(4));
308
309 auto GetFormatNumRegs = [](unsigned FormatVal) {
310 switch (FormatVal) {
311 case 0:
312 case 1:
313 return 8u;
314 case 2:
315 case 3:
316 return 6u;
317 case 4:
318 return 4u;
319 default:
320 llvm_unreachable("invalid format value");
321 }
322 };
323
324 auto IsValidSrcASrcBVector = [](FixedVectorType *Ty) {
325 if (!Ty || !Ty->getElementType()->isIntegerTy(32))
326 return false;
327 unsigned NumElts = Ty->getNumElements();
328 return NumElts == 4 || NumElts == 6 || NumElts == 8;
329 };
330
333 Check(IsValidSrcASrcBVector(Src0Ty),
334 "operand 0 must be 4, 6 or 8 element i32 vector", &Call, Src0);
335 Check(IsValidSrcASrcBVector(Src1Ty),
336 "operand 1 must be 4, 6 or 8 element i32 vector", &Call, Src1);
337
338 Check(Src0Ty->getNumElements() >= GetFormatNumRegs(CBSZ),
339 "invalid vector type for format", &Call, Src0, Call.getArgOperand(3));
340 Check(Src1Ty->getNumElements() >= GetFormatNumRegs(BLGP),
341 "invalid vector type for format", &Call, Src1, Call.getArgOperand(5));
342 break;
343 }
344 case Intrinsic::amdgcn_wmma_f32_16x16x128_f8f6f4:
345 case Intrinsic::amdgcn_wmma_scale_f32_16x16x128_f8f6f4:
346 case Intrinsic::amdgcn_wmma_scale16_f32_16x16x128_f8f6f4: {
347 Value *Src0 = Call.getArgOperand(1);
348 Value *Src1 = Call.getArgOperand(3);
349
350 unsigned FmtA = cast<ConstantInt>(Call.getArgOperand(0))->getZExtValue();
351 unsigned FmtB = cast<ConstantInt>(Call.getArgOperand(2))->getZExtValue();
352 Check(FmtA <= 4, "invalid value for matrix format", Call,
353 Call.getArgOperand(0));
354 Check(FmtB <= 4, "invalid value for matrix format", Call,
355 Call.getArgOperand(2));
356
357 auto GetFormatNumRegs = [](unsigned FormatVal) {
358 switch (FormatVal) {
359 case 0:
360 case 1:
361 return 16u;
362 case 2:
363 case 3:
364 return 12u;
365 case 4:
366 return 8u;
367 default:
368 llvm_unreachable("invalid format value");
369 }
370 };
371
372 auto IsValidSrcASrcBVector = [](FixedVectorType *Ty) {
373 if (!Ty || !Ty->getElementType()->isIntegerTy(32))
374 return false;
375 unsigned NumElts = Ty->getNumElements();
376 return NumElts == 16 || NumElts == 12 || NumElts == 8;
377 };
378
381 Check(IsValidSrcASrcBVector(Src0Ty),
382 "operand 1 must be 8, 12 or 16 element i32 vector", &Call, Src0);
383 Check(IsValidSrcASrcBVector(Src1Ty),
384 "operand 3 must be 8, 12 or 16 element i32 vector", &Call, Src1);
385
386 Check(Src0Ty->getNumElements() >= GetFormatNumRegs(FmtA),
387 "invalid vector type for format", &Call, Src0, Call.getArgOperand(0));
388 Check(Src1Ty->getNumElements() >= GetFormatNumRegs(FmtB),
389 "invalid vector type for format", &Call, Src1, Call.getArgOperand(2));
390 break;
391 }
392 case Intrinsic::amdgcn_cooperative_atomic_load_32x4B:
393 case Intrinsic::amdgcn_cooperative_atomic_load_16x8B:
394 case Intrinsic::amdgcn_cooperative_atomic_load_8x16B:
395 case Intrinsic::amdgcn_cooperative_atomic_store_32x4B:
396 case Intrinsic::amdgcn_cooperative_atomic_store_16x8B:
397 case Intrinsic::amdgcn_cooperative_atomic_store_8x16B: {
398 Value *PtrArg = Call.getArgOperand(0);
399 const unsigned AS = PtrArg->getType()->getPointerAddressSpace();
401 "cooperative atomic intrinsics require a generic or global pointer",
402 &Call, PtrArg);
403
405 cast<MetadataAsValue>(Call.getArgOperand(Call.arg_size() - 1));
406 MDNode *MD = cast<MDNode>(Op->getMetadata());
407 Check((MD->getNumOperands() == 1) && isa<MDString>(MD->getOperand(0)),
408 "cooperative atomic intrinsics require that the last argument is a "
409 "metadata string",
410 &Call, Op);
411 break;
412 }
413 case Intrinsic::amdgcn_av_load_b128:
414 case Intrinsic::amdgcn_av_store_b128: {
416 cast<MetadataAsValue>(Call.getArgOperand(Call.arg_size() - 1));
417 MDNode *MD = dyn_cast<MDNode>(Op->getMetadata());
418 Check(MD && (MD->getNumOperands() == 1) && isa<MDString>(MD->getOperand(0)),
419 "the last argument to av load/store intrinsics must be a "
420 "metadata string",
421 &Call, Op);
422 break;
423 }
424 }
425}
426
427#undef Check
AMDGPU address space definition.
static GCRegistry::Add< ShadowStackGC > C("shadow-stack", "Very portable GC for uncooperative code generators")
This file contains the declarations for the subclasses of Constant, which represent the different fla...
#define F(x, y, z)
Definition MD5.cpp:54
This file contains some functions that are useful when dealing with strings.
#define Check(C,...)
static void verifyAMDGPUReqdWorkGroupSize(VerifierSupport &VS, const Function &F)
bool ult(const APInt &RHS) const
Unsigned less than comparison.
Definition APInt.h:1120
an instruction to allocate memory on the stack
unsigned getAddressSpace() const
Return the address space for the allocation.
This class represents an incoming formal argument to a Function.
Definition Argument.h:32
LLVM_ABI bool hasInRegAttr() const
Return true if this argument has the inreg attribute.
Definition Function.cpp:287
Functions, function parameters, and return types can have attributes to indicate how they should be t...
Definition Attributes.h:105
LLVM_ABI bool isStringAttribute() const
Return true if the attribute is a string (target-dependent) attribute.
LLVM_ABI StringRef getValueAsString() const
Return the attribute's value as a string.
bool isValid() const
Return true if the attribute is any kind of attribute.
Definition Attributes.h:261
Base class for all callable instructions (InvokeInst and CallInst) Holds everything related to callin...
LLVM_ABI Intrinsic::ID getIntrinsicID() const
Returns the intrinsic ID of the intrinsic called or Intrinsic::not_intrinsic if the called function i...
This class represents a function call, abstracting a target machine's calling convention.
This is the shared class of boolean and integer constants.
Definition Constants.h:87
const APInt & getValue() const
Return the constant as an APInt value reference.
Definition Constants.h:159
Class to represent fixed width SIMD vectors.
Metadata node.
Definition Metadata.h:1069
const MDOperand & getOperand(unsigned I) const
Definition Metadata.h:1426
unsigned getNumOperands() const
Return number of MDNode operands.
Definition Metadata.h:1432
Tracking metadata reference owned by Metadata.
Definition Metadata.h:891
A single uniqued string.
Definition Metadata.h:722
Metadata wrapper in the Value hierarchy.
Definition Metadata.h:184
ModFlagBehavior
This enumeration defines the supported behaviors of module flags.
Definition Module.h:117
@ Error
Emits an error if two values disagree, otherwise the resulting value is that of the operands.
Definition Module.h:120
@ Max
Takes the max of the two values, which are required to be integers.
Definition Module.h:149
Represent a constant reference to a string, i.e.
Definition StringRef.h:56
std::pair< StringRef, StringRef > split(char Separator) const
Split into two substrings around the first occurrence of a separator character.
Definition StringRef.h:736
bool consume_front(char Prefix)
Returns true if this StringRef has the given prefix and removes that prefix.
Definition StringRef.h:661
LLVM_ABI unsigned getPointerAddressSpace() const
Get the address space of this pointer or pointer vector type.
LLVM Value Representation.
Definition Value.h:75
Type * getType() const
All values are typed, get the type of this value.
Definition Value.h:255
CallInst * Call
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
@ FLAT_ADDRESS
Address space for flat memory.
@ GLOBAL_ADDRESS
Address space for global memory (RAT0, VTX0).
@ PRIVATE_ADDRESS
Address space for private memory.
bool isFlatGlobalAddrSpace(unsigned AS)
unsigned ID
LLVM IR allows to use arbitrary numbers as calling convention identifiers.
Definition CallingConv.h:24
@ AMDGPU_CS
Used for Mesa/AMDPAL compute shaders.
@ AMDGPU_VS
Used for Mesa vertex shaders, or AMDPAL last shader stage before rasterization (vertex shader if tess...
@ AMDGPU_CS_ChainPreserve
Used on AMDGPUs to give the middle-end more control over argument placement.
@ AMDGPU_HS
Used for Mesa/AMDPAL hull shaders (= tessellation control shaders).
@ AMDGPU_GS
Used for Mesa/AMDPAL geometry shaders.
@ AMDGPU_CS_Chain
Used on AMDGPUs to give the middle-end more control over argument placement.
@ AMDGPU_ES
Used for AMDPAL shader stage before geometry shader if geometry is in use.
@ AMDGPU_LS
Used for AMDPAL vertex shader if tessellation is in use.
std::enable_if_t< detail::IsValidPointer< X, Y >::value, X * > dyn_extract_or_null(Y &&MD)
Extract a Value from Metadata, if any, allowing null.
Definition Metadata.h:709
std::enable_if_t< detail::IsValidPointer< X, Y >::value, X * > dyn_extract(Y &&MD)
Extract a Value from Metadata, if any.
Definition Metadata.h:696
This is an optimization pass for GlobalISel generic memory operations.
auto drop_begin(T &&RangeOrContainer, size_t N=1)
Return a range covering RangeOrContainer with the first N elements excluded.
Definition STLExtras.h:315
detail::zippy< detail::zip_first, T, U, Args... > zip_equal(T &&t, U &&u, Args &&...args)
zip iterator that assumes that all iteratees have the same length.
Definition STLExtras.h:840
RelativeUniformCounterPtr Values
Definition InstrProf.h:91
decltype(auto) dyn_cast(const From &Val)
dyn_cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:643
auto dyn_cast_if_present(const Y &Val)
dyn_cast_if_present<X> - Functionally identical to dyn_cast, except that a null (or none in the case ...
Definition Casting.h:732
void verifyAMDGPUAlloca(VerifierSupport &VS, const AllocaInst &AI)
bool isa_and_nonnull(const Y &Val)
Definition Casting.h:676
void verifyAMDGPUFunctionMetadata(VerifierSupport &VS, const Function &F)
void verifyAMDGPUIntrinsicCall(VerifierSupport &VS, Intrinsic::ID ID, CallBase &Call)
bool isa(const From &Val)
isa<X> - Return true if the parameter to the template is an instance of one of the template type argu...
Definition Casting.h:547
DWARFExpression::Operation Op
decltype(auto) cast(const From &Val)
cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:559
RelativeUniformCounterPtr ValuesPtrExpr VTableAddr Next
Definition InstrProf.h:147
void verifyAMDGPUModuleFlag(VerifierSupport &VS, const MDString *ID, Module::ModFlagBehavior MFB, const MDNode *Op)
bool to_integer(StringRef S, N &Num, unsigned Base=0)
Convert the string S to an integer of the specified type using the radix Base. If Base is 0,...
bool isAMDGPUCallBrIntrinsic(Intrinsic::ID ID)