38#include "llvm/ADT/ArrayRef.h"
39#include "llvm/ADT/STLExtras.h"
40#include "llvm/ADT/SmallVector.h"
41#include "llvm/ADT/StringExtras.h"
42#include "llvm/ADT/StringRef.h"
43#include "llvm/ADT/Twine.h"
44#include "llvm/Frontend/HLSL/HLSLBinding.h"
45#include "llvm/Frontend/HLSL/RootSignatureValidations.h"
46#include "llvm/Support/Casting.h"
47#include "llvm/Support/DXILABI.h"
48#include "llvm/Support/ErrorHandling.h"
49#include "llvm/Support/FormatVariadic.h"
50#include "llvm/Support/raw_ostream.h"
51#include "llvm/TargetParser/Triple.h"
60using llvm::hlsl::InterpolationModifier;
61using llvm::hlsl::IOType;
62using llvm::hlsl::SemanticStageInfo;
71 return VT->getElementType();
73 return MT->getElementType();
79 case ResourceClass::SRV:
80 return RegisterType::SRV;
81 case ResourceClass::UAV:
82 return RegisterType::UAV;
83 case ResourceClass::CBuffer:
84 return RegisterType::CBuffer;
85 case ResourceClass::Sampler:
86 return RegisterType::Sampler;
88 llvm_unreachable(
"unexpected ResourceClass value");
97 case ResourceClass::SRV:
98 case ResourceClass::UAV:
100 case ResourceClass::CBuffer:
102 case ResourceClass::Sampler:
105 llvm_unreachable(
"unexpected ResourceClass value");
111 assert(RT !=
nullptr);
115 *RT = RegisterType::SRV;
119 *RT = RegisterType::UAV;
123 *RT = RegisterType::CBuffer;
127 *RT = RegisterType::Sampler;
131 *RT = RegisterType::C;
135 *RT = RegisterType::I;
144 case RegisterType::SRV:
146 case RegisterType::UAV:
148 case RegisterType::CBuffer:
150 case RegisterType::Sampler:
152 case RegisterType::C:
154 case RegisterType::I:
157 llvm_unreachable(
"unexpected RegisterType value");
162 case RegisterType::SRV:
163 return ResourceClass::SRV;
164 case RegisterType::UAV:
165 return ResourceClass::UAV;
166 case RegisterType::CBuffer:
167 return ResourceClass::CBuffer;
168 case RegisterType::Sampler:
169 return ResourceClass::Sampler;
170 case RegisterType::C:
171 case RegisterType::I:
175 llvm_unreachable(
"unexpected RegisterType value");
179 const auto *BT = dyn_cast<BuiltinType>(
Type);
183 return Builtin::BI__builtin_get_spirv_spec_constant_int;
186 switch (BT->getKind()) {
187 case BuiltinType::Bool:
188 return Builtin::BI__builtin_get_spirv_spec_constant_bool;
189 case BuiltinType::Short:
190 return Builtin::BI__builtin_get_spirv_spec_constant_short;
191 case BuiltinType::Int:
192 return Builtin::BI__builtin_get_spirv_spec_constant_int;
193 case BuiltinType::LongLong:
194 return Builtin::BI__builtin_get_spirv_spec_constant_longlong;
195 case BuiltinType::UShort:
196 return Builtin::BI__builtin_get_spirv_spec_constant_ushort;
197 case BuiltinType::UInt:
198 return Builtin::BI__builtin_get_spirv_spec_constant_uint;
199 case BuiltinType::ULongLong:
200 return Builtin::BI__builtin_get_spirv_spec_constant_ulonglong;
201 case BuiltinType::Half:
202 return Builtin::BI__builtin_get_spirv_spec_constant_half;
203 case BuiltinType::Float:
204 return Builtin::BI__builtin_get_spirv_spec_constant_float;
205 case BuiltinType::Double:
206 return Builtin::BI__builtin_get_spirv_spec_constant_double;
215 llvm::raw_svector_ostream OS(Buffer);
222 ResourceClass ResClass) {
224 "DeclBindingInfo already added");
230 DeclToBindingListIndex.try_emplace(VD, BindingsList.size());
231 return &BindingsList.emplace_back(VD, ResClass);
235 ResourceClass ResClass) {
236 auto Entry = DeclToBindingListIndex.find(VD);
237 if (Entry != DeclToBindingListIndex.end()) {
238 for (
unsigned Index = Entry->getSecond();
239 Index < BindingsList.size() && BindingsList[Index].Decl == VD;
241 if (BindingsList[Index].ResClass == ResClass)
242 return &BindingsList[Index];
249 return DeclToBindingListIndex.contains(VD);
261 getASTContext(), LexicalParent, CBuffer, KwLoc, Ident, IdentLoc, LBrace);
264 auto RC = CBuffer ? llvm::hlsl::ResourceClass::CBuffer
265 : llvm::hlsl::ResourceClass::SRV;
277 if (
T->isArrayType() ||
T->isStructureType() ||
T->isConstantMatrixType())
284 assert(Context.getTypeSize(
T) <= 64 &&
285 "Scalar bit widths larger than 64 not supported");
288 return Context.getTypeSize(
T) / 8;
295 constexpr unsigned CBufferAlign = 16;
296 if (
const auto *RD =
T->getAsRecordDecl()) {
298 for (
const FieldDecl *Field : RD->fields()) {
305 unsigned AlignSize = llvm::alignTo(Size, FieldAlign);
306 if ((AlignSize % CBufferAlign) + FieldSize > CBufferAlign) {
307 FieldAlign = CBufferAlign;
310 Size = llvm::alignTo(Size, FieldAlign);
317 unsigned ElementCount = AT->getSize().getZExtValue();
318 if (ElementCount == 0)
321 unsigned ElementSize =
323 unsigned AlignedElementSize = llvm::alignTo(ElementSize, CBufferAlign);
324 return AlignedElementSize * (ElementCount - 1) + ElementSize;
328 unsigned ElementCount = VT->getNumElements();
329 unsigned ElementSize =
331 return ElementSize * ElementCount;
334 return Context.getTypeSize(
T) / 8;
345 bool HasPackOffset =
false;
346 bool HasNonPackOffset =
false;
348 VarDecl *Var = dyn_cast<VarDecl>(Field);
351 if (Field->hasAttr<HLSLPackOffsetAttr>()) {
352 PackOffsetVec.emplace_back(Var, Field->
getAttr<HLSLPackOffsetAttr>());
353 HasPackOffset =
true;
355 HasNonPackOffset =
true;
362 if (HasNonPackOffset)
369 std::sort(PackOffsetVec.begin(), PackOffsetVec.end(),
370 [](
const std::pair<VarDecl *, HLSLPackOffsetAttr *> &LHS,
371 const std::pair<VarDecl *, HLSLPackOffsetAttr *> &RHS) {
372 return LHS.second->getOffsetInBytes() <
373 RHS.second->getOffsetInBytes();
375 for (
unsigned i = 0; i < PackOffsetVec.size() - 1; i++) {
376 VarDecl *Var = PackOffsetVec[i].first;
377 HLSLPackOffsetAttr *
Attr = PackOffsetVec[i].second;
379 unsigned Begin =
Attr->getOffsetInBytes();
380 unsigned End = Begin + Size;
381 unsigned NextBegin = PackOffsetVec[i + 1].second->getOffsetInBytes();
382 if (End > NextBegin) {
383 VarDecl *NextVar = PackOffsetVec[i + 1].first;
395 CAT = dyn_cast<ConstantArrayType>(
397 return CAT !=
nullptr;
408static const HLSLAttributedResourceType *
411 "expected array of resource records");
413 while (
const ArrayType *AT = dyn_cast<ArrayType>(Ty))
415 return HLSLAttributedResourceType::findHandleTypeOnResource(Ty);
418static const HLSLAttributedResourceType *
432 return RD->isEmpty();
461 Base.getType()->castAsCXXRecordDecl()))
472 assert(RD ==
nullptr &&
473 "there should be at most 1 record by a given name in a scope");
490 Name.append(NameBaseII->
getName());
497 size_t NameLength = Name.size();
506 Name.append(llvm::Twine(suffix).str());
507 II = &AST.
Idents.
get(Name, tok::TokenKind::identifier);
514 Name.truncate(NameLength);
529 if (
const auto *CAT = dyn_cast<ConstantArrayType>(Ty)) {
531 S, CAT->getElementType()->getUnqualifiedDesugaredType());
536 CAT->getSizeModifier(),
537 CAT->getIndexTypeCVRQualifiers())
586 "struct is already HLSL buffer compatible");
600 LS->
addAttr(PackedAttr::CreateImplicit(AST));
604 if (
unsigned NumBases = StructDecl->
getNumBases()) {
605 assert(NumBases == 1 &&
"HLSL supports only one base type");
655 LS->
addAttr(PackedAttr::CreateImplicit(AST));
660 VarDecl *VD = dyn_cast<VarDecl>(D);
676 "host layout field for $Globals decl failed to be created");
695 HLSLResourceBindingAttr::CreateImplicit(S.
getASTContext(),
"",
"0", {});
696 Attr->setBinding(RT, std::nullopt, 0);
697 Attr->setImplicitBindingOrderID(ImplicitBindingOrderID);
704 BufDecl->setRBraceLoc(RBrace);
721 BufDecl->isCBuffer() ? RegisterType::CBuffer
731 int X,
int Y,
int Z) {
732 if (HLSLNumThreadsAttr *NT = D->
getAttr<HLSLNumThreadsAttr>()) {
733 if (NT->getX() !=
X || NT->getY() != Y || NT->getZ() != Z) {
734 Diag(NT->getLocation(), diag::err_hlsl_attribute_param_mismatch) << AL;
735 Diag(AL.
getLoc(), diag::note_conflicting_attribute);
745 int Min,
int Max,
int Preferred,
746 int SpelledArgsCount) {
747 if (HLSLWaveSizeAttr *WS = D->
getAttr<HLSLWaveSizeAttr>()) {
748 if (WS->getMin() !=
Min || WS->getMax() !=
Max ||
749 WS->getPreferred() != Preferred ||
750 WS->getSpelledArgsCount() != SpelledArgsCount) {
751 Diag(WS->getLocation(), diag::err_hlsl_attribute_param_mismatch) << AL;
752 Diag(AL.
getLoc(), diag::note_conflicting_attribute);
758 Result->setSpelledArgsCount(SpelledArgsCount);
762HLSLVkConstantIdAttr *
768 Diag(AL.
getLoc(), diag::warn_attribute_ignored) << AL;
776 Diag(VD->getLocation(), diag::err_specialization_const);
780 if (!VD->getType().isConstQualified()) {
781 Diag(VD->getLocation(), diag::err_specialization_const);
785 if (HLSLVkConstantIdAttr *CI = D->
getAttr<HLSLVkConstantIdAttr>()) {
786 if (CI->getId() != Id) {
787 Diag(CI->getLocation(), diag::err_hlsl_attribute_param_mismatch) << AL;
788 Diag(AL.
getLoc(), diag::note_conflicting_attribute);
793 HLSLVkConstantIdAttr *
Result =
800 llvm::Triple::EnvironmentType ShaderType) {
801 if (HLSLShaderAttr *NT = D->
getAttr<HLSLShaderAttr>()) {
802 if (NT->getType() != ShaderType) {
803 Diag(NT->getLocation(), diag::err_hlsl_attribute_param_mismatch) << AL;
804 Diag(AL.
getLoc(), diag::note_conflicting_attribute);
808 return HLSLShaderAttr::Create(
getASTContext(), ShaderType, AL);
811HLSLParamModifierAttr *
813 HLSLParamModifierAttr::Spelling Spelling) {
816 if (HLSLParamModifierAttr *PA = D->
getAttr<HLSLParamModifierAttr>()) {
817 if ((PA->isIn() && Spelling == HLSLParamModifierAttr::Keyword_out) ||
818 (PA->isOut() && Spelling == HLSLParamModifierAttr::Keyword_in)) {
819 D->
dropAttr<HLSLParamModifierAttr>();
821 return HLSLParamModifierAttr::Create(
823 HLSLParamModifierAttr::Keyword_inout);
825 Diag(AL.
getLoc(), diag::err_hlsl_duplicate_parameter_modifier) << AL;
826 Diag(PA->getLocation(), diag::note_conflicting_attribute);
833 InterpolationModifier Modifier;
834 switch (
static_cast<HLSLInterpolationModifierAttr::Spelling
>(
836 case HLSLInterpolationModifierAttr::Keyword_nointerpolation:
837 Modifier = InterpolationModifier::NoInterpolation;
839 case HLSLInterpolationModifierAttr::Keyword_linear:
840 Modifier = InterpolationModifier::Linear;
842 case HLSLInterpolationModifierAttr::Keyword_centroid:
843 Modifier = InterpolationModifier::Centroid;
845 case HLSLInterpolationModifierAttr::Keyword_noperspective:
846 Modifier = InterpolationModifier::NoPerspective;
848 case HLSLInterpolationModifierAttr::Keyword_sample:
849 Modifier = InterpolationModifier::Sample;
851 case HLSLInterpolationModifierAttr::Keyword_center:
852 Modifier = InterpolationModifier::Center;
854 case HLSLInterpolationModifierAttr::SpellingNotCalculated:
855 llvm_unreachable(
"interpolation modifier spelling was not calculated");
858 InterpolationModifier Modifiers = Modifier;
860 auto Old =
static_cast<InterpolationModifier
>(
Previous->getModifiers());
862 if (
any(Old & Modifier)) {
863 Diag(AL.
getLoc(), diag::warn_hlsl_duplicate_interpolation) << AL;
864 }
else if (llvm::hlsl::getInterpolationMode(Modifiers) ==
865 llvm::dxbc::PSV::InterpolationMode::Invalid &&
866 llvm::hlsl::getInterpolationMode(Old) !=
867 llvm::dxbc::PSV::InterpolationMode::Invalid) {
868 Diag(AL.
getLoc(), diag::err_hlsl_interpolation_conflict);
869 Diag(
Previous->getLocation(), diag::note_conflicting_attribute);
872 InterpolationModifier OldLocation =
873 llvm::hlsl::getInterpolationSamplingLocation(Old);
874 InterpolationModifier NewLocation =
875 llvm::hlsl::getInterpolationSamplingLocation(Modifier);
876 if (
any(OldLocation) &&
any(NewLocation)) {
877 Diag(AL.
getLoc(), diag::warn_hlsl_interpolation_override)
878 << (std::max(OldLocation, NewLocation) ==
879 InterpolationModifier::Sample)
880 << (std::min(OldLocation, NewLocation) ==
881 InterpolationModifier::Centroid);
884 D->
dropAttr<HLSLInterpolationModifierAttr>();
886 D->
addAttr(HLSLInterpolationModifierAttr::Create(
890bool SemaHLSL::checkInterpolationModifiers(
891 const DeclaratorDecl *D,
const HLSLInterpolationModifierAttr *Inherited,
892 const HLSLParsedSemanticAttr *Semantic) {
895 const auto *A = D->
getAttr<HLSLInterpolationModifierAttr>();
899 Semantic = D->
getAttr<HLSLParsedSemanticAttr>();
901 const auto *FD = dyn_cast<FunctionDecl>(D);
904 if (
T->isDependentType())
906 if (
const auto *RT =
T->getAs<RecordType>()) {
912 Valid &= checkInterpolationModifiers(Field, A, Semantic);
918 auto Modifiers =
static_cast<InterpolationModifier
>(A->getModifiers());
919 if (Modifiers == InterpolationModifier::NoInterpolation) {
923 llvm::hlsl::getSemanticKind(Semantic->getSemanticName());
924 if (Kind != SemanticKind::Position && Kind != SemanticKind::Barycentrics)
926 Diag(A->getLocation(), diag::err_hlsl_interpolation_semantic)
927 << Semantic->getSemanticName();
928 Diag(Semantic->getLocation(), diag::note_conflicting_attribute);
935 Diag(A->getLocation(), diag::err_hlsl_interpolation_type) <<
T;
961 if (HLSLShaderAttr::isValidShaderType(Env) && Env != llvm::Triple::Library) {
962 if (
const auto *Shader = FD->
getAttr<HLSLShaderAttr>()) {
965 if (Shader->getType() != Env) {
966 Diag(Shader->getLocation(), diag::err_hlsl_entry_shader_attr_mismatch)
978 case llvm::Triple::UnknownEnvironment:
979 case llvm::Triple::Library:
981 case llvm::Triple::RootSignature:
982 llvm_unreachable(
"rootsig environment has no functions");
984 llvm_unreachable(
"Unhandled environment in triple");
991 HLSLAppliedSemanticAttr *Semantic,
994 if (D->
hasAttr<HLSLVkBuiltInAttr>())
1000 const auto *ShaderAttr = FD->
getAttr<HLSLShaderAttr>();
1001 assert(ShaderAttr &&
"Entry point has no shader attribute");
1002 llvm::Triple::EnvironmentType ST = ShaderAttr->getType();
1003 SemanticKind Kind = llvm::hlsl::getSemanticKind(Semantic->getSemanticName());
1006 case SemanticKind::Position:
1010 return (ST == llvm::Triple::Vertex && !IsInput) ||
1011 (ST == llvm::Triple::Pixel && IsInput);
1012 case SemanticKind::VertexID:
1014 case SemanticKind::InstanceID:
1015 return ST == llvm::Triple::Vertex && IsInput;
1016 case SemanticKind::IsFrontFace:
1017 return ST == llvm::Triple::Pixel && IsInput;
1018 case SemanticKind::ShadingRate:
1023 return (ST == llvm::Triple::Pixel && IsInput) ||
1024 (ST == llvm::Triple::Vertex && !IsInput);
1025 case SemanticKind::Barycentrics:
1026 case SemanticKind::SampleIndex:
1027 case SemanticKind::PrimitiveID:
1028 return ST == llvm::Triple::Pixel && IsInput;
1029 case SemanticKind::StartVertexLocation:
1030 case SemanticKind::StartInstanceLocation:
1031 return ST == llvm::Triple::Vertex && IsInput;
1032 case SemanticKind::ViewID:
1034 case SemanticKind::StencilRef:
1035 return ST == llvm::Triple::Pixel && !IsInput;
1043 const HLSLVkBuiltInAttr *
Attr,
1044 IOType CurrentIOType) {
1049 StringRef BuiltIn =
Attr->getBuiltIn();
1053 const auto *ShaderAttr = FD->
getAttr<HLSLShaderAttr>();
1054 assert(ShaderAttr &&
"Entry point has no shader attribute");
1055 llvm::Triple::EnvironmentType Stage = ShaderAttr->getType();
1056 bool IsIn =
any(CurrentIOType & IOType::In);
1057 bool IsOut =
any(CurrentIOType & IOType::Out);
1059 if (BuiltIn ==
"PointSize") {
1063 bool Is32BitFloat =
T->isSpecificBuiltinType(BuiltinType::Float) ||
1064 (
T->isSpecificBuiltinType(BuiltinType::Half) &&
1073 bool IsPatchConstantOrPrimitive =
1074 any(CurrentIOType & IOType::PatchConstantOrPrimitive);
1076 !IsPatchConstantOrPrimitive &&
1077 ((Stage == llvm::Triple::Vertex && IsOut) ||
1078 Stage == llvm::Triple::Hull || Stage == llvm::Triple::Domain ||
1079 Stage == llvm::Triple::Geometry ||
1080 (Stage == llvm::Triple::Mesh && IsOut));
1082 StringRef IOTypeName = (IsIn && IsOut) ?
"inputs and outputs"
1086 << BuiltIn << llvm::Triple::getEnvironmentTypeName(Stage)
1092bool SemaHLSL::determineActiveSemanticOnScalar(
FunctionDecl *FD,
1095 SemanticInfo &ActiveSemantic,
1096 SemaHLSL::SemanticContext &SC) {
1097 if (ActiveSemantic.Semantic ==
nullptr) {
1098 ActiveSemantic.Semantic = D->
getAttr<HLSLParsedSemanticAttr>();
1099 if (ActiveSemantic.Semantic)
1100 ActiveSemantic.Index = ActiveSemantic.Semantic->getSemanticIndex();
1103 if (!ActiveSemantic.Semantic) {
1109 HLSLAppliedSemanticAttr(
getASTContext(), *ActiveSemantic.Semantic,
1110 ActiveSemantic.Semantic->getAttrName()->getName(),
1111 ActiveSemantic.Index.value_or(0));
1116 QualType
T = D == FD ? FD->getReturnType() : D->
getType();
1117 const ConstantArrayType *AT =
1120 Diag(A->getLoc(), diag::err_hlsl_semantic_zero_sized_array)
1121 << A->getAttrName();
1129 if (
const auto *MT = BaseTy->
getAs<ConstantMatrixType>())
1132 : MT->getNumColumns();
1134 checkSemanticAnnotation(FD, D, A, SC, ElementCount);
1137 unsigned Location = ActiveSemantic.Index.value_or(0);
1140 any(SC.CurrentIOType & IOType::In));
1142 if (
const auto *BuiltInAttr = D->
getAttr<HLSLVkBuiltInAttr>())
1147 bool HasVkLocation =
false;
1148 if (
auto *A = D->
getAttr<HLSLVkLocationAttr>()) {
1149 HasVkLocation =
true;
1150 Location = A->getLocation();
1153 if (SC.UsesExplicitVkLocations.value_or(HasVkLocation) != HasVkLocation) {
1154 Diag(D->
getLocation(), diag::err_hlsl_semantic_partial_explicit_indexing);
1157 SC.UsesExplicitVkLocations = HasVkLocation;
1160 ActiveSemantic.Index = Location + ElementCount;
1162 StringRef BaseName = ActiveSemantic.Semantic->getAttrName()->getName();
1163 std::string LowerName = BaseName.lower();
1164 for (
unsigned I = 0; I < ElementCount; ++I) {
1165 auto [It, Inserted] = SC.ActiveSemantics.try_emplace(
1166 (Twine(LowerName) + Twine(Location + I)).str(), D->
getLocation());
1169 << (BaseName + Twine(Location + I)).str();
1170 Diag(It->second, diag::note_previous_use);
1178bool SemaHLSL::determineActiveSemantic(
FunctionDecl *FD,
1181 SemanticInfo &ActiveSemantic,
1182 SemaHLSL::SemanticContext &SC) {
1183 if (ActiveSemantic.Semantic ==
nullptr) {
1184 ActiveSemantic.Semantic = D->
getAttr<HLSLParsedSemanticAttr>();
1185 if (ActiveSemantic.Semantic)
1186 ActiveSemantic.Index = ActiveSemantic.Semantic->getSemanticIndex();
1192 const RecordType *RT = dyn_cast<RecordType>(
T);
1194 return determineActiveSemanticOnScalar(FD, OutputDecl, D, ActiveSemantic,
1197 const RecordDecl *RD = RT->getDecl();
1198 for (FieldDecl *Field : RD->
fields()) {
1199 SemanticInfo Info = ActiveSemantic;
1200 if (!determineActiveSemantic(FD, OutputDecl, Field, Info, SC)) {
1201 Diag(
Field->getLocation(), diag::note_hlsl_semantic_used_here) <<
Field;
1204 if (ActiveSemantic.Semantic)
1205 ActiveSemantic = Info;
1212 const auto *ShaderAttr = FD->
getAttr<HLSLShaderAttr>();
1213 assert(ShaderAttr &&
"Entry point has no shader attribute");
1214 llvm::Triple::EnvironmentType ST = ShaderAttr->getType();
1218 case llvm::Triple::Pixel:
1219 case llvm::Triple::Vertex:
1220 case llvm::Triple::Geometry:
1221 case llvm::Triple::Hull:
1222 case llvm::Triple::Domain:
1223 case llvm::Triple::RayGeneration:
1224 case llvm::Triple::Intersection:
1225 case llvm::Triple::AnyHit:
1226 case llvm::Triple::ClosestHit:
1227 case llvm::Triple::Miss:
1228 case llvm::Triple::Callable:
1229 if (
const auto *NT = FD->
getAttr<HLSLNumThreadsAttr>()) {
1230 diagnoseAttrStageMismatch(NT, ST,
1231 {llvm::Triple::Compute,
1232 llvm::Triple::Amplification,
1233 llvm::Triple::Mesh});
1236 if (
const auto *WS = FD->
getAttr<HLSLWaveSizeAttr>()) {
1237 diagnoseAttrStageMismatch(WS, ST,
1238 {llvm::Triple::Compute,
1239 llvm::Triple::Amplification,
1240 llvm::Triple::Mesh});
1245 case llvm::Triple::Compute:
1246 case llvm::Triple::Amplification:
1247 case llvm::Triple::Mesh:
1248 if (!FD->
hasAttr<HLSLNumThreadsAttr>()) {
1250 << llvm::Triple::getEnvironmentTypeName(ST);
1253 if (
const auto *WS = FD->
getAttr<HLSLWaveSizeAttr>()) {
1255 Diag(WS->getLocation(), diag::warn_hlsl_wavesize_unsupported_spirv);
1256 }
else if (Ver < VersionTuple(6, 6)) {
1257 Diag(WS->getLocation(), diag::err_hlsl_attribute_in_wrong_shader_model)
1260 }
else if (WS->getSpelledArgsCount() > 1 && Ver < VersionTuple(6, 8)) {
1263 diag::err_hlsl_attribute_number_arguments_insufficient_shader_model)
1264 << WS << WS->getSpelledArgsCount() <<
"6.8";
1269 case llvm::Triple::RootSignature:
1270 llvm_unreachable(
"rootsig environment has no function entry point");
1272 llvm_unreachable(
"Unhandled environment in triple");
1275 SemaHLSL::SemanticContext InputSC = {};
1276 InputSC.CurrentIOType = IOType::In;
1277 SemaHLSL::SemanticContext OutputSC = {};
1278 OutputSC.CurrentIOType = IOType::Out;
1281 SemanticInfo ActiveSemantic;
1282 ActiveSemantic.Semantic = Param->getAttr<HLSLParsedSemanticAttr>();
1283 if (ActiveSemantic.Semantic)
1284 ActiveSemantic.Index = ActiveSemantic.Semantic->getSemanticIndex();
1288 const auto *MA = Param->getAttr<HLSLParamModifierAttr>();
1289 SemanticContext &SC = MA && MA->isAnyOut() ? OutputSC : InputSC;
1293 if (((ST == llvm::Triple::Pixel && (!MA || MA->isAnyIn())) ||
1294 (ST == llvm::Triple::Vertex && MA && MA->isAnyOut())) &&
1295 !checkInterpolationModifiers(Param,
nullptr,
nullptr))
1298 if (!determineActiveSemantic(FD, Param, Param, ActiveSemantic, SC)) {
1299 Diag(Param->getLocation(), diag::note_previous_decl) << Param;
1304 SemanticInfo ActiveSemantic;
1305 ActiveSemantic.Semantic = FD->
getAttr<HLSLParsedSemanticAttr>();
1306 if (ActiveSemantic.Semantic)
1307 ActiveSemantic.Index = ActiveSemantic.Semantic->getSemanticIndex();
1309 if (ST == llvm::Triple::Vertex &&
1310 !checkInterpolationModifiers(FD,
nullptr,
nullptr))
1312 determineActiveSemantic(FD, FD, FD, ActiveSemantic, OutputSC);
1316void SemaHLSL::checkSemanticAnnotation(
1318 const HLSLAppliedSemanticAttr *SemanticAttr,
const SemanticContext &SC,
1319 unsigned ElementCount) {
1320 auto *ShaderAttr = EntryPoint->
getAttr<HLSLShaderAttr>();
1321 assert(ShaderAttr &&
"Entry point has no shader attribute");
1322 llvm::Triple::EnvironmentType ST = ShaderAttr->getType();
1325 llvm::hlsl::getSemanticKind(SemanticAttr->getSemanticName());
1326 llvm::hlsl::SemanticInterpretation Interpretation =
1327 llvm::hlsl::getInterpretationKind(Kind, ST, SC.CurrentIOType);
1328 if (Interpretation == llvm::hlsl::SemanticInterpretation::Invalid) {
1329 diagnoseSemanticStageMismatch(SemanticAttr, ST, SC.CurrentIOType, Kind);
1335 if (Interpretation == llvm::hlsl::SemanticInterpretation::Arbitrary) {
1336 diagnoseSemanticType(Param, SemanticAttr, SemanticKind::Arbitrary);
1340 diagnoseSystemSemanticIndex(SemanticAttr, Kind, ElementCount);
1341 diagnoseSemanticType(Param, SemanticAttr, Kind);
1342 diagnoseSemanticShaderModel(SemanticAttr, Kind);
1345void SemaHLSL::diagnoseSemanticShaderModel(
const HLSLAppliedSemanticAttr *A,
1348 if (!Triple.isDXIL())
1352 case SemanticKind::Barycentrics:
1353 case SemanticKind::ViewID:
1354 if (Triple.getOSVersion() < VersionTuple(6, 1))
1355 Diag(A->getLoc(), diag::err_hlsl_semantic_in_wrong_shader_model)
1356 << A->getAttrName() <<
"6.1";
1358 case SemanticKind::ShadingRate:
1359 if (Triple.getOSVersion() < VersionTuple(6, 4))
1360 Diag(A->getLoc(), diag::err_hlsl_semantic_in_wrong_shader_model)
1361 << A->getAttrName() <<
"6.4";
1363 case SemanticKind::StartVertexLocation:
1364 case SemanticKind::StartInstanceLocation:
1365 if (Triple.getOSVersion() < VersionTuple(6, 8))
1366 Diag(A->getLoc(), diag::err_hlsl_semantic_in_wrong_shader_model)
1367 << A->getAttrName() <<
"6.8";
1374void SemaHLSL::diagnoseSystemSemanticIndex(
const HLSLAppliedSemanticAttr *A,
1376 unsigned ElementCount) {
1377 assert(Kind != SemanticKind::Invalid && Kind != SemanticKind::Arbitrary &&
1378 "expected a recognized system semantic");
1379 assert(ElementCount > 0 &&
"a semantic covers at least one element");
1382 uint32_t FirstIndex = A->getSemanticIndex();
1384 constexpr uint32_t MaxSemanticIndex = std::numeric_limits<uint32_t>::max();
1385 if (LastIndex > MaxSemanticIndex) {
1386 Diag(A->getLoc(), diag::err_hlsl_semantic_index_out_of_range)
1387 << A->getAttrName() << LastIndex << MaxSemanticIndex;
1395 case SemanticKind::ClipDistance:
1396 case SemanticKind::CullDistance:
1398 case SemanticKind::Target: {
1399 constexpr unsigned MaxTargetIndex = 7;
1400 if (LastIndex > MaxTargetIndex)
1401 Diag(A->getLoc(), diag::err_hlsl_semantic_index_out_of_range)
1402 << A->getAttrName() << LastIndex << MaxTargetIndex;
1406 Diag(A->getLoc(), diag::err_hlsl_semantic_indexing_not_supported)
1407 << A->getAttrName();
1414 return VT->getElementType();
1417 return MT->getElementType();
1423 return VT->getNumElements();
1444void SemaHLSL::diagnoseSemanticType(
const Decl *D,
1445 const HLSLAppliedSemanticAttr *A,
1447 assert(Kind != SemanticKind::Invalid &&
"expected a valid semantic");
1451 if (
const auto *FD = dyn_cast<FunctionDecl>(D))
1457 T =
T.getNonReferenceType();
1460 QualType DeclaredTy =
T;
1462 T = AT->getElementType();
1470 case SemanticKind::Barycentrics:
1472 Diag(A->getLoc(), diag::err_hlsl_semantic_invalid_type)
1473 << A->getAttrName() << 2 << 3
1476 case SemanticKind::DispatchThreadID:
1477 case SemanticKind::GroupID:
1478 case SemanticKind::GroupThreadID:
1480 Diag(A->getLoc(), diag::err_hlsl_semantic_invalid_type)
1481 << A->getAttrName() << 1 << 3
1484 case SemanticKind::StartVertexLocation:
1485 case SemanticKind::StartInstanceLocation:
1486 case SemanticKind::ViewID:
1489 Diag(A->getLoc(), diag::err_hlsl_semantic_invalid_type)
1490 << A->getAttrName() << 0 << 1 << 1
1493 case SemanticKind::GroupIndex:
1495 Diag(A->getLoc(), diag::err_hlsl_semantic_invalid_type)
1496 << A->getAttrName() << 0 << 1 << 1
1499 case SemanticKind::VertexID:
1501 Diag(A->getLoc(), diag::err_hlsl_semantic_invalid_type)
1502 << A->getAttrName() << 0 << 1
1505 case SemanticKind::Position:
1506 case SemanticKind::Target:
1508 Diag(A->getLoc(), diag::err_hlsl_semantic_invalid_type)
1509 << A->getAttrName() << 1 << 4
1512 case SemanticKind::SampleIndex:
1513 case SemanticKind::PrimitiveID:
1514 case SemanticKind::StencilRef:
1518 Diag(A->getLoc(), diag::err_hlsl_semantic_invalid_type)
1519 << A->getAttrName() << 0 << 1
1522 case SemanticKind::InstanceID:
1523 case SemanticKind::ShadingRate:
1530 Diag(A->getLoc(), diag::err_hlsl_semantic_invalid_type)
1531 << A->getAttrName() << 0 << 1
1533 (IsSPIRV ? 4 : 3) << DeclaredTy;
1535 case SemanticKind::IsFrontFace:
1540 Diag(A->getLoc(), diag::err_hlsl_semantic_invalid_type)
1541 << A->getAttrName() << 0 << 1
1555 Diag(A->getLoc(), diag::err_hlsl_semantic_64bit_type)
1556 << A->getAttrName() << DeclaredTy;
1559void SemaHLSL::diagnoseAttrStageMismatch(
1560 const Attr *A, llvm::Triple::EnvironmentType Stage,
1561 std::initializer_list<llvm::Triple::EnvironmentType> AllowedStages) {
1562 SmallVector<StringRef, 8> StageStrings;
1563 llvm::transform(AllowedStages, std::back_inserter(StageStrings),
1564 [](llvm::Triple::EnvironmentType ST) {
1566 HLSLShaderAttr::ConvertEnvironmentTypeToStr(ST));
1568 Diag(A->
getLoc(), diag::err_hlsl_attr_unsupported_in_stage)
1569 << A->
getAttrName() << llvm::Triple::getEnvironmentTypeName(Stage)
1570 << (AllowedStages.size() != 1) <<
join(StageStrings,
", ");
1573void SemaHLSL::diagnoseSemanticStageMismatch(
1574 const Attr *A, llvm::Triple::EnvironmentType Stage, IOType CurrentIOType,
1577 ArrayRef<SemanticStageInfo> Allowed = llvm::hlsl::getAvailableStages(Kind);
1578 auto It = llvm::find_if(Allowed, [&Stage](
const SemanticStageInfo &Info) {
1579 return Info.Stage == Stage;
1582 StringRef CurrentIOTypeName =
"patch constants or primitives";
1583 if (
any(CurrentIOType & IOType::In))
1584 CurrentIOTypeName =
"inputs";
1585 else if (
any(CurrentIOType & IOType::Out))
1586 CurrentIOTypeName =
"outputs";
1589 if (It == Allowed.end()) {
1590 Diag(A->
getLoc(), diag::err_hlsl_semantic_unsupported_iotype_for_stage)
1591 << A->
getAttrName() << llvm::Triple::getEnvironmentTypeName(Stage)
1592 << CurrentIOTypeName;
1596 IOType AllowedIOTypes = It->AllowedIOTypesMask;
1597 if (!(AllowedIOTypes & CurrentIOType)) {
1598 Diag(A->
getLoc(), diag::err_hlsl_semantic_unsupported_iotype_for_stage)
1599 << A->
getAttrName() << llvm::Triple::getEnvironmentTypeName(Stage)
1600 << CurrentIOTypeName;
1605template <CastKind Kind>
1608 Ty = VTy->getElementType();
1613template <CastKind Kind>
1625 if (LHSFloat && RHSFloat) {
1653 if (LHSSigned == RHSSigned) {
1654 if (IsCompAssign || IntOrder >= 0)
1662 if (IntOrder != (LHSSigned ? 1 : -1)) {
1663 if (IsCompAssign || RHSSigned)
1672 if (IsCompAssign || LHSSigned)
1699 return CK_FloatingCast;
1701 return CK_IntegralCast;
1703 return CK_IntegralToFloating;
1705 return CK_FloatingToIntegral;
1711 bool IsCompAssign) {
1718 if (!LVecTy && IsCompAssign) {
1720 RHS =
SemaRef.ImpCastExprToType(RHS.
get(), RElTy, CK_HLSLVectorTruncation);
1722 if (Ctx.hasSameUnqualifiedType(LHSType, RHSType))
1724 RHS =
SemaRef.ImpCastExprToType(RHS.
get(), LHSType,
1729 unsigned EndSz = std::numeric_limits<unsigned>::max();
1732 LSz = EndSz = LVecTy->getNumElements();
1735 assert(EndSz != std::numeric_limits<unsigned>::max() &&
1736 "one of the above should have had a value");
1740 if (IsCompAssign && LSz != EndSz) {
1742 diag::err_hlsl_vector_compound_assignment_truncation)
1743 << LHSType << RHSType;
1749 if (!IsCompAssign && LVecTy && LVecTy->getNumElements() > EndSz)
1754 if (!IsCompAssign && !LVecTy)
1758 if (Ctx.hasSameUnqualifiedType(LHSType, RHSType))
1759 return Ctx.getCommonSugaredType(LHSType, RHSType);
1767 LElTy, RElTy, IsCompAssign);
1770 "HLSL Vectors can only contain integer or floating point types");
1772 LElTy, RElTy, IsCompAssign);
1777 assert((Opc == BO_LOr || Opc == BO_LAnd) &&
1778 "Called with non-logical operator");
1780 llvm::raw_svector_ostream OS(Buff);
1782 StringRef NewFnName = Opc == BO_LOr ?
"or" :
"and";
1783 OS << NewFnName <<
"(";
1793std::pair<IdentifierInfo *, bool>
1796 std::string IdStr =
"__hlsl_rootsig_decl_" + std::to_string(Hash);
1803 return {DeclIdent,
Found};
1814 for (
auto &RootSigElement : RootElements)
1815 Elements.push_back(RootSigElement.getElement());
1819 DeclIdent,
SemaRef.getLangOpts().HLSLRootSigVer, Elements);
1821 SignatureDecl->setImplicit();
1827 if (RootSigOverrideIdent) {
1830 if (
SemaRef.LookupQualifiedName(R, DC))
1831 return dyn_cast<HLSLRootSignatureDecl>(R.getFoundDecl());
1839struct PerVisibilityBindingChecker {
1842 std::array<llvm::hlsl::BindingInfoBuilder, 8> Builders;
1846 llvm::dxbc::ShaderVisibility Vis;
1851 PerVisibilityBindingChecker(
SemaHLSL *S) : S(S) {}
1853 void trackBinding(llvm::dxbc::ShaderVisibility
Visibility,
1854 llvm::dxil::ResourceClass RC,
uint32_t Space,
1856 const hlsl::RootSignatureElement *Elem) {
1858 assert(BuilderIndex < Builders.size() &&
1859 "Not enough builders for visibility type");
1860 Builders[BuilderIndex].trackBinding(RC, Space, LowerBound, UpperBound,
1861 static_cast<const void *
>(Elem));
1863 static_assert(llvm::to_underlying(llvm::dxbc::ShaderVisibility::All) == 0,
1864 "'All' visibility must come first");
1865 if (
Visibility == llvm::dxbc::ShaderVisibility::All)
1866 for (
size_t I = 1, E = Builders.size(); I < E; ++I)
1867 Builders[I].trackBinding(RC, Space, LowerBound, UpperBound,
1868 static_cast<const void *
>(Elem));
1870 ElemInfoMap.push_back({Elem,
Visibility,
false});
1873 ElemInfo &
getInfo(
const hlsl::RootSignatureElement *Elem) {
1874 auto It = llvm::lower_bound(
1876 [](
const auto &LHS,
const auto &RHS) {
return LHS.Elem < RHS; });
1877 assert(It->Elem == Elem &&
"Element not in map");
1881 bool checkOverlap() {
1882 llvm::sort(ElemInfoMap, [](
const auto &LHS,
const auto &RHS) {
1883 return LHS.Elem < RHS.Elem;
1886 bool HadOverlap =
false;
1888 using llvm::hlsl::BindingInfoBuilder;
1889 auto ReportOverlap = [
this,
1890 &HadOverlap](
const BindingInfoBuilder &Builder,
1891 const llvm::hlsl::Binding &Reported) {
1895 static_cast<const hlsl::RootSignatureElement *
>(Reported.Cookie);
1896 const llvm::hlsl::Binding &
Previous = Builder.findOverlapping(Reported);
1897 const auto *PrevElem =
1898 static_cast<const hlsl::RootSignatureElement *
>(
Previous.Cookie);
1900 ElemInfo &Info =
getInfo(Elem);
1905 Info.Diagnosed =
true;
1907 ElemInfo &PrevInfo =
getInfo(PrevElem);
1908 llvm::dxbc::ShaderVisibility CommonVis =
1909 Info.Vis == llvm::dxbc::ShaderVisibility::All ? PrevInfo.Vis
1912 this->S->
Diag(Elem->
getLocation(), diag::err_hlsl_resource_range_overlap)
1913 << llvm::to_underlying(Reported.RC) << Reported.LowerBound
1914 << Reported.isUnbounded() << Reported.UpperBound
1919 this->S->
Diag(PrevElem->getLocation(),
1920 diag::note_hlsl_resource_range_here);
1923 for (BindingInfoBuilder &Builder : Builders)
1924 Builder.calculateBindingInfo(ReportOverlap);
1944 bool HadError =
false;
1945 auto ReportError = [
this, &HadError](
SourceLocation Loc, uint32_t LowerBound,
1946 uint32_t UpperBound) {
1948 this->
Diag(Loc, diag::err_hlsl_invalid_rootsig_value)
1949 << LowerBound << UpperBound;
1956 this->
Diag(Loc, diag::err_hlsl_invalid_rootsig_value)
1957 << llvm::formatv(
"{0:f}", LowerBound).sstr<6>()
1958 << llvm::formatv(
"{0:f}", UpperBound).sstr<6>();
1961 auto VerifyRegister = [ReportError](
SourceLocation Loc, uint32_t Register) {
1962 if (!llvm::hlsl::rootsig::verifyRegisterValue(Register))
1963 ReportError(Loc, 0, 0xfffffffe);
1966 auto VerifySpace = [ReportError](
SourceLocation Loc, uint32_t Space) {
1967 if (!llvm::hlsl::rootsig::verifyRegisterSpace(Space))
1968 ReportError(Loc, 0, 0xffffffef);
1971 const uint32_t Version =
1972 llvm::to_underlying(
SemaRef.getLangOpts().HLSLRootSigVer);
1973 const uint32_t VersionEnum = Version - 1;
1974 auto ReportFlagError = [
this, &HadError, VersionEnum](
SourceLocation Loc) {
1976 this->
Diag(Loc, diag::err_hlsl_invalid_rootsig_flag)
1983 const llvm::hlsl::rootsig::RootElement &Elem = RootSigElem.
getElement();
1984 if (
const auto *Descriptor =
1985 std::get_if<llvm::hlsl::rootsig::RootDescriptor>(&Elem)) {
1986 VerifyRegister(Loc, Descriptor->Reg.Number);
1987 VerifySpace(Loc, Descriptor->Space);
1989 if (!llvm::hlsl::rootsig::verifyRootDescriptorFlag(Version,
1991 ReportFlagError(Loc);
1992 }
else if (
const auto *Constants =
1993 std::get_if<llvm::hlsl::rootsig::RootConstants>(&Elem)) {
1994 VerifyRegister(Loc, Constants->Reg.Number);
1995 VerifySpace(Loc, Constants->Space);
1996 }
else if (
const auto *Sampler =
1997 std::get_if<llvm::hlsl::rootsig::StaticSampler>(&Elem)) {
1998 VerifyRegister(Loc, Sampler->Reg.Number);
1999 VerifySpace(Loc, Sampler->Space);
2002 "By construction, parseFloatParam can't produce a NaN from a "
2003 "float_literal token");
2005 if (!llvm::hlsl::rootsig::verifyMaxAnisotropy(Sampler->MaxAnisotropy))
2006 ReportError(Loc, 0, 16);
2007 if (!llvm::hlsl::rootsig::verifyMipLODBias(Sampler->MipLODBias))
2008 ReportFloatError(Loc, -16.f, 15.99f);
2009 }
else if (
const auto *Clause =
2010 std::get_if<llvm::hlsl::rootsig::DescriptorTableClause>(
2012 VerifyRegister(Loc, Clause->Reg.Number);
2013 VerifySpace(Loc, Clause->Space);
2015 if (!llvm::hlsl::rootsig::verifyNumDescriptors(Clause->NumDescriptors)) {
2019 ReportError(Loc, 1, 0xfffffffe);
2022 if (!llvm::hlsl::rootsig::verifyDescriptorRangeFlag(Version, Clause->Type,
2024 ReportFlagError(Loc);
2028 PerVisibilityBindingChecker BindingChecker(
this);
2029 SmallVector<std::pair<
const llvm::hlsl::rootsig::DescriptorTableClause *,
2034 const llvm::hlsl::rootsig::RootElement &Elem = RootSigElem.
getElement();
2035 if (
const auto *Descriptor =
2036 std::get_if<llvm::hlsl::rootsig::RootDescriptor>(&Elem)) {
2037 uint32_t LowerBound(Descriptor->Reg.Number);
2038 uint32_t UpperBound(LowerBound);
2040 BindingChecker.trackBinding(
2041 Descriptor->Visibility,
2042 static_cast<llvm::dxil::ResourceClass
>(Descriptor->Type),
2043 Descriptor->Space, LowerBound, UpperBound, &RootSigElem);
2044 }
else if (
const auto *Constants =
2045 std::get_if<llvm::hlsl::rootsig::RootConstants>(&Elem)) {
2046 uint32_t LowerBound(Constants->Reg.Number);
2047 uint32_t UpperBound(LowerBound);
2049 BindingChecker.trackBinding(
2050 Constants->Visibility, llvm::dxil::ResourceClass::CBuffer,
2051 Constants->Space, LowerBound, UpperBound, &RootSigElem);
2052 }
else if (
const auto *Sampler =
2053 std::get_if<llvm::hlsl::rootsig::StaticSampler>(&Elem)) {
2054 uint32_t LowerBound(Sampler->Reg.Number);
2055 uint32_t UpperBound(LowerBound);
2057 BindingChecker.trackBinding(
2058 Sampler->Visibility, llvm::dxil::ResourceClass::Sampler,
2059 Sampler->Space, LowerBound, UpperBound, &RootSigElem);
2060 }
else if (
const auto *Clause =
2061 std::get_if<llvm::hlsl::rootsig::DescriptorTableClause>(
2064 UnboundClauses.emplace_back(Clause, &RootSigElem);
2065 }
else if (
const auto *Table =
2066 std::get_if<llvm::hlsl::rootsig::DescriptorTable>(&Elem)) {
2067 assert(UnboundClauses.size() == Table->NumClauses &&
2068 "Number of unbound elements must match the number of clauses");
2069 bool HasAnySampler =
false;
2070 bool HasAnyNonSampler =
false;
2071 uint64_t Offset = 0;
2072 bool IsPrevUnbound =
false;
2073 for (
const auto &[Clause, ClauseElem] : UnboundClauses) {
2075 if (Clause->Type == llvm::dxil::ResourceClass::Sampler)
2076 HasAnySampler =
true;
2078 HasAnyNonSampler =
true;
2080 if (HasAnySampler && HasAnyNonSampler)
2081 Diag(Loc, diag::err_hlsl_invalid_mixed_resources);
2086 if (Clause->NumDescriptors == 0)
2090 Clause->Offset == llvm::hlsl::rootsig::DescriptorTableOffsetAppend;
2092 Offset = Clause->Offset;
2094 uint64_t RangeBound = llvm::hlsl::rootsig::computeRangeBound(
2095 Offset, Clause->NumDescriptors);
2097 if (IsPrevUnbound && IsAppending)
2098 Diag(Loc, diag::err_hlsl_appending_onto_unbound);
2099 else if (!llvm::hlsl::rootsig::verifyNoOverflowedOffset(RangeBound))
2100 Diag(Loc, diag::err_hlsl_offset_overflow) << Offset << RangeBound;
2103 Offset = RangeBound + 1;
2104 IsPrevUnbound = Clause->NumDescriptors ==
2105 llvm::hlsl::rootsig::NumDescriptorsUnbounded;
2108 uint32_t LowerBound(Clause->Reg.Number);
2109 uint32_t UpperBound = llvm::hlsl::rootsig::computeRangeBound(
2110 LowerBound, Clause->NumDescriptors);
2112 BindingChecker.trackBinding(
2114 static_cast<llvm::dxil::ResourceClass
>(Clause->Type), Clause->Space,
2115 LowerBound, UpperBound, ClauseElem);
2117 UnboundClauses.clear();
2121 return BindingChecker.checkOverlap();
2126 Diag(AL.
getLoc(), diag::err_attribute_wrong_number_arguments) << AL << 1;
2131 if (
auto *RS = D->
getAttr<RootSignatureAttr>()) {
2132 if (RS->getSignatureIdent() != Ident) {
2133 Diag(AL.
getLoc(), diag::err_disallowed_duplicate_attribute) << RS;
2137 Diag(AL.
getLoc(), diag::warn_duplicate_attribute_exact) << RS;
2143 if (
auto *SignatureDecl =
2144 dyn_cast<HLSLRootSignatureDecl>(R.getFoundDecl())) {
2151 llvm::VersionTuple SMVersion =
2156 uint32_t ZMax = 1024;
2157 uint32_t ThreadMax = 1024;
2158 if (IsDXIL && SMVersion.getMajor() <= 4) {
2161 }
else if (IsDXIL && SMVersion.getMajor() == 5) {
2171 diag::err_hlsl_numthreads_argument_oor)
2180 diag::err_hlsl_numthreads_argument_oor)
2189 diag::err_hlsl_numthreads_argument_oor)
2194 if (
X * Y * Z > ThreadMax) {
2195 Diag(AL.
getLoc(), diag::err_hlsl_numthreads_invalid) << ThreadMax;
2212 if (SpelledArgsCount == 0 || SpelledArgsCount > 3)
2220 if (SpelledArgsCount > 1 &&
2224 uint32_t Preferred = 0;
2225 if (SpelledArgsCount > 2 &&
2229 if (SpelledArgsCount > 2) {
2232 diag::err_attribute_power_of_two_in_range)
2233 << AL << llvm::dxil::MinWaveSize << llvm::dxil::MaxWaveSize
2238 if (Preferred < Min || Preferred >
Max) {
2240 diag::err_attribute_power_of_two_in_range)
2241 << AL <<
Min <<
Max << Preferred;
2244 }
else if (SpelledArgsCount > 1) {
2247 diag::err_attribute_power_of_two_in_range)
2248 << AL << llvm::dxil::MinWaveSize << llvm::dxil::MaxWaveSize <<
Max;
2252 Diag(AL.
getLoc(), diag::err_attribute_argument_invalid) << AL << 1;
2255 Diag(AL.
getLoc(), diag::warn_attr_min_eq_max) << AL;
2260 diag::err_attribute_power_of_two_in_range)
2261 << AL << llvm::dxil::MinWaveSize << llvm::dxil::MaxWaveSize <<
Min;
2266 HLSLWaveSizeAttr *NewAttr =
2303 uint32_t Binding = 0;
2321 if (
const auto *BuiltIn = D->
getAttr<HLSLVkBuiltInAttr>()) {
2322 Diag(AL.
getLoc(), diag::err_attributes_are_not_compatible)
2325 BuiltIn->isRegularKeywordAttribute());
2326 Diag(BuiltIn->getLocation(), diag::note_conflicting_attribute);
2336 if (!
SemaRef.checkStringLiteralArgumentAttr(AL, 0, BuiltIn, &ArgLoc))
2339 static constexpr StringRef SupportedBuiltIns[] = {
2344 if (!llvm::is_contained(SupportedBuiltIns, BuiltIn)) {
2346 llvm::raw_string_ostream OS(Quoted);
2347 llvm::interleaveComma(SupportedBuiltIns, OS,
2348 [&](StringRef S) { OS <<
"'" << S <<
"'"; });
2349 Diag(ArgLoc, diag::err_hlsl_vk_builtin_unsupported_value)
2350 << BuiltIn << Quoted;
2355 if (
const auto *Location = D->
getAttr<HLSLVkLocationAttr>()) {
2356 Diag(AL.
getLoc(), diag::err_attributes_are_not_compatible)
2359 Location->isRegularKeywordAttribute());
2360 Diag(Location->getLoc(), diag::note_conflicting_attribute);
2368 uint32_t IndexValue(0), ExplicitIndex(0);
2371 assert(0 &&
"HLSLUnparsedSemantic is expected to have 2 int arguments.");
2373 assert(IndexValue > 0 ? ExplicitIndex :
true);
2376 if (Kind == SemanticKind::Invalid) {
2377 Diag(AL.
getLoc(), diag::err_hlsl_unknown_semantic) << AL;
2383 case SemanticKind::RenderTargetArrayIndex:
2384 case SemanticKind::ViewPortArrayIndex:
2385 case SemanticKind::ClipDistance:
2386 case SemanticKind::CullDistance:
2387 case SemanticKind::OutputControlPointID:
2388 case SemanticKind::DomainLocation:
2389 case SemanticKind::GSInstanceID:
2390 case SemanticKind::Coverage:
2391 case SemanticKind::InnerCoverage:
2392 case SemanticKind::Depth:
2393 case SemanticKind::DepthLessEqual:
2394 case SemanticKind::DepthGreaterEqual:
2395 case SemanticKind::TessFactor:
2396 case SemanticKind::InsideTessFactor:
2397 case SemanticKind::CullPrimitive:
2398 Diag(AL.
getLoc(), diag::err_hlsl_unknown_semantic) << AL;
2404 D->
addAttr(HLSLParsedSemanticAttr::Create(
2410 Diag(AL.
getLoc(), diag::err_hlsl_attr_invalid_ast_node)
2411 << AL <<
"shader constant in a constant buffer";
2415 uint32_t SubComponent;
2425 bool IsAggregateTy = (
T->isArrayType() ||
T->isStructureType());
2430 if (IsAggregateTy) {
2431 Diag(AL.
getLoc(), diag::err_hlsl_invalid_register_or_packoffset);
2435 if ((Component * 32 + Size) > 128) {
2436 Diag(AL.
getLoc(), diag::err_hlsl_packoffset_cross_reg_boundary);
2441 EltTy = VT->getElementType();
2443 if (Align > 32 && Component == 1) {
2446 Diag(AL.
getLoc(), diag::err_hlsl_packoffset_alignment_mismatch)
2460 if (!
SemaRef.checkStringLiteralArgumentAttr(AL, 0, Str, &ArgLoc))
2463 llvm::Triple::EnvironmentType ShaderType;
2464 if (!HLSLShaderAttr::ConvertStrToEnvironmentType(Str, ShaderType)) {
2465 Diag(AL.
getLoc(), diag::warn_attribute_type_not_supported)
2466 << AL << Str << ArgLoc;
2480 Expr *SampleCountExpr) {
2481 assert(AttrList.size() &&
"expected list of resource attributes");
2488 HLSLAttributedResourceType::Attributes ResAttrs;
2490 bool HasResourceClass =
false;
2491 bool HasResourceDimension =
false;
2492 for (
const Attr *A : AttrList) {
2497 case attr::HLSLResourceClass: {
2499 if (HasResourceClass) {
2501 ? diag::warn_duplicate_attribute_exact
2502 : diag::warn_duplicate_attribute)
2506 ResAttrs.ResourceClass = RC;
2507 HasResourceClass =
true;
2510 case attr::HLSLResourceDimension: {
2511 llvm::dxil::ResourceDimension RD =
2513 if (HasResourceDimension) {
2515 ? diag::warn_duplicate_attribute_exact
2516 : diag::warn_duplicate_attribute)
2520 ResAttrs.ResourceDimension = RD;
2521 HasResourceDimension =
true;
2524 case attr::HLSLIsROV:
2525 if (ResAttrs.IsROV) {
2529 ResAttrs.IsROV =
true;
2531 case attr::HLSLRawBuffer:
2532 if (ResAttrs.RawBuffer) {
2536 ResAttrs.RawBuffer =
true;
2538 case attr::HLSLIsArray:
2539 if (ResAttrs.IsArray) {
2543 ResAttrs.IsArray =
true;
2545 case attr::HLSLIsMultiSampled:
2546 if (ResAttrs.SampleCountExpr) {
2552 ResAttrs.SampleCountExpr =
2558 case attr::HLSLIsCounter:
2559 if (ResAttrs.IsCounter) {
2563 ResAttrs.IsCounter =
true;
2565 case attr::HLSLContainedType: {
2568 if (!ContainedTy.
isNull()) {
2570 ? diag::warn_duplicate_attribute_exact
2571 : diag::warn_duplicate_attribute)
2580 llvm_unreachable(
"unhandled resource attribute type");
2584 if (!HasResourceClass) {
2585 S.
Diag(AttrList.back()->getRange().getEnd(),
2586 diag::err_hlsl_missing_resource_class);
2591 Wrapped, ContainedTy, ResAttrs);
2593 if (LocInfo && ContainedTyInfo) {
2606 if (!
T->isHLSLResourceType()) {
2607 Diag(AL.
getLoc(), diag::err_hlsl_attribute_needs_intangible_type)
2622 AttributeCommonInfo::AS_CXX11, 0, false ,
2627 case ParsedAttr::AT_HLSLResourceClass: {
2628 StringRef Identifier;
2630 if (!
SemaRef.checkStringLiteralArgumentAttr(AL, 0, Identifier, &ArgLoc))
2635 if (!HLSLResourceClassAttr::ConvertStrToResourceClass(Identifier, RC)) {
2636 Diag(ArgLoc, diag::warn_attribute_type_not_supported)
2637 <<
"ResourceClass" << Identifier;
2640 A = HLSLResourceClassAttr::Create(
getASTContext(), RC, ACI);
2644 case ParsedAttr::AT_HLSLResourceDimension: {
2645 StringRef Identifier;
2647 if (!
SemaRef.checkStringLiteralArgumentAttr(AL, 0, Identifier, &ArgLoc))
2651 llvm::dxil::ResourceDimension RD;
2652 if (!HLSLResourceDimensionAttr::ConvertStrToResourceDimension(Identifier,
2654 Diag(ArgLoc, diag::warn_attribute_type_not_supported)
2655 <<
"ResourceDimension" << Identifier;
2658 A = HLSLResourceDimensionAttr::Create(
getASTContext(), RD, ACI);
2662 case ParsedAttr::AT_HLSLIsROV:
2666 case ParsedAttr::AT_HLSLRawBuffer:
2670 case ParsedAttr::AT_HLSLIsCounter:
2674 case ParsedAttr::AT_HLSLIsArray:
2678 case ParsedAttr::AT_HLSLIsMultiSampled:
2682 case ParsedAttr::AT_HLSLContainedType: {
2684 Diag(AL.
getLoc(), diag::err_attribute_wrong_number_arguments) << AL << 1;
2690 assert(TSI &&
"no type source info for attribute argument");
2692 diag::err_incomplete_type))
2694 A = HLSLContainedTypeAttr::Create(
getASTContext(), TSI, ACI);
2699 llvm_unreachable(
"unhandled HLSL attribute");
2702 HLSLResourcesTypeAttrs.emplace_back(A);
2708 if (!HLSLResourcesTypeAttrs.size())
2714 HLSLResourcesTypeAttrs, QT, &LocInfo)) {
2715 const HLSLAttributedResourceType *RT =
2722 LocsForHLSLAttributedResources.insert(std::pair(RT, LocInfo));
2724 HLSLResourcesTypeAttrs.clear();
2732 auto I = LocsForHLSLAttributedResources.find(RT);
2733 if (I != LocsForHLSLAttributedResources.end()) {
2734 LocInfo = I->second;
2735 LocsForHLSLAttributedResources.erase(I);
2744void SemaHLSL::collectResourceBindingsOnUserRecordDecl(
const VarDecl *VD,
2745 const RecordType *RT) {
2753 "incomplete arrays inside user defined types are not supported");
2762 if (
const HLSLAttributedResourceType *AttrResType =
2763 HLSLAttributedResourceType::findHandleTypeOnResource(Ty)) {
2768 Bindings.addDeclBindingInfo(VD, RC);
2769 }
else if (
const RecordType *RT = dyn_cast<RecordType>(Ty)) {
2775 collectResourceBindingsOnUserRecordDecl(VD, RT);
2787 bool SpecifiedSpace) {
2788 int RegTypeNum =
static_cast<int>(RegType);
2791 if (D->
hasAttr<HLSLGroupSharedAddressSpaceAttr>()) {
2792 S.
Diag(ArgLoc, diag::err_hlsl_binding_type_mismatch) << RegTypeNum;
2797 if (
HLSLBufferDecl *CBufferOrTBuffer = dyn_cast<HLSLBufferDecl>(D)) {
2798 ResourceClass RC = CBufferOrTBuffer->isCBuffer() ? ResourceClass::CBuffer
2799 : ResourceClass::SRV;
2809 assert(
isa<VarDecl>(D) &&
"D is expected to be VarDecl or HLSLBufferDecl");
2813 if (
const HLSLAttributedResourceType *AttrResType =
2814 HLSLAttributedResourceType::findHandleTypeOnResource(
2831 if (SpecifiedSpace && !DeclaredInCOrTBuffer)
2832 S.
Diag(ArgLoc, diag::err_hlsl_space_on_global_constant);
2837 if (RegType == RegisterType::CBuffer)
2838 S.
Diag(ArgLoc, diag::warn_hlsl_deprecated_register_type_b);
2839 else if (RegType != RegisterType::C)
2840 S.
Diag(ArgLoc, diag::err_hlsl_binding_type_mismatch) << RegTypeNum;
2844 if (RegType == RegisterType::C)
2845 S.
Diag(ArgLoc, diag::warn_hlsl_register_type_c_packoffset);
2847 S.
Diag(ArgLoc, diag::err_hlsl_binding_type_mismatch) << RegTypeNum;
2857 S.
Diag(ArgLoc, diag::err_hlsl_binding_type_mismatch) << RegTypeNum;
2865 bool RegisterTypesDetected[5] = {
false};
2866 RegisterTypesDetected[
static_cast<int>(regType)] =
true;
2869 if (HLSLResourceBindingAttr *
attr =
2870 dyn_cast<HLSLResourceBindingAttr>(*it)) {
2873 if (RegisterTypesDetected[
static_cast<int>(otherRegType)]) {
2874 int otherRegTypeNum =
static_cast<int>(otherRegType);
2876 diag::err_hlsl_duplicate_register_annotation)
2880 RegisterTypesDetected[
static_cast<int>(otherRegType)] =
true;
2888 bool SpecifiedSpace) {
2893 "expecting VarDecl or HLSLBufferDecl");
2913 if (StartSlot > Limit)
2917 if (
const auto *AT = dyn_cast<ArrayType>(
T)) {
2920 if (
const auto *CAT = dyn_cast<ConstantArrayType>(AT))
2921 Count = CAT->
getSize().getZExtValue();
2923 QualType ElemTy = AT->getElementType();
2925 ArrayCount * Count);
2929 if (
auto ResTy = dyn_cast<HLSLAttributedResourceType>(
T)) {
2932 if (ResTy->getAttrs().ResourceClass != ResClass)
2936 uint64_t EndSlot = StartSlot + ArrayCount - 1;
2937 if (EndSlot > Limit)
2941 StartSlot = EndSlot + 1;
2946 if (
const auto *RT = dyn_cast<RecordType>(
T)) {
2949 if (
const auto *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
2952 ResClass, Ctx, ArrayCount))
2959 ResClass, Ctx, ArrayCount))
2974 if (SlotNum > Limit)
2979 if (RegTy == RegisterType::C || RegTy == RegisterType::I)
2982 if (
VarDecl *VD = dyn_cast<VarDecl>(TheDecl)) {
2991 return (BaseSlot > Limit);
2998 return (SlotNum > Limit);
3001 llvm_unreachable(
"unexpected decl type");
3005 if (
VarDecl *VD = dyn_cast<VarDecl>(TheDecl)) {
3007 if (
const auto *IAT = dyn_cast<IncompleteArrayType>(Ty))
3008 Ty = IAT->getElementType();
3010 diag::err_incomplete_type))
3014 StringRef Slot =
"";
3015 StringRef Space =
"";
3019 Diag(AL.
getLoc(), diag::err_attribute_argument_type)
3029 Diag(AL.
getLoc(), diag::err_attribute_argument_type)
3035 SpaceLoc = Loc->
getLoc();
3038 if (Str.starts_with(
"space")) {
3040 SpaceLoc = Loc->
getLoc();
3049 std::optional<unsigned> SlotNum;
3050 unsigned SpaceNum = 0;
3053 if (!Slot.empty()) {
3055 Diag(SlotLoc, diag::err_hlsl_binding_type_invalid) << Slot.substr(0, 1);
3058 if (RegType == RegisterType::I) {
3059 Diag(SlotLoc, diag::warn_hlsl_deprecated_register_type_i);
3062 const StringRef SlotNumStr = Slot.substr(1);
3067 if (SlotNumStr.getAsInteger(10, N)) {
3068 Diag(SlotLoc, diag::err_hlsl_unsupported_register_number);
3076 Diag(SlotLoc, diag::err_hlsl_register_number_too_large);
3081 SlotNum = (unsigned)N;
3085 if (!Space.starts_with(
"space")) {
3086 Diag(SpaceLoc, diag::err_hlsl_expected_space) << Space;
3089 StringRef SpaceNumStr = Space.substr(5);
3090 if (SpaceNumStr.getAsInteger(10, SpaceNum)) {
3091 Diag(SpaceLoc, diag::err_hlsl_expected_space) << Space;
3096 if (SlotNum.has_value())
3101 HLSLResourceBindingAttr *NewAttr =
3102 HLSLResourceBindingAttr::Create(
getASTContext(), Slot, Space, AL);
3104 NewAttr->setBinding(RegType, SlotNum, SpaceNum);
3128 while (
const auto *AT = Cur->
getAs<AttributedType>()) {
3130 if (K == attr::HLSLRowMajor || K == attr::HLSLColumnMajor) {
3134 Cur = AT->getModifiedType();
3145 ? attr::HLSLRowMajor
3146 : attr::HLSLColumnMajor;
3150 Diag(AL.
getLoc(), diag::err_hlsl_matrix_layout_non_matrix)
3159 if (ExistingKind == AttrK) {
3160 Diag(AL.
getLoc(), diag::warn_duplicate_attribute_exact)
3162 Diag(AL.
getLoc(), diag::note_previous_attribute);
3166 ExistingKind == attr::HLSLRowMajor ?
"row_major" :
"column_major");
3167 Diag(AL.
getLoc(), diag::err_hlsl_matrix_layout_conflict)
3169 Diag(AL.
getLoc(), diag::note_conflicting_attribute);
3174 if (AttrK == attr::HLSLRowMajor)
3175 return ::new (Ctx) HLSLRowMajorAttr(Ctx, AL);
3176 return ::new (Ctx) HLSLColumnMajorAttr(Ctx, AL);
3187 if (K != attr::HLSLRowMajor && K != attr::HLSLColumnMajor)
3189 if (
T.isNull() ||
T->isDependentType())
3194 K == attr::HLSLRowMajor ?
"row_major" :
"column_major");
3195 Diag(Loc, diag::err_hlsl_matrix_layout_non_matrix) << II;
3203using llvm::dxil::BarrierMemoryTypeFlag;
3204using llvm::dxil::BarrierSemanticFlag;
3206template <
typename T>
constexpr uint64_t barrierFlagValue(
T Flag) {
3207 return llvm::to_underlying(Flag);
3221 bool DiagnoseAvailability;
3248 llvm::DenseMap<const FunctionDecl *, unsigned> ScannedDecls;
3252 llvm::Triple::EnvironmentType CurrentShaderEnvironment;
3253 unsigned CurrentShaderStageBit;
3258 bool ReportOnlyShaderStageIssues;
3261 void SetShaderStageContext(llvm::Triple::EnvironmentType ShaderType) {
3262 static_assert(
sizeof(
unsigned) >= 4);
3263 assert(HLSLShaderAttr::isValidShaderType(ShaderType));
3264 assert((
unsigned)(ShaderType - llvm::Triple::Pixel) < 31 &&
3265 "ShaderType is too big for this bitmap");
3268 unsigned bitmapIndex = ShaderType - llvm::Triple::Pixel;
3269 CurrentShaderEnvironment = ShaderType;
3270 CurrentShaderStageBit = (1 << bitmapIndex);
3273 void SetUnknownShaderStageContext() {
3274 CurrentShaderEnvironment = llvm::Triple::UnknownEnvironment;
3275 CurrentShaderStageBit = (1 << 31);
3278 llvm::Triple::EnvironmentType GetCurrentShaderEnvironment()
const {
3279 return CurrentShaderEnvironment;
3282 bool InUnknownShaderStageContext()
const {
3283 return CurrentShaderEnvironment == llvm::Triple::UnknownEnvironment;
3287 void AddToScannedFunctions(
const FunctionDecl *FD) {
3288 unsigned &ScannedStages = ScannedDecls[FD];
3289 ScannedStages |= CurrentShaderStageBit;
3292 unsigned GetScannedStages(
const FunctionDecl *FD) {
return ScannedDecls[FD]; }
3294 bool WasAlreadyScannedInCurrentStage(
const FunctionDecl *FD) {
3295 return WasAlreadyScannedInCurrentStage(GetScannedStages(FD));
3298 bool WasAlreadyScannedInCurrentStage(
unsigned ScannerStages) {
3299 return ScannerStages & CurrentShaderStageBit;
3302 static bool NeverBeenScanned(
unsigned ScannedStages) {
3303 return ScannedStages == 0;
3307 void HandleFunctionOrMethodRef(FunctionDecl *FD, Expr *RefExpr);
3308 void CheckDeclAvailability(NamedDecl *D,
const AvailabilityAttr *AA,
3310 const AvailabilityAttr *FindAvailabilityAttr(
const Decl *D);
3311 bool HasMatchingEnvironmentOrNone(
const AvailabilityAttr *AA);
3312 void DiagnoseBarrierCall(CallExpr *CE);
3314 bool HasVisibleGroup,
bool IsAllMemory);
3316 bool HasKnownStage,
bool IsAllMemory);
3317 void DiagnoseBarrierGroupSemantic(Expr *SemanticArg,
uint64_t SemanticFlags,
3318 bool HasVisibleGroup);
3319 void DiagnoseBarrierScope(Expr *SemanticArg,
uint64_t MemoryFlags,
3323 DiagnoseHLSLAvailability(Sema &SemaRef,
bool DiagnoseAvailability)
3324 : SemaRef(SemaRef), DiagnoseAvailability(DiagnoseAvailability),
3325 CurrentShaderEnvironment(llvm::Triple::UnknownEnvironment),
3326 CurrentShaderStageBit(0), ReportOnlyShaderStageIssues(
false) {}
3329 void RunOnTranslationUnit(
const TranslationUnitDecl *TU);
3330 void RunOnFunction(
const FunctionDecl *FD);
3332 bool VisitDeclRefExpr(DeclRefExpr *DRE)
override {
3333 FunctionDecl *FD = llvm::dyn_cast<FunctionDecl>(DRE->
getDecl());
3335 HandleFunctionOrMethodRef(FD, DRE);
3339 bool VisitMemberExpr(MemberExpr *ME)
override {
3340 FunctionDecl *FD = llvm::dyn_cast<FunctionDecl>(ME->
getMemberDecl());
3342 HandleFunctionOrMethodRef(FD, ME);
3346 bool VisitCallExpr(CallExpr *CE)
override {
3347 DiagnoseBarrierCall(CE);
3352uint64_t DiagnoseHLSLAvailability::DiagnoseBarrierGroupMemory(
3353 Expr *MemoryArg,
uint64_t MemoryFlags,
bool HasVisibleGroup,
3356 barrierFlagValue(BarrierMemoryTypeFlag::GroupSharedMemory);
3357 if (HasVisibleGroup || (MemoryFlags & GroupSharedMemory) == 0)
3362 diag::err_hlsl_barrier_flag_requires_group)
3367 return MemoryFlags & ~GroupSharedMemory;
3370uint64_t DiagnoseHLSLAvailability::DiagnoseBarrierNodeMemory(
3371 Expr *MemoryArg,
uint64_t MemoryFlags,
bool HasKnownStage,
3374 barrierFlagValue(BarrierMemoryTypeFlag::NodeMemory);
3375 if (!HasKnownStage || (MemoryFlags & NodeMemory) == 0)
3380 diag::err_hlsl_barrier_node_memory_requires_node);
3384 return MemoryFlags & ~NodeMemory;
3387void DiagnoseHLSLAvailability::DiagnoseBarrierGroupSemantic(
3388 Expr *SemanticArg,
uint64_t SemanticFlags,
bool HasVisibleGroup) {
3389 if (HasVisibleGroup ||
3390 (SemanticFlags & barrierFlagValue(BarrierSemanticFlag::GroupFlags)) == 0)
3394 diag::err_hlsl_barrier_flag_requires_group)
3395 << ((SemanticFlags & barrierFlagValue(BarrierSemanticFlag::GroupSync)) !=
3401void DiagnoseHLSLAvailability::DiagnoseBarrierScope(
Expr *SemanticArg,
3404 if (ReportOnlyShaderStageIssues)
3408 barrierFlagValue(BarrierMemoryTypeFlag::UAVMemory) |
3409 barrierFlagValue(BarrierMemoryTypeFlag::NodeInputMemory);
3410 if ((SemanticFlags & barrierFlagValue(BarrierSemanticFlag::DeviceScope)) !=
3412 (MemoryFlags & DeviceScopeMemory) == 0)
3414 diag::err_hlsl_barrier_scope_requires_memory)
3416 if ((SemanticFlags & barrierFlagValue(BarrierSemanticFlag::GroupScope)) !=
3420 diag::err_hlsl_barrier_scope_requires_memory)
3424void DiagnoseHLSLAvailability::DiagnoseBarrierCall(
CallExpr *CE) {
3426 if (!FD || FD->
getBuiltinID() != Builtin::BI__builtin_hlsl_barrier)
3429 const llvm::Triple::EnvironmentType Stage = GetCurrentShaderEnvironment();
3430 const bool HasKnownStage = !InUnknownShaderStageContext();
3431 const bool HasVisibleGroup =
3432 !HasKnownStage || Stage == llvm::Triple::Compute ||
3433 Stage == llvm::Triple::Mesh || Stage == llvm::Triple::Amplification;
3435 uint64_t MemoryFlags = barrierFlagValue(BarrierMemoryTypeFlag::ValidMask);
3438 std::optional<llvm::APSInt>
Value =
3442 MemoryFlags =
Value->getZExtValue();
3443 const bool IsAllMemory =
3444 MemoryFlags == barrierFlagValue(BarrierMemoryTypeFlag::ValidMask);
3446 MemoryFlags = DiagnoseBarrierGroupMemory(MemoryArg, MemoryFlags,
3447 HasVisibleGroup, IsAllMemory);
3448 MemoryFlags = DiagnoseBarrierNodeMemory(MemoryArg, MemoryFlags,
3449 HasKnownStage, IsAllMemory);
3450 }
else if (!HasVisibleGroup) {
3452 diag::err_hlsl_barrier_resource_requires_group);
3457 std::optional<llvm::APSInt>
Value =
3463 DiagnoseBarrierGroupSemantic(SemanticArg, SemanticFlags, HasVisibleGroup);
3466 DiagnoseBarrierScope(SemanticArg, MemoryFlags, SemanticFlags);
3469void DiagnoseHLSLAvailability::HandleFunctionOrMethodRef(
FunctionDecl *FD,
3472 "expected DeclRefExpr or MemberExpr");
3474 if (DiagnoseAvailability)
3475 if (
const AvailabilityAttr *AA = FindAvailabilityAttr(FD))
3476 CheckDeclAvailability(
3481 if (FD->
hasBody(FDWithBody) && !WasAlreadyScannedInCurrentStage(FDWithBody))
3482 DeclsToScan.push_back(FDWithBody);
3485void DiagnoseHLSLAvailability::RunOnTranslationUnit(
3490 llvm::Triple::EnvironmentType::Library;
3499 DeclContextsToScan.push_back(TU);
3501 while (!DeclContextsToScan.empty()) {
3502 const DeclContext *DC = DeclContextsToScan.pop_back_val();
3503 for (
auto &D : DC->
decls()) {
3510 if (llvm::dyn_cast<NamespaceDecl>(D) || llvm::dyn_cast<ExportDecl>(D)) {
3511 DeclContextsToScan.push_back(llvm::dyn_cast<DeclContext>(D));
3516 const FunctionDecl *FD = llvm::dyn_cast<FunctionDecl>(D);
3521 if (HLSLShaderAttr *ShaderAttr = FD->
getAttr<HLSLShaderAttr>()) {
3522 if (!IsLibraryShader && FD->
getName() == EntryName) {
3525 diag::err_hlsl_ambiguous_entry_point)
3527 SemaRef.
Diag(EntryLoc, diag::note_previous_declaration_as)
3533 SetShaderStageContext(ShaderAttr->getType());
3542 for (
const auto *Redecl : FD->
redecls()) {
3543 if (Redecl->isInExportDeclContext()) {
3550 SetUnknownShaderStageContext();
3557 if (!IsLibraryShader && EntryLoc.
isInvalid()) {
3564void DiagnoseHLSLAvailability::RunOnFunction(
const FunctionDecl *FD) {
3565 assert(DeclsToScan.empty() &&
"DeclsToScan should be empty");
3566 DeclsToScan.push_back(FD);
3568 while (!DeclsToScan.empty()) {
3576 const unsigned ScannedStages = GetScannedStages(FD);
3577 if (WasAlreadyScannedInCurrentStage(ScannedStages))
3580 ReportOnlyShaderStageIssues = !NeverBeenScanned(ScannedStages);
3582 AddToScannedFunctions(FD);
3587bool DiagnoseHLSLAvailability::HasMatchingEnvironmentOrNone(
3588 const AvailabilityAttr *AA) {
3593 llvm::Triple::EnvironmentType CurrentEnv = GetCurrentShaderEnvironment();
3594 if (CurrentEnv == llvm::Triple::UnknownEnvironment)
3597 llvm::Triple::EnvironmentType AttrEnv =
3598 AvailabilityAttr::getEnvironmentType(IIEnvironment->
getName());
3600 return CurrentEnv == AttrEnv;
3603const AvailabilityAttr *
3604DiagnoseHLSLAvailability::FindAvailabilityAttr(
const Decl *D) {
3605 AvailabilityAttr
const *PartialMatch =
nullptr;
3609 for (
const auto *A : D->
attrs()) {
3610 if (
const auto *Avail = dyn_cast<AvailabilityAttr>(A)) {
3611 const AvailabilityAttr *EffectiveAvail = Avail->getEffectiveAttr();
3612 StringRef AttrPlatform = EffectiveAvail->getPlatform()->getName();
3613 StringRef TargetPlatform =
3617 if (AttrPlatform == TargetPlatform) {
3619 if (HasMatchingEnvironmentOrNone(EffectiveAvail))
3621 PartialMatch = Avail;
3625 return PartialMatch;
3630void DiagnoseHLSLAvailability::CheckDeclAvailability(
NamedDecl *D,
3631 const AvailabilityAttr *AA,
3650 if (ReportOnlyShaderStageIssues)
3656 if (InUnknownShaderStageContext())
3661 bool EnvironmentMatches = HasMatchingEnvironmentOrNone(AA);
3662 VersionTuple Introduced = AA->getIntroduced();
3671 llvm::StringRef PlatformName(
3674 llvm::StringRef CurrentEnvStr =
3675 llvm::Triple::getEnvironmentTypeName(GetCurrentShaderEnvironment());
3677 llvm::StringRef AttrEnvStr =
3678 AA->getEnvironment() ? AA->getEnvironment()->getName() :
"";
3679 bool UseEnvironment = !AttrEnvStr.empty();
3681 if (EnvironmentMatches) {
3682 SemaRef.
Diag(
Range.getBegin(), diag::warn_hlsl_availability)
3683 <<
Range << D << PlatformName << Introduced.getAsString()
3684 << UseEnvironment << CurrentEnvStr;
3686 SemaRef.
Diag(
Range.getBegin(), diag::warn_hlsl_availability_unavailable)
3690 SemaRef.
Diag(D->
getLocation(), diag::note_partial_availability_specified_here)
3691 << D << PlatformName << Introduced.getAsString()
3693 << UseEnvironment << AttrEnvStr << CurrentEnvStr;
3700 if (!DefaultCBufferDecls.empty()) {
3703 DefaultCBufferDecls);
3706 SemaRef.getCurLexicalContext()->addDecl(DefaultCBuffer);
3710 for (
const Decl *VD : DefaultCBufferDecls) {
3711 const HLSLResourceBindingAttr *RBA =
3712 VD->
getAttr<HLSLResourceBindingAttr>();
3713 if (RBA && RBA->hasRegisterSlot() &&
3714 RBA->getRegisterType() == HLSLResourceBindingAttr::RegisterType::C) {
3721 SemaRef.Consumer.HandleTopLevelDecl(DG);
3723 diagnoseAvailabilityViolations(TU);
3732 "expected member expr to have resource record type or array of them");
3738 const Expr *NonConstIndexExpr =
nullptr;
3741 if (
const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
3742 if (!NonConstIndexExpr)
3750 diag::err_hlsl_resource_member_array_access_not_constant);
3754 if (
const auto *ASE = dyn_cast<ArraySubscriptExpr>(E)) {
3755 const Expr *IdxExpr = ASE->getIdx();
3757 NonConstIndexExpr = IdxExpr;
3759 }
else if (
const auto *SubME = dyn_cast<MemberExpr>(E)) {
3760 E = SubME->getBase();
3761 }
else if (
const auto *ICE = dyn_cast<ImplicitCastExpr>(E)) {
3762 E = ICE->getSubExpr();
3766 llvm_unreachable(
"unexpected expr type in resource member access");
3775 SemaRef.Context.getCanonicalType(
SemaRef.Context.getAddrSpaceQualType(
3778 SemaRef.Context.getLValueReferenceType(AddrSpaceType));
3781 SemaRef.Context.DeclarationNames.getCXXConversionFunctionName(
3785 [[maybe_unused]]
bool LookupSucceeded =
3786 SemaRef.LookupQualifiedName(ConvR, RD);
3787 assert(LookupSucceeded);
3796std::optional<ExprResult>
3799 const HLSLAttributedResourceType *ResTy =
3800 HLSLAttributedResourceType::findHandleTypeOnResource(
3801 BaseType.getTypePtr());
3803 ResTy->getAttrs().ResourceClass != llvm::dxil::ResourceClass::CBuffer)
3804 return std::nullopt;
3806 QualType TemplateType = ResTy->getContainedType();
3810 assert(NamedConversionDecl &&
3811 "Could not find conversion function for ConstantBuffer.");
3812 auto *ConversionDecl =
3815 return SemaRef.BuildCXXMemberCallExpr(BaseExpr, NamedConversionDecl,
3825 const bool DiagnoseAvailability =
3827 TI.
getTriple().getEnvironment() == llvm::Triple::EnvironmentType::Library;
3828 DiagnoseHLSLAvailability(
SemaRef, DiagnoseAvailability)
3829 .RunOnTranslationUnit(TU);
3836 for (
unsigned I = 1, N = TheCall->
getNumArgs(); I < N; ++I) {
3839 S->
Diag(TheCall->
getBeginLoc(), diag::err_vec_builtin_incompatible_vector)
3864 for (
unsigned I = 0; I < TheCall->
getNumArgs(); ++I) {
3877 if (!BaseType->isFloat32Type())
3878 return S->
Diag(Loc, diag::err_builtin_invalid_arg_type)
3879 << ArgOrdinal << 5 << 0
3889 if (!BaseType->isHalfType() && !BaseType->isFloat32Type())
3890 return S->
Diag(Loc, diag::err_builtin_invalid_arg_type)
3891 << ArgOrdinal << 5 << 0
3900 if (!BaseType->isDoubleType()) {
3903 return S->
Diag(Loc, diag::err_builtin_requires_double_type)
3904 << ArgOrdinal << PassedType;
3911 unsigned ArgIndex) {
3912 auto *Arg = TheCall->
getArg(ArgIndex);
3914 if (Arg->IgnoreCasts()->isModifiableLvalue(S->
Context, &OrigLoc) ==
3917 S->
Diag(OrigLoc, diag::error_hlsl_inout_lvalue) << Arg << 0;
3931 << (ArgIndex + 1) << LValueTy;
3941 if (VecTy->getElementType()->isDoubleType())
3942 return S->
Diag(Loc, diag::err_builtin_invalid_arg_type)
3943 << ArgOrdinal << 1 << 0 << 1
3954 return S->
Diag(Loc, diag::err_builtin_invalid_arg_type)
3955 << ArgOrdinal << 5 << 1
3964 if (VecTy->getElementType()->isUnsignedIntegerType())
3967 return S->
Diag(Loc, diag::err_builtin_invalid_arg_type)
3968 << ArgOrdinal << 4 << 3 << 0
3977 return S->
Diag(Loc, diag::err_builtin_invalid_arg_type)
3978 << ArgOrdinal << 5 << 3
3984 unsigned ArgOrdinal,
unsigned Width) {
3987 ArgTy = VTy->getElementType();
3991 if (ElementBitCount != Width) {
3993 diag::err_integer_incorrect_bit_count)
3994 << Width << ElementBitCount;
4005 else if (
auto *MatTyA =
4008 ReturnType, MatTyA->getNumRows(), MatTyA->getNumColumns());
4014 unsigned ArgIndex) {
4023 diag::err_typecheck_expect_scalar_or_vector)
4024 << ArgType << Scalar;
4031 QualType Scalar,
unsigned ArgIndex) {
4042 if (
const auto *VTy = ArgType->getAs<
VectorType>()) {
4055 diag::err_typecheck_expect_scalar_or_vector_or_matrix)
4056 << ArgType << Scalar;
4061 unsigned ArgIndex) {
4066 if (!(ArgType->isScalarType() ||
4067 (VTy && VTy->getElementType()->isScalarType()))) {
4069 diag::err_typecheck_expect_any_scalar_or_vector_or_matrix)
4077 unsigned ArgIndex) {
4080 if (ArgType->isDependentType())
4084 if (
const auto *VectorTy = ArgType->getAs<
VectorType>())
4085 ElementType = VectorTy->getElementType();
4087 ElementType = MatrixTy->getElementType();
4089 if (ElementType->isBooleanType())
4092 if (ElementType->isIntegerType() || ElementType->isRealFloatingType()) {
4094 if (BitWidth == 16 || BitWidth == 32 || BitWidth == 64)
4099 diag::err_typecheck_expect_any_scalar_or_vector_or_matrix)
4107 unsigned ArgIndex) {
4109 assert(ArgIndex < TheCall->getNumArgs());
4117 diag::err_typecheck_expect_any_scalar_or_vector_or_matrix)
4143 diag::err_typecheck_convert_incompatible)
4144 << MaskTy << UInt4Ty << 1 << 0 << 0;
4154 diag::err_typecheck_call_different_arg_types)
4173 Arg1ScalarTy = VTy->getElementType();
4177 Arg2ScalarTy = VTy->getElementType();
4180 S->
Diag(Arg1->
getBeginLoc(), diag::err_hlsl_builtin_scalar_vector_mismatch)
4181 << 1 << TheCall->
getCallee() << Arg1Ty << Arg2Ty;
4191 if (Arg1Length > 0 && Arg0Length != Arg1Length) {
4193 diag::err_typecheck_vector_lengths_not_equal)
4199 if (Arg2Length > 0 && Arg0Length != Arg2Length) {
4201 diag::err_typecheck_vector_lengths_not_equal)
4221 Arg1ScalarTy = MTy->getElementType();
4225 Arg2ScalarTy = MTy->getElementType();
4228 S->
Diag(Arg1->
getBeginLoc(), diag::err_hlsl_builtin_scalar_vector_mismatch)
4229 << 1 << TheCall->
getCallee() << Arg1Ty << Arg2Ty;
4234 unsigned Arg0Cols = Arg0MatTy->getNumColumns();
4236 for (
Expr *Arg : {Arg1, Arg2}) {
4239 (MTy->getNumRows() != Arg0Rows || MTy->getNumColumns() != Arg0Cols)) {
4241 diag::err_typecheck_vector_lengths_not_equal)
4243 << Arg->getSourceRange();
4259 unsigned ArgIndex) {
4264 assert(TheCall->
getNumArgs() > IndexArgIndex &&
"Index argument missing");
4267 unsigned int ActualDim = 1;
4269 ActualDim = VTy->getNumElements();
4270 IndexTy = VTy->getElementType();
4274 diag::err_typecheck_expect_int)
4280 const HLSLAttributedResourceType *ResTy =
4282 assert(ResTy &&
"Resource argument must be a resource");
4283 HLSLAttributedResourceType::Attributes ResAttrs = ResTy->getAttrs();
4285 unsigned int ExpectedDim = 1;
4286 if (ResAttrs.ResourceDimension != llvm::dxil::ResourceDimension::Unknown)
4288 (ResAttrs.IsArray ? 1 : 0);
4290 if (ActualDim != ExpectedDim) {
4292 diag::err_hlsl_builtin_resource_coordinate_dimension_mismatch)
4303 llvm::function_ref<
bool(
const HLSLAttributedResourceType *ResType)> Check =
4307 const HLSLAttributedResourceType *ResTy =
4311 diag::err_typecheck_expect_hlsl_resource)
4315 if (Check && Check(ResTy)) {
4317 diag::err_invalid_hlsl_resource_type)
4327 "expected resource handle type");
4328 auto *MainResType = MainHandleTy->
getAs<HLSLAttributedResourceType>();
4329 auto MainAttrs = MainResType->getAttrs();
4330 assert(!MainAttrs.IsCounter &&
"cannot create a counter from a counter");
4331 MainAttrs.IsCounter =
true;
4333 MainResType->getContainedType(),
4344 return "SampleBias";
4346 return "SampleGrad";
4348 return "SampleLevel";
4352 return "SampleCmpLevelZero";
4354 llvm_unreachable(
"Invalid SampleKind");
4364 if (!MD || !MD->getDeclName().isIdentifier())
4371 return MD->getName();
4379 StringRef DefaultName) {
4384 S.
Diag(TheCall->
getBeginLoc(), diag::err_hlsl_sample_double_element_type)
4411 if (SMVersion >= VersionTuple(6, 7))
4414 S.
Diag(TheCall->
getBeginLoc(), diag::err_hlsl_sample_integer_element_type)
4416 << ContainedType << SMVersion.getAsString();
4421 bool IncludeArraySlice =
true) {
4424 [](
const HLSLAttributedResourceType *ResType) {
4425 return ResType->getAttrs().ResourceDimension ==
4426 llvm::dxil::ResourceDimension::Unknown;
4432 [](
const HLSLAttributedResourceType *ResType) {
4433 return ResType->getAttrs().ResourceClass !=
4434 llvm::hlsl::ResourceClass::Sampler;
4442 unsigned ExpectedDim =
4444 (IncludeArraySlice && ResourceTy->getAttrs().IsArray ? 1 : 0);
4473 unsigned NextIdx = 3;
4485 Expr *ComponentArg = TheCall->
getArg(NextIdx);
4489 std::optional<llvm::APSInt> ComponentOpt =
4492 int64_t ComponentVal = ComponentOpt->getSExtValue();
4493 if (ComponentVal != 0) {
4496 assert(ComponentVal >= 0 && ComponentVal <= 3 &&
4497 "The component is not in the expected range.");
4499 diag::err_hlsl_gathercmp_invalid_component)
4509 const HLSLAttributedResourceType *ResourceTy =
4512 unsigned ExpectedDim =
4515 &S, TheCall->
getArg(NextIdx),
4521 assert(ResourceTy->hasContainedType() &&
4522 "Expecting a contained type for resource with a dimension "
4524 QualType ReturnType = ResourceTy->getContainedType();
4527 IsCmp ?
"GatherCmp" :
"Gather"))
4532 S.
Diag(TheCall->
getBeginLoc(), diag::err_hlsl_samplecmp_requires_float);
4538 ReturnType = VecTy->getElementType();
4551 [](
const HLSLAttributedResourceType *ResType) {
4552 return ResType->getAttrs().ResourceDimension ==
4553 llvm::dxil::ResourceDimension::Unknown;
4563 ResourceTy->getAttrs().ResourceClass == llvm::dxil::ResourceClass::UAV;
4570 unsigned ResourceDim =
4572 unsigned LocationDim = ResourceDim + (ResourceTy->getAttrs().IsArray ? 1 : 0);
4588 TheCall->
setType(ResourceTy->getContainedType());
4598 [](
const HLSLAttributedResourceType *ResType) {
4599 return !ResType->isMultiSampled();
4608 unsigned ResourceDim =
4610 unsigned LocationDim = ResourceDim + (ResourceTy->getAttrs().IsArray ? 1 : 0);
4628 TheCall->
setType(ResourceTy->getContainedType());
4633 unsigned MinArgs, MaxArgs;
4661 const HLSLAttributedResourceType *ResourceTy =
4663 unsigned ExpectedDim =
4666 unsigned NextIdx = 3;
4691 &S, TheCall->
getArg(NextIdx),
4704 assert(ResourceTy->hasContainedType() &&
4705 "Expecting a contained type for resource with a dimension "
4707 QualType ReturnType = ResourceTy->getContainedType();
4718 S.
Diag(TheCall->
getBeginLoc(), diag::err_hlsl_samplecmp_requires_float);
4735 unsigned MinArgs,
unsigned MaxArgs,
4737 bool ReportsOriginalValue) {
4738 if (MinArgs == MaxArgs) {
4741 }
else if (TheCall->
getNumArgs() < MinArgs) {
4742 S.
Diag(TheCall->
getEndLoc(), diag::err_typecheck_call_too_few_args_at_least)
4752 const bool DestIsOK =
4758 diag::err_builtin_invalid_arg_type)
4772 TI.
getTriple().getArch() == llvm::Triple::dxil &&
4788 for (
unsigned I = 1, E = TheCall->
getNumArgs(); I != E; ++I)
4794 const unsigned NumArgs = TheCall->
getNumArgs();
4795 if (ReportsOriginalValue && NumArgs == MaxArgs &&
4806 switch (BuiltinID) {
4807 case Builtin::BI__builtin_hlsl_barrier: {
4808 if (
SemaRef.checkArgCount(TheCall, 2))
4811 if (
SemaRef.Context.getTargetInfo().getTriple().getArch() !=
4812 llvm::Triple::dxil) {
4820 std::optional<llvm::APSInt> MemoryFlags =
4824 diag::err_constant_integer_arg_type)
4828 if ((MemoryFlags->getZExtValue() &
4829 ~barrierFlagValue(BarrierMemoryTypeFlag::ValidMask)) != 0) {
4831 diag::err_hlsl_invalid_barrier_memory_flags);
4835 const HLSLAttributedResourceType *ResTy =
4836 HLSLAttributedResourceType::findHandleTypeOnResource(
4840 diag::err_typecheck_expect_hlsl_resource)
4844 if (ResTy->getAttrs().ResourceClass != ResourceClass::UAV) {
4846 diag::err_invalid_hlsl_resource_type)
4853 std::optional<llvm::APSInt> SemanticFlags =
4855 if (!SemanticFlags) {
4857 diag::err_constant_integer_arg_type)
4861 if ((SemanticFlags->getZExtValue() &
4862 ~barrierFlagValue(BarrierSemanticFlag::ValidMask)) != 0) {
4864 diag::err_hlsl_invalid_barrier_semantic_flags);
4871 case Builtin::BI__builtin_hlsl_adduint64: {
4872 if (
SemaRef.checkArgCount(TheCall, 2))
4886 if (NumElementsArg != 2 && NumElementsArg != 4) {
4888 << 1 << 64 << NumElementsArg * 32;
4902 case Builtin::BI__builtin_hlsl_resource_getpointer: {
4903 if (
SemaRef.checkArgCountRange(TheCall, 1, 2) ||
4910 QualType ContainedTy = ResourceTy->getContainedType();
4911 auto ReturnType =
SemaRef.Context.getAddrSpaceQualType(
4914 ReturnType =
SemaRef.Context.getPointerType(ReturnType);
4919 case Builtin::BI__builtin_hlsl_resource_getpointer_typed: {
4920 if (
SemaRef.checkArgCount(TheCall, 3) ||
4927 "expected pointer type for second argument");
4934 diag::err_invalid_use_of_array_type);
4938 auto ReturnType =
SemaRef.Context.getAddrSpaceQualType(
4941 ReturnType =
SemaRef.Context.getPointerType(ReturnType);
4946 case Builtin::BI__builtin_hlsl_transpose_if_memory_is_row_major: {
4947 if (
SemaRef.checkArgCount(TheCall, 2) ||
4949 SemaRef.getASTContext().IntTy))
4956 case Builtin::BI__builtin_hlsl_resource_load_with_status: {
4957 if (
SemaRef.checkArgCount(TheCall, 3) ||
4960 SemaRef.getASTContext().UnsignedIntTy) ||
4962 SemaRef.getASTContext().UnsignedIntTy) ||
4968 QualType ReturnType = ResourceTy->getContainedType();
4973 case Builtin::BI__builtin_hlsl_resource_load_with_status_typed: {
4974 if (
SemaRef.checkArgCount(TheCall, 4) ||
4977 SemaRef.getASTContext().UnsignedIntTy) ||
4979 SemaRef.getASTContext().UnsignedIntTy) ||
4985 "expected pointer type for second argument");
4992 diag::err_invalid_use_of_array_type);
4998 case Builtin::BI__builtin_hlsl_resource_load_level:
5000 case Builtin::BI__builtin_hlsl_resource_load_ms:
5002 case Builtin::BI__builtin_hlsl_resource_sample:
5004 case Builtin::BI__builtin_hlsl_resource_sample_bias:
5006 case Builtin::BI__builtin_hlsl_resource_sample_grad:
5008 case Builtin::BI__builtin_hlsl_resource_sample_level:
5010 case Builtin::BI__builtin_hlsl_resource_sample_cmp:
5012 case Builtin::BI__builtin_hlsl_resource_sample_cmp_level_zero:
5014 case Builtin::BI__builtin_hlsl_resource_calculate_lod:
5015 case Builtin::BI__builtin_hlsl_resource_calculate_lod_unclamped:
5017 case Builtin::BI__builtin_hlsl_resource_gather:
5019 case Builtin::BI__builtin_hlsl_resource_gather_cmp:
5021 case Builtin::BI__builtin_hlsl_resource_uninitializedhandle: {
5022 assert(TheCall->
getNumArgs() == 1 &&
"expected 1 arg");
5028 case Builtin::BI__builtin_hlsl_resource_handlefrombinding: {
5029 assert(TheCall->
getNumArgs() == 6 &&
"expected 6 args");
5035 case Builtin::BI__builtin_hlsl_resource_handlefromimplicitbinding: {
5036 assert(TheCall->
getNumArgs() == 6 &&
"expected 6 args");
5042 case Builtin::BI__builtin_hlsl_resource_counterhandlefromimplicitbinding: {
5043 assert(TheCall->
getNumArgs() == 3 &&
"expected 3 args");
5049 TheCall->
setType(CounterHandleTy);
5052 case Builtin::BI__builtin_hlsl_resource_handlefromheap: {
5053 if (
SemaRef.checkArgCount(TheCall, 2) ||
5056 SemaRef.getASTContext().UnsignedIntTy))
5064 case Builtin::BI__builtin_hlsl_resource_counterhandlefromheap: {
5065 if (
SemaRef.checkArgCount(TheCall, 1) ||
5073 TheCall->
setType(CounterHandleTy);
5076 case Builtin::BI__builtin_hlsl_and:
5077 case Builtin::BI__builtin_hlsl_or: {
5078 if (
SemaRef.checkArgCount(TheCall, 2))
5092 case Builtin::BI__builtin_hlsl_asdouble: {
5093 if (
SemaRef.checkArgCount(TheCall, 2))
5097 SemaRef.Context.UnsignedIntTy,
5102 SemaRef.Context.UnsignedIntTy,
5111 case Builtin::BI__builtin_hlsl_elementwise_clamp: {
5112 if (
SemaRef.BuiltinElementwiseTernaryMath(
5118 case Builtin::BI__builtin_hlsl_dot: {
5120 if (
SemaRef.BuiltinVectorToScalarMath(TheCall))
5126 case Builtin::BI__builtin_hlsl_elementwise_firstbithigh:
5127 case Builtin::BI__builtin_hlsl_elementwise_firstbitlow: {
5128 if (
SemaRef.PrepareBuiltinElementwiseMathOneArgCall(TheCall))
5138 EltTy = VecTy->getElementType();
5139 ResTy =
SemaRef.Context.getExtVectorType(ResTy, VecTy->getNumElements());
5152 case Builtin::BI__builtin_hlsl_select: {
5153 if (
SemaRef.checkArgCount(TheCall, 3))
5162 if (VTy && VTy->getElementType()->isBooleanType() &&
5166 if (MTy && MTy->getElementType()->isBooleanType() &&
5171 case Builtin::BI__builtin_hlsl_elementwise_saturate:
5172 case Builtin::BI__builtin_hlsl_elementwise_rcp: {
5173 if (
SemaRef.checkArgCount(TheCall, 1))
5179 diag::err_builtin_invalid_arg_type)
5182 if (
SemaRef.PrepareBuiltinElementwiseMathOneArgCall(TheCall))
5186 case Builtin::BI__builtin_hlsl_elementwise_rsqrt:
5187 case Builtin::BI__builtin_hlsl_elementwise_frac:
5188 case Builtin::BI__builtin_hlsl_elementwise_ddx_coarse:
5189 case Builtin::BI__builtin_hlsl_elementwise_ddy_coarse:
5190 case Builtin::BI__builtin_hlsl_elementwise_ddx_fine:
5191 case Builtin::BI__builtin_hlsl_elementwise_ddy_fine: {
5192 if (
SemaRef.checkArgCount(TheCall, 1))
5197 if (
SemaRef.PrepareBuiltinElementwiseMathOneArgCall(TheCall))
5201 case Builtin::BI__builtin_hlsl_elementwise_isfinite:
5202 case Builtin::BI__builtin_hlsl_elementwise_isinf:
5203 case Builtin::BI__builtin_hlsl_elementwise_isnan: {
5204 if (
SemaRef.checkArgCount(TheCall, 1))
5209 if (
SemaRef.PrepareBuiltinElementwiseMathOneArgCall(TheCall))
5214 case Builtin::BI__builtin_hlsl_mad: {
5215 if (
SemaRef.BuiltinElementwiseTernaryMath(
5221 case Builtin::BI__builtin_hlsl_mul: {
5222 if (
SemaRef.checkArgCount(TheCall, 2))
5232 return VTy->getElementType();
5234 return MTy->getElementType();
5238 QualType EltTy0 = getElemType(Ty0);
5247 if (IsVec0 && IsMat1) {
5250 }
else if (IsMat0 && IsVec1) {
5254 assert(IsMat0 && IsMat1);
5264 case Builtin::BI__builtin_elementwise_fma: {
5265 if (
SemaRef.checkArgCount(TheCall, 3) ||
5280 case Builtin::BI__builtin_hlsl_transpose: {
5281 if (
SemaRef.checkArgCount(TheCall, 1))
5290 << 1 << 3 << 0 << 0 << ArgTy;
5295 MatTy->getElementType(), MatTy->getNumColumns(), MatTy->getNumRows());
5299 case Builtin::BI__builtin_hlsl_elementwise_sign: {
5300 if (
SemaRef.PrepareBuiltinElementwiseMathOneArgCall(TheCall))
5308 case Builtin::BI__builtin_hlsl_wave_active_all_equal: {
5309 if (
SemaRef.checkArgCount(TheCall, 1))
5323 unsigned NumElts = VecTy->getNumElements();
5333 case Builtin::BI__builtin_hlsl_wave_active_max:
5334 case Builtin::BI__builtin_hlsl_wave_active_min:
5335 case Builtin::BI__builtin_hlsl_wave_active_sum:
5336 case Builtin::BI__builtin_hlsl_wave_active_product: {
5337 if (
SemaRef.checkArgCount(TheCall, 1))
5350 case Builtin::BI__builtin_hlsl_wave_active_bit_or:
5351 case Builtin::BI__builtin_hlsl_wave_active_bit_xor:
5352 case Builtin::BI__builtin_hlsl_wave_active_bit_and: {
5353 if (
SemaRef.checkArgCount(TheCall, 1))
5368 (VTy && VTy->getElementType()->isIntegerType()))) {
5370 diag::err_builtin_invalid_arg_type)
5371 << ArgTyExpr <<
SemaRef.Context.UnsignedIntTy << 1 << 0 << 0;
5379 case Builtin::BI__builtin_hlsl_interlocked_add:
5380 case Builtin::BI__builtin_hlsl_interlocked_and:
5381 case Builtin::BI__builtin_hlsl_interlocked_max:
5382 case Builtin::BI__builtin_hlsl_interlocked_min:
5383 case Builtin::BI__builtin_hlsl_interlocked_or:
5384 case Builtin::BI__builtin_hlsl_interlocked_xor:
5390 case Builtin::BI__builtin_hlsl_interlocked_exchange:
5396 case Builtin::BI__builtin_hlsl_interlocked_compare_store:
5402 case Builtin::BI__builtin_hlsl_interlocked_compare_store_float_bitwise:
5408 case Builtin::BI__builtin_hlsl_interlocked_compare_exchange:
5414 case Builtin::BI__builtin_hlsl_interlocked_compare_exchange_float_bitwise:
5422 case Builtin::BI__builtin_elementwise_bitreverse: {
5430 case Builtin::BI__builtin_hlsl_wave_prefix_count_bits:
5431 case Builtin::BI__builtin_hlsl_wave_multi_prefix_count_bits: {
5432 bool IsMultiPrefix =
5433 BuiltinID == Builtin::BI__builtin_hlsl_wave_multi_prefix_count_bits;
5434 if (
SemaRef.checkArgCount(TheCall, IsMultiPrefix ? 2 : 1))
5439 if (!(
ArgType->isScalarType())) {
5441 diag::err_typecheck_expect_any_scalar_or_vector_or_matrix)
5446 if (!(
ArgType->isBooleanType())) {
5448 diag::err_typecheck_expect_any_scalar_or_vector_or_matrix)
5453 if (IsMultiPrefix) {
5461 diag::err_builtin_target_unsupported)
5469 case Builtin::BI__builtin_hlsl_wave_read_lane_at: {
5470 if (
SemaRef.checkArgCount(TheCall, 2))
5478 diag::err_typecheck_convert_incompatible)
5479 << ArgTyIndex <<
SemaRef.Context.UnsignedIntTy << 1 << 0 << 0;
5492 case Builtin::BI__builtin_hlsl_wave_read_lane_first: {
5493 if (
SemaRef.checkArgCount(TheCall, 1))
5502 case Builtin::BI__builtin_hlsl_wave_get_lane_index: {
5503 if (
SemaRef.checkArgCount(TheCall, 0))
5507 case Builtin::BI__builtin_hlsl_wave_prefix_sum:
5508 case Builtin::BI__builtin_hlsl_wave_prefix_product: {
5509 if (
SemaRef.checkArgCount(TheCall, 1))
5522 case Builtin::BI__builtin_hlsl_wave_multi_prefix_bit_and:
5523 case Builtin::BI__builtin_hlsl_wave_multi_prefix_bit_or:
5524 case Builtin::BI__builtin_hlsl_wave_multi_prefix_bit_xor:
5525 case Builtin::BI__builtin_hlsl_wave_multi_prefix_product:
5526 case Builtin::BI__builtin_hlsl_wave_multi_prefix_sum: {
5527 if (
SemaRef.checkArgCount(TheCall, 2))
5537 BuiltinID == Builtin::BI__builtin_hlsl_wave_multi_prefix_product ||
5538 BuiltinID == Builtin::BI__builtin_hlsl_wave_multi_prefix_sum;
5543 diag::err_builtin_invalid_arg_type)
5544 << 1 << (ValueTy->
isMatrixType() ? 3 : 5) << 1 << IsArithmetic
5555 case Builtin::BI__builtin_hlsl_quad_read_across_x:
5556 case Builtin::BI__builtin_hlsl_quad_read_across_y:
5557 case Builtin::BI__builtin_hlsl_quad_read_across_diagonal: {
5558 if (
SemaRef.checkArgCount(TheCall, 1))
5570 case Builtin::BI__builtin_hlsl_elementwise_splitdouble: {
5571 if (
SemaRef.checkArgCount(TheCall, 3))
5577 SemaRef.Context.UnsignedIntTy, 1) ||
5579 SemaRef.Context.UnsignedIntTy, 2))
5587 case Builtin::BI__builtin_hlsl_elementwise_clip: {
5588 if (
SemaRef.checkArgCount(TheCall, 1))
5595 case Builtin::BI__builtin_elementwise_acos:
5596 case Builtin::BI__builtin_elementwise_asin:
5597 case Builtin::BI__builtin_elementwise_atan:
5598 case Builtin::BI__builtin_elementwise_atan2:
5599 case Builtin::BI__builtin_elementwise_ceil:
5600 case Builtin::BI__builtin_elementwise_cos:
5601 case Builtin::BI__builtin_elementwise_cosh:
5602 case Builtin::BI__builtin_elementwise_exp:
5603 case Builtin::BI__builtin_elementwise_exp2:
5604 case Builtin::BI__builtin_elementwise_exp10:
5605 case Builtin::BI__builtin_elementwise_floor:
5606 case Builtin::BI__builtin_elementwise_fmod:
5607 case Builtin::BI__builtin_elementwise_log:
5608 case Builtin::BI__builtin_elementwise_log2:
5609 case Builtin::BI__builtin_elementwise_log10:
5610 case Builtin::BI__builtin_elementwise_pow:
5611 case Builtin::BI__builtin_elementwise_roundeven:
5612 case Builtin::BI__builtin_elementwise_sin:
5613 case Builtin::BI__builtin_elementwise_sinh:
5614 case Builtin::BI__builtin_elementwise_sqrt:
5615 case Builtin::BI__builtin_elementwise_tan:
5616 case Builtin::BI__builtin_elementwise_tanh:
5617 case Builtin::BI__builtin_elementwise_trunc: {
5623 case Builtin::BI__builtin_hlsl_buffer_update_counter: {
5624 assert(TheCall->
getNumArgs() == 2 &&
"expected 2 args");
5625 auto checkResTy = [](
const HLSLAttributedResourceType *ResTy) ->
bool {
5626 return !(ResTy->getAttrs().ResourceClass == ResourceClass::UAV &&
5627 ResTy->getAttrs().RawBuffer && ResTy->hasContainedType());
5632 std::optional<llvm::APSInt> Offset =
5634 if (!Offset.has_value() ||
std::abs(Offset->getExtValue()) != 1) {
5636 diag::err_hlsl_expect_arg_const_int_one_or_neg_one)
5642 case Builtin::BI__builtin_hlsl_elementwise_f16tof32: {
5643 if (
SemaRef.checkArgCount(TheCall, 1))
5654 ArgTy = VTy->getElementType();
5657 diag::err_builtin_invalid_arg_type)
5666 case Builtin::BI__builtin_hlsl_elementwise_f32tof16: {
5667 if (
SemaRef.checkArgCount(TheCall, 1))
5675 case Builtin::BI__builtin_hlsl_isdebuggingenabled: {
5678 diag::err_builtin_target_unsupported);
5690 WorkList.push_back(BaseTy);
5691 while (!WorkList.empty()) {
5693 T =
T.getCanonicalType().getUnqualifiedType();
5694 if (
const auto *AT = dyn_cast<ConstantArrayType>(
T)) {
5702 for (
uint64_t Ct = 0; Ct < AT->getZExtSize(); ++Ct)
5703 llvm::append_range(List, ElementFields);
5708 if (
const auto *VT = dyn_cast<VectorType>(
T)) {
5709 List.insert(List.end(), VT->getNumElements(), VT->getElementType());
5712 if (
const auto *MT = dyn_cast<ConstantMatrixType>(
T)) {
5713 List.insert(List.end(), MT->getNumElementsFlattened(),
5714 MT->getElementType());
5717 if (
const auto *RD =
T->getAsCXXRecordDecl()) {
5718 if (RD->isStandardLayout())
5719 RD = RD->getStandardLayoutBaseWithFields();
5723 if (RD->
isUnion() || !RD->isAggregate()) {
5729 for (
const auto *FD : RD->
fields())
5730 if (!FD->isUnnamedBitField())
5731 FieldTypes.push_back(FD->
getType());
5733 std::reverse(FieldTypes.begin(), FieldTypes.end());
5734 llvm::append_range(WorkList, FieldTypes);
5738 if (!RD->isStandardLayout()) {
5740 for (
const auto &
Base : RD->bases())
5741 FieldTypes.push_back(
Base.getType());
5742 std::reverse(FieldTypes.begin(), FieldTypes.end());
5743 llvm::append_range(WorkList, FieldTypes);
5778 if (
SemaRef.Context.getTypeSize(QT) / 8 > 16)
5784 int ArraySize = VT->getNumElements();
5789 QualType ElTy = VT->getElementType();
5793 if (
SemaRef.Context.getTypeSize(QT) / 8 > 16)
5809 if (
SemaRef.getASTContext().hasSameType(T1, T2))
5818 return llvm::equal(T1Types, T2Types,
5820 return SemaRef.IsLayoutCompatible(LHS, RHS);
5829 bool HadError =
false;
5831 for (
unsigned i = 0, e =
New->getNumParams(); i != e; ++i) {
5839 const auto *NDAttr = NewParam->
getAttr<HLSLParamModifierAttr>();
5840 unsigned NSpellingIdx = (NDAttr ? NDAttr->getSpellingListIndex() : 0);
5841 const auto *ODAttr = OldParam->
getAttr<HLSLParamModifierAttr>();
5842 unsigned OSpellingIdx = (ODAttr ? ODAttr->getSpellingListIndex() : 0);
5844 if (NSpellingIdx != OSpellingIdx) {
5846 diag::err_hlsl_param_qualifier_mismatch)
5847 << NDAttr << NewParam;
5863 if (
SemaRef.getASTContext().hasSameUnqualifiedType(SrcTy, DestTy))
5878 llvm_unreachable(
"HLSL doesn't support pointers.");
5881 llvm_unreachable(
"HLSL doesn't support complex types.");
5883 llvm_unreachable(
"HLSL doesn't support fixed point types.");
5885 llvm_unreachable(
"Should have returned before this");
5895 llvm_unreachable(
"HLSL doesn't support complex types.");
5897 llvm_unreachable(
"HLSL doesn't support fixed point types.");
5902 llvm_unreachable(
"HLSL doesn't support pointers.");
5904 llvm_unreachable(
"Should have returned before this");
5910 llvm_unreachable(
"HLSL doesn't support pointers.");
5913 llvm_unreachable(
"HLSL doesn't support fixed point types.");
5917 llvm_unreachable(
"HLSL doesn't support complex types.");
5920 llvm_unreachable(
"Unhandled scalar cast");
5941 !(SrcMatTy && SrcMatTy->getNumElementsFlattened() == 1))
5947 SrcTy = SrcMatTy->getElementType();
5952 for (
unsigned I = 0, Size = DestTypes.size(); I < Size; ++I) {
5953 if (DestTypes[I]->isUnionType())
5985 if (SrcTypes.size() < DestTypes.size())
5988 unsigned SrcSize = SrcTypes.size();
5989 unsigned DstSize = DestTypes.size();
5991 for (I = 0; I < DstSize && I < SrcSize; I++) {
5992 if (SrcTypes[I]->isUnionType() || DestTypes[I]->isUnionType())
6000 for (; I < SrcSize; I++) {
6001 if (SrcTypes[I]->isUnionType())
6044 tok::equal, ArgOpV, OpV);
6056 assert(Param->hasAttr<HLSLParamModifierAttr>() &&
6057 "We should not get here without a parameter modifier expression");
6058 const auto *
Attr = Param->getAttr<HLSLParamModifierAttr>();
6065 << Arg << (IsInOut ? 1 : 0);
6069 QualType Ty = Param->getType().getNonLValueExprType(Ctx);
6076 << Arg << (IsInOut ? 1 : 0);
6084 Param->getBeginLoc(), IsInOut);
6092 "Pointer and reference types cannot be inout or out parameters");
6093 Ty =
SemaRef.getASTContext().getLValueReferenceType(Ty);
6109 for (
const auto *FD : RD->
fields()) {
6113 assert(RD->getNumBases() <= 1 &&
6114 "HLSL doesn't support multiple inheritance");
6115 return RD->getNumBases()
6120 if (
const auto *AT = dyn_cast<ArrayType>(Ty)) {
6121 if (
const auto *CAT = dyn_cast<ConstantArrayType>(AT))
6133 bool IsVKPushConstant = IsVulkan && VD->
hasAttr<HLSLVkPushConstantAttr>();
6138 !VD->
hasAttr<HLSLVkConstantIdAttr>() && !IsVKPushConstant &&
6144 if (
Decl->getType().hasAddressSpace())
6147 if (
Decl->getType()->isDependentType())
6159 if (
Decl->
hasAttr<HLSLVkExtBuiltinOutputAttr>()) {
6173 llvm::Triple::Vulkan;
6174 if (IsVulkan &&
Decl->
hasAttr<HLSLVkPushConstantAttr>()) {
6175 if (HasDeclaredAPushConstant)
6181 HasDeclaredAPushConstant =
true;
6208class StructBindingContext {
6211 HLSLResourceBindingAttr *RegBindingsAttrs[4];
6212 unsigned RegBindingOffset[4];
6215 static_assert(
static_cast<unsigned>(RegisterType::SRV) == 0 &&
6216 static_cast<unsigned>(RegisterType::UAV) == 1 &&
6217 static_cast<unsigned>(RegisterType::CBuffer) == 2 &&
6218 static_cast<unsigned>(RegisterType::Sampler) == 3,
6219 "unexpected register type values");
6222 HLSLVkBindingAttr *VkBindingAttr;
6223 unsigned VkBindingOffset;
6228 StructBindingContext(
VarDecl *VD) {
6229 for (
unsigned i = 0; i < 4; ++i) {
6230 RegBindingsAttrs[i] =
nullptr;
6231 RegBindingOffset[i] = 0;
6233 VkBindingAttr =
nullptr;
6234 VkBindingOffset = 0;
6240 if (
auto *RBA = dyn_cast<HLSLResourceBindingAttr>(A)) {
6242 unsigned RegTypeIdx =
static_cast<unsigned>(RegType);
6245 RegBindingsAttrs[RegTypeIdx] = RBA;
6250 if (
auto *VBA = dyn_cast<HLSLVkBindingAttr>(A))
6251 VkBindingAttr = VBA;
6258 Attr *createBindingAttr(SemaHLSL &S, ASTContext &AST,
RegisterType RegType,
6259 unsigned Range,
bool HasCounter) {
6260 assert(
static_cast<unsigned>(RegType) < 4 &&
"unexpected register type");
6262 if (VkBindingAttr) {
6263 unsigned Offset = VkBindingOffset;
6264 VkBindingOffset +=
Range;
6265 return HLSLVkBindingAttr::CreateImplicit(
6266 AST, VkBindingAttr->getBinding() + Offset, VkBindingAttr->getSet(),
6267 VkBindingAttr->getRange());
6270 HLSLResourceBindingAttr *RBA =
6271 RegBindingsAttrs[
static_cast<unsigned>(RegType)];
6272 HLSLResourceBindingAttr *NewAttr =
nullptr;
6274 if (RBA && RBA->hasRegisterSlot()) {
6277 unsigned Offset = RegBindingOffset[
static_cast<unsigned>(RegType)];
6278 RegBindingOffset[
static_cast<unsigned>(RegType)] += Range;
6280 unsigned NewSlotNumber = RBA->getSlotNumber() + Offset;
6281 StringRef NewSlotNumberStr =
6283 NewAttr = HLSLResourceBindingAttr::CreateImplicit(
6284 AST, NewSlotNumberStr, RBA->getSpace(), RBA->getRange());
6285 NewAttr->setBinding(RegType, NewSlotNumber, RBA->getSpaceNumber());
6289 NewAttr = HLSLResourceBindingAttr::CreateImplicit(AST,
"",
"0", {});
6290 NewAttr->setBinding(RegType, std::nullopt,
6291 RBA ? RBA->getSpaceNumber() : 0);
6295 NewAttr->setImplicitCounterBindingOrderID(
6304static void createGlobalResourceDeclForStruct(
6306 QualType ResTy, StructBindingContext &BindingCtx) {
6308 "expected resource type or array of resources");
6319 while (
const auto *AT = dyn_cast<ArrayType>(SingleResTy)) {
6320 const auto *CAT = dyn_cast<ConstantArrayType>(AT);
6325 const HLSLAttributedResourceType *ResHandleTy =
6326 HLSLAttributedResourceType::findHandleTypeOnResource(SingleResTy);
6330 Attr *BindingAttr = BindingCtx.createBindingAttr(
6332 ResDecl->
addAttr(BindingAttr);
6333 ResDecl->
addAttr(InternalLinkageAttr::CreateImplicit(AST));
6342 HLSLAssociatedResourceDeclAttr::CreateImplicit(AST, ResDecl));
6349static void handleArrayOfStructWithResources(
6351 EmbeddedResourceNameBuilder &NameBuilder, StructBindingContext &BindingCtx);
6356static void handleStructWithResources(
Sema &S,
VarDecl *ParentVD,
6358 EmbeddedResourceNameBuilder &NameBuilder,
6359 StructBindingContext &BindingCtx) {
6362 assert(RD->
getNumBases() <= 1 &&
"HLSL doesn't support multiple inheritance");
6369 handleStructWithResources(S, ParentVD, BaseRD, NameBuilder, BindingCtx);
6383 createGlobalResourceDeclForStruct(S, ParentVD, FD->
getLocation(), II,
6386 handleStructWithResources(S, ParentVD, RD, NameBuilder, BindingCtx);
6388 }
else if (
const auto *ArrayTy = dyn_cast<ConstantArrayType>(FDTy)) {
6390 "resource arrays should have been already handled");
6391 handleArrayOfStructWithResources(S, ParentVD, ArrayTy, NameBuilder,
6400handleArrayOfStructWithResources(
Sema &S,
VarDecl *ParentVD,
6402 EmbeddedResourceNameBuilder &NameBuilder,
6403 StructBindingContext &BindingCtx) {
6411 if (!SubCAT && !ElementRD)
6414 for (
unsigned I = 0, E = CAT->
getSize().getZExtValue(); I < E; ++I) {
6417 handleStructWithResources(S, ParentVD, ElementRD, NameBuilder,
6420 handleArrayOfStructWithResources(S, ParentVD, SubCAT, NameBuilder,
6433void SemaHLSL::handleGlobalStructOrArrayOfWithResources(
VarDecl *VD) {
6434 EmbeddedResourceNameBuilder NameBuilder(VD->
getName());
6435 StructBindingContext BindingCtx(VD);
6439 "Expected non-resource struct or array type");
6442 handleStructWithResources(
SemaRef, VD, RD, NameBuilder, BindingCtx);
6446 if (
const auto *CAT = dyn_cast<ConstantArrayType>(VDTy)) {
6447 handleArrayOfStructWithResources(
SemaRef, VD, CAT, NameBuilder, BindingCtx);
6455 if (
SemaRef.RequireCompleteType(
6458 diag::err_typecheck_decl_incomplete_type)) {
6472 DefaultCBufferDecls.push_back(VD);
6477 collectResourceBindingsOnVarDecl(VD);
6479 if (VD->
hasAttr<HLSLVkConstantIdAttr>())
6491 processExplicitBindingsOnDecl(VD);
6528 handleGlobalStructOrArrayOfWithResources(VD);
6532 if (VD->
hasAttr<HLSLGroupSharedAddressSpaceAttr>())
6541 "expected resource record type");
6557 const char *CreateMethodName;
6559 CreateMethodName = HasCounter ?
"__createFromBindingWithImplicitCounter"
6560 :
"__createFromBinding";
6562 CreateMethodName = HasCounter
6563 ?
"__createFromImplicitBindingWithImplicitCounter"
6564 :
"__createFromImplicitBinding";
6569 if (!CreateMethod) {
6574 "create method lookup should always succeed for built-in resource "
6583 Args.push_back(RegSlot);
6591 Args.push_back(OrderId);
6597 Args.push_back(Space);
6601 Args.push_back(RangeSize);
6605 Args.push_back(Index);
6607 StringRef VarName = VD->
getName();
6615 Args.push_back(NameCast);
6623 Args.push_back(CounterId);
6646 SemaRef.CheckCompleteVariableDeclaration(VD);
6652 "expected array of resource records");
6673 lookupMethod(
SemaRef, ResourceDecl,
6674 HasCounter ?
"__createFromBindingWithImplicitCounter"
6675 :
"__createFromBinding",
6679 CreateMethod = lookupMethod(
6681 HasCounter ?
"__createFromImplicitBindingWithImplicitCounter"
6682 :
"__createFromImplicitBinding",
6725std::optional<const DeclBindingInfo *> SemaHLSL::inferGlobalBinding(
Expr *E) {
6726 if (
auto *Ternary = dyn_cast<ConditionalOperator>(E)) {
6727 auto TrueInfo = inferGlobalBinding(Ternary->getTrueExpr());
6728 auto FalseInfo = inferGlobalBinding(Ternary->getFalseExpr());
6729 if (!TrueInfo || !FalseInfo)
6730 return std::nullopt;
6731 if (*TrueInfo != *FalseInfo)
6732 return std::nullopt;
6736 if (
auto *ASE = dyn_cast<ArraySubscriptExpr>(E))
6745 if (
const auto *AttrResType =
6746 HLSLAttributedResourceType::findHandleTypeOnResource(Ty)) {
6748 return Bindings.getDeclBindingInfo(VD, RC);
6755void SemaHLSL::trackLocalResource(
VarDecl *VD,
Expr *E) {
6756 std::optional<const DeclBindingInfo *> ExprBinding = inferGlobalBinding(E);
6759 diag::warn_hlsl_assigning_local_resource_is_not_unique)
6764 if (*ExprBinding ==
nullptr)
6767 auto PrevBinding = Assigns.find(VD);
6768 if (PrevBinding == Assigns.end()) {
6770 Assigns.insert({VD, *ExprBinding});
6775 if (*ExprBinding != PrevBinding->second) {
6777 diag::warn_hlsl_assigning_local_resource_is_not_unique)
6779 SemaRef.Diag(VD->getLocation(), diag::note_var_declared_here) << VD;
6790 "expected LHS to be a resource record or array of resource records");
6791 if (Opc != BO_Assign)
6796 while (
auto *ASE = dyn_cast<ArraySubscriptExpr>(E))
6804 SemaRef.Diag(Loc, diag::err_hlsl_assign_to_global_resource) << VD;
6809 trackLocalResource(VD, RHSExpr);
6826void SemaHLSL::collectResourceBindingsOnVarDecl(
VarDecl *VD) {
6828 "expected global variable that contains HLSL resource");
6831 if (
const HLSLBufferDecl *CBufferOrTBuffer = dyn_cast<HLSLBufferDecl>(VD)) {
6832 Bindings.addDeclBindingInfo(VD, CBufferOrTBuffer->isCBuffer()
6833 ? ResourceClass::CBuffer
6834 : ResourceClass::SRV);
6847 if (
const HLSLAttributedResourceType *AttrResType =
6848 HLSLAttributedResourceType::findHandleTypeOnResource(Ty)) {
6849 Bindings.addDeclBindingInfo(VD, AttrResType->getAttrs().ResourceClass);
6854 if (
const RecordType *RT = dyn_cast<RecordType>(Ty))
6855 collectResourceBindingsOnUserRecordDecl(VD, RT);
6861void SemaHLSL::processExplicitBindingsOnDecl(
VarDecl *VD) {
6864 bool HasBinding =
false;
6865 for (Attr *A : VD->
attrs()) {
6868 if (
auto PA = VD->
getAttr<HLSLVkPushConstantAttr>())
6869 Diag(PA->getLoc(), diag::err_hlsl_attr_incompatible) << A << PA;
6872 HLSLResourceBindingAttr *RBA = dyn_cast<HLSLResourceBindingAttr>(A);
6873 if (!RBA || !RBA->hasRegisterSlot())
6878 assert(RT != RegisterType::I &&
"invalid or obsolete register type should "
6879 "never have an attribute created");
6881 if (RT == RegisterType::C) {
6882 if (Bindings.hasBindingInfoForDecl(VD))
6884 diag::warn_hlsl_user_defined_type_missing_member)
6885 <<
static_cast<int>(RT);
6893 if (DeclBindingInfo *BI = Bindings.getDeclBindingInfo(VD, RC)) {
6898 diag::warn_hlsl_user_defined_type_missing_member)
6899 <<
static_cast<int>(RT);
6907class InitListTransformer {
6911 QualType *DstIt =
nullptr;
6912 Expr **ArgIt =
nullptr;
6918 bool castInitializer(Expr *E) {
6919 assert(DstIt &&
"This should always be something!");
6920 if (DstIt == DestTypes.end()) {
6922 ArgExprs.push_back(E);
6927 DstIt = DestTypes.begin();
6930 Ctx, *DstIt,
false);
6935 ArgExprs.push_back(
Init);
6940 bool buildInitializerListImpl(Expr *E) {
6942 if (
auto *
Init = dyn_cast<InitListExpr>(E)) {
6943 for (
auto *SubInit :
Init->inits())
6944 if (!buildInitializerListImpl(SubInit))
6954 return castInitializer(E);
6968 if (
auto *VecTy = Ty->
getAs<VectorType>()) {
6975 SizeTy, SourceLocation());
6981 if (!castInitializer(ElExpr.
get()))
6986 if (
auto *MTy = Ty->
getAs<ConstantMatrixType>()) {
6987 unsigned Rows = MTy->getNumRows();
6988 unsigned Cols = MTy->getNumColumns();
6989 QualType ElemTy = MTy->getElementType();
6991 for (
unsigned R = 0;
R < Rows; ++
R) {
6992 for (
unsigned C = 0;
C < Cols; ++
C) {
7005 if (!castInitializer(ElExpr.
get()))
7013 if (
auto *ArrTy = dyn_cast<ConstantArrayType>(Ty.
getTypePtr())) {
7019 SizeTy, SourceLocation());
7024 if (!buildInitializerListImpl(ElExpr.
get()))
7031 llvm::SmallVector<CXXRecordDecl *> RecordDecls;
7032 RecordDecls.push_back(RD);
7033 while (RecordDecls.back()->getNumBases()) {
7034 CXXRecordDecl *D = RecordDecls.back();
7036 "HLSL doesn't support multiple inheritance");
7037 RecordDecls.push_back(
7040 while (!RecordDecls.empty()) {
7041 CXXRecordDecl *RD = RecordDecls.pop_back_val();
7042 for (
auto *FD : RD->
fields()) {
7043 if (FD->isUnnamedBitField())
7051 if (!buildInitializerListImpl(Res.
get()))
7059 Expr *generateInitListsImpl(QualType Ty) {
7061 assert(ArgIt != ArgExprs.end() &&
"Something is off in iteration!");
7066 llvm::SmallVector<Expr *>
Inits;
7071 if (
auto *ATy = Ty->
getAs<VectorType>()) {
7072 ElTy = ATy->getElementType();
7073 Size = ATy->getNumElements();
7074 }
else if (
auto *CMTy = Ty->
getAs<ConstantMatrixType>()) {
7075 ElTy = CMTy->getElementType();
7076 Size = CMTy->getNumElementsFlattened();
7079 ElTy = VTy->getElementType();
7080 Size = VTy->getZExtSize();
7083 Inits.push_back(generateInitListsImpl(ElTy));
7086 llvm::SmallVector<CXXRecordDecl *> RecordDecls;
7087 RecordDecls.push_back(RD);
7088 while (RecordDecls.back()->getNumBases()) {
7089 CXXRecordDecl *D = RecordDecls.back();
7091 "HLSL doesn't support multiple inheritance");
7092 RecordDecls.push_back(
7095 while (!RecordDecls.empty()) {
7096 CXXRecordDecl *RD = RecordDecls.pop_back_val();
7097 for (
auto *FD : RD->
fields())
7098 if (!FD->isUnnamedBitField())
7103 new (Ctx) InitListExpr(Ctx,
Inits.front()->getBeginLoc(),
Inits,
7104 Inits.back()->getEndLoc(),
false);
7105 NewInit->setType(Ty);
7110 llvm::SmallVector<QualType, 16> DestTypes;
7111 llvm::SmallVector<Expr *, 16> ArgExprs;
7112 InitListTransformer(Sema &SemaRef,
const InitializedEntity &Entity)
7113 : S(SemaRef), Ctx(SemaRef.getASTContext()),
7114 Wrap(Entity.
getType()->isIncompleteArrayType()) {
7115 InitTy = Entity.
getType().getNonReferenceType();
7125 DstIt = DestTypes.begin();
7128 bool buildInitializerList(Expr *E) {
return buildInitializerListImpl(E); }
7130 Expr *generateInitLists() {
7131 assert(!ArgExprs.empty() &&
7132 "Call buildInitializerList to generate argument expressions.");
7133 ArgIt = ArgExprs.begin();
7135 return generateInitListsImpl(InitTy);
7136 llvm::SmallVector<Expr *>
Inits;
7137 while (ArgIt != ArgExprs.end())
7138 Inits.push_back(generateInitListsImpl(InitTy));
7141 new (Ctx) InitListExpr(Ctx,
Inits.front()->getBeginLoc(),
Inits,
7142 Inits.back()->getEndLoc(),
false);
7143 llvm::APInt ArySize(64,
Inits.size());
7145 ArraySizeModifier::Normal, 0));
7157 if (
const ArrayType *AT = dyn_cast<ArrayType>(Ty)) {
7164 if (
const auto *RT = Ty->
getAs<RecordType>()) {
7168 if (
const auto *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
7188 if (
Init->getType()->isScalarType())
7191 InitListTransformer ILT(
SemaRef, Entity);
7193 for (
unsigned I = 0; I <
Init->getNumInits(); ++I) {
7201 Init->setInit(I, E);
7203 if (!ILT.buildInitializerList(E))
7206 size_t ExpectedSize = ILT.DestTypes.size();
7207 size_t ActualSize = ILT.ArgExprs.size();
7208 if (ExpectedSize == 0 && ActualSize == 0)
7215 InitTy =
SemaRef.getASTContext().removeAddrSpaceQualType(InitTy);
7217 SemaRef.Diag(
Init->getBeginLoc(), diag::err_hlsl_incorrect_num_initializers)
7218 << (int)(ExpectedSize < ActualSize) << InitTy
7219 << ExpectedSize << ActualSize;
7229 assert(ExpectedSize > 0 &&
7230 "The expected size of an incomplete array type must be at least 1.");
7232 ((ActualSize + ExpectedSize - 1) / ExpectedSize) * ExpectedSize;
7240 InitTy =
SemaRef.getASTContext().removeAddrSpaceQualType(InitTy);
7241 if (ExpectedSize != ActualSize) {
7242 int TooManyOrFew = ActualSize > ExpectedSize ? 1 : 0;
7243 SemaRef.Diag(
Init->getBeginLoc(), diag::err_hlsl_incorrect_num_initializers)
7244 << TooManyOrFew << InitTy << ExpectedSize << ActualSize;
7251 Init->resizeInits(Ctx, NewInit->getNumInits());
7252 for (
unsigned I = 0; I < NewInit->getNumInits(); ++I)
7253 Init->updateInit(Ctx, I, NewInit->getInit(I));
7261 S.
Diag(OpLoc, diag::err_builtin_matrix_invalid_member)
7271 StringRef AccessorName = CompName->
getName();
7272 assert(!AccessorName.empty() &&
"Matrix Accessor must have a name");
7274 unsigned Rows = MT->getNumRows();
7275 unsigned Cols = MT->getNumColumns();
7276 bool IsZeroBasedAccessor =
false;
7277 unsigned ChunkLen = 0;
7278 if (AccessorName.size() < 2)
7280 "length 4 for zero based: \'_mRC\' or "
7281 "length 3 for one-based: \'_RC\' accessor",
7284 if (AccessorName[0] ==
'_') {
7285 if (AccessorName[1] ==
'm') {
7286 IsZeroBasedAccessor =
true;
7293 S, AccessorName,
"zero based: \'_mRC\' or one-based: \'_RC\' accessor",
7296 if (AccessorName.size() % ChunkLen != 0) {
7297 const llvm::StringRef
Expected = IsZeroBasedAccessor
7298 ?
"zero based: '_mRC' accessor"
7299 :
"one-based: '_RC' accessor";
7304 auto isDigit = [](
char c) {
return c >=
'0' && c <=
'9'; };
7305 auto isZeroBasedIndex = [](
unsigned i) {
return i <= 3; };
7306 auto isOneBasedIndex = [](
unsigned i) {
return i >= 1 && i <= 4; };
7308 bool HasRepeated =
false;
7310 unsigned NumComponents = 0;
7311 const char *Begin = AccessorName.data();
7313 for (
unsigned I = 0, E = AccessorName.size(); I < E; I += ChunkLen) {
7314 const char *Chunk = Begin + I;
7315 char RowChar = 0, ColChar = 0;
7316 if (IsZeroBasedAccessor) {
7318 if (Chunk[0] !=
'_' || Chunk[1] !=
'm') {
7319 char Bad = (Chunk[0] !=
'_') ? Chunk[0] : Chunk[1];
7321 S, StringRef(&Bad, 1),
"\'_m\' prefix",
7328 if (Chunk[0] !=
'_')
7330 S, StringRef(&Chunk[0], 1),
"\'_\' prefix",
7337 bool IsDigitsError =
false;
7339 unsigned BadPos = IsZeroBasedAccessor ? 2 : 1;
7343 IsDigitsError =
true;
7347 unsigned BadPos = IsZeroBasedAccessor ? 3 : 2;
7351 IsDigitsError =
true;
7356 unsigned Row = RowChar -
'0';
7357 unsigned Col = ColChar -
'0';
7359 bool HasIndexingError =
false;
7360 if (IsZeroBasedAccessor) {
7362 if (!isZeroBasedIndex(Row)) {
7363 S.
Diag(OpLoc, diag::err_hlsl_matrix_element_not_in_bounds)
7365 HasIndexingError =
true;
7367 if (!isZeroBasedIndex(Col)) {
7368 S.
Diag(OpLoc, diag::err_hlsl_matrix_element_not_in_bounds)
7370 HasIndexingError =
true;
7374 if (!isOneBasedIndex(Row)) {
7375 S.
Diag(OpLoc, diag::err_hlsl_matrix_element_not_in_bounds)
7377 HasIndexingError =
true;
7379 if (!isOneBasedIndex(Col)) {
7380 S.
Diag(OpLoc, diag::err_hlsl_matrix_element_not_in_bounds)
7382 HasIndexingError =
true;
7389 if (HasIndexingError)
7395 bool HasBoundsError =
false;
7397 Diag(OpLoc, diag::err_hlsl_matrix_index_out_of_bounds)
7399 HasBoundsError =
true;
7402 Diag(OpLoc, diag::err_hlsl_matrix_index_out_of_bounds)
7404 HasBoundsError =
true;
7409 unsigned FlatIndex = Row * Cols + Col;
7410 if (Seen[FlatIndex])
7412 Seen[FlatIndex] =
true;
7415 if (NumComponents == 0 || NumComponents > 4) {
7416 S.
Diag(OpLoc, diag::err_hlsl_matrix_swizzle_invalid_length)
7421 QualType ElemTy = MT->getElementType();
7422 if (NumComponents == 1)
7428 for (Sema::ExtVectorDeclsType::iterator
7432 if ((*I)->getUnderlyingType() == VT)
7443 trackLocalResource(VDecl,
Init);
7445 const HLSLVkConstantIdAttr *ConstIdAttr =
7446 VDecl->
getAttr<HLSLVkConstantIdAttr>();
7453 if (!
Init->isCXX11ConstantExpr(Context, InitValue)) {
7463 int ConstantID = ConstIdAttr->getId();
7464 llvm::APInt IDVal(Context.getIntWidth(Context.IntTy), ConstantID);
7466 ConstIdAttr->getLocation());
7470 if (
C->getType()->getCanonicalTypeUnqualified() !=
7474 Context.getTrivialTypeSourceInfo(
7475 Init->getType(),
Init->getExprLoc()),
7494 if (!Params || Params->
size() != 1)
7507 if (
auto *TTP = dyn_cast<TemplateTypeParmDecl>(P)) {
7508 if (TTP->hasDefaultArgument()) {
7509 TemplateArgs.
addArgument(TTP->getDefaultArgument());
7512 }
else if (
auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(P)) {
7513 if (NTTP->hasDefaultArgument()) {
7514 TemplateArgs.
addArgument(NTTP->getDefaultArgument());
7517 }
else if (
auto *TTPD = dyn_cast<TemplateTemplateParmDecl>(P)) {
7518 if (TTPD->hasDefaultArgument()) {
7519 TemplateArgs.
addArgument(TTPD->getDefaultArgument());
7526 return SemaRef.CheckTemplateIdType(
7528 TemplateArgs,
nullptr,
false);
Defines the clang::ASTContext interface.
static bool isBooleanType(QualType Ty)
Defines enum values for all the target-independent builtin functions.
llvm::dxil::ResourceClass ResourceClass
Defines the C++ Decl subclasses, other than those for templates (found in DeclTemplate....
Defines the clang::IdentifierInfo, clang::IdentifierTable, and clang::Selector interfaces.
Forward-declares and imports various common LLVM datatypes that clang wants to use unqualified.
Defines AST-level helper utilities for matrix types.
static StringRef getTriple(const Command &Job)
llvm::SmallVector< std::pair< const MemRegion *, SVal >, 4 > Bindings
static bool CheckArgTypeMatches(Sema *S, Expr *Arg, QualType ExpectedType)
static void BuildFlattenedTypeList(QualType BaseTy, llvm::SmallVectorImpl< QualType > &List)
static bool CheckUnsignedIntRepresentation(Sema *S, SourceLocation Loc, int ArgOrdinal, clang::QualType PassedType)
static bool containsIncompleteArrayType(QualType Ty)
static QualType handleIntegerVectorBinOpConversion(Sema &SemaRef, ExprResult &LHS, ExprResult &RHS, QualType LHSType, QualType RHSType, QualType LElTy, QualType RElTy, bool IsCompAssign)
static bool convertToRegisterType(StringRef Slot, RegisterType *RT)
static StringRef createRegisterString(ASTContext &AST, RegisterType RegType, unsigned N)
static bool CheckWaveActive(Sema *S, CallExpr *TheCall)
static void createHostLayoutStructForBuffer(Sema &S, HLSLBufferDecl *BufDecl)
static void castVector(Sema &S, ExprResult &E, QualType &Ty, unsigned Sz)
static QualType ReportMatrixInvalidMember(Sema &S, StringRef Name, StringRef Expected, SourceLocation OpLoc, SourceLocation CompLoc)
static bool CheckBoolSelect(Sema *S, CallExpr *TheCall)
static bool isIntUpTo32Element(const ASTContext &Ctx, QualType Elem)
static unsigned calculateLegacyCbufferFieldAlign(const ASTContext &Context, QualType T)
static bool CheckScalarFloatOperand(Sema &S, CallExpr *TheCall, unsigned ArgIndex)
static bool isVkPipelineBuiltin(const ASTContext &AstContext, FunctionDecl *FD, const DeclaratorDecl *D, HLSLAppliedSemanticAttr *Semantic, bool IsInput)
static bool isIntElementOfWidth(const ASTContext &Ctx, QualType Elem, uint64_t Width)
static bool isZeroSizedArray(const ConstantArrayType *CAT)
static bool DiagnoseHLSLRegisterAttribute(Sema &S, SourceLocation &ArgLoc, Decl *D, RegisterType RegType, bool SpecifiedSpace)
static bool CheckAnyScalarOrVectorOrMatrix(Sema *S, CallExpr *TheCall, unsigned ArgIndex)
static bool hasConstantBufferLayout(QualType QT)
llvm::dxbc::PSV::SemanticKind SemanticKind
static FieldDecl * createFieldForHostLayoutStruct(Sema &S, const Type *Ty, IdentifierInfo *II, CXXRecordDecl *LayoutStruct)
static bool CheckIntegerElementTypeShaderModel(Sema &S, CallExpr *TheCall, QualType ContainedType, SampleKind Kind)
static bool isMatrixType(QualType QT)
static bool CheckUnsignedIntVecRepresentation(Sema *S, SourceLocation Loc, int ArgOrdinal, clang::QualType PassedType)
static bool isInvalidConstantBufferLeafElementType(const Type *Ty)
static bool CheckCalculateLodBuiltin(Sema &S, CallExpr *TheCall)
static QualType getScalarComponentType(QualType T)
static Builtin::ID getSpecConstBuiltinId(const Type *Type)
static bool CheckNumericRepresentation(Sema *S, SourceLocation Loc, int ArgOrdinal, clang::QualType PassedType)
static bool CheckNoDoubleElementType(Sema &S, CallExpr *TheCall, QualType ContainedType, StringRef DefaultName)
static const Type * createHostLayoutType(Sema &S, const Type *Ty)
static bool CheckAnyScalarOrVector(Sema *S, CallExpr *TheCall, unsigned ArgIndex)
static bool CheckInterlockedBuiltin(Sema &S, CallExpr *TheCall, unsigned MinArgs, unsigned MaxArgs, InterlockedDest Dest, bool ReportsOriginalValue)
Check a call to an HLSL interlocked builtin.
static const HLSLAttributedResourceType * getResourceArrayHandleType(QualType QT)
static IdentifierInfo * getHostLayoutStructName(Sema &S, NamedDecl *BaseDecl, bool MustBeUnique)
static QualType createCounterHandleType(ASTContext &AST, QualType MainHandleTy)
static bool CheckMatrixSelect(Sema *S, CallExpr *TheCall)
static bool CheckArgAddrSpaceOneOf(Sema *S, CallExpr *TheCall, unsigned ArgIndex, ArrayRef< LangAS > AllowedSpaces)
static void addImplicitBindingAttrToDecl(Sema &S, Decl *D, RegisterType RT, uint32_t ImplicitBindingOrderID)
static StringRef getSampleMethodName(SampleKind Kind)
static void SetElementTypeAsReturnType(Sema *S, CallExpr *TheCall, QualType ReturnType)
static unsigned calculateLegacyCbufferSize(const ASTContext &Context, QualType T)
static bool CheckLoadLevelBuiltin(Sema &S, CallExpr *TheCall)
static RegisterType getRegisterType(ResourceClass RC)
static bool ValidateRegisterNumber(uint64_t SlotNum, Decl *TheDecl, ASTContext &Ctx, RegisterType RegTy)
static bool CheckModifiableLValue(Sema *S, CallExpr *TheCall, unsigned ArgIndex)
static QualType castElement(Sema &S, ExprResult &E, QualType Ty)
static char getRegisterTypeChar(RegisterType RT)
static bool CheckNotBoolScalarOrVector(Sema *S, CallExpr *TheCall, unsigned ArgIndex)
static bool findExistingMatrixLayoutMarker(QualType T, attr::Kind &ExistingKind)
Walks the existing AttributedType sugar of T looking for a previously applied HLSLRowMajor/HLSLColumn...
static CXXRecordDecl * findRecordDeclInContext(IdentifierInfo *II, DeclContext *DC)
static bool CheckWavePrefix(Sema *S, CallExpr *TheCall)
static bool CheckExpectedBitWidth(Sema *S, CallExpr *TheCall, unsigned ArgOrdinal, unsigned Width)
static LangAS getLangASFromResourceClass(ResourceClass RC)
static bool CheckTextureSamplerAndLocation(Sema &S, CallExpr *TheCall, bool IncludeArraySlice=true)
static bool CheckVectorSelect(Sema *S, CallExpr *TheCall)
static void validateVkBuiltinUsage(Sema &S, FunctionDecl *FD, const DeclaratorDecl *D, const HLSLVkBuiltInAttr *Attr, IOType CurrentIOType)
static QualType handleFloatVectorBinOpConversion(Sema &SemaRef, ExprResult &LHS, ExprResult &RHS, QualType LHSType, QualType RHSType, QualType LElTy, QualType RElTy, bool IsCompAssign)
static const Type * getHostLayoutFieldType(QualType QT)
InterlockedDest
The dest types an interlocked operation accepts. Float is 32-bit only.
static unsigned getComponentCountOf(QualType T)
static ResourceClass getResourceClass(RegisterType RT)
static CXXRecordDecl * createHostLayoutStruct(Sema &S, CXXRecordDecl *StructDecl)
static bool CheckScalarOrVector(Sema *S, CallExpr *TheCall, QualType Scalar, unsigned ArgIndex)
static QualType getVectorOrScalarType(Sema &S, QualType BaseType, unsigned Count)
static bool CheckSamplingBuiltin(Sema &S, CallExpr *TheCall, SampleKind Kind)
static bool CheckScalarOrVectorOrMatrix(Sema *S, CallExpr *TheCall, QualType Scalar, unsigned ArgIndex)
static bool CheckFloatRepresentation(Sema *S, SourceLocation Loc, int ArgOrdinal, clang::QualType PassedType)
static bool CheckAnyDoubleRepresentation(Sema *S, SourceLocation Loc, int ArgOrdinal, clang::QualType PassedType)
static bool requiresImplicitBufferLayoutStructure(const CXXRecordDecl *RD)
static bool CheckResourceHandle(Sema *S, CallExpr *TheCall, unsigned ArgIndex, llvm::function_ref< bool(const HLSLAttributedResourceType *ResType)> Check=nullptr)
static void validatePackoffset(Sema &S, HLSLBufferDecl *BufDecl)
static StringRef getCurrentResourceMethodName(Sema &S, StringRef DefaultName)
static bool IsDefaultBufferConstantDecl(const ASTContext &Ctx, VarDecl *VD)
HLSLResourceBindingAttr::RegisterType RegisterType
static CastKind getScalarCastKind(ASTContext &Ctx, QualType DestTy, QualType SrcTy)
static bool CheckGatherBuiltin(Sema &S, CallExpr *TheCall, bool IsCmp)
static QualType getElementTypeOf(QualType T, bool IncludeMatrix)
static bool isValidWaveSizeValue(unsigned Value)
static bool isResourceRecordTypeOrArrayOf(QualType Ty)
static bool CheckLoadMSBuiltin(Sema &S, CallExpr *TheCall)
static bool AccumulateHLSLResourceSlots(QualType Ty, uint64_t &StartSlot, const uint64_t &Limit, const ResourceClass ResClass, ASTContext &Ctx, uint64_t ArrayCount=1)
static bool CheckNoDoubleVectors(Sema *S, SourceLocation Loc, int ArgOrdinal, clang::QualType PassedType)
static bool ValidateMultipleRegisterAnnotations(Sema &S, Decl *TheDecl, RegisterType regType)
static bool CheckWaveMultiPrefixMask(Sema *S, CallExpr *TheCall)
static bool DiagnoseLocalRegisterBinding(Sema &S, SourceLocation &ArgLoc, Decl *D, RegisterType RegType, bool SpecifiedSpace)
static bool CheckIndexType(Sema *S, CallExpr *TheCall, unsigned IndexArgIndex)
static bool isFloatOrHalfElement(QualType Elem)
This file declares semantic analysis for HLSL constructs.
Defines the clang::SourceLocation class and associated facilities.
Defines various enumerations that describe declaration and type specifiers.
C Language Family Type Representation.
Defines the clang::TypeLoc interface and its subclasses.
C Language Family Type Representation.
static const TypeInfo & getInfo(unsigned id)
return(__x > > __y)|(__x<<(32 - __y))
APValue - This class implements a discriminated union of [uninitialized] [APSInt] [APFloat],...
virtual bool HandleTopLevelDecl(DeclGroupRef D)
HandleTopLevelDecl - Handle the specified top-level declaration.
Holds long-lived AST nodes (such as types and decls) that can be referred to throughout the semantic ...
const ConstantArrayType * getAsConstantArrayType(QualType T) const
unsigned getIntWidth(QualType T) const
QualType getConstantMatrixType(QualType ElementType, unsigned NumRows, unsigned NumColumns, std::optional< MatrixType::LayoutKind > Layout=std::nullopt) const
Return the unique reference to the matrix type of the specified element type and size.
int getIntegerTypeOrder(QualType LHS, QualType RHS) const
Return the highest ranked integer type, see C99 6.3.1.8p1.
QualType getPointerType(QualType T) const
Return the uniqued reference to the type for a pointer to the specified type.
const IncompleteArrayType * getAsIncompleteArrayType(QualType T) const
QualType getConstantArrayType(QualType EltTy, const llvm::APInt &ArySize, const Expr *SizeExpr, ArraySizeModifier ASM, unsigned IndexTypeQuals) const
Return the unique reference to the type for a constant array of the specified element type.
const LangOptions & getLangOpts() const
QualType getBaseElementType(const ArrayType *VAT) const
Return the innermost element type of an array type.
int getFloatingTypeOrder(QualType LHS, QualType RHS) const
Compare the rank of the two specified floating point types, ignoring the domain of the type (i....
TypeSourceInfo * getTrivialTypeSourceInfo(QualType T, SourceLocation Loc=SourceLocation()) const
Allocate a TypeSourceInfo where all locations have been initialized to a given location,...
QualType getStringLiteralArrayType(QualType EltTy, unsigned Length) const
Return a type for a constant array for a string literal of the specified element type and length.
uint64_t getTypeSize(QualType T) const
Return the size of the specified (complete) type T, in bits.
CharUnits getTypeSizeInChars(QualType T) const
Return the size of the specified (complete) type T, in characters.
CanQualType UnsignedIntTy
QualType getTypedefType(ElaboratedTypeKeyword Keyword, NestedNameSpecifier Qualifier, const TypedefNameDecl *Decl, QualType UnderlyingType=QualType(), std::optional< bool > TypeMatchesDeclOrNone=std::nullopt) const
Return the unique reference to the type for the specified typedef-name decl.
static uint64_t getConstantArrayElementCount(const ConstantArrayType *CA)
Return number of (potentially nested) constant array elements.
llvm::StringRef backupStr(llvm::StringRef S) const
QualType getSizeType() const
Return the unique type for "size_t" (C99 7.17), defined in <stddef.h>.
QualType getExtVectorType(QualType VectorType, unsigned NumElts) const
Return the unique reference to an extended vector type of the specified element type and size.
const TargetInfo & getTargetInfo() const
QualType getCorrespondingUnsignedType(QualType T) const
QualType getHLSLAttributedResourceType(QualType Wrapped, QualType Contained, const HLSLAttributedResourceType::Attributes &Attrs)
QualType getAddrSpaceQualType(QualType T, LangAS AddressSpace) const
Return the uniqued reference to the type for an address space qualified type with the specified type ...
CanQualType getCanonicalTagType(const TagDecl *TD) const
static bool hasSameUnqualifiedType(QualType T1, QualType T2)
Determine whether the given types are equivalent after cvr-qualifiers have been removed.
unsigned getTypeAlign(QualType T) const
Return the ABI-specified alignment of a (complete) type T, in bits.
Represents an array type, per C99 6.7.5.2 - Array Declarators.
QualType getElementType() const
Attr - This represents one attribute.
attr::Kind getKind() const
SourceLocation getLocation() const
SourceLocation getScopeLoc() const
SourceRange getRange() const
const IdentifierInfo * getScopeName() const
bool isRegularKeywordAttribute() const
SourceLocation getLoc() const
const IdentifierInfo * getAttrName() const
Represents a base class of a C++ class.
QualType getType() const
Retrieves the type of the base class.
Represents a static or instance method of a struct/union/class.
Represents a C++ struct/union/class.
bool isHLSLIntangible() const
Returns true if the class contains HLSL intangible type, either as a field or in base class.
static CXXRecordDecl * Create(const ASTContext &C, TagKind TK, DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc, IdentifierInfo *Id, CXXRecordDecl *PrevDecl=nullptr)
void setBases(CXXBaseSpecifier const *const *Bases, unsigned NumBases)
Sets the base classes of this struct or class.
base_class_iterator bases_end()
void completeDefinition() override
Indicates that the definition of this class is now complete.
unsigned getNumBases() const
Retrieves the number of base classes of this class.
bool isHLSLBuiltinRecord() const
Returns true if the class is a built-in HLSL record.
base_class_iterator bases_begin()
bool isEmpty() const
Determine whether this is an empty class in the sense of (C++11 [meta.unary.prop]).
CallExpr - Represents a function call (C99 6.5.2.2, C++ [expr.call]).
Expr * getArg(unsigned Arg)
getArg - Return the specified argument.
SourceLocation getBeginLoc() const
static CallExpr * Create(const ASTContext &Ctx, Expr *Fn, ArrayRef< Expr * > Args, QualType Ty, ExprValueKind VK, SourceLocation RParenLoc, FPOptionsOverride FPFeatures, unsigned MinNumArgs=0, ADLCallKind UsesADL=NotADL)
Create a call expression.
FunctionDecl * getDirectCallee()
If the callee is a FunctionDecl, return it. Otherwise return null.
unsigned getNumArgs() const
getNumArgs - Return the number of actual arguments to this call.
SourceLocation getEndLoc() const
static CanQual< Type > CreateUnsafe(QualType Other)
QualType withConst() const
Retrieves a version of this type with const applied.
const T * getTypePtr() const
Retrieve the underlying type pointer, which refers to a canonical type.
QuantityType getQuantity() const
Get the raw integer representation of this quantity.
Represents the canonical version of C arrays with a specified constant size.
bool isZeroSize() const
Return true if the size is zero.
llvm::APInt getSize() const
Return the constant array size as an APInt.
Represents a concrete matrix type with constant number of rows and columns.
unsigned getNumColumns() const
Returns the number of columns in the matrix.
unsigned getNumRows() const
Returns the number of rows in the matrix.
static DeclAccessPair make(NamedDecl *D, AccessSpecifier AS)
DeclContext - This is used only as base class of specific decl types that can act as declaration cont...
lookup_result lookup(DeclarationName Name) const
lookup - Find the declarations (if any) with the given Name in this context.
bool isTranslationUnit() const
void addDecl(Decl *D)
Add the declaration D into this context.
decl_range decls() const
decls_begin/decls_end - Iterate over the declarations stored in this context.
DeclContext * getNonTransparentContext()
A reference to a declared variable, function, enum, etc.
static DeclRefExpr * Create(const ASTContext &Context, NestedNameSpecifierLoc QualifierLoc, SourceLocation TemplateKWLoc, ValueDecl *D, bool RefersToEnclosingVariableOrCapture, SourceLocation NameLoc, QualType T, ExprValueKind VK, NamedDecl *FoundD=nullptr, const TemplateArgumentListInfo *TemplateArgs=nullptr, NonOdrUseReason NOUR=NOUR_None)
Decl - This represents one declaration (or definition), e.g.
ASTContext & getASTContext() const LLVM_READONLY
attr_iterator attr_end() const
bool isImplicit() const
isImplicit - Indicates whether the declaration was implicitly generated by the implementation.
void setInvalidDecl(bool Invalid=true)
setInvalidDecl - Indicates the Decl had a semantic error.
bool isInExportDeclContext() const
Whether this declaration was exported in a lexical context.
attr_iterator attr_begin() const
DeclContext * getNonTransparentDeclContext()
Return the non transparent context.
bool isInvalidDecl() const
SourceLocation getLocation() const
void setImplicit(bool I=true)
DeclContext * getDeclContext()
AccessSpecifier getAccess() const
SourceLocation getBeginLoc() const LLVM_READONLY
The name of a declaration.
Represents a ValueDecl that came out of a declarator.
SourceLocation getBeginLoc() const LLVM_READONLY
This represents one expression.
bool isIntegerConstantExpr(const ASTContext &Ctx) const
ExprValueKind getValueKind() const
getValueKind - The value kind that this expression produces.
Expr * IgnoreParenImpCasts() LLVM_READONLY
Skip past any parentheses and implicit casts which might surround this expression until reaching a fi...
Expr * IgnoreParens() LLVM_READONLY
Skip past any parentheses which might surround this expression until reaching a fixed point.
bool isLValue() const
isLValue - True if this expression is an "l-value" according to the rules of the current language.
ExprObjectKind getObjectKind() const
getObjectKind - The object kind that this expression produces.
Expr * IgnoreCasts() LLVM_READONLY
Skip past any casts which might surround this expression until reaching a fixed point.
bool HasSideEffects(const ASTContext &Ctx, bool IncludePossibleEffects=true) const
HasSideEffects - This routine returns true for all those expressions which have any effect other than...
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.
SourceLocation getExprLoc() const LLVM_READONLY
getExprLoc - Return the preferred location for the arrow when diagnosing a problem with a generic exp...
ExtVectorType - Extended vector type.
Represents difference between two FPOptions values.
Represents a member of a struct/union/class.
static FieldDecl * Create(const ASTContext &C, DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc, const IdentifierInfo *Id, QualType T, TypeSourceInfo *TInfo, Expr *BW, bool Mutable, InClassInitStyle InitStyle)
static FixItHint CreateReplacement(CharSourceRange RemoveRange, StringRef Code)
Create a code modification hint that replaces the given source range with the given code string.
Represents a function declaration or definition.
const ParmVarDecl * getParamDecl(unsigned i) const
Stmt * getBody(const FunctionDecl *&Definition) const
Retrieve the body (definition) of the function.
bool isThisDeclarationADefinition() const
Returns whether this specific declaration of the function is also a definition that does not contain ...
unsigned getBuiltinID(bool ConsiderWrapperFunctions=false) const
Returns a value indicating whether this function corresponds to a builtin function.
QualType getReturnType() const
ArrayRef< ParmVarDecl * > parameters() const
bool isTemplateInstantiation() const
Determines if the given function was instantiated from a function template.
redecl_range redecls() const
Returns an iterator range for all the redeclarations of the same decl.
unsigned getNumParams() const
Return the number of parameters this function must have based on its FunctionType.
DeclarationNameInfo getNameInfo() const
bool hasBody(const FunctionDecl *&Definition) const
Returns true if the function has a body.
bool isDefined(const FunctionDecl *&Definition, bool CheckForPendingFriendDefinition=false) const
Returns true if the function has a definition that does not need to be instantiated.
HLSLBufferDecl - Represent a cbuffer or tbuffer declaration.
static HLSLBufferDecl * Create(ASTContext &C, DeclContext *LexicalParent, bool CBuffer, SourceLocation KwLoc, IdentifierInfo *ID, SourceLocation IDLoc, SourceLocation LBrace)
void addLayoutStruct(CXXRecordDecl *LS)
void setHasValidPackoffset(bool PO)
static HLSLBufferDecl * CreateDefaultCBuffer(ASTContext &C, DeclContext *LexicalParent, ArrayRef< Decl * > DefaultCBufferDecls)
buffer_decl_range buffer_decls() const
static HLSLOutArgExpr * Create(const ASTContext &C, QualType Ty, OpaqueValueExpr *Base, OpaqueValueExpr *OpV, Expr *WB, bool IsInOut)
static HLSLRootSignatureDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation Loc, IdentifierInfo *ID, llvm::dxbc::RootSignatureVersion Version, ArrayRef< llvm::hlsl::rootsig::RootElement > RootElements)
One of these records is kept for each identifier that is lexed.
StringRef getName() const
Return the actual identifier string.
A simple pair of identifier info and location.
SourceLocation getLoc() const
IdentifierInfo * getIdentifierInfo() const
IdentifierInfo & get(StringRef Name)
Return the identifier token info for the specified named identifier.
ImplicitCastExpr - Allows us to explicitly represent implicit type conversions, which have no direct ...
static ImplicitCastExpr * Create(const ASTContext &Context, QualType T, CastKind Kind, Expr *Operand, const CXXCastPath *BasePath, ExprValueKind Cat, FPOptionsOverride FPO)
Describes an C or C++ initializer list.
Describes an entity that is being initialized.
QualType getType() const
Retrieve type being initialized.
static InitializedEntity InitializeParameter(ASTContext &Context, ParmVarDecl *Parm)
Create the initialization entity for a parameter.
static IntegerLiteral * Create(const ASTContext &C, const llvm::APInt &V, QualType type, SourceLocation l)
Returns a new integer literal with value 'V' and type 'type'.
iterator begin(ExternalSemaSource *source, bool LocalOnly=false)
Represents the results of name lookup.
Represents a prvalue temporary that is written into memory so that a reference can bind to it.
Represents a matrix type, as defined in the Matrix Types clang extensions.
MemberExpr - [C99 6.5.2.3] Structure and Union Members.
ValueDecl * getMemberDecl() const
Retrieve the member declaration to which this expression refers.
This represents a decl that may have a name.
NamedDecl * getUnderlyingDecl()
Looks through UsingDecls and ObjCCompatibleAliasDecls for the underlying named decl.
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.
DeclarationName getDeclName() const
Get the actual, stored name of the declaration, which may be a special name.
A C++ nested-name-specifier augmented with source location information.
OpaqueValueExpr - An expression referring to an opaque object of a fixed type and value class.
Represents a parameter to a function.
ParsedAttr - Represents a syntactic attribute.
unsigned getSemanticSpelling() const
If the parsed attribute has a semantic equivalent, and it would have a semantic Spelling enumeration ...
unsigned getMinArgs() const
bool checkExactlyNumArgs(class Sema &S, unsigned Num) const
Check if the attribute has exactly as many args as Num.
IdentifierLoc * getArgAsIdent(unsigned Arg) const
bool hasParsedType() const
void setInvalid(bool b=true) const
const ParsedType & getTypeArg() const
unsigned getNumArgs() const
getNumArgs - Return the number of actual arguments to this attribute.
bool isArgIdent(unsigned Arg) const
Expr * getArgAsExpr(unsigned Arg) const
AttributeCommonInfo::Kind getKind() const
A (possibly-)qualified type.
void addRestrict()
Add the restrict qualifier to this QualType.
QualType getNonLValueExprType(const ASTContext &Context) const
Determine the type of a (typically non-lvalue) expression with the specified result type.
QualType getDesugaredType(const ASTContext &Context) const
Return the specified type with any "sugar" removed from the type.
bool isNull() const
Return true if this QualType doesn't point to a type yet.
const Type * getTypePtr() const
Retrieves a pointer to the underlying (unqualified) type.
LangAS getAddressSpace() const
Return the address space of this type.
QualType getNonReferenceType() const
If Type is a reference type (e.g., const int&), returns the type that the reference refers to ("const...
QualType getCanonicalType() const
QualType getUnqualifiedType() const
Retrieve the unqualified variant of the given type, removing as little sugar as possible.
bool hasAddressSpace() const
Check if this type has any address space qualifier.
Represents a struct/union/class.
field_range fields() const
RecordDecl * getDefinition() const
Returns the RecordDecl that actually defines this struct/union/class.
RecordDecl * getDefinitionOrSelf() const
bool hasBindingInfoForDecl(const VarDecl *VD) const
DeclBindingInfo * getDeclBindingInfo(const VarDecl *VD, ResourceClass ResClass)
DeclBindingInfo * addDeclBindingInfo(const VarDecl *VD, ResourceClass ResClass)
Scope - A scope is a transient data structure that is used while parsing the program.
ASTContext & getASTContext() const
const LangOptions & getLangOpts() const
SemaDiagnosticBuilder Diag(SourceLocation Loc, unsigned DiagID)
Emit a diagnostic.
ExprResult ActOnOutParamExpr(ParmVarDecl *Param, Expr *Arg)
void handleVkBuiltInAttr(Decl *D, const ParsedAttr &AL)
HLSLRootSignatureDecl * lookupRootSignatureOverrideDecl(DeclContext *DC) const
bool CanPerformElementwiseCast(Expr *Src, QualType DestType)
ExprResult CreateOutArgExpr(Expr *Arg, QualType ArgTy, QualType ParamTy, InitializedEntity Entity, SourceLocation Loc, bool IsInOut)
void handleWaveSizeAttr(Decl *D, const ParsedAttr &AL)
void handleVkLocationAttr(Decl *D, const ParsedAttr &AL)
HLSLAttributedResourceLocInfo TakeLocForHLSLAttribute(const HLSLAttributedResourceType *RT)
void handleSemanticAttr(Decl *D, const ParsedAttr &AL)
bool CanPerformScalarCast(QualType SrcTy, QualType DestTy)
QualType ProcessResourceTypeAttributes(QualType Wrapped)
void handleInterpolationModifierAttr(Decl *D, const ParsedAttr &AL)
void handleShaderAttr(Decl *D, const ParsedAttr &AL)
uint32_t getNextImplicitBindingOrderID()
void CheckEntryPoint(FunctionDecl *FD)
void handleVkExtBuiltinOutputAttr(Decl *D, const ParsedAttr &AL)
void emitLogicalOperatorFixIt(Expr *LHS, Expr *RHS, BinaryOperatorKind Opc)
bool initGlobalResourceDecl(VarDecl *VD)
void ActOnEndOfTranslationUnit(TranslationUnitDecl *TU)
bool initGlobalResourceArrayDecl(VarDecl *VD)
HLSLVkConstantIdAttr * mergeVkConstantIdAttr(Decl *D, const AttributeCommonInfo &AL, int Id)
HLSLNumThreadsAttr * mergeNumThreadsAttr(Decl *D, const AttributeCommonInfo &AL, int X, int Y, int Z)
void deduceAddressSpace(VarDecl *Decl)
std::pair< IdentifierInfo *, bool > ActOnStartRootSignatureDecl(StringRef Signature)
Computes the unique Root Signature identifier from the given signature, then lookup if there is a pre...
void handlePackOffsetAttr(Decl *D, const ParsedAttr &AL)
Attr * buildMatrixLayoutTypeAttr(QualType T, const ParsedAttr &AL)
bool handleInitialization(VarDecl *VDecl, Expr *&Init)
void handleParamModifierAttr(Decl *D, const ParsedAttr &AL)
bool CheckResourceBinOp(BinaryOperatorKind Opc, Expr *LHSExpr, Expr *RHSExpr, SourceLocation Loc)
bool CanPerformAggregateSplatCast(Expr *Src, QualType DestType)
bool ActOnResourceMemberAccessExpr(MemberExpr *ME)
bool IsScalarizedLayoutCompatible(QualType T1, QualType T2) const
QualType ActOnTemplateShorthand(TemplateDecl *Template, SourceLocation NameLoc)
void handleRootSignatureAttr(Decl *D, const ParsedAttr &AL)
bool CheckCompatibleParameterABI(FunctionDecl *New, FunctionDecl *Old)
QualType handleVectorBinOpConversion(ExprResult &LHS, ExprResult &RHS, QualType LHSType, QualType RHSType, bool IsCompAssign)
QualType checkMatrixComponent(Sema &S, QualType baseType, ExprValueKind &VK, SourceLocation OpLoc, const IdentifierInfo *CompName, SourceLocation CompLoc)
bool IsConstantBufferElementCompatible(QualType T1)
void handleResourceBindingAttr(Decl *D, const ParsedAttr &AL)
bool IsTypedResourceElementCompatible(QualType T1)
bool transformInitList(const InitializedEntity &Entity, InitListExpr *Init)
void handleNumThreadsAttr(Decl *D, const ParsedAttr &AL)
bool ActOnUninitializedVarDecl(VarDecl *D)
void handleVkExtBuiltinInputAttr(Decl *D, const ParsedAttr &AL)
bool canHaveOverloadedBinOp(QualType Ty, BinaryOperatorKind Opc)
void ActOnTopLevelFunction(FunctionDecl *FD)
bool handleResourceTypeAttr(QualType T, const ParsedAttr &AL)
void handleVkPushConstantAttr(Decl *D, const ParsedAttr &AL)
HLSLShaderAttr * mergeShaderAttr(Decl *D, const AttributeCommonInfo &AL, llvm::Triple::EnvironmentType ShaderType)
NamedDecl * getConstantBufferConversionFunction(QualType Type, CXXRecordDecl *RD)
void ActOnFinishBuffer(Decl *Dcl, SourceLocation RBrace)
void handleVkBindingAttr(Decl *D, const ParsedAttr &AL)
HLSLParamModifierAttr * mergeParamModifierAttr(Decl *D, const AttributeCommonInfo &AL, HLSLParamModifierAttr::Spelling Spelling)
QualType getInoutParameterType(QualType Ty)
void handleVkConstantIdAttr(Decl *D, const ParsedAttr &AL)
std::optional< ExprResult > tryPerformConstantBufferConversion(Expr *BaseExpr)
Decl * ActOnStartBuffer(Scope *BufferScope, bool CBuffer, SourceLocation KwLoc, IdentifierInfo *Ident, SourceLocation IdentLoc, SourceLocation LBrace)
bool diagnoseMatrixLayoutInstantiation(attr::Kind K, QualType T, SourceLocation Loc)
HLSLWaveSizeAttr * mergeWaveSizeAttr(Decl *D, const AttributeCommonInfo &AL, int Min, int Max, int Preferred, int SpelledArgsCount)
bool handleRootSignatureElements(ArrayRef< hlsl::RootSignatureElement > Elements)
bool CanPerformPackedTypeCast(Expr *Src, QualType DestTy)
void ActOnFinishRootSignatureDecl(SourceLocation Loc, IdentifierInfo *DeclIdent, ArrayRef< hlsl::RootSignatureElement > Elements)
Creates the Root Signature decl of the parsed Root Signature elements onto the AST and push it onto c...
void ActOnVariableDeclarator(VarDecl *VD)
bool CheckBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall)
Sema - This implements semantic analysis and AST building for C.
@ LookupOrdinaryName
Ordinary name lookup, which finds ordinary names (functions, variables, typedefs, etc....
@ LookupMemberName
Member name lookup, which finds the names of class/struct/union members.
bool checkArgCountAtMost(CallExpr *Call, unsigned MaxArgCount)
Checks that a call expression's argument count is at most the desired number.
ExtVectorDeclsType ExtVectorDecls
ExtVectorDecls - This is a list all the extended vector types.
FunctionDecl * getCurFunctionDecl(bool AllowLambda=false) const
Returns a pointer to the innermost enclosing function, or nullptr if the current context is not insid...
ASTContext & getASTContext() const
ExprResult ImpCastExprToType(Expr *E, QualType Type, CastKind CK, ExprValueKind VK=VK_PRValue, const CXXCastPath *BasePath=nullptr, CheckedConversionKind CCK=CheckedConversionKind::Implicit)
ImpCastExprToType - If Expr is not of type 'Type', insert an implicit cast.
const LangOptions & getLangOpts() const
ExprResult TemporaryMaterializationConversion(Expr *E)
If E is a prvalue denoting an unmaterialized temporary, materialize it as an xvalue.
ExprResult BuildFieldReferenceExpr(Expr *BaseExpr, bool IsArrow, SourceLocation OpLoc, const CXXScopeSpec &SS, FieldDecl *Field, DeclAccessPair FoundDecl, const DeclarationNameInfo &MemberNameInfo)
bool checkArgCountRange(CallExpr *Call, unsigned MinArgCount, unsigned MaxArgCount)
Checks that a call expression's argument count is in the desired range.
ExternalSemaSource * getExternalSource() const
bool checkArgCount(CallExpr *Call, unsigned DesiredArgCount)
Checks that a call expression's argument count is the desired number.
ExprResult CreateBuiltinArraySubscriptExpr(Expr *Base, SourceLocation LLoc, Expr *Idx, SourceLocation RLoc)
bool LookupQualifiedName(LookupResult &R, DeclContext *LookupCtx, bool InUnqualifiedLookup=false)
Perform qualified name lookup into a given context.
ExprResult PerformCopyInitialization(const InitializedEntity &Entity, SourceLocation EqualLoc, ExprResult Init, bool TopLevelOfInitList=false, bool AllowExplicit=false)
ExprResult CreateBuiltinMatrixSubscriptExpr(Expr *Base, Expr *RowIdx, Expr *ColumnIdx, SourceLocation RBLoc)
Encodes a location in the source.
bool isValid() const
Return true if this is a valid SourceLocation object.
SourceLocation getLocWithOffset(IntTy Offset) const
Return a source location with the specified offset from this SourceLocation.
A trivial tuple used to represent a source range.
SourceLocation getEnd() const
SourceLocation getEndLoc() const LLVM_READONLY
void printPretty(raw_ostream &OS, PrinterHelper *Helper, const PrintingPolicy &Policy, unsigned Indentation=0, StringRef NewlineSymbol="\n", const ASTContext *Context=nullptr) const
SourceRange getSourceRange() const LLVM_READONLY
SourceLocation tokens are not useful in isolation - they are low level value objects created/interpre...
SourceLocation getBeginLoc() const LLVM_READONLY
StringLiteral - This represents a string literal expression, e.g.
static StringLiteral * Create(const ASTContext &Ctx, StringRef Str, StringLiteralKind Kind, bool Pascal, QualType Ty, ArrayRef< SourceLocation > Locs)
This is the "fully general" constructor that allows representation of strings formed from one or more...
void startDefinition()
Starts the definition of this tag declaration.
Exposes information about the current target.
TargetOptions & getTargetOpts() const
Retrieve the target options.
const llvm::Triple & getTriple() const
Returns the target triple of the primary target.
StringRef getPlatformName() const
Retrieve the name of the platform as it is used in the availability attribute.
VersionTuple getPlatformMinVersion() const
Retrieve the minimum desired version of the platform, to which the program should be compiled.
std::string HLSLEntry
The entry point name for HLSL shader being compiled as specified by -E.
A convenient class for passing around template argument information.
void addArgument(const TemplateArgumentLoc &Loc)
The base class of all kinds of template declarations (e.g., class, function, etc.).
Stores a list of template parameters for a TemplateDecl and its derived classes.
The top declaration context.
SourceLocation getBeginLoc() const
Get the begin source location.
A container of type source information.
TypeLoc getTypeLoc() const
Return the TypeLoc wrapper for the type source info.
The base class of the type hierarchy.
bool isBooleanType() const
bool isIncompleteArrayType() const
bool isFloat16Type() const
CXXRecordDecl * getAsCXXRecordDecl() const
Retrieves the CXXRecordDecl that this type refers to, either because the type is a RecordType or beca...
bool isConstantArrayType() const
bool hasIntegerRepresentation() const
Determine whether this type has an integer representation of some sort, e.g., it is an integer type o...
CXXRecordDecl * castAsCXXRecordDecl() const
bool isArithmeticType() const
bool isConstantMatrixType() const
bool isHLSLBuiltinIntangibleType() const
bool isPointerType() const
CanQualType getCanonicalTypeUnqualified() const
bool isIntegerType() const
isIntegerType() does not include complex integers (a GCC extension).
const T * castAs() const
Member-template castAs<specific type>.
bool isReferenceType() const
bool isHLSLIntangibleType() const
bool isEnumeralType() const
bool isScalarType() const
bool isIntegralType(const ASTContext &Ctx) const
Determine whether this type is an integral type.
const Type * getArrayElementTypeNoTypeQual() const
If this is an array type, return the element type of the array, potentially with type qualifiers miss...
QualType getPointeeType() const
If this is a pointer, ObjC object pointer, or block pointer, this returns the respective pointee.
bool hasUnsignedIntegerRepresentation() const
Determine whether this type has an unsigned integer representation of some sort, e....
bool isSpecificBuiltinType(unsigned K) const
Test for a particular builtin type.
bool isDependentType() const
Whether this type is a dependent type, meaning that its definition somehow depends on a template para...
bool isAggregateType() const
Determines whether the type is a C++ aggregate type or C aggregate or union type.
bool isFloat32Type() const
ScalarTypeKind getScalarTypeKind() const
Given that this is a scalar type, classify it.
bool hasSignedIntegerRepresentation() const
Determine whether this type has an signed integer representation of some sort, e.g....
bool isMatrixType() const
bool isHLSLBuiltinPackedType() const
bool isHLSLResourceRecord() const
bool hasFloatingRepresentation() const
Determine whether this type has a floating-point representation of some sort, e.g....
bool isVectorType() const
bool isRealFloatingType() const
Floating point categories.
bool isHLSLAttributedResourceType() const
bool isFloatingType() const
bool isUnsignedIntegerType() const
Return true if this is an integer type that is unsigned, according to C99 6.2.5p6 [which returns true...
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
void setType(QualType newType)
Represents a variable declaration or definition.
static VarDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc, const IdentifierInfo *Id, QualType T, TypeSourceInfo *TInfo, StorageClass S)
void setInitStyle(InitializationStyle Style)
@ CallInit
Call-style initialization (C++98)
void setStorageClass(StorageClass SC)
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.
unsigned getNumElements() const
QualType getElementType() const
void pushName(llvm::StringRef N)
void pushArrayIndex(uint64_t Index)
void pushBaseName(llvm::StringRef N)
IdentifierInfo * getNameAsIdentifier(ASTContext &AST) const
Defines the clang::TargetInfo interface.
bool isStructOrArrayOfWithResources(QualType Ty)
uint32_t getResourceDimensions(llvm::dxil::ResourceDimension Dim)
bool hasResourceOffset(llvm::dxil::ResourceDimension Dim)
bool hasCounterHandle(const CXXRecordDecl *RD)
SetTy< T > join(SetTy< T > A, SetTy< T > B, typename SetTy< T >::Factory &F)
Computes the union of two ImmutableSets.
Top level wrappers for InstallAPI frontend operations.
bool isa(CodeGen::Address addr)
if(T->getSizeExpr()) TRY_TO(TraverseStmt(const_cast< Expr * >(T -> getSizeExpr())))
static bool CheckFloatOrHalfRepresentation(Sema *S, SourceLocation Loc, int ArgOrdinal, clang::QualType PassedType)
@ ICIS_NoInit
No in-class initializer.
@ TemplateName
The identifier is a template name. FIXME: Add an annotation for that.
@ OK_Ordinary
An ordinary object is located at an address in memory.
static bool CheckAllArgTypesAreCorrect(Sema *S, CallExpr *TheCall, llvm::ArrayRef< llvm::function_ref< bool(Sema *, SourceLocation, int, QualType)> > Checks)
bool isMatrixRowMajor(const LangOptions &LangOpts, QualType T)
Returns true if matrices of T should be laid out in row-major order.
@ AANT_ArgumentIdentifier
@ Result
The result type of a method or function.
@ Ordinary
This parameter uses ordinary ABI rules for its type.
const FunctionProtoType * T
llvm::Expected< QualType > ExpectedType
@ Template
We are parsing a template declaration.
LLVM_READONLY bool isDigit(unsigned char c)
Return true if this character is an ASCII digit: [0-9].
static bool CheckAllArgsHaveSameType(Sema *S, CallExpr *TheCall)
LangAS
Defines the address space values used by the address space qualifier of QualType.
CastKind
CastKind - The kind of operation required for a conversion.
ExprValueKind
The categorization of expression values, currently following the C++11 scheme.
@ VK_PRValue
A pr-value expression (in the C++11 taxonomy) produces a temporary value.
@ VK_LValue
An l-value expression is a reference to an object with independent storage.
bool CreateHLSLAttributedResourceType(Sema &S, QualType Wrapped, ArrayRef< const Attr * > AttrList, QualType &ResType, HLSLAttributedResourceLocInfo *LocInfo=nullptr, Expr *SampleCountExpr=nullptr)
DynamicRecursiveASTVisitorBase< false > DynamicRecursiveASTVisitor
U cast(CodeGen::Address addr)
@ None
No keyword precedes the qualified type name.
ActionResult< Expr * > ExprResult
Visibility
Describes the different kinds of visibility that a declaration may have.
hash_code hash_value(const clang::dependencies::ModuleID &ID)
__DEVICE__ bool isnan(float __x)
__DEVICE__ _Tp abs(const std::complex< _Tp > &__c)
int __ovld __cnfn any(char)
Returns 1 if the most significant bit in any component of x is set; otherwise returns 0.
__builtin_elementwise_add_sat __builtin_elementwise_sub_sat uint32_t uint64_t __builtin_riscv_ssha_i32 __builtin_riscv_sshl_u32 unsigned
__builtin_elementwise_add_sat __builtin_elementwise_sub_sat uint32_t int64_t
__builtin_elementwise_add_sat __builtin_elementwise_sub_sat uint32_t uint64_t __builtin_riscv_ssha_i32 __builtin_riscv_sshl_u32 uint64_t
TypeSourceInfo * ContainedTyInfo
Describes how types, statements, expressions, and declarations should be printed.
unsigned getImplicitOrderID() const
void setCounterImplicitOrderID(unsigned Value) const
bool hasCounterImplicitOrderID() const
unsigned getSpace() const
bool hasImplicitOrderID() const
void setImplicitOrderID(unsigned Value) const
const SourceLocation & getLocation() const
const llvm::hlsl::rootsig::RootElement & getElement() const