clang 24.0.0git
SemaAMDGPU.cpp
Go to the documentation of this file.
1//===------ SemaAMDGPU.cpp ------- AMDGPU target-specific routines --------===//
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 implements semantic analysis functions specific to AMDGPU.
10//
11//===----------------------------------------------------------------------===//
12
14#include "clang/AST/Decl.h"
16#include "clang/AST/Expr.h"
21#include "clang/Sema/Scope.h"
22#include "clang/Sema/Sema.h"
23#include "llvm/ADT/SmallVector.h"
24#include "llvm/ADT/StringExtras.h"
25#include "llvm/ADT/StringMap.h"
26#include "llvm/Support/AMDGPUAddrSpace.h"
27#include "llvm/Support/AMDGPUAsyncStages.h"
28#include "llvm/Support/AtomicOrdering.h"
29#include "llvm/TargetParser/AMDGPUTargetParser.h"
30#include "llvm/TargetParser/AtomicScope.h"
31#include <cstdint>
32#include <utility>
33
34namespace clang {
35
37
39 unsigned BuiltinID,
40 CallExpr *TheCall) {
41 const auto *FD = SemaRef.getCurFunctionDecl(/*AllowLambda=*/true);
42 assert(FD && "AMDGPU builtins should not be used outside of a function");
43 llvm::StringMap<bool> CallerFeatureMap;
44 getASTContext().getFunctionFeatureMap(CallerFeatureMap, FD);
45 bool HasGFX950Insts =
46 Builtin::evaluateRequiredTargetFeatures("gfx950-insts", CallerFeatureMap);
47
48 switch (BuiltinID) {
49 case AMDGPU::BI__builtin_amdgcn_raw_ptr_buffer_load_lds:
50 case AMDGPU::BI__builtin_amdgcn_raw_ptr_buffer_load_async_lds:
51 case AMDGPU::BI__builtin_amdgcn_struct_ptr_buffer_load_lds:
52 case AMDGPU::BI__builtin_amdgcn_struct_ptr_buffer_load_async_lds:
53 case AMDGPU::BI__builtin_amdgcn_load_to_lds:
54 case AMDGPU::BI__builtin_amdgcn_load_async_to_lds:
55 case AMDGPU::BI__builtin_amdgcn_global_load_lds:
56 case AMDGPU::BI__builtin_amdgcn_global_load_async_lds: {
57 constexpr const int SizeIdx = 2;
58 llvm::APSInt Size;
59 Expr *ArgExpr = TheCall->getArg(SizeIdx);
60 // Check for instantiation-dependent expressions (e.g., involving template
61 // parameters). These will be checked again during template instantiation.
62 if (ArgExpr->isInstantiationDependent())
63 return false;
64 [[maybe_unused]] ExprResult R =
65 SemaRef.VerifyIntegerConstantExpression(ArgExpr, &Size);
66 assert(!R.isInvalid());
67 switch (Size.getSExtValue()) {
68 case 1:
69 case 2:
70 case 4:
71 return false;
72 case 12:
73 case 16: {
74 if (HasGFX950Insts)
75 return false;
76 [[fallthrough]];
77 }
78 default:
79 SemaRef.targetDiag(ArgExpr->getExprLoc(),
80 diag::err_amdgcn_load_lds_size_invalid_value)
81 << ArgExpr->getSourceRange();
82 SemaRef.targetDiag(ArgExpr->getExprLoc(),
83 diag::note_amdgcn_load_lds_size_valid_value)
84 << HasGFX950Insts << ArgExpr->getSourceRange();
85 return true;
86 }
87 }
88 case AMDGPU::BI__builtin_amdgcn_uicmp:
89 case AMDGPU::BI__builtin_amdgcn_uicmpl:
90 case AMDGPU::BI__builtin_amdgcn_sicmp:
91 case AMDGPU::BI__builtin_amdgcn_sicmpl:
92 case AMDGPU::BI__builtin_amdgcn_fcmp:
93 case AMDGPU::BI__builtin_amdgcn_fcmpf: {
94 // These builtins are deprecated in favor of
95 // __builtin_amdgcn_ballot_{w32|w64}. Suggest the replacement matching the
96 // wavefront size of the calling function.
97 bool IsWave32 = Builtin::evaluateRequiredTargetFeatures("wavefrontsize32",
98 CallerFeatureMap);
99 Diag(TheCall->getBeginLoc(), diag::warn_deprecated_builtin)
101 << (IsWave32 ? "__builtin_amdgcn_ballot_w32"
102 : "__builtin_amdgcn_ballot_w64");
103 return false;
104 }
105 case AMDGPU::BI__builtin_amdgcn_get_fpenv:
106 case AMDGPU::BI__builtin_amdgcn_set_fpenv:
107 return false;
108 case AMDGPU::BI__builtin_amdgcn_atomic_inc32:
109 case AMDGPU::BI__builtin_amdgcn_atomic_inc64:
110 case AMDGPU::BI__builtin_amdgcn_atomic_dec32:
111 case AMDGPU::BI__builtin_amdgcn_atomic_dec64:
112 case AMDGPU::BI__builtin_amdgcn_fence: {
113 bool IsFence = BuiltinID == AMDGPU::BI__builtin_amdgcn_fence;
114 unsigned OrderIndex = IsFence ? 0 : 2;
115 unsigned ScopeIndex = IsFence ? 1 : 3;
116 Expr *OrderExpr = TheCall->getArg(OrderIndex);
117 Expr *ScopeExpr = TheCall->getArg(ScopeIndex);
118
119 // Checks requiring constant evaluation are deferred until instantiation.
120 if (OrderExpr->isInstantiationDependent() ||
121 ScopeExpr->isInstantiationDependent())
122 return false;
123
124 Expr::EvalResult OrderResult;
125 if (!OrderExpr->EvaluateAsInt(OrderResult, getASTContext()))
126 return Diag(OrderExpr->getExprLoc(), diag::err_typecheck_expect_int)
127 << OrderExpr->getType();
128 uint64_t Ord = OrderResult.Val.getInt().getZExtValue();
129
130 // Check validity of memory ordering as per C11 / C++11's memory model.
131 // Only fence needs check. Atomic dec/inc allow all memory orders.
132 // An invalid ordering is not ill-formed despite being UB, so only emit a
133 // warning.
134 if (!llvm::isValidAtomicOrderingCABI(Ord) ||
135 (IsFence && (Ord == (uint64_t)llvm::AtomicOrderingCABI::relaxed ||
136 Ord == (uint64_t)llvm::AtomicOrderingCABI::consume)))
137 Diag(OrderExpr->getBeginLoc(),
138 diag::warn_atomic_op_has_invalid_memory_order)
139 << 0 << OrderExpr->getSourceRange();
140
141 Expr::EvalResult ScopeResult;
142 // Check that sync scope is a constant literal
143 if (!ScopeExpr->EvaluateAsConstantExpr(ScopeResult, getASTContext()))
144 return Diag(ScopeExpr->getExprLoc(), diag::err_expr_not_string_literal)
145 << ScopeExpr->getType();
146
147 // Reject any string that is not a valid synchronization scope name.
148 std::optional<std::string> ScopeName =
149 ScopeExpr->tryEvaluateString(getASTContext());
150 const llvm::Triple &TT = TI.getTriple();
151 if (ScopeName && !llvm::parseAtomicScopeIRString(TT, *ScopeName)) {
152 return Diag(ScopeExpr->getExprLoc(), diag::err_invalid_sync_scope)
153 << *ScopeName << ScopeExpr->getSourceRange();
154 }
155
156 return false;
157 }
158 case AMDGPU::BI__builtin_amdgcn_flat_prefetch:
159 case AMDGPU::BI__builtin_amdgcn_global_prefetch: {
160 // Only th (bits 0-2, not 7), scope (bits 3-4) and nv (bit 5) may be set.
161 llvm::APSInt CPol;
162 if (SemaRef.BuiltinConstantArg(TheCall, /*ArgNum=*/1, CPol))
163 return true;
164 if ((CPol.getZExtValue() & 0x7) != 0x7)
165 return false;
166 Expr *ArgExpr = TheCall->getArg(1);
167 SemaRef.targetDiag(ArgExpr->getExprLoc(),
168 diag::err_amdgcn_prefetch_reserved_th)
169 << ArgExpr->getSourceRange();
170 return true;
171 }
172 case AMDGPU::BI__builtin_amdgcn_s_wait_event: {
173 llvm::APSInt Result;
174 if (SemaRef.BuiltinConstantArg(TheCall, 0, Result))
175 return true;
176
178 "gfx12-insts", CallerFeatureMap);
179
180 // gfx11 -> gfx12 changed the interpretation of the bitmask. gfx12 inverted
181 // the intepretation for export_ready, but shifted the used bit by 1. Thus
182 // waiting for the export_ready event can use a value of 2 universally.
183 if (((IsGFX12Plus && !Result[1]) || (!IsGFX12Plus && Result[0])) ||
184 Result.getZExtValue() > 2) {
185 Expr *ArgExpr = TheCall->getArg(0);
186 SemaRef.targetDiag(ArgExpr->getExprLoc(),
187 diag::warn_amdgpu_s_wait_event_mask_no_effect_target)
188 << ArgExpr->getSourceRange();
189 SemaRef.targetDiag(ArgExpr->getExprLoc(),
190 diag::note_amdgpu_s_wait_event_suggested_value)
191 << ArgExpr->getSourceRange();
192 }
193
194 return false;
195 }
196 case AMDGPU::BI__builtin_amdgcn_mov_dpp:
197 return checkMovDPPFunctionCall(TheCall, 5, 1);
198 case AMDGPU::BI__builtin_amdgcn_mov_dpp8:
199 return checkMovDPPFunctionCall(TheCall, 2, 1);
200 case AMDGPU::BI__builtin_amdgcn_update_dpp:
201 return checkMovDPPFunctionCall(TheCall, 6, 2);
202 case AMDGPU::BI__builtin_amdgcn_asyncmark:
203 case AMDGPU::BI__builtin_amdgcn_wait_asyncmark: {
204 bool IsMark = BuiltinID == AMDGPU::BI__builtin_amdgcn_asyncmark;
205
206 // Check the sequence length limit is a constant.
207 llvm::APSInt NumMarks;
208 if (!IsMark && SemaRef.BuiltinConstantArg(TheCall, 0, NumMarks))
209 return true;
210
211 // The stage mask names the stages to act on, so every combination of known
212 // stage bits is meaningful, including none of them: the zero mask names
213 // every stage.
214 unsigned MaskArgNum = IsMark ? 0 : 1;
215 return SemaRef.BuiltinConstantArgRange(
216 TheCall, MaskArgNum, 0,
217 llvm::to_underlying(llvm::AMDGPU::AsyncStages::ALL));
218 }
219 case AMDGPU::BI__builtin_amdgcn_av_load_b8:
220 case AMDGPU::BI__builtin_amdgcn_av_load_b16:
221 case AMDGPU::BI__builtin_amdgcn_av_load_b32:
222 case AMDGPU::BI__builtin_amdgcn_av_load_b64:
223 case AMDGPU::BI__builtin_amdgcn_av_load_b128:
224 return checkAVLoadStore(TheCall, /*IsStore=*/false);
225 case AMDGPU::BI__builtin_amdgcn_av_store_b8:
226 case AMDGPU::BI__builtin_amdgcn_av_store_b16:
227 case AMDGPU::BI__builtin_amdgcn_av_store_b32:
228 case AMDGPU::BI__builtin_amdgcn_av_store_b64:
229 case AMDGPU::BI__builtin_amdgcn_av_store_b128:
230 return checkAVLoadStore(TheCall, /*IsStore=*/true);
231 case AMDGPU::BI__builtin_amdgcn_cooperative_atomic_load_32x4B:
232 case AMDGPU::BI__builtin_amdgcn_cooperative_atomic_load_16x8B:
233 case AMDGPU::BI__builtin_amdgcn_cooperative_atomic_load_8x16B:
234 return checkCoopAtomicFunctionCall(TheCall, /*IsStore=*/false);
235 case AMDGPU::BI__builtin_amdgcn_cooperative_atomic_store_32x4B:
236 case AMDGPU::BI__builtin_amdgcn_cooperative_atomic_store_16x8B:
237 case AMDGPU::BI__builtin_amdgcn_cooperative_atomic_store_8x16B:
238 return checkCoopAtomicFunctionCall(TheCall, /*IsStore=*/true);
239 case AMDGPU::BI__builtin_amdgcn_flat_load_monitor_b32:
240 case AMDGPU::BI__builtin_amdgcn_flat_load_monitor_b64:
241 case AMDGPU::BI__builtin_amdgcn_flat_load_monitor_b128:
242 case AMDGPU::BI__builtin_amdgcn_global_load_monitor_b32:
243 case AMDGPU::BI__builtin_amdgcn_global_load_monitor_b64:
244 case AMDGPU::BI__builtin_amdgcn_global_load_monitor_b128:
245 return checkAtomicMonitorLoad(TheCall);
246 case AMDGPU::BI__builtin_amdgcn_image_load_1d_v4f32_i32:
247 case AMDGPU::BI__builtin_amdgcn_image_load_1darray_v4f32_i32:
248 case AMDGPU::BI__builtin_amdgcn_image_load_1d_v4f16_i32:
249 case AMDGPU::BI__builtin_amdgcn_image_load_1darray_v4f16_i32:
250 case AMDGPU::BI__builtin_amdgcn_image_load_2d_f32_i32:
251 case AMDGPU::BI__builtin_amdgcn_image_load_2d_v4f32_i32:
252 case AMDGPU::BI__builtin_amdgcn_image_load_2d_v4f16_i32:
253 case AMDGPU::BI__builtin_amdgcn_image_load_2darray_f32_i32:
254 case AMDGPU::BI__builtin_amdgcn_image_load_2darray_v4f32_i32:
255 case AMDGPU::BI__builtin_amdgcn_image_load_2darray_v4f16_i32:
256 case AMDGPU::BI__builtin_amdgcn_image_load_3d_v4f32_i32:
257 case AMDGPU::BI__builtin_amdgcn_image_load_3d_v4f16_i32:
258 case AMDGPU::BI__builtin_amdgcn_image_load_cube_v4f32_i32:
259 case AMDGPU::BI__builtin_amdgcn_image_load_cube_v4f16_i32:
260 case AMDGPU::BI__builtin_amdgcn_image_load_mip_1d_v4f32_i32:
261 case AMDGPU::BI__builtin_amdgcn_image_load_mip_1d_v4f16_i32:
262 case AMDGPU::BI__builtin_amdgcn_image_load_mip_1darray_v4f32_i32:
263 case AMDGPU::BI__builtin_amdgcn_image_load_mip_1darray_v4f16_i32:
264 case AMDGPU::BI__builtin_amdgcn_image_load_mip_2d_f32_i32:
265 case AMDGPU::BI__builtin_amdgcn_image_load_mip_2d_v4f32_i32:
266 case AMDGPU::BI__builtin_amdgcn_image_load_mip_2d_v4f16_i32:
267 case AMDGPU::BI__builtin_amdgcn_image_load_mip_2darray_f32_i32:
268 case AMDGPU::BI__builtin_amdgcn_image_load_mip_2darray_v4f32_i32:
269 case AMDGPU::BI__builtin_amdgcn_image_load_mip_2darray_v4f16_i32:
270 case AMDGPU::BI__builtin_amdgcn_image_load_mip_3d_v4f32_i32:
271 case AMDGPU::BI__builtin_amdgcn_image_load_mip_3d_v4f16_i32:
272 case AMDGPU::BI__builtin_amdgcn_image_load_mip_cube_v4f32_i32:
273 case AMDGPU::BI__builtin_amdgcn_image_load_mip_cube_v4f16_i32:
274 case AMDGPU::BI__builtin_amdgcn_image_sample_1d_v4f32_f32:
275 case AMDGPU::BI__builtin_amdgcn_image_sample_1darray_v4f32_f32:
276 case AMDGPU::BI__builtin_amdgcn_image_sample_1d_v4f16_f32:
277 case AMDGPU::BI__builtin_amdgcn_image_sample_1darray_v4f16_f32:
278 case AMDGPU::BI__builtin_amdgcn_image_sample_2d_f32_f32:
279 case AMDGPU::BI__builtin_amdgcn_image_sample_2d_v4f32_f32:
280 case AMDGPU::BI__builtin_amdgcn_image_sample_2d_v4f16_f32:
281 case AMDGPU::BI__builtin_amdgcn_image_sample_2darray_f32_f32:
282 case AMDGPU::BI__builtin_amdgcn_image_sample_2darray_v4f32_f32:
283 case AMDGPU::BI__builtin_amdgcn_image_sample_2darray_v4f16_f32:
284 case AMDGPU::BI__builtin_amdgcn_image_sample_3d_v4f32_f32:
285 case AMDGPU::BI__builtin_amdgcn_image_sample_3d_v4f16_f32:
286 case AMDGPU::BI__builtin_amdgcn_image_sample_cube_v4f32_f32:
287 case AMDGPU::BI__builtin_amdgcn_image_sample_cube_v4f16_f32:
288 case AMDGPU::BI__builtin_amdgcn_image_sample_lz_1d_v4f32_f32:
289 case AMDGPU::BI__builtin_amdgcn_image_sample_lz_1d_v4f16_f32:
290 case AMDGPU::BI__builtin_amdgcn_image_sample_lz_1darray_v4f32_f32:
291 case AMDGPU::BI__builtin_amdgcn_image_sample_lz_1darray_v4f16_f32:
292 case AMDGPU::BI__builtin_amdgcn_image_sample_lz_2d_f32_f32:
293 case AMDGPU::BI__builtin_amdgcn_image_sample_lz_2d_v4f32_f32:
294 case AMDGPU::BI__builtin_amdgcn_image_sample_lz_2d_v4f16_f32:
295 case AMDGPU::BI__builtin_amdgcn_image_sample_lz_2darray_f32_f32:
296 case AMDGPU::BI__builtin_amdgcn_image_sample_lz_2darray_v4f32_f32:
297 case AMDGPU::BI__builtin_amdgcn_image_sample_lz_2darray_v4f16_f32:
298 case AMDGPU::BI__builtin_amdgcn_image_sample_lz_3d_v4f32_f32:
299 case AMDGPU::BI__builtin_amdgcn_image_sample_lz_3d_v4f16_f32:
300 case AMDGPU::BI__builtin_amdgcn_image_sample_lz_cube_v4f32_f32:
301 case AMDGPU::BI__builtin_amdgcn_image_sample_lz_cube_v4f16_f32:
302 case AMDGPU::BI__builtin_amdgcn_image_sample_l_1d_v4f32_f32:
303 case AMDGPU::BI__builtin_amdgcn_image_sample_l_1d_v4f16_f32:
304 case AMDGPU::BI__builtin_amdgcn_image_sample_l_1darray_v4f32_f32:
305 case AMDGPU::BI__builtin_amdgcn_image_sample_l_1darray_v4f16_f32:
306 case AMDGPU::BI__builtin_amdgcn_image_sample_l_2d_f32_f32:
307 case AMDGPU::BI__builtin_amdgcn_image_sample_l_2d_v4f16_f32:
308 case AMDGPU::BI__builtin_amdgcn_image_sample_l_2d_v4f32_f32:
309 case AMDGPU::BI__builtin_amdgcn_image_sample_l_2darray_f32_f32:
310 case AMDGPU::BI__builtin_amdgcn_image_sample_l_2darray_v4f32_f32:
311 case AMDGPU::BI__builtin_amdgcn_image_sample_l_2darray_v4f16_f32:
312 case AMDGPU::BI__builtin_amdgcn_image_sample_l_3d_v4f32_f32:
313 case AMDGPU::BI__builtin_amdgcn_image_sample_l_3d_v4f16_f32:
314 case AMDGPU::BI__builtin_amdgcn_image_sample_l_cube_v4f32_f32:
315 case AMDGPU::BI__builtin_amdgcn_image_sample_l_cube_v4f16_f32:
316 case AMDGPU::BI__builtin_amdgcn_image_sample_d_1d_v4f32_f32:
317 case AMDGPU::BI__builtin_amdgcn_image_sample_d_1d_v4f16_f32:
318 case AMDGPU::BI__builtin_amdgcn_image_sample_d_1darray_v4f32_f32:
319 case AMDGPU::BI__builtin_amdgcn_image_sample_d_1darray_v4f16_f32:
320 case AMDGPU::BI__builtin_amdgcn_image_sample_d_2d_f32_f32:
321 case AMDGPU::BI__builtin_amdgcn_image_sample_d_2d_v4f32_f32:
322 case AMDGPU::BI__builtin_amdgcn_image_sample_d_2d_v4f16_f32:
323 case AMDGPU::BI__builtin_amdgcn_image_sample_d_2darray_f32_f32:
324 case AMDGPU::BI__builtin_amdgcn_image_sample_d_2darray_v4f32_f32:
325 case AMDGPU::BI__builtin_amdgcn_image_sample_d_2darray_v4f16_f32:
326 case AMDGPU::BI__builtin_amdgcn_image_sample_d_3d_v4f32_f32:
327 case AMDGPU::BI__builtin_amdgcn_image_sample_d_3d_v4f16_f32:
328 case AMDGPU::BI__builtin_amdgcn_image_gather4_lz_2d_v4f32_f32:
329 case AMDGPU::BI__builtin_amdgcn_image_gather4_lz_2d_v4f16_f32: {
330
331 unsigned ArgCount = TheCall->getNumArgs() - 1;
332 llvm::APSInt Result;
333
334 // Compilain about dmask values which are too huge to fully fit into 4 bits
335 // (which is the actual size of the dmask in corresponding HW instructions).
336 constexpr unsigned DMaskArgNo = 0;
337 constexpr int Low = 0;
338 constexpr int High = 15;
339 if (SemaRef.BuiltinConstantArg(TheCall, DMaskArgNo, Result) ||
340 SemaRef.BuiltinConstantArgRange(TheCall, DMaskArgNo, Low, High,
341 /* RangeIsError = */ true))
342 return true;
343
344 // Dmask indicates which elements should be returned and it is not possible
345 // to return more values than there are elements in return type.
346 int NumElementsInRetTy = 1;
347 const Type *RetTy = TheCall->getType().getTypePtr();
348 if (auto *VTy = dyn_cast<VectorType>(RetTy))
349 NumElementsInRetTy = VTy->getNumElements();
350 int NumActiveBitsInDMask =
351 llvm::popcount(static_cast<uint8_t>(Result.getExtValue()));
352 if (NumActiveBitsInDMask > NumElementsInRetTy) {
353 Diag(TheCall->getBeginLoc(),
354 diag::err_amdgcn_dmask_has_too_many_bits_set);
355 return true;
356 }
357
358 // For gather, only one bit can be set indicating which exact component to
359 // return.
360 bool ExtraGatherChecks =
361 (BuiltinID ==
362 AMDGPU::BI__builtin_amdgcn_image_gather4_lz_2d_v4f32_f32 ||
363 BuiltinID ==
364 AMDGPU::BI__builtin_amdgcn_image_gather4_lz_2d_v4f16_f32) &&
365 SemaRef.BuiltinConstantArgPower2(TheCall, 0);
366
367 return ExtraGatherChecks ||
368 (SemaRef.BuiltinConstantArg(TheCall, ArgCount, Result)) ||
369 (SemaRef.BuiltinConstantArg(TheCall, (ArgCount - 1), Result));
370 }
371 case AMDGPU::BI__builtin_amdgcn_image_store_1d_v4f32_i32:
372 case AMDGPU::BI__builtin_amdgcn_image_store_1darray_v4f32_i32:
373 case AMDGPU::BI__builtin_amdgcn_image_store_1d_v4f16_i32:
374 case AMDGPU::BI__builtin_amdgcn_image_store_1darray_v4f16_i32:
375 case AMDGPU::BI__builtin_amdgcn_image_store_2d_f32_i32:
376 case AMDGPU::BI__builtin_amdgcn_image_store_2d_v4f32_i32:
377 case AMDGPU::BI__builtin_amdgcn_image_store_2d_v4f16_i32:
378 case AMDGPU::BI__builtin_amdgcn_image_store_2darray_f32_i32:
379 case AMDGPU::BI__builtin_amdgcn_image_store_2darray_v4f32_i32:
380 case AMDGPU::BI__builtin_amdgcn_image_store_2darray_v4f16_i32:
381 case AMDGPU::BI__builtin_amdgcn_image_store_3d_v4f32_i32:
382 case AMDGPU::BI__builtin_amdgcn_image_store_3d_v4f16_i32:
383 case AMDGPU::BI__builtin_amdgcn_image_store_cube_v4f32_i32:
384 case AMDGPU::BI__builtin_amdgcn_image_store_cube_v4f16_i32:
385 case AMDGPU::BI__builtin_amdgcn_image_store_mip_1d_v4f32_i32:
386 case AMDGPU::BI__builtin_amdgcn_image_store_mip_1d_v4f16_i32:
387 case AMDGPU::BI__builtin_amdgcn_image_store_mip_1darray_v4f32_i32:
388 case AMDGPU::BI__builtin_amdgcn_image_store_mip_1darray_v4f16_i32:
389 case AMDGPU::BI__builtin_amdgcn_image_store_mip_2d_f32_i32:
390 case AMDGPU::BI__builtin_amdgcn_image_store_mip_2d_v4f32_i32:
391 case AMDGPU::BI__builtin_amdgcn_image_store_mip_2d_v4f16_i32:
392 case AMDGPU::BI__builtin_amdgcn_image_store_mip_2darray_f32_i32:
393 case AMDGPU::BI__builtin_amdgcn_image_store_mip_2darray_v4f32_i32:
394 case AMDGPU::BI__builtin_amdgcn_image_store_mip_2darray_v4f16_i32:
395 case AMDGPU::BI__builtin_amdgcn_image_store_mip_3d_v4f32_i32:
396 case AMDGPU::BI__builtin_amdgcn_image_store_mip_3d_v4f16_i32:
397 case AMDGPU::BI__builtin_amdgcn_image_store_mip_cube_v4f32_i32:
398 case AMDGPU::BI__builtin_amdgcn_image_store_mip_cube_v4f16_i32: {
399
400 unsigned ArgCount = TheCall->getNumArgs() - 1;
401 llvm::APSInt Result;
402
403 // Complain about dmask values which are too huge to fully fit into 4 bits
404 // (which is the actual size of the dmask in corresponding HW instructions).
405 constexpr unsigned DMaskArgNo = 1;
406 return SemaRef.BuiltinConstantArgRange(TheCall, DMaskArgNo, /*Low=*/0,
407 /*High=*/15,
408 /*RangeIsError=*/true) ||
409 SemaRef.BuiltinConstantArg(TheCall, ArgCount, Result) ||
410 SemaRef.BuiltinConstantArg(TheCall, (ArgCount - 1), Result);
411 }
412 case AMDGPU::BI__builtin_amdgcn_wmma_i32_16x16x64_iu8:
413 case AMDGPU::BI__builtin_amdgcn_swmmac_i32_16x16x128_iu8: {
414 if (BuiltinID == AMDGPU::BI__builtin_amdgcn_wmma_i32_16x16x64_iu8) {
415 if (SemaRef.checkArgCountRange(TheCall, 7, 8))
416 return true;
417 if (TheCall->getNumArgs() == 7)
418 return false;
419 } else if (BuiltinID ==
420 AMDGPU::BI__builtin_amdgcn_swmmac_i32_16x16x128_iu8) {
421 if (SemaRef.checkArgCountRange(TheCall, 8, 9))
422 return true;
423 if (TheCall->getNumArgs() == 8)
424 return false;
425 }
426 // Check if the last argument (clamp operand) is a constant and is
427 // convertible to bool.
428 Expr *ClampArg = TheCall->getArg(TheCall->getNumArgs() - 1);
429 // 1) Ensure clamp argument is a constant expression
430 llvm::APSInt ClampValue;
431 if (!SemaRef.VerifyIntegerConstantExpression(ClampArg, &ClampValue)
432 .isUsable())
433 return true;
434 // 2) Check if the argument can be converted to bool type
435 if (!SemaRef.Context.hasSameType(ClampArg->getType(),
436 SemaRef.Context.BoolTy)) {
437 // Try to convert to bool
438 QualType BoolTy = SemaRef.Context.BoolTy;
439 ExprResult ClampExpr(ClampArg);
440 SemaRef.CheckSingleAssignmentConstraints(BoolTy, ClampExpr);
441 if (ClampExpr.isInvalid())
442 return true;
443 }
444 return false;
445 }
446 default:
447 return false;
448 }
449}
450
452 bool MayStore) {
453 Expr::EvalResult AtomicOrdArgRes;
454 if (!E->EvaluateAsInt(AtomicOrdArgRes, getASTContext()))
455 llvm_unreachable("Intrinsic requires imm for atomic ordering argument!");
456 auto Ord =
457 llvm::AtomicOrderingCABI(AtomicOrdArgRes.Val.getInt().getZExtValue());
458
459 // Atomic ordering cannot be acq_rel in any case, acquire/consume for stores
460 // or release for loads.
461 // An invalid ordering is not ill-formed despite being UB, so only emit a
462 // warning.
463 if (!llvm::isValidAtomicOrderingCABI((unsigned)Ord) ||
464 (!(MayLoad && MayStore) && (Ord == llvm::AtomicOrderingCABI::acq_rel)) ||
465 (!MayLoad && (Ord == llvm::AtomicOrderingCABI::acquire ||
466 Ord == llvm::AtomicOrderingCABI::consume)) ||
467 (!MayStore && Ord == llvm::AtomicOrderingCABI::release)) {
468 Diag(E->getBeginLoc(), diag::warn_atomic_op_has_invalid_memory_order)
469 << 0 << E->getSourceRange();
470 }
471}
472
473// Check that the first argument to TheCall is a global or generic pointer.
475 Expr *PtrArg = TheCall->getArg(0);
476 QualType PtrTy = PtrArg->getType()->getPointeeType();
477 unsigned AS =
478 S.getASTContext().getTargetAddressSpace(PtrTy.getAddressSpace());
479 if (AS != llvm::AMDGPUAS::FLAT_ADDRESS &&
480 AS != llvm::AMDGPUAS::GLOBAL_ADDRESS) {
481 return S.Diag(TheCall->getBeginLoc(),
482 diag::err_amdgcn_global_or_flat_pointer_required)
483 << PtrArg->getSourceRange();
484 }
485 return false;
486}
487
489 if (Scope->isValueDependent())
490 return false;
492 if (std::optional<llvm::APSInt> Result =
493 Scope->getIntegerConstantExpr(S.SemaRef.Context)) {
494 if (!ScopeModel->isValid(Result->getZExtValue())) {
495 return S.Diag(Scope->getBeginLoc(),
496 diag::err_atomic_op_has_invalid_sync_scope)
497 << Scope->getSourceRange();
498 }
499 }
500 return false;
501}
502
503bool SemaAMDGPU::checkAVLoadStore(CallExpr *TheCall, bool IsStore) {
504 if (checkGlobalOrFlatPointerArg(*this, TheCall))
505 return true;
506
507 Expr *Scope = TheCall->getArg(TheCall->getNumArgs() - 1);
508 return checkScopeAsInt(*this, Scope);
509}
510
512 bool Fail = checkGlobalOrFlatPointerArg(*this, TheCall);
513
514 Expr *AO = TheCall->getArg(IsStore ? 2 : 1);
515 Expr *Scope = TheCall->getArg(TheCall->getNumArgs() - 1);
516
517 if (AO->isValueDependent() || Scope->isValueDependent())
518 return false;
519
520 // Check atomic ordering
521 checkAtomicOrderingCABIArg(AO, /*MayLoad=*/!IsStore, /*MayStore=*/IsStore);
522
523 // Last argument is the syncscope as a string literal.
524 if (!isa<StringLiteral>(Scope->IgnoreParenImpCasts())) {
525 Diag(TheCall->getBeginLoc(), diag::err_expr_not_string_literal)
526 << Scope->getSourceRange();
527 Fail = true;
528 }
529
530 return Fail;
531}
532
534 Expr *AO = TheCall->getArg(1);
535 Expr *Scope = TheCall->getArg(TheCall->getNumArgs() - 1);
536
537 if (AO->isValueDependent() || Scope->isValueDependent())
538 return false;
539
540 checkAtomicOrderingCABIArg(AO, /*MayLoad=*/true, /*MayStore=*/false);
541 return checkScopeAsInt(*this, Scope);
542}
543
544bool SemaAMDGPU::checkMovDPPFunctionCall(CallExpr *TheCall, unsigned NumArgs,
545 unsigned NumDataArgs) {
546 assert(NumDataArgs <= 2);
547 if (SemaRef.checkArgCountRange(TheCall, NumArgs, NumArgs))
548 return true;
549 Expr *Args[2];
550 QualType ArgTys[2];
551 for (unsigned I = 0; I != NumDataArgs; ++I) {
552 Args[I] = TheCall->getArg(I);
553 ArgTys[I] = Args[I]->getType();
554 // TODO: Vectors can also be supported.
555 if (!ArgTys[I]->isArithmeticType() || ArgTys[I]->isAnyComplexType()) {
556 SemaRef.Diag(Args[I]->getBeginLoc(),
557 diag::err_typecheck_cond_expect_int_float)
558 << ArgTys[I] << Args[I]->getSourceRange();
559 return true;
560 }
561 }
562 if (NumDataArgs < 2)
563 return false;
564
565 if (getASTContext().hasSameUnqualifiedType(ArgTys[0], ArgTys[1]))
566 return false;
567
568 if (((ArgTys[0]->isUnsignedIntegerType() &&
569 ArgTys[1]->isSignedIntegerType()) ||
570 (ArgTys[0]->isSignedIntegerType() &&
571 ArgTys[1]->isUnsignedIntegerType())) &&
572 getASTContext().getTypeSize(ArgTys[0]) ==
573 getASTContext().getTypeSize(ArgTys[1]))
574 return false;
575
576 SemaRef.Diag(Args[1]->getBeginLoc(),
577 diag::err_typecheck_call_different_arg_types)
578 << ArgTys[0] << ArgTys[1];
579 return true;
580}
581
582static bool
584 const AMDGPUFlatWorkGroupSizeAttr &Attr) {
585 // Accept template arguments for now as they depend on something else.
586 // We'll get to check them when they eventually get instantiated.
587 if (MinExpr->isValueDependent() || MaxExpr->isValueDependent())
588 return false;
589
590 uint32_t Min = 0;
591 if (!S.checkUInt32Argument(Attr, MinExpr, Min, 0))
592 return true;
593
594 uint32_t Max = 0;
595 if (!S.checkUInt32Argument(Attr, MaxExpr, Max, 1))
596 return true;
597
598 if (Min == 0 && Max != 0) {
599 S.Diag(Attr.getLocation(), diag::err_attribute_argument_invalid)
600 << &Attr << 0;
601 return true;
602 }
603 if (Min > Max) {
604 S.Diag(Attr.getLocation(), diag::err_attribute_argument_invalid)
605 << &Attr << 1;
606 return true;
607 }
608
609 return false;
610}
611
612AMDGPUFlatWorkGroupSizeAttr *
614 Expr *MinExpr, Expr *MaxExpr) {
615 ASTContext &Context = getASTContext();
616 AMDGPUFlatWorkGroupSizeAttr TmpAttr(Context, CI, MinExpr, MaxExpr);
617
618 if (checkAMDGPUFlatWorkGroupSizeArguments(SemaRef, MinExpr, MaxExpr, TmpAttr))
619 return nullptr;
620 return ::new (Context)
621 AMDGPUFlatWorkGroupSizeAttr(Context, CI, MinExpr, MaxExpr);
622}
623
625 const AttributeCommonInfo &CI,
626 Expr *MinExpr, Expr *MaxExpr) {
627 if (auto *Attr = CreateAMDGPUFlatWorkGroupSizeAttr(CI, MinExpr, MaxExpr))
628 D->addAttr(Attr);
629}
630
632 const ParsedAttr &AL) {
633 Expr *MinExpr = AL.getArgAsExpr(0);
634 Expr *MaxExpr = AL.getArgAsExpr(1);
635
636 addAMDGPUFlatWorkGroupSizeAttr(D, AL, MinExpr, MaxExpr);
637}
638
639static bool checkAMDGPUWavesPerEUArguments(Sema &S, Expr *MinExpr,
640 Expr *MaxExpr,
641 const AMDGPUWavesPerEUAttr &Attr) {
642 if (S.DiagnoseUnexpandedParameterPack(MinExpr) ||
643 (MaxExpr && S.DiagnoseUnexpandedParameterPack(MaxExpr)))
644 return true;
645
646 // Accept template arguments for now as they depend on something else.
647 // We'll get to check them when they eventually get instantiated.
648 if (MinExpr->isValueDependent() || (MaxExpr && MaxExpr->isValueDependent()))
649 return false;
650
651 uint32_t Min = 0;
652 if (!S.checkUInt32Argument(Attr, MinExpr, Min, 0))
653 return true;
654
655 uint32_t Max = 0;
656 if (MaxExpr && !S.checkUInt32Argument(Attr, MaxExpr, Max, 1))
657 return true;
658
659 if (Min == 0 && Max != 0) {
660 S.Diag(Attr.getLocation(), diag::err_attribute_argument_invalid)
661 << &Attr << 0;
662 return true;
663 }
664 if (Max != 0 && Min > Max) {
665 S.Diag(Attr.getLocation(), diag::err_attribute_argument_invalid)
666 << &Attr << 1;
667 return true;
668 }
669
670 return false;
671}
672
673AMDGPUWavesPerEUAttr *
675 Expr *MinExpr, Expr *MaxExpr) {
676 ASTContext &Context = getASTContext();
677 AMDGPUWavesPerEUAttr TmpAttr(Context, CI, MinExpr, MaxExpr);
678
679 if (checkAMDGPUWavesPerEUArguments(SemaRef, MinExpr, MaxExpr, TmpAttr))
680 return nullptr;
681
682 return ::new (Context) AMDGPUWavesPerEUAttr(Context, CI, MinExpr, MaxExpr);
683}
684
686 Expr *MinExpr, Expr *MaxExpr) {
687 if (auto *Attr = CreateAMDGPUWavesPerEUAttr(CI, MinExpr, MaxExpr))
688 D->addAttr(Attr);
689}
690
693 return;
694
695 Expr *MinExpr = AL.getArgAsExpr(0);
696 Expr *MaxExpr = (AL.getNumArgs() > 1) ? AL.getArgAsExpr(1) : nullptr;
697
698 addAMDGPUWavesPerEUAttr(D, AL, MinExpr, MaxExpr);
699}
700
702 Diag(AL.getLoc(), diag::warn_amdgpu_num_reg_attr_deprecated) << AL;
703
704 uint32_t NumSGPR = 0;
705 Expr *NumSGPRExpr = AL.getArgAsExpr(0);
706 if (!SemaRef.checkUInt32Argument(AL, NumSGPRExpr, NumSGPR))
707 return;
708
709 D->addAttr(::new (getASTContext())
710 AMDGPUNumSGPRAttr(getASTContext(), AL, NumSGPR));
711}
712
714 Diag(AL.getLoc(), diag::warn_amdgpu_num_reg_attr_deprecated) << AL;
715
716 uint32_t NumVGPR = 0;
717 Expr *NumVGPRExpr = AL.getArgAsExpr(0);
718 if (!SemaRef.checkUInt32Argument(AL, NumVGPRExpr, NumVGPR))
719 return;
720
721 D->addAttr(::new (getASTContext())
722 AMDGPUNumVGPRAttr(getASTContext(), AL, NumVGPR));
723}
724
725static bool
727 Expr *ZExpr,
728 const AMDGPUMaxNumWorkGroupsAttr &Attr) {
729 if (S.DiagnoseUnexpandedParameterPack(XExpr) ||
730 (YExpr && S.DiagnoseUnexpandedParameterPack(YExpr)) ||
731 (ZExpr && S.DiagnoseUnexpandedParameterPack(ZExpr)))
732 return true;
733
734 // Accept template arguments for now as they depend on something else.
735 // We'll get to check them when they eventually get instantiated.
736 if (XExpr->isValueDependent() || (YExpr && YExpr->isValueDependent()) ||
737 (ZExpr && ZExpr->isValueDependent()))
738 return false;
739
740 uint32_t NumWG = 0;
741 Expr *Exprs[3] = {XExpr, YExpr, ZExpr};
742 for (int i = 0; i < 3; i++) {
743 if (Exprs[i]) {
744 if (!S.checkUInt32Argument(Attr, Exprs[i], NumWG, i,
745 /*StrictlyUnsigned=*/true))
746 return true;
747 if (NumWG == 0) {
748 S.Diag(Attr.getLoc(), diag::err_attribute_argument_is_zero)
749 << &Attr << Exprs[i]->getSourceRange();
750 return true;
751 }
752 }
753 }
754
755 return false;
756}
757
759 const AttributeCommonInfo &CI, Expr *XExpr, Expr *YExpr, Expr *ZExpr) {
760 ASTContext &Context = getASTContext();
761 AMDGPUMaxNumWorkGroupsAttr TmpAttr(Context, CI, XExpr, YExpr, ZExpr);
762 assert(!SemaRef.isSFINAEContext() &&
763 "Can't produce SFINAE diagnostic pointing to temporary attribute");
764
765 if (checkAMDGPUMaxNumWorkGroupsArguments(SemaRef, XExpr, YExpr, ZExpr,
766 TmpAttr))
767 return nullptr;
768
769 return ::new (Context)
770 AMDGPUMaxNumWorkGroupsAttr(Context, CI, XExpr, YExpr, ZExpr);
771}
772
774 const AttributeCommonInfo &CI,
775 Expr *XExpr, Expr *YExpr,
776 Expr *ZExpr) {
777 if (auto *Attr = CreateAMDGPUMaxNumWorkGroupsAttr(CI, XExpr, YExpr, ZExpr))
778 D->addAttr(Attr);
779}
780
782 const ParsedAttr &AL) {
783 Expr *YExpr = (AL.getNumArgs() > 1) ? AL.getArgAsExpr(1) : nullptr;
784 Expr *ZExpr = (AL.getNumArgs() > 2) ? AL.getArgAsExpr(2) : nullptr;
785 addAMDGPUMaxNumWorkGroupsAttr(D, AL, AL.getArgAsExpr(0), YExpr, ZExpr);
786}
787
790 ASTContext &Ctx = getASTContext();
791 QualType BoolTy = Ctx.getLogicalOperationType();
792 SourceLocation Loc = CE->getExprLoc();
793
794 if (!CE->getBuiltinCallee())
795 return *ExpandedPredicates
796 .insert(SemaRef.BuildBoolLiteral(Loc, false).get())
797 .first;
798
799 bool P = false;
800 unsigned BI = CE->getBuiltinCallee();
801 if (Ctx.BuiltinInfo.isAuxBuiltinID(BI))
802 BI = Ctx.BuiltinInfo.getAuxBuiltinID(BI);
803
804 if (BI == AMDGPU::BI__builtin_amdgcn_processor_is) {
805 auto *GFX = dyn_cast<StringLiteral>(CE->getArg(0)->IgnoreParenCasts());
806 if (!GFX) {
807 Diag(Loc, diag::err_amdgcn_processor_is_arg_not_literal);
808 return nullptr;
809 }
810
811 StringRef N = GFX->getString();
812 const TargetInfo &TI = Ctx.getTargetInfo();
813 if (llvm::AMDGPU::parseArchAMDGCN(N) == llvm::AMDGPU::GK_NONE) {
814 Diag(Loc, diag::err_amdgcn_processor_is_arg_invalid_value) << N;
816 llvm::AMDGPU::fillValidArchListAMDGCN(ValidList);
817 if (!ValidList.empty())
818 Diag(Loc, diag::note_amdgcn_processor_is_valid_options)
819 << llvm::join(ValidList, ", ");
820 return nullptr;
821 }
822 if (TI.getTriple().isSPIRV()) {
823 CE->setType(BoolTy);
824 return *ExpandedPredicates.insert(CE).first;
825 }
826
827 P = TI.isProcessorName(N);
828 } else {
829 Expr *Arg = CE->getArg(0);
830 if (!Arg || Arg->getType() != Ctx.BuiltinFnTy) {
831 Diag(Loc, diag::err_amdgcn_is_invocable_arg_invalid_value) << Arg;
832 return nullptr;
833 }
834
835 if (Ctx.getTargetInfo().getTriple().isSPIRV()) {
836 CE->setType(BoolTy);
837 return *ExpandedPredicates.insert(CE).first;
838 }
839
841
842 StringRef RF = Ctx.BuiltinInfo.getRequiredFeatures(FD->getBuiltinID());
843 llvm::StringMap<bool> CF;
844 Ctx.getFunctionFeatureMap(CF, FD);
845
847 }
848
849 return *ExpandedPredicates.insert(SemaRef.BuildBoolLiteral(Loc, P).get())
850 .first;
851}
852
854 return ExpandedPredicates.contains(E);
855}
856
858 PotentiallyUnguardedBuiltinUsers.insert(FD);
859}
860
862 return PotentiallyUnguardedBuiltinUsers.contains(FD);
863}
864
865namespace {
866/// This class implements -Wamdgpu-unguarded-builtin-usage.
867///
868/// This is done with a traversal of the AST of a function that includes a
869/// call to a target specific builtin. Whenever we encounter an \c if of the
870/// form: \c if(__builtin_amdgcn_is_invocable), we consider the then statement
871/// guarded.
872class DiagnoseUnguardedBuiltins : public DynamicRecursiveASTVisitor {
873 // TODO: this could eventually be extended to consider what happens when there
874 // are multiple target architectures specified via target("arch=gfxXXX")
875 // target("arch=gfxyyy") etc., as well as feature disabling via "-XXX".
876 Sema &SemaRef;
877
878 SmallVector<StringRef> TargetFeatures;
880 SmallVector<unsigned> GuardedBuiltins;
881
882 static Expr *FindPredicate(Expr *Cond) {
883 if (auto *CE = dyn_cast<CallExpr>(Cond)) {
884 if (CE->getBuiltinCallee() == AMDGPU::BI__builtin_amdgcn_is_invocable ||
885 CE->getBuiltinCallee() == AMDGPU::BI__builtin_amdgcn_processor_is)
886 return Cond;
887 } else if (auto *UO = dyn_cast<UnaryOperator>(Cond)) {
888 return FindPredicate(UO->getSubExpr());
889 } else if (auto *BO = dyn_cast<BinaryOperator>(Cond)) {
890 if ((Cond = FindPredicate(BO->getLHS())))
891 return Cond;
892 return FindPredicate(BO->getRHS());
893 }
894 return nullptr;
895 }
896
897 bool EnterPredicateGuardedContext(CallExpr *P);
898 void ExitPredicateGuardedContext(bool WasProcessorCheck);
899 bool TraverseGuardedStmt(Stmt *S, CallExpr *P);
900
901public:
902 DiagnoseUnguardedBuiltins(Sema &SemaRef) : SemaRef(SemaRef) {
903 if (auto *TAT = SemaRef.getCurFunctionDecl(true)->getAttr<TargetAttr>()) {
904 // We use the somewhat misnamed x86 accessors because they provide exactly
905 // what we require.
906 TAT->getX86AddedFeatures(TargetFeatures);
907 if (auto GFXIP = TAT->getX86Architecture())
908 CurrentGFXIP.emplace_back(TAT->getLocation(), *GFXIP);
909 }
910 }
911
912 bool TraverseLambdaExpr(LambdaExpr *LE) override {
913 if (SemaRef.AMDGPU().HasPotentiallyUnguardedBuiltinUsage(
914 LE->getCallOperator()))
915 return true; // We have already handled this.
916 return DynamicRecursiveASTVisitor::TraverseLambdaExpr(LE);
917 }
918
919 bool TraverseStmt(Stmt *S) override {
920 if (!S)
921 return true;
923 }
924
925 void IssueDiagnostics(Stmt *S) { TraverseStmt(S); }
926
927 bool TraverseIfStmt(IfStmt *If) override {
928 if (auto *CE = dyn_cast_or_null<CallExpr>(FindPredicate(If->getCond())))
929 return TraverseGuardedStmt(If, CE);
930 return DynamicRecursiveASTVisitor::TraverseIfStmt(If);
931 }
932
933 bool TraverseCaseStmt(CaseStmt *CS) override {
934 return TraverseStmt(CS->getSubStmt());
935 }
936
937 bool TraverseConditionalOperator(ConditionalOperator *CO) override {
938 if (auto *CE = dyn_cast_or_null<CallExpr>(FindPredicate(CO->getCond())))
939 return TraverseGuardedStmt(CO, CE);
940 return DynamicRecursiveASTVisitor::TraverseConditionalOperator(CO);
941 }
942
943 bool VisitAsmStmt(AsmStmt *ASM) override;
944 bool VisitCallExpr(CallExpr *CE) override;
945};
946
947bool DiagnoseUnguardedBuiltins::EnterPredicateGuardedContext(CallExpr *P) {
948 bool IsProcessorCheck =
949 P->getBuiltinCallee() == AMDGPU::BI__builtin_amdgcn_processor_is;
950
951 if (IsProcessorCheck) {
952 StringRef G = cast<clang::StringLiteral>(P->getArg(0))->getString();
953 // TODO: handle generic ISAs.
954 if (!CurrentGFXIP.empty() && G != CurrentGFXIP.back().second) {
955 SemaRef.Diag(P->getExprLoc(),
956 diag::err_amdgcn_conflicting_is_processor_options)
957 << P;
958 SemaRef.Diag(CurrentGFXIP.back().first,
959 diag::note_amdgcn_previous_is_processor_guard);
960 }
961 CurrentGFXIP.emplace_back(P->getExprLoc(), G);
962 } else {
963 auto *FD = cast<FunctionDecl>(
964 cast<DeclRefExpr>(P->getArg(0))->getReferencedDeclOfCallee());
965 GuardedBuiltins.push_back(FD->getBuiltinID());
966 }
967
968 return IsProcessorCheck;
969}
970
971void DiagnoseUnguardedBuiltins::ExitPredicateGuardedContext(bool WasProcCheck) {
972 if (WasProcCheck)
973 CurrentGFXIP.pop_back();
974 else
975 GuardedBuiltins.pop_back();
976}
977
978inline std::pair<Stmt *, Stmt *> GetTraversalOrder(Stmt *S) {
979 std::pair<Stmt *, Stmt *> Ordered;
980 Expr *Condition = nullptr;
981
982 if (auto *CO = dyn_cast<ConditionalOperator>(S)) {
983 Condition = CO->getCond();
984 Ordered = {CO->getTrueExpr(), CO->getFalseExpr()};
985 } else if (auto *If = dyn_cast<IfStmt>(S)) {
986 Condition = If->getCond();
987 Ordered = {If->getThen(), If->getElse()};
988 }
989
990 if (auto *UO = dyn_cast<UnaryOperator>(Condition))
991 if (UO->getOpcode() == UnaryOperatorKind::UO_LNot)
992 std::swap(Ordered.first, Ordered.second);
993
994 return Ordered;
995}
996
997bool DiagnoseUnguardedBuiltins::TraverseGuardedStmt(Stmt *S, CallExpr *P) {
998 assert(S && "Unexpected missing Statement!");
999 assert(P && "Unexpected missing Predicate!");
1000
1001 auto [Guarded, Unguarded] = GetTraversalOrder(S);
1002
1003 bool WasProcessorCheck = EnterPredicateGuardedContext(P);
1004
1005 bool Continue = TraverseStmt(Guarded);
1006
1007 ExitPredicateGuardedContext(WasProcessorCheck);
1008
1009 return Continue && TraverseStmt(Unguarded);
1010}
1011
1012bool DiagnoseUnguardedBuiltins::VisitAsmStmt(AsmStmt *ASM) {
1013 // TODO: should we check if the ASM is valid for the target? Can we?
1014 if (!CurrentGFXIP.empty())
1015 return true;
1016
1017 std::string S = ASM->generateAsmString(SemaRef.getASTContext());
1018 SemaRef.Diag(ASM->getAsmLoc(), diag::warn_amdgcn_unguarded_asm_stmt) << S;
1019 SemaRef.Diag(ASM->getAsmLoc(), diag::note_amdgcn_unguarded_asm_silence) << S;
1020
1021 return true;
1022}
1023
1024bool DiagnoseUnguardedBuiltins::VisitCallExpr(CallExpr *CE) {
1025 unsigned ID = CE->getBuiltinCallee();
1026 Builtin::Context &BInfo = SemaRef.getASTContext().BuiltinInfo;
1027
1028 if (!ID)
1029 return true;
1030 if (!BInfo.isTSBuiltin(ID))
1031 return true;
1032 if (ID == AMDGPU::BI__builtin_amdgcn_processor_is ||
1033 ID == AMDGPU::BI__builtin_amdgcn_is_invocable)
1034 return true;
1035 if (llvm::find(GuardedBuiltins, ID) != GuardedBuiltins.end())
1036 return true;
1037
1038 StringRef FL(BInfo.getRequiredFeatures(ID));
1039 llvm::StringMap<bool> FeatureMap;
1040 if (CurrentGFXIP.empty()) {
1041 for (auto &&F : TargetFeatures)
1042 FeatureMap[F] = true;
1043 for (auto &&GID : GuardedBuiltins)
1044 for (auto &&F : llvm::split(BInfo.getRequiredFeatures(GID), ','))
1045 FeatureMap[F] = true;
1046 } else {
1047 static const llvm::Triple AMDGCN(llvm::Triple::amdgpu,
1048 llvm::Triple::NoSubArch, llvm::Triple::AMD,
1049 llvm::Triple::AMDHSA);
1050 llvm::AMDGPU::fillAMDGPUFeatureMap(CurrentGFXIP.back().second, AMDGCN,
1051 FeatureMap);
1052 }
1053
1054 FunctionDecl *BI = CE->getDirectCallee();
1055 SourceLocation BICallLoc = CE->getExprLoc();
1056 if (Builtin::evaluateRequiredTargetFeatures(FL, FeatureMap)) {
1057 SemaRef.Diag(BICallLoc, diag::warn_amdgcn_unguarded_builtin) << BI;
1058 SemaRef.Diag(BICallLoc, diag::note_amdgcn_unguarded_builtin_silence) << BI;
1059 } else {
1060 StringRef GFXIP = CurrentGFXIP.empty() ? "" : CurrentGFXIP.back().second;
1061 SemaRef.Diag(BICallLoc, diag::err_amdgcn_incompatible_builtin)
1062 << BI << FL << !CurrentGFXIP.empty() << GFXIP;
1063 if (!CurrentGFXIP.empty())
1064 SemaRef.Diag(CurrentGFXIP.back().first,
1065 diag::note_amdgcn_previous_is_processor_guard);
1066 }
1067
1068 return true;
1069}
1070} // Unnamed namespace
1071
1073 DiagnoseUnguardedBuiltins(SemaRef).IssueDiagnostics(FD->getBody());
1074}
1075
1077 ASTContext &Ctx = getASTContext();
1078 llvm::Triple TT = Ctx.getTargetInfo().getTriple();
1079 const Type *BaseTy = Ty->getPointeeOrArrayElementType();
1080
1081 if (Ctx.getTargetInfo().getTriple().isSPIRV()) {
1082 // The AMDGPU named barrier type requires special handling in the back-end
1083 // and is not supported for SPIR-V
1084 if (BaseTy->isAMDGPUNamedBarrierType()) {
1085 SemaRef.Diag(Loc, diag::err_amdgpu_target_ext_type_unsupported)
1086 << Ty << TT.str();
1087 return false;
1088 }
1089 }
1090
1091 return true;
1092}
1093
1095 for (FieldDecl *FD : R->fields()) {
1096 QualType FDTy = FD->getType();
1098 return FD;
1099 }
1100
1101 return nullptr;
1102}
1103
1105 ASTContext &Context = getASTContext();
1106 if (R->isInvalidDecl())
1107 return;
1108
1109 if (!Context.getTargetInfo().hasAMDGPUTypes() &&
1110 (!Context.getAuxTargetInfo() ||
1111 !Context.getAuxTargetInfo()->hasAMDGPUTypes()))
1112 return;
1113
1114 bool IsWrapper = false;
1115 std::function<void()> DiagWrapperNote;
1116
1117 // First, check if this is a named barrier wrapper by virtue of the class
1118 // declaring a named barrier field. This covers both C and C++.
1119 if (FieldDecl *NamedBarrField = getNamedBarrierField(R)) {
1120 // If this record contains a named barrier field, it must have only one
1121 // field.
1122 if (R->getNumFields() > 1) {
1123 SemaRef.Diag(NamedBarrField->getLocation(),
1124 diag::err_amdgpu_invalid_field_not_a_wrapper)
1125 << NamedBarrField->getType();
1126 SemaRef.Diag(
1127 R->getLocation(),
1128 diag::note_amdgpu_not_a_named_barrier_wrapper_too_many_fields)
1129 << R->getDeclName();
1130 return;
1131 }
1132
1133 IsWrapper = true;
1134 DiagWrapperNote = [this, R, NamedBarrField]() {
1135 SemaRef.Diag(NamedBarrField->getLocation(),
1136 diag::note_amdgpu_named_barrier_reason_field)
1137 << R->getDeclName() << NamedBarrField->getDeclName();
1138 };
1139 }
1140
1141 // Then, for C++ classes, check if this is a named barrier wrapper by virtue
1142 // of inheriting one.
1143 const auto *CxxR = dyn_cast<CXXRecordDecl>(R);
1144 if (CxxR && !IsWrapper) {
1145 for (CXXBaseSpecifier BS : CxxR->bases()) {
1146 const RecordDecl *Base = BS.getType()->getAsRecordDecl();
1147 if (!Base || !Base->hasAttr<AMDGPUNamedBarrierWrapperAttr>())
1148 continue;
1149
1150 IsWrapper = true;
1151 DiagWrapperNote = [this, BS, R]() {
1152 // Print using the CXXBaseSpecifier type as it includes the template
1153 // parameters.
1154 SemaRef.Diag(BS.getBeginLoc(),
1155 diag::note_amdgpu_named_barrier_reason_inherited)
1156 << R->getDeclName() << BS.getType();
1157 };
1158 }
1159 }
1160
1161 if (!IsWrapper)
1162 return;
1163
1164 // Set the attribute even if the wrapper may be found to be invalid later.
1165 R->addAttr(
1166 AMDGPUNamedBarrierWrapperAttr::CreateImplicit(Context, SourceRange()));
1167
1168 // This is a wrapper CXXRecordDecl, it must have a C++11 standard layout.
1169 if (CxxR && !CxxR->isCXX11StandardLayout()) {
1170 SemaRef.Diag(R->getLocation(),
1171 diag::err_amdgpu_named_barrier_wrapper_non_standard_layout)
1172 << R->getDeclName();
1173 assert(DiagWrapperNote &&
1174 "IsWrapper is set but no context diagnostic provided");
1175 DiagWrapperNote();
1176 }
1177}
1178} // namespace clang
This file declares semantic analysis functions specific to AMDGPU.
Enumerates target-specific builtins in their own namespaces within namespace clang.
APSInt & getInt()
Definition APValue.h:577
Holds long-lived AST nodes (such as types and decls) that can be referred to throughout the semantic ...
Definition ASTContext.h:246
const llvm::StringMap< bool > & getFunctionFeatureMap(const FunctionDecl *FD) const
Builtin::Context & BuiltinInfo
Definition ASTContext.h:864
CanQualType getLogicalOperationType() const
The result type of logical operations, '<', '>', '!=', etc.
CanQualType BuiltinFnTy
const TargetInfo & getTargetInfo() const
Definition ASTContext.h:981
unsigned getTargetAddressSpace(LangAS AS) const
bool isInvalid() const
Definition Ownership.h:167
static std::unique_ptr< AtomicScopeModel > create(AtomicScopeModelKind K)
Create an atomic scope model by AtomicScopeModelKind.
Definition SyncScope.h:299
Attr - This represents one attribute.
Definition Attr.h:47
SourceLocation getLocation() const
Definition Attr.h:100
SourceLocation getLoc() const
llvm::SmallString< 64 > getQuotedName(unsigned ID) const
Return the identifier name for the specified builtin inside single quotes for a diagnostic,...
Definition Builtins.cpp:86
bool isAuxBuiltinID(unsigned ID) const
Return true if the builtin ID belongs exclusively to the AuxTarget, and false if it belongs to both p...
Definition Builtins.h:521
unsigned getAuxBuiltinID(unsigned ID) const
Return real builtin ID (i.e.
Definition Builtins.h:527
const char * getRequiredFeatures(unsigned ID) const
Definition Builtins.cpp:105
Represents a base class of a C++ class.
Definition DeclCXX.h:146
CallExpr - Represents a function call (C99 6.5.2.2, C++ [expr.call]).
Definition Expr.h:3012
Expr * getArg(unsigned Arg)
getArg - Return the specified argument.
Definition Expr.h:3216
SourceLocation getBeginLoc() const
Definition Expr.h:3346
unsigned getBuiltinCallee() const
getBuiltinCallee - If this is a call to a builtin, return the builtin ID of the callee.
Definition Expr.cpp:1624
unsigned getNumArgs() const
getNumArgs - Return the number of actual arguments to this call.
Definition Expr.h:3203
Decl - This represents one declaration (or definition), e.g.
Definition DeclBase.h:86
void addAttr(Attr *A)
virtual bool TraverseStmt(MaybeConst< Stmt > *S)
This represents one expression.
Definition Expr.h:114
bool EvaluateAsInt(EvalResult &Result, const ASTContext &Ctx, SideEffectsKind AllowSideEffects=SE_NoSideEffects, bool InConstantContext=false) const
EvaluateAsInt - Return true if this is a constant which we can fold and convert to an integer,...
Expr * IgnoreParenCasts() LLVM_READONLY
Skip past any parentheses and casts which might surround this expression until reaching a fixed point...
Definition Expr.cpp:3135
void setType(QualType t)
Definition Expr.h:147
bool isValueDependent() const
Determines whether the value of this expression depends on.
Definition Expr.h:179
Expr * IgnoreParens() LLVM_READONLY
Skip past any parentheses which might surround this expression until reaching a fixed point.
Definition Expr.cpp:3126
Decl * getReferencedDeclOfCallee()
Definition Expr.cpp:1578
bool EvaluateAsConstantExpr(EvalResult &Result, const ASTContext &Ctx, ConstantExprKind Kind=ConstantExprKind::Normal) const
Evaluate an expression that is required to be a constant expression.
bool isInstantiationDependent() const
Whether this expression is instantiation-dependent, meaning that it depends in some way on.
Definition Expr.h:225
std::optional< std::string > tryEvaluateString(ASTContext &Ctx) const
If the current Expr can be evaluated to a pointer to a null-terminated constant string,...
SourceLocation getExprLoc() const LLVM_READONLY
getExprLoc - Return the preferred location for the arrow when diagnosing a problem with a generic exp...
Definition Expr.cpp:283
QualType getType() const
Definition Expr.h:146
Represents a member of a struct/union/class.
Definition Decl.h:3346
Represents a function declaration or definition.
Definition Decl.h:2082
Stmt * getBody(const FunctionDecl *&Definition) const
Retrieve the body (definition) of the function.
Definition Decl.cpp:3287
ParsedAttr - Represents a syntactic attribute.
Definition ParsedAttr.h:119
unsigned getNumArgs() const
getNumArgs - Return the number of actual arguments to this attribute.
Definition ParsedAttr.h:371
Expr * getArgAsExpr(unsigned Arg) const
Definition ParsedAttr.h:383
bool checkAtLeastNumArgs(class Sema &S, unsigned Num) const
Check if the attribute has at least as many args as Num.
bool checkAtMostNumArgs(class Sema &S, unsigned Num) const
Check if the attribute has at most as many args as Num.
A (possibly-)qualified type.
Definition TypeBase.h:938
const Type * getTypePtr() const
Retrieves a pointer to the underlying (unqualified) type.
Definition TypeBase.h:8680
Represents a struct/union/class.
Definition Decl.h:4512
Scope - A scope is a transient data structure that is used while parsing the program.
Definition Scope.h:42
void handleAMDGPUMaxNumWorkGroupsAttr(Decl *D, const ParsedAttr &AL)
void addAMDGPUFlatWorkGroupSizeAttr(Decl *D, const AttributeCommonInfo &CI, Expr *Min, Expr *Max)
addAMDGPUFlatWorkGroupSizeAttr - Adds an amdgpu_flat_work_group_size attribute to a particular declar...
bool checkCoopAtomicFunctionCall(CallExpr *TheCall, bool IsStore)
bool HasPotentiallyUnguardedBuiltinUsage(FunctionDecl *FD) const
void handleAMDGPUFlatWorkGroupSizeAttr(Decl *D, const ParsedAttr &AL)
bool checkAVLoadStore(CallExpr *TheCall, bool IsStore)
bool checkAtomicMonitorLoad(CallExpr *TheCall)
void handleAMDGPUNumSGPRAttr(Decl *D, const ParsedAttr &AL)
AMDGPUMaxNumWorkGroupsAttr * CreateAMDGPUMaxNumWorkGroupsAttr(const AttributeCommonInfo &CI, Expr *XExpr, Expr *YExpr, Expr *ZExpr)
Create an AMDGPUMaxNumWorkGroupsAttr attribute.
Expr * ExpandAMDGPUPredicateBuiltIn(Expr *CE)
Expand a valid use of the feature identification builtins into its corresponding sequence of instruct...
AMDGPUWavesPerEUAttr * CreateAMDGPUWavesPerEUAttr(const AttributeCommonInfo &CI, Expr *Min, Expr *Max)
Create an AMDGPUWavesPerEUAttr attribute.
bool CheckAMDGCNBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID, CallExpr *TheCall)
void DiagnoseUnguardedBuiltinUsage(FunctionDecl *FD)
bool checkAMDGPUTypeSupport(QualType Ty, SourceLocation Loc)
Check if Ty is supported on this AMDGPU target.
void handleAMDGPUNumVGPRAttr(Decl *D, const ParsedAttr &AL)
void checkAtomicOrderingCABIArg(Expr *E, bool MayLoad, bool MayStore)
Emits a diagnostic if the E is not an atomic ordering encoded in the C ABI format,...
AMDGPUFlatWorkGroupSizeAttr * CreateAMDGPUFlatWorkGroupSizeAttr(const AttributeCommonInfo &CI, Expr *Min, Expr *Max)
Create an AMDGPUWavesPerEUAttr attribute.
void AddPotentiallyUnguardedBuiltinUser(FunctionDecl *FD)
Diagnose unguarded usages of AMDGPU builtins and recommend guarding with __builtin_amdgcn_is_invocabl...
bool checkMovDPPFunctionCall(CallExpr *TheCall, unsigned NumArgs, unsigned NumDataArgs)
void handleAMDGPUWavesPerEUAttr(Decl *D, const ParsedAttr &AL)
void checkNamedBarrierWrapper(RecordDecl *R)
Called in ActOnFields - whenever a C/C++ Record is being finalized.
bool IsPredicate(Expr *E) const
void addAMDGPUWavesPerEUAttr(Decl *D, const AttributeCommonInfo &CI, Expr *Min, Expr *Max)
addAMDGPUWavePersEUAttr - Adds an amdgpu_waves_per_eu attribute to a particular declaration.
void addAMDGPUMaxNumWorkGroupsAttr(Decl *D, const AttributeCommonInfo &CI, Expr *XExpr, Expr *YExpr, Expr *ZExpr)
addAMDGPUMaxNumWorkGroupsAttr - Adds an amdgpu_max_num_work_groups attribute to a particular declarat...
SemaBase(Sema &S)
Definition SemaBase.cpp:7
ASTContext & getASTContext() const
Definition SemaBase.cpp:9
Sema & SemaRef
Definition SemaBase.h:49
SemaDiagnosticBuilder Diag(SourceLocation Loc, unsigned DiagID)
Emit a diagnostic.
Definition SemaBase.cpp:61
Sema - This implements semantic analysis and AST building for C.
Definition Sema.h:863
ASTContext & Context
Definition Sema.h:1339
bool DiagnoseUnexpandedParameterPack(SourceLocation Loc, TypeSourceInfo *T, UnexpandedParameterPackContext UPPC)
If the given type contains an unexpanded parameter pack, diagnose the error.
bool checkUInt32Argument(const AttrInfo &AI, const Expr *Expr, uint32_t &Val, unsigned Idx=UINT_MAX, bool StrictlyUnsigned=false)
If Expr is a valid integer constant, get the value of the integer expression and return success or fa...
Definition Sema.h:5086
Encodes a location in the source.
A trivial tuple used to represent a source range.
SourceRange getSourceRange() const LLVM_READONLY
SourceLocation tokens are not useful in isolation - they are low level value objects created/interpre...
Definition Stmt.cpp:343
SourceLocation getBeginLoc() const LLVM_READONLY
Definition Stmt.cpp:355
Exposes information about the current target.
Definition TargetInfo.h:228
const llvm::Triple & getTriple() const
Returns the target triple of the primary target.
virtual bool isProcessorName(StringRef Name) const
Returns true if the target's processor is compatible with the processor named by Name,...
The base class of the type hierarchy.
Definition TypeBase.h:1879
const Type * getPointeeOrArrayElementType() const
If this is a pointer type, return the pointee type.
Definition TypeBase.h:9497
bool isAMDGPUNamedBarrierTypeOrWrapper() const
Check if the type is the AMDGPU named barrier type/a RecordType of a named barrier wrapper,...
Definition Type.cpp:5719
QualType getPointeeType() const
If this is a pointer, ObjC object pointer, or block pointer, this returns the respective pointee.
Definition Type.cpp:885
bool isAMDGPUNamedBarrierType() const
Check if the type is the AMDGPU named barrier type, or an array thereof.
Definition Type.cpp:5715
Defines the clang::TargetInfo interface.
bool evaluateRequiredTargetFeatures(llvm::StringRef RequiredFatures, const llvm::StringMap< bool > &TargetFetureMap)
Returns true if the required target features of a builtin function are enabled.
bool LE(InterpState &S, CodePtr OpPC)
Definition Interp.h:1512
Top level wrappers for InstallAPI frontend operations.
bool isa(CodeGen::Address addr)
Definition Address.h:330
static FieldDecl * getNamedBarrierField(const RecordDecl *R)
static bool checkScopeAsInt(SemaAMDGPU &S, Expr *Scope)
@ If
'if' clause, allowed on all the Compute Constructs, Data Constructs, Executable Constructs,...
@ Result
The result type of a method or function.
Definition TypeBase.h:906
static bool checkAMDGPUMaxNumWorkGroupsArguments(Sema &S, Expr *XExpr, Expr *YExpr, Expr *ZExpr, const AMDGPUMaxNumWorkGroupsAttr &Attr)
DynamicRecursiveASTVisitorBase< false > DynamicRecursiveASTVisitor
U cast(CodeGen::Address addr)
Definition Address.h:327
static bool checkAMDGPUFlatWorkGroupSizeArguments(Sema &S, Expr *MinExpr, Expr *MaxExpr, const AMDGPUFlatWorkGroupSizeAttr &Attr)
static bool checkGlobalOrFlatPointerArg(SemaAMDGPU &S, CallExpr *TheCall)
ActionResult< Expr * > ExprResult
Definition Ownership.h:249
static bool checkAMDGPUWavesPerEUArguments(Sema &S, Expr *MinExpr, Expr *MaxExpr, const AMDGPUWavesPerEUAttr &Attr)
int const char * function
Definition c++config.h:31
__builtin_elementwise_add_sat __builtin_elementwise_sub_sat uint32_t uint64_t __builtin_riscv_ssha_i32 __builtin_riscv_sshl_u32 uint64_t
int32_t uint32_t uint32_t __builtin_riscv_mhracc_i32 __builtin_riscv_mhraccu_u32 __builtin_riscv_mhraccsu_i32 __builtin_riscv_mhacc_h1_i32 __builtin_riscv_mhaccsu_h1_i32 __builtin_riscv_mulqr_i32 __builtin_riscv_mqrwacc_i64 __packed_splat4 __packed_splat2 __packed_splat8 __packed_splat4 __packed_splat2 uint8_t
EvalResult is a struct with detailed info about an evaluated expression.
Definition Expr.h:667
APValue Val
Val - This is the value the expression can be folded to.
Definition Expr.h:669