clang 23.0.0git
SPIR.cpp
Go to the documentation of this file.
1//===- SPIR.cpp -----------------------------------------------------------===//
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#include "ABIInfoImpl.h"
11#include "TargetInfo.h"
13#include "llvm/IR/DerivedTypes.h"
14
15#include <stdint.h>
16#include <utility>
17
18using namespace clang;
19using namespace clang::CodeGen;
20
21//===----------------------------------------------------------------------===//
22// Base ABI and target codegen info implementation common between SPIR and
23// SPIR-V.
24//===----------------------------------------------------------------------===//
25
26namespace {
27class CommonSPIRABIInfo : public DefaultABIInfo {
28public:
29 CommonSPIRABIInfo(CodeGenTypes &CGT) : DefaultABIInfo(CGT) { setCCs(); }
30
31private:
32 void setCCs();
33};
34
35class SPIRVABIInfo : public CommonSPIRABIInfo {
36public:
37 SPIRVABIInfo(CodeGenTypes &CGT) : CommonSPIRABIInfo(CGT) {}
38 void computeInfo(CGFunctionInfo &FI) const override;
39 RValue EmitVAArg(CodeGenFunction &CGF, Address VAListAddr, QualType Ty,
40 AggValueSlot Slot) const override;
41
42 llvm::FixedVectorType *
43 getOptimalVectorMemoryType(llvm::FixedVectorType *Ty,
44 const LangOptions &LangOpt) const override;
45
46private:
47 ABIArgInfo classifyKernelArgumentType(QualType Ty) const;
48};
49
50class AMDGCNSPIRVABIInfo : public SPIRVABIInfo {
51 // TODO: this should be unified / shared with AMDGPU, ideally we'd like to
52 // re-use AMDGPUABIInfo eventually, rather than duplicate.
53 static constexpr unsigned MaxNumRegsForArgsRet = 16; // 16 32-bit registers
54 mutable unsigned NumRegsLeft = 0;
55
56 uint64_t numRegsForType(QualType Ty) const;
57
58 bool isHomogeneousAggregateBaseType(QualType Ty) const override {
59 return true;
60 }
61 bool isHomogeneousAggregateSmallEnough(const Type *Base,
62 uint64_t Members) const override {
63 uint32_t NumRegs = (getContext().getTypeSize(Base) + 31) / 32;
64
65 // Homogeneous Aggregates may occupy at most 16 registers.
66 return Members * NumRegs <= MaxNumRegsForArgsRet;
67 }
68
69 // Coerce HIP scalar pointer arguments from generic pointers to global ones.
70 llvm::Type *coerceKernelArgumentType(llvm::Type *Ty, unsigned FromAS,
71 unsigned ToAS) const;
72
73 ABIArgInfo classifyReturnType(QualType RetTy) const;
74 ABIArgInfo classifyKernelArgumentType(QualType Ty) const;
75 ABIArgInfo classifyArgumentType(QualType Ty) const;
76
77public:
78 AMDGCNSPIRVABIInfo(CodeGenTypes &CGT) : SPIRVABIInfo(CGT) {}
79 void computeInfo(CGFunctionInfo &FI) const override;
80
81 llvm::FixedVectorType *
82 getOptimalVectorMemoryType(llvm::FixedVectorType *Ty,
83 const LangOptions &LangOpt) const override;
84};
85} // end anonymous namespace
86namespace {
87class CommonSPIRTargetCodeGenInfo : public TargetCodeGenInfo {
88public:
89 CommonSPIRTargetCodeGenInfo(CodeGen::CodeGenTypes &CGT)
90 : TargetCodeGenInfo(std::make_unique<CommonSPIRABIInfo>(CGT)) {}
91 CommonSPIRTargetCodeGenInfo(std::unique_ptr<ABIInfo> ABIInfo)
92 : TargetCodeGenInfo(std::move(ABIInfo)) {}
93
94 LangAS getASTAllocaAddressSpace() const override {
96 getABIInfo().getDataLayout().getAllocaAddrSpace());
97 }
98
99 unsigned getDeviceKernelCallingConv() const override;
100 llvm::Type *getOpenCLType(CodeGenModule &CGM, const Type *T) const override;
101 llvm::Type *getHLSLType(CodeGenModule &CGM, const Type *Ty,
102 const CGHLSLOffsetInfo &OffsetInfo) const override;
103
104 llvm::Type *getHLSLPadding(CodeGenModule &CGM,
105 CharUnits NumBytes) const override {
106 unsigned Size = NumBytes.getQuantity();
107 return llvm::TargetExtType::get(CGM.getLLVMContext(), "spirv.Padding", {},
108 {Size});
109 }
110
111 bool isHLSLPadding(llvm::Type *Ty) const override {
112 if (auto *TET = dyn_cast<llvm::TargetExtType>(Ty))
113 return TET->getName() == "spirv.Padding";
114 return false;
115 }
116
117 llvm::Type *getSPIRVImageTypeFromHLSLResource(
118 const HLSLAttributedResourceType::Attributes &attributes,
119 QualType SampledType, CodeGenModule &CGM) const;
120 void
121 setOCLKernelStubCallingConvention(const FunctionType *&FT) const override;
122 llvm::Constant *getNullPointer(const CodeGen::CodeGenModule &CGM,
123 llvm::PointerType *T,
124 QualType QT) const override;
125};
126class SPIRVTargetCodeGenInfo : public CommonSPIRTargetCodeGenInfo {
127public:
128 SPIRVTargetCodeGenInfo(CodeGen::CodeGenTypes &CGT)
129 : CommonSPIRTargetCodeGenInfo(
130 (CGT.getTarget().getTriple().getVendor() == llvm::Triple::AMD)
131 ? std::make_unique<AMDGCNSPIRVABIInfo>(CGT)
132 : std::make_unique<SPIRVABIInfo>(CGT)) {}
133 void setCUDAKernelCallingConvention(const FunctionType *&FT) const override;
134 LangAS getGlobalVarAddressSpace(CodeGenModule &CGM,
135 const VarDecl *D) const override;
136 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
137 CodeGen::CodeGenModule &M) const override;
138 StringRef getLLVMSyncScopeStr(const LangOptions &LangOpts, SyncScope Scope,
139 llvm::AtomicOrdering Ordering) const override;
140 bool supportsLibCall() const override {
141 return getABIInfo().getTarget().getTriple().getVendor() !=
142 llvm::Triple::AMD;
143 }
144};
145} // End anonymous namespace.
146
147void CommonSPIRABIInfo::setCCs() {
148 assert(getRuntimeCC() == llvm::CallingConv::C);
149 RuntimeCC = llvm::CallingConv::SPIR_FUNC;
150}
151
152ABIArgInfo SPIRVABIInfo::classifyKernelArgumentType(QualType Ty) const {
153 // Coerce pointer arguments with default address space to CrossWorkGroup
154 // pointers as default address space kernel
155 // arguments are not allowed. We use the opencl_global language address
156 // space which always maps to CrossWorkGroup.
157 llvm::Type *LTy = CGT.ConvertType(Ty);
158 auto DefaultAS = getContext().getTargetAddressSpace(LangAS::Default);
159 auto GlobalAS = getContext().getTargetAddressSpace(LangAS::opencl_global);
160 auto *PtrTy = llvm::dyn_cast<llvm::PointerType>(LTy);
161 if (PtrTy && PtrTy->getAddressSpace() == DefaultAS) {
162 LTy = llvm::PointerType::get(PtrTy->getContext(), GlobalAS);
163 return ABIArgInfo::getDirect(LTy, 0, nullptr, false);
164 }
165
166 if (getContext().getLangOpts().isTargetDevice() &&
168 // Force copying aggregate type in kernel arguments by value when
169 // compiling CUDA targeting SPIR-V. This is required for the object
170 // copied to be valid on the device.
171 // This behavior follows the CUDA spec
172 // https://docs.nvidia.com/cuda/cuda-c-programming-guide/index.html#global-function-argument-processing,
173 // and matches the NVPTX implementation. TODO: hardcoding to 0 should be
174 // revisited if HIPSPV / byval starts making use of the AS of an indirect
175 // arg.
176 return getNaturalAlignIndirect(Ty, /*AddrSpace=*/0, /*byval=*/true);
177 }
178 return classifyArgumentType(Ty);
179}
180
181void SPIRVABIInfo::computeInfo(CGFunctionInfo &FI) const {
182 // The logic is same as in DefaultABIInfo with an exception on the kernel
183 // arguments handling.
184 llvm::CallingConv::ID CC = FI.getCallingConvention();
185
186 for (auto &&[ArgumentsCount, I] : llvm::enumerate(FI.arguments()))
187 I.info = ArgumentsCount < FI.getNumRequiredArgs()
188 ? classifyArgumentType(I.type)
189 : ABIArgInfo::getDirect();
190
191 if (!getCXXABI().classifyReturnType(FI))
193
194 for (auto &I : FI.arguments()) {
195 if (CC == llvm::CallingConv::SPIR_KERNEL) {
196 I.info = classifyKernelArgumentType(I.type);
197 } else {
198 I.info = classifyArgumentType(I.type);
199 }
200 }
201}
202
203RValue SPIRVABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
204 QualType Ty, AggValueSlot Slot) const {
205 return emitVoidPtrVAArg(CGF, VAListAddr, Ty, /*IsIndirect=*/false,
206 getContext().getTypeInfoInChars(Ty),
208 /*AllowHigherAlign=*/true, Slot);
209}
210
211uint64_t AMDGCNSPIRVABIInfo::numRegsForType(QualType Ty) const {
212 // This duplicates the AMDGPUABI computation.
213 uint64_t NumRegs = 0;
214
215 if (const VectorType *VT = Ty->getAs<VectorType>()) {
216 // Compute from the number of elements. The reported size is based on the
217 // in-memory size, which includes the padding 4th element for 3-vectors.
218 QualType EltTy = VT->getElementType();
219 uint64_t EltSize = getContext().getTypeSize(EltTy);
220
221 // 16-bit element vectors should be passed as packed.
222 if (EltSize == 16)
223 return (VT->getNumElements() + 1) / 2;
224
225 uint64_t EltNumRegs = (EltSize + 31) / 32;
226 return EltNumRegs * VT->getNumElements();
227 }
228
229 if (const auto *RD = Ty->getAsRecordDecl()) {
230 assert(!RD->hasFlexibleArrayMember());
231
232 for (const FieldDecl *Field : RD->fields()) {
233 QualType FieldTy = Field->getType();
234 NumRegs += numRegsForType(FieldTy);
235 }
236
237 return NumRegs;
238 }
239
240 return (getContext().getTypeSize(Ty) + 31) / 32;
241}
242
243llvm::Type *AMDGCNSPIRVABIInfo::coerceKernelArgumentType(llvm::Type *Ty,
244 unsigned FromAS,
245 unsigned ToAS) const {
246 // Single value types.
247 auto *PtrTy = llvm::dyn_cast<llvm::PointerType>(Ty);
248 if (PtrTy && PtrTy->getAddressSpace() == FromAS)
249 return llvm::PointerType::get(Ty->getContext(), ToAS);
250 return Ty;
251}
252
253ABIArgInfo AMDGCNSPIRVABIInfo::classifyReturnType(QualType RetTy) const {
254 if (!isAggregateTypeForABI(RetTy) || getRecordArgABI(RetTy, getCXXABI()))
256
257 // Ignore empty structs/unions.
258 if (isEmptyRecord(getContext(), RetTy, true))
259 return ABIArgInfo::getIgnore();
260
261 // Lower single-element structs to just return a regular value.
262 if (const Type *SeltTy = isSingleElementStruct(RetTy, getContext()))
263 return ABIArgInfo::getDirect(CGT.ConvertType(QualType(SeltTy, 0)));
264
265 if (const auto *RD = RetTy->getAsRecordDecl();
266 RD && RD->hasFlexibleArrayMember())
268
269 // Pack aggregates <= 4 bytes into single VGPR or pair.
270 uint64_t Size = getContext().getTypeSize(RetTy);
271 if (Size <= 16)
272 return ABIArgInfo::getDirect(llvm::Type::getInt16Ty(getVMContext()));
273
274 if (Size <= 32)
275 return ABIArgInfo::getDirect(llvm::Type::getInt32Ty(getVMContext()));
276
277 // TODO: This carried over from AMDGPU oddity, we retain it to
278 // ensure consistency, but it might be reasonable to return Int64.
279 if (Size <= 64) {
280 llvm::Type *I32Ty = llvm::Type::getInt32Ty(getVMContext());
281 return ABIArgInfo::getDirect(llvm::ArrayType::get(I32Ty, 2));
282 }
283
284 if (numRegsForType(RetTy) <= MaxNumRegsForArgsRet)
285 return ABIArgInfo::getDirect();
287}
288
289/// For kernels all parameters are really passed in a special buffer. It doesn't
290/// make sense to pass anything byval, so everything must be direct.
291ABIArgInfo AMDGCNSPIRVABIInfo::classifyKernelArgumentType(QualType Ty) const {
293
294 // TODO: Can we omit empty structs?
295
296 if (const Type *SeltTy = isSingleElementStruct(Ty, getContext()))
297 Ty = QualType(SeltTy, 0);
298
299 llvm::Type *OrigLTy = CGT.ConvertType(Ty);
300 llvm::Type *LTy = OrigLTy;
301 if (getContext().getLangOpts().isTargetDevice()) {
302 LTy = coerceKernelArgumentType(
303 OrigLTy, /*FromAS=*/getContext().getTargetAddressSpace(LangAS::Default),
304 /*ToAS=*/getContext().getTargetAddressSpace(LangAS::opencl_global));
305 }
306
307 // FIXME: This doesn't apply the optimization of coercing pointers in structs
308 // to global address space when using byref. This would require implementing a
309 // new kind of coercion of the in-memory type when for indirect arguments.
310 if (LTy == OrigLTy && isAggregateTypeForABI(Ty)) {
312 getContext().getTypeAlignInChars(Ty),
313 getContext().getTargetAddressSpace(LangAS::opencl_constant),
314 false /*Realign*/, nullptr /*Padding*/);
315 }
316
317 // TODO: inhibiting flattening is an AMDGPU workaround for Clover, which might
318 // be vestigial and should be revisited.
319 return ABIArgInfo::getDirect(LTy, 0, nullptr, false);
320}
321
322ABIArgInfo AMDGCNSPIRVABIInfo::classifyArgumentType(QualType Ty) const {
323 assert(NumRegsLeft <= MaxNumRegsForArgsRet && "register estimate underflow");
324
326
327 // TODO: support for variadics.
328
329 if (!isAggregateTypeForABI(Ty)) {
330 ABIArgInfo ArgInfo = DefaultABIInfo::classifyArgumentType(Ty);
331 if (!ArgInfo.isIndirect()) {
332 uint64_t NumRegs = numRegsForType(Ty);
333 NumRegsLeft -= std::min(NumRegs, uint64_t{NumRegsLeft});
334 }
335
336 return ArgInfo;
337 }
338
339 // Records with non-trivial destructors/copy-constructors should not be
340 // passed by value.
341 if (auto RAA = getRecordArgABI(Ty, getCXXABI()))
342 return getNaturalAlignIndirect(Ty, getDataLayout().getAllocaAddrSpace(),
344
345 // Ignore empty structs/unions.
346 if (isEmptyRecord(getContext(), Ty, true))
347 return ABIArgInfo::getIgnore();
348
349 // Lower single-element structs to just pass a regular value. TODO: We
350 // could do reasonable-size multiple-element structs too, using getExpand(),
351 // though watch out for things like bitfields.
352 if (const Type *SeltTy = isSingleElementStruct(Ty, getContext()))
353 return ABIArgInfo::getDirect(CGT.ConvertType(QualType(SeltTy, 0)));
354
355 if (const auto *RD = Ty->getAsRecordDecl();
356 RD && RD->hasFlexibleArrayMember())
358
359 uint64_t Size = getContext().getTypeSize(Ty);
360 if (Size <= 64) {
361 // Pack aggregates <= 8 bytes into single VGPR or pair.
362 unsigned NumRegs = (Size + 31) / 32;
363 NumRegsLeft -= std::min(NumRegsLeft, NumRegs);
364
365 if (Size <= 16)
366 return ABIArgInfo::getDirect(llvm::Type::getInt16Ty(getVMContext()));
367
368 if (Size <= 32)
369 return ABIArgInfo::getDirect(llvm::Type::getInt32Ty(getVMContext()));
370
371 // TODO: This is an AMDGPU oddity, and might be vestigial, we retain it to
372 // ensure consistency, but it should be revisited.
373 llvm::Type *I32Ty = llvm::Type::getInt32Ty(getVMContext());
374 return ABIArgInfo::getDirect(llvm::ArrayType::get(I32Ty, 2));
375 }
376
377 if (NumRegsLeft > 0) {
378 uint64_t NumRegs = numRegsForType(Ty);
379 if (NumRegsLeft >= NumRegs) {
380 NumRegsLeft -= NumRegs;
381 return ABIArgInfo::getDirect();
382 }
383 }
384
385 // Use pass-by-reference in stead of pass-by-value for struct arguments in
386 // function ABI.
388 getContext().getTypeAlignInChars(Ty),
389 getContext().getTargetAddressSpace(LangAS::opencl_private));
390}
391
392void AMDGCNSPIRVABIInfo::computeInfo(CGFunctionInfo &FI) const {
393 llvm::CallingConv::ID CC = FI.getCallingConvention();
394
395 if (!getCXXABI().classifyReturnType(FI))
397
398 NumRegsLeft = MaxNumRegsForArgsRet;
399 for (auto &I : FI.arguments()) {
400 if (CC == llvm::CallingConv::SPIR_KERNEL)
401 I.info = classifyKernelArgumentType(I.type);
402 else
403 I.info = classifyArgumentType(I.type);
404 }
405}
406
407llvm::FixedVectorType *
408SPIRVABIInfo::getOptimalVectorMemoryType(llvm::FixedVectorType *Ty,
409 const LangOptions &LangOpt) const {
410 // For Logical SPIR-V, we don't know the underlying hardware or layout.
411 // This means we don't know which vector size is better, and also cannot
412 // assume a smaller vector size is stored in a larger vector size.
413 if (getTarget().getTriple().isSPIRVLogical())
414 return Ty;
415 return DefaultABIInfo::getOptimalVectorMemoryType(Ty, LangOpt);
416}
417
418llvm::FixedVectorType *AMDGCNSPIRVABIInfo::getOptimalVectorMemoryType(
419 llvm::FixedVectorType *Ty, const LangOptions &LangOpt) const {
420 // AMDGPU has legal instructions for 96-bit so 3x32 can be supported.
421 if (Ty->getNumElements() == 3 && getDataLayout().getTypeSizeInBits(Ty) == 96)
422 return Ty;
423 return DefaultABIInfo::getOptimalVectorMemoryType(Ty, LangOpt);
424}
425
426namespace clang {
427namespace CodeGen {
429 if (CGM.getTarget().getTriple().isSPIRV()) {
430 if (CGM.getTarget().getTriple().getVendor() == llvm::Triple::AMD)
431 AMDGCNSPIRVABIInfo(CGM.getTypes()).computeInfo(FI);
432 else
433 SPIRVABIInfo(CGM.getTypes()).computeInfo(FI);
434 } else {
435 CommonSPIRABIInfo(CGM.getTypes()).computeInfo(FI);
436 }
437}
438}
439}
440
441unsigned CommonSPIRTargetCodeGenInfo::getDeviceKernelCallingConv() const {
442 return llvm::CallingConv::SPIR_KERNEL;
443}
444
445void SPIRVTargetCodeGenInfo::setCUDAKernelCallingConvention(
446 const FunctionType *&FT) const {
447 // Convert HIP kernels to SPIR-V kernels.
448 if (getABIInfo().getContext().getLangOpts().HIP) {
449 FT = getABIInfo().getContext().adjustFunctionType(
451 return;
452 }
453}
454
455void CommonSPIRTargetCodeGenInfo::setOCLKernelStubCallingConvention(
456 const FunctionType *&FT) const {
457 FT = getABIInfo().getContext().adjustFunctionType(
459}
460
461// LLVM currently assumes a null pointer has the bit pattern 0, but some GPU
462// targets use a non-zero encoding for null in certain address spaces.
463// Because SPIR(-V) is a generic target and the bit pattern of null in
464// non-generic AS is unspecified, materialize null in non-generic AS via an
465// addrspacecast from null in generic AS. This allows later lowering to
466// substitute the target's real sentinel value.
467llvm::Constant *
468CommonSPIRTargetCodeGenInfo::getNullPointer(const CodeGen::CodeGenModule &CGM,
469 llvm::PointerType *PT,
470 QualType QT) const {
472 ? LangAS::Default
474 unsigned ASAsInt = static_cast<unsigned>(AS);
475 unsigned FirstTargetASAsInt =
476 static_cast<unsigned>(LangAS::FirstTargetAddressSpace);
477 unsigned CodeSectionINTELAS = FirstTargetASAsInt + 9;
478 // As per SPV_INTEL_function_pointers, it is illegal to addrspacecast
479 // function pointers to/from the generic AS.
480 bool IsFunctionPtrAS =
481 CGM.getTriple().isSPIRV() && ASAsInt == CodeSectionINTELAS;
482 if (AS == LangAS::Default || AS == LangAS::opencl_generic ||
483 AS == LangAS::opencl_constant || IsFunctionPtrAS)
484 return llvm::ConstantPointerNull::get(PT);
485
486 auto &Ctx = CGM.getContext();
487 auto NPT = llvm::PointerType::get(
488 PT->getContext(), Ctx.getTargetAddressSpace(LangAS::opencl_generic));
489 return llvm::ConstantExpr::getAddrSpaceCast(
490 llvm::ConstantPointerNull::get(NPT), PT);
491}
492
493LangAS
494SPIRVTargetCodeGenInfo::getGlobalVarAddressSpace(CodeGenModule &CGM,
495 const VarDecl *D) const {
496 assert(!CGM.getLangOpts().OpenCL &&
497 !(CGM.getLangOpts().CUDA && CGM.getLangOpts().CUDAIsDevice) &&
498 "Address space agnostic languages only");
499 // If we're here it means that we're using the SPIRDefIsGen ASMap, hence for
500 // the global AS we can rely on either cuda_device or sycl_global to be
501 // correct; however, since this is not a CUDA Device context, we use
502 // sycl_global to prevent confusion with the assertion.
503 LangAS DefaultGlobalAS = getLangASFromTargetAS(
504 CGM.getContext().getTargetAddressSpace(LangAS::sycl_global));
505 if (!D)
506 return DefaultGlobalAS;
507
508 LangAS AddrSpace = D->getType().getAddressSpace();
509 if (AddrSpace != LangAS::Default)
510 return AddrSpace;
511
512 return DefaultGlobalAS;
513}
514
515void SPIRVTargetCodeGenInfo::setTargetAttributes(
516 const Decl *D, llvm::GlobalValue *GV, CodeGen::CodeGenModule &M) const {
517 if (GV->isDeclaration())
518 return;
519
520 const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D);
521 if (!FD)
522 return;
523
524 llvm::Function *F = dyn_cast<llvm::Function>(GV);
525 assert(F && "Expected GlobalValue to be a Function");
526
527 if (!M.getLangOpts().HIP ||
528 M.getTarget().getTriple().getVendor() != llvm::Triple::AMD)
529 return;
530
531 if (!FD->hasAttr<CUDAGlobalAttr>())
532 return;
533
534 unsigned N = M.getLangOpts().GPUMaxThreadsPerBlock;
535 if (auto FlatWGS = FD->getAttr<AMDGPUFlatWorkGroupSizeAttr>())
536 N = FlatWGS->getMax()->EvaluateKnownConstInt(M.getContext()).getExtValue();
537
538 // We encode the maximum flat WG size in the first component of the 3D
539 // max_work_group_size attribute, which will get reverse translated into the
540 // original AMDGPU attribute when targeting AMDGPU.
541 auto Int32Ty = llvm::IntegerType::getInt32Ty(M.getLLVMContext());
542 llvm::Metadata *AttrMDArgs[] = {
543 llvm::ConstantAsMetadata::get(llvm::ConstantInt::get(Int32Ty, N)),
544 llvm::ConstantAsMetadata::get(llvm::ConstantInt::get(Int32Ty, 1)),
545 llvm::ConstantAsMetadata::get(llvm::ConstantInt::get(Int32Ty, 1))};
546
547 F->setMetadata("max_work_group_size",
548 llvm::MDNode::get(M.getLLVMContext(), AttrMDArgs));
549}
550
551StringRef SPIRVTargetCodeGenInfo::getLLVMSyncScopeStr(
552 const LangOptions &, SyncScope Scope, llvm::AtomicOrdering) const {
553 switch (Scope) {
554 case SyncScope::HIPSingleThread:
555 case SyncScope::SingleScope:
556 return "singlethread";
557 case SyncScope::HIPWavefront:
558 case SyncScope::OpenCLSubGroup:
559 case SyncScope::WavefrontScope:
560 return "subgroup";
561 case SyncScope::HIPCluster:
562 case SyncScope::ClusterScope:
563 case SyncScope::HIPWorkgroup:
564 case SyncScope::OpenCLWorkGroup:
565 case SyncScope::WorkgroupScope:
566 return "workgroup";
567 case SyncScope::HIPAgent:
568 case SyncScope::OpenCLDevice:
569 case SyncScope::DeviceScope:
570 return "device";
571 case SyncScope::SystemScope:
572 case SyncScope::HIPSystem:
573 case SyncScope::OpenCLAllSVMDevices:
574 return "";
575 }
576 return "";
577}
578
579/// Construct a SPIR-V target extension type for the given OpenCL image type.
580static llvm::Type *getSPIRVImageType(llvm::LLVMContext &Ctx, StringRef BaseType,
581 StringRef OpenCLName,
582 unsigned AccessQualifier) {
583 // These parameters compare to the operands of OpTypeImage (see
584 // https://registry.khronos.org/SPIR-V/specs/unified1/SPIRV.html#OpTypeImage
585 // for more details). The first 6 integer parameters all default to 0, and
586 // will be changed to 1 only for the image type(s) that set the parameter to
587 // one. The 7th integer parameter is the access qualifier, which is tacked on
588 // at the end.
589 SmallVector<unsigned, 7> IntParams = {0, 0, 0, 0, 0, 0};
590
591 // Choose the dimension of the image--this corresponds to the Dim enum in
592 // SPIR-V (first integer parameter of OpTypeImage).
593 if (OpenCLName.starts_with("image2d"))
594 IntParams[0] = 1;
595 else if (OpenCLName.starts_with("image3d"))
596 IntParams[0] = 2;
597 else if (OpenCLName == "image1d_buffer")
598 IntParams[0] = 5; // Buffer
599 else
600 assert(OpenCLName.starts_with("image1d") && "Unknown image type");
601
602 // Set the other integer parameters of OpTypeImage if necessary. Note that the
603 // OpenCL image types don't provide any information for the Sampled or
604 // Image Format parameters.
605 if (OpenCLName.contains("_depth"))
606 IntParams[1] = 1;
607 if (OpenCLName.contains("_array"))
608 IntParams[2] = 1;
609 if (OpenCLName.contains("_msaa"))
610 IntParams[3] = 1;
611
612 // Access qualifier
613 IntParams.push_back(AccessQualifier);
614
615 return llvm::TargetExtType::get(Ctx, BaseType, {llvm::Type::getVoidTy(Ctx)},
616 IntParams);
617}
618
619llvm::Type *CommonSPIRTargetCodeGenInfo::getOpenCLType(CodeGenModule &CGM,
620 const Type *Ty) const {
621 llvm::LLVMContext &Ctx = CGM.getLLVMContext();
622 if (auto *PipeTy = dyn_cast<PipeType>(Ty))
623 return llvm::TargetExtType::get(Ctx, "spirv.Pipe", {},
624 {!PipeTy->isReadOnly()});
625 if (auto *BuiltinTy = dyn_cast<BuiltinType>(Ty)) {
626 enum AccessQualifier : unsigned { AQ_ro = 0, AQ_wo = 1, AQ_rw = 2 };
627 switch (BuiltinTy->getKind()) {
628#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
629 case BuiltinType::Id: \
630 return getSPIRVImageType(Ctx, "spirv.Image", #ImgType, AQ_##Suffix);
631#include "clang/Basic/OpenCLImageTypes.def"
632 case BuiltinType::OCLSampler:
633 return llvm::TargetExtType::get(Ctx, "spirv.Sampler");
634 case BuiltinType::OCLEvent:
635 return llvm::TargetExtType::get(Ctx, "spirv.Event");
636 case BuiltinType::OCLClkEvent:
637 return llvm::TargetExtType::get(Ctx, "spirv.DeviceEvent");
638 case BuiltinType::OCLQueue:
639 return llvm::TargetExtType::get(Ctx, "spirv.Queue");
640 case BuiltinType::OCLReserveID:
641 return llvm::TargetExtType::get(Ctx, "spirv.ReserveId");
642#define INTEL_SUBGROUP_AVC_TYPE(Name, Id) \
643 case BuiltinType::OCLIntelSubgroupAVC##Id: \
644 return llvm::TargetExtType::get(Ctx, "spirv.Avc" #Id "INTEL");
645#include "clang/Basic/OpenCLExtensionTypes.def"
646 default:
647 return nullptr;
648 }
649 }
650
651 return nullptr;
652}
653
654// Gets a spirv.IntegralConstant or spirv.Literal. If IntegralType is present,
655// returns an IntegralConstant, otherwise returns a Literal.
656static llvm::Type *getInlineSpirvConstant(CodeGenModule &CGM,
657 llvm::Type *IntegralType,
658 llvm::APInt Value) {
659 llvm::LLVMContext &Ctx = CGM.getLLVMContext();
660
661 // Convert the APInt value to an array of uint32_t words
663
664 while (Value.ugt(0)) {
665 uint32_t Word = Value.trunc(32).getZExtValue();
666 Value.lshrInPlace(32);
667
668 Words.push_back(Word);
669 }
670 if (Words.size() == 0)
671 Words.push_back(0);
672
673 if (IntegralType)
674 return llvm::TargetExtType::get(Ctx, "spirv.IntegralConstant",
675 {IntegralType}, Words);
676 return llvm::TargetExtType::get(Ctx, "spirv.Literal", {}, Words);
677}
678
679static llvm::Type *getInlineSpirvType(CodeGenModule &CGM,
680 const HLSLInlineSpirvType *SpirvType) {
681 llvm::LLVMContext &Ctx = CGM.getLLVMContext();
682
684
685 for (auto &Operand : SpirvType->getOperands()) {
686 using SpirvOperandKind = SpirvOperand::SpirvOperandKind;
687
688 llvm::Type *Result = nullptr;
689 switch (Operand.getKind()) {
690 case SpirvOperandKind::ConstantId: {
691 llvm::Type *IntegralType =
692 CGM.getTypes().ConvertType(Operand.getResultType());
693
694 Result = getInlineSpirvConstant(CGM, IntegralType, Operand.getValue());
695 break;
696 }
697 case SpirvOperandKind::Literal: {
698 Result = getInlineSpirvConstant(CGM, nullptr, Operand.getValue());
699 break;
700 }
701 case SpirvOperandKind::TypeId: {
702 QualType TypeOperand = Operand.getResultType();
703 if (const auto *RD = TypeOperand->getAsRecordDecl()) {
704 assert(RD->isCompleteDefinition() &&
705 "Type completion should have been required in Sema");
706
707 const FieldDecl *HandleField = RD->findFirstNamedDataMember();
708 if (HandleField) {
709 QualType ResourceType = HandleField->getType();
710 if (ResourceType->getAs<HLSLAttributedResourceType>()) {
711 TypeOperand = ResourceType;
712 }
713 }
714 }
715 Result = CGM.getTypes().ConvertType(TypeOperand);
716 break;
717 }
718 default:
719 llvm_unreachable("HLSLInlineSpirvType had invalid operand!");
720 break;
721 }
722
723 assert(Result);
724 Operands.push_back(Result);
725 }
726
727 return llvm::TargetExtType::get(Ctx, "spirv.Type", Operands,
728 {SpirvType->getOpcode(), SpirvType->getSize(),
729 SpirvType->getAlignment()});
730}
731
732llvm::Type *CommonSPIRTargetCodeGenInfo::getHLSLType(
733 CodeGenModule &CGM, const Type *Ty,
734 const CGHLSLOffsetInfo &OffsetInfo) const {
735 llvm::LLVMContext &Ctx = CGM.getLLVMContext();
736
737 if (auto *SpirvType = dyn_cast<HLSLInlineSpirvType>(Ty))
738 return getInlineSpirvType(CGM, SpirvType);
739
740 auto *ResType = dyn_cast<HLSLAttributedResourceType>(Ty);
741 if (!ResType)
742 return nullptr;
743
744 const HLSLAttributedResourceType::Attributes &ResAttrs = ResType->getAttrs();
745 switch (ResAttrs.ResourceClass) {
746 case llvm::dxil::ResourceClass::UAV:
747 case llvm::dxil::ResourceClass::SRV: {
748 // TypedBuffer and RawBuffer both need element type
749 QualType ContainedTy = ResType->getContainedType();
750 if (ContainedTy.isNull())
751 return nullptr;
752
753 assert(!ResAttrs.IsROV &&
754 "Rasterizer order views not implemented for SPIR-V yet");
755
756 if (!ResAttrs.RawBuffer) {
757 // convert element type
758 return getSPIRVImageTypeFromHLSLResource(ResAttrs, ContainedTy, CGM);
759 }
760
761 if (ResAttrs.IsCounter) {
762 llvm::Type *ElemType = llvm::Type::getInt32Ty(Ctx);
763 uint32_t StorageClass = /* StorageBuffer storage class */ 12;
764 return llvm::TargetExtType::get(Ctx, "spirv.VulkanBuffer", {ElemType},
765 {StorageClass, true});
766 }
767 llvm::Type *ElemType = CGM.getTypes().ConvertTypeForMem(ContainedTy);
768 llvm::ArrayType *RuntimeArrayType = llvm::ArrayType::get(ElemType, 0);
769 uint32_t StorageClass = /* StorageBuffer storage class */ 12;
770 bool IsWritable = ResAttrs.ResourceClass == llvm::dxil::ResourceClass::UAV;
771 return llvm::TargetExtType::get(Ctx, "spirv.VulkanBuffer",
772 {RuntimeArrayType},
773 {StorageClass, IsWritable});
774 }
775 case llvm::dxil::ResourceClass::CBuffer: {
776 QualType ContainedTy = ResType->getContainedType();
777 if (ContainedTy.isNull() || !ContainedTy->isStructureType())
778 return nullptr;
779
780 llvm::StructType *BufferLayoutTy =
781 HLSLBufferLayoutBuilder(CGM).layOutStruct(
782 ContainedTy->getAsCanonical<RecordType>(), OffsetInfo);
783 uint32_t StorageClass = /* Uniform storage class */ 2;
784 return llvm::TargetExtType::get(Ctx, "spirv.VulkanBuffer", {BufferLayoutTy},
785 {StorageClass, false});
786 break;
787 }
788 case llvm::dxil::ResourceClass::Sampler:
789 return llvm::TargetExtType::get(Ctx, "spirv.Sampler");
790 }
791 return nullptr;
792}
793
794static unsigned
796 const HLSLAttributedResourceType::Attributes &attributes,
797 llvm::Type *SampledType, QualType Ty, unsigned NumChannels) {
798 // For images with `Sampled` operand equal to 2, there are restrictions on
799 // using the Unknown image format. To avoid these restrictions in common
800 // cases, we guess an image format for them based on the sampled type and the
801 // number of channels. This is intended to match the behaviour of DXC.
802 if (LangOpts.HLSLSpvUseUnknownImageFormat ||
803 attributes.ResourceClass != llvm::dxil::ResourceClass::UAV) {
804 return 0; // Unknown
805 }
806
807 if (SampledType->isIntegerTy(32)) {
808 if (Ty->isSignedIntegerType()) {
809 if (NumChannels == 1)
810 return 24; // R32i
811 if (NumChannels == 2)
812 return 25; // Rg32i
813 if (NumChannels == 4)
814 return 21; // Rgba32i
815 } else {
816 if (NumChannels == 1)
817 return 33; // R32ui
818 if (NumChannels == 2)
819 return 35; // Rg32ui
820 if (NumChannels == 4)
821 return 30; // Rgba32ui
822 }
823 } else if (SampledType->isIntegerTy(64)) {
824 if (NumChannels == 1) {
825 if (Ty->isSignedIntegerType()) {
826 return 41; // R64i
827 }
828 return 40; // R64ui
829 }
830 } else if (SampledType->isFloatTy()) {
831 if (NumChannels == 1)
832 return 3; // R32f
833 if (NumChannels == 2)
834 return 6; // Rg32f
835 if (NumChannels == 4)
836 return 1; // Rgba32f
837 }
838
839 return 0; // Unknown
840}
841
842llvm::Type *CommonSPIRTargetCodeGenInfo::getSPIRVImageTypeFromHLSLResource(
843 const HLSLAttributedResourceType::Attributes &attributes, QualType Ty,
844 CodeGenModule &CGM) const {
845 llvm::LLVMContext &Ctx = CGM.getLLVMContext();
846
847 unsigned NumChannels = 1;
849 if (const VectorType *V = dyn_cast<VectorType>(Ty)) {
850 NumChannels = V->getNumElements();
851 Ty = V->getElementType();
852 }
853 assert(!Ty->isVectorType() && "We still have a vector type.");
854
855 llvm::Type *SampledType = CGM.getTypes().ConvertTypeForMem(Ty);
856
857 assert((SampledType->isIntegerTy() || SampledType->isFloatingPointTy()) &&
858 "The element type for a SPIR-V resource must be a scalar integer or "
859 "floating point type.");
860
861 // These parameters correspond to the operands to the OpTypeImage SPIR-V
862 // instruction. See
863 // https://registry.khronos.org/SPIR-V/specs/unified1/SPIRV.html#OpTypeImage.
864 SmallVector<unsigned, 6> IntParams(6, 0);
865
866 const char *Name =
867 Ty->isSignedIntegerType() ? "spirv.SignedImage" : "spirv.Image";
868
869 // Dim
870 switch (attributes.ResourceDimension) {
871 case llvm::dxil::ResourceDimension::Dim1D:
872 IntParams[0] = 0;
873 break;
874 case llvm::dxil::ResourceDimension::Dim2D:
875 IntParams[0] = 1;
876 break;
877 case llvm::dxil::ResourceDimension::Dim3D:
878 IntParams[0] = 2;
879 break;
880 case llvm::dxil::ResourceDimension::Cube:
881 IntParams[0] = 3;
882 break;
883 case llvm::dxil::ResourceDimension::Unknown:
884 IntParams[0] = 5;
885 break;
886 }
887
888 // Depth
889 // HLSL does not indicate if it is a depth texture or not, so we use unknown.
890 IntParams[1] = 2;
891
892 // Arrayed
893 IntParams[2] = 0;
894
895 // MS
896 IntParams[3] = 0;
897
898 // Sampled
899 IntParams[4] =
900 attributes.ResourceClass == llvm::dxil::ResourceClass::UAV ? 2 : 1;
901
902 // Image format.
903 IntParams[5] = getImageFormat(CGM.getLangOpts(), attributes, SampledType, Ty,
904 NumChannels);
905
906 llvm::TargetExtType *ImageType =
907 llvm::TargetExtType::get(Ctx, Name, {SampledType}, IntParams);
908 return ImageType;
909}
910
911std::unique_ptr<TargetCodeGenInfo>
913 return std::make_unique<CommonSPIRTargetCodeGenInfo>(CGM.getTypes());
914}
915
916std::unique_ptr<TargetCodeGenInfo>
918 return std::make_unique<SPIRVTargetCodeGenInfo>(CGM.getTypes());
919}
#define V(N, I)
static void setCUDAKernelCallingConvention(CanQualType &FTy, CodeGenModule &CGM, const FunctionDecl *FD)
Set calling convention for CUDA/HIP kernel.
Definition CGCall.cpp:362
static llvm::Type * getInlineSpirvType(CodeGenModule &CGM, const HLSLInlineSpirvType *SpirvType)
Definition SPIR.cpp:679
static llvm::Type * getSPIRVImageType(llvm::LLVMContext &Ctx, StringRef BaseType, StringRef OpenCLName, unsigned AccessQualifier)
Construct a SPIR-V target extension type for the given OpenCL image type.
Definition SPIR.cpp:580
static unsigned getImageFormat(const LangOptions &LangOpts, const HLSLAttributedResourceType::Attributes &attributes, llvm::Type *SampledType, QualType Ty, unsigned NumChannels)
Definition SPIR.cpp:795
static llvm::Type * getInlineSpirvConstant(CodeGenModule &CGM, llvm::Type *IntegralType, llvm::APInt Value)
Definition SPIR.cpp:656
Defines the clang::LangOptions interface.
static StringRef getTriple(const Command &Job)
unsigned getTargetAddressSpace(LangAS AS) const
QuantityType getQuantity() const
getQuantity - Get the raw integer representation of this quantity.
Definition CharUnits.h:185
static CharUnits fromQuantity(QuantityType Quantity)
fromQuantity - Construct a CharUnits quantity from a raw integer type.
Definition CharUnits.h:63
static ABIArgInfo getIgnore()
static ABIArgInfo getDirect(llvm::Type *T=nullptr, unsigned Offset=0, llvm::Type *Padding=nullptr, bool CanBeFlattened=true, unsigned Align=0)
static ABIArgInfo getIndirectAliased(CharUnits Alignment, unsigned AddrSpace, bool Realign=false, llvm::Type *Padding=nullptr)
Pass this in memory using the IR byref attribute.
@ RAA_DirectInMemory
Pass it on the stack using its defined layout.
Definition CGCXXABI.h:158
CGFunctionInfo - Class to encapsulate the information about a function definition.
unsigned getCallingConvention() const
getCallingConvention - Return the user specified calling convention, which has been translated into a...
CanQualType getReturnType() const
MutableArrayRef< ArgInfo > arguments()
This class organizes the cross-function state that is used while generating LLVM code.
const LangOptions & getLangOpts() const
const TargetInfo & getTarget() const
const llvm::Triple & getTriple() const
ASTContext & getContext() const
llvm::LLVMContext & getLLVMContext()
llvm::Type * ConvertType(QualType T)
ConvertType - Convert type T into a llvm::Type.
llvm::Type * ConvertTypeForMem(QualType T)
ConvertTypeForMem - Convert type T into a llvm::Type.
DefaultABIInfo - The default implementation for ABI specific details.
Definition ABIInfoImpl.h:21
ABIArgInfo classifyArgumentType(QualType RetTy) const
ABIArgInfo classifyReturnType(QualType RetTy) const
TargetCodeGenInfo - This class organizes various target-specific codegeneration issues,...
Definition TargetInfo.h:49
T * getAttr() const
Definition DeclBase.h:581
bool hasAttr() const
Definition DeclBase.h:585
Represents a member of a struct/union/class.
Definition Decl.h:3175
ExtInfo withCallingConv(CallingConv cc) const
Definition TypeBase.h:4776
ExtInfo getExtInfo() const
Definition TypeBase.h:4909
Keeps track of the various options that can be enabled, which controls the dialect of C or C++ that i...
A (possibly-)qualified type.
Definition TypeBase.h:937
bool isNull() const
Return true if this QualType doesn't point to a type yet.
Definition TypeBase.h:1004
LangAS getAddressSpace() const
Return the address space of this type.
Definition TypeBase.h:8557
bool hasFlexibleArrayMember() const
Definition Decl.h:4375
const llvm::Triple & getTriple() const
Returns the target triple of the primary target.
bool isStructureType() const
Definition Type.cpp:680
bool isSignedIntegerType() const
Return true if this is an integer type that is signed, according to C99 6.2.5p4 [char,...
Definition Type.cpp:2231
RecordDecl * getAsRecordDecl() const
Retrieves the RecordDecl this type refers to.
Definition Type.h:41
CanQualType getCanonicalTypeUnqualified() const
QualType getPointeeType() const
If this is a pointer, ObjC object pointer, or block pointer, this returns the respective pointee.
Definition Type.cpp:754
bool isVectorType() const
Definition TypeBase.h:8807
const T * getAsCanonical() const
If this type is canonically the specified type, return its canonical type cast to that specified type...
Definition TypeBase.h:2971
const T * getAs() const
Member-template getAs<specific type>'.
Definition TypeBase.h:9261
const Type * getUnqualifiedDesugaredType() const
Return the specified type with any "sugar" removed from the type, removing any typedefs,...
Definition Type.cpp:655
bool isNullPtrType() const
Definition TypeBase.h:9071
QualType getType() const
Definition Decl.h:723
ABIArgInfo classifyArgumentType(CodeGenModule &CGM, CanQualType type)
Classify the rules for how to pass a particular type.
@ Decl
The l-value was an access to a declared entity or something equivalently strong, like the address of ...
Definition CGValue.h:146
CGCXXABI::RecordArgABI getRecordArgABI(const RecordType *RT, CGCXXABI &CXXABI)
bool classifyReturnType(const CGCXXABI &CXXABI, CGFunctionInfo &FI, const ABIInfo &Info)
void computeSPIRKernelABIInfo(CodeGenModule &CGM, CGFunctionInfo &FI)
Definition SPIR.cpp:428
RValue emitVoidPtrVAArg(CodeGenFunction &CGF, Address VAListAddr, QualType ValueTy, bool IsIndirect, TypeInfoChars ValueInfo, CharUnits SlotSizeAndAlign, bool AllowHigherAlign, AggValueSlot Slot, bool ForceRightAdjust=false)
Emit va_arg for a platform using the common void* representation, where arguments are simply emitted ...
bool isAggregateTypeForABI(QualType T)
const Type * isSingleElementStruct(QualType T, ASTContext &Context)
isSingleElementStruct - Determine if a structure is a "singleelement struct", i.e.
std::unique_ptr< TargetCodeGenInfo > createSPIRVTargetCodeGenInfo(CodeGenModule &CGM)
Definition SPIR.cpp:917
QualType useFirstFieldIfTransparentUnion(QualType Ty)
Pass transparent unions as if they were the type of the first element.
std::unique_ptr< TargetCodeGenInfo > createCommonSPIRTargetCodeGenInfo(CodeGenModule &CGM)
Definition SPIR.cpp:912
bool isEmptyRecord(ASTContext &Context, QualType T, bool AllowArrays, bool AsIfNoUniqueAddr=false)
isEmptyRecord - Return true iff a structure contains only empty fields.
The JSON file list parser is used to communicate input to InstallAPI.
StorageClass
Storage classes.
Definition Specifiers.h:249
@ Type
The name was classified as a type.
Definition Sema.h:564
LangAS
Defines the address space values used by the address space qualifier of QualType.
for(const auto &A :T->param_types())
SyncScope
Defines sync scope values used internally by clang.
Definition SyncScope.h:42
@ CC_DeviceKernel
Definition Specifiers.h:293
@ CC_SpirFunction
Definition Specifiers.h:292
LangAS getLangASFromTargetAS(unsigned TargetAS)
unsigned long uint64_t
unsigned int uint32_t