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;
1036 case SemanticKind::ViewPortArrayIndex:
1037 case SemanticKind::RenderTargetArrayIndex:
1038 return (ST == llvm::Triple::Vertex && !IsInput) ||
1039 (ST == llvm::Triple::Pixel && IsInput);
1040 case SemanticKind::Coverage:
1042 return ST == llvm::Triple::Pixel;
1043 case SemanticKind::InnerCoverage:
1044 return ST == llvm::Triple::Pixel && IsInput;
1045 case SemanticKind::CullDistance:
1048 return (ST == llvm::Triple::Vertex && !IsInput) ||
1049 (ST == llvm::Triple::Pixel && IsInput);
1057 const HLSLVkBuiltInAttr *
Attr,
1058 IOType CurrentIOType) {
1063 StringRef BuiltIn =
Attr->getBuiltIn();
1067 const auto *ShaderAttr = FD->
getAttr<HLSLShaderAttr>();
1068 assert(ShaderAttr &&
"Entry point has no shader attribute");
1069 llvm::Triple::EnvironmentType Stage = ShaderAttr->getType();
1070 bool IsIn =
any(CurrentIOType & IOType::In);
1071 bool IsOut =
any(CurrentIOType & IOType::Out);
1073 if (BuiltIn ==
"PointSize") {
1077 bool Is32BitFloat = T->isSpecificBuiltinType(BuiltinType::Float) ||
1078 (T->isSpecificBuiltinType(BuiltinType::Half) &&
1087 bool IsPatchConstantOrPrimitive =
1088 any(CurrentIOType & IOType::PatchConstantOrPrimitive);
1090 !IsPatchConstantOrPrimitive &&
1091 ((Stage == llvm::Triple::Vertex && IsOut) ||
1092 Stage == llvm::Triple::Hull || Stage == llvm::Triple::Domain ||
1093 Stage == llvm::Triple::Geometry ||
1094 (Stage == llvm::Triple::Mesh && IsOut) ||
1098 (Stage == llvm::Triple::Pixel && IsIn && !IsOut));
1100 StringRef IOTypeName = (IsIn && IsOut) ?
"inputs and outputs"
1104 << BuiltIn << llvm::Triple::getEnvironmentTypeName(Stage)
1110bool SemaHLSL::determineActiveSemanticOnScalar(
FunctionDecl *FD,
1113 SemanticInfo &ActiveSemantic,
1114 SemaHLSL::SemanticContext &SC) {
1115 if (ActiveSemantic.Semantic ==
nullptr) {
1116 ActiveSemantic.Semantic = D->
getAttr<HLSLParsedSemanticAttr>();
1117 if (ActiveSemantic.Semantic)
1118 ActiveSemantic.Index = ActiveSemantic.Semantic->getSemanticIndex();
1121 if (!ActiveSemantic.Semantic) {
1127 HLSLAppliedSemanticAttr(
getASTContext(), *ActiveSemantic.Semantic,
1128 ActiveSemantic.Semantic->getAttrName()->getName(),
1129 ActiveSemantic.Index.value_or(0));
1134 QualType T = D == FD ? FD->getReturnType() : D->
getType();
1135 const ConstantArrayType *AT =
1136 getASTContext().getAsConstantArrayType(T.getNonReferenceType());
1138 Diag(A->getLoc(), diag::err_hlsl_semantic_zero_sized_array)
1139 << A->getAttrName();
1147 if (
const auto *MT = BaseTy->
getAs<ConstantMatrixType>())
1150 : MT->getNumColumns();
1152 checkSemanticAnnotation(FD, D, A, SC, ElementCount);
1155 unsigned Location = ActiveSemantic.Index.value_or(0);
1158 any(SC.CurrentIOType & IOType::In));
1160 if (
const auto *BuiltInAttr = D->
getAttr<HLSLVkBuiltInAttr>())
1165 bool HasVkLocation =
false;
1166 if (
auto *A = D->
getAttr<HLSLVkLocationAttr>()) {
1167 HasVkLocation =
true;
1168 Location = A->getLocation();
1171 if (SC.UsesExplicitVkLocations.value_or(HasVkLocation) != HasVkLocation) {
1172 Diag(D->
getLocation(), diag::err_hlsl_semantic_partial_explicit_indexing);
1175 SC.UsesExplicitVkLocations = HasVkLocation;
1178 ActiveSemantic.Index = Location + ElementCount;
1180 StringRef BaseName = ActiveSemantic.Semantic->getAttrName()->getName();
1181 std::string LowerName = BaseName.lower();
1182 for (
unsigned I = 0; I < ElementCount; ++I) {
1183 auto [It, Inserted] = SC.ActiveSemantics.try_emplace(
1184 (Twine(LowerName) + Twine(Location + I)).str(), D->
getLocation());
1187 << (BaseName + Twine(Location + I)).str();
1188 Diag(It->second, diag::note_previous_use);
1196bool SemaHLSL::determineActiveSemantic(
FunctionDecl *FD,
1199 SemanticInfo &ActiveSemantic,
1200 SemaHLSL::SemanticContext &SC) {
1201 if (ActiveSemantic.Semantic ==
nullptr) {
1202 ActiveSemantic.Semantic = D->
getAttr<HLSLParsedSemanticAttr>();
1203 if (ActiveSemantic.Semantic)
1204 ActiveSemantic.Index = ActiveSemantic.Semantic->getSemanticIndex();
1210 const RecordType *RT = dyn_cast<RecordType>(T);
1212 return determineActiveSemanticOnScalar(FD, OutputDecl, D, ActiveSemantic,
1215 const RecordDecl *RD = RT->getDecl();
1216 for (FieldDecl *Field : RD->
fields()) {
1217 SemanticInfo Info = ActiveSemantic;
1218 if (!determineActiveSemantic(FD, OutputDecl, Field, Info, SC)) {
1219 Diag(
Field->getLocation(), diag::note_hlsl_semantic_used_here) <<
Field;
1222 if (ActiveSemantic.Semantic)
1223 ActiveSemantic = Info;
1230 const auto *ShaderAttr = FD->
getAttr<HLSLShaderAttr>();
1231 assert(ShaderAttr &&
"Entry point has no shader attribute");
1232 llvm::Triple::EnvironmentType ST = ShaderAttr->getType();
1236 case llvm::Triple::Pixel:
1237 case llvm::Triple::Vertex:
1238 case llvm::Triple::Geometry:
1239 case llvm::Triple::Hull:
1240 case llvm::Triple::Domain:
1241 case llvm::Triple::RayGeneration:
1242 case llvm::Triple::Intersection:
1243 case llvm::Triple::AnyHit:
1244 case llvm::Triple::ClosestHit:
1245 case llvm::Triple::Miss:
1246 case llvm::Triple::Callable:
1247 if (
const auto *NT = FD->
getAttr<HLSLNumThreadsAttr>()) {
1248 diagnoseAttrStageMismatch(NT, ST,
1249 {llvm::Triple::Compute,
1250 llvm::Triple::Amplification,
1251 llvm::Triple::Mesh});
1254 if (
const auto *WS = FD->
getAttr<HLSLWaveSizeAttr>()) {
1255 diagnoseAttrStageMismatch(WS, ST,
1256 {llvm::Triple::Compute,
1257 llvm::Triple::Amplification,
1258 llvm::Triple::Mesh});
1263 case llvm::Triple::Compute:
1264 case llvm::Triple::Amplification:
1265 case llvm::Triple::Mesh:
1266 if (!FD->
hasAttr<HLSLNumThreadsAttr>()) {
1268 << llvm::Triple::getEnvironmentTypeName(ST);
1271 if (
const auto *WS = FD->
getAttr<HLSLWaveSizeAttr>()) {
1273 Diag(WS->getLocation(), diag::warn_hlsl_wavesize_unsupported_spirv);
1274 }
else if (Ver < VersionTuple(6, 6)) {
1275 Diag(WS->getLocation(), diag::err_hlsl_attribute_in_wrong_shader_model)
1278 }
else if (WS->getSpelledArgsCount() > 1 && Ver < VersionTuple(6, 8)) {
1281 diag::err_hlsl_attribute_number_arguments_insufficient_shader_model)
1282 << WS << WS->getSpelledArgsCount() <<
"6.8";
1287 case llvm::Triple::RootSignature:
1288 llvm_unreachable(
"rootsig environment has no function entry point");
1290 llvm_unreachable(
"Unhandled environment in triple");
1293 SemaHLSL::SemanticContext InputSC = {};
1294 InputSC.CurrentIOType = IOType::In;
1295 SemaHLSL::SemanticContext OutputSC = {};
1296 OutputSC.CurrentIOType = IOType::Out;
1299 SemanticInfo ActiveSemantic;
1300 ActiveSemantic.Semantic = Param->getAttr<HLSLParsedSemanticAttr>();
1301 if (ActiveSemantic.Semantic)
1302 ActiveSemantic.Index = ActiveSemantic.Semantic->getSemanticIndex();
1306 const auto *MA = Param->getAttr<HLSLParamModifierAttr>();
1307 SemanticContext &SC = MA && MA->isAnyOut() ? OutputSC : InputSC;
1311 if (((ST == llvm::Triple::Pixel && (!MA || MA->isAnyIn())) ||
1312 (ST == llvm::Triple::Vertex && MA && MA->isAnyOut())) &&
1313 !checkInterpolationModifiers(Param,
nullptr,
nullptr))
1316 if (!determineActiveSemantic(FD, Param, Param, ActiveSemantic, SC)) {
1317 Diag(Param->getLocation(), diag::note_previous_decl) << Param;
1324 if (ST == llvm::Triple::Pixel) {
1325 auto Coverage = InputSC.ActiveSemantics.find(
"sv_coverage0");
1326 auto InnerCoverage = InputSC.ActiveSemantics.find(
"sv_innercoverage0");
1327 if (Coverage != InputSC.ActiveSemantics.end() &&
1328 InnerCoverage != InputSC.ActiveSemantics.end()) {
1329 Diag(InnerCoverage->second, diag::err_hlsl_semantic_mutually_exclusive)
1330 <<
"SV_Coverage" <<
"SV_InnerCoverage"
1331 << llvm::Triple::getEnvironmentTypeName(ST) <<
"inputs";
1332 Diag(Coverage->second, diag::note_previous_use);
1337 SemanticInfo ActiveSemantic;
1338 ActiveSemantic.Semantic = FD->
getAttr<HLSLParsedSemanticAttr>();
1339 if (ActiveSemantic.Semantic)
1340 ActiveSemantic.Index = ActiveSemantic.Semantic->getSemanticIndex();
1342 if (ST == llvm::Triple::Vertex &&
1343 !checkInterpolationModifiers(FD,
nullptr,
nullptr))
1345 determineActiveSemantic(FD, FD, FD, ActiveSemantic, OutputSC);
1349void SemaHLSL::checkSemanticAnnotation(
1351 const HLSLAppliedSemanticAttr *SemanticAttr,
const SemanticContext &SC,
1352 unsigned ElementCount) {
1353 auto *ShaderAttr = EntryPoint->
getAttr<HLSLShaderAttr>();
1354 assert(ShaderAttr &&
"Entry point has no shader attribute");
1355 llvm::Triple::EnvironmentType ST = ShaderAttr->getType();
1358 llvm::hlsl::getSemanticKind(SemanticAttr->getSemanticName());
1359 llvm::hlsl::SemanticInterpretation Interpretation =
1360 llvm::hlsl::getInterpretationKind(Kind, ST, SC.CurrentIOType);
1361 if (Interpretation == llvm::hlsl::SemanticInterpretation::Invalid) {
1362 diagnoseSemanticStageMismatch(SemanticAttr, ST, SC.CurrentIOType, Kind);
1368 if (Interpretation == llvm::hlsl::SemanticInterpretation::Arbitrary) {
1369 diagnoseSemanticType(Param, SemanticAttr, SemanticKind::Arbitrary);
1373 diagnoseSystemSemanticIndex(SemanticAttr, Kind, ElementCount);
1374 diagnoseSemanticType(Param, SemanticAttr, Kind);
1375 diagnoseSemanticShaderModel(SemanticAttr, Kind);
1378void SemaHLSL::diagnoseSemanticShaderModel(
const HLSLAppliedSemanticAttr *A,
1381 if (!Triple.isDXIL())
1385 case SemanticKind::Barycentrics:
1386 case SemanticKind::ViewID:
1387 if (Triple.getOSVersion() < VersionTuple(6, 1))
1388 Diag(A->getLoc(), diag::err_hlsl_semantic_in_wrong_shader_model)
1389 << A->getAttrName() <<
"6.1";
1391 case SemanticKind::ShadingRate:
1392 if (Triple.getOSVersion() < VersionTuple(6, 4))
1393 Diag(A->getLoc(), diag::err_hlsl_semantic_in_wrong_shader_model)
1394 << A->getAttrName() <<
"6.4";
1396 case SemanticKind::StartVertexLocation:
1397 case SemanticKind::StartInstanceLocation:
1398 if (Triple.getOSVersion() < VersionTuple(6, 8))
1399 Diag(A->getLoc(), diag::err_hlsl_semantic_in_wrong_shader_model)
1400 << A->getAttrName() <<
"6.8";
1407void SemaHLSL::diagnoseSystemSemanticIndex(
const HLSLAppliedSemanticAttr *A,
1409 unsigned ElementCount) {
1410 assert(Kind != SemanticKind::Invalid && Kind != SemanticKind::Arbitrary &&
1411 "expected a recognized system semantic");
1412 assert(ElementCount > 0 &&
"a semantic covers at least one element");
1415 uint32_t FirstIndex = A->getSemanticIndex();
1417 constexpr uint32_t MaxSemanticIndex = std::numeric_limits<uint32_t>::max();
1418 if (LastIndex > MaxSemanticIndex) {
1419 Diag(A->getLoc(), diag::err_hlsl_semantic_index_out_of_range)
1420 << A->getAttrName() << LastIndex << MaxSemanticIndex;
1428 case SemanticKind::ClipDistance:
1429 case SemanticKind::CullDistance:
1431 case SemanticKind::Target: {
1432 constexpr unsigned MaxTargetIndex = 7;
1433 if (LastIndex > MaxTargetIndex)
1434 Diag(A->getLoc(), diag::err_hlsl_semantic_index_out_of_range)
1435 << A->getAttrName() << LastIndex << MaxTargetIndex;
1439 Diag(A->getLoc(), diag::err_hlsl_semantic_indexing_not_supported)
1440 << A->getAttrName();
1447 return VT->getElementType();
1450 return MT->getElementType();
1456 return VT->getNumElements();
1477void SemaHLSL::diagnoseSemanticType(
const Decl *D,
1478 const HLSLAppliedSemanticAttr *A,
1480 assert(Kind != SemanticKind::Invalid &&
"expected a valid semantic");
1484 if (
const auto *FD = dyn_cast<FunctionDecl>(D))
1493 QualType DeclaredTy = T;
1495 T = AT->getElementType();
1503 case SemanticKind::Barycentrics:
1505 Diag(A->getLoc(), diag::err_hlsl_semantic_invalid_type)
1506 << A->getAttrName() << 2 << 3
1509 case SemanticKind::DispatchThreadID:
1510 case SemanticKind::GroupID:
1511 case SemanticKind::GroupThreadID:
1513 Diag(A->getLoc(), diag::err_hlsl_semantic_invalid_type)
1514 << A->getAttrName() << 1 << 3
1517 case SemanticKind::StartVertexLocation:
1518 case SemanticKind::StartInstanceLocation:
1519 case SemanticKind::ViewID:
1520 case SemanticKind::Coverage:
1521 case SemanticKind::InnerCoverage:
1524 Diag(A->getLoc(), diag::err_hlsl_semantic_invalid_type)
1525 << A->getAttrName() << 0 << 1 << 1
1528 case SemanticKind::GroupIndex:
1530 Diag(A->getLoc(), diag::err_hlsl_semantic_invalid_type)
1531 << A->getAttrName() << 0 << 1 << 1
1534 case SemanticKind::VertexID:
1536 Diag(A->getLoc(), diag::err_hlsl_semantic_invalid_type)
1537 << A->getAttrName() << 0 << 1
1540 case SemanticKind::Position:
1541 case SemanticKind::Target:
1543 Diag(A->getLoc(), diag::err_hlsl_semantic_invalid_type)
1544 << A->getAttrName() << 1 << 4
1547 case SemanticKind::CullDistance: {
1556 if (!IsValidFloat || Components > 4)
1557 Diag(A->getLoc(), diag::err_hlsl_semantic_invalid_type)
1558 << A->getAttrName() << 1 << 4
1560 (IsSPIRV ? 6 : 2) << DeclaredTy;
1563 case SemanticKind::SampleIndex:
1564 case SemanticKind::PrimitiveID:
1565 case SemanticKind::StencilRef:
1566 case SemanticKind::ViewPortArrayIndex:
1567 case SemanticKind::RenderTargetArrayIndex:
1571 Diag(A->getLoc(), diag::err_hlsl_semantic_invalid_type)
1572 << A->getAttrName() << 0 << 1
1575 case SemanticKind::InstanceID:
1576 case SemanticKind::ShadingRate:
1583 Diag(A->getLoc(), diag::err_hlsl_semantic_invalid_type)
1584 << A->getAttrName() << 0 << 1
1586 (IsSPIRV ? 4 : 3) << DeclaredTy;
1588 case SemanticKind::IsFrontFace:
1593 Diag(A->getLoc(), diag::err_hlsl_semantic_invalid_type)
1594 << A->getAttrName() << 0 << 1
1608 Diag(A->getLoc(), diag::err_hlsl_semantic_64bit_type)
1609 << A->getAttrName() << DeclaredTy;
1612void SemaHLSL::diagnoseAttrStageMismatch(
1613 const Attr *A, llvm::Triple::EnvironmentType Stage,
1614 std::initializer_list<llvm::Triple::EnvironmentType> AllowedStages) {
1615 SmallVector<StringRef, 8> StageStrings;
1616 llvm::transform(AllowedStages, std::back_inserter(StageStrings),
1617 [](llvm::Triple::EnvironmentType ST) {
1619 HLSLShaderAttr::ConvertEnvironmentTypeToStr(ST));
1621 Diag(A->
getLoc(), diag::err_hlsl_attr_unsupported_in_stage)
1622 << A->
getAttrName() << llvm::Triple::getEnvironmentTypeName(Stage)
1623 << (AllowedStages.size() != 1) <<
join(StageStrings,
", ");
1626void SemaHLSL::diagnoseSemanticStageMismatch(
1627 const Attr *A, llvm::Triple::EnvironmentType Stage, IOType CurrentIOType,
1630 ArrayRef<SemanticStageInfo> Allowed = llvm::hlsl::getAvailableStages(Kind);
1631 auto It = llvm::find_if(Allowed, [&Stage](
const SemanticStageInfo &Info) {
1632 return Info.Stage == Stage;
1635 StringRef CurrentIOTypeName =
"patch constants or primitives";
1636 if (
any(CurrentIOType & IOType::In))
1637 CurrentIOTypeName =
"inputs";
1638 else if (
any(CurrentIOType & IOType::Out))
1639 CurrentIOTypeName =
"outputs";
1642 if (It == Allowed.end()) {
1643 Diag(A->
getLoc(), diag::err_hlsl_semantic_unsupported_iotype_for_stage)
1644 << A->
getAttrName() << llvm::Triple::getEnvironmentTypeName(Stage)
1645 << CurrentIOTypeName;
1649 IOType AllowedIOTypes = It->AllowedIOTypesMask;
1650 if (!(AllowedIOTypes & CurrentIOType)) {
1651 Diag(A->
getLoc(), diag::err_hlsl_semantic_unsupported_iotype_for_stage)
1652 << A->
getAttrName() << llvm::Triple::getEnvironmentTypeName(Stage)
1653 << CurrentIOTypeName;
1658template <CastKind Kind>
1661 Ty = VTy->getElementType();
1666template <CastKind Kind>
1678 if (LHSFloat && RHSFloat) {
1706 if (LHSSigned == RHSSigned) {
1707 if (IsCompAssign || IntOrder >= 0)
1715 if (IntOrder != (LHSSigned ? 1 : -1)) {
1716 if (IsCompAssign || RHSSigned)
1725 if (IsCompAssign || LHSSigned)
1752 return CK_FloatingCast;
1754 return CK_IntegralCast;
1756 return CK_IntegralToFloating;
1758 return CK_FloatingToIntegral;
1764 bool IsCompAssign) {
1771 if (!LVecTy && IsCompAssign) {
1773 RHS =
SemaRef.ImpCastExprToType(RHS.
get(), RElTy, CK_HLSLVectorTruncation);
1775 if (Ctx.hasSameUnqualifiedType(LHSType, RHSType))
1777 RHS =
SemaRef.ImpCastExprToType(RHS.
get(), LHSType,
1782 unsigned EndSz = std::numeric_limits<unsigned>::max();
1785 LSz = EndSz = LVecTy->getNumElements();
1788 assert(EndSz != std::numeric_limits<unsigned>::max() &&
1789 "one of the above should have had a value");
1793 if (IsCompAssign && LSz != EndSz) {
1795 diag::err_hlsl_vector_compound_assignment_truncation)
1796 << LHSType << RHSType;
1802 if (!IsCompAssign && LVecTy && LVecTy->getNumElements() > EndSz)
1807 if (!IsCompAssign && !LVecTy)
1811 if (Ctx.hasSameUnqualifiedType(LHSType, RHSType))
1812 return Ctx.getCommonSugaredType(LHSType, RHSType);
1820 LElTy, RElTy, IsCompAssign);
1823 "HLSL Vectors can only contain integer or floating point types");
1825 LElTy, RElTy, IsCompAssign);
1830 assert((Opc == BO_LOr || Opc == BO_LAnd) &&
1831 "Called with non-logical operator");
1833 llvm::raw_svector_ostream OS(Buff);
1835 StringRef NewFnName = Opc == BO_LOr ?
"or" :
"and";
1836 OS << NewFnName <<
"(";
1846std::pair<IdentifierInfo *, bool>
1849 std::string IdStr =
"__hlsl_rootsig_decl_" + std::to_string(Hash);
1856 return {DeclIdent,
Found};
1867 for (
auto &RootSigElement : RootElements)
1868 Elements.push_back(RootSigElement.getElement());
1872 DeclIdent,
SemaRef.getLangOpts().HLSLRootSigVer, Elements);
1874 SignatureDecl->setImplicit();
1880 if (RootSigOverrideIdent) {
1883 if (
SemaRef.LookupQualifiedName(R, DC))
1884 return dyn_cast<HLSLRootSignatureDecl>(R.getFoundDecl());
1892struct PerVisibilityBindingChecker {
1895 std::array<llvm::hlsl::BindingInfoBuilder, 8> Builders;
1899 llvm::dxbc::ShaderVisibility Vis;
1904 PerVisibilityBindingChecker(
SemaHLSL *S) : S(S) {}
1906 void trackBinding(llvm::dxbc::ShaderVisibility
Visibility,
1907 llvm::dxil::ResourceClass RC,
uint32_t Space,
1909 const hlsl::RootSignatureElement *Elem) {
1911 assert(BuilderIndex < Builders.size() &&
1912 "Not enough builders for visibility type");
1913 Builders[BuilderIndex].trackBinding(RC, Space, LowerBound, UpperBound,
1914 static_cast<const void *
>(Elem));
1916 static_assert(llvm::to_underlying(llvm::dxbc::ShaderVisibility::All) == 0,
1917 "'All' visibility must come first");
1918 if (
Visibility == llvm::dxbc::ShaderVisibility::All)
1919 for (
size_t I = 1, E = Builders.size(); I < E; ++I)
1920 Builders[I].trackBinding(RC, Space, LowerBound, UpperBound,
1921 static_cast<const void *
>(Elem));
1923 ElemInfoMap.push_back({Elem,
Visibility,
false});
1926 ElemInfo &
getInfo(
const hlsl::RootSignatureElement *Elem) {
1927 auto It = llvm::lower_bound(
1929 [](
const auto &LHS,
const auto &RHS) {
return LHS.Elem < RHS; });
1930 assert(It->Elem == Elem &&
"Element not in map");
1934 bool checkOverlap() {
1935 llvm::sort(ElemInfoMap, [](
const auto &LHS,
const auto &RHS) {
1936 return LHS.Elem < RHS.Elem;
1939 bool HadOverlap =
false;
1941 using llvm::hlsl::BindingInfoBuilder;
1942 auto ReportOverlap = [
this,
1943 &HadOverlap](
const BindingInfoBuilder &Builder,
1944 const llvm::hlsl::Binding &Reported) {
1948 static_cast<const hlsl::RootSignatureElement *
>(Reported.Cookie);
1949 const llvm::hlsl::Binding &
Previous = Builder.findOverlapping(Reported);
1950 const auto *PrevElem =
1951 static_cast<const hlsl::RootSignatureElement *
>(
Previous.Cookie);
1953 ElemInfo &Info =
getInfo(Elem);
1958 Info.Diagnosed =
true;
1960 ElemInfo &PrevInfo =
getInfo(PrevElem);
1961 llvm::dxbc::ShaderVisibility CommonVis =
1962 Info.Vis == llvm::dxbc::ShaderVisibility::All ? PrevInfo.Vis
1965 this->S->
Diag(Elem->
getLocation(), diag::err_hlsl_resource_range_overlap)
1966 << llvm::to_underlying(Reported.RC) << Reported.LowerBound
1967 << Reported.isUnbounded() << Reported.UpperBound
1972 this->S->
Diag(PrevElem->getLocation(),
1973 diag::note_hlsl_resource_range_here);
1976 for (BindingInfoBuilder &Builder : Builders)
1977 Builder.calculateBindingInfo(ReportOverlap);
1997 bool HadError =
false;
1998 auto ReportError = [
this, &HadError](
SourceLocation Loc, uint32_t LowerBound,
1999 uint32_t UpperBound) {
2001 this->
Diag(Loc, diag::err_hlsl_invalid_rootsig_value)
2002 << LowerBound << UpperBound;
2009 this->
Diag(Loc, diag::err_hlsl_invalid_rootsig_value)
2010 << llvm::formatv(
"{0:f}", LowerBound).sstr<6>()
2011 << llvm::formatv(
"{0:f}", UpperBound).sstr<6>();
2014 auto VerifyRegister = [ReportError](
SourceLocation Loc, uint32_t Register) {
2015 if (!llvm::hlsl::rootsig::verifyRegisterValue(Register))
2016 ReportError(Loc, 0, 0xfffffffe);
2019 auto VerifySpace = [ReportError](
SourceLocation Loc, uint32_t Space) {
2020 if (!llvm::hlsl::rootsig::verifyRegisterSpace(Space))
2021 ReportError(Loc, 0, 0xffffffef);
2024 const uint32_t Version =
2025 llvm::to_underlying(
SemaRef.getLangOpts().HLSLRootSigVer);
2026 const uint32_t VersionEnum = Version - 1;
2027 auto ReportFlagError = [
this, &HadError, VersionEnum](
SourceLocation Loc) {
2029 this->
Diag(Loc, diag::err_hlsl_invalid_rootsig_flag)
2036 const llvm::hlsl::rootsig::RootElement &Elem = RootSigElem.
getElement();
2037 if (
const auto *Descriptor =
2038 std::get_if<llvm::hlsl::rootsig::RootDescriptor>(&Elem)) {
2039 VerifyRegister(Loc, Descriptor->Reg.Number);
2040 VerifySpace(Loc, Descriptor->Space);
2042 if (!llvm::hlsl::rootsig::verifyRootDescriptorFlag(Version,
2044 ReportFlagError(Loc);
2045 }
else if (
const auto *Constants =
2046 std::get_if<llvm::hlsl::rootsig::RootConstants>(&Elem)) {
2047 VerifyRegister(Loc, Constants->Reg.Number);
2048 VerifySpace(Loc, Constants->Space);
2049 }
else if (
const auto *Sampler =
2050 std::get_if<llvm::hlsl::rootsig::StaticSampler>(&Elem)) {
2051 VerifyRegister(Loc, Sampler->Reg.Number);
2052 VerifySpace(Loc, Sampler->Space);
2055 "By construction, parseFloatParam can't produce a NaN from a "
2056 "float_literal token");
2058 if (!llvm::hlsl::rootsig::verifyMaxAnisotropy(Sampler->MaxAnisotropy))
2059 ReportError(Loc, 0, 16);
2060 if (!llvm::hlsl::rootsig::verifyMipLODBias(Sampler->MipLODBias))
2061 ReportFloatError(Loc, -16.f, 15.99f);
2062 }
else if (
const auto *Clause =
2063 std::get_if<llvm::hlsl::rootsig::DescriptorTableClause>(
2065 VerifyRegister(Loc, Clause->Reg.Number);
2066 VerifySpace(Loc, Clause->Space);
2068 if (!llvm::hlsl::rootsig::verifyNumDescriptors(Clause->NumDescriptors)) {
2072 ReportError(Loc, 1, 0xfffffffe);
2075 if (!llvm::hlsl::rootsig::verifyDescriptorRangeFlag(Version, Clause->Type,
2077 ReportFlagError(Loc);
2081 PerVisibilityBindingChecker BindingChecker(
this);
2082 SmallVector<std::pair<
const llvm::hlsl::rootsig::DescriptorTableClause *,
2087 const llvm::hlsl::rootsig::RootElement &Elem = RootSigElem.
getElement();
2088 if (
const auto *Descriptor =
2089 std::get_if<llvm::hlsl::rootsig::RootDescriptor>(&Elem)) {
2090 uint32_t LowerBound(Descriptor->Reg.Number);
2091 uint32_t UpperBound(LowerBound);
2093 BindingChecker.trackBinding(
2094 Descriptor->Visibility,
2095 static_cast<llvm::dxil::ResourceClass
>(Descriptor->Type),
2096 Descriptor->Space, LowerBound, UpperBound, &RootSigElem);
2097 }
else if (
const auto *Constants =
2098 std::get_if<llvm::hlsl::rootsig::RootConstants>(&Elem)) {
2099 uint32_t LowerBound(Constants->Reg.Number);
2100 uint32_t UpperBound(LowerBound);
2102 BindingChecker.trackBinding(
2103 Constants->Visibility, llvm::dxil::ResourceClass::CBuffer,
2104 Constants->Space, LowerBound, UpperBound, &RootSigElem);
2105 }
else if (
const auto *Sampler =
2106 std::get_if<llvm::hlsl::rootsig::StaticSampler>(&Elem)) {
2107 uint32_t LowerBound(Sampler->Reg.Number);
2108 uint32_t UpperBound(LowerBound);
2110 BindingChecker.trackBinding(
2111 Sampler->Visibility, llvm::dxil::ResourceClass::Sampler,
2112 Sampler->Space, LowerBound, UpperBound, &RootSigElem);
2113 }
else if (
const auto *Clause =
2114 std::get_if<llvm::hlsl::rootsig::DescriptorTableClause>(
2117 UnboundClauses.emplace_back(Clause, &RootSigElem);
2118 }
else if (
const auto *Table =
2119 std::get_if<llvm::hlsl::rootsig::DescriptorTable>(&Elem)) {
2120 assert(UnboundClauses.size() == Table->NumClauses &&
2121 "Number of unbound elements must match the number of clauses");
2122 bool HasAnySampler =
false;
2123 bool HasAnyNonSampler =
false;
2124 uint64_t Offset = 0;
2125 bool IsPrevUnbound =
false;
2126 for (
const auto &[Clause, ClauseElem] : UnboundClauses) {
2128 if (Clause->Type == llvm::dxil::ResourceClass::Sampler)
2129 HasAnySampler =
true;
2131 HasAnyNonSampler =
true;
2133 if (HasAnySampler && HasAnyNonSampler)
2134 Diag(Loc, diag::err_hlsl_invalid_mixed_resources);
2139 if (Clause->NumDescriptors == 0)
2143 Clause->Offset == llvm::hlsl::rootsig::DescriptorTableOffsetAppend;
2145 Offset = Clause->Offset;
2147 uint64_t RangeBound = llvm::hlsl::rootsig::computeRangeBound(
2148 Offset, Clause->NumDescriptors);
2150 if (IsPrevUnbound && IsAppending)
2151 Diag(Loc, diag::err_hlsl_appending_onto_unbound);
2152 else if (!llvm::hlsl::rootsig::verifyNoOverflowedOffset(RangeBound))
2153 Diag(Loc, diag::err_hlsl_offset_overflow) << Offset << RangeBound;
2156 Offset = RangeBound + 1;
2157 IsPrevUnbound = Clause->NumDescriptors ==
2158 llvm::hlsl::rootsig::NumDescriptorsUnbounded;
2161 uint32_t LowerBound(Clause->Reg.Number);
2162 uint32_t UpperBound = llvm::hlsl::rootsig::computeRangeBound(
2163 LowerBound, Clause->NumDescriptors);
2165 BindingChecker.trackBinding(
2167 static_cast<llvm::dxil::ResourceClass
>(Clause->Type), Clause->Space,
2168 LowerBound, UpperBound, ClauseElem);
2170 UnboundClauses.clear();
2174 return BindingChecker.checkOverlap();
2179 Diag(AL.
getLoc(), diag::err_attribute_wrong_number_arguments) << AL << 1;
2184 if (
auto *RS = D->
getAttr<RootSignatureAttr>()) {
2185 if (RS->getSignatureIdent() != Ident) {
2186 Diag(AL.
getLoc(), diag::err_disallowed_duplicate_attribute) << RS;
2190 Diag(AL.
getLoc(), diag::warn_duplicate_attribute_exact) << RS;
2196 if (
auto *SignatureDecl =
2197 dyn_cast<HLSLRootSignatureDecl>(R.getFoundDecl())) {
2204 llvm::VersionTuple SMVersion =
2209 uint32_t ZMax = 1024;
2210 uint32_t ThreadMax = 1024;
2211 if (IsDXIL && SMVersion.getMajor() <= 4) {
2214 }
else if (IsDXIL && SMVersion.getMajor() == 5) {
2224 diag::err_hlsl_numthreads_argument_oor)
2233 diag::err_hlsl_numthreads_argument_oor)
2242 diag::err_hlsl_numthreads_argument_oor)
2247 if (
X * Y * Z > ThreadMax) {
2248 Diag(AL.
getLoc(), diag::err_hlsl_numthreads_invalid) << ThreadMax;
2265 if (SpelledArgsCount == 0 || SpelledArgsCount > 3)
2273 if (SpelledArgsCount > 1 &&
2277 uint32_t Preferred = 0;
2278 if (SpelledArgsCount > 2 &&
2282 if (SpelledArgsCount > 2) {
2285 diag::err_attribute_power_of_two_in_range)
2286 << AL << llvm::dxil::MinWaveSize << llvm::dxil::MaxWaveSize
2291 if (Preferred < Min || Preferred >
Max) {
2293 diag::err_attribute_power_of_two_in_range)
2294 << AL <<
Min <<
Max << Preferred;
2297 }
else if (SpelledArgsCount > 1) {
2300 diag::err_attribute_power_of_two_in_range)
2301 << AL << llvm::dxil::MinWaveSize << llvm::dxil::MaxWaveSize <<
Max;
2305 Diag(AL.
getLoc(), diag::err_attribute_argument_invalid) << AL << 1;
2308 Diag(AL.
getLoc(), diag::warn_attr_min_eq_max) << AL;
2313 diag::err_attribute_power_of_two_in_range)
2314 << AL << llvm::dxil::MinWaveSize << llvm::dxil::MaxWaveSize <<
Min;
2319 HLSLWaveSizeAttr *NewAttr =
2356 uint32_t Binding = 0;
2374 if (
const auto *BuiltIn = D->
getAttr<HLSLVkBuiltInAttr>()) {
2375 Diag(AL.
getLoc(), diag::err_attributes_are_not_compatible)
2378 BuiltIn->isRegularKeywordAttribute());
2379 Diag(BuiltIn->getLocation(), diag::note_conflicting_attribute);
2389 if (!
SemaRef.checkStringLiteralArgumentAttr(AL, 0, BuiltIn, &ArgLoc))
2392 static constexpr StringRef SupportedBuiltIns[] = {
2397 if (!llvm::is_contained(SupportedBuiltIns, BuiltIn)) {
2399 llvm::raw_string_ostream OS(Quoted);
2400 llvm::interleaveComma(SupportedBuiltIns, OS,
2401 [&](StringRef S) { OS <<
"'" << S <<
"'"; });
2402 Diag(ArgLoc, diag::err_hlsl_vk_builtin_unsupported_value)
2403 << BuiltIn << Quoted;
2408 if (
const auto *Location = D->
getAttr<HLSLVkLocationAttr>()) {
2409 Diag(AL.
getLoc(), diag::err_attributes_are_not_compatible)
2412 Location->isRegularKeywordAttribute());
2413 Diag(Location->getLoc(), diag::note_conflicting_attribute);
2421 uint32_t IndexValue(0), ExplicitIndex(0);
2424 assert(0 &&
"HLSLUnparsedSemantic is expected to have 2 int arguments.");
2426 assert(IndexValue > 0 ? ExplicitIndex :
true);
2429 if (Kind == SemanticKind::Invalid) {
2430 Diag(AL.
getLoc(), diag::err_hlsl_unknown_semantic) << AL;
2436 case SemanticKind::ClipDistance:
2437 case SemanticKind::OutputControlPointID:
2438 case SemanticKind::DomainLocation:
2439 case SemanticKind::GSInstanceID:
2440 case SemanticKind::Depth:
2441 case SemanticKind::DepthLessEqual:
2442 case SemanticKind::DepthGreaterEqual:
2443 case SemanticKind::TessFactor:
2444 case SemanticKind::InsideTessFactor:
2445 case SemanticKind::CullPrimitive:
2446 Diag(AL.
getLoc(), diag::err_hlsl_unknown_semantic) << AL;
2452 D->
addAttr(HLSLParsedSemanticAttr::Create(
2458 Diag(AL.
getLoc(), diag::err_hlsl_attr_invalid_ast_node)
2459 << AL <<
"shader constant in a constant buffer";
2463 uint32_t SubComponent;
2473 bool IsAggregateTy = (T->isArrayType() || T->isStructureType());
2478 if (IsAggregateTy) {
2479 Diag(AL.
getLoc(), diag::err_hlsl_invalid_register_or_packoffset);
2483 if ((Component * 32 + Size) > 128) {
2484 Diag(AL.
getLoc(), diag::err_hlsl_packoffset_cross_reg_boundary);
2489 EltTy = VT->getElementType();
2491 if (Align > 32 && Component == 1) {
2494 Diag(AL.
getLoc(), diag::err_hlsl_packoffset_alignment_mismatch)
2508 if (!
SemaRef.checkStringLiteralArgumentAttr(AL, 0, Str, &ArgLoc))
2511 llvm::Triple::EnvironmentType ShaderType;
2512 if (!HLSLShaderAttr::ConvertStrToEnvironmentType(Str, ShaderType)) {
2513 Diag(AL.
getLoc(), diag::warn_attribute_type_not_supported)
2514 << AL << Str << ArgLoc;
2528 Expr *SampleCountExpr) {
2529 assert(AttrList.size() &&
"expected list of resource attributes");
2536 HLSLAttributedResourceType::Attributes ResAttrs;
2538 bool HasResourceClass =
false;
2539 bool HasResourceDimension =
false;
2540 for (
const Attr *A : AttrList) {
2545 case attr::HLSLResourceClass: {
2547 if (HasResourceClass) {
2549 ? diag::warn_duplicate_attribute_exact
2550 : diag::warn_duplicate_attribute)
2554 ResAttrs.ResourceClass = RC;
2555 HasResourceClass =
true;
2558 case attr::HLSLResourceDimension: {
2559 llvm::dxil::ResourceDimension RD =
2561 if (HasResourceDimension) {
2563 ? diag::warn_duplicate_attribute_exact
2564 : diag::warn_duplicate_attribute)
2568 ResAttrs.ResourceDimension = RD;
2569 HasResourceDimension =
true;
2572 case attr::HLSLIsROV:
2573 if (ResAttrs.IsROV) {
2577 ResAttrs.IsROV =
true;
2579 case attr::HLSLRawBuffer:
2580 if (ResAttrs.RawBuffer) {
2584 ResAttrs.RawBuffer =
true;
2586 case attr::HLSLIsArray:
2587 if (ResAttrs.IsArray) {
2591 ResAttrs.IsArray =
true;
2593 case attr::HLSLIsMultiSampled:
2594 if (ResAttrs.SampleCountExpr) {
2600 ResAttrs.SampleCountExpr =
2606 case attr::HLSLIsCounter:
2607 if (ResAttrs.IsCounter) {
2611 ResAttrs.IsCounter =
true;
2613 case attr::HLSLContainedType: {
2616 if (!ContainedTy.
isNull()) {
2618 ? diag::warn_duplicate_attribute_exact
2619 : diag::warn_duplicate_attribute)
2628 llvm_unreachable(
"unhandled resource attribute type");
2632 if (!HasResourceClass) {
2633 S.
Diag(AttrList.back()->getRange().getEnd(),
2634 diag::err_hlsl_missing_resource_class);
2639 Wrapped, ContainedTy, ResAttrs);
2641 if (LocInfo && ContainedTyInfo) {
2654 if (!T->isHLSLResourceType()) {
2655 Diag(AL.
getLoc(), diag::err_hlsl_attribute_needs_intangible_type)
2670 AttributeCommonInfo::AS_CXX11, 0, false ,
2675 case ParsedAttr::AT_HLSLResourceClass: {
2676 StringRef Identifier;
2678 if (!
SemaRef.checkStringLiteralArgumentAttr(AL, 0, Identifier, &ArgLoc))
2683 if (!HLSLResourceClassAttr::ConvertStrToResourceClass(Identifier, RC)) {
2684 Diag(ArgLoc, diag::warn_attribute_type_not_supported)
2685 <<
"ResourceClass" << Identifier;
2688 A = HLSLResourceClassAttr::Create(
getASTContext(), RC, ACI);
2692 case ParsedAttr::AT_HLSLResourceDimension: {
2693 StringRef Identifier;
2695 if (!
SemaRef.checkStringLiteralArgumentAttr(AL, 0, Identifier, &ArgLoc))
2699 llvm::dxil::ResourceDimension RD;
2700 if (!HLSLResourceDimensionAttr::ConvertStrToResourceDimension(Identifier,
2702 Diag(ArgLoc, diag::warn_attribute_type_not_supported)
2703 <<
"ResourceDimension" << Identifier;
2706 A = HLSLResourceDimensionAttr::Create(
getASTContext(), RD, ACI);
2710 case ParsedAttr::AT_HLSLIsROV:
2714 case ParsedAttr::AT_HLSLRawBuffer:
2718 case ParsedAttr::AT_HLSLIsCounter:
2722 case ParsedAttr::AT_HLSLIsArray:
2726 case ParsedAttr::AT_HLSLIsMultiSampled:
2730 case ParsedAttr::AT_HLSLContainedType: {
2732 Diag(AL.
getLoc(), diag::err_attribute_wrong_number_arguments) << AL << 1;
2738 assert(TSI &&
"no type source info for attribute argument");
2740 diag::err_incomplete_type))
2742 A = HLSLContainedTypeAttr::Create(
getASTContext(), TSI, ACI);
2747 llvm_unreachable(
"unhandled HLSL attribute");
2750 HLSLResourcesTypeAttrs.emplace_back(A);
2756 if (!HLSLResourcesTypeAttrs.size())
2762 HLSLResourcesTypeAttrs, QT, &LocInfo)) {
2763 const HLSLAttributedResourceType *RT =
2770 LocsForHLSLAttributedResources.insert(std::pair(RT, LocInfo));
2772 HLSLResourcesTypeAttrs.clear();
2780 auto I = LocsForHLSLAttributedResources.find(RT);
2781 if (I != LocsForHLSLAttributedResources.end()) {
2782 LocInfo = I->second;
2783 LocsForHLSLAttributedResources.erase(I);
2792void SemaHLSL::collectResourceBindingsOnUserRecordDecl(
const VarDecl *VD,
2793 const RecordType *RT) {
2801 "incomplete arrays inside user defined types are not supported");
2810 if (
const HLSLAttributedResourceType *AttrResType =
2811 HLSLAttributedResourceType::findHandleTypeOnResource(Ty)) {
2816 Bindings.addDeclBindingInfo(VD, RC);
2817 }
else if (
const RecordType *RT = dyn_cast<RecordType>(Ty)) {
2823 collectResourceBindingsOnUserRecordDecl(VD, RT);
2835 bool SpecifiedSpace) {
2836 int RegTypeNum =
static_cast<int>(RegType);
2839 if (D->
hasAttr<HLSLGroupSharedAddressSpaceAttr>()) {
2840 S.
Diag(ArgLoc, diag::err_hlsl_binding_type_mismatch) << RegTypeNum;
2845 if (
HLSLBufferDecl *CBufferOrTBuffer = dyn_cast<HLSLBufferDecl>(D)) {
2846 ResourceClass RC = CBufferOrTBuffer->isCBuffer() ? ResourceClass::CBuffer
2847 : ResourceClass::SRV;
2857 assert(
isa<VarDecl>(D) &&
"D is expected to be VarDecl or HLSLBufferDecl");
2861 if (
const HLSLAttributedResourceType *AttrResType =
2862 HLSLAttributedResourceType::findHandleTypeOnResource(
2879 if (SpecifiedSpace && !DeclaredInCOrTBuffer)
2880 S.
Diag(ArgLoc, diag::err_hlsl_space_on_global_constant);
2885 if (RegType == RegisterType::CBuffer)
2886 S.
Diag(ArgLoc, diag::warn_hlsl_deprecated_register_type_b);
2887 else if (RegType != RegisterType::C)
2888 S.
Diag(ArgLoc, diag::err_hlsl_binding_type_mismatch) << RegTypeNum;
2892 if (RegType == RegisterType::C)
2893 S.
Diag(ArgLoc, diag::warn_hlsl_register_type_c_packoffset);
2895 S.
Diag(ArgLoc, diag::err_hlsl_binding_type_mismatch) << RegTypeNum;
2905 S.
Diag(ArgLoc, diag::err_hlsl_binding_type_mismatch) << RegTypeNum;
2913 bool RegisterTypesDetected[5] = {
false};
2914 RegisterTypesDetected[
static_cast<int>(regType)] =
true;
2917 if (HLSLResourceBindingAttr *
attr =
2918 dyn_cast<HLSLResourceBindingAttr>(*it)) {
2921 if (RegisterTypesDetected[
static_cast<int>(otherRegType)]) {
2922 int otherRegTypeNum =
static_cast<int>(otherRegType);
2924 diag::err_hlsl_duplicate_register_annotation)
2928 RegisterTypesDetected[
static_cast<int>(otherRegType)] =
true;
2936 bool SpecifiedSpace) {
2941 "expecting VarDecl or HLSLBufferDecl");
2961 if (StartSlot > Limit)
2965 if (
const auto *AT = dyn_cast<ArrayType>(T)) {
2968 if (
const auto *CAT = dyn_cast<ConstantArrayType>(AT))
2969 Count = CAT->
getSize().getZExtValue();
2971 QualType ElemTy = AT->getElementType();
2973 ArrayCount * Count);
2977 if (
auto ResTy = dyn_cast<HLSLAttributedResourceType>(T)) {
2980 if (ResTy->getAttrs().ResourceClass != ResClass)
2984 uint64_t EndSlot = StartSlot + ArrayCount - 1;
2985 if (EndSlot > Limit)
2989 StartSlot = EndSlot + 1;
2994 if (
const auto *RT = dyn_cast<RecordType>(T)) {
2997 if (
const auto *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
3000 ResClass, Ctx, ArrayCount))
3007 ResClass, Ctx, ArrayCount))
3022 if (SlotNum > Limit)
3027 if (RegTy == RegisterType::C || RegTy == RegisterType::I)
3030 if (
VarDecl *VD = dyn_cast<VarDecl>(TheDecl)) {
3039 return (BaseSlot > Limit);
3046 return (SlotNum > Limit);
3049 llvm_unreachable(
"unexpected decl type");
3053 if (
VarDecl *VD = dyn_cast<VarDecl>(TheDecl)) {
3055 if (
const auto *IAT = dyn_cast<IncompleteArrayType>(Ty))
3056 Ty = IAT->getElementType();
3058 diag::err_incomplete_type))
3062 StringRef Slot =
"";
3063 StringRef Space =
"";
3067 Diag(AL.
getLoc(), diag::err_attribute_argument_type)
3077 Diag(AL.
getLoc(), diag::err_attribute_argument_type)
3083 SpaceLoc = Loc->
getLoc();
3086 if (Str.starts_with(
"space")) {
3088 SpaceLoc = Loc->
getLoc();
3097 std::optional<unsigned> SlotNum;
3098 unsigned SpaceNum = 0;
3101 if (!Slot.empty()) {
3103 Diag(SlotLoc, diag::err_hlsl_binding_type_invalid) << Slot.substr(0, 1);
3106 if (RegType == RegisterType::I) {
3107 Diag(SlotLoc, diag::warn_hlsl_deprecated_register_type_i);
3110 const StringRef SlotNumStr = Slot.substr(1);
3115 if (SlotNumStr.getAsInteger(10, N)) {
3116 Diag(SlotLoc, diag::err_hlsl_unsupported_register_number);
3124 Diag(SlotLoc, diag::err_hlsl_register_number_too_large);
3129 SlotNum = (unsigned)N;
3133 if (!Space.starts_with(
"space")) {
3134 Diag(SpaceLoc, diag::err_hlsl_expected_space) << Space;
3137 StringRef SpaceNumStr = Space.substr(5);
3138 if (SpaceNumStr.getAsInteger(10, SpaceNum)) {
3139 Diag(SpaceLoc, diag::err_hlsl_expected_space) << Space;
3144 if (SlotNum.has_value())
3149 HLSLResourceBindingAttr *NewAttr =
3150 HLSLResourceBindingAttr::Create(
getASTContext(), Slot, Space, AL);
3152 NewAttr->setBinding(RegType, SlotNum, SpaceNum);
3176 while (
const auto *AT = Cur->
getAs<AttributedType>()) {
3178 if (K == attr::HLSLRowMajor || K == attr::HLSLColumnMajor) {
3182 Cur = AT->getModifiedType();
3193 ? attr::HLSLRowMajor
3194 : attr::HLSLColumnMajor;
3198 Diag(AL.
getLoc(), diag::err_hlsl_matrix_layout_non_matrix)
3207 if (ExistingKind == AttrK) {
3208 Diag(AL.
getLoc(), diag::warn_duplicate_attribute_exact)
3210 Diag(AL.
getLoc(), diag::note_previous_attribute);
3214 ExistingKind == attr::HLSLRowMajor ?
"row_major" :
"column_major");
3215 Diag(AL.
getLoc(), diag::err_hlsl_matrix_layout_conflict)
3217 Diag(AL.
getLoc(), diag::note_conflicting_attribute);
3222 if (AttrK == attr::HLSLRowMajor)
3223 return ::new (Ctx) HLSLRowMajorAttr(Ctx, AL);
3224 return ::new (Ctx) HLSLColumnMajorAttr(Ctx, AL);
3235 if (K != attr::HLSLRowMajor && K != attr::HLSLColumnMajor)
3237 if (T.isNull() || T->isDependentType())
3242 K == attr::HLSLRowMajor ?
"row_major" :
"column_major");
3243 Diag(Loc, diag::err_hlsl_matrix_layout_non_matrix) << II;
3251using llvm::dxil::BarrierMemoryTypeFlag;
3252using llvm::dxil::BarrierSemanticFlag;
3254template <
typename T>
constexpr uint64_t barrierFlagValue(T Flag) {
3255 return llvm::to_underlying(Flag);
3269 bool DiagnoseAvailability;
3296 llvm::DenseMap<const FunctionDecl *, unsigned> ScannedDecls;
3300 llvm::Triple::EnvironmentType CurrentShaderEnvironment;
3301 unsigned CurrentShaderStageBit;
3306 bool ReportOnlyShaderStageIssues;
3309 void SetShaderStageContext(llvm::Triple::EnvironmentType ShaderType) {
3310 static_assert(
sizeof(
unsigned) >= 4);
3311 assert(HLSLShaderAttr::isValidShaderType(ShaderType));
3312 assert((
unsigned)(ShaderType - llvm::Triple::Pixel) < 31 &&
3313 "ShaderType is too big for this bitmap");
3316 unsigned bitmapIndex = ShaderType - llvm::Triple::Pixel;
3317 CurrentShaderEnvironment = ShaderType;
3318 CurrentShaderStageBit = (1 << bitmapIndex);
3321 void SetUnknownShaderStageContext() {
3322 CurrentShaderEnvironment = llvm::Triple::UnknownEnvironment;
3323 CurrentShaderStageBit = (1 << 31);
3326 llvm::Triple::EnvironmentType GetCurrentShaderEnvironment()
const {
3327 return CurrentShaderEnvironment;
3330 bool InUnknownShaderStageContext()
const {
3331 return CurrentShaderEnvironment == llvm::Triple::UnknownEnvironment;
3335 void AddToScannedFunctions(
const FunctionDecl *FD) {
3336 unsigned &ScannedStages = ScannedDecls[FD];
3337 ScannedStages |= CurrentShaderStageBit;
3340 unsigned GetScannedStages(
const FunctionDecl *FD) {
return ScannedDecls[FD]; }
3342 bool WasAlreadyScannedInCurrentStage(
const FunctionDecl *FD) {
3343 return WasAlreadyScannedInCurrentStage(GetScannedStages(FD));
3346 bool WasAlreadyScannedInCurrentStage(
unsigned ScannerStages) {
3347 return ScannerStages & CurrentShaderStageBit;
3350 static bool NeverBeenScanned(
unsigned ScannedStages) {
3351 return ScannedStages == 0;
3355 void HandleFunctionOrMethodRef(FunctionDecl *FD, Expr *RefExpr);
3356 void CheckDeclAvailability(NamedDecl *D,
const AvailabilityAttr *AA,
3358 const AvailabilityAttr *FindAvailabilityAttr(
const Decl *D);
3359 bool HasMatchingEnvironmentOrNone(
const AvailabilityAttr *AA);
3360 void DiagnoseBarrierCall(CallExpr *CE);
3362 bool HasVisibleGroup,
bool IsAllMemory);
3364 bool HasKnownStage,
bool IsAllMemory);
3365 void DiagnoseBarrierGroupSemantic(Expr *SemanticArg,
uint64_t SemanticFlags,
3366 bool HasVisibleGroup);
3367 void DiagnoseBarrierScope(Expr *SemanticArg,
uint64_t MemoryFlags,
3371 DiagnoseHLSLAvailability(Sema &SemaRef,
bool DiagnoseAvailability)
3372 : SemaRef(SemaRef), DiagnoseAvailability(DiagnoseAvailability),
3373 CurrentShaderEnvironment(llvm::Triple::UnknownEnvironment),
3374 CurrentShaderStageBit(0), ReportOnlyShaderStageIssues(
false) {}
3377 void RunOnTranslationUnit(
const TranslationUnitDecl *TU);
3378 void RunOnFunction(
const FunctionDecl *FD);
3380 bool VisitDeclRefExpr(DeclRefExpr *DRE)
override {
3381 FunctionDecl *FD = llvm::dyn_cast<FunctionDecl>(DRE->
getDecl());
3383 HandleFunctionOrMethodRef(FD, DRE);
3387 bool VisitMemberExpr(MemberExpr *ME)
override {
3388 FunctionDecl *FD = llvm::dyn_cast<FunctionDecl>(ME->
getMemberDecl());
3390 HandleFunctionOrMethodRef(FD, ME);
3394 bool VisitCallExpr(CallExpr *CE)
override {
3395 DiagnoseBarrierCall(CE);
3400uint64_t DiagnoseHLSLAvailability::DiagnoseBarrierGroupMemory(
3401 Expr *MemoryArg,
uint64_t MemoryFlags,
bool HasVisibleGroup,
3404 barrierFlagValue(BarrierMemoryTypeFlag::GroupSharedMemory);
3405 if (HasVisibleGroup || (MemoryFlags & GroupSharedMemory) == 0)
3410 diag::err_hlsl_barrier_flag_requires_group)
3415 return MemoryFlags & ~GroupSharedMemory;
3418uint64_t DiagnoseHLSLAvailability::DiagnoseBarrierNodeMemory(
3419 Expr *MemoryArg,
uint64_t MemoryFlags,
bool HasKnownStage,
3422 barrierFlagValue(BarrierMemoryTypeFlag::NodeMemory);
3423 if (!HasKnownStage || (MemoryFlags & NodeMemory) == 0)
3428 diag::err_hlsl_barrier_node_memory_requires_node);
3432 return MemoryFlags & ~NodeMemory;
3435void DiagnoseHLSLAvailability::DiagnoseBarrierGroupSemantic(
3436 Expr *SemanticArg,
uint64_t SemanticFlags,
bool HasVisibleGroup) {
3437 if (HasVisibleGroup ||
3438 (SemanticFlags & barrierFlagValue(BarrierSemanticFlag::GroupFlags)) == 0)
3442 diag::err_hlsl_barrier_flag_requires_group)
3443 << ((SemanticFlags & barrierFlagValue(BarrierSemanticFlag::GroupSync)) !=
3449void DiagnoseHLSLAvailability::DiagnoseBarrierScope(
Expr *SemanticArg,
3452 if (ReportOnlyShaderStageIssues)
3456 barrierFlagValue(BarrierMemoryTypeFlag::UAVMemory) |
3457 barrierFlagValue(BarrierMemoryTypeFlag::NodeInputMemory);
3458 if ((SemanticFlags & barrierFlagValue(BarrierSemanticFlag::DeviceScope)) !=
3460 (MemoryFlags & DeviceScopeMemory) == 0)
3462 diag::err_hlsl_barrier_scope_requires_memory)
3464 if ((SemanticFlags & barrierFlagValue(BarrierSemanticFlag::GroupScope)) !=
3468 diag::err_hlsl_barrier_scope_requires_memory)
3472void DiagnoseHLSLAvailability::DiagnoseBarrierCall(
CallExpr *CE) {
3474 if (!FD || FD->
getBuiltinID() != Builtin::BI__builtin_hlsl_barrier)
3477 const llvm::Triple::EnvironmentType Stage = GetCurrentShaderEnvironment();
3478 const bool HasKnownStage = !InUnknownShaderStageContext();
3479 const bool HasVisibleGroup =
3480 !HasKnownStage || Stage == llvm::Triple::Compute ||
3481 Stage == llvm::Triple::Mesh || Stage == llvm::Triple::Amplification;
3483 uint64_t MemoryFlags = barrierFlagValue(BarrierMemoryTypeFlag::ValidMask);
3486 std::optional<llvm::APSInt>
Value =
3490 MemoryFlags =
Value->getZExtValue();
3491 const bool IsAllMemory =
3492 MemoryFlags == barrierFlagValue(BarrierMemoryTypeFlag::ValidMask);
3494 MemoryFlags = DiagnoseBarrierGroupMemory(MemoryArg, MemoryFlags,
3495 HasVisibleGroup, IsAllMemory);
3496 MemoryFlags = DiagnoseBarrierNodeMemory(MemoryArg, MemoryFlags,
3497 HasKnownStage, IsAllMemory);
3498 }
else if (!HasVisibleGroup) {
3500 diag::err_hlsl_barrier_resource_requires_group);
3505 std::optional<llvm::APSInt>
Value =
3511 DiagnoseBarrierGroupSemantic(SemanticArg, SemanticFlags, HasVisibleGroup);
3514 DiagnoseBarrierScope(SemanticArg, MemoryFlags, SemanticFlags);
3517void DiagnoseHLSLAvailability::HandleFunctionOrMethodRef(
FunctionDecl *FD,
3520 "expected DeclRefExpr or MemberExpr");
3522 if (DiagnoseAvailability)
3523 if (
const AvailabilityAttr *AA = FindAvailabilityAttr(FD))
3524 CheckDeclAvailability(
3529 if (FD->
hasBody(FDWithBody) && !WasAlreadyScannedInCurrentStage(FDWithBody))
3530 DeclsToScan.push_back(FDWithBody);
3533void DiagnoseHLSLAvailability::RunOnTranslationUnit(
3538 llvm::Triple::EnvironmentType::Library;
3547 DeclContextsToScan.push_back(TU);
3549 while (!DeclContextsToScan.empty()) {
3550 const DeclContext *DC = DeclContextsToScan.pop_back_val();
3551 for (
auto &D : DC->
decls()) {
3558 if (llvm::dyn_cast<NamespaceDecl>(D) || llvm::dyn_cast<ExportDecl>(D)) {
3559 DeclContextsToScan.push_back(llvm::dyn_cast<DeclContext>(D));
3564 const FunctionDecl *FD = llvm::dyn_cast<FunctionDecl>(D);
3569 if (HLSLShaderAttr *ShaderAttr = FD->
getAttr<HLSLShaderAttr>()) {
3570 if (!IsLibraryShader && FD->
getName() == EntryName) {
3573 diag::err_hlsl_ambiguous_entry_point)
3575 SemaRef.
Diag(EntryLoc, diag::note_previous_declaration_as)
3581 SetShaderStageContext(ShaderAttr->getType());
3590 for (
const auto *Redecl : FD->
redecls()) {
3591 if (Redecl->isInExportDeclContext()) {
3598 SetUnknownShaderStageContext();
3605 if (!IsLibraryShader && EntryLoc.
isInvalid()) {
3612void DiagnoseHLSLAvailability::RunOnFunction(
const FunctionDecl *FD) {
3613 assert(DeclsToScan.empty() &&
"DeclsToScan should be empty");
3614 DeclsToScan.push_back(FD);
3616 while (!DeclsToScan.empty()) {
3624 const unsigned ScannedStages = GetScannedStages(FD);
3625 if (WasAlreadyScannedInCurrentStage(ScannedStages))
3628 ReportOnlyShaderStageIssues = !NeverBeenScanned(ScannedStages);
3630 AddToScannedFunctions(FD);
3635bool DiagnoseHLSLAvailability::HasMatchingEnvironmentOrNone(
3636 const AvailabilityAttr *AA) {
3641 llvm::Triple::EnvironmentType CurrentEnv = GetCurrentShaderEnvironment();
3642 if (CurrentEnv == llvm::Triple::UnknownEnvironment)
3645 llvm::Triple::EnvironmentType AttrEnv =
3646 AvailabilityAttr::getEnvironmentType(IIEnvironment->
getName());
3648 return CurrentEnv == AttrEnv;
3651const AvailabilityAttr *
3652DiagnoseHLSLAvailability::FindAvailabilityAttr(
const Decl *D) {
3653 AvailabilityAttr
const *PartialMatch =
nullptr;
3657 for (
const auto *A : D->
attrs()) {
3658 if (
const auto *Avail = dyn_cast<AvailabilityAttr>(A)) {
3659 const AvailabilityAttr *EffectiveAvail = Avail->getEffectiveAttr();
3660 StringRef AttrPlatform = EffectiveAvail->getPlatform()->getName();
3661 StringRef TargetPlatform =
3665 if (AttrPlatform == TargetPlatform) {
3667 if (HasMatchingEnvironmentOrNone(EffectiveAvail))
3669 PartialMatch = Avail;
3673 return PartialMatch;
3678void DiagnoseHLSLAvailability::CheckDeclAvailability(
NamedDecl *D,
3679 const AvailabilityAttr *AA,
3698 if (ReportOnlyShaderStageIssues)
3704 if (InUnknownShaderStageContext())
3709 bool EnvironmentMatches = HasMatchingEnvironmentOrNone(AA);
3710 VersionTuple Introduced = AA->getIntroduced();
3719 llvm::StringRef PlatformName(
3722 llvm::StringRef CurrentEnvStr =
3723 llvm::Triple::getEnvironmentTypeName(GetCurrentShaderEnvironment());
3725 llvm::StringRef AttrEnvStr =
3726 AA->getEnvironment() ? AA->getEnvironment()->getName() :
"";
3727 bool UseEnvironment = !AttrEnvStr.empty();
3729 if (EnvironmentMatches) {
3730 SemaRef.
Diag(
Range.getBegin(), diag::warn_hlsl_availability)
3731 <<
Range << D << PlatformName << Introduced.getAsString()
3732 << UseEnvironment << CurrentEnvStr;
3734 SemaRef.
Diag(
Range.getBegin(), diag::warn_hlsl_availability_unavailable)
3738 SemaRef.
Diag(D->
getLocation(), diag::note_partial_availability_specified_here)
3739 << D << PlatformName << Introduced.getAsString()
3741 << UseEnvironment << AttrEnvStr << CurrentEnvStr;
3748 if (!DefaultCBufferDecls.empty()) {
3751 DefaultCBufferDecls);
3754 SemaRef.getCurLexicalContext()->addDecl(DefaultCBuffer);
3758 for (
const Decl *VD : DefaultCBufferDecls) {
3759 const HLSLResourceBindingAttr *RBA =
3760 VD->
getAttr<HLSLResourceBindingAttr>();
3761 if (RBA && RBA->hasRegisterSlot() &&
3762 RBA->getRegisterType() == HLSLResourceBindingAttr::RegisterType::C) {
3769 SemaRef.Consumer.HandleTopLevelDecl(DG);
3771 diagnoseAvailabilityViolations(TU);
3780 "expected member expr to have resource record type or array of them");
3786 const Expr *NonConstIndexExpr =
nullptr;
3789 if (
const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
3790 if (!NonConstIndexExpr)
3798 diag::err_hlsl_resource_member_array_access_not_constant);
3802 if (
const auto *ASE = dyn_cast<ArraySubscriptExpr>(E)) {
3803 const Expr *IdxExpr = ASE->getIdx();
3805 NonConstIndexExpr = IdxExpr;
3807 }
else if (
const auto *SubME = dyn_cast<MemberExpr>(E)) {
3808 E = SubME->getBase();
3809 }
else if (
const auto *ICE = dyn_cast<ImplicitCastExpr>(E)) {
3810 E = ICE->getSubExpr();
3814 llvm_unreachable(
"unexpected expr type in resource member access");
3823 SemaRef.Context.getCanonicalType(
SemaRef.Context.getAddrSpaceQualType(
3826 SemaRef.Context.getLValueReferenceType(AddrSpaceType));
3829 SemaRef.Context.DeclarationNames.getCXXConversionFunctionName(
3833 [[maybe_unused]]
bool LookupSucceeded =
3834 SemaRef.LookupQualifiedName(ConvR, RD);
3835 assert(LookupSucceeded);
3844std::optional<ExprResult>
3847 const HLSLAttributedResourceType *ResTy =
3848 HLSLAttributedResourceType::findHandleTypeOnResource(
3849 BaseType.getTypePtr());
3851 ResTy->getAttrs().ResourceClass != llvm::dxil::ResourceClass::CBuffer)
3852 return std::nullopt;
3854 QualType TemplateType = ResTy->getContainedType();
3858 assert(NamedConversionDecl &&
3859 "Could not find conversion function for ConstantBuffer.");
3860 auto *ConversionDecl =
3863 return SemaRef.BuildCXXMemberCallExpr(BaseExpr, NamedConversionDecl,
3873 const bool DiagnoseAvailability =
3875 TI.
getTriple().getEnvironment() == llvm::Triple::EnvironmentType::Library;
3876 DiagnoseHLSLAvailability(
SemaRef, DiagnoseAvailability)
3877 .RunOnTranslationUnit(TU);
3884 for (
unsigned I = 1, N = TheCall->
getNumArgs(); I < N; ++I) {
3887 S->
Diag(TheCall->
getBeginLoc(), diag::err_vec_builtin_incompatible_vector)
3912 for (
unsigned I = 0; I < TheCall->
getNumArgs(); ++I) {
3925 if (!BaseType->isFloat32Type())
3926 return S->
Diag(Loc, diag::err_builtin_invalid_arg_type)
3927 << ArgOrdinal << 5 << 0
3937 if (!BaseType->isHalfType() && !BaseType->isFloat32Type())
3938 return S->
Diag(Loc, diag::err_builtin_invalid_arg_type)
3939 << ArgOrdinal << 5 << 0
3948 if (!BaseType->isDoubleType()) {
3951 return S->
Diag(Loc, diag::err_builtin_requires_double_type)
3952 << ArgOrdinal << PassedType;
3959 unsigned ArgIndex) {
3960 auto *Arg = TheCall->
getArg(ArgIndex);
3962 if (Arg->IgnoreCasts()->isModifiableLvalue(S->
Context, &OrigLoc) ==
3965 S->
Diag(OrigLoc, diag::error_hlsl_inout_lvalue) << Arg << 0;
3979 << (ArgIndex + 1) << LValueTy;
3989 if (VecTy->getElementType()->isDoubleType())
3990 return S->
Diag(Loc, diag::err_builtin_invalid_arg_type)
3991 << ArgOrdinal << 1 << 0 << 1
4002 return S->
Diag(Loc, diag::err_builtin_invalid_arg_type)
4003 << ArgOrdinal << 5 << 1
4012 if (VecTy->getElementType()->isUnsignedIntegerType())
4015 return S->
Diag(Loc, diag::err_builtin_invalid_arg_type)
4016 << ArgOrdinal << 4 << 3 << 0
4025 return S->
Diag(Loc, diag::err_builtin_invalid_arg_type)
4026 << ArgOrdinal << 5 << 3
4032 unsigned ArgOrdinal,
unsigned Width) {
4035 ArgTy = VTy->getElementType();
4039 if (ElementBitCount != Width) {
4041 diag::err_integer_incorrect_bit_count)
4042 << Width << ElementBitCount;
4053 else if (
auto *MatTyA =
4056 ReturnType, MatTyA->getNumRows(), MatTyA->getNumColumns());
4062 unsigned ArgIndex) {
4071 diag::err_typecheck_expect_scalar_or_vector)
4072 << ArgType << Scalar;
4079 QualType Scalar,
unsigned ArgIndex) {
4090 if (
const auto *VTy = ArgType->getAs<
VectorType>()) {
4103 diag::err_typecheck_expect_scalar_or_vector_or_matrix)
4104 << ArgType << Scalar;
4109 unsigned ArgIndex) {
4114 if (!(ArgType->isScalarType() ||
4115 (VTy && VTy->getElementType()->isScalarType()))) {
4117 diag::err_typecheck_expect_any_scalar_or_vector_or_matrix)
4125 unsigned ArgIndex) {
4128 if (ArgType->isDependentType())
4132 if (
const auto *VectorTy = ArgType->getAs<
VectorType>())
4133 ElementType = VectorTy->getElementType();
4135 ElementType = MatrixTy->getElementType();
4137 if (ElementType->isBooleanType())
4140 if (ElementType->isIntegerType() || ElementType->isRealFloatingType()) {
4142 if (BitWidth == 16 || BitWidth == 32 || BitWidth == 64)
4147 diag::err_typecheck_expect_any_scalar_or_vector_or_matrix)
4155 unsigned ArgIndex) {
4157 assert(ArgIndex < TheCall->getNumArgs());
4165 diag::err_typecheck_expect_any_scalar_or_vector_or_matrix)
4191 diag::err_typecheck_convert_incompatible)
4192 << MaskTy << UInt4Ty << 1 << 0 << 0;
4202 diag::err_typecheck_call_different_arg_types)
4221 Arg1ScalarTy = VTy->getElementType();
4225 Arg2ScalarTy = VTy->getElementType();
4228 S->
Diag(Arg1->
getBeginLoc(), diag::err_hlsl_builtin_scalar_vector_mismatch)
4229 << 1 << TheCall->
getCallee() << Arg1Ty << Arg2Ty;
4239 if (Arg1Length > 0 && Arg0Length != Arg1Length) {
4241 diag::err_typecheck_vector_lengths_not_equal)
4247 if (Arg2Length > 0 && Arg0Length != Arg2Length) {
4249 diag::err_typecheck_vector_lengths_not_equal)
4269 Arg1ScalarTy = MTy->getElementType();
4273 Arg2ScalarTy = MTy->getElementType();
4276 S->
Diag(Arg1->
getBeginLoc(), diag::err_hlsl_builtin_scalar_vector_mismatch)
4277 << 1 << TheCall->
getCallee() << Arg1Ty << Arg2Ty;
4282 unsigned Arg0Cols = Arg0MatTy->getNumColumns();
4284 for (
Expr *Arg : {Arg1, Arg2}) {
4287 (MTy->getNumRows() != Arg0Rows || MTy->getNumColumns() != Arg0Cols)) {
4289 diag::err_typecheck_vector_lengths_not_equal)
4291 << Arg->getSourceRange();
4307 unsigned ArgIndex) {
4312 assert(TheCall->
getNumArgs() > IndexArgIndex &&
"Index argument missing");
4315 unsigned int ActualDim = 1;
4317 ActualDim = VTy->getNumElements();
4318 IndexTy = VTy->getElementType();
4322 diag::err_typecheck_expect_int)
4328 const HLSLAttributedResourceType *ResTy =
4330 assert(ResTy &&
"Resource argument must be a resource");
4331 HLSLAttributedResourceType::Attributes ResAttrs = ResTy->getAttrs();
4333 unsigned int ExpectedDim = 1;
4334 if (ResAttrs.ResourceDimension != llvm::dxil::ResourceDimension::Unknown)
4336 (ResAttrs.IsArray ? 1 : 0);
4338 if (ActualDim != ExpectedDim) {
4340 diag::err_hlsl_builtin_resource_coordinate_dimension_mismatch)
4351 llvm::function_ref<
bool(
const HLSLAttributedResourceType *ResType)> Check =
4355 const HLSLAttributedResourceType *ResTy =
4359 diag::err_typecheck_expect_hlsl_resource)
4363 if (Check && Check(ResTy)) {
4365 diag::err_invalid_hlsl_resource_type)
4375 "expected resource handle type");
4376 auto *MainResType = MainHandleTy->
getAs<HLSLAttributedResourceType>();
4377 auto MainAttrs = MainResType->getAttrs();
4378 assert(!MainAttrs.IsCounter &&
"cannot create a counter from a counter");
4379 MainAttrs.IsCounter =
true;
4381 MainResType->getContainedType(),
4392 return "SampleBias";
4394 return "SampleGrad";
4396 return "SampleLevel";
4400 return "SampleCmpLevelZero";
4402 llvm_unreachable(
"Invalid SampleKind");
4412 if (!MD || !MD->getDeclName().isIdentifier())
4419 return MD->getName();
4427 StringRef DefaultName) {
4432 S.
Diag(TheCall->
getBeginLoc(), diag::err_hlsl_sample_double_element_type)
4459 if (SMVersion >= VersionTuple(6, 7))
4462 S.
Diag(TheCall->
getBeginLoc(), diag::err_hlsl_sample_integer_element_type)
4464 << ContainedType << SMVersion.getAsString();
4469 bool IncludeArraySlice =
true) {
4472 [](
const HLSLAttributedResourceType *ResType) {
4473 return ResType->getAttrs().ResourceDimension ==
4474 llvm::dxil::ResourceDimension::Unknown;
4480 [](
const HLSLAttributedResourceType *ResType) {
4481 return ResType->getAttrs().ResourceClass !=
4482 llvm::hlsl::ResourceClass::Sampler;
4490 unsigned ExpectedDim =
4492 (IncludeArraySlice && ResourceTy->getAttrs().IsArray ? 1 : 0);
4521 unsigned NextIdx = 3;
4533 Expr *ComponentArg = TheCall->
getArg(NextIdx);
4537 std::optional<llvm::APSInt> ComponentOpt =
4540 int64_t ComponentVal = ComponentOpt->getSExtValue();
4541 if (ComponentVal != 0) {
4544 assert(ComponentVal >= 0 && ComponentVal <= 3 &&
4545 "The component is not in the expected range.");
4547 diag::err_hlsl_gathercmp_invalid_component)
4557 const HLSLAttributedResourceType *ResourceTy =
4560 unsigned ExpectedDim =
4563 &S, TheCall->
getArg(NextIdx),
4569 assert(ResourceTy->hasContainedType() &&
4570 "Expecting a contained type for resource with a dimension "
4572 QualType ReturnType = ResourceTy->getContainedType();
4575 IsCmp ?
"GatherCmp" :
"Gather"))
4580 S.
Diag(TheCall->
getBeginLoc(), diag::err_hlsl_samplecmp_requires_float);
4586 ReturnType = VecTy->getElementType();
4599 [](
const HLSLAttributedResourceType *ResType) {
4600 return ResType->getAttrs().ResourceDimension ==
4601 llvm::dxil::ResourceDimension::Unknown;
4611 ResourceTy->getAttrs().ResourceClass == llvm::dxil::ResourceClass::UAV;
4618 unsigned ResourceDim =
4620 unsigned LocationDim = ResourceDim + (ResourceTy->getAttrs().IsArray ? 1 : 0);
4636 TheCall->
setType(ResourceTy->getContainedType());
4646 [](
const HLSLAttributedResourceType *ResType) {
4647 return !ResType->isMultiSampled();
4656 unsigned ResourceDim =
4658 unsigned LocationDim = ResourceDim + (ResourceTy->getAttrs().IsArray ? 1 : 0);
4676 TheCall->
setType(ResourceTy->getContainedType());
4681 unsigned MinArgs, MaxArgs;
4709 const HLSLAttributedResourceType *ResourceTy =
4711 unsigned ExpectedDim =
4714 unsigned NextIdx = 3;
4739 &S, TheCall->
getArg(NextIdx),
4752 assert(ResourceTy->hasContainedType() &&
4753 "Expecting a contained type for resource with a dimension "
4755 QualType ReturnType = ResourceTy->getContainedType();
4766 S.
Diag(TheCall->
getBeginLoc(), diag::err_hlsl_samplecmp_requires_float);
4783 unsigned MinArgs,
unsigned MaxArgs,
4785 bool ReportsOriginalValue) {
4786 if (MinArgs == MaxArgs) {
4789 }
else if (TheCall->
getNumArgs() < MinArgs) {
4790 S.
Diag(TheCall->
getEndLoc(), diag::err_typecheck_call_too_few_args_at_least)
4800 const bool DestIsOK =
4806 diag::err_builtin_invalid_arg_type)
4820 TI.
getTriple().getArch() == llvm::Triple::dxil &&
4836 for (
unsigned I = 1, E = TheCall->
getNumArgs(); I != E; ++I)
4842 const unsigned NumArgs = TheCall->
getNumArgs();
4843 if (ReportsOriginalValue && NumArgs == MaxArgs &&
4854 switch (BuiltinID) {
4855 case Builtin::BI__builtin_hlsl_barrier: {
4856 if (
SemaRef.checkArgCount(TheCall, 2))
4859 if (
SemaRef.Context.getTargetInfo().getTriple().getArch() !=
4860 llvm::Triple::dxil) {
4868 std::optional<llvm::APSInt> MemoryFlags =
4872 diag::err_constant_integer_arg_type)
4876 if ((MemoryFlags->getZExtValue() &
4877 ~barrierFlagValue(BarrierMemoryTypeFlag::ValidMask)) != 0) {
4879 diag::err_hlsl_invalid_barrier_memory_flags);
4883 const HLSLAttributedResourceType *ResTy =
4884 HLSLAttributedResourceType::findHandleTypeOnResource(
4888 diag::err_typecheck_expect_hlsl_resource)
4892 if (ResTy->getAttrs().ResourceClass != ResourceClass::UAV) {
4894 diag::err_invalid_hlsl_resource_type)
4901 std::optional<llvm::APSInt> SemanticFlags =
4903 if (!SemanticFlags) {
4905 diag::err_constant_integer_arg_type)
4909 if ((SemanticFlags->getZExtValue() &
4910 ~barrierFlagValue(BarrierSemanticFlag::ValidMask)) != 0) {
4912 diag::err_hlsl_invalid_barrier_semantic_flags);
4919 case Builtin::BI__builtin_hlsl_adduint64: {
4920 if (
SemaRef.checkArgCount(TheCall, 2))
4934 if (NumElementsArg != 2 && NumElementsArg != 4) {
4936 << 1 << 64 << NumElementsArg * 32;
4950 case Builtin::BI__builtin_hlsl_resource_getpointer: {
4951 if (
SemaRef.checkArgCountRange(TheCall, 1, 2) ||
4958 QualType ContainedTy = ResourceTy->getContainedType();
4959 auto ReturnType =
SemaRef.Context.getAddrSpaceQualType(
4962 ReturnType =
SemaRef.Context.getPointerType(ReturnType);
4967 case Builtin::BI__builtin_hlsl_resource_getpointer_typed: {
4968 if (
SemaRef.checkArgCount(TheCall, 3) ||
4975 "expected pointer type for second argument");
4982 diag::err_invalid_use_of_array_type);
4986 auto ReturnType =
SemaRef.Context.getAddrSpaceQualType(
4989 ReturnType =
SemaRef.Context.getPointerType(ReturnType);
4994 case Builtin::BI__builtin_hlsl_transpose_if_memory_is_row_major: {
4995 if (
SemaRef.checkArgCount(TheCall, 2) ||
4997 SemaRef.getASTContext().IntTy))
5004 case Builtin::BI__builtin_hlsl_resource_load_with_status: {
5005 if (
SemaRef.checkArgCount(TheCall, 3) ||
5008 SemaRef.getASTContext().UnsignedIntTy) ||
5010 SemaRef.getASTContext().UnsignedIntTy) ||
5016 QualType ReturnType = ResourceTy->getContainedType();
5021 case Builtin::BI__builtin_hlsl_resource_load_with_status_typed: {
5022 if (
SemaRef.checkArgCount(TheCall, 4) ||
5025 SemaRef.getASTContext().UnsignedIntTy) ||
5027 SemaRef.getASTContext().UnsignedIntTy) ||
5033 "expected pointer type for second argument");
5040 diag::err_invalid_use_of_array_type);
5046 case Builtin::BI__builtin_hlsl_resource_load_level:
5048 case Builtin::BI__builtin_hlsl_resource_load_ms:
5050 case Builtin::BI__builtin_hlsl_resource_sample:
5052 case Builtin::BI__builtin_hlsl_resource_sample_bias:
5054 case Builtin::BI__builtin_hlsl_resource_sample_grad:
5056 case Builtin::BI__builtin_hlsl_resource_sample_level:
5058 case Builtin::BI__builtin_hlsl_resource_sample_cmp:
5060 case Builtin::BI__builtin_hlsl_resource_sample_cmp_level_zero:
5062 case Builtin::BI__builtin_hlsl_resource_calculate_lod:
5063 case Builtin::BI__builtin_hlsl_resource_calculate_lod_unclamped:
5065 case Builtin::BI__builtin_hlsl_resource_gather:
5067 case Builtin::BI__builtin_hlsl_resource_gather_cmp:
5069 case Builtin::BI__builtin_hlsl_resource_uninitializedhandle: {
5070 assert(TheCall->
getNumArgs() == 1 &&
"expected 1 arg");
5076 case Builtin::BI__builtin_hlsl_resource_handlefrombinding: {
5077 assert(TheCall->
getNumArgs() == 6 &&
"expected 6 args");
5083 case Builtin::BI__builtin_hlsl_resource_handlefromimplicitbinding: {
5084 assert(TheCall->
getNumArgs() == 6 &&
"expected 6 args");
5090 case Builtin::BI__builtin_hlsl_resource_counterhandlefromimplicitbinding: {
5091 assert(TheCall->
getNumArgs() == 3 &&
"expected 3 args");
5097 TheCall->
setType(CounterHandleTy);
5100 case Builtin::BI__builtin_hlsl_resource_handlefromheap: {
5101 if (
SemaRef.checkArgCount(TheCall, 2) ||
5104 SemaRef.getASTContext().UnsignedIntTy))
5112 case Builtin::BI__builtin_hlsl_resource_counterhandlefromheap: {
5113 if (
SemaRef.checkArgCount(TheCall, 1) ||
5121 TheCall->
setType(CounterHandleTy);
5124 case Builtin::BI__builtin_hlsl_and:
5125 case Builtin::BI__builtin_hlsl_or: {
5126 if (
SemaRef.checkArgCount(TheCall, 2))
5140 case Builtin::BI__builtin_hlsl_asdouble: {
5141 if (
SemaRef.checkArgCount(TheCall, 2))
5145 SemaRef.Context.UnsignedIntTy,
5150 SemaRef.Context.UnsignedIntTy,
5159 case Builtin::BI__builtin_hlsl_elementwise_clamp: {
5160 if (
SemaRef.BuiltinElementwiseTernaryMath(
5166 case Builtin::BI__builtin_hlsl_dot: {
5168 if (
SemaRef.BuiltinVectorToScalarMath(TheCall))
5174 case Builtin::BI__builtin_hlsl_elementwise_firstbithigh:
5175 case Builtin::BI__builtin_hlsl_elementwise_firstbitlow: {
5176 if (
SemaRef.PrepareBuiltinElementwiseMathOneArgCall(TheCall))
5186 EltTy = VecTy->getElementType();
5187 ResTy =
SemaRef.Context.getExtVectorType(ResTy, VecTy->getNumElements());
5200 case Builtin::BI__builtin_hlsl_select: {
5201 if (
SemaRef.checkArgCount(TheCall, 3))
5210 if (VTy && VTy->getElementType()->isBooleanType() &&
5214 if (MTy && MTy->getElementType()->isBooleanType() &&
5219 case Builtin::BI__builtin_hlsl_elementwise_saturate:
5220 case Builtin::BI__builtin_hlsl_elementwise_rcp: {
5221 if (
SemaRef.checkArgCount(TheCall, 1))
5227 diag::err_builtin_invalid_arg_type)
5230 if (
SemaRef.PrepareBuiltinElementwiseMathOneArgCall(TheCall))
5234 case Builtin::BI__builtin_hlsl_elementwise_rsqrt:
5235 case Builtin::BI__builtin_hlsl_elementwise_frac:
5236 case Builtin::BI__builtin_hlsl_elementwise_ddx_coarse:
5237 case Builtin::BI__builtin_hlsl_elementwise_ddy_coarse:
5238 case Builtin::BI__builtin_hlsl_elementwise_ddx_fine:
5239 case Builtin::BI__builtin_hlsl_elementwise_ddy_fine: {
5240 if (
SemaRef.checkArgCount(TheCall, 1))
5245 if (
SemaRef.PrepareBuiltinElementwiseMathOneArgCall(TheCall))
5249 case Builtin::BI__builtin_hlsl_elementwise_isfinite:
5250 case Builtin::BI__builtin_hlsl_elementwise_isinf:
5251 case Builtin::BI__builtin_hlsl_elementwise_isnan: {
5252 if (
SemaRef.checkArgCount(TheCall, 1))
5257 if (
SemaRef.PrepareBuiltinElementwiseMathOneArgCall(TheCall))
5262 case Builtin::BI__builtin_hlsl_mad: {
5263 if (
SemaRef.BuiltinElementwiseTernaryMath(
5269 case Builtin::BI__builtin_hlsl_mul: {
5270 if (
SemaRef.checkArgCount(TheCall, 2))
5279 if (
const auto *VTy = T->getAs<
VectorType>())
5280 return VTy->getElementType();
5282 return MTy->getElementType();
5286 QualType EltTy0 = getElemType(Ty0);
5295 if (IsVec0 && IsMat1) {
5298 }
else if (IsMat0 && IsVec1) {
5302 assert(IsMat0 && IsMat1);
5312 case Builtin::BI__builtin_elementwise_fma: {
5313 if (
SemaRef.checkArgCount(TheCall, 3) ||
5328 case Builtin::BI__builtin_hlsl_transpose: {
5329 if (
SemaRef.checkArgCount(TheCall, 1))
5338 << 1 << 3 << 0 << 0 << ArgTy;
5343 MatTy->getElementType(), MatTy->getNumColumns(), MatTy->getNumRows());
5347 case Builtin::BI__builtin_hlsl_elementwise_sign: {
5348 if (
SemaRef.PrepareBuiltinElementwiseMathOneArgCall(TheCall))
5356 case Builtin::BI__builtin_hlsl_wave_active_all_equal: {
5357 if (
SemaRef.checkArgCount(TheCall, 1))
5371 unsigned NumElts = VecTy->getNumElements();
5381 case Builtin::BI__builtin_hlsl_wave_active_max:
5382 case Builtin::BI__builtin_hlsl_wave_active_min:
5383 case Builtin::BI__builtin_hlsl_wave_active_sum:
5384 case Builtin::BI__builtin_hlsl_wave_active_product: {
5385 if (
SemaRef.checkArgCount(TheCall, 1))
5398 case Builtin::BI__builtin_hlsl_wave_active_bit_or:
5399 case Builtin::BI__builtin_hlsl_wave_active_bit_xor:
5400 case Builtin::BI__builtin_hlsl_wave_active_bit_and: {
5401 if (
SemaRef.checkArgCount(TheCall, 1))
5416 (VTy && VTy->getElementType()->isIntegerType()))) {
5418 diag::err_builtin_invalid_arg_type)
5419 << ArgTyExpr <<
SemaRef.Context.UnsignedIntTy << 1 << 0 << 0;
5427 case Builtin::BI__builtin_hlsl_interlocked_add:
5428 case Builtin::BI__builtin_hlsl_interlocked_and:
5429 case Builtin::BI__builtin_hlsl_interlocked_max:
5430 case Builtin::BI__builtin_hlsl_interlocked_min:
5431 case Builtin::BI__builtin_hlsl_interlocked_or:
5432 case Builtin::BI__builtin_hlsl_interlocked_xor:
5438 case Builtin::BI__builtin_hlsl_interlocked_exchange:
5444 case Builtin::BI__builtin_hlsl_interlocked_compare_store:
5450 case Builtin::BI__builtin_hlsl_interlocked_compare_store_float_bitwise:
5456 case Builtin::BI__builtin_hlsl_interlocked_compare_exchange:
5462 case Builtin::BI__builtin_hlsl_interlocked_compare_exchange_float_bitwise:
5470 case Builtin::BI__builtin_elementwise_bitreverse: {
5478 case Builtin::BI__builtin_hlsl_wave_prefix_count_bits:
5479 case Builtin::BI__builtin_hlsl_wave_multi_prefix_count_bits: {
5480 bool IsMultiPrefix =
5481 BuiltinID == Builtin::BI__builtin_hlsl_wave_multi_prefix_count_bits;
5482 if (
SemaRef.checkArgCount(TheCall, IsMultiPrefix ? 2 : 1))
5487 if (!(
ArgType->isScalarType())) {
5489 diag::err_typecheck_expect_any_scalar_or_vector_or_matrix)
5494 if (!(
ArgType->isBooleanType())) {
5496 diag::err_typecheck_expect_any_scalar_or_vector_or_matrix)
5501 if (IsMultiPrefix) {
5509 diag::err_builtin_target_unsupported)
5517 case Builtin::BI__builtin_hlsl_wave_read_lane_at: {
5518 if (
SemaRef.checkArgCount(TheCall, 2))
5526 diag::err_typecheck_convert_incompatible)
5527 << ArgTyIndex <<
SemaRef.Context.UnsignedIntTy << 1 << 0 << 0;
5540 case Builtin::BI__builtin_hlsl_wave_read_lane_first: {
5541 if (
SemaRef.checkArgCount(TheCall, 1))
5550 case Builtin::BI__builtin_hlsl_wave_get_lane_index: {
5551 if (
SemaRef.checkArgCount(TheCall, 0))
5555 case Builtin::BI__builtin_hlsl_wave_prefix_sum:
5556 case Builtin::BI__builtin_hlsl_wave_prefix_product: {
5557 if (
SemaRef.checkArgCount(TheCall, 1))
5570 case Builtin::BI__builtin_hlsl_wave_multi_prefix_bit_and:
5571 case Builtin::BI__builtin_hlsl_wave_multi_prefix_bit_or:
5572 case Builtin::BI__builtin_hlsl_wave_multi_prefix_bit_xor:
5573 case Builtin::BI__builtin_hlsl_wave_multi_prefix_product:
5574 case Builtin::BI__builtin_hlsl_wave_multi_prefix_sum: {
5575 if (
SemaRef.checkArgCount(TheCall, 2))
5585 BuiltinID == Builtin::BI__builtin_hlsl_wave_multi_prefix_product ||
5586 BuiltinID == Builtin::BI__builtin_hlsl_wave_multi_prefix_sum;
5591 diag::err_builtin_invalid_arg_type)
5592 << 1 << (ValueTy->
isMatrixType() ? 3 : 5) << 1 << IsArithmetic
5603 case Builtin::BI__builtin_hlsl_quad_read_across_x:
5604 case Builtin::BI__builtin_hlsl_quad_read_across_y:
5605 case Builtin::BI__builtin_hlsl_quad_read_across_diagonal: {
5606 if (
SemaRef.checkArgCount(TheCall, 1))
5618 case Builtin::BI__builtin_hlsl_elementwise_splitdouble: {
5619 if (
SemaRef.checkArgCount(TheCall, 3))
5625 SemaRef.Context.UnsignedIntTy, 1) ||
5627 SemaRef.Context.UnsignedIntTy, 2))
5635 case Builtin::BI__builtin_hlsl_elementwise_clip: {
5636 if (
SemaRef.checkArgCount(TheCall, 1))
5643 case Builtin::BI__builtin_elementwise_acos:
5644 case Builtin::BI__builtin_elementwise_asin:
5645 case Builtin::BI__builtin_elementwise_atan:
5646 case Builtin::BI__builtin_elementwise_atan2:
5647 case Builtin::BI__builtin_elementwise_ceil:
5648 case Builtin::BI__builtin_elementwise_cos:
5649 case Builtin::BI__builtin_elementwise_cosh:
5650 case Builtin::BI__builtin_elementwise_exp:
5651 case Builtin::BI__builtin_elementwise_exp2:
5652 case Builtin::BI__builtin_elementwise_exp10:
5653 case Builtin::BI__builtin_elementwise_floor:
5654 case Builtin::BI__builtin_elementwise_fmod:
5655 case Builtin::BI__builtin_elementwise_log:
5656 case Builtin::BI__builtin_elementwise_log2:
5657 case Builtin::BI__builtin_elementwise_log10:
5658 case Builtin::BI__builtin_elementwise_pow:
5659 case Builtin::BI__builtin_elementwise_roundeven:
5660 case Builtin::BI__builtin_elementwise_sin:
5661 case Builtin::BI__builtin_elementwise_sinh:
5662 case Builtin::BI__builtin_elementwise_sqrt:
5663 case Builtin::BI__builtin_elementwise_tan:
5664 case Builtin::BI__builtin_elementwise_tanh:
5665 case Builtin::BI__builtin_elementwise_trunc: {
5671 case Builtin::BI__builtin_hlsl_buffer_update_counter: {
5672 assert(TheCall->
getNumArgs() == 2 &&
"expected 2 args");
5673 auto checkResTy = [](
const HLSLAttributedResourceType *ResTy) ->
bool {
5674 return !(ResTy->getAttrs().ResourceClass == ResourceClass::UAV &&
5675 ResTy->getAttrs().RawBuffer && ResTy->hasContainedType());
5680 std::optional<llvm::APSInt> Offset =
5682 if (!Offset.has_value() ||
std::abs(Offset->getExtValue()) != 1) {
5684 diag::err_hlsl_expect_arg_const_int_one_or_neg_one)
5690 case Builtin::BI__builtin_hlsl_elementwise_f16tof32: {
5691 if (
SemaRef.checkArgCount(TheCall, 1))
5702 ArgTy = VTy->getElementType();
5705 diag::err_builtin_invalid_arg_type)
5714 case Builtin::BI__builtin_hlsl_elementwise_f32tof16: {
5715 if (
SemaRef.checkArgCount(TheCall, 1))
5723 case Builtin::BI__builtin_hlsl_isdebuggingenabled: {
5726 diag::err_builtin_target_unsupported);
5738 WorkList.push_back(BaseTy);
5739 while (!WorkList.empty()) {
5740 QualType T = WorkList.pop_back_val();
5741 T = T.getCanonicalType().getUnqualifiedType();
5742 if (
const auto *AT = dyn_cast<ConstantArrayType>(T)) {
5750 for (
uint64_t Ct = 0; Ct < AT->getZExtSize(); ++Ct)
5751 llvm::append_range(List, ElementFields);
5756 if (
const auto *VT = dyn_cast<VectorType>(T)) {
5757 List.insert(List.end(), VT->getNumElements(), VT->getElementType());
5760 if (
const auto *MT = dyn_cast<ConstantMatrixType>(T)) {
5761 List.insert(List.end(), MT->getNumElementsFlattened(),
5762 MT->getElementType());
5765 if (
const auto *RD = T->getAsCXXRecordDecl()) {
5766 if (RD->isStandardLayout())
5767 RD = RD->getStandardLayoutBaseWithFields();
5771 if (RD->
isUnion() || !RD->isAggregate()) {
5777 for (
const auto *FD : RD->
fields())
5778 if (!FD->isUnnamedBitField())
5779 FieldTypes.push_back(FD->
getType());
5781 std::reverse(FieldTypes.begin(), FieldTypes.end());
5782 llvm::append_range(WorkList, FieldTypes);
5786 if (!RD->isStandardLayout()) {
5788 for (
const auto &
Base : RD->bases())
5789 FieldTypes.push_back(
Base.getType());
5790 std::reverse(FieldTypes.begin(), FieldTypes.end());
5791 llvm::append_range(WorkList, FieldTypes);
5826 if (
SemaRef.Context.getTypeSize(QT) / 8 > 16)
5832 int ArraySize = VT->getNumElements();
5837 QualType ElTy = VT->getElementType();
5841 if (
SemaRef.Context.getTypeSize(QT) / 8 > 16)
5857 return Size == 32 || (Size == 64 && EltTy->
isIntegerType());
5868 if (
SemaRef.getASTContext().hasSameType(T1, T2))
5877 return llvm::equal(T1Types, T2Types,
5879 return SemaRef.IsLayoutCompatible(LHS, RHS);
5888 bool HadError =
false;
5890 for (
unsigned i = 0, e =
New->getNumParams(); i != e; ++i) {
5898 const auto *NDAttr = NewParam->
getAttr<HLSLParamModifierAttr>();
5899 unsigned NSpellingIdx = (NDAttr ? NDAttr->getSpellingListIndex() : 0);
5900 const auto *ODAttr = OldParam->
getAttr<HLSLParamModifierAttr>();
5901 unsigned OSpellingIdx = (ODAttr ? ODAttr->getSpellingListIndex() : 0);
5903 if (NSpellingIdx != OSpellingIdx) {
5905 diag::err_hlsl_param_qualifier_mismatch)
5906 << NDAttr << NewParam;
5922 if (
SemaRef.getASTContext().hasSameUnqualifiedType(SrcTy, DestTy))
5937 llvm_unreachable(
"HLSL doesn't support pointers.");
5940 llvm_unreachable(
"HLSL doesn't support complex types.");
5942 llvm_unreachable(
"HLSL doesn't support fixed point types.");
5944 llvm_unreachable(
"Should have returned before this");
5954 llvm_unreachable(
"HLSL doesn't support complex types.");
5956 llvm_unreachable(
"HLSL doesn't support fixed point types.");
5961 llvm_unreachable(
"HLSL doesn't support pointers.");
5963 llvm_unreachable(
"Should have returned before this");
5969 llvm_unreachable(
"HLSL doesn't support pointers.");
5972 llvm_unreachable(
"HLSL doesn't support fixed point types.");
5976 llvm_unreachable(
"HLSL doesn't support complex types.");
5979 llvm_unreachable(
"Unhandled scalar cast");
6000 !(SrcMatTy && SrcMatTy->getNumElementsFlattened() == 1))
6006 SrcTy = SrcMatTy->getElementType();
6011 for (
unsigned I = 0, Size = DestTypes.size(); I < Size; ++I) {
6012 if (DestTypes[I]->isUnionType())
6044 if (SrcTypes.size() < DestTypes.size())
6047 unsigned SrcSize = SrcTypes.size();
6048 unsigned DstSize = DestTypes.size();
6050 for (I = 0; I < DstSize && I < SrcSize; I++) {
6051 if (SrcTypes[I]->isUnionType() || DestTypes[I]->isUnionType())
6059 for (; I < SrcSize; I++) {
6060 if (SrcTypes[I]->isUnionType())
6103 tok::equal, ArgOpV, OpV);
6115 assert(Param->hasAttr<HLSLParamModifierAttr>() &&
6116 "We should not get here without a parameter modifier expression");
6117 const auto *
Attr = Param->getAttr<HLSLParamModifierAttr>();
6124 << Arg << (IsInOut ? 1 : 0);
6128 QualType Ty = Param->getType().getNonLValueExprType(Ctx);
6135 << Arg << (IsInOut ? 1 : 0);
6143 Param->getBeginLoc(), IsInOut);
6151 "Pointer and reference types cannot be inout or out parameters");
6152 Ty =
SemaRef.getASTContext().getLValueReferenceType(Ty);
6168 for (
const auto *FD : RD->
fields()) {
6172 assert(RD->getNumBases() <= 1 &&
6173 "HLSL doesn't support multiple inheritance");
6174 return RD->getNumBases()
6179 if (
const auto *AT = dyn_cast<ArrayType>(Ty)) {
6180 if (
const auto *CAT = dyn_cast<ConstantArrayType>(AT))
6192 bool IsVKPushConstant = IsVulkan && VD->
hasAttr<HLSLVkPushConstantAttr>();
6197 !VD->
hasAttr<HLSLVkConstantIdAttr>() && !IsVKPushConstant &&
6203 if (
Decl->getType().hasAddressSpace())
6206 if (
Decl->getType()->isDependentType())
6218 if (
Decl->
hasAttr<HLSLVkExtBuiltinOutputAttr>()) {
6232 llvm::Triple::Vulkan;
6233 if (IsVulkan &&
Decl->
hasAttr<HLSLVkPushConstantAttr>()) {
6234 if (HasDeclaredAPushConstant)
6240 HasDeclaredAPushConstant =
true;
6267class StructBindingContext {
6270 HLSLResourceBindingAttr *RegBindingsAttrs[4];
6271 unsigned RegBindingOffset[4];
6274 static_assert(
static_cast<unsigned>(RegisterType::SRV) == 0 &&
6275 static_cast<unsigned>(RegisterType::UAV) == 1 &&
6276 static_cast<unsigned>(RegisterType::CBuffer) == 2 &&
6277 static_cast<unsigned>(RegisterType::Sampler) == 3,
6278 "unexpected register type values");
6281 HLSLVkBindingAttr *VkBindingAttr;
6282 unsigned VkBindingOffset;
6287 StructBindingContext(
VarDecl *VD) {
6288 for (
unsigned i = 0; i < 4; ++i) {
6289 RegBindingsAttrs[i] =
nullptr;
6290 RegBindingOffset[i] = 0;
6292 VkBindingAttr =
nullptr;
6293 VkBindingOffset = 0;
6299 if (
auto *RBA = dyn_cast<HLSLResourceBindingAttr>(A)) {
6301 unsigned RegTypeIdx =
static_cast<unsigned>(RegType);
6304 RegBindingsAttrs[RegTypeIdx] = RBA;
6309 if (
auto *VBA = dyn_cast<HLSLVkBindingAttr>(A))
6310 VkBindingAttr = VBA;
6317 Attr *createBindingAttr(SemaHLSL &S, ASTContext &AST,
RegisterType RegType,
6318 unsigned Range,
bool HasCounter) {
6319 assert(
static_cast<unsigned>(RegType) < 4 &&
"unexpected register type");
6321 if (VkBindingAttr) {
6322 unsigned Offset = VkBindingOffset;
6323 VkBindingOffset +=
Range;
6324 return HLSLVkBindingAttr::CreateImplicit(
6325 AST, VkBindingAttr->getBinding() + Offset, VkBindingAttr->getSet(),
6326 VkBindingAttr->getRange());
6329 HLSLResourceBindingAttr *RBA =
6330 RegBindingsAttrs[
static_cast<unsigned>(RegType)];
6331 HLSLResourceBindingAttr *NewAttr =
nullptr;
6333 if (RBA && RBA->hasRegisterSlot()) {
6336 unsigned Offset = RegBindingOffset[
static_cast<unsigned>(RegType)];
6337 RegBindingOffset[
static_cast<unsigned>(RegType)] += Range;
6339 unsigned NewSlotNumber = RBA->getSlotNumber() + Offset;
6340 StringRef NewSlotNumberStr =
6342 NewAttr = HLSLResourceBindingAttr::CreateImplicit(
6343 AST, NewSlotNumberStr, RBA->getSpace(), RBA->getRange());
6344 NewAttr->setBinding(RegType, NewSlotNumber, RBA->getSpaceNumber());
6348 NewAttr = HLSLResourceBindingAttr::CreateImplicit(AST,
"",
"0", {});
6349 NewAttr->setBinding(RegType, std::nullopt,
6350 RBA ? RBA->getSpaceNumber() : 0);
6354 NewAttr->setImplicitCounterBindingOrderID(
6363static void createGlobalResourceDeclForStruct(
6365 QualType ResTy, StructBindingContext &BindingCtx) {
6367 "expected resource type or array of resources");
6378 while (
const auto *AT = dyn_cast<ArrayType>(SingleResTy)) {
6379 const auto *CAT = dyn_cast<ConstantArrayType>(AT);
6384 const HLSLAttributedResourceType *ResHandleTy =
6385 HLSLAttributedResourceType::findHandleTypeOnResource(SingleResTy);
6389 Attr *BindingAttr = BindingCtx.createBindingAttr(
6391 ResDecl->
addAttr(BindingAttr);
6392 ResDecl->
addAttr(InternalLinkageAttr::CreateImplicit(AST));
6401 HLSLAssociatedResourceDeclAttr::CreateImplicit(AST, ResDecl));
6408static void handleArrayOfStructWithResources(
6410 EmbeddedResourceNameBuilder &NameBuilder, StructBindingContext &BindingCtx);
6415static void handleStructWithResources(
Sema &S,
VarDecl *ParentVD,
6417 EmbeddedResourceNameBuilder &NameBuilder,
6418 StructBindingContext &BindingCtx) {
6421 assert(RD->
getNumBases() <= 1 &&
"HLSL doesn't support multiple inheritance");
6428 handleStructWithResources(S, ParentVD, BaseRD, NameBuilder, BindingCtx);
6442 createGlobalResourceDeclForStruct(S, ParentVD, FD->
getLocation(), II,
6445 handleStructWithResources(S, ParentVD, RD, NameBuilder, BindingCtx);
6447 }
else if (
const auto *ArrayTy = dyn_cast<ConstantArrayType>(FDTy)) {
6449 "resource arrays should have been already handled");
6450 handleArrayOfStructWithResources(S, ParentVD, ArrayTy, NameBuilder,
6459handleArrayOfStructWithResources(
Sema &S,
VarDecl *ParentVD,
6461 EmbeddedResourceNameBuilder &NameBuilder,
6462 StructBindingContext &BindingCtx) {
6470 if (!SubCAT && !ElementRD)
6473 for (
unsigned I = 0, E = CAT->
getSize().getZExtValue(); I < E; ++I) {
6476 handleStructWithResources(S, ParentVD, ElementRD, NameBuilder,
6479 handleArrayOfStructWithResources(S, ParentVD, SubCAT, NameBuilder,
6492void SemaHLSL::handleGlobalStructOrArrayOfWithResources(
VarDecl *VD) {
6493 EmbeddedResourceNameBuilder NameBuilder(VD->
getName());
6494 StructBindingContext BindingCtx(VD);
6498 "Expected non-resource struct or array type");
6501 handleStructWithResources(
SemaRef, VD, RD, NameBuilder, BindingCtx);
6505 if (
const auto *CAT = dyn_cast<ConstantArrayType>(VDTy)) {
6506 handleArrayOfStructWithResources(
SemaRef, VD, CAT, NameBuilder, BindingCtx);
6514 if (
SemaRef.RequireCompleteType(
6517 diag::err_typecheck_decl_incomplete_type)) {
6531 DefaultCBufferDecls.push_back(VD);
6536 collectResourceBindingsOnVarDecl(VD);
6538 if (VD->
hasAttr<HLSLVkConstantIdAttr>())
6550 processExplicitBindingsOnDecl(VD);
6587 handleGlobalStructOrArrayOfWithResources(VD);
6591 if (VD->
hasAttr<HLSLGroupSharedAddressSpaceAttr>())
6600 "expected resource record type");
6616 const char *CreateMethodName;
6618 CreateMethodName = HasCounter ?
"__createFromBindingWithImplicitCounter"
6619 :
"__createFromBinding";
6621 CreateMethodName = HasCounter
6622 ?
"__createFromImplicitBindingWithImplicitCounter"
6623 :
"__createFromImplicitBinding";
6628 if (!CreateMethod) {
6633 "create method lookup should always succeed for built-in resource "
6642 Args.push_back(RegSlot);
6650 Args.push_back(OrderId);
6656 Args.push_back(Space);
6660 Args.push_back(RangeSize);
6664 Args.push_back(Index);
6666 StringRef VarName = VD->
getName();
6674 Args.push_back(NameCast);
6682 Args.push_back(CounterId);
6705 SemaRef.CheckCompleteVariableDeclaration(VD);
6711 "expected array of resource records");
6732 lookupMethod(
SemaRef, ResourceDecl,
6733 HasCounter ?
"__createFromBindingWithImplicitCounter"
6734 :
"__createFromBinding",
6738 CreateMethod = lookupMethod(
6740 HasCounter ?
"__createFromImplicitBindingWithImplicitCounter"
6741 :
"__createFromImplicitBinding",
6784std::optional<const DeclBindingInfo *> SemaHLSL::inferGlobalBinding(
Expr *E) {
6785 if (
auto *Ternary = dyn_cast<ConditionalOperator>(E)) {
6786 auto TrueInfo = inferGlobalBinding(Ternary->getTrueExpr());
6787 auto FalseInfo = inferGlobalBinding(Ternary->getFalseExpr());
6788 if (!TrueInfo || !FalseInfo)
6789 return std::nullopt;
6790 if (*TrueInfo != *FalseInfo)
6791 return std::nullopt;
6795 if (
auto *ASE = dyn_cast<ArraySubscriptExpr>(E))
6804 if (
const auto *AttrResType =
6805 HLSLAttributedResourceType::findHandleTypeOnResource(Ty)) {
6807 return Bindings.getDeclBindingInfo(VD, RC);
6814void SemaHLSL::trackLocalResource(
VarDecl *VD,
Expr *E) {
6815 std::optional<const DeclBindingInfo *> ExprBinding = inferGlobalBinding(E);
6818 diag::warn_hlsl_assigning_local_resource_is_not_unique)
6823 if (*ExprBinding ==
nullptr)
6826 auto PrevBinding = Assigns.find(VD);
6827 if (PrevBinding == Assigns.end()) {
6829 Assigns.insert({VD, *ExprBinding});
6834 if (*ExprBinding != PrevBinding->second) {
6836 diag::warn_hlsl_assigning_local_resource_is_not_unique)
6838 SemaRef.Diag(VD->getLocation(), diag::note_var_declared_here) << VD;
6849 "expected LHS to be a resource record or array of resource records");
6850 if (Opc != BO_Assign)
6855 while (
auto *ASE = dyn_cast<ArraySubscriptExpr>(E))
6863 SemaRef.Diag(Loc, diag::err_hlsl_assign_to_global_resource) << VD;
6868 trackLocalResource(VD, RHSExpr);
6885void SemaHLSL::collectResourceBindingsOnVarDecl(
VarDecl *VD) {
6887 "expected global variable that contains HLSL resource");
6890 if (
const HLSLBufferDecl *CBufferOrTBuffer = dyn_cast<HLSLBufferDecl>(VD)) {
6891 Bindings.addDeclBindingInfo(VD, CBufferOrTBuffer->isCBuffer()
6892 ? ResourceClass::CBuffer
6893 : ResourceClass::SRV);
6906 if (
const HLSLAttributedResourceType *AttrResType =
6907 HLSLAttributedResourceType::findHandleTypeOnResource(Ty)) {
6908 Bindings.addDeclBindingInfo(VD, AttrResType->getAttrs().ResourceClass);
6913 if (
const RecordType *RT = dyn_cast<RecordType>(Ty))
6914 collectResourceBindingsOnUserRecordDecl(VD, RT);
6920void SemaHLSL::processExplicitBindingsOnDecl(
VarDecl *VD) {
6923 bool HasBinding =
false;
6924 for (Attr *A : VD->
attrs()) {
6927 if (
auto PA = VD->
getAttr<HLSLVkPushConstantAttr>())
6928 Diag(PA->getLoc(), diag::err_hlsl_attr_incompatible) << A << PA;
6931 HLSLResourceBindingAttr *RBA = dyn_cast<HLSLResourceBindingAttr>(A);
6932 if (!RBA || !RBA->hasRegisterSlot())
6937 assert(RT != RegisterType::I &&
"invalid or obsolete register type should "
6938 "never have an attribute created");
6940 if (RT == RegisterType::C) {
6941 if (Bindings.hasBindingInfoForDecl(VD))
6943 diag::warn_hlsl_user_defined_type_missing_member)
6944 <<
static_cast<int>(RT);
6952 if (DeclBindingInfo *BI = Bindings.getDeclBindingInfo(VD, RC)) {
6957 diag::warn_hlsl_user_defined_type_missing_member)
6958 <<
static_cast<int>(RT);
6966class InitListTransformer {
6970 QualType *DstIt =
nullptr;
6971 Expr **ArgIt =
nullptr;
6977 bool castInitializer(Expr *E) {
6978 assert(DstIt &&
"This should always be something!");
6979 if (DstIt == DestTypes.end()) {
6981 ArgExprs.push_back(E);
6986 DstIt = DestTypes.begin();
6989 Ctx, *DstIt,
false);
6994 ArgExprs.push_back(
Init);
6999 bool buildInitializerListImpl(Expr *E) {
7001 if (
auto *
Init = dyn_cast<InitListExpr>(E)) {
7002 for (
auto *SubInit :
Init->inits())
7003 if (!buildInitializerListImpl(SubInit))
7013 return castInitializer(E);
7027 if (
auto *VecTy = Ty->
getAs<VectorType>()) {
7034 SizeTy, SourceLocation());
7040 if (!castInitializer(ElExpr.
get()))
7045 if (
auto *MTy = Ty->
getAs<ConstantMatrixType>()) {
7046 unsigned Rows = MTy->getNumRows();
7047 unsigned Cols = MTy->getNumColumns();
7048 QualType ElemTy = MTy->getElementType();
7050 for (
unsigned R = 0;
R < Rows; ++
R) {
7051 for (
unsigned C = 0;
C < Cols; ++
C) {
7064 if (!castInitializer(ElExpr.
get()))
7072 if (
auto *ArrTy = dyn_cast<ConstantArrayType>(Ty.
getTypePtr())) {
7078 SizeTy, SourceLocation());
7083 if (!buildInitializerListImpl(ElExpr.
get()))
7090 llvm::SmallVector<CXXRecordDecl *> RecordDecls;
7091 RecordDecls.push_back(RD);
7092 while (RecordDecls.back()->getNumBases()) {
7093 CXXRecordDecl *D = RecordDecls.back();
7095 "HLSL doesn't support multiple inheritance");
7096 RecordDecls.push_back(
7099 while (!RecordDecls.empty()) {
7100 CXXRecordDecl *RD = RecordDecls.pop_back_val();
7101 for (
auto *FD : RD->
fields()) {
7102 if (FD->isUnnamedBitField())
7110 if (!buildInitializerListImpl(Res.
get()))
7118 Expr *generateInitListsImpl(QualType Ty) {
7120 assert(ArgIt != ArgExprs.end() &&
"Something is off in iteration!");
7125 llvm::SmallVector<Expr *>
Inits;
7130 if (
auto *ATy = Ty->
getAs<VectorType>()) {
7131 ElTy = ATy->getElementType();
7132 Size = ATy->getNumElements();
7133 }
else if (
auto *CMTy = Ty->
getAs<ConstantMatrixType>()) {
7134 ElTy = CMTy->getElementType();
7135 Size = CMTy->getNumElementsFlattened();
7138 ElTy = VTy->getElementType();
7139 Size = VTy->getZExtSize();
7142 Inits.push_back(generateInitListsImpl(ElTy));
7145 llvm::SmallVector<CXXRecordDecl *> RecordDecls;
7146 RecordDecls.push_back(RD);
7147 while (RecordDecls.back()->getNumBases()) {
7148 CXXRecordDecl *D = RecordDecls.back();
7150 "HLSL doesn't support multiple inheritance");
7151 RecordDecls.push_back(
7154 while (!RecordDecls.empty()) {
7155 CXXRecordDecl *RD = RecordDecls.pop_back_val();
7156 for (
auto *FD : RD->
fields())
7157 if (!FD->isUnnamedBitField())
7162 new (Ctx) InitListExpr(Ctx,
Inits.front()->getBeginLoc(),
Inits,
7163 Inits.back()->getEndLoc(),
false);
7164 NewInit->setType(Ty);
7169 llvm::SmallVector<QualType, 16> DestTypes;
7170 llvm::SmallVector<Expr *, 16> ArgExprs;
7171 InitListTransformer(Sema &SemaRef,
const InitializedEntity &Entity)
7172 : S(SemaRef), Ctx(SemaRef.getASTContext()),
7173 Wrap(Entity.
getType()->isIncompleteArrayType()) {
7174 InitTy = Entity.
getType().getNonReferenceType();
7184 DstIt = DestTypes.begin();
7187 bool buildInitializerList(Expr *E) {
return buildInitializerListImpl(E); }
7189 Expr *generateInitLists() {
7190 assert(!ArgExprs.empty() &&
7191 "Call buildInitializerList to generate argument expressions.");
7192 ArgIt = ArgExprs.begin();
7194 return generateInitListsImpl(InitTy);
7195 llvm::SmallVector<Expr *>
Inits;
7196 while (ArgIt != ArgExprs.end())
7197 Inits.push_back(generateInitListsImpl(InitTy));
7200 new (Ctx) InitListExpr(Ctx,
Inits.front()->getBeginLoc(),
Inits,
7201 Inits.back()->getEndLoc(),
false);
7202 llvm::APInt ArySize(64,
Inits.size());
7204 ArraySizeModifier::Normal, 0));
7216 if (
const ArrayType *AT = dyn_cast<ArrayType>(Ty)) {
7223 if (
const auto *RT = Ty->
getAs<RecordType>()) {
7227 if (
const auto *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
7247 if (
Init->getType()->isScalarType())
7250 InitListTransformer ILT(
SemaRef, Entity);
7252 for (
unsigned I = 0; I <
Init->getNumInits(); ++I) {
7260 Init->setInit(I, E);
7262 if (!ILT.buildInitializerList(E))
7265 size_t ExpectedSize = ILT.DestTypes.size();
7266 size_t ActualSize = ILT.ArgExprs.size();
7267 if (ExpectedSize == 0 && ActualSize == 0)
7274 InitTy =
SemaRef.getASTContext().removeAddrSpaceQualType(InitTy);
7276 SemaRef.Diag(
Init->getBeginLoc(), diag::err_hlsl_incorrect_num_initializers)
7277 << (int)(ExpectedSize < ActualSize) << InitTy
7278 << ExpectedSize << ActualSize;
7288 assert(ExpectedSize > 0 &&
7289 "The expected size of an incomplete array type must be at least 1.");
7291 ((ActualSize + ExpectedSize - 1) / ExpectedSize) * ExpectedSize;
7299 InitTy =
SemaRef.getASTContext().removeAddrSpaceQualType(InitTy);
7300 if (ExpectedSize != ActualSize) {
7301 int TooManyOrFew = ActualSize > ExpectedSize ? 1 : 0;
7302 SemaRef.Diag(
Init->getBeginLoc(), diag::err_hlsl_incorrect_num_initializers)
7303 << TooManyOrFew << InitTy << ExpectedSize << ActualSize;
7310 Init->resizeInits(Ctx, NewInit->getNumInits());
7311 for (
unsigned I = 0; I < NewInit->getNumInits(); ++I)
7312 Init->updateInit(Ctx, I, NewInit->getInit(I));
7320 S.
Diag(OpLoc, diag::err_builtin_matrix_invalid_member)
7330 StringRef AccessorName = CompName->
getName();
7331 assert(!AccessorName.empty() &&
"Matrix Accessor must have a name");
7333 unsigned Rows = MT->getNumRows();
7334 unsigned Cols = MT->getNumColumns();
7335 bool IsZeroBasedAccessor =
false;
7336 unsigned ChunkLen = 0;
7337 if (AccessorName.size() < 2)
7339 "length 4 for zero based: \'_mRC\' or "
7340 "length 3 for one-based: \'_RC\' accessor",
7343 if (AccessorName[0] ==
'_') {
7344 if (AccessorName[1] ==
'm') {
7345 IsZeroBasedAccessor =
true;
7352 S, AccessorName,
"zero based: \'_mRC\' or one-based: \'_RC\' accessor",
7355 if (AccessorName.size() % ChunkLen != 0) {
7356 const llvm::StringRef
Expected = IsZeroBasedAccessor
7357 ?
"zero based: '_mRC' accessor"
7358 :
"one-based: '_RC' accessor";
7363 auto isDigit = [](
char c) {
return c >=
'0' && c <=
'9'; };
7364 auto isZeroBasedIndex = [](
unsigned i) {
return i <= 3; };
7365 auto isOneBasedIndex = [](
unsigned i) {
return i >= 1 && i <= 4; };
7367 bool HasRepeated =
false;
7369 unsigned NumComponents = 0;
7370 const char *Begin = AccessorName.data();
7372 for (
unsigned I = 0, E = AccessorName.size(); I < E; I += ChunkLen) {
7373 const char *Chunk = Begin + I;
7374 char RowChar = 0, ColChar = 0;
7375 if (IsZeroBasedAccessor) {
7377 if (Chunk[0] !=
'_' || Chunk[1] !=
'm') {
7378 char Bad = (Chunk[0] !=
'_') ? Chunk[0] : Chunk[1];
7380 S, StringRef(&Bad, 1),
"\'_m\' prefix",
7387 if (Chunk[0] !=
'_')
7389 S, StringRef(&Chunk[0], 1),
"\'_\' prefix",
7396 bool IsDigitsError =
false;
7398 unsigned BadPos = IsZeroBasedAccessor ? 2 : 1;
7402 IsDigitsError =
true;
7406 unsigned BadPos = IsZeroBasedAccessor ? 3 : 2;
7410 IsDigitsError =
true;
7415 unsigned Row = RowChar -
'0';
7416 unsigned Col = ColChar -
'0';
7418 bool HasIndexingError =
false;
7419 if (IsZeroBasedAccessor) {
7421 if (!isZeroBasedIndex(Row)) {
7422 S.
Diag(OpLoc, diag::err_hlsl_matrix_element_not_in_bounds)
7424 HasIndexingError =
true;
7426 if (!isZeroBasedIndex(Col)) {
7427 S.
Diag(OpLoc, diag::err_hlsl_matrix_element_not_in_bounds)
7429 HasIndexingError =
true;
7433 if (!isOneBasedIndex(Row)) {
7434 S.
Diag(OpLoc, diag::err_hlsl_matrix_element_not_in_bounds)
7436 HasIndexingError =
true;
7438 if (!isOneBasedIndex(Col)) {
7439 S.
Diag(OpLoc, diag::err_hlsl_matrix_element_not_in_bounds)
7441 HasIndexingError =
true;
7448 if (HasIndexingError)
7454 bool HasBoundsError =
false;
7456 Diag(OpLoc, diag::err_hlsl_matrix_index_out_of_bounds)
7458 HasBoundsError =
true;
7461 Diag(OpLoc, diag::err_hlsl_matrix_index_out_of_bounds)
7463 HasBoundsError =
true;
7468 unsigned FlatIndex = Row * Cols + Col;
7469 if (Seen[FlatIndex])
7471 Seen[FlatIndex] =
true;
7474 if (NumComponents == 0 || NumComponents > 4) {
7475 S.
Diag(OpLoc, diag::err_hlsl_matrix_swizzle_invalid_length)
7480 QualType ElemTy = MT->getElementType();
7481 if (NumComponents == 1)
7487 for (Sema::ExtVectorDeclsType::iterator
7491 if ((*I)->getUnderlyingType() == VT)
7502 trackLocalResource(VDecl,
Init);
7504 const HLSLVkConstantIdAttr *ConstIdAttr =
7505 VDecl->
getAttr<HLSLVkConstantIdAttr>();
7512 if (!
Init->isCXX11ConstantExpr(Context, InitValue)) {
7522 int ConstantID = ConstIdAttr->getId();
7523 llvm::APInt IDVal(Context.getIntWidth(Context.IntTy), ConstantID);
7525 ConstIdAttr->getLocation());
7529 if (
C->getType()->getCanonicalTypeUnqualified() !=
7533 Context.getTrivialTypeSourceInfo(
7534 Init->getType(),
Init->getExprLoc()),
7553 if (!Params || Params->
size() != 1)
7566 if (
auto *TTP = dyn_cast<TemplateTypeParmDecl>(P)) {
7567 if (TTP->hasDefaultArgument()) {
7568 TemplateArgs.
addArgument(TTP->getDefaultArgument());
7571 }
else if (
auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(P)) {
7572 if (NTTP->hasDefaultArgument()) {
7573 TemplateArgs.
addArgument(NTTP->getDefaultArgument());
7576 }
else if (
auto *TTPD = dyn_cast<TemplateTemplateParmDecl>(P)) {
7577 if (TTPD->hasDefaultArgument()) {
7578 TemplateArgs.
addArgument(TTPD->getDefaultArgument());
7585 return SemaRef.CheckTemplateIdType(
7587 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)
bool IsVulkanTypedResourceElementCompatible(QualType T1)
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.
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