1//===--- AMDGPU.h - Declare AMDGPU target feature support -------*- C++ -*-===//
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 declares AMDGPU TargetInfo objects.
10//
11//===----------------------------------------------------------------------===//
12
13#ifndef LLVM_CLANG_LIB_BASIC_TARGETS_AMDGPU_H
14#define LLVM_CLANG_LIB_BASIC_TARGETS_AMDGPU_H
15
16#include "clang/Basic/TargetID.h"
17#include "clang/Basic/TargetInfo.h"
18#include "clang/Basic/TargetOptions.h"
19#include "llvm/ADT/StringSet.h"
20#include "llvm/Support/AMDGPUAddrSpace.h"
21#include "llvm/Support/Compiler.h"
22#include "llvm/TargetParser/AMDGPUTargetParser.h"
23#include "llvm/TargetParser/Triple.h"
24#include <optional>
25
26namespace clang {
27namespace targets {
28
29class LLVM_LIBRARY_VISIBILITY AMDGPUTargetInfo final : public TargetInfo {
30
31 static const char *const GCCRegNames[];
32
33 static const LangASMap AMDGPUAddrSpaceMap;
34
35 llvm::AMDGPU::GPUKind GPUKind;
36 unsigned GPUFeatures;
37 unsigned WavefrontSize;
38
39 /// Whether to use cumode or WGP mode. True for cumode. False for WGP mode.
40 bool CUMode;
41
42 /// Whether having image instructions.
43 bool HasImage = false;
44
45 /// Target ID is device name followed by optional feature name postfixed
46 /// by plus or minus sign delimitted by colon, e.g. gfx908:xnack+:sramecc-.
47 /// If the target ID contains feature+, map it to true.
48 /// If the target ID contains feature-, map it to false.
49 /// If the target ID does not contain a feature (default), do not map it.
50 llvm::StringMap<bool> OffloadArchFeatures;
51 std::string TargetID;
52
53 bool hasFP64() const {
54 return getTriple().isAMDGCN() ||
55 !!(GPUFeatures & llvm::AMDGPU::FEATURE_FP64);
56 }
57
58 /// Has fast fma f32
59 bool hasFastFMAF() const {
60 return !!(GPUFeatures & llvm::AMDGPU::FEATURE_FAST_FMA_F32);
61 }
62
63 /// Has fast fma f64
64 bool hasFastFMA() const { return getTriple().isAMDGCN(); }
65
66 bool hasFMAF() const {
67 return getTriple().isAMDGCN() ||
68 !!(GPUFeatures & llvm::AMDGPU::FEATURE_FMA);
69 }
70
71 bool hasFullRateDenormalsF32() const {
72 return !!(GPUFeatures & llvm::AMDGPU::FEATURE_FAST_DENORMAL_F32);
73 }
74
75 bool hasLDEXPF() const {
76 return getTriple().isAMDGCN() ||
77 !!(GPUFeatures & llvm::AMDGPU::FEATURE_LDEXP);
78 }
79
80 static bool isR600(const llvm::Triple &TT) {
81 return TT.getArch() == llvm::Triple::r600;
82 }
83
84 bool hasFlatSupport() const {
85 if (GPUKind >= llvm::AMDGPU::GK_GFX700)
86 return true;
87
88 // Dummy target is assumed to be gfx700+ for amdhsa.
89 if (GPUKind == llvm::AMDGPU::GK_NONE &&
90 getTriple().getOS() == llvm::Triple::AMDHSA)
91 return true;
92
93 return false;
94 }
95
96public:
97 AMDGPUTargetInfo(const llvm::Triple &Triple, const TargetOptions &Opts);
98
99 void adjust(DiagnosticsEngine &Diags, LangOptions &Opts,
100 const TargetInfo *Aux) override;
101
102 uint64_t getPointerWidthV(LangAS AS) const override {
103 if (isR600(TT: getTriple()))
104 return 32;
105 unsigned TargetAS = getTargetAddressSpace(AS);
106
107 if (TargetAS == llvm::AMDGPUAS::PRIVATE_ADDRESS ||
108 TargetAS == llvm::AMDGPUAS::LOCAL_ADDRESS)
109 return 32;
110
111 return 64;
112 }
113
114 uint64_t getPointerAlignV(LangAS AddrSpace) const override {
115 return getPointerWidthV(AS: AddrSpace);
116 }
117
118 virtual bool isAddressSpaceSupersetOf(LangAS A, LangAS B) const override {
119 // The flat address space AS(0) is a superset of all the other address
120 // spaces used by the backend target.
121 return A == B ||
122 ((A == LangAS::Default ||
123 (isTargetAddressSpace(AS: A) &&
124 toTargetAddressSpace(AS: A) == llvm::AMDGPUAS::FLAT_ADDRESS)) &&
125 isTargetAddressSpace(AS: B) &&
126 toTargetAddressSpace(AS: B) >= llvm::AMDGPUAS::FLAT_ADDRESS &&
127 toTargetAddressSpace(AS: B) <= llvm::AMDGPUAS::PRIVATE_ADDRESS &&
128 toTargetAddressSpace(AS: B) != llvm::AMDGPUAS::REGION_ADDRESS);
129 }
130
131 uint64_t getMaxPointerWidth() const override {
132 return getTriple().isAMDGCN() ? 64 : 32;
133 }
134
135 bool hasBFloat16Type() const override { return getTriple().isAMDGCN(); }
136
137 std::string_view getClobbers() const override { return ""; }
138
139 ArrayRef<const char *> getGCCRegNames() const override;
140
141 ArrayRef<TargetInfo::GCCRegAlias> getGCCRegAliases() const override {
142 return {};
143 }
144
145 /// Accepted register names: (n, m is unsigned integer, n < m)
146 /// v
147 /// s
148 /// a
149 /// {vn}, {v[n]}
150 /// {sn}, {s[n]}
151 /// {an}, {a[n]}
152 /// {S} , where S is a special register name
153 ////{v[n:m]}
154 /// {s[n:m]}
155 /// {a[n:m]}
156 bool validateAsmConstraint(const char *&Name,
157 TargetInfo::ConstraintInfo &Info) const override {
158 static const ::llvm::StringSet<> SpecialRegs({
159 "exec", "vcc", "flat_scratch", "m0", "scc", "tba", "tma",
160 "flat_scratch_lo", "flat_scratch_hi", "vcc_lo", "vcc_hi", "exec_lo",
161 "exec_hi", "tma_lo", "tma_hi", "tba_lo", "tba_hi",
162 });
163
164 switch (*Name) {
165 case 'I':
166 Info.setRequiresImmediate(Min: -16, Max: 64);
167 return true;
168 case 'J':
169 Info.setRequiresImmediate(Min: -32768, Max: 32767);
170 return true;
171 case 'A':
172 case 'B':
173 case 'C':
174 Info.setRequiresImmediate();
175 return true;
176 default:
177 break;
178 }
179
180 StringRef S(Name);
181
182 if (S == "DA" || S == "DB") {
183 Name++;
184 Info.setRequiresImmediate();
185 return true;
186 }
187
188 bool HasLeftParen = S.consume_front(Prefix: "{");
189 if (S.empty())
190 return false;
191 if (S.front() != 'v' && S.front() != 's' && S.front() != 'a') {
192 if (!HasLeftParen)
193 return false;
194 auto E = S.find(C: '}');
195 if (!SpecialRegs.count(Key: S.substr(Start: 0, N: E)))
196 return false;
197 S = S.drop_front(N: E + 1);
198 if (!S.empty())
199 return false;
200 // Found {S} where S is a special register.
201 Info.setAllowsRegister();
202 Name = S.data() - 1;
203 return true;
204 }
205 S = S.drop_front();
206 if (!HasLeftParen) {
207 if (!S.empty())
208 return false;
209 // Found s, v or a.
210 Info.setAllowsRegister();
211 Name = S.data() - 1;
212 return true;
213 }
214 bool HasLeftBracket = S.consume_front(Prefix: "[");
215 unsigned long long N;
216 if (S.empty() || consumeUnsignedInteger(Str&: S, Radix: 10, Result&: N))
217 return false;
218 if (S.consume_front(Prefix: ":")) {
219 if (!HasLeftBracket)
220 return false;
221 unsigned long long M;
222 if (consumeUnsignedInteger(Str&: S, Radix: 10, Result&: M) || N >= M)
223 return false;
224 }
225 if (HasLeftBracket) {
226 if (!S.consume_front(Prefix: "]"))
227 return false;
228 }
229 if (!S.consume_front(Prefix: "}"))
230 return false;
231 if (!S.empty())
232 return false;
233 // Found {vn}, {sn}, {an}, {v[n]}, {s[n]}, {a[n]}, {v[n:m]}, {s[n:m]}
234 // or {a[n:m]}.
235 Info.setAllowsRegister();
236 Name = S.data() - 1;
237 return true;
238 }
239
240 // \p Constraint will be left pointing at the last character of
241 // the constraint. In practice, it won't be changed unless the
242 // constraint is longer than one character.
243 std::string convertConstraint(const char *&Constraint) const override {
244
245 StringRef S(Constraint);
246 if (S == "DA" || S == "DB") {
247 return std::string("^") + std::string(Constraint++, 2);
248 }
249
250 const char *Begin = Constraint;
251 TargetInfo::ConstraintInfo Info("", "");
252 if (validateAsmConstraint(Name&: Constraint, Info))
253 return std::string(Begin).substr(pos: 0, n: Constraint - Begin + 1);
254
255 Constraint = Begin;
256 return std::string(1, *Constraint);
257 }
258
259 bool
260 initFeatureMap(llvm::StringMap<bool> &Features, DiagnosticsEngine &Diags,
261 StringRef CPU,
262 const std::vector<std::string> &FeatureVec) const override;
263
264 llvm::SmallVector<Builtin::InfosShard> getTargetBuiltins() const override;
265
266 bool useFP16ConversionIntrinsics() const override { return false; }
267
268 void getTargetDefines(const LangOptions &Opts,
269 MacroBuilder &Builder) const override;
270
271 BuiltinVaListKind getBuiltinVaListKind() const override {
272 return TargetInfo::CharPtrBuiltinVaList;
273 }
274
275 bool isValidCPUName(StringRef Name) const override {
276 if (getTriple().isAMDGCN())
277 return llvm::AMDGPU::parseArchAMDGCN(CPU: Name) != llvm::AMDGPU::GK_NONE;
278 return llvm::AMDGPU::parseArchR600(CPU: Name) != llvm::AMDGPU::GK_NONE;
279 }
280
281 void fillValidCPUList(SmallVectorImpl<StringRef> &Values) const override;
282
283 bool setCPU(StringRef Name) override {
284 if (getTriple().isAMDGCN()) {
285 GPUKind = llvm::AMDGPU::parseArchAMDGCN(CPU: Name);
286 GPUFeatures = llvm::AMDGPU::getArchAttrAMDGCN(AK: GPUKind);
287 } else {
288 GPUKind = llvm::AMDGPU::parseArchR600(CPU: Name);
289 GPUFeatures = llvm::AMDGPU::getArchAttrR600(AK: GPUKind);
290 }
291
292 return GPUKind != llvm::AMDGPU::GK_NONE;
293 }
294
295 void setSupportedOpenCLOpts() override {
296 auto &Opts = getSupportedOpenCLOpts();
297 Opts["cl_clang_storage_class_specifiers"] = true;
298 Opts["__cl_clang_variadic_functions"] = true;
299 Opts["__cl_clang_function_pointers"] = true;
300 Opts["__cl_clang_function_scope_local_variables"] = true;
301 Opts["__cl_clang_non_portable_kernel_param_types"] = true;
302 Opts["__cl_clang_bitfields"] = true;
303
304 bool IsAMDGCN = getTriple().isAMDGCN();
305
306 Opts["cl_khr_fp64"] = hasFP64();
307 Opts["__opencl_c_fp64"] = hasFP64();
308
309 if (IsAMDGCN || GPUKind >= llvm::AMDGPU::GK_CEDAR) {
310 Opts["cl_khr_byte_addressable_store"] = true;
311 Opts["cl_khr_global_int32_base_atomics"] = true;
312 Opts["cl_khr_global_int32_extended_atomics"] = true;
313 Opts["cl_khr_local_int32_base_atomics"] = true;
314 Opts["cl_khr_local_int32_extended_atomics"] = true;
315 }
316
317 if (IsAMDGCN) {
318 Opts["cl_khr_fp16"] = true;
319 Opts["cl_khr_int64_base_atomics"] = true;
320 Opts["cl_khr_int64_extended_atomics"] = true;
321 Opts["cl_khr_mipmap_image"] = true;
322 Opts["cl_khr_mipmap_image_writes"] = true;
323 Opts["cl_khr_subgroups"] = true;
324 Opts["cl_amd_media_ops"] = true;
325 Opts["cl_amd_media_ops2"] = true;
326
327 // FIXME: Check subtarget for image support.
328 Opts["__opencl_c_images"] = true;
329 Opts["__opencl_c_3d_image_writes"] = true;
330 Opts["__opencl_c_read_write_images"] = true;
331 Opts["cl_khr_3d_image_writes"] = true;
332 Opts["__opencl_c_program_scope_global_variables"] = true;
333 Opts["__opencl_c_atomic_order_acq_rel"] = true;
334 Opts["__opencl_c_atomic_order_seq_cst"] = true;
335 Opts["__opencl_c_atomic_scope_device"] = true;
336 Opts["__opencl_c_atomic_scope_all_devices"] = true;
337 Opts["__opencl_c_work_group_collective_functions"] = true;
338
339 if (hasFlatSupport()) {
340 Opts["__opencl_c_generic_address_space"] = true;
341 Opts["__opencl_c_device_enqueue"] = true;
342 Opts["__opencl_c_pipes"] = true;
343 }
344
345 if (getTriple().getEnvironment() == llvm::Triple::LLVM) {
346 Opts["cl_khr_subgroup_extended_types"] = true;
347 }
348 }
349 }
350
351 LangAS getOpenCLTypeAddrSpace(OpenCLTypeKind TK) const override {
352 switch (TK) {
353 case OCLTK_Image:
354 return LangAS::opencl_constant;
355
356 case OCLTK_ClkEvent:
357 case OCLTK_Queue:
358 case OCLTK_ReserveID:
359 return LangAS::opencl_global;
360
361 default:
362 return TargetInfo::getOpenCLTypeAddrSpace(TK);
363 }
364 }
365
366 LangAS getOpenCLBuiltinAddressSpace(unsigned AS) const override {
367 switch (AS) {
368 case 0:
369 return LangAS::opencl_generic;
370 case 1:
371 return LangAS::opencl_global;
372 case 3:
373 return LangAS::opencl_local;
374 case 4:
375 return LangAS::opencl_constant;
376 case 5:
377 return LangAS::opencl_private;
378 default:
379 return getLangASFromTargetAS(TargetAS: AS);
380 }
381 }
382
383 LangAS getCUDABuiltinAddressSpace(unsigned AS) const override {
384 switch (AS) {
385 case 0:
386 return LangAS::Default;
387 case 1:
388 return LangAS::cuda_device;
389 case 3:
390 return LangAS::cuda_shared;
391 case 4:
392 return LangAS::cuda_constant;
393 default:
394 return getLangASFromTargetAS(TargetAS: AS);
395 }
396 }
397
398 std::optional<LangAS> getConstantAddressSpace() const override {
399 return getLangASFromTargetAS(TargetAS: llvm::AMDGPUAS::CONSTANT_ADDRESS);
400 }
401
402 const llvm::omp::GV &getGridValue() const override {
403 switch (WavefrontSize) {
404 case 32:
405 return llvm::omp::getAMDGPUGridValues<32>();
406 case 64:
407 return llvm::omp::getAMDGPUGridValues<64>();
408 default:
409 llvm_unreachable("getGridValue not implemented for this wavesize");
410 }
411 }
412
413 /// \returns Target specific vtbl ptr address space.
414 unsigned getVtblPtrAddressSpace() const override {
415 return static_cast<unsigned>(llvm::AMDGPUAS::CONSTANT_ADDRESS);
416 }
417
418 /// \returns If a target requires an address within a target specific address
419 /// space \p AddressSpace to be converted in order to be used, then return the
420 /// corresponding target specific DWARF address space.
421 ///
422 /// \returns Otherwise return std::nullopt and no conversion will be emitted
423 /// in the DWARF.
424 std::optional<unsigned>
425 getDWARFAddressSpace(unsigned AddressSpace) const override {
426 int DWARFAS = llvm::AMDGPU::mapToDWARFAddrSpace(LLVMAddrSpace: AddressSpace);
427 // If there is no corresponding address space identifier, or it would be
428 // the default, then don't emit the attribute.
429 if (DWARFAS == -1 || DWARFAS == llvm::AMDGPU::DWARFAS::DEFAULT)
430 return std::nullopt;
431 return DWARFAS;
432 }
433
434 CallingConvCheckResult checkCallingConvention(CallingConv CC) const override {
435 switch (CC) {
436 default:
437 return CCCR_Warning;
438 case CC_C:
439 case CC_DeviceKernel:
440 return CCCR_OK;
441 }
442 }
443
444 // In amdgcn target the null pointer in global, constant, and generic
445 // address space has value 0 but in private and local address space has
446 // value ~0.
447 uint64_t getNullPointerValue(LangAS AS) const override {
448 // Check language-specific address spaces
449 if (AS == LangAS::opencl_local || AS == LangAS::opencl_private ||
450 AS == LangAS::sycl_local || AS == LangAS::sycl_private)
451 return ~0;
452 if (isTargetAddressSpace(AS))
453 return llvm::AMDGPU::getNullPointerValue(AS: toTargetAddressSpace(AS));
454 return 0;
455 }
456
457 void setAuxTarget(const TargetInfo *Aux) override;
458
459 bool hasBitIntType() const override { return true; }
460
461 // Record offload arch features since they are needed for defining the
462 // pre-defined macros.
463 bool handleTargetFeatures(std::vector<std::string> &Features,
464 DiagnosticsEngine &Diags) override {
465 HasFullBFloat16 = true;
466 auto TargetIDFeatures =
467 getAllPossibleTargetIDFeatures(T: getTriple(), Processor: getArchNameAMDGCN(AK: GPUKind));
468 for (const auto &F : Features) {
469 assert(F.front() == '+' || F.front() == '-');
470 if (F == "+wavefrontsize64")
471 WavefrontSize = 64;
472 else if (F == "+cumode")
473 CUMode = true;
474 else if (F == "-cumode")
475 CUMode = false;
476 else if (F == "+image-insts")
477 HasImage = true;
478 bool IsOn = F.front() == '+';
479 StringRef Name = StringRef(F).drop_front();
480 if (!llvm::is_contained(Range&: TargetIDFeatures, Element: Name))
481 continue;
482 assert(!OffloadArchFeatures.contains(Name));
483 OffloadArchFeatures[Name] = IsOn;
484 }
485 return true;
486 }
487
488 bool isProcessorName(StringRef Name) const override {
489 llvm::AMDGPU::GPUKind NameKind = getTriple().isAMDGCN()
490 ? llvm::AMDGPU::parseArchAMDGCN(CPU: Name)
491 : llvm::AMDGPU::parseArchR600(CPU: Name);
492 return NameKind == GPUKind;
493 }
494
495 bool hasHIPImageSupport() const override { return HasImage; }
496
497 std::pair<unsigned, unsigned> hardwareInterferenceSizes() const override {
498 // This is imprecise as the value can vary between 64, 128 (even 256!) bytes
499 // depending on the level of cache and the target architecture. We select
500 // the size that corresponds to the largest L1 cache line for all
501 // architectures.
502 return std::make_pair(x: 128, y: 128);
503 }
504};
505
506} // namespace targets
507} // namespace clang
508
509#endif // LLVM_CLANG_LIB_BASIC_TARGETS_AMDGPU_H
510