34#include "llvm/ADT/DenseMap.h"
35#include "llvm/ADT/Enum.h"
36#include "llvm/ADT/STLExtras.h"
37#include "llvm/ADT/ScopeExit.h"
38#include "llvm/ADT/SmallPtrSet.h"
39#include "llvm/ADT/SmallString.h"
40#include "llvm/ADT/SmallVector.h"
41#include "llvm/ADT/StringSwitch.h"
42#include "llvm/Frontend/HLSL/HLSLResource.h"
43#include "llvm/Frontend/HLSL/HLSLUtils.h"
44#include "llvm/Frontend/HLSL/RootSignatureMetadata.h"
45#include "llvm/Frontend/HLSL/SemanticSignaturePacking.h"
46#include "llvm/IR/Constants.h"
47#include "llvm/IR/DerivedTypes.h"
48#include "llvm/IR/GlobalVariable.h"
49#include "llvm/IR/IntrinsicInst.h"
50#include "llvm/IR/LLVMContext.h"
51#include "llvm/IR/Metadata.h"
52#include "llvm/IR/Module.h"
53#include "llvm/IR/Type.h"
54#include "llvm/IR/Value.h"
55#include "llvm/Support/Alignment.h"
56#include "llvm/Support/ErrorHandling.h"
57#include "llvm/Support/FormatVariadic.h"
58#include "llvm/Support/Path.h"
59#include "llvm/Transforms/Utils/ModuleUtils.h"
69using llvm::hlsl::CBufferRowSizeInBytes;
73enum class SPIRVExecutionMode :
uint32_t {
74 DerivativeGroupQuadsKHR = 5289,
75 DerivativeGroupLinearKHR = 5290
78void addDxilValVersion(StringRef ValVersionStr, llvm::Module &M) {
82 if (Version.tryParse(ValVersionStr) || Version.getBuild() ||
83 Version.getSubminor() || !Version.getMinor()) {
88 uint64_t Minor = *Version.getMinor();
90 auto &Ctx = M.getContext();
92 MDNode *Val = MDNode::get(Ctx, {ConstantAsMetadata::get(B.getInt32(Major)),
93 ConstantAsMetadata::get(B.getInt32(Minor))});
94 StringRef DXILValKey =
"dx.valver";
95 auto *DXILValMD = M.getOrInsertNamedMetadata(DXILValKey);
96 DXILValMD->addOperand(Val);
99void addRootSignatureMD(llvm::dxbc::RootSignatureVersion RootSigVer,
101 llvm::Function *Fn, llvm::Module &M) {
102 auto &Ctx = M.getContext();
104 llvm::hlsl::rootsig::MetadataBuilder RSBuilder(M, Elements);
105 MDNode *RootSignature = RSBuilder.BuildRootSignature();
107 ConstantAsMetadata *Version = ConstantAsMetadata::get(ConstantInt::get(
108 llvm::Type::getInt32Ty(Ctx), llvm::to_underlying(RootSigVer)));
109 ValueAsMetadata *EntryFunc =
Fn ? ValueAsMetadata::get(Fn) :
nullptr;
110 MDNode *MDVals = MDNode::get(Ctx, {EntryFunc, RootSignature, Version});
112 StringRef RootSignatureValKey =
"dx.rootsignatures";
113 auto *RootSignatureValMD = M.getOrInsertNamedMetadata(RootSignatureValKey);
114 RootSignatureValMD->addOperand(MDVals);
119 llvm::Triple::EnvironmentType Stage, llvm::hlsl::IOType IOTy,
121 bool UseNative16BitTypes) {
122 using namespace llvm::hlsl;
125 if (Stage == llvm::Triple::Vertex && IOTy == IOType::In)
126 return packSignatureStacked(Elements, Stage, IOTy);
127 if (Stage == llvm::Triple::Pixel && IOTy == IOType::Out)
128 return packSignatureIndexed(Elements, Stage, IOTy);
130 return packSignatureOptimized(Elements, Stage, IOTy, UseNative16BitTypes);
131 return packSignaturePrefixStable(Elements, Stage, IOTy, UseNative16BitTypes);
134MDNode *buildSemanticSignatureMD(
136 if (Elements.empty())
140 for (
const llvm::hlsl::SemanticSignatureElement &Element : Elements)
141 ElementMD.push_back(Element.toMetadata(Ctx));
142 return MDNode::get(Ctx, ElementMD);
145void addSemanticSignatureMD(
148 llvm::Function *Fn, llvm::Module &M) {
149 if (InputElements.empty() && OutputElements.empty())
152 LLVMContext &Ctx = M.getContext();
153 MDNode *InputSignature = buildSemanticSignatureMD(InputElements, Ctx);
154 MDNode *OutputSignature = buildSemanticSignatureMD(OutputElements, Ctx);
155 MDNode *MDVals = MDNode::get(
156 Ctx, {ValueAsMetadata::get(Fn), InputSignature, OutputSignature});
158 M.getOrInsertNamedMetadata(
"dx.semantic.signatures")->addOperand(MDVals);
163 GlobalVariable *ResGV =
165 assert(ResGV &&
"expected valid global variable");
182static const VarDecl *findStructResourceParentDeclAndBuildName(
189 if (
const auto *DRE = dyn_cast<DeclRefExpr>(E)) {
191 "member expr base is not a var decl");
197 WorkList.push_back(E);
198 if (
const auto *MExp = dyn_cast<MemberExpr>(E))
200 else if (
const auto *ICE = dyn_cast<ImplicitCastExpr>(E))
201 E = ICE->getSubExpr();
202 else if (
const auto *ASE = dyn_cast<ArraySubscriptExpr>(E))
209 llvm_unreachable(
"unexpected expr type in resource member access");
211 assert(E &&
"expected valid expression");
214 while (!WorkList.empty()) {
215 E = WorkList.pop_back_val();
216 if (
const auto *ME = dyn_cast<MemberExpr>(E)) {
218 ME->getMemberNameInfo().getName().getAsIdentifierInfo()->getName());
219 }
else if (
const auto *ICE = dyn_cast<ImplicitCastExpr>(E)) {
220 if (ICE->getCastKind() == CK_UncheckedDerivedToBase) {
222 ICE->getSubExpr()->getType()->getAsCXXRecordDecl();
223 CXXRecordDecl *BaseRD = ICE->getType()->getAsCXXRecordDecl();
226 }
else if (
const auto *ASE = dyn_cast<ArraySubscriptExpr>(E)) {
227 const Expr *IdxExpr = ASE->getIdx();
228 std::optional<llvm::APSInt>
Value =
231 "expected constant index in struct with resource array access");
234 llvm_unreachable(
"unexpected expr type in resource member access");
248 findStructResourceParentDeclAndBuildName(ME, NameBuilder);
257 if (
const auto *ADA = dyn_cast<HLSLAssociatedResourceDeclAttr>(A)) {
258 VarDecl *AssocResVD = ADA->getResDecl();
270 auto &Ctx = M.getContext();
273 llvm::NamedMDNode *DXContents =
274 M.getOrInsertNamedMetadata(
"dx.source.contents");
275 auto addFile = [&](
const std::pair<StringRef, StringRef> &NameContent) {
276 llvm::MDTuple *FileInfo =
277 llvm::MDNode::get(Ctx, {llvm::MDString::get(Ctx, NameContent.first),
278 llvm::MDString::get(Ctx, NameContent.second)});
279 DXContents->addOperand(FileInfo);
284 &SM.getSLocEntry(SM.getMainFileID(), &
Invalid);
285 assert(!
Invalid &&
"Main file SLocEntry must not be invalid!");
290 std::optional<SmallString<256>> MainFileName;
291 Files.reserve(SM.local_sloc_entry_size());
292 for (
unsigned I : llvm::seq(SM.local_sloc_entry_size())) {
307 llvm::sys::path::native(Path);
311 SM.getDiagnostics().Report(diag::warn_hlsl_failed_to_embed_source)
316 if (&MainCCEntry != &CCEntry) {
317 Files.emplace_back(Path, Buffer->getBuffer());
320 addFile(std::make_pair(Path, Buffer->getBuffer()));
321 MainFileName.emplace(Path);
324 assert(MainFileName &&
"Main file not found.");
329 for (
unsigned I = 1; I < Files.size(); ++I)
330 assert((Files[I - 1].first != Files[I].first) &&
331 "duplicate files in dx.source.contents");
333 llvm::for_each(Files, addFile);
336 Defines.reserve(
Macros.size());
337 for (
const auto &
Macro : Macros) {
340 Defines.emplace_back(llvm::MDString::get(Ctx,
Macro.first));
342 M.getOrInsertNamedMetadata(
"dx.source.defines")
343 ->addOperand(llvm::MDNode::get(Ctx, Defines));
345 if (!CodeGenOpts.MainFileName.empty())
346 llvm::sys::path::native(CodeGenOpts.MainFileName, *MainFileName);
347 M.getOrInsertNamedMetadata(
"dx.source.mainFileName")
349 llvm::MDNode::get(Ctx, llvm::MDString::get(Ctx, *MainFileName)));
352 Args.reserve(CodeGenOpts.HLSLParsedCommandLine.size());
353 if (!CodeGenOpts.HLSLParsedCommandLine.empty())
354 for (
const auto &Arg : llvm::drop_begin(CodeGenOpts.HLSLParsedCommandLine))
355 Args.push_back(llvm::MDString::get(Ctx, Arg));
356 M.getOrInsertNamedMetadata(
"dx.source.args")
357 ->addOperand(llvm::MDNode::get(Ctx, Args));
363 if (
const auto *DRE = dyn_cast_or_null<DeclRefExpr>(E))
364 return DRE->getDecl();
365 if (
auto *OVE = dyn_cast<OpaqueValueExpr>(E))
375 const Expr *E =
nullptr;
376 while (ASE !=
nullptr) {
380 ASE = dyn_cast<ArraySubscriptExpr>(E);
382 return getArrayDecl(AST, E);
388 assert(Ty->
isArrayType() &&
"expected array type");
394static Value *buildNameForResource(llvm::StringRef BaseName,
403 for (
auto *Method :
Record->methods()) {
404 if (Method->getStorageClass() == SC && Method->getName() == Name)
414 assert(Binding.
hasBinding() &&
"at least one binding attribute expected");
418 Value *NameStr = buildNameForResource(Name, CGM);
423 "resources with counter handle must have a binding with counter "
424 "implicit order ID");
427 auto *RegSlot = llvm::ConstantInt::get(CGM.
IntTy, Binding.
getSlot());
430 ?
"__createFromBindingWithImplicitCounter"
431 :
"__createFromBinding";
432 CreateMethod = lookupMethod(ResourceDecl, Name,
SC_Static);
439 ?
"__createFromImplicitBindingWithImplicitCounter"
440 :
"__createFromImplicitBinding";
441 CreateMethod = lookupMethod(ResourceDecl, Name,
SC_Static);
449 auto *CounterOrderID = llvm::ConstantInt::get(CGM.
IntTy, CounterBinding);
465 Args, Proto,
false,
nullptr);
468 CGF.
EmitCall(FnInfo, Callee, ReturnValue, Args,
nullptr);
477static std::optional<llvm::Value *> initializeResourceArrayFromGlobal(
480 llvm::Value *Range, llvm::Value *StartIndex, StringRef ResourceName,
484 llvm::IntegerType *IntTy = CGF.
CGM.
IntTy;
485 llvm::Value *Index = StartIndex;
486 llvm::Value *One = llvm::ConstantInt::get(IntTy, 1);
494 GEPIndices.push_back(llvm::ConstantInt::get(IntTy, 0));
499 for (
uint64_t I = 0; I < ArraySize; I++) {
501 Index = CGF.
Builder.CreateAdd(Index, One);
502 GEPIndices.back() = llvm::ConstantInt::get(IntTy, I);
504 std::optional<llvm::Value *> MaybeIndex =
505 initializeResourceArrayFromGlobal(CGF, ResourceDecl, SubArrayTy,
506 ValueSlot, Range, Index,
507 ResourceName, Binding, GEPIndices);
521 for (
uint64_t I = 0; I < ArraySize; I++) {
523 Index = CGF.
Builder.CreateAdd(Index, One);
524 GEPIndices.back() = llvm::ConstantInt::get(IntTy, I);
530 CXXMethodDecl *CreateMethod = lookupResourceInitMethodAndSetupArgs(
531 CGF.
CGM, ResourceDecl, Range, Index, ResourceName, Binding, Args);
539 callResourceInitMethod(CGF, CreateMethod, Args, ReturnAddress);
546class HLSLBufferCopyEmitter {
547 CodeGenFunction &CGF;
550 llvm::Type *LayoutTy =
nullptr;
552 SmallVector<llvm::Value *> CurStoreIndices;
553 SmallVector<llvm::Value *> CurLoadIndices;
555 using EmitResourceFnTy = llvm::function_ref<void(AggValueSlot &)>;
559 llvm::Value *emitAccessChain(llvm::Type *BaseTy, llvm::Value *Base,
560 ArrayRef<llvm::Value *> Indices) {
561 bool EmitLogical = CGF.getLangOpts().EmitLogicalPointer;
563 return CGF.Builder.CreateAccessChain(EmitLogical, BaseTy, Base, Indices);
565 llvm::SmallVector<llvm::Value *> GEPIndices;
566 GEPIndices.reserve(Indices.size() + 1);
567 GEPIndices.push_back(llvm::ConstantInt::get(CGF.IntTy, 0));
568 GEPIndices.append(Indices.begin(), Indices.end());
569 return CGF.Builder.CreateAccessChain(EmitLogical, BaseTy, Base, GEPIndices);
572 bool isBufferLayoutArray(llvm::StructType *ST) {
578 if (!ST || ST->getNumElements() != 2)
581 auto *PaddedEltsTy = dyn_cast<llvm::ArrayType>(ST->getElementType(0));
585 auto *PaddedTy = dyn_cast<llvm::StructType>(PaddedEltsTy->getElementType());
586 if (!PaddedTy || PaddedTy->getNumElements() != 2)
589 if (!CGF.CGM.getTargetCodeGenInfo().isHLSLPadding(
590 PaddedTy->getElementType(1)))
593 llvm::Type *ElementTy = ST->getElementType(1);
594 if (PaddedTy->getElementType(0) != ElementTy)
605 bool isResourceOrResourceArray(llvm::Type *Ty) {
606 while (
auto *AT = dyn_cast<llvm::ArrayType>(Ty))
607 Ty = AT->getElementType();
609 auto *ST = dyn_cast<llvm::StructType>(Ty);
610 if (!ST || ST->getNumElements() < 1)
613 auto *TargetTy = dyn_cast<llvm::TargetExtType>(ST->getElementType(0));
614 return TargetTy !=
nullptr;
617 void emitResourceOrResourceArray(
Value *Dst, llvm::Type *DstTy,
618 EmitResourceFnTy EmitResFn) {
621 Address DstAddr(Dst, DstTy, DstAlign);
630 void emitBufferLayoutCopy(
Value *Src, llvm::StructType *SrcTy,
Value *Dst,
631 llvm::ArrayType *DstTy,
632 EmitResourceFnTy EmitResFn) {
635 assert(SrcPaddedArrayTy->getNumElements() + 1 == DstTy->getNumElements());
637 ->getElementType(0) == SrcTy->getElementType(1));
639 auto *SrcDataTy = SrcTy->getElementType(1);
640 auto Zero = llvm::ConstantInt::get(CGF.IntTy, 0);
642 for (
unsigned I = 0; I < SrcPaddedArrayTy->getNumElements(); ++I) {
643 auto Index = llvm::ConstantInt::get(CGF.IntTy, I);
644 auto *SrcElt = emitAccessChain(SrcTy, Src, {
Zero, Index,
Zero});
645 auto *DstElt = emitAccessChain(DstTy, Dst, {Index});
646 emitElementCopy(SrcElt, SrcDataTy, DstElt, DstTy->getElementType(),
651 emitAccessChain(SrcTy, Src, {llvm::ConstantInt::get(CGF.IntTy, 1)});
652 auto *DstElt = emitAccessChain(
654 {llvm::ConstantInt::get(CGF.IntTy, DstTy->getNumElements() - 1)});
655 emitElementCopy(SrcElt, SrcDataTy, DstElt, DstTy->getElementType(),
659 void emitCopy(
Value *Src, llvm::StructType *SrcTy,
Value *Dst,
660 llvm::Type *DstTy, EmitResourceFnTy EmitResFn) {
661 assert(!isResourceOrResourceArray(DstTy) &&
662 "direct access to resources or resource arrays should be handled "
665 if (isBufferLayoutArray(SrcTy))
669 unsigned SrcIndex = 0;
670 unsigned DstIndex = 0;
677 while (DstIndex < DstST->getNumElements()) {
678 llvm::Type *DstEltTy = DstST->getElementType(DstIndex);
679 if (CGF.CGM.getTargetCodeGenInfo().isHLSLPadding(DstEltTy)) {
683 if (isResourceOrResourceArray(DstEltTy)) {
684 auto *DstElt = emitAccessChain(
685 DstTy, Dst, {llvm::ConstantInt::get(CGF.IntTy, DstIndex)});
686 emitResourceOrResourceArray(DstElt, DstEltTy, EmitResFn);
691 assert(SrcIndex < SrcTy->getNumElements());
692 llvm::Type *SrcEltTy = SrcTy->getElementType(SrcIndex);
693 if (CGF.CGM.getTargetCodeGenInfo().isHLSLPadding(SrcEltTy)) {
698 auto *SrcElt = emitAccessChain(
699 SrcTy, Src, {llvm::ConstantInt::get(CGF.IntTy, SrcIndex)});
700 auto *DstElt = emitAccessChain(
701 DstTy, Dst, {llvm::ConstantInt::get(CGF.IntTy, DstIndex)});
702 emitElementCopy(SrcElt, SrcEltTy, DstElt, DstEltTy, EmitResFn);
708 void emitCopy(
Value *Src, llvm::ArrayType *SrcTy,
Value *Dst,
709 llvm::Type *DstTy, EmitResourceFnTy EmitResFn) {
710 for (
unsigned I = 0, E = SrcTy->getNumElements(); I < E; ++I) {
712 emitAccessChain(SrcTy, Src, {llvm::ConstantInt::get(CGF.IntTy, I)});
714 emitAccessChain(DstTy, Dst, {llvm::ConstantInt::get(CGF.IntTy, I)});
715 emitElementCopy(SrcElt, SrcTy->getElementType(), DstElt,
721 void emitElementCopy(
Value *Src, llvm::Type *SrcTy,
Value *Dst,
722 llvm::Type *DstTy, EmitResourceFnTy EmitResFn) {
723 if (
auto *AT = dyn_cast<llvm::ArrayType>(SrcTy))
724 return emitCopy(Src, AT, Dst, DstTy, EmitResFn);
725 if (
auto *ST = dyn_cast<llvm::StructType>(SrcTy))
726 return emitCopy(Src, ST, Dst, DstTy, EmitResFn);
733 Address SrcAddr(Src, SrcTy, SrcAlign);
734 Address DstAddr(Dst, DstTy, DstAlign);
735 llvm::Value *
Load = CGF.Builder.CreateLoad(SrcAddr,
"cbuf.load");
736 CGF.Builder.CreateStore(Load, DstAddr);
740 HLSLBufferCopyEmitter(CodeGenFunction &CGF, Address DstPtr, Address SrcPtr)
741 : CGF(CGF), DstPtr(DstPtr), SrcPtr(SrcPtr) {}
743 bool emitCopy(QualType CType, EmitResourceFnTy EmitResFn =
nullptr) {
744 LayoutTy = HLSLBufferLayoutBuilder(CGF.CGM).layOutType(CType);
751 emitElementCopy(SrcPtr.getBasePointer(), LayoutTy, DstPtr.getBasePointer(),
752 DstPtr.getElementType(), EmitResFn);
763class AssociatedResourcesList {
768 specific_attr_iterator<HLSLAssociatedResourceDeclAttr> Begin, End, Next;
771 AssociatedResourcesList(
const VarDecl *StructVD,
772 StringRef ResourceNamePrefix) {
778 !I->getResDecl()->getName().starts_with(ResourceNamePrefix))
780 assert(I != E &&
"expected associated resource not found");
785 while (I != E && ((HLSLAssociatedResourceDeclAttr *)*I)
788 .starts_with(ResourceNamePrefix))
794 const VarDecl *getNextResource() {
798 const VarDecl *Res = Next->getResDecl();
809 assert(
T->isHLSLSpecificType() &&
"Not an HLSL specific type!");
812 if (llvm::Type *TargetTy =
813 CGM.getTargetCodeGenInfo().getHLSLType(
CGM,
T, OffsetInfo))
816 llvm_unreachable(
"Generic handling of HLSL types is not supported.");
819llvm::Triple::ArchType CGHLSLRuntime::getArch() {
825void CGHLSLRuntime::emitBufferGlobalsAndMetadata(
831 llvm::Type *BufType = BufGV->getValueType();
836 size_t OffsetIdx = 0;
846 VarDecl *VD = dyn_cast<VarDecl>(D);
862 DeclsWithOffset.emplace_back(VD, OffsetInfo[OffsetIdx++]);
865 if (!OffsetInfo.
empty())
866 llvm::stable_sort(DeclsWithOffset, [](
const auto &LHS,
const auto &RHS) {
871 SmallVector<llvm::Metadata *> BufGlobals;
872 BufGlobals.reserve(DeclsWithOffset.size() + 1);
873 BufGlobals.push_back(ValueAsMetadata::get(BufGV));
875 auto ElemIt = LayoutStruct->element_begin();
876 for (
auto &[VD, _] : DeclsWithOffset) {
877 if (
CGM.getTargetCodeGenInfo().isHLSLPadding(*ElemIt))
880 assert(ElemIt != LayoutStruct->element_end() &&
881 "number of elements in layout struct does not match");
882 llvm::Type *LayoutType = *ElemIt++;
884 GlobalVariable *ElemGV =
886 BufGlobals.push_back(ValueAsMetadata::get(ElemGV));
888 assert(ElemIt == LayoutStruct->element_end() &&
889 "number of elements in layout struct does not match");
893 .getOrInsertNamedMetadata(
"hlsl.cbs")
894 ->addOperand(MDNode::get(Ctx, BufGlobals));
898static const clang::HLSLAttributedResourceType *
903 HLSLAttributedResourceType::Attributes(ResourceClass::CBuffer));
918 VarDecl *VD = dyn_cast<VarDecl>(D);
929 if (
auto *POA = dyn_cast<HLSLPackOffsetAttr>(
Attr)) {
930 Offset = POA->getOffsetInBytes();
933 auto *RBA = dyn_cast<HLSLResourceBindingAttr>(
Attr);
935 RBA->getRegisterType() == HLSLResourceBindingAttr::RegisterType::C) {
936 Offset = RBA->getSlotNumber() * CBufferRowSizeInBytes;
940 Result.Offsets.push_back(Offset);
948 assert(BufDecl->
isCBuffer() &&
"tbuffer codegen is not supported yet");
951 const clang::HLSLAttributedResourceType *ResHandleTy =
955 if (ResHandleTy->getContainedType()->getAsCXXRecordDecl()->isEmpty())
961 llvm::GlobalVariable *BufGV =
new GlobalVariable(
963 GlobalValue::LinkageTypes::InternalLinkage, PoisonValue::get(LayoutTy),
964 llvm::formatv(
"{0}{1}", BufDecl->
getName(),
966 GlobalValue::NotThreadLocal);
968 llvm::Module &M =
CGM.getModule();
969 M.insertGlobalVariable(BufGV);
974 llvm::appendToCompilerUsed(M, {BufGV});
977 emitBufferGlobalsAndMetadata(BufDecl, BufGV, OffsetInfo);
980 initializeBufferFromBinding(BufDecl, BufGV);
985 llvm::Module &M =
CGM.getModule();
986 Triple
T(M.getTargetTriple());
989 if (
T.getEnvironment() != Triple::EnvironmentType::RootSignature)
992 addRootSignatureMD(SignatureDecl->
getVersion(),
998 const auto Entry = LayoutTypes.find(StructType);
999 if (Entry != LayoutTypes.end())
1000 return Entry->getSecond();
1005 llvm::StructType *LayoutTy) {
1007 "layout type for this struct already exist");
1008 LayoutTypes[StructType] = LayoutTy;
1014 Intrinsic::getDeclarationIfExists(&M, Intrinsic::spv_quad_all);
1021 while (!Worklist.empty()) {
1022 Function *F = Worklist.pop_back_val();
1023 if (!Visited.insert(F).second)
1026 Attribute NumThreadsAttr = F->getFnAttribute(
"hlsl.numthreads");
1027 if (NumThreadsAttr.isValid()) {
1028 std::array<uint32_t, 3> Threads;
1029 llvm::hlsl::parseThreadCounts(NumThreadsAttr.getValueAsString(),
1030 Threads[0], Threads[1], Threads[2]);
1031 bool IsLinear = Threads[1] == 1 && Threads[2] == 1;
1035 bool InvalidThreads;
1036 SPIRVExecutionMode Mode;
1039 (
uint64_t(Threads[0]) * Threads[1] * Threads[2]) % 4 != 0;
1040 Mode = SPIRVExecutionMode::DerivativeGroupLinearKHR;
1042 InvalidThreads = Threads[0] % 2 != 0 || Threads[1] % 2 != 0;
1043 Mode = SPIRVExecutionMode::DerivativeGroupQuadsKHR;
1045 if (InvalidThreads) {
1046 CGM.
getDiags().
Report(diag::err_hlsl_spirv_derivative_group_numthreads)
1047 << F->getName() << IsLinear;
1049 diag::note_hlsl_spirv_derivative_group_requirement)
1050 <<
"QuadAll" << F->getName();
1053 MDNode *MD = MDNode::get(
1055 {ValueAsMetadata::get(F),
1056 ConstantAsMetadata::get(B.getInt32(llvm::to_underlying(Mode)))});
1057 M.getOrInsertNamedMetadata(
"spirv.ExecutionMode")->addOperand(MD);
1060 for (User *
U : F->users())
1061 if (
auto *
Call = dyn_cast<CallBase>(
U))
1062 Worklist.push_back(
Call->getFunction());
1067 auto &TargetOpts =
CGM.getTarget().getTargetOpts();
1068 auto &CodeGenOpts =
CGM.getCodeGenOpts();
1069 auto &LangOpts =
CGM.getLangOpts();
1070 llvm::Module &M =
CGM.getModule();
1071 Triple
T(M.getTargetTriple());
1072 if (
T.getArch() == Triple::ArchType::dxil)
1073 addDxilValVersion(TargetOpts.DxilValidatorVersion, M);
1074 if (!CodeGenOpts.DisableDXSourceMetadata &&
1075 CodeGenOpts.getDebugInfo() >=
1076 llvm::codegenoptions::DebugInfoKind::DebugInfoConstructor)
1077 addSourceInfo(
CGM, M);
1078 if (CodeGenOpts.ResMayAlias)
1079 M.setModuleFlag(llvm::Module::ModFlagBehavior::Error,
"dx.resmayalias", 1);
1080 if (CodeGenOpts.AllResourcesBound)
1081 M.setModuleFlag(llvm::Module::ModFlagBehavior::Error,
1082 "dx.allresourcesbound", 1);
1083 if (CodeGenOpts.OptimizationLevel == 0)
1084 M.addModuleFlag(llvm::Module::ModFlagBehavior::Override,
1085 "dx.disable_optimizations", 1);
1090 if (LangOpts.NativeHalfType)
1091 M.setModuleFlag(llvm::Module::ModFlagBehavior::Error,
"dx.nativelowprec",
1094 if (LangOpts.HLSLSpvPreserveInterface &&
T.isSPIRV()) {
1100 for (GlobalVariable &GV : M.globals()) {
1101 unsigned AS = GV.getAddressSpace();
1102 if (AS == InputAS || AS == OutputAS)
1103 InterfaceVars.push_back(&GV);
1105 if (!InterfaceVars.empty())
1106 appendToCompilerUsed(M, InterfaceVars);
1116 const auto *ShaderAttr = FD->
getAttr<HLSLShaderAttr>();
1117 assert(ShaderAttr &&
"All entry functions must have a HLSLShaderAttr");
1118 const StringRef ShaderAttrKindStr =
"hlsl.shader";
1119 Fn->addFnAttr(ShaderAttrKindStr,
1120 llvm::Triple::getEnvironmentTypeName(ShaderAttr->getType()));
1121 if (HLSLNumThreadsAttr *NumThreadsAttr = FD->
getAttr<HLSLNumThreadsAttr>()) {
1122 const StringRef NumThreadsKindStr =
"hlsl.numthreads";
1123 std::string NumThreadsStr =
1124 formatv(
"{0},{1},{2}", NumThreadsAttr->getX(), NumThreadsAttr->getY(),
1125 NumThreadsAttr->getZ());
1126 Fn->addFnAttr(NumThreadsKindStr, NumThreadsStr);
1128 if (HLSLWaveSizeAttr *WaveSizeAttr = FD->
getAttr<HLSLWaveSizeAttr>()) {
1129 const StringRef WaveSizeKindStr =
"hlsl.wavesize";
1130 std::string WaveSizeStr =
1131 formatv(
"{0},{1},{2}", WaveSizeAttr->getMin(), WaveSizeAttr->getMax(),
1132 WaveSizeAttr->getPreferred());
1133 Fn->addFnAttr(WaveSizeKindStr, WaveSizeStr);
1140 Fn->addFnAttr(llvm::Attribute::NoInline);
1142 if (
CGM.getLangOpts().HLSLSpvEnableMaximalReconvergence) {
1143 Fn->addFnAttr(
"enable-maximal-reconvergence",
"true");
1150 if (
const auto *VT = dyn_cast<FixedVectorType>(Ty)) {
1152 for (
unsigned I = 0; I < VT->getNumElements(); ++I) {
1153 Value *Elt = B.CreateCall(F, {B.getInt32(I)});
1154 Elt = B.CreateTrunc(Elt, VT->getElementType());
1159 return B.CreateTrunc(B.CreateCall(F, {B.getInt32(0)}), Ty);
1169 if (
auto *AT = dyn_cast<llvm::ArrayType>(Ty)) {
1170 Ty = AT->getElementType();
1173 if (
auto *VT = dyn_cast<llvm::FixedVectorType>(Ty)) {
1174 Ty = VT->getElementType();
1179 return Ty->isIntegerTy() || Ty->isDoubleTy();
1182static llvm::hlsl::InterpolationMode
1184 llvm::Type *Ty, llvm::Triple::EnvironmentType Stage,
1185 llvm::hlsl::IOType
IO) {
1186 using llvm::hlsl::InterpolationMode;
1187 if (!((Stage == llvm::Triple::Pixel &&
IO == llvm::hlsl::IOType::In) ||
1188 (Stage == llvm::Triple::Vertex &&
IO == llvm::hlsl::IOType::Out)))
1189 return InterpolationMode::Undefined;
1190 if (InterpMode == InterpolationMode::Undefined &&
1192 return InterpolationMode::Constant;
1198 llvm::hlsl::SPIRVInterfaceDecoration Decoration,
1200 llvm::hlsl::InterpolationMode InterpMode =
1201 llvm::hlsl::InterpolationMode::Undefined) {
1202 using llvm::hlsl::InterpolationMode;
1203 using llvm::hlsl::SPIRVInterpolationMode;
1205 LLVMContext &Ctx = GV->getContext();
1206 IRBuilder<> B(*GV->getParent());
1208 Decorations.push_back(MDNode::get(
1210 {ConstantAsMetadata::get(B.getInt32(llvm::to_underlying(Decoration))),
1211 ConstantAsMetadata::get(B.getInt32(Operand))}));
1212 auto Add = [&](SPIRVInterpolationMode InterpolationDecoration) {
1213 Decorations.push_back(
1214 MDNode::get(Ctx, {ConstantAsMetadata::get(B.getInt32(
1215 llvm::to_underlying(InterpolationDecoration)))}));
1217 switch (InterpMode) {
1218 case InterpolationMode::Undefined:
1219 case InterpolationMode::Linear:
1221 case InterpolationMode::Constant:
1222 Add(SPIRVInterpolationMode::Flat);
1224 case InterpolationMode::LinearNoperspective:
1225 Add(SPIRVInterpolationMode::NoPerspective);
1227 case InterpolationMode::LinearNoperspectiveCentroid:
1228 Add(SPIRVInterpolationMode::NoPerspective);
1230 case InterpolationMode::LinearCentroid:
1231 Add(SPIRVInterpolationMode::Centroid);
1233 case InterpolationMode::LinearNoperspectiveSample:
1234 Add(SPIRVInterpolationMode::NoPerspective);
1236 case InterpolationMode::LinearSample:
1237 Add(SPIRVInterpolationMode::Sample);
1240 llvm_unreachable(
"invalid interpolation mode");
1244 GV->addMetadata(
"spirv.Decorations", *MDNode::get(Ctx, Decorations));
1248 IRBuilder<> &B, llvm::Module &M, llvm::Type *Ty,
const Twine &Name,
1249 llvm::hlsl::SPIRVInterfaceDecoration Decoration,
unsigned Operand,
1250 llvm::hlsl::InterpolationMode InterpMode) {
1254 bool Truncate = Decoration == llvm::hlsl::SPIRVInterfaceDecoration::BuiltIn &&
1255 Ty->isIntegerTy() && Ty->getIntegerBitWidth() > 1 &&
1256 Ty->getIntegerBitWidth() < 32;
1257 llvm::Type *LoadTy = Truncate ? B.getInt32Ty() : Ty;
1258 auto *GV =
new llvm::GlobalVariable(
1259 M, LoadTy,
true, llvm::GlobalValue::ExternalLinkage,
1260 nullptr, Name,
nullptr,
1261 llvm::GlobalVariable::GeneralDynamicTLSModel,
1263 GV->setVisibility(llvm::GlobalValue::HiddenVisibility);
1265 llvm::Value *
Value = B.CreateLoad(LoadTy, GV);
1266 return Truncate ? B.CreateTrunc(
Value, Ty) :
Value;
1274 const Twine &Name,
unsigned BuiltInID,
1275 unsigned BaseBuiltInID,
1276 llvm::hlsl::InterpolationMode InterpMode) {
1278 B, M, Ty, Name, llvm::hlsl::SPIRVInterfaceDecoration::BuiltIn, BuiltInID,
1281 B, M, Ty, Name + Twine(
".base"),
1282 llvm::hlsl::SPIRVInterfaceDecoration::BuiltIn, BaseBuiltInID, InterpMode);
1286llvm::Value *CGHLSLRuntime::emitSPIRVUserSemanticLoad(
1287 llvm::IRBuilder<> &B, llvm::Type *
Type,
const clang::DeclaratorDecl *
Decl,
1288 HLSLAppliedSemanticAttr *Semantic, std::optional<unsigned> Index,
1289 llvm::hlsl::InterpolationMode InterpMode) {
1290 Twine BaseName = Twine(Semantic->getAttrName()->getName());
1291 Twine VariableName = BaseName.concat(Twine(Index.value_or(0)));
1293 unsigned Location = SPIRVLastAssignedInputSemanticLocation;
1294 if (
auto *L =
Decl->getAttr<HLSLVkLocationAttr>())
1295 Location = L->getLocation();
1299 llvm::ArrayType *AT = dyn_cast<llvm::ArrayType>(
Type);
1300 unsigned ElementCount = AT ? AT->getNumElements() : 1;
1301 SPIRVLastAssignedInputSemanticLocation += ElementCount;
1304 llvm::hlsl::SPIRVInterfaceDecoration::Location,
1305 Location, InterpMode);
1309 IRBuilder<> &B, llvm::Module &M, llvm::Value *Source,
const Twine &Name,
1310 llvm::hlsl::SPIRVInterfaceDecoration Decoration,
unsigned Operand,
1311 llvm::hlsl::InterpolationMode InterpMode,
bool IsSigned =
false) {
1314 llvm::Type *Ty = Source->getType();
1315 if (Decoration == llvm::hlsl::SPIRVInterfaceDecoration::BuiltIn &&
1316 Ty->isIntegerTy() && Ty->getIntegerBitWidth() < 32)
1317 Source = IsSigned ? B.CreateSExt(Source, B.getInt32Ty())
1318 : B.CreateZExt(Source, B.getInt32Ty());
1319 auto *GV =
new llvm::GlobalVariable(
1320 M, Source->getType(),
false,
1321 llvm::GlobalValue::ExternalLinkage,
1322 nullptr, Name,
nullptr,
1323 llvm::GlobalVariable::GeneralDynamicTLSModel,
1325 GV->setVisibility(llvm::GlobalValue::HiddenVisibility);
1327 B.CreateStore(Source, GV);
1330void CGHLSLRuntime::emitSPIRVUserSemanticStore(
1331 llvm::IRBuilder<> &B, llvm::Value *Source,
1332 const clang::DeclaratorDecl *
Decl, HLSLAppliedSemanticAttr *Semantic,
1333 std::optional<unsigned> Index, llvm::hlsl::InterpolationMode InterpMode,
1334 bool UseLocationFromIndex) {
1335 Twine BaseName = Twine(Semantic->getAttrName()->getName());
1336 Twine VariableName = BaseName.concat(Twine(Index.value_or(0)));
1339 if (UseLocationFromIndex) {
1340 Location = Index.value_or(0);
1342 Location = SPIRVLastAssignedOutputSemanticLocation;
1343 llvm::ArrayType *AT = dyn_cast<llvm::ArrayType>(Source->getType());
1346 SPIRVLastAssignedOutputSemanticLocation += AT ? AT->getNumElements() : 1;
1348 if (
auto *L =
Decl->getAttr<HLSLVkLocationAttr>())
1349 Location = L->getLocation();
1352 llvm::hlsl::SPIRVInterfaceDecoration::Location,
1353 Location, InterpMode);
1358struct SemanticShape {
1360 SmallVector<unsigned> Dimensions;
1363 bool IsMatrix =
false;
1364 bool IsRowMajor =
false;
1368 unsigned getMatrixElementIndex(
unsigned Row,
unsigned Col)
const {
1370 unsigned MatrixRow = Row % Dimensions.back();
1371 return IsRowMajor ? Col * Dimensions.back() + MatrixRow
1372 : MatrixRow * Cols + Col;
1375 unsigned getNumRows()
const {
1377 for (
unsigned Dimension : Dimensions)
1382 SmallVector<unsigned> getArrayIndicesForRow(
unsigned Row)
const {
1383 assert(Row < getNumRows() &&
"row exceeds semantic shape");
1385 SmallVector<unsigned> Indices(Dimensions.size());
1386 for (
auto [Index, Dimension] :
1387 llvm::zip_equal(llvm::reverse(Indices), llvm::reverse(Dimensions))) {
1388 Index = Row % Dimension;
1399 if (
const auto *FD = dyn_cast<clang::FunctionDecl>(
Decl))
1400 return FD->getDeclaredReturnType();
1401 return Decl->getType();
1407 SemanticShape Shape{{}, 1, Ty};
1410 Shape.Dimensions.push_back(CAT->getSize().getZExtValue());
1411 Shape.RowType = CAT->getElementType();
1415 Shape.Cols = VT->getNumElements();
1416 }
else if (
const auto *MT =
1418 Shape.IsMatrix =
true;
1420 Shape.Dimensions.push_back(Shape.IsRowMajor ? MT->getNumRows()
1421 : MT->getNumColumns());
1422 Shape.Cols = Shape.IsRowMajor ? MT->getNumColumns() : MT->getNumRows();
1432 Ty = VT->getElementType();
1436 return llvm::hlsl::getDXILElementType(IRTy, IsSigned);
1441 std::optional<unsigned> Index,
const SemanticShape &Shape) {
1442 StringRef Name = Semantic->getAttrName()->getName();
1446 uint32_t FirstSemanticIndex = Index.value_or(0);
1447 for (
uint32_t I = 0, E = Shape.getNumRows(); I < E; ++I)
1448 SemanticIndices.push_back(FirstSemanticIndex + I);
1450 llvm::dxbc::PSV::SemanticKind Kind = llvm::hlsl::getSemanticKind(Name);
1451 llvm::dxil::ElementType CompType =
1457 if (Kind == llvm::dxbc::PSV::SemanticKind::SampleIndex ||
1458 Kind == llvm::dxbc::PSV::SemanticKind::PrimitiveID ||
1459 Kind == llvm::dxbc::PSV::SemanticKind::StencilRef) {
1460 if (CompType == llvm::dxil::ElementType::I16)
1461 CompType = llvm::dxil::ElementType::U16;
1462 else if (CompType == llvm::dxil::ElementType::I32)
1463 CompType = llvm::dxil::ElementType::U32;
1469 return llvm::hlsl::SemanticSignatureElement(SigId, Name, CompType, Kind,
1471 static_cast<uint8_t>(Shape.Cols));
1474llvm::Value *CGHLSLRuntime::emitDXILUserSemanticLoad(
1475 llvm::IRBuilder<> &B, llvm::Type *
Type,
const clang::DeclaratorDecl *
Decl,
1476 HLSLAppliedSemanticAttr *Semantic, std::optional<unsigned> Index,
1477 SemanticSignatures &Signature) {
1478 StringRef Name = Semantic->getAttrName()->getName();
1479 SemanticShape Shape =
1483 Signature.push_back(
1486 llvm::Type *RowTy =
CGM.getTypes().ConvertTypeForMem(Shape.RowType);
1488 llvm::Function *IntrFn = llvm::Intrinsic::getOrInsertDeclaration(
1489 B.getModule(), llvm::Intrinsic::dx_load_input, {RowTy});
1491 SmallVector<OperandBundleDef, 1> OB;
1493 llvm::Value *bundleArgs[] = {Token};
1494 OB.emplace_back(
"convergencectrl", bundleArgs);
1497 bool IsMatrixValue = Shape.IsMatrix &&
Type->isVectorTy();
1498 llvm::Type *LeafTy = Shape.IsMatrix && !IsMatrixValue
1500 :
CGM.getTypes().ConvertType(Shape.RowType);
1501 llvm::Value *
Result = llvm::PoisonValue::get(
Type);
1503 const unsigned NumRows = Shape.getNumRows();
1505 for (
unsigned Row = 0; Row < NumRows; ++Row) {
1506 std::array<Value *, 4> Args{
1510 llvm::PoisonValue::get(B.getInt32Ty())};
1511 llvm::Value *
Value =
1512 B.CreateCall(IntrFn, Args, OB, Twine(Name).concat(Twine(Row)));
1515 if (
Value->getType() != LeafTy) {
1517 "unexpected semantic load type mismatch");
1518 Value = B.CreateICmpNE(
1519 Value, llvm::Constant::getNullValue(
Value->getType()),
"loadedv");
1522 if (IsMatrixValue) {
1523 for (
unsigned Col = 0; Col < Shape.Cols; ++Col)
1525 B.CreateInsertElement(
Result, B.CreateExtractElement(
Value, Col),
1526 Shape.getMatrixElementIndex(Row, Col));
1528 SmallVector<unsigned> Indices = Shape.getArrayIndicesForRow(Row);
1536void CGHLSLRuntime::emitDXILUserSemanticStore(llvm::IRBuilder<> &B,
1537 llvm::Value *Source,
1538 const clang::DeclaratorDecl *
Decl,
1539 HLSLAppliedSemanticAttr *Semantic,
1540 std::optional<unsigned> Index,
1541 SemanticSignatures &Signature,
1542 bool EnforceOneElementPerRow) {
1543 SemanticShape Shape =
1545 assert(!(EnforceOneElementPerRow && Shape.IsMatrix) &&
1546 "matrices cannot be split into one element per row");
1551 SemanticShape RowShape{{}, Shape.Cols, Shape.RowType};
1552 uint32_t FirstSigId = Signature.size();
1553 if (!EnforceOneElementPerRow)
1555 Semantic, Index, Shape));
1557 llvm::Type *RowTy =
CGM.getTypes().ConvertTypeForMem(Shape.RowType);
1559 llvm::Function *IntrFn = llvm::Intrinsic::getOrInsertDeclaration(
1560 B.getModule(), llvm::Intrinsic::dx_store_output, {RowTy});
1562 SmallVector<OperandBundleDef, 1> OB;
1564 llvm::Value *bundleArgs[] = {Token};
1565 OB.emplace_back(
"convergencectrl", bundleArgs);
1568 bool IsMatrixValue = Shape.IsMatrix && Source->getType()->isVectorTy();
1569 const unsigned NumRows = Shape.getNumRows();
1570 for (
unsigned Row = 0; Row < NumRows; ++Row) {
1572 if (IsMatrixValue) {
1573 SmallVector<int, 4> Mask;
1574 for (
unsigned Col = 0; Col < Shape.Cols; ++Col)
1575 Mask.push_back(Shape.getMatrixElementIndex(Row, Col));
1576 Val = B.CreateShuffleVector(Source, Mask);
1578 SmallVector<unsigned> Indices = Shape.getArrayIndicesForRow(Row);
1579 Val = Indices.empty() ? Source : B.CreateExtractValue(Source, Indices);
1584 if (Val->getType() != RowTy) {
1586 "unexpected semantic store type mismatch");
1587 Val = B.CreateZExt(Val, RowTy,
"storedv");
1592 if (EnforceOneElementPerRow) {
1593 SigId = Signature.size();
1596 CGM, SigId, Semantic, Index.value_or(0) + Row, RowShape));
1599 std::array<Value *, 4> Args{B.getInt32(SigId),
1602 B.CreateCall(IntrFn, Args, OB);
1606llvm::Value *CGHLSLRuntime::emitUserSemanticLoad(
1607 IRBuilder<> &B, llvm::Type *
Type,
const clang::DeclaratorDecl *
Decl,
1608 HLSLAppliedSemanticAttr *Semantic, std::optional<unsigned> Index,
1609 SemanticSignatures &Signature, llvm::hlsl::InterpolationMode InterpMode) {
1610 if (
CGM.getTarget().getTriple().isSPIRV())
1611 return emitSPIRVUserSemanticLoad(B,
Type,
Decl, Semantic, Index,
1614 if (
CGM.getTarget().getTriple().isDXIL())
1615 return emitDXILUserSemanticLoad(B,
Type,
Decl, Semantic, Index, Signature);
1617 llvm_unreachable(
"Unsupported target for user-semantic load.");
1620void CGHLSLRuntime::emitUserSemanticStore(
1621 IRBuilder<> &B, llvm::Value *Source,
const clang::DeclaratorDecl *
Decl,
1622 HLSLAppliedSemanticAttr *Semantic, std::optional<unsigned> Index,
1623 SemanticSignatures &Signature, llvm::hlsl::InterpolationMode InterpMode) {
1624 if (
CGM.getTarget().getTriple().isSPIRV())
1625 return emitSPIRVUserSemanticStore(B, Source,
Decl, Semantic, Index,
1628 if (
CGM.getTarget().getTriple().isDXIL())
1629 return emitDXILUserSemanticStore(B, Source,
Decl, Semantic, Index,
1632 llvm_unreachable(
"Unsupported target for user-semantic load.");
1637 HLSLAppliedSemanticAttr *Semantic,
1639 llvm::Triple::EnvironmentType Stage, std::optional<unsigned> Index,
1642 case llvm::dxbc::PSV::SemanticKind::Barycentrics:
1643 assert(Stage == llvm::Triple::Pixel &&
1644 "SV_Barycentrics is in an unavailable stage and should have been "
1645 "diagnosed by Sema");
1646 if (
CGM.getTarget().getTriple().isSPIRV()) {
1647 using llvm::hlsl::InterpolationMode;
1650 bool NoPerspective =
false;
1651 switch (InterpMode) {
1652 case InterpolationMode::LinearNoperspective:
1653 NoPerspective =
true;
1654 InterpMode = InterpolationMode::Linear;
1656 case InterpolationMode::LinearNoperspectiveCentroid:
1657 NoPerspective =
true;
1658 InterpMode = InterpolationMode::LinearCentroid;
1660 case InterpolationMode::LinearNoperspectiveSample:
1661 NoPerspective =
true;
1662 InterpMode = InterpolationMode::LinearSample;
1668 llvm::Type *
BuiltinType = llvm::FixedVectorType::get(
CGM.FloatTy, 3);
1671 llvm::hlsl::SPIRVInterfaceDecoration::BuiltIn,
1672 NoPerspective ? 5287
1675 if (
Type->getScalarType()->isHalfTy())
1676 return B.CreateFPTrunc(Barycentrics,
Type);
1677 return Barycentrics;
1679 if (
CGM.getTarget().getTriple().isDXIL())
1680 return emitDXILUserSemanticLoad(B,
Type,
Decl, Semantic, Index,
1683 case llvm::dxbc::PSV::SemanticKind::GroupIndex: {
1684 assert(llvm::is_contained({llvm::Triple::Compute, llvm::Triple::Mesh,
1685 llvm::Triple::Amplification},
1687 "SV_GroupIndex is in an unavailable stage and should have been "
1688 "diagnosed by Sema");
1689 assert(Stage != llvm::Triple::Mesh &&
1690 Stage != llvm::Triple::Amplification &&
1691 "FIXME: SV_GroupIndex is not yet implemented for this shader "
1693 llvm::Function *GroupIndex =
1694 CGM.getIntrinsic(getFlattenedThreadIdInGroupIntrinsic());
1695 return B.CreateCall(FunctionCallee(GroupIndex));
1697 case llvm::dxbc::PSV::SemanticKind::DispatchThreadID: {
1698 assert(llvm::is_contained({llvm::Triple::Compute, llvm::Triple::Mesh,
1699 llvm::Triple::Amplification},
1701 "SV_DispatchThreadID is in an unavailable stage and should have "
1702 "been diagnosed by Sema");
1703 assert(Stage != llvm::Triple::Mesh &&
1704 Stage != llvm::Triple::Amplification &&
1705 "FIXME: SV_DispatchThreadID is not yet implemented for this "
1707 llvm::Intrinsic::ID IntrinID = getThreadIdIntrinsic();
1708 llvm::Function *ThreadIDIntrinsic =
1709 llvm::Intrinsic::isOverloaded(IntrinID)
1710 ?
CGM.getIntrinsic(IntrinID, {
CGM.Int32Ty})
1711 :
CGM.getIntrinsic(IntrinID);
1714 case llvm::dxbc::PSV::SemanticKind::GroupThreadID: {
1715 assert(llvm::is_contained({llvm::Triple::Compute, llvm::Triple::Mesh,
1716 llvm::Triple::Amplification},
1718 "SV_GroupThreadID is in an unavailable stage and should have been "
1719 "diagnosed by Sema");
1720 assert(Stage != llvm::Triple::Mesh &&
1721 Stage != llvm::Triple::Amplification &&
1722 "FIXME: SV_GroupThreadID is not yet implemented for this shader "
1724 llvm::Intrinsic::ID IntrinID = getGroupThreadIdIntrinsic();
1725 llvm::Function *GroupThreadIDIntrinsic =
1726 llvm::Intrinsic::isOverloaded(IntrinID)
1727 ?
CGM.getIntrinsic(IntrinID, {
CGM.Int32Ty})
1728 :
CGM.getIntrinsic(IntrinID);
1731 case llvm::dxbc::PSV::SemanticKind::GroupID: {
1732 assert(llvm::is_contained({llvm::Triple::Compute, llvm::Triple::Mesh,
1733 llvm::Triple::Amplification},
1735 "SV_GroupID is in an unavailable stage and should have been "
1736 "diagnosed by Sema");
1737 assert(Stage != llvm::Triple::Mesh &&
1738 Stage != llvm::Triple::Amplification &&
1739 "FIXME: SV_GroupID is not yet implemented for this shader stage");
1740 llvm::Intrinsic::ID IntrinID = getGroupIdIntrinsic();
1741 llvm::Function *GroupIDIntrinsic =
1742 llvm::Intrinsic::isOverloaded(IntrinID)
1743 ?
CGM.getIntrinsic(IntrinID, {
CGM.Int32Ty})
1744 :
CGM.getIntrinsic(IntrinID);
1747 case llvm::dxbc::PSV::SemanticKind::Position:
1748 assert(llvm::is_contained({llvm::Triple::Hull, llvm::Triple::Domain,
1749 llvm::Triple::Geometry, llvm::Triple::Pixel},
1751 "SV_Position is in an unavailable stage and should have been "
1752 "diagnosed by Sema");
1753 assert(Stage != llvm::Triple::Hull && Stage != llvm::Triple::Domain &&
1754 Stage != llvm::Triple::Geometry &&
1755 "FIXME: loading SV_Position is not yet implemented for this "
1757 if (
CGM.getTarget().getTriple().isSPIRV())
1759 Semantic->getAttrName()->getName(),
1760 llvm::hlsl::SPIRVInterfaceDecoration::BuiltIn,
1762 if (
CGM.getTarget().getTriple().isDXIL())
1763 return emitDXILUserSemanticLoad(B,
Type,
Decl, Semantic, Index,
1766 case llvm::dxbc::PSV::SemanticKind::VertexID:
1767 assert(Stage == llvm::Triple::Vertex &&
1768 "SV_VertexID is in an unavailable stage and should have been "
1769 "diagnosed by Sema");
1770 if (
CGM.getTarget().getTriple().isSPIRV())
1772 Semantic->getAttrName()->getName(),
1773 llvm::hlsl::SPIRVInterfaceDecoration::BuiltIn,
1775 if (
CGM.getTarget().getTriple().isDXIL())
1776 return emitDXILUserSemanticLoad(B,
Type,
Decl, Semantic, Index,
1779 case llvm::dxbc::PSV::SemanticKind::InstanceID:
1780 assert(Stage == llvm::Triple::Vertex &&
1781 "SV_InstanceID is in an unavailable stage and should have been "
1782 "diagnosed by Sema");
1783 if (
CGM.getTarget().getTriple().isSPIRV()) {
1786 if (
CGM.getLangOpts().HLSLSpvSupportNonzeroBaseInstance)
1788 B,
CGM.getModule(),
Type, Semantic->getAttrName()->getName(),
1789 43, 4425, InterpMode);
1791 Semantic->getAttrName()->getName(),
1792 llvm::hlsl::SPIRVInterfaceDecoration::BuiltIn,
1795 if (
CGM.getTarget().getTriple().isDXIL())
1796 return emitDXILUserSemanticLoad(B,
Type,
Decl, Semantic, Index,
1799 case llvm::dxbc::PSV::SemanticKind::IsFrontFace:
1800 assert(Stage == llvm::Triple::Pixel &&
1801 "SV_IsFrontFace is in an unavailable stage and should have been "
1802 "diagnosed by Sema");
1803 if (
CGM.getTarget().getTriple().isSPIRV()) {
1806 llvm::Type *BoolTy = B.getInt1Ty();
1809 B,
CGM.getModule(), BoolTy, Semantic->getAttrName()->getName(),
1810 llvm::hlsl::SPIRVInterfaceDecoration::BuiltIn,
1811 17, llvm::hlsl::InterpolationMode::Constant);
1813 return Type == BoolTy ? FF : B.CreateZExt(FF,
Type);
1815 if (
CGM.getTarget().getTriple().isDXIL())
1816 return emitDXILUserSemanticLoad(B,
Type,
Decl, Semantic, Index,
1819 case llvm::dxbc::PSV::SemanticKind::ShadingRate:
1820 assert(llvm::is_contained({llvm::Triple::Hull, llvm::Triple::Domain,
1821 llvm::Triple::Geometry, llvm::Triple::Pixel},
1823 "SV_ShadingRate is in an unavailable stage and should have been "
1824 "diagnosed by Sema");
1825 assert(Stage != llvm::Triple::Hull && Stage != llvm::Triple::Domain &&
1826 Stage != llvm::Triple::Geometry &&
1827 "FIXME: loading SV_ShadingRate is not yet implemented for this "
1829 if (
CGM.getTarget().getTriple().isSPIRV())
1831 Semantic->getAttrName()->getName(),
1832 llvm::hlsl::SPIRVInterfaceDecoration::BuiltIn,
1834 if (
CGM.getTarget().getTriple().isDXIL())
1835 return emitDXILUserSemanticLoad(B,
Type,
Decl, Semantic, Index,
1838 case llvm::dxbc::PSV::SemanticKind::StartVertexLocation:
1839 assert(Stage == llvm::Triple::Vertex &&
1840 "SV_StartVertexLocation is in an unavailable stage and should have "
1841 "been diagnosed by Sema");
1842 if (
CGM.getTarget().getTriple().isSPIRV())
1844 Semantic->getAttrName()->getName(),
1845 llvm::hlsl::SPIRVInterfaceDecoration::BuiltIn,
1847 if (
CGM.getTarget().getTriple().isDXIL())
1848 return B.CreateCall(
1849 CGM.getIntrinsic(llvm::Intrinsic::dx_start_vertex_location));
1851 case llvm::dxbc::PSV::SemanticKind::PrimitiveID:
1852 assert(Stage == llvm::Triple::Pixel &&
1853 "SV_PrimitiveID is in an unavailable stage and should have been "
1854 "diagnosed by Sema");
1855 if (
CGM.getTarget().getTriple().isSPIRV())
1857 Semantic->getAttrName()->getName(),
1858 llvm::hlsl::SPIRVInterfaceDecoration::BuiltIn,
1862 if (
CGM.getTarget().getTriple().isDXIL())
1863 return emitDXILUserSemanticLoad(B,
Type,
Decl, Semantic, Index,
1866 case llvm::dxbc::PSV::SemanticKind::SampleIndex:
1867 assert(Stage == llvm::Triple::Pixel &&
1868 "SV_SampleIndex is in an unavailable stage and should have been "
1869 "diagnosed by Sema");
1870 if (
CGM.getTarget().getTriple().isSPIRV())
1872 Semantic->getAttrName()->getName(),
1873 llvm::hlsl::SPIRVInterfaceDecoration::BuiltIn,
1875 if (
CGM.getTarget().getTriple().isDXIL()) {
1876 assert(
Type->isIntegerTy() &&
Type->getIntegerBitWidth() <= 32 &&
1877 "SV_SampleIndex must be a 16 or 32 bit scalar integer, as "
1878 "diagnosed by Sema");
1881 SemanticShape Shape =
1884 CGM, Signature.size(), Semantic, Index, Shape));
1885 llvm::Value *SampleIndex =
1886 B.CreateCall(
CGM.getIntrinsic(llvm::Intrinsic::dx_sample_index));
1889 if (
Type->getIntegerBitWidth() < 32)
1890 SampleIndex = B.CreateTrunc(SampleIndex,
Type);
1894 case llvm::dxbc::PSV::SemanticKind::ViewID:
1895 assert(llvm::is_contained({llvm::Triple::Vertex, llvm::Triple::Hull,
1896 llvm::Triple::Domain, llvm::Triple::Geometry,
1897 llvm::Triple::Pixel, llvm::Triple::Mesh},
1899 "SV_ViewID is in an unavailable stage and should have been "
1900 "diagnosed by Sema");
1901 if (
CGM.getTarget().getTriple().isSPIRV())
1903 Semantic->getAttrName()->getName(),
1904 llvm::hlsl::SPIRVInterfaceDecoration::BuiltIn,
1906 if (
CGM.getTarget().getTriple().isDXIL())
1907 return B.CreateCall(
CGM.getIntrinsic(llvm::Intrinsic::dx_view_id));
1909 case llvm::dxbc::PSV::SemanticKind::StartInstanceLocation:
1910 assert(Stage == llvm::Triple::Vertex &&
1911 "SV_StartInstanceLocation is in an unavailable stage and should "
1912 "have been diagnosed by Sema");
1913 if (
CGM.getTarget().getTriple().isSPIRV())
1915 Semantic->getAttrName()->getName(),
1916 llvm::hlsl::SPIRVInterfaceDecoration::BuiltIn,
1918 if (
CGM.getTarget().getTriple().isDXIL())
1919 return B.CreateCall(
1920 CGM.getIntrinsic(llvm::Intrinsic::dx_start_instance_location));
1927 "Load hasn't been implemented yet for this system semantic. FIXME");
1934 unsigned ID = llvm::StringSwitch<unsigned>(BuiltIn)
1935 .Case(
"PointSize", 1)
1937 assert(ID !=
static_cast<unsigned>(-1) &&
1938 "Sema should only allow builtin names implemented here");
1944 HLSLAppliedSemanticAttr *Semantic,
1946 llvm::Triple::EnvironmentType Stage, std::optional<unsigned> Index,
1948 const bool IsSignedInt =
1951 case llvm::dxbc::PSV::SemanticKind::Position:
1952 assert(llvm::is_contained({llvm::Triple::Vertex, llvm::Triple::Hull,
1953 llvm::Triple::Domain, llvm::Triple::Geometry,
1954 llvm::Triple::Mesh},
1956 "SV_Position is in an unavailable stage and should have been "
1957 "diagnosed by Sema");
1958 assert(Stage != llvm::Triple::Hull && Stage != llvm::Triple::Domain &&
1959 Stage != llvm::Triple::Geometry && Stage != llvm::Triple::Mesh &&
1960 "FIXME: storing SV_Position is not yet implemented for this "
1962 if (
CGM.getTarget().getTriple().isDXIL()) {
1963 emitDXILUserSemanticStore(B, Source,
Decl, Semantic, Index, Signature);
1966 if (
CGM.getTarget().getTriple().isSPIRV()) {
1968 Semantic->getAttrName()->getName(),
1969 llvm::hlsl::SPIRVInterfaceDecoration::BuiltIn,
1974 case llvm::dxbc::PSV::SemanticKind::StencilRef:
1975 assert(Stage == llvm::Triple::Pixel &&
1976 "SV_StencilRef is in an unavailable stage and should have been "
1977 "diagnosed by Sema");
1980 if (
CGM.getTarget().getTriple().isDXIL()) {
1981 emitDXILUserSemanticStore(B, Source,
Decl, Semantic, Index, Signature);
1984 if (
CGM.getTarget().getTriple().isSPIRV()) {
1986 B,
CGM.getModule(), Source, Semantic->getAttrName()->getName(),
1987 llvm::hlsl::SPIRVInterfaceDecoration::BuiltIn,
1988 5014, InterpMode, IsSignedInt);
1992 case llvm::dxbc::PSV::SemanticKind::Target:
1993 assert(Stage == llvm::Triple::Pixel &&
1994 "SV_Target is in an unavailable stage and should have been "
1995 "diagnosed by Sema");
1996 if (
CGM.getTarget().getTriple().isDXIL()) {
1997 emitDXILUserSemanticStore(B, Source,
Decl, Semantic, Index, Signature,
2001 if (
CGM.getTarget().getTriple().isSPIRV()) {
2002 emitSPIRVUserSemanticStore(B, Source,
Decl, Semantic, Index, InterpMode,
2007 case llvm::dxbc::PSV::SemanticKind::ShadingRate:
2008 assert(llvm::is_contained({llvm::Triple::Vertex, llvm::Triple::Hull,
2009 llvm::Triple::Domain, llvm::Triple::Geometry,
2010 llvm::Triple::Mesh},
2012 "SV_ShadingRate is in an unavailable stage and should have been "
2013 "diagnosed by Sema");
2014 assert(Stage != llvm::Triple::Hull && Stage != llvm::Triple::Domain &&
2015 Stage != llvm::Triple::Geometry && Stage != llvm::Triple::Mesh &&
2016 "FIXME: storing SV_ShadingRate is not yet implemented for this "
2018 if (
CGM.getTarget().getTriple().isDXIL()) {
2019 emitDXILUserSemanticStore(B, Source,
Decl, Semantic, Index, Signature);
2022 if (
CGM.getTarget().getTriple().isSPIRV()) {
2026 Semantic->getAttrName()->getName(),
2027 llvm::hlsl::SPIRVInterfaceDecoration::BuiltIn,
2029 llvm::hlsl::InterpolationMode::Undefined);
2038 "Store hasn't been implemented yet for this system semantic. FIXME");
2046 size_t FirstElement) {
2047 for (
auto &Element : llvm::drop_begin(Signature, FirstElement))
2048 Element.SemanticKind = llvm::dxbc::PSV::SemanticKind::Arbitrary;
2059 if (
const auto *BuiltInAttr =
Decl->getAttr<HLSLVkBuiltInAttr>())
2061 B,
CGM.getModule(),
Type, Semantic->getAttrName()->getName(),
2062 llvm::hlsl::SPIRVInterfaceDecoration::BuiltIn,
2065 std::optional<unsigned> Index = Semantic->getSemanticIndex();
2067 llvm::hlsl::getSemanticKind(Semantic->getAttrName()->getName());
2068 const auto *ShaderAttr = FD->
getAttr<HLSLShaderAttr>();
2069 assert(ShaderAttr &&
"Entry point has no shader attribute");
2070 llvm::hlsl::SemanticInterpretation Interpretation =
2071 llvm::hlsl::getInterpretationKind(
SemanticKind, ShaderAttr->getType(),
2072 llvm::hlsl::IOType::In);
2073 assert(Interpretation != llvm::hlsl::SemanticInterpretation::Invalid &&
2074 "invalid semantic should have been diagnosed by Sema");
2075 if (
CGM.getTarget().getTriple().isSPIRV())
2077 InterpMode,
Type, ShaderAttr->getType(), llvm::hlsl::IOType::In);
2078 if (Interpretation == llvm::hlsl::SemanticInterpretation::Arbitrary) {
2079 size_t FirstElement = Signature.size();
2080 llvm::Value *
Value = emitUserSemanticLoad(B,
Type,
Decl, Semantic, Index,
2081 Signature, InterpMode);
2086 ShaderAttr->getType(), Index, Signature,
2091 IRBuilder<> &B,
const FunctionDecl *FD, llvm::Value *Source,
2095 if (
const auto *BuiltInAttr =
Decl->getAttr<HLSLVkBuiltInAttr>()) {
2097 B,
CGM.getModule(), Source, Semantic->getAttrName()->getName(),
2098 llvm::hlsl::SPIRVInterfaceDecoration::BuiltIn,
2103 std::optional<unsigned> Index = Semantic->getSemanticIndex();
2105 llvm::hlsl::getSemanticKind(Semantic->getAttrName()->getName());
2106 const auto *ShaderAttr = FD->
getAttr<HLSLShaderAttr>();
2107 assert(ShaderAttr &&
"Entry point has no shader attribute");
2109 llvm::hlsl::SemanticInterpretation Interpretation =
2110 llvm::hlsl::getInterpretationKind(
SemanticKind, ShaderAttr->getType(),
2111 llvm::hlsl::IOType::Out);
2112 assert(Interpretation != llvm::hlsl::SemanticInterpretation::Invalid &&
2113 "invalid semantic should have been diagnosed by Sema");
2114 if (
CGM.getTarget().getTriple().isSPIRV())
2116 ShaderAttr->getType(),
2117 llvm::hlsl::IOType::Out);
2119 if (Interpretation == llvm::hlsl::SemanticInterpretation::Arbitrary) {
2120 size_t FirstElement = Signature.size();
2121 emitUserSemanticStore(B, Source,
Decl, Semantic, Index, Signature,
2127 ShaderAttr->getType(), Index, Signature, InterpMode);
2130std::pair<llvm::Value *, specific_attr_iterator<HLSLAppliedSemanticAttr>>
2137 llvm::hlsl::InterpolationModifier Modifiers) {
2145 for (
unsigned I = 0; I < ST->getNumElements(); ++I) {
2146 auto [ChildValue, NextAttr] =
2148 AttrEnd, Signature, Modifiers);
2149 AttrBegin = NextAttr;
2155 return std::make_pair(
Aggregate, AttrBegin);
2160 IRBuilder<> &B,
const FunctionDecl *FD, llvm::Value *Source,
2165 llvm::hlsl::InterpolationModifier Modifiers) {
2173 RD =
Decl->getType()->getAsRecordDecl();
2179 for (
unsigned I = 0; I < ST->getNumElements(); ++I, ++
FieldDecl) {
2180 llvm::Value *Extract = B.CreateExtractValue(Source, I);
2182 AttrEnd, Signature, Modifiers);
2188std::pair<llvm::Value *, specific_attr_iterator<HLSLAppliedSemanticAttr>>
2195 llvm::hlsl::InterpolationModifier Modifiers) {
2196 assert(AttrBegin != AttrEnd);
2199 if (
const auto *A =
Decl->getAttr<HLSLInterpolationModifierAttr>())
2201 static_cast<llvm::hlsl::InterpolationModifier
>(A->getModifiers());
2202 if (
Type->isStructTy())
2204 Signature, Modifiers);
2206 HLSLAppliedSemanticAttr *
Attr = *AttrBegin;
2208 size_t PreviousSize = Signature.size();
2209 auto InterpMode = llvm::hlsl::getInterpolationMode(Modifiers);
2210 llvm::Value *
Value =
2214 if (Signature.size() != PreviousSize) {
2215 auto &Element = Signature.back();
2216 Element.InterpMode = llvm::hlsl::normalizeInterpolationMode(
2217 InterpMode, Element.CompType, Element.SemanticKind,
2218 FD->
getAttr<HLSLShaderAttr>()->getType(), llvm::hlsl::IOType::In);
2220 return std::make_pair(
Value, AttrBegin);
2225 IRBuilder<> &B,
const FunctionDecl *FD, llvm::Value *Source,
2230 llvm::hlsl::InterpolationModifier Modifiers) {
2231 assert(AttrBegin != AttrEnd);
2233 if (
const auto *A =
Decl->getAttr<HLSLInterpolationModifierAttr>())
2235 static_cast<llvm::hlsl::InterpolationModifier
>(A->getModifiers());
2236 if (Source->getType()->isStructTy())
2238 Signature, Modifiers);
2240 HLSLAppliedSemanticAttr *
Attr = *AttrBegin;
2242 size_t PreviousSize = Signature.size();
2243 auto InterpMode = llvm::hlsl::getInterpolationMode(Modifiers);
2246 for (
auto &Element : llvm::drop_begin(Signature, PreviousSize))
2247 Element.InterpMode = llvm::hlsl::normalizeInterpolationMode(
2248 InterpMode, Element.CompType, Element.SemanticKind,
2249 FD->
getAttr<HLSLShaderAttr>()->getType(), llvm::hlsl::IOType::Out);
2254 llvm::Function *Fn) {
2258 llvm::Module &M =
CGM.getModule();
2259 llvm::LLVMContext &Ctx = M.getContext();
2260 auto *EntryTy = llvm::FunctionType::get(llvm::Type::getVoidTy(Ctx),
false);
2262 Function::Create(EntryTy, Function::ExternalLinkage, FD->
getName(), &M);
2266 AttributeList NewAttrs = AttributeList::get(Ctx, AttributeList::FunctionIndex,
2267 Fn->getAttributes().getFnAttrs());
2268 EntryFn->setAttributes(NewAttrs);
2272 Fn->setLinkage(GlobalValue::InternalLinkage);
2274 BasicBlock *BB = BasicBlock::Create(Ctx,
"entry", EntryFn);
2279 if (
CGM.shouldEmitConvergenceTokens()) {
2280 assert(EntryFn->isConvergent());
2282 B.CreateIntrinsic(llvm::Intrinsic::experimental_convergence_entry, {});
2283 llvm::Value *bundleArgs[] = {I};
2284 OB.emplace_back(
"convergencectrl", bundleArgs);
2289 unsigned SRetOffset = 0;
2290 for (
const auto &Param : Fn->args()) {
2291 if (Param.hasStructRetAttr()) {
2293 llvm::Type *VarType = Param.getParamStructRetType();
2295 CGM.getLangOpts().EmitLogicalPointer
2298 OutputSemantic.push_back(std::make_pair(Var, VarType));
2299 Args.push_back(Var);
2304 llvm::Value *SemanticValue =
nullptr;
2306 if ([[maybe_unused]] HLSLParamModifierAttr *MA =
2307 PD->
getAttr<HLSLParamModifierAttr>()) {
2308 llvm_unreachable(
"Not handled yet");
2310 llvm::Type *ParamType =
nullptr;
2311 if (Param.hasByValAttr())
2312 ParamType = Param.getParamByValType();
2314 ParamType =
CGM.getTypes().ConvertType(PD->
getType());
2316 ParamType = Param.getType();
2322 SemanticValue =
Result.first;
2327 CGM.getLangOpts().EmitLogicalPointer
2330 B.CreateStore(SemanticValue, Var);
2331 SemanticValue = Var;
2335 assert(SemanticValue);
2336 Args.push_back(SemanticValue);
2339 CallInst *CI = B.CreateCall(FunctionCallee(Fn), Args, OB);
2340 CI->setCallingConv(Fn->getCallingConv());
2342 if (Fn->getReturnType() !=
CGM.VoidTy)
2344 OutputSemantic.push_back(std::make_pair(CI,
nullptr));
2346 for (
auto &SourcePair : OutputSemantic) {
2347 llvm::Value *Source = SourcePair.first;
2348 llvm::Type *ElementType = SourcePair.second;
2349 AllocaInst *AI = dyn_cast<AllocaInst>(Source);
2350 llvm::Value *SourceValue = AI ? B.CreateLoad(ElementType, Source) : Source;
2362 if (
const auto *RSAttr = dyn_cast<RootSignatureAttr>(
Attr)) {
2363 auto *RSDecl = RSAttr->getSignatureDecl();
2364 addRootSignatureMD(RSDecl->getVersion(), RSDecl->getRootElements(),
2369 if (
CGM.getTarget().getTriple().isDXIL()) {
2374 auto Mode =
CGM.getCodeGenOpts().getHLSLSemanticSignaturePacking();
2375 for (
auto IOTy : {llvm::hlsl::IOType::In, llvm::hlsl::IOType::Out}) {
2376 bool IsOutput = IOTy == llvm::hlsl::IOType::Out;
2377 auto &Signature = IsOutput ? OutputSignature : InputSignature;
2378 auto Packed = packSemanticSignature(Signature, Stage, IOTy, Mode,
2379 CGM.getLangOpts().NativeHalfType);
2382 diag::err_hlsl_signature_packing)
2383 << IsOutput << llvm::toString(
Packed.takeError());
2387 if (Mode != PackingMode::Default &&
2388 CGM.getTarget().getTriple().getEnvironment() !=
2389 llvm::Triple::Library &&
2390 ((Stage == llvm::Triple::Vertex && !IsOutput) ||
2391 (Stage == llvm::Triple::Pixel && IsOutput)))
2393 diag::warn_hlsl_signature_packing_ignored)
2394 << (Mode == PackingMode::Optimized ?
"optimized" :
"prefix-stable")
2399 addSemanticSignatureMD(InputSignature, OutputSignature, EntryFn, M);
2405 M.getNamedGlobal(CtorOrDtor ?
"llvm.global_ctors" :
"llvm.global_dtors");
2408 const auto *CA = dyn_cast<ConstantArray>(GV->getInitializer());
2415 for (
const auto &Ctor : CA->operands()) {
2421 "HLSL doesn't support setting priority for global ctors.");
2423 "HLSL doesn't support COMDat for global ctors.");
2429 llvm::Module &M =
CGM.getModule();
2438 for (
auto &F : M.functions()) {
2439 if (!F.hasFnAttribute(
"hlsl.shader"))
2442 Instruction *IP = &*F.getEntryBlock().begin();
2445 llvm::Value *bundleArgs[] = {
Token};
2446 OB.emplace_back(
"convergencectrl", bundleArgs);
2447 IP =
Token->getNextNode();
2450 for (
auto *Fn : CtorFns) {
2451 auto CI = B.CreateCall(FunctionCallee(Fn), {}, OB);
2452 CI->setCallingConv(Fn->getCallingConv());
2456 B.SetInsertPoint(F.back().getTerminator());
2457 for (
auto *Fn : DtorFns) {
2458 auto CI = B.CreateCall(FunctionCallee(Fn), {}, OB);
2459 CI->setCallingConv(Fn->getCallingConv());
2465 Triple
T(M.getTargetTriple());
2466 if (
T.getEnvironment() != Triple::EnvironmentType::Library) {
2467 if (
auto *GV = M.getNamedGlobal(
"llvm.global_ctors"))
2468 GV->eraseFromParent();
2469 if (
auto *GV = M.getNamedGlobal(
"llvm.global_dtors"))
2470 GV->eraseFromParent();
2475 Intrinsic::ID IntrID,
2479 llvm::Function *InitResFunc =
2480 llvm::Function::Create(llvm::FunctionType::get(CGM.
VoidTy,
false),
2481 llvm::GlobalValue::InternalLinkage,
2482 "_init_buffer_" + GV->getName(), CGM.
getModule());
2483 InitResFunc->addFnAttr(llvm::Attribute::AlwaysInline);
2485 llvm::BasicBlock *EntryBB =
2486 llvm::BasicBlock::Create(Ctx,
"entry", InitResFunc);
2488 const DataLayout &DL = CGM.
getModule().getDataLayout();
2489 Builder.SetInsertPoint(EntryBB);
2492 llvm::Type *HandleTy = GV->getValueType();
2493 assert(HandleTy->isTargetExtTy() &&
"unexpected type of the buffer global");
2495 llvm::Value *CreateHandle = Builder.CreateIntrinsic(
2496 HandleTy, IntrID, Args,
nullptr,
2497 Twine(GV->getName()).concat(
"_h"));
2499 Builder.CreateAlignedStore(CreateHandle, GV, GV->getPointerAlignment(DL));
2500 Builder.CreateRetVoid();
2505void CGHLSLRuntime::initializeBufferFromBinding(
const HLSLBufferDecl *BufDecl,
2506 llvm::GlobalVariable *GV) {
2507 ResourceBindingAttrs Binding(BufDecl);
2509 "cbuffer/tbuffer should always have resource binding attribute");
2511 auto *Index = llvm::ConstantInt::get(
CGM.IntTy, 0);
2512 auto *RangeSize = llvm::ConstantInt::get(
CGM.IntTy, 1);
2513 auto *Space = llvm::ConstantInt::get(
CGM.IntTy, Binding.
getSpace());
2518 llvm::Intrinsic::ID IntrinsicID =
2519 CGM.getHLSLRuntime().getCreateHandleFromBindingIntrinsic();
2520 auto *RegSlot = llvm::ConstantInt::get(
CGM.IntTy, Binding.
getSlot());
2521 SmallVector<Value *> Args{Space, RegSlot, RangeSize, Index, Name};
2525 llvm::Intrinsic::ID IntrinsicID =
2526 CGM.getHLSLRuntime().getCreateHandleFromImplicitBindingIntrinsic();
2529 SmallVector<Value *> Args{OrderID, Space, RangeSize, Index, Name};
2535 llvm::GlobalVariable *GV) {
2536 if (
auto Attr = VD->
getAttr<HLSLVkExtBuiltinInputAttr>())
2538 GV, llvm::hlsl::SPIRVInterfaceDecoration::BuiltIn,
Attr->getBuiltIn());
2539 if (
auto Attr = VD->
getAttr<HLSLVkExtBuiltinOutputAttr>())
2541 GV, llvm::hlsl::SPIRVInterfaceDecoration::BuiltIn,
Attr->getBuiltIn());
2545 if (!
CGM.shouldEmitConvergenceTokens())
2549 for (
auto I = BB.begin(); I != E; ++I) {
2550 auto *II = dyn_cast<llvm::IntrinsicInst>(&*I);
2551 if (II && llvm::isConvergenceControlIntrinsic(II->getIntrinsicID())) {
2555 llvm_unreachable(
"Convergence token should have been emitted.");
2592 for (
auto *OVE : Visitor.
OVEs) {
2595 if (OpaqueValueMappingData::shouldBindAsLValue(OVE)) {
2597 OpaqueValueMappingData::bind(CGF, OVE, LV);
2600 OpaqueValueMappingData::bind(CGF, OVE, RV);
2609 "expected resource array subscript expression");
2614 const VarDecl *ArrayDecl = dyn_cast_or_null<VarDecl>(
2618 return std::nullopt;
2624 "expected array of resource classes");
2630 Value *Index =
nullptr;
2632 while (ASE !=
nullptr) {
2634 if (
const auto *ArrayTy =
2636 Value *Multiplier = llvm::ConstantInt::get(
2638 SubIndex = CGF.
Builder.CreateMul(SubIndex, Multiplier);
2640 Index = Index ? CGF.
Builder.CreateAdd(Index, SubIndex) : SubIndex;
2648 "resource array must have a binding attribute");
2669 llvm::Value *Range = llvm::ConstantInt::getSigned(
2670 CGM.IntTy, getTotalArraySize(AST, ResArrayTy));
2674 if (ResultTy == ResourceTy) {
2676 CXXMethodDecl *CreateMethod = lookupResourceInitMethodAndSetupArgs(
2678 ArrayDecl->
getName(), Binding, Args);
2680 if (!CreateMethod) {
2685 "create method lookup should always succeed for built-in resource "
2687 return std::nullopt;
2690 callResourceInitMethod(CGF, CreateMethod, Args, ValueSlot.getAddress());
2697 std::optional<llvm::Value *> EndIndex = initializeResourceArrayFromGlobal(
2699 ArrayDecl->
getName(), Binding, {llvm::ConstantInt::get(CGM.IntTy, 0)});
2701 return std::nullopt;
2707bool CGHLSLRuntime::initializeGlobalResourceArray(
CodeGenFunction &CGF,
2713 "expected global non-static resource array");
2719 "resource array must have a binding attribute");
2724 const auto *ResArrayTy =
2728 int Size = getTotalArraySize(AST, ResArrayTy);
2729 llvm::Value *
Zero = llvm::ConstantInt::get(
CGM.
IntTy, 0);
2730 llvm::Value *Range = llvm::ConstantInt::get(
CGM.
IntTy, Size);
2733 std::optional<llvm::Value *> EndIndex = initializeResourceArrayFromGlobal(
2735 ArrayDecl->
getName(), Binding, {Zero});
2736 return EndIndex.has_value();
2745 "expected resource array");
2750 dyn_cast_or_null<VarDecl>(getArrayDecl(CGF.
CGM.
getContext(), E));
2755 return initializeGlobalResourceArray(CGF, ArrayDecl, DestSlot);
2762std::optional<LValue>
2766 "expected resource array declaration");
2770 return std::nullopt;
2774 if (initializeGlobalResourceArray(CGF, ArrayDecl, TmpArraySlot))
2777 return std::nullopt;
2785 "expected cbuffer matrix");
2796 HLSLBufferCopyEmitter(CGF, DestAlloca, SrcAddr).emitCopy(MatQualTy);
2802 llvm::function_ref<llvm::Value *(
bool Promote)> EmitIdxAfterBase) {
2806 llvm::Type *LayoutTy =
2808 uint64_t LayoutSizeInBits =
2809 CGM.getDataLayout().getTypeSizeInBits(LayoutTy).getFixedValue();
2812 if (RowAlignedSize > ElementSize) {
2813 llvm::Type *Padding =
CGM.getTargetCodeGenInfo().getHLSLPadding(
2814 CGM, RowAlignedSize - ElementSize);
2815 assert(Padding &&
"No padding type for target?");
2816 LayoutTy = llvm::StructType::get(CGF.
getLLVMContext(), {LayoutTy, Padding},
2823 if (LayoutTy == OrigTy)
2824 return std::nullopt;
2833 llvm::Value *Idx = EmitIdxAfterBase(
true);
2834 Indices.push_back(Idx);
2835 Indices.push_back(llvm::ConstantInt::get(CGF.
Int32Ty, 0));
2841 assert(CE->
getCastKind() == CastKind::CK_ArrayToPointerDecay);
2845 LayoutTy = llvm::ArrayType::get(
2849 LayoutTy,
Addr.emitRawPointer(CGF), Indices,
"cbufferidx"));
2858 Indices,
"cbufferidx");
2863std::optional<LValue>
2868 "expected resource member expression");
2871 findAssociatedResourceDeclForStruct(CGF.
CGM.
getContext(), ME);
2873 return std::nullopt;
2879 GlobalVariable *ResGV =
2881 const DataLayout &DL =
CGM.getDataLayout();
2882 llvm::Type *Ty = ResGV->getValueType();
2895 "expected expression in HLSL constant address space");
2898 "direct accesses to resource types should be handled separately");
2910 return HLSLBufferCopyEmitter(CGF, DstPtr, SrcPtr).emitCopy(Ty);
2916 const VarDecl *VD = findStructResourceParentDeclAndBuildName(E, NameBuilder);
2917 AssociatedResourcesList AssociatedResources(VD, NameBuilder.
getName());
2921 const VarDecl *ResDecl = AssociatedResources.getNextResource();
2922 assert(ResDecl &&
"associated resource declaration not found");
2925 [[maybe_unused]] llvm::Type *DestType =
2926 ResSlot.getAddress().getElementType();
2927 [[maybe_unused]] llvm::Type *SrcConvertedType =
2928 CGM.getTypes().ConvertTypeForMem(ResDecl->
getType());
2929 assert(DestType == SrcConvertedType &&
"resource slot type mismatch");
2932 copyGlobalResource(CGF, ResDecl, ResSlot);
2934 initializeGlobalResourceArray(CGF, ResDecl, ResSlot);
2938 HLSLBufferCopyEmitter(CGF, DstPtr, SrcPtr).emitCopy(Ty, EmitResFn);
2939 assert(AssociatedResources.getNextResource() ==
nullptr &&
2940 "expected all associated resources to be processed");
2949 assert(Field &&
"Unexpected access into HLSL buffer");
2954 QualType RecType =
CGM.getContext().getCanonicalTagType(Rec);
2965 CGM.getTypes().getCGRecordLayout(Rec).getLLVMFieldNo(Field);
2966 assert(FieldIdx < LayoutTy->getNumElements() &&
2967 "Layout struct is smaller than member struct");
2968 unsigned Skipped = 0;
2969 for (
unsigned I = 0; I <= FieldIdx;) {
2970 llvm::Type *ElementTy = LayoutTy->getElementType(I + Skipped);
2976 FieldIdx += Skipped;
2977 assert(FieldIdx < LayoutTy->getNumElements() &&
"Access out of bounds");
2981 QualType FieldType = Field->getType();
2982 llvm::Type *FieldLLVMTy =
CGM.getTypes().ConvertTypeForMem(FieldType);
2987 ? CGF.
Builder.CreateStructuredGEP(
2988 LayoutTy,
Base.getPointer(CGF),
2989 llvm::ConstantInt::get(
CGM.IntTy, FieldIdx))
2991 FieldIdx, Field->getName());
2996 CGM.getTBAAAccessInfo(FieldType));
Defines the clang::ASTContext interface.
static bool requiresFlatInterpolation(llvm::Type *Ty)
static llvm::dxil::ElementType getSignatureComponentType(CodeGenModule &CGM, QualType Ty)
static QualType getSemanticLeafType(const clang::DeclaratorDecl *Decl)
static void addSPIRVInterfaceDecorations(llvm::GlobalVariable *GV, llvm::hlsl::SPIRVInterfaceDecoration Decoration, unsigned Operand, llvm::hlsl::InterpolationMode InterpMode=llvm::hlsl::InterpolationMode::Undefined)
static llvm::hlsl::SemanticSignatureElement createSemanticSignatureElement(CodeGenModule &CGM, uint32_t SigId, HLSLAppliedSemanticAttr *Semantic, std::optional< unsigned > Index, const SemanticShape &Shape)
static unsigned getSPIRVVkBuiltinID(StringRef BuiltIn)
static void gatherFunctions(SmallVectorImpl< Function * > &Fns, llvm::Module &M, bool CtorOrDtor)
static llvm::Value * createSPIRVInputLoad(IRBuilder<> &B, llvm::Module &M, llvm::Type *Ty, const Twine &Name, llvm::hlsl::SPIRVInterfaceDecoration Decoration, unsigned Operand, llvm::hlsl::InterpolationMode InterpMode)
static llvm::hlsl::InterpolationMode getSPIRVInterpolationMode(llvm::hlsl::InterpolationMode InterpMode, llvm::Type *Ty, llvm::Triple::EnvironmentType Stage, llvm::hlsl::IOType IO)
static void addSPIRVQuadAllExecutionModes(CodeGenModule &CGM)
static Value * buildVectorInput(IRBuilder<> &B, Function *F, llvm::Type *Ty)
static void createSPIRVOutputStore(IRBuilder<> &B, llvm::Module &M, llvm::Value *Source, const Twine &Name, llvm::hlsl::SPIRVInterfaceDecoration Decoration, unsigned Operand, llvm::hlsl::InterpolationMode InterpMode, bool IsSigned=false)
static void markArbitrarySignatureElements(SmallVectorImpl< llvm::hlsl::SemanticSignatureElement > &Signature, size_t FirstElement)
static void initializeBuffer(CodeGenModule &CGM, llvm::GlobalVariable *GV, Intrinsic::ID IntrID, ArrayRef< llvm::Value * > Args)
static llvm::Value * createSPIRVBuiltinDelta(IRBuilder<> &B, llvm::Module &M, llvm::Type *Ty, const Twine &Name, unsigned BuiltInID, unsigned BaseBuiltInID, llvm::hlsl::InterpolationMode InterpMode)
static const clang::HLSLAttributedResourceType * createBufferHandleType(const HLSLBufferDecl *BufDecl)
static SemanticShape getSemanticShape(ASTContext &Ctx, QualType Ty)
Result
Implement __builtin_bit_cast and related operations.
llvm::MachO::Record Record
Defines AST-level helper utilities for matrix types.
llvm::dxbc::PSV::SemanticKind SemanticKind
Defines the SourceManager interface.
Defines the clang::TargetOptions class.
C Language Family Type Representation.
bool VisitHLSLOutArgExpr(HLSLOutArgExpr *)
llvm::SmallVector< OpaqueValueExpr *, 8 > OVEs
bool VisitOpaqueValueExpr(OpaqueValueExpr *E)
llvm::SmallPtrSet< OpaqueValueExpr *, 8 > Visited
Holds long-lived AST nodes (such as types and decls) that can be referred to throughout the semantic ...
SourceManager & getSourceManager()
const ConstantArrayType * getAsConstantArrayType(QualType T) const
QualType getPointerType(QualType T) const
Return the uniqued reference to the type for a pointer to the specified type.
const LangOptions & getLangOpts() const
QualType getBaseElementType(const ArrayType *VAT) const
Return the innermost element type of an array type.
CharUnits getTypeSizeInChars(QualType T) const
Return the size of the specified (complete) type T, in characters.
CanQualType UnsignedIntTy
static uint64_t getConstantArrayElementCount(const ConstantArrayType *CA)
Return number of (potentially nested) constant array elements.
QualType getExtVectorType(QualType VectorType, unsigned NumElts) const
Return the unique reference to an extended vector type of the specified element type and size.
QualType getHLSLAttributedResourceType(QualType Wrapped, QualType Contained, const HLSLAttributedResourceType::Attributes &Attrs)
CanQualType getCanonicalTagType(const TagDecl *TD) const
unsigned getTargetAddressSpace(LangAS AS) const
ArraySubscriptExpr - [C99 6.5.2.1] Array Subscripting.
QualType getElementType() const
Attr - This represents one attribute.
This class is used for builtin types like 'int'.
Represents a static or instance method of a struct/union/class.
Represents a C++ struct/union/class.
QualType withConst() const
Retrieves a version of this type with const applied.
CastExpr - Base class for type casts, including both implicit casts (ImplicitCastExpr) and explicit c...
CastKind getCastKind() const
This is an opaque type for sizes expressed in character units.
CharUnits alignTo(CharUnits Align) const
Returns the next integer (mod 2**64) that is greater than or equal to this quantity and is a multiple...
CharUnits alignmentOfArrayElement(CharUnits elementSize) const
Given that this is the alignment of the first element of an array, return the minimum alignment of an...
static CharUnits fromQuantity(QuantityType Quantity)
Construct a CharUnits quantity from a raw integer type.
HLSLSemanticSignaturePackingMode
Like RawAddress, an abstract representation of an aligned address, but the pointer contained in this ...
CharUnits getAlignment() const
Address getAddress() const
static AggValueSlot forAddr(Address addr, Qualifiers quals, IsDestructed_t isDestructed, NeedsGCBarriers_t needsGC, IsAliased_t isAliased, Overlap_t mayOverlap, IsZeroed_t isZeroed=IsNotZeroed, IsSanitizerChecked_t isChecked=IsNotSanitizerChecked)
forAddr - Make a slot for an aggregate value.
llvm::StoreInst * CreateStore(llvm::Value *Val, Address Addr, bool IsVolatile=false)
Address CreateGEP(CodeGenFunction &CGF, Address Addr, llvm::Value *Index, const llvm::Twine &Name="")
Address CreateStructGEP(Address Addr, unsigned Index, const llvm::Twine &Name="")
Abstract information about a function or function prototype.
All available information about a concrete callee.
CGFunctionInfo - Class to encapsulate the information about a function definition.
static const uint32_t Unspecified
static bool compareOffsets(uint32_t LHS, uint32_t RHS)
Comparison function for offsets received from operator[] suitable for use in a stable_sort.
static CGHLSLOffsetInfo fromDecl(const HLSLBufferDecl &BufDecl)
Iterates over all declarations in the HLSL buffer and based on the packoffset or register(c#) annotat...
llvm::Instruction * getConvergenceToken(llvm::BasicBlock &BB)
void setHLSLEntryAttributes(const FunctionDecl *FD, llvm::Function *Fn)
llvm::Value * handleScalarSemanticLoad(llvm::IRBuilder<> &B, const FunctionDecl *FD, llvm::Type *Type, const clang::DeclaratorDecl *Decl, HLSLAppliedSemanticAttr *Semantic, SemanticSignatures &Signature, llvm::hlsl::InterpolationMode InterpMode)
llvm::StructType * getHLSLBufferLayoutType(const RecordType *LayoutStructTy)
void emitEntryFunction(const FunctionDecl *FD, llvm::Function *Fn)
void handleGlobalVarDefinition(const VarDecl *VD, llvm::GlobalVariable *Var)
void handleScalarSemanticStore(llvm::IRBuilder<> &B, const FunctionDecl *FD, llvm::Value *Source, const clang::DeclaratorDecl *Decl, HLSLAppliedSemanticAttr *Semantic, SemanticSignatures &Signature, llvm::hlsl::InterpolationMode InterpMode)
std::optional< LValue > emitResourceMemberExpr(CodeGenFunction &CGF, const MemberExpr *E)
specific_attr_iterator< HLSLAppliedSemanticAttr > handleStructSemanticStore(llvm::IRBuilder<> &B, const FunctionDecl *FD, llvm::Value *Source, const clang::DeclaratorDecl *Decl, specific_attr_iterator< HLSLAppliedSemanticAttr > AttrBegin, specific_attr_iterator< HLSLAppliedSemanticAttr > AttrEnd, SemanticSignatures &Signature, llvm::hlsl::InterpolationModifier Modifiers)
llvm::SmallVectorImpl< llvm::hlsl::SemanticSignatureElement > SemanticSignatures
void addHLSLBufferLayoutType(const RecordType *LayoutStructTy, llvm::StructType *LayoutTy)
std::optional< LValue > emitGlobalResourceArrayAsLValue(CodeGenFunction &CGF, const VarDecl *ArrayDecl)
void emitSystemSemanticStore(llvm::IRBuilder<> &B, llvm::Value *Source, const clang::DeclaratorDecl *Decl, HLSLAppliedSemanticAttr *Semantic, llvm::dxbc::PSV::SemanticKind SemanticKind, llvm::Triple::EnvironmentType Stage, std::optional< unsigned > Index, SemanticSignatures &Signature, llvm::hlsl::InterpolationMode InterpMode)
bool emitBufferCopy(CodeGenFunction &CGF, const Expr *E, const LValue &SrcLV, AggValueSlot &DestSlot)
std::optional< LValue > emitBufferArraySubscriptExpr(const ArraySubscriptExpr *E, CodeGenFunction &CGF, llvm::function_ref< llvm::Value *(bool Promote)> EmitIdxAfterBase)
std::optional< LValue > emitResourceArraySubscriptExpr(const ArraySubscriptExpr *E, CodeGenFunction &CGF)
void addRootSignature(const HLSLRootSignatureDecl *D)
LValue emitBufferMemberExpr(CodeGenFunction &CGF, const MemberExpr *E)
llvm::Value * emitSystemSemanticLoad(llvm::IRBuilder<> &B, llvm::Type *Type, const clang::DeclaratorDecl *Decl, HLSLAppliedSemanticAttr *Semantic, llvm::dxbc::PSV::SemanticKind SemanticKind, llvm::Triple::EnvironmentType Stage, std::optional< unsigned > Index, SemanticSignatures &Signature, llvm::hlsl::InterpolationMode InterpMode)
llvm::Type * convertHLSLSpecificType(const Type *T, const CGHLSLOffsetInfo &OffsetInfo)
RawAddress createBufferMatrixTempAddress(const LValue &LV, CodeGenFunction &CGF)
specific_attr_iterator< HLSLAppliedSemanticAttr > handleSemanticStore(llvm::IRBuilder<> &B, const FunctionDecl *FD, llvm::Value *Source, const clang::DeclaratorDecl *Decl, specific_attr_iterator< HLSLAppliedSemanticAttr > AttrBegin, specific_attr_iterator< HLSLAppliedSemanticAttr > AttrEnd, SemanticSignatures &Signature, llvm::hlsl::InterpolationModifier Modifiers=llvm::hlsl::InterpolationModifier::None)
void addBuffer(const HLSLBufferDecl *D)
void generateGlobalCtorDtorCalls()
std::pair< llvm::Value *, specific_attr_iterator< HLSLAppliedSemanticAttr > > handleStructSemanticLoad(llvm::IRBuilder<> &B, const FunctionDecl *FD, llvm::Type *Type, const clang::DeclaratorDecl *Decl, specific_attr_iterator< HLSLAppliedSemanticAttr > begin, specific_attr_iterator< HLSLAppliedSemanticAttr > end, SemanticSignatures &Signature, llvm::hlsl::InterpolationModifier Modifiers)
bool emitGlobalResourceArray(CodeGenFunction &CGF, const Expr *E, AggValueSlot &DestSlot)
void emitInitListOpaqueValues(CodeGenFunction &CGF, InitListExpr *E)
std::pair< llvm::Value *, specific_attr_iterator< HLSLAppliedSemanticAttr > > handleSemanticLoad(llvm::IRBuilder<> &B, const FunctionDecl *FD, llvm::Type *Type, const clang::DeclaratorDecl *Decl, specific_attr_iterator< HLSLAppliedSemanticAttr > begin, specific_attr_iterator< HLSLAppliedSemanticAttr > end, SemanticSignatures &Signature, llvm::hlsl::InterpolationModifier Modifiers=llvm::hlsl::InterpolationModifier::None)
CallArgList - Type for representing both the value and type of arguments in a call.
void add(RValue rvalue, QualType type)
A non-RAII class containing all the information about a bound opaque value.
CodeGenFunction - This class organizes the per-function state that is used while generating LLVM code...
const LangOptions & getLangOpts() const
@ TCK_MemberAccess
Checking the object expression in a non-static data member access.
void pushFullExprCleanup(CleanupKind kind, As... A)
pushFullExprCleanup - Push a cleanup to be run at the end of the current full-expression.
AggValueSlot CreateAggTemp(QualType T, const Twine &Name="tmp", RawAddress *Alloca=nullptr)
CreateAggTemp - Create a temporary memory object for the given aggregate type.
bool EmitLifetimeStart(llvm::Value *Addr)
Emit a lifetime.begin marker if some criteria are satisfied.
RValue EmitCall(const CGFunctionInfo &CallInfo, const CGCallee &Callee, ReturnValueSlot ReturnValue, const CallArgList &Args, llvm::CallBase **CallOrInvoke, bool IsMustTail, SourceLocation Loc, bool IsVirtualFunctionPointerThunk=false)
EmitCall - Generate a call of the given function, expecting the given result type,...
RawAddress CreateMemTempWithoutCast(QualType T, const Twine &Name="tmp")
CreateMemTemp - Create a temporary memory object of the given type, with appropriate alignmen without...
ASTContext & getContext() const
RValue EmitAnyExpr(const Expr *E, AggValueSlot aggSlot=AggValueSlot::ignored(), bool ignoreResult=false)
EmitAnyExpr - Emit code to compute the specified expression which can have any type.
llvm::Type * ConvertTypeForMem(QualType T)
Address EmitPointerWithAlignment(const Expr *Addr, LValueBaseInfo *BaseInfo=nullptr, TBAAAccessInfo *TBAAInfo=nullptr, KnownNonNull_t IsKnownNonNull=NotKnownNonNull)
EmitPointerWithAlignment - Given an expression with a pointer type, emit the value and compute our be...
LValue EmitCheckedLValue(const Expr *E, TypeCheckKind TCK)
Same as EmitLValue but additionally we generate checking code to guard against undefined behavior.
llvm::Value * EmitScalarExpr(const Expr *E, bool IgnoreResultAssign=false)
EmitScalarExpr - Emit the computation of the specified expression of LLVM scalar type,...
LValue MakeAddrLValue(Address Addr, QualType T, AlignmentSource Source=AlignmentSource::Type)
LValue EmitLValue(const Expr *E, KnownNonNull_t IsKnownNonNull=NotKnownNonNull)
EmitLValue - Emit code to compute a designator that specifies the location of the expression.
bool isOpaqueValueEmitted(const OpaqueValueExpr *E)
isOpaqueValueEmitted - Return true if the opaque value expression has already been emitted.
llvm::LLVMContext & getLLVMContext()
This class organizes the cross-function state that is used while generating LLVM code.
const PreprocessorOptions & getPreprocessorOpts() const
llvm::Module & getModule() const
llvm::Constant * GetAddrOfFunction(GlobalDecl GD, llvm::Type *Ty=nullptr, bool ForVTable=false, bool DontDefer=false, ForDefinition_t IsForDefinition=NotForDefinition)
Return the address of the given function.
DiagnosticsEngine & getDiags() const
void AddCXXGlobalInit(llvm::Function *F)
CodeGenTypes & getTypes()
const TargetInfo & getTarget() const
void EmitGlobal(GlobalDecl D)
Emit code for a single global function or var decl.
const llvm::DataLayout & getDataLayout() const
ASTContext & getContext() const
llvm::Constant * GetAddrOfGlobalVar(const VarDecl *D, llvm::Type *Ty=nullptr, ForDefinition_t IsForDefinition=NotForDefinition)
Return the llvm::Constant for the address of the given global variable.
const TargetCodeGenInfo & getTargetCodeGenInfo()
const CodeGenOptions & getCodeGenOpts() const
llvm::LLVMContext & getLLVMContext()
void EmitTopLevelDecl(Decl *D)
Emit code for a single top level declaration.
ConstantAddress GetAddrOfConstantCString(const std::string &Str, StringRef GlobalName=".str")
Returns a pointer to a character array containing the literal and a terminating '\0' character.
const CGFunctionInfo & arrangeFreeFunctionCall(const CallArgList &Args, const FunctionType *Ty, bool ChainCall, const FunctionDecl *ABIInfoFD)
Figure out the rules for calling a function with the given formal type using the given arguments.
llvm::Type * ConvertTypeForMem(QualType T)
ConvertTypeForMem - Convert type T into a llvm::Type.
llvm::Constant * getPointer() const
llvm::StructType * layOutStruct(const RecordType *StructType, const CGHLSLOffsetInfo &OffsetInfo)
Lays out a struct type following HLSL buffer rules and considering any explicit offset information.
llvm::Type * layOutType(QualType Type)
Lays out a type following HLSL buffer rules.
LValue - This represents an lvalue references.
static LValue MakeAddr(Address Addr, QualType type, ASTContext &Context, LValueBaseInfo BaseInfo, TBAAAccessInfo TBAAInfo)
const Qualifiers & getQuals() const
Address getAddress() const
RValue - This trivial value class is used to represent the result of an expression that is evaluated.
static RValue get(llvm::Value *V)
An abstract representation of an aligned address.
llvm::Value * getPointer() const
ReturnValueSlot - Contains the address where the return value of a function can be stored,...
virtual bool isHLSLPadding(llvm::Type *Ty) const
Return true if this is an HLSL padding type.
Represents the canonical version of C arrays with a specified constant size.
int64_t getSExtSize() const
Return the size sign-extended as a uint64_t.
Represents a concrete matrix type with constant number of rows and columns.
DeclContext * getParent()
getParent - Returns the containing DeclContext.
Decl - This represents one declaration (or definition), e.g.
ASTContext & getASTContext() const LLVM_READONLY
bool isImplicit() const
isImplicit - Indicates whether the declaration was implicitly generated by the implementation.
SourceLocation getLocation() const
specific_attr_iterator< T > specific_attr_end() const
specific_attr_iterator< T > specific_attr_begin() const
Represents a ValueDecl that came out of a declarator.
DiagnosticBuilder Report(SourceLocation Loc, unsigned DiagID)
Issue the message to the client.
This represents one expression.
Expr * IgnoreParenImpCasts() LLVM_READONLY
Skip past any parentheses and implicit casts which might surround this expression until reaching a fi...
std::optional< llvm::APSInt > getIntegerConstantExpr(const ASTContext &Ctx, bool AllowRelaxedEval=false) const
isIntegerConstantExpr - Return the value if this expression is a valid integer constant expression.
Expr * IgnoreImpCasts() LLVM_READONLY
Skip past any implicit casts which might surround this expression until reaching a fixed point.
Represents a member of a struct/union/class.
StringRef getName() const
The name of this FileEntry.
Represents a function declaration or definition.
const ParmVarDecl * getParamDecl(unsigned i) const
QualType getDeclaredReturnType() const
Get the declared return type, which may differ from the actual return type if the return type is dedu...
Represents a prototype with parameter type info, e.g.
HLSLBufferDecl - Represent a cbuffer or tbuffer declaration.
const CXXRecordDecl * getLayoutStruct() const
bool hasValidPackoffset() const
buffer_decl_range buffer_decls() const
This class represents temporary values used to represent inout and out arguments in HLSL.
ArrayRef< llvm::hlsl::rootsig::RootElement > getRootElements() const
llvm::dxbc::RootSignatureVersion getVersion() const
One of these records is kept for each identifier that is lexed.
Describes an C or C++ initializer list.
MemberExpr - [C99 6.5.2.3] Structure and Union Members.
ValueDecl * getMemberDecl() const
Retrieve the member declaration to which this expression refers.
IdentifierInfo * getIdentifier() const
Get the identifier that names this declaration, if there is one.
StringRef getName() const
Get the name of identifier for this declaration as a StringRef.
OpaqueValueExpr - An expression referring to an opaque object of a fixed type and value class.
Expr * getSourceExpr() const
The source expression of an opaque value expression is the expression which originally generated the ...
Represents a parameter to a function.
std::vector< std::pair< std::string, bool > > Macros
A (possibly-)qualified type.
const Type * getTypePtr() const
Retrieves a pointer to the underlying (unqualified) type.
LangAS getAddressSpace() const
Return the address space of this type.
The collection of all-type qualifiers we support.
void addCVRQualifiers(unsigned mask)
Represents a struct/union/class.
unsigned getNumFields() const
Returns the number of fields (non-static data members) in this record.
field_iterator field_begin() const
A class that does preorder or postorder depth-first traversal on the entire Clang AST and visits each...
bool TraverseStmt(Stmt *S, DataRecursionQueue *Queue=nullptr)
Encodes a location in the source.
One instance of this struct is kept for every file loaded or used.
std::optional< llvm::MemoryBufferRef > getBufferOrNone(DiagnosticsEngine &Diag, FileManager &FM, SourceLocation Loc=SourceLocation()) const
Returns the memory buffer for the associated content.
OptionalFileEntryRef OrigEntry
Reference to the file entry representing this ContentCache.
Information about a FileID, basically just the logical file that it represents and include stack info...
const ContentCache & getContentCache() const
CharacteristicKind getFileCharacteristic() const
Return whether this is a system header or not.
This is a discriminated union of FileInfo and ExpansionInfo.
const FileInfo & getFile() const
const llvm::Triple & getTriple() const
Returns the target triple of the primary target.
Token - This structure provides full information about a lexed token.
The base class of the type hierarchy.
bool isSignedIntegerOrEnumerationType() const
Determines whether this is an integer type that is signed or an enumeration types whose underlying ty...
bool isIncompleteArrayType() const
CXXRecordDecl * getAsCXXRecordDecl() const
Retrieves the CXXRecordDecl that this type refers to, either because the type is a RecordType or beca...
RecordDecl * getAsRecordDecl() const
Retrieves the RecordDecl this type refers to.
bool isConstantMatrixType() const
bool isHLSLIntangibleType() const
bool isHLSLResourceRecord() const
bool isStructureOrClassType() const
const T * getAsCanonical() const
If this type is canonically the specified type, return its canonical type cast to that specified type...
const T * getAs() const
Member-template getAs<specific type>'.
const Type * getUnqualifiedDesugaredType() const
Return the specified type with any "sugar" removed from the type, removing any typedefs,...
bool isRecordType() const
bool isHLSLResourceRecordArray() const
bool hasBooleanRepresentation() const
Determine whether this type has a boolean representation – i.e., it is a boolean type,...
Represent the declaration of a variable (in which case it is an lvalue) a function (in which case it ...
Represents a variable declaration or definition.
bool hasGlobalStorage() const
Returns true for all variables that do not have local storage.
StorageClass getStorageClass() const
Returns the storage class as written in the source.
Represents a GCC generic vector type.
void pushName(llvm::StringRef N)
void pushArrayIndex(uint64_t Index)
llvm::StringRef getName() const
void pushBaseNameHierarchy(CXXRecordDecl *DerivedRD, CXXRecordDecl *BaseRD)
IdentifierInfo * getNameAsIdentifier(ASTContext &AST) const
specific_attr_iterator - Iterates over a subrange of an AttrVec, only providing attributes that are o...
@ Type
The l-value was considered opaque, so the alignment was determined from a type.
@ Decl
The l-value was an access to a declared entity or something equivalently strong, like the address of ...
bool isSystem(CharacteristicKind CK)
Determine whether a file / directory characteristic is for system code.
@ Macros
Canonicalize -D and -U options.
bool hasCounterHandle(const CXXRecordDecl *RD)
StringRef getName(const HeaderType T)
@ Address
A pointer to a ValueDecl.
bool Load(InterpState &S, CodePtr OpPC)
Top level wrappers for InstallAPI frontend operations.
bool isa(CodeGen::Address addr)
CustomizableOptional< FileEntryRef > OptionalFileEntryRef
bool isMatrixRowMajor(const LangOptions &LangOpts, QualType T)
Returns true if matrices of T should be laid out in row-major order.
nullptr
This class represents a compute construct, representing a 'Kind' of ‘parallel’, 'serial',...
StorageClass
Storage classes.
@ Result
The result type of a method or function.
const FunctionProtoType * T
U cast(CodeGen::Address addr)
Diagnostic wrappers for TextAPI types for error reporting.
__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
llvm::IntegerType * Int32Ty
llvm::IntegerType * IntTy
int
unsigned getImplicitOrderID() const
bool hasCounterImplicitOrderID() const
unsigned getSpace() const
unsigned getCounterImplicitOrderID() const