clang 22.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"
12
13using namespace clang;
14using namespace clang::CodeGen;
15
16//===----------------------------------------------------------------------===//
17// Base ABI and target codegen info implementation common between SPIR and
18// SPIR-V.
19//===----------------------------------------------------------------------===//
20
21namespace {
22class CommonSPIRABIInfo : public DefaultABIInfo {
23public:
24 CommonSPIRABIInfo(CodeGenTypes &CGT) : DefaultABIInfo(CGT) { setCCs(); }
25
26private:
27 void setCCs();
28};
29
30class SPIRVABIInfo : public CommonSPIRABIInfo {
31public:
32 SPIRVABIInfo(CodeGenTypes &CGT) : CommonSPIRABIInfo(CGT) {}
33 void computeInfo(CGFunctionInfo &FI) const override;
34
35private:
36 ABIArgInfo classifyReturnType(QualType RetTy) const;
37 ABIArgInfo classifyKernelArgumentType(QualType Ty) const;
38 ABIArgInfo classifyArgumentType(QualType Ty) const;
39};
40} // end anonymous namespace
41namespace {
42class CommonSPIRTargetCodeGenInfo : public TargetCodeGenInfo {
43public:
44 CommonSPIRTargetCodeGenInfo(CodeGen::CodeGenTypes &CGT)
45 : TargetCodeGenInfo(std::make_unique<CommonSPIRABIInfo>(CGT)) {}
46 CommonSPIRTargetCodeGenInfo(std::unique_ptr<ABIInfo> ABIInfo)
47 : TargetCodeGenInfo(std::move(ABIInfo)) {}
48
49 LangAS getASTAllocaAddressSpace() const override {
51 getABIInfo().getDataLayout().getAllocaAddrSpace());
52 }
53
54 unsigned getDeviceKernelCallingConv() const override;
55 llvm::Type *getOpenCLType(CodeGenModule &CGM, const Type *T) const override;
56 llvm::Type *
57 getHLSLType(CodeGenModule &CGM, const Type *Ty,
58 const SmallVector<int32_t> *Packoffsets = nullptr) const override;
59 llvm::Type *getSPIRVImageTypeFromHLSLResource(
60 const HLSLAttributedResourceType::Attributes &attributes,
61 QualType SampledType, CodeGenModule &CGM) const;
62 void
63 setOCLKernelStubCallingConvention(const FunctionType *&FT) const override;
64 llvm::Constant *getNullPointer(const CodeGen::CodeGenModule &CGM,
65 llvm::PointerType *T,
66 QualType QT) const override;
67 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
68 CodeGen::CodeGenModule &M) const override;
69};
70class SPIRVTargetCodeGenInfo : public CommonSPIRTargetCodeGenInfo {
71public:
72 SPIRVTargetCodeGenInfo(CodeGen::CodeGenTypes &CGT)
73 : CommonSPIRTargetCodeGenInfo(std::make_unique<SPIRVABIInfo>(CGT)) {}
74 void setCUDAKernelCallingConvention(const FunctionType *&FT) const override;
75 LangAS getGlobalVarAddressSpace(CodeGenModule &CGM,
76 const VarDecl *D) const override;
77 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
78 CodeGen::CodeGenModule &M) const override;
79 llvm::SyncScope::ID getLLVMSyncScopeID(const LangOptions &LangOpts,
80 SyncScope Scope,
81 llvm::AtomicOrdering Ordering,
82 llvm::LLVMContext &Ctx) const override;
83 bool supportsLibCall() const override {
84 return getABIInfo().getTarget().getTriple().getVendor() !=
85 llvm::Triple::AMD;
86 }
87};
88
89inline StringRef mapClangSyncScopeToLLVM(SyncScope Scope) {
90 switch (Scope) {
93 return "singlethread";
97 return "subgroup";
103 return "workgroup";
107 return "device";
111 return "";
112 }
113 return "";
114}
115} // End anonymous namespace.
116
117void CommonSPIRABIInfo::setCCs() {
118 assert(getRuntimeCC() == llvm::CallingConv::C);
119 RuntimeCC = llvm::CallingConv::SPIR_FUNC;
120}
121
122ABIArgInfo SPIRVABIInfo::classifyReturnType(QualType RetTy) const {
123 if (getTarget().getTriple().getVendor() != llvm::Triple::AMD)
125 if (!isAggregateTypeForABI(RetTy) || getRecordArgABI(RetTy, getCXXABI()))
127
128 if (const auto *RD = RetTy->getAsRecordDecl();
129 RD && RD->hasFlexibleArrayMember())
131
132 // TODO: The AMDGPU ABI is non-trivial to represent in SPIR-V; in order to
133 // avoid encoding various architecture specific bits here we return everything
134 // as direct to retain type info for things like aggregates, for later perusal
135 // when translating back to LLVM/lowering in the BE. This is also why we
136 // disable flattening as the outcomes can mismatch between SPIR-V and AMDGPU.
137 // This will be revisited / optimised in the future.
138 return ABIArgInfo::getDirect(CGT.ConvertType(RetTy), 0u, nullptr, false);
139}
140
141ABIArgInfo SPIRVABIInfo::classifyKernelArgumentType(QualType Ty) const {
142 if (getContext().getLangOpts().isTargetDevice()) {
143 // Coerce pointer arguments with default address space to CrossWorkGroup
144 // pointers for target devices as default address space kernel arguments
145 // are not allowed. We use the opencl_global language address space which
146 // always maps to CrossWorkGroup.
147 llvm::Type *LTy = CGT.ConvertType(Ty);
148 auto DefaultAS = getContext().getTargetAddressSpace(LangAS::Default);
149 auto GlobalAS = getContext().getTargetAddressSpace(LangAS::opencl_global);
150 auto *PtrTy = llvm::dyn_cast<llvm::PointerType>(LTy);
151 if (PtrTy && PtrTy->getAddressSpace() == DefaultAS) {
152 LTy = llvm::PointerType::get(PtrTy->getContext(), GlobalAS);
153 return ABIArgInfo::getDirect(LTy, 0, nullptr, false);
154 }
155
156 if (isAggregateTypeForABI(Ty)) {
157 if (getTarget().getTriple().getVendor() == llvm::Triple::AMD)
158 // TODO: The AMDGPU kernel ABI passes aggregates byref, which is not
159 // currently expressible in SPIR-V; SPIR-V passes aggregates byval,
160 // which the AMDGPU kernel ABI does not allow. Passing aggregates as
161 // direct works around this impedance mismatch, as it retains type info
162 // and can be correctly handled, post reverse-translation, by the AMDGPU
163 // BE, which has to support this CC for legacy OpenCL purposes. It can
164 // be brittle and does lead to performance degradation in certain
165 // pathological cases. This will be revisited / optimised in the future,
166 // once a way to deal with the byref/byval impedance mismatch is
167 // identified.
168 return ABIArgInfo::getDirect(LTy, 0, nullptr, false);
169 // Force copying aggregate type in kernel arguments by value when
170 // compiling CUDA targeting SPIR-V. This is required for the object
171 // copied to be valid on the device.
172 // This behavior follows the CUDA spec
173 // https://docs.nvidia.com/cuda/cuda-c-programming-guide/index.html#global-function-argument-processing,
174 // and matches the NVPTX implementation. TODO: hardcoding to 0 should be
175 // revisited if HIPSPV / byval starts making use of the AS of an indirect
176 // arg.
177 return getNaturalAlignIndirect(Ty, /*AddrSpace=*/0, /*byval=*/true);
178 }
179 }
180 return classifyArgumentType(Ty);
181}
182
183ABIArgInfo SPIRVABIInfo::classifyArgumentType(QualType Ty) const {
184 if (getTarget().getTriple().getVendor() != llvm::Triple::AMD)
186 if (!isAggregateTypeForABI(Ty))
188
189 // Records with non-trivial destructors/copy-constructors should not be
190 // passed by value.
191 if (auto RAA = getRecordArgABI(Ty, getCXXABI()))
192 return getNaturalAlignIndirect(Ty, getDataLayout().getAllocaAddrSpace(),
194
195 if (const auto *RD = Ty->getAsRecordDecl();
196 RD && RD->hasFlexibleArrayMember())
198
199 return ABIArgInfo::getDirect(CGT.ConvertType(Ty), 0u, nullptr, false);
200}
201
202void SPIRVABIInfo::computeInfo(CGFunctionInfo &FI) const {
203 // The logic is same as in DefaultABIInfo with an exception on the kernel
204 // arguments handling.
205 llvm::CallingConv::ID CC = FI.getCallingConvention();
206
207 if (!getCXXABI().classifyReturnType(FI))
209
210 for (auto &I : FI.arguments()) {
211 if (CC == llvm::CallingConv::SPIR_KERNEL) {
212 I.info = classifyKernelArgumentType(I.type);
213 } else {
214 I.info = classifyArgumentType(I.type);
215 }
216 }
217}
218
219namespace clang {
220namespace CodeGen {
222 if (CGM.getTarget().getTriple().isSPIRV())
223 SPIRVABIInfo(CGM.getTypes()).computeInfo(FI);
224 else
225 CommonSPIRABIInfo(CGM.getTypes()).computeInfo(FI);
226}
227}
228}
229
230unsigned CommonSPIRTargetCodeGenInfo::getDeviceKernelCallingConv() const {
231 return llvm::CallingConv::SPIR_KERNEL;
232}
233
234void SPIRVTargetCodeGenInfo::setCUDAKernelCallingConvention(
235 const FunctionType *&FT) const {
236 // Convert HIP kernels to SPIR-V kernels.
237 if (getABIInfo().getContext().getLangOpts().HIP) {
238 FT = getABIInfo().getContext().adjustFunctionType(
240 return;
241 }
242}
243
244void CommonSPIRTargetCodeGenInfo::setOCLKernelStubCallingConvention(
245 const FunctionType *&FT) const {
246 FT = getABIInfo().getContext().adjustFunctionType(
248}
249
250// LLVM currently assumes a null pointer has the bit pattern 0, but some GPU
251// targets use a non-zero encoding for null in certain address spaces.
252// Because SPIR(-V) is a generic target and the bit pattern of null in
253// non-generic AS is unspecified, materialize null in non-generic AS via an
254// addrspacecast from null in generic AS. This allows later lowering to
255// substitute the target's real sentinel value.
256llvm::Constant *
257CommonSPIRTargetCodeGenInfo::getNullPointer(const CodeGen::CodeGenModule &CGM,
258 llvm::PointerType *PT,
259 QualType QT) const {
261 ? LangAS::Default
263 if (AS == LangAS::Default || AS == LangAS::opencl_generic ||
264 AS == LangAS::opencl_constant)
265 return llvm::ConstantPointerNull::get(PT);
266
267 auto &Ctx = CGM.getContext();
268 auto NPT = llvm::PointerType::get(
269 PT->getContext(), Ctx.getTargetAddressSpace(LangAS::opencl_generic));
270 return llvm::ConstantExpr::getAddrSpaceCast(
271 llvm::ConstantPointerNull::get(NPT), PT);
272}
273
274void CommonSPIRTargetCodeGenInfo::setTargetAttributes(
275 const Decl *D, llvm::GlobalValue *GV, CodeGen::CodeGenModule &M) const {
276 if (M.getLangOpts().OpenCL || GV->isDeclaration())
277 return;
278
279 const FunctionDecl *FD = dyn_cast<FunctionDecl>(D);
280 if (!FD)
281 return;
282
283 llvm::Function *F = dyn_cast<llvm::Function>(GV);
284 assert(F && "Expected GlobalValue to be a Function");
285
286 if (FD->hasAttr<DeviceKernelAttr>())
287 F->setCallingConv(getDeviceKernelCallingConv());
288}
289
290LangAS
291SPIRVTargetCodeGenInfo::getGlobalVarAddressSpace(CodeGenModule &CGM,
292 const VarDecl *D) const {
293 assert(!CGM.getLangOpts().OpenCL &&
294 !(CGM.getLangOpts().CUDA && CGM.getLangOpts().CUDAIsDevice) &&
295 "Address space agnostic languages only");
296 // If we're here it means that we're using the SPIRDefIsGen ASMap, hence for
297 // the global AS we can rely on either cuda_device or sycl_global to be
298 // correct; however, since this is not a CUDA Device context, we use
299 // sycl_global to prevent confusion with the assertion.
300 LangAS DefaultGlobalAS = getLangASFromTargetAS(
301 CGM.getContext().getTargetAddressSpace(LangAS::sycl_global));
302 if (!D)
303 return DefaultGlobalAS;
304
305 LangAS AddrSpace = D->getType().getAddressSpace();
306 if (AddrSpace != LangAS::Default)
307 return AddrSpace;
308
309 return DefaultGlobalAS;
310}
311
312void SPIRVTargetCodeGenInfo::setTargetAttributes(
313 const Decl *D, llvm::GlobalValue *GV, CodeGen::CodeGenModule &M) const {
314 if (GV->isDeclaration())
315 return;
316
317 const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D);
318 if (!FD)
319 return;
320
321 llvm::Function *F = dyn_cast<llvm::Function>(GV);
322 assert(F && "Expected GlobalValue to be a Function");
323
324 if (FD->hasAttr<DeviceKernelAttr>())
325 F->setCallingConv(getDeviceKernelCallingConv());
326
327 if (!M.getLangOpts().HIP ||
328 M.getTarget().getTriple().getVendor() != llvm::Triple::AMD)
329 return;
330
331 if (!FD->hasAttr<CUDAGlobalAttr>())
332 return;
333
334 unsigned N = M.getLangOpts().GPUMaxThreadsPerBlock;
335 if (auto FlatWGS = FD->getAttr<AMDGPUFlatWorkGroupSizeAttr>())
336 N = FlatWGS->getMax()->EvaluateKnownConstInt(M.getContext()).getExtValue();
337
338 // We encode the maximum flat WG size in the first component of the 3D
339 // max_work_group_size attribute, which will get reverse translated into the
340 // original AMDGPU attribute when targeting AMDGPU.
341 auto Int32Ty = llvm::IntegerType::getInt32Ty(M.getLLVMContext());
342 llvm::Metadata *AttrMDArgs[] = {
343 llvm::ConstantAsMetadata::get(llvm::ConstantInt::get(Int32Ty, N)),
344 llvm::ConstantAsMetadata::get(llvm::ConstantInt::get(Int32Ty, 1)),
345 llvm::ConstantAsMetadata::get(llvm::ConstantInt::get(Int32Ty, 1))};
346
347 F->setMetadata("max_work_group_size",
348 llvm::MDNode::get(M.getLLVMContext(), AttrMDArgs));
349}
350
351llvm::SyncScope::ID
352SPIRVTargetCodeGenInfo::getLLVMSyncScopeID(const LangOptions &, SyncScope Scope,
353 llvm::AtomicOrdering,
354 llvm::LLVMContext &Ctx) const {
355 return Ctx.getOrInsertSyncScopeID(mapClangSyncScopeToLLVM(Scope));
356}
357
358/// Construct a SPIR-V target extension type for the given OpenCL image type.
359static llvm::Type *getSPIRVImageType(llvm::LLVMContext &Ctx, StringRef BaseType,
360 StringRef OpenCLName,
361 unsigned AccessQualifier) {
362 // These parameters compare to the operands of OpTypeImage (see
363 // https://registry.khronos.org/SPIR-V/specs/unified1/SPIRV.html#OpTypeImage
364 // for more details). The first 6 integer parameters all default to 0, and
365 // will be changed to 1 only for the image type(s) that set the parameter to
366 // one. The 7th integer parameter is the access qualifier, which is tacked on
367 // at the end.
368 SmallVector<unsigned, 7> IntParams = {0, 0, 0, 0, 0, 0};
369
370 // Choose the dimension of the image--this corresponds to the Dim enum in
371 // SPIR-V (first integer parameter of OpTypeImage).
372 if (OpenCLName.starts_with("image2d"))
373 IntParams[0] = 1;
374 else if (OpenCLName.starts_with("image3d"))
375 IntParams[0] = 2;
376 else if (OpenCLName == "image1d_buffer")
377 IntParams[0] = 5; // Buffer
378 else
379 assert(OpenCLName.starts_with("image1d") && "Unknown image type");
380
381 // Set the other integer parameters of OpTypeImage if necessary. Note that the
382 // OpenCL image types don't provide any information for the Sampled or
383 // Image Format parameters.
384 if (OpenCLName.contains("_depth"))
385 IntParams[1] = 1;
386 if (OpenCLName.contains("_array"))
387 IntParams[2] = 1;
388 if (OpenCLName.contains("_msaa"))
389 IntParams[3] = 1;
390
391 // Access qualifier
392 IntParams.push_back(AccessQualifier);
393
394 return llvm::TargetExtType::get(Ctx, BaseType, {llvm::Type::getVoidTy(Ctx)},
395 IntParams);
396}
397
398llvm::Type *CommonSPIRTargetCodeGenInfo::getOpenCLType(CodeGenModule &CGM,
399 const Type *Ty) const {
400 llvm::LLVMContext &Ctx = CGM.getLLVMContext();
401 if (auto *PipeTy = dyn_cast<PipeType>(Ty))
402 return llvm::TargetExtType::get(Ctx, "spirv.Pipe", {},
403 {!PipeTy->isReadOnly()});
404 if (auto *BuiltinTy = dyn_cast<BuiltinType>(Ty)) {
405 enum AccessQualifier : unsigned { AQ_ro = 0, AQ_wo = 1, AQ_rw = 2 };
406 switch (BuiltinTy->getKind()) {
407#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
408 case BuiltinType::Id: \
409 return getSPIRVImageType(Ctx, "spirv.Image", #ImgType, AQ_##Suffix);
410#include "clang/Basic/OpenCLImageTypes.def"
411 case BuiltinType::OCLSampler:
412 return llvm::TargetExtType::get(Ctx, "spirv.Sampler");
413 case BuiltinType::OCLEvent:
414 return llvm::TargetExtType::get(Ctx, "spirv.Event");
415 case BuiltinType::OCLClkEvent:
416 return llvm::TargetExtType::get(Ctx, "spirv.DeviceEvent");
417 case BuiltinType::OCLQueue:
418 return llvm::TargetExtType::get(Ctx, "spirv.Queue");
419 case BuiltinType::OCLReserveID:
420 return llvm::TargetExtType::get(Ctx, "spirv.ReserveId");
421#define INTEL_SUBGROUP_AVC_TYPE(Name, Id) \
422 case BuiltinType::OCLIntelSubgroupAVC##Id: \
423 return llvm::TargetExtType::get(Ctx, "spirv.Avc" #Id "INTEL");
424#include "clang/Basic/OpenCLExtensionTypes.def"
425 default:
426 return nullptr;
427 }
428 }
429
430 return nullptr;
431}
432
433// Gets a spirv.IntegralConstant or spirv.Literal. If IntegralType is present,
434// returns an IntegralConstant, otherwise returns a Literal.
435static llvm::Type *getInlineSpirvConstant(CodeGenModule &CGM,
436 llvm::Type *IntegralType,
437 llvm::APInt Value) {
438 llvm::LLVMContext &Ctx = CGM.getLLVMContext();
439
440 // Convert the APInt value to an array of uint32_t words
442
443 while (Value.ugt(0)) {
444 uint32_t Word = Value.trunc(32).getZExtValue();
445 Value.lshrInPlace(32);
446
447 Words.push_back(Word);
448 }
449 if (Words.size() == 0)
450 Words.push_back(0);
451
452 if (IntegralType)
453 return llvm::TargetExtType::get(Ctx, "spirv.IntegralConstant",
454 {IntegralType}, Words);
455 return llvm::TargetExtType::get(Ctx, "spirv.Literal", {}, Words);
456}
457
458static llvm::Type *getInlineSpirvType(CodeGenModule &CGM,
459 const HLSLInlineSpirvType *SpirvType) {
460 llvm::LLVMContext &Ctx = CGM.getLLVMContext();
461
463
464 for (auto &Operand : SpirvType->getOperands()) {
465 using SpirvOperandKind = SpirvOperand::SpirvOperandKind;
466
467 llvm::Type *Result = nullptr;
468 switch (Operand.getKind()) {
469 case SpirvOperandKind::ConstantId: {
470 llvm::Type *IntegralType =
471 CGM.getTypes().ConvertType(Operand.getResultType());
472
473 Result = getInlineSpirvConstant(CGM, IntegralType, Operand.getValue());
474 break;
475 }
476 case SpirvOperandKind::Literal: {
477 Result = getInlineSpirvConstant(CGM, nullptr, Operand.getValue());
478 break;
479 }
480 case SpirvOperandKind::TypeId: {
481 QualType TypeOperand = Operand.getResultType();
482 if (const auto *RD = TypeOperand->getAsRecordDecl()) {
483 assert(RD->isCompleteDefinition() &&
484 "Type completion should have been required in Sema");
485
486 const FieldDecl *HandleField = RD->findFirstNamedDataMember();
487 if (HandleField) {
488 QualType ResourceType = HandleField->getType();
489 if (ResourceType->getAs<HLSLAttributedResourceType>()) {
490 TypeOperand = ResourceType;
491 }
492 }
493 }
494 Result = CGM.getTypes().ConvertType(TypeOperand);
495 break;
496 }
497 default:
498 llvm_unreachable("HLSLInlineSpirvType had invalid operand!");
499 break;
500 }
501
502 assert(Result);
503 Operands.push_back(Result);
504 }
505
506 return llvm::TargetExtType::get(Ctx, "spirv.Type", Operands,
507 {SpirvType->getOpcode(), SpirvType->getSize(),
508 SpirvType->getAlignment()});
509}
510
511llvm::Type *CommonSPIRTargetCodeGenInfo::getHLSLType(
512 CodeGenModule &CGM, const Type *Ty,
513 const SmallVector<int32_t> *Packoffsets) const {
514 llvm::LLVMContext &Ctx = CGM.getLLVMContext();
515
516 if (auto *SpirvType = dyn_cast<HLSLInlineSpirvType>(Ty))
517 return getInlineSpirvType(CGM, SpirvType);
518
519 auto *ResType = dyn_cast<HLSLAttributedResourceType>(Ty);
520 if (!ResType)
521 return nullptr;
522
523 const HLSLAttributedResourceType::Attributes &ResAttrs = ResType->getAttrs();
524 switch (ResAttrs.ResourceClass) {
525 case llvm::dxil::ResourceClass::UAV:
526 case llvm::dxil::ResourceClass::SRV: {
527 // TypedBuffer and RawBuffer both need element type
528 QualType ContainedTy = ResType->getContainedType();
529 if (ContainedTy.isNull())
530 return nullptr;
531
532 assert(!ResAttrs.IsROV &&
533 "Rasterizer order views not implemented for SPIR-V yet");
534
535 if (!ResAttrs.RawBuffer) {
536 // convert element type
537 return getSPIRVImageTypeFromHLSLResource(ResAttrs, ContainedTy, CGM);
538 }
539
540 if (ResAttrs.IsCounter) {
541 llvm::Type *ElemType = llvm::Type::getInt32Ty(Ctx);
542 uint32_t StorageClass = /* StorageBuffer storage class */ 12;
543 return llvm::TargetExtType::get(Ctx, "spirv.VulkanBuffer", {ElemType},
544 {StorageClass, true});
545 }
546 llvm::Type *ElemType = CGM.getTypes().ConvertTypeForMem(ContainedTy);
547 llvm::ArrayType *RuntimeArrayType = llvm::ArrayType::get(ElemType, 0);
548 uint32_t StorageClass = /* StorageBuffer storage class */ 12;
549 bool IsWritable = ResAttrs.ResourceClass == llvm::dxil::ResourceClass::UAV;
550 return llvm::TargetExtType::get(Ctx, "spirv.VulkanBuffer",
551 {RuntimeArrayType},
552 {StorageClass, IsWritable});
553 }
554 case llvm::dxil::ResourceClass::CBuffer: {
555 QualType ContainedTy = ResType->getContainedType();
556 if (ContainedTy.isNull() || !ContainedTy->isStructureType())
557 return nullptr;
558
559 llvm::Type *BufferLayoutTy =
560 HLSLBufferLayoutBuilder(CGM, "spirv.Layout")
561 .createLayoutType(ContainedTy->castAsCanonical<RecordType>(),
562 Packoffsets);
563 uint32_t StorageClass = /* Uniform storage class */ 2;
564 return llvm::TargetExtType::get(Ctx, "spirv.VulkanBuffer", {BufferLayoutTy},
565 {StorageClass, false});
566 break;
567 }
568 case llvm::dxil::ResourceClass::Sampler:
569 return llvm::TargetExtType::get(Ctx, "spirv.Sampler");
570 }
571 return nullptr;
572}
573
574static unsigned
576 const HLSLAttributedResourceType::Attributes &attributes,
577 llvm::Type *SampledType, QualType Ty, unsigned NumChannels) {
578 // For images with `Sampled` operand equal to 2, there are restrictions on
579 // using the Unknown image format. To avoid these restrictions in common
580 // cases, we guess an image format for them based on the sampled type and the
581 // number of channels. This is intended to match the behaviour of DXC.
582 if (LangOpts.HLSLSpvUseUnknownImageFormat ||
583 attributes.ResourceClass != llvm::dxil::ResourceClass::UAV) {
584 return 0; // Unknown
585 }
586
587 if (SampledType->isIntegerTy(32)) {
588 if (Ty->isSignedIntegerType()) {
589 if (NumChannels == 1)
590 return 24; // R32i
591 if (NumChannels == 2)
592 return 25; // Rg32i
593 if (NumChannels == 4)
594 return 21; // Rgba32i
595 } else {
596 if (NumChannels == 1)
597 return 33; // R32ui
598 if (NumChannels == 2)
599 return 35; // Rg32ui
600 if (NumChannels == 4)
601 return 30; // Rgba32ui
602 }
603 } else if (SampledType->isIntegerTy(64)) {
604 if (NumChannels == 1) {
605 if (Ty->isSignedIntegerType()) {
606 return 41; // R64i
607 }
608 return 40; // R64ui
609 }
610 } else if (SampledType->isFloatTy()) {
611 if (NumChannels == 1)
612 return 3; // R32f
613 if (NumChannels == 2)
614 return 6; // Rg32f
615 if (NumChannels == 4)
616 return 1; // Rgba32f
617 }
618
619 return 0; // Unknown
620}
621
622llvm::Type *CommonSPIRTargetCodeGenInfo::getSPIRVImageTypeFromHLSLResource(
623 const HLSLAttributedResourceType::Attributes &attributes, QualType Ty,
624 CodeGenModule &CGM) const {
625 llvm::LLVMContext &Ctx = CGM.getLLVMContext();
626
627 unsigned NumChannels = 1;
629 if (const VectorType *V = dyn_cast<VectorType>(Ty)) {
630 NumChannels = V->getNumElements();
631 Ty = V->getElementType();
632 }
633 assert(!Ty->isVectorType() && "We still have a vector type.");
634
635 llvm::Type *SampledType = CGM.getTypes().ConvertTypeForMem(Ty);
636
637 assert((SampledType->isIntegerTy() || SampledType->isFloatingPointTy()) &&
638 "The element type for a SPIR-V resource must be a scalar integer or "
639 "floating point type.");
640
641 // These parameters correspond to the operands to the OpTypeImage SPIR-V
642 // instruction. See
643 // https://registry.khronos.org/SPIR-V/specs/unified1/SPIRV.html#OpTypeImage.
644 SmallVector<unsigned, 6> IntParams(6, 0);
645
646 const char *Name =
647 Ty->isSignedIntegerType() ? "spirv.SignedImage" : "spirv.Image";
648
649 // Dim
650 // For now we assume everything is a buffer.
651 IntParams[0] = 5;
652
653 // Depth
654 // HLSL does not indicate if it is a depth texture or not, so we use unknown.
655 IntParams[1] = 2;
656
657 // Arrayed
658 IntParams[2] = 0;
659
660 // MS
661 IntParams[3] = 0;
662
663 // Sampled
664 IntParams[4] =
665 attributes.ResourceClass == llvm::dxil::ResourceClass::UAV ? 2 : 1;
666
667 // Image format.
668 IntParams[5] = getImageFormat(CGM.getLangOpts(), attributes, SampledType, Ty,
669 NumChannels);
670
671 llvm::TargetExtType *ImageType =
672 llvm::TargetExtType::get(Ctx, Name, {SampledType}, IntParams);
673 return ImageType;
674}
675
676std::unique_ptr<TargetCodeGenInfo>
678 return std::make_unique<CommonSPIRTargetCodeGenInfo>(CGM.getTypes());
679}
680
681std::unique_ptr<TargetCodeGenInfo>
683 return std::make_unique<SPIRVTargetCodeGenInfo>(CGM.getTypes());
684}
#define V(N, I)
static void setCUDAKernelCallingConvention(CanQualType &FTy, CodeGenModule &CGM, const FunctionDecl *FD)
Set calling convention for CUDA/HIP kernel.
Definition CGCall.cpp:359
static llvm::Type * getInlineSpirvType(CodeGenModule &CGM, const HLSLInlineSpirvType *SpirvType)
Definition SPIR.cpp:458
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:359
static unsigned getImageFormat(const LangOptions &LangOpts, const HLSLAttributedResourceType::Attributes &attributes, llvm::Type *SampledType, QualType Ty, unsigned NumChannels)
Definition SPIR.cpp:575
static llvm::Type * getInlineSpirvConstant(CodeGenModule &CGM, llvm::Type *IntegralType, llvm::APInt Value)
Definition SPIR.cpp:435
unsigned getTargetAddressSpace(LangAS AS) const
static ABIArgInfo getDirect(llvm::Type *T=nullptr, unsigned Offset=0, llvm::Type *Padding=nullptr, bool CanBeFlattened=true, unsigned Align=0)
@ 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
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:47
T * getAttr() const
Definition DeclBase.h:573
bool hasAttr() const
Definition DeclBase.h:577
Represents a member of a struct/union/class.
Definition Decl.h:3160
ExtInfo withCallingConv(CallingConv cc) const
Definition TypeBase.h:4673
ExtInfo getExtInfo() const
Definition TypeBase.h:4806
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:8404
bool hasFlexibleArrayMember() const
Definition Decl.h:4345
Scope - A scope is a transient data structure that is used while parsing the program.
Definition Scope.h:41
const llvm::Triple & getTriple() const
Returns the target triple of the primary target.
bool isStructureType() const
Definition Type.cpp:678
bool isSignedIntegerType() const
Return true if this is an integer type that is signed, according to C99 6.2.5p4 [char,...
Definition Type.cpp:2205
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:752
bool isVectorType() const
Definition TypeBase.h:8654
const T * castAsCanonical() const
Return this type's canonical type cast to the specified type.
Definition TypeBase.h:2928
const T * getAs() const
Member-template getAs<specific type>'.
Definition TypeBase.h:9091
const Type * getUnqualifiedDesugaredType() const
Return the specified type with any "sugar" removed from the type, removing any typedefs,...
Definition Type.cpp:653
bool isNullPtrType() const
Definition TypeBase.h:8908
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:145
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:221
bool isAggregateTypeForABI(QualType T)
std::unique_ptr< TargetCodeGenInfo > createSPIRVTargetCodeGenInfo(CodeGenModule &CGM)
Definition SPIR.cpp:682
std::unique_ptr< TargetCodeGenInfo > createCommonSPIRTargetCodeGenInfo(CodeGenModule &CGM)
Definition SPIR.cpp:677
The JSON file list parser is used to communicate input to InstallAPI.
StorageClass
Storage classes.
Definition Specifiers.h:248
const FunctionProtoType * T
@ Type
The name was classified as a type.
Definition Sema.h:562
LangAS
Defines the address space values used by the address space qualifier of QualType.
SyncScope
Defines sync scope values used internally by clang.
Definition SyncScope.h:42
@ CC_DeviceKernel
Definition Specifiers.h:292
@ CC_SpirFunction
Definition Specifiers.h:291
LangAS getLangASFromTargetAS(unsigned TargetAS)
unsigned int uint32_t