clang 23.0.0git
SemaHLSL.cpp
Go to the documentation of this file.
1//===- SemaHLSL.cpp - Semantic Analysis for HLSL constructs ---------------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8// This implements Semantic Analysis for HLSL constructs.
9//===----------------------------------------------------------------------===//
10
11#include "clang/Sema/SemaHLSL.h"
14#include "clang/AST/Attr.h"
15#include "clang/AST/Decl.h"
16#include "clang/AST/DeclBase.h"
17#include "clang/AST/DeclCXX.h"
20#include "clang/AST/Expr.h"
22#include "clang/AST/Type.h"
23#include "clang/AST/TypeBase.h"
24#include "clang/AST/TypeLoc.h"
28#include "clang/Basic/LLVM.h"
33#include "clang/Sema/Lookup.h"
35#include "clang/Sema/Sema.h"
36#include "clang/Sema/Template.h"
37#include "llvm/ADT/ArrayRef.h"
38#include "llvm/ADT/STLExtras.h"
39#include "llvm/ADT/SmallVector.h"
40#include "llvm/ADT/StringExtras.h"
41#include "llvm/ADT/StringRef.h"
42#include "llvm/ADT/Twine.h"
43#include "llvm/Frontend/HLSL/HLSLBinding.h"
44#include "llvm/Frontend/HLSL/RootSignatureValidations.h"
45#include "llvm/Support/Casting.h"
46#include "llvm/Support/DXILABI.h"
47#include "llvm/Support/ErrorHandling.h"
48#include "llvm/Support/FormatVariadic.h"
49#include "llvm/TargetParser/Triple.h"
50#include <cmath>
51#include <cstddef>
52#include <iterator>
53#include <utility>
54
55using namespace clang;
56using namespace clang::hlsl;
57using RegisterType = HLSLResourceBindingAttr::RegisterType;
58
60 CXXRecordDecl *StructDecl);
61
63 switch (RC) {
64 case ResourceClass::SRV:
65 return RegisterType::SRV;
66 case ResourceClass::UAV:
67 return RegisterType::UAV;
68 case ResourceClass::CBuffer:
69 return RegisterType::CBuffer;
70 case ResourceClass::Sampler:
71 return RegisterType::Sampler;
72 }
73 llvm_unreachable("unexpected ResourceClass value");
74}
75
76static RegisterType getRegisterType(const HLSLAttributedResourceType *ResTy) {
77 return getRegisterType(ResTy->getAttrs().ResourceClass);
78}
79
81 switch (RC) {
82 case ResourceClass::SRV:
83 case ResourceClass::UAV:
85 case ResourceClass::CBuffer:
87 case ResourceClass::Sampler:
89 }
90 llvm_unreachable("unexpected ResourceClass value");
91}
92
93// Converts the first letter of string Slot to RegisterType.
94// Returns false if the letter does not correspond to a valid register type.
95static bool convertToRegisterType(StringRef Slot, RegisterType *RT) {
96 assert(RT != nullptr);
97 switch (Slot[0]) {
98 case 't':
99 case 'T':
100 *RT = RegisterType::SRV;
101 return true;
102 case 'u':
103 case 'U':
104 *RT = RegisterType::UAV;
105 return true;
106 case 'b':
107 case 'B':
108 *RT = RegisterType::CBuffer;
109 return true;
110 case 's':
111 case 'S':
112 *RT = RegisterType::Sampler;
113 return true;
114 case 'c':
115 case 'C':
116 *RT = RegisterType::C;
117 return true;
118 case 'i':
119 case 'I':
120 *RT = RegisterType::I;
121 return true;
122 default:
123 return false;
124 }
125}
126
128 switch (RT) {
129 case RegisterType::SRV:
130 return 't';
131 case RegisterType::UAV:
132 return 'u';
133 case RegisterType::CBuffer:
134 return 'b';
135 case RegisterType::Sampler:
136 return 's';
137 case RegisterType::C:
138 return 'c';
139 case RegisterType::I:
140 return 'i';
141 }
142 llvm_unreachable("unexpected RegisterType value");
143}
144
146 switch (RT) {
147 case RegisterType::SRV:
148 return ResourceClass::SRV;
149 case RegisterType::UAV:
150 return ResourceClass::UAV;
151 case RegisterType::CBuffer:
152 return ResourceClass::CBuffer;
153 case RegisterType::Sampler:
154 return ResourceClass::Sampler;
155 case RegisterType::C:
156 case RegisterType::I:
157 // Deliberately falling through to the unreachable below.
158 break;
159 }
160 llvm_unreachable("unexpected RegisterType value");
161}
162
164 const auto *BT = dyn_cast<BuiltinType>(Type);
165 if (!BT) {
166 if (!Type->isEnumeralType())
167 return Builtin::NotBuiltin;
168 return Builtin::BI__builtin_get_spirv_spec_constant_int;
169 }
170
171 switch (BT->getKind()) {
172 case BuiltinType::Bool:
173 return Builtin::BI__builtin_get_spirv_spec_constant_bool;
174 case BuiltinType::Short:
175 return Builtin::BI__builtin_get_spirv_spec_constant_short;
176 case BuiltinType::Int:
177 return Builtin::BI__builtin_get_spirv_spec_constant_int;
178 case BuiltinType::LongLong:
179 return Builtin::BI__builtin_get_spirv_spec_constant_longlong;
180 case BuiltinType::UShort:
181 return Builtin::BI__builtin_get_spirv_spec_constant_ushort;
182 case BuiltinType::UInt:
183 return Builtin::BI__builtin_get_spirv_spec_constant_uint;
184 case BuiltinType::ULongLong:
185 return Builtin::BI__builtin_get_spirv_spec_constant_ulonglong;
186 case BuiltinType::Half:
187 return Builtin::BI__builtin_get_spirv_spec_constant_half;
188 case BuiltinType::Float:
189 return Builtin::BI__builtin_get_spirv_spec_constant_float;
190 case BuiltinType::Double:
191 return Builtin::BI__builtin_get_spirv_spec_constant_double;
192 default:
193 return Builtin::NotBuiltin;
194 }
195}
196
197static StringRef createRegisterString(ASTContext &AST, RegisterType RegType,
198 unsigned N) {
200 llvm::raw_svector_ostream OS(Buffer);
201 OS << getRegisterTypeChar(RegType);
202 OS << N;
203 return AST.backupStr(OS.str());
204}
205
207 ResourceClass ResClass) {
208 assert(getDeclBindingInfo(VD, ResClass) == nullptr &&
209 "DeclBindingInfo already added");
210 assert(!hasBindingInfoForDecl(VD) || BindingsList.back().Decl == VD);
211 // VarDecl may have multiple entries for different resource classes.
212 // DeclToBindingListIndex stores the index of the first binding we saw
213 // for this decl. If there are any additional ones then that index
214 // shouldn't be updated.
215 DeclToBindingListIndex.try_emplace(VD, BindingsList.size());
216 return &BindingsList.emplace_back(VD, ResClass);
217}
218
220 ResourceClass ResClass) {
221 auto Entry = DeclToBindingListIndex.find(VD);
222 if (Entry != DeclToBindingListIndex.end()) {
223 for (unsigned Index = Entry->getSecond();
224 Index < BindingsList.size() && BindingsList[Index].Decl == VD;
225 ++Index) {
226 if (BindingsList[Index].ResClass == ResClass)
227 return &BindingsList[Index];
228 }
229 }
230 return nullptr;
231}
232
234 return DeclToBindingListIndex.contains(VD);
235}
236
238
239Decl *SemaHLSL::ActOnStartBuffer(Scope *BufferScope, bool CBuffer,
240 SourceLocation KwLoc, IdentifierInfo *Ident,
241 SourceLocation IdentLoc,
242 SourceLocation LBrace) {
243 // For anonymous namespace, take the location of the left brace.
244 DeclContext *LexicalParent = SemaRef.getCurLexicalContext();
246 getASTContext(), LexicalParent, CBuffer, KwLoc, Ident, IdentLoc, LBrace);
247
248 // if CBuffer is false, then it's a TBuffer
249 auto RC = CBuffer ? llvm::hlsl::ResourceClass::CBuffer
250 : llvm::hlsl::ResourceClass::SRV;
251 Result->addAttr(HLSLResourceClassAttr::CreateImplicit(getASTContext(), RC));
252
253 SemaRef.PushOnScopeChains(Result, BufferScope);
254 SemaRef.PushDeclContext(BufferScope, Result);
255
256 return Result;
257}
258
259static unsigned calculateLegacyCbufferFieldAlign(const ASTContext &Context,
260 QualType T) {
261 // Arrays, Matrices, and Structs are always aligned to new buffer rows
262 if (T->isArrayType() || T->isStructureType() || T->isConstantMatrixType())
263 return 16;
264
265 // Vectors are aligned to the type they contain
266 if (const VectorType *VT = T->getAs<VectorType>())
267 return calculateLegacyCbufferFieldAlign(Context, VT->getElementType());
268
269 assert(Context.getTypeSize(T) <= 64 &&
270 "Scalar bit widths larger than 64 not supported");
271
272 // Scalar types are aligned to their byte width
273 return Context.getTypeSize(T) / 8;
274}
275
276// Calculate the size of a legacy cbuffer type in bytes based on
277// https://learn.microsoft.com/en-us/windows/win32/direct3dhlsl/dx-graphics-hlsl-packing-rules
278static unsigned calculateLegacyCbufferSize(const ASTContext &Context,
279 QualType T) {
280 constexpr unsigned CBufferAlign = 16;
281 if (const auto *RD = T->getAsRecordDecl()) {
282 unsigned Size = 0;
283 for (const FieldDecl *Field : RD->fields()) {
284 QualType Ty = Field->getType();
285 unsigned FieldSize = calculateLegacyCbufferSize(Context, Ty);
286 unsigned FieldAlign = calculateLegacyCbufferFieldAlign(Context, Ty);
287
288 // If the field crosses the row boundary after alignment it drops to the
289 // next row
290 unsigned AlignSize = llvm::alignTo(Size, FieldAlign);
291 if ((AlignSize % CBufferAlign) + FieldSize > CBufferAlign) {
292 FieldAlign = CBufferAlign;
293 }
294
295 Size = llvm::alignTo(Size, FieldAlign);
296 Size += FieldSize;
297 }
298 return Size;
299 }
300
301 if (const ConstantArrayType *AT = Context.getAsConstantArrayType(T)) {
302 unsigned ElementCount = AT->getSize().getZExtValue();
303 if (ElementCount == 0)
304 return 0;
305
306 unsigned ElementSize =
307 calculateLegacyCbufferSize(Context, AT->getElementType());
308 unsigned AlignedElementSize = llvm::alignTo(ElementSize, CBufferAlign);
309 return AlignedElementSize * (ElementCount - 1) + ElementSize;
310 }
311
312 if (const VectorType *VT = T->getAs<VectorType>()) {
313 unsigned ElementCount = VT->getNumElements();
314 unsigned ElementSize =
315 calculateLegacyCbufferSize(Context, VT->getElementType());
316 return ElementSize * ElementCount;
317 }
318
319 return Context.getTypeSize(T) / 8;
320}
321
322// Validate packoffset:
323// - if packoffset it used it must be set on all declarations inside the buffer
324// - packoffset ranges must not overlap
325static void validatePackoffset(Sema &S, HLSLBufferDecl *BufDecl) {
327
328 // Make sure the packoffset annotations are either on all declarations
329 // or on none.
330 bool HasPackOffset = false;
331 bool HasNonPackOffset = false;
332 for (auto *Field : BufDecl->buffer_decls()) {
333 VarDecl *Var = dyn_cast<VarDecl>(Field);
334 if (!Var)
335 continue;
336 if (Field->hasAttr<HLSLPackOffsetAttr>()) {
337 PackOffsetVec.emplace_back(Var, Field->getAttr<HLSLPackOffsetAttr>());
338 HasPackOffset = true;
339 } else {
340 HasNonPackOffset = true;
341 }
342 }
343
344 if (!HasPackOffset)
345 return;
346
347 if (HasNonPackOffset)
348 S.Diag(BufDecl->getLocation(), diag::warn_hlsl_packoffset_mix);
349
350 // Make sure there is no overlap in packoffset - sort PackOffsetVec by offset
351 // and compare adjacent values.
352 bool IsValid = true;
353 ASTContext &Context = S.getASTContext();
354 std::sort(PackOffsetVec.begin(), PackOffsetVec.end(),
355 [](const std::pair<VarDecl *, HLSLPackOffsetAttr *> &LHS,
356 const std::pair<VarDecl *, HLSLPackOffsetAttr *> &RHS) {
357 return LHS.second->getOffsetInBytes() <
358 RHS.second->getOffsetInBytes();
359 });
360 for (unsigned i = 0; i < PackOffsetVec.size() - 1; i++) {
361 VarDecl *Var = PackOffsetVec[i].first;
362 HLSLPackOffsetAttr *Attr = PackOffsetVec[i].second;
363 unsigned Size = calculateLegacyCbufferSize(Context, Var->getType());
364 unsigned Begin = Attr->getOffsetInBytes();
365 unsigned End = Begin + Size;
366 unsigned NextBegin = PackOffsetVec[i + 1].second->getOffsetInBytes();
367 if (End > NextBegin) {
368 VarDecl *NextVar = PackOffsetVec[i + 1].first;
369 S.Diag(NextVar->getLocation(), diag::err_hlsl_packoffset_overlap)
370 << NextVar << Var;
371 IsValid = false;
372 }
373 }
374 BufDecl->setHasValidPackoffset(IsValid);
375}
376
377// Returns true if the array has a zero size = if any of the dimensions is 0
378static bool isZeroSizedArray(const ConstantArrayType *CAT) {
379 while (CAT && !CAT->isZeroSize())
380 CAT = dyn_cast<ConstantArrayType>(
382 return CAT != nullptr;
383}
384
388
392
393static const HLSLAttributedResourceType *
395 assert(QT->isHLSLResourceRecordArray() &&
396 "expected array of resource records");
397 const Type *Ty = QT->getUnqualifiedDesugaredType();
398 while (const ArrayType *AT = dyn_cast<ArrayType>(Ty))
400 return HLSLAttributedResourceType::findHandleTypeOnResource(Ty);
401}
402
403static const HLSLAttributedResourceType *
407
408// Returns true if the type is a leaf element type that is not valid to be
409// included in HLSL Buffer, such as a resource class, empty struct, zero-sized
410// array, or a builtin intangible type. Returns false it is a valid leaf element
411// type or if it is a record type that needs to be inspected further.
415 return true;
416 if (const auto *RD = Ty->getAsCXXRecordDecl())
417 return RD->isEmpty();
418 if (Ty->isConstantArrayType() &&
420 return true;
422 return true;
423 return false;
424}
425
426// Returns true if the struct contains at least one element that prevents it
427// from being included inside HLSL Buffer as is, such as an intangible type,
428// empty struct, or zero-sized array. If it does, a new implicit layout struct
429// needs to be created for HLSL Buffer use that will exclude these unwanted
430// declarations (see createHostLayoutStruct function).
432 if (RD->isHLSLIntangible() || RD->isEmpty())
433 return true;
434 // check fields
435 for (const FieldDecl *Field : RD->fields()) {
436 QualType Ty = Field->getType();
438 return true;
439 if (const auto *RD = Ty->getAsCXXRecordDecl();
441 return true;
442 }
443 // check bases
444 for (const CXXBaseSpecifier &Base : RD->bases())
446 Base.getType()->castAsCXXRecordDecl()))
447 return true;
448 return false;
449}
450
452 DeclContext *DC) {
453 CXXRecordDecl *RD = nullptr;
454 for (NamedDecl *Decl :
456 if (CXXRecordDecl *FoundRD = dyn_cast<CXXRecordDecl>(Decl)) {
457 assert(RD == nullptr &&
458 "there should be at most 1 record by a given name in a scope");
459 RD = FoundRD;
460 }
461 }
462 return RD;
463}
464
465// Creates a name for buffer layout struct using the provide name base.
466// If the name must be unique (not previously defined), a suffix is added
467// until a unique name is found.
469 bool MustBeUnique) {
470 ASTContext &AST = S.getASTContext();
471
472 IdentifierInfo *NameBaseII = BaseDecl->getIdentifier();
473 llvm::SmallString<64> Name("__cblayout_");
474 if (NameBaseII) {
475 Name.append(NameBaseII->getName());
476 } else {
477 // anonymous struct
478 Name.append("anon");
479 MustBeUnique = true;
480 }
481
482 size_t NameLength = Name.size();
483 IdentifierInfo *II = &AST.Idents.get(Name, tok::TokenKind::identifier);
484 if (!MustBeUnique)
485 return II;
486
487 unsigned suffix = 0;
488 while (true) {
489 if (suffix != 0) {
490 Name.append("_");
491 Name.append(llvm::Twine(suffix).str());
492 II = &AST.Idents.get(Name, tok::TokenKind::identifier);
493 }
494 if (!findRecordDeclInContext(II, BaseDecl->getDeclContext()))
495 return II;
496 // declaration with that name already exists - increment suffix and try
497 // again until unique name is found
498 suffix++;
499 Name.truncate(NameLength);
500 };
501}
502
503static const Type *createHostLayoutType(Sema &S, const Type *Ty) {
504 ASTContext &AST = S.getASTContext();
505 if (auto *RD = Ty->getAsCXXRecordDecl()) {
507 return Ty;
508 RD = createHostLayoutStruct(S, RD);
509 if (!RD)
510 return nullptr;
511 return AST.getCanonicalTagType(RD)->getTypePtr();
512 }
513
514 if (const auto *CAT = dyn_cast<ConstantArrayType>(Ty)) {
515 const Type *ElementTy = createHostLayoutType(
516 S, CAT->getElementType()->getUnqualifiedDesugaredType());
517 if (!ElementTy)
518 return nullptr;
519 return AST
520 .getConstantArrayType(QualType(ElementTy, 0), CAT->getSize(), nullptr,
521 CAT->getSizeModifier(),
522 CAT->getIndexTypeCVRQualifiers())
523 .getTypePtr();
524 }
525 return Ty;
526}
527
528// Returns the type to use for a host layout struct field. For most types this
529// is the unqualified desugared type. Matrix types, however, retain their sugar
530// so that the row_major/column_major orientation (carried as an AttributedType)
531// is preserved; the orientation determines the in-memory cbuffer layout.
533 const Type *Desugared = QT->getUnqualifiedDesugaredType();
534 if (Desugared->isConstantMatrixType())
535 return QT.getTypePtr();
536 return Desugared;
537}
538
539// Creates a field declaration of given name and type for HLSL buffer layout
540// struct. Returns nullptr if the type cannot be use in HLSL Buffer layout.
542 IdentifierInfo *II,
543 CXXRecordDecl *LayoutStruct) {
545 return nullptr;
546
547 Ty = createHostLayoutType(S, Ty);
548 if (!Ty)
549 return nullptr;
550
551 QualType QT = QualType(Ty, 0);
552 ASTContext &AST = S.getASTContext();
554 auto *Field = FieldDecl::Create(AST, LayoutStruct, SourceLocation(),
555 SourceLocation(), II, QT, TSI, nullptr, false,
557 Field->setAccess(AccessSpecifier::AS_public);
558 return Field;
559}
560
561// Creates host layout struct for a struct included in HLSL Buffer.
562// The layout struct will include only fields that are allowed in HLSL buffer.
563// These fields will be filtered out:
564// - resource classes
565// - empty structs
566// - zero-sized arrays
567// Returns nullptr if the resulting layout struct would be empty.
569 CXXRecordDecl *StructDecl) {
570 assert(requiresImplicitBufferLayoutStructure(StructDecl) &&
571 "struct is already HLSL buffer compatible");
572
573 ASTContext &AST = S.getASTContext();
574 DeclContext *DC = StructDecl->getDeclContext();
575 IdentifierInfo *II = getHostLayoutStructName(S, StructDecl, false);
576
577 // reuse existing if the layout struct if it already exists
578 if (CXXRecordDecl *RD = findRecordDeclInContext(II, DC))
579 return RD;
580
581 CXXRecordDecl *LS =
582 CXXRecordDecl::Create(AST, TagDecl::TagKind::Struct, DC, SourceLocation(),
583 SourceLocation(), II);
584 LS->setImplicit(true);
585 LS->addAttr(PackedAttr::CreateImplicit(AST));
586 LS->startDefinition();
587
588 // copy base struct, create HLSL Buffer compatible version if needed
589 if (unsigned NumBases = StructDecl->getNumBases()) {
590 assert(NumBases == 1 && "HLSL supports only one base type");
591 (void)NumBases;
592 CXXBaseSpecifier Base = *StructDecl->bases_begin();
593 CXXRecordDecl *BaseDecl = Base.getType()->castAsCXXRecordDecl();
595 BaseDecl = createHostLayoutStruct(S, BaseDecl);
596 if (BaseDecl) {
597 TypeSourceInfo *TSI =
599 Base = CXXBaseSpecifier(SourceRange(), false, StructDecl->isClass(),
600 AS_none, TSI, SourceLocation());
601 }
602 }
603 if (BaseDecl) {
604 const CXXBaseSpecifier *BasesArray[1] = {&Base};
605 LS->setBases(BasesArray, 1);
606 }
607 }
608
609 // filter struct fields
610 for (const FieldDecl *FD : StructDecl->fields()) {
611 const Type *Ty = getHostLayoutFieldType(FD->getType());
612 if (FieldDecl *NewFD =
613 createFieldForHostLayoutStruct(S, Ty, FD->getIdentifier(), LS))
614 LS->addDecl(NewFD);
615 }
616 LS->completeDefinition();
617
618 if (LS->field_empty() && LS->getNumBases() == 0)
619 return nullptr;
620
621 DC->addDecl(LS);
622 return LS;
623}
624
625// Creates host layout struct for HLSL Buffer. The struct will include only
626// fields of types that are allowed in HLSL buffer and it will filter out:
627// - static or groupshared variable declarations
628// - resource classes
629// - empty structs
630// - zero-sized arrays
631// - non-variable declarations
632// The layout struct will be added to the HLSLBufferDecl declarations.
634 ASTContext &AST = S.getASTContext();
635 IdentifierInfo *II = getHostLayoutStructName(S, BufDecl, true);
636
637 CXXRecordDecl *LS =
638 CXXRecordDecl::Create(AST, TagDecl::TagKind::Struct, BufDecl,
640 LS->addAttr(PackedAttr::CreateImplicit(AST));
641 LS->setImplicit(true);
642 LS->startDefinition();
643
644 for (Decl *D : BufDecl->buffer_decls()) {
645 VarDecl *VD = dyn_cast<VarDecl>(D);
646 if (!VD || VD->getStorageClass() == SC_Static ||
648 continue;
649 const Type *Ty = getHostLayoutFieldType(VD->getType());
650
651 FieldDecl *FD =
653 // Declarations collected for the default $Globals constant buffer have
654 // already been checked to have non-empty cbuffer layout, so
655 // createFieldForHostLayoutStruct should always succeed. These declarations
656 // already have their address space set to hlsl_constant.
657 // For declarations in a named cbuffer block
658 // createFieldForHostLayoutStruct can still return nullptr if the type
659 // is empty (does not have a cbuffer layout).
660 assert((FD || VD->getType().getAddressSpace() != LangAS::hlsl_constant) &&
661 "host layout field for $Globals decl failed to be created");
662 if (FD) {
663 // Add the field decl to the layout struct.
664 LS->addDecl(FD);
666 // Update address space of the original decl to hlsl_constant.
667 QualType NewTy =
669 VD->setType(NewTy);
670 }
671 }
672 }
673 LS->completeDefinition();
674 BufDecl->addLayoutStruct(LS);
675}
676
678 uint32_t ImplicitBindingOrderID) {
679 auto *Attr =
680 HLSLResourceBindingAttr::CreateImplicit(S.getASTContext(), "", "0", {});
681 Attr->setBinding(RT, std::nullopt, 0);
682 Attr->setImplicitBindingOrderID(ImplicitBindingOrderID);
683 D->addAttr(Attr);
684}
685
686// Handle end of cbuffer/tbuffer declaration
688 auto *BufDecl = cast<HLSLBufferDecl>(Dcl);
689 BufDecl->setRBraceLoc(RBrace);
690
691 validatePackoffset(SemaRef, BufDecl);
692
694
695 // Handle implicit binding if needed.
696 ResourceBindingAttrs ResourceAttrs(Dcl);
697 if (!ResourceAttrs.isExplicit()) {
698 SemaRef.Diag(Dcl->getLocation(), diag::warn_hlsl_implicit_binding);
699 // Use HLSLResourceBindingAttr to transfer implicit binding order_ID
700 // to codegen. If it does not exist, create an implicit attribute.
701 uint32_t OrderID = getNextImplicitBindingOrderID();
702 if (ResourceAttrs.hasBinding())
703 ResourceAttrs.setImplicitOrderID(OrderID);
704 else
706 BufDecl->isCBuffer() ? RegisterType::CBuffer
707 : RegisterType::SRV,
708 OrderID);
709 }
710
711 SemaRef.PopDeclContext();
712}
713
714HLSLNumThreadsAttr *SemaHLSL::mergeNumThreadsAttr(Decl *D,
715 const AttributeCommonInfo &AL,
716 int X, int Y, int Z) {
717 if (HLSLNumThreadsAttr *NT = D->getAttr<HLSLNumThreadsAttr>()) {
718 if (NT->getX() != X || NT->getY() != Y || NT->getZ() != Z) {
719 Diag(NT->getLocation(), diag::err_hlsl_attribute_param_mismatch) << AL;
720 Diag(AL.getLoc(), diag::note_conflicting_attribute);
721 }
722 return nullptr;
723 }
724 return ::new (getASTContext())
725 HLSLNumThreadsAttr(getASTContext(), AL, X, Y, Z);
726}
727
729 const AttributeCommonInfo &AL,
730 int Min, int Max, int Preferred,
731 int SpelledArgsCount) {
732 if (HLSLWaveSizeAttr *WS = D->getAttr<HLSLWaveSizeAttr>()) {
733 if (WS->getMin() != Min || WS->getMax() != Max ||
734 WS->getPreferred() != Preferred ||
735 WS->getSpelledArgsCount() != SpelledArgsCount) {
736 Diag(WS->getLocation(), diag::err_hlsl_attribute_param_mismatch) << AL;
737 Diag(AL.getLoc(), diag::note_conflicting_attribute);
738 }
739 return nullptr;
740 }
741 HLSLWaveSizeAttr *Result = ::new (getASTContext())
742 HLSLWaveSizeAttr(getASTContext(), AL, Min, Max, Preferred);
743 Result->setSpelledArgsCount(SpelledArgsCount);
744 return Result;
745}
746
747HLSLVkConstantIdAttr *
749 int Id) {
750
752 if (TargetInfo.getTriple().getArch() != llvm::Triple::spirv) {
753 Diag(AL.getLoc(), diag::warn_attribute_ignored) << AL;
754 return nullptr;
755 }
756
757 auto *VD = cast<VarDecl>(D);
758
759 if (getSpecConstBuiltinId(VD->getType()->getUnqualifiedDesugaredType()) ==
761 Diag(VD->getLocation(), diag::err_specialization_const);
762 return nullptr;
763 }
764
765 if (!VD->getType().isConstQualified()) {
766 Diag(VD->getLocation(), diag::err_specialization_const);
767 return nullptr;
768 }
769
770 if (HLSLVkConstantIdAttr *CI = D->getAttr<HLSLVkConstantIdAttr>()) {
771 if (CI->getId() != Id) {
772 Diag(CI->getLocation(), diag::err_hlsl_attribute_param_mismatch) << AL;
773 Diag(AL.getLoc(), diag::note_conflicting_attribute);
774 }
775 return nullptr;
776 }
777
778 HLSLVkConstantIdAttr *Result =
779 ::new (getASTContext()) HLSLVkConstantIdAttr(getASTContext(), AL, Id);
780 return Result;
781}
782
783HLSLShaderAttr *
785 llvm::Triple::EnvironmentType ShaderType) {
786 if (HLSLShaderAttr *NT = D->getAttr<HLSLShaderAttr>()) {
787 if (NT->getType() != ShaderType) {
788 Diag(NT->getLocation(), diag::err_hlsl_attribute_param_mismatch) << AL;
789 Diag(AL.getLoc(), diag::note_conflicting_attribute);
790 }
791 return nullptr;
792 }
793 return HLSLShaderAttr::Create(getASTContext(), ShaderType, AL);
794}
795
796HLSLParamModifierAttr *
798 HLSLParamModifierAttr::Spelling Spelling) {
799 // We can only merge an `in` attribute with an `out` attribute. All other
800 // combinations of duplicated attributes are ill-formed.
801 if (HLSLParamModifierAttr *PA = D->getAttr<HLSLParamModifierAttr>()) {
802 if ((PA->isIn() && Spelling == HLSLParamModifierAttr::Keyword_out) ||
803 (PA->isOut() && Spelling == HLSLParamModifierAttr::Keyword_in)) {
804 D->dropAttr<HLSLParamModifierAttr>();
805 SourceRange AdjustedRange = {PA->getLocation(), AL.getRange().getEnd()};
806 return HLSLParamModifierAttr::Create(
807 getASTContext(), /*MergedSpelling=*/true, AdjustedRange,
808 HLSLParamModifierAttr::Keyword_inout);
809 }
810 Diag(AL.getLoc(), diag::err_hlsl_duplicate_parameter_modifier) << AL;
811 Diag(PA->getLocation(), diag::note_conflicting_attribute);
812 return nullptr;
813 }
814 return HLSLParamModifierAttr::Create(getASTContext(), AL);
815}
816
819
821 return;
822
823 // If we have specified a root signature to override the entry function then
824 // attach it now
825 HLSLRootSignatureDecl *SignatureDecl =
827 if (SignatureDecl) {
828 FD->dropAttr<RootSignatureAttr>();
829 // We could look up the SourceRange of the macro here as well
830 AttributeCommonInfo AL(RootSigOverrideIdent, AttributeScopeInfo(),
831 SourceRange(), ParsedAttr::Form::Microsoft());
832 FD->addAttr(::new (getASTContext()) RootSignatureAttr(
833 getASTContext(), AL, RootSigOverrideIdent, SignatureDecl));
834 }
835
836 llvm::Triple::EnvironmentType Env = TargetInfo.getTriple().getEnvironment();
837 if (HLSLShaderAttr::isValidShaderType(Env) && Env != llvm::Triple::Library) {
838 if (const auto *Shader = FD->getAttr<HLSLShaderAttr>()) {
839 // The entry point is already annotated - check that it matches the
840 // triple.
841 if (Shader->getType() != Env) {
842 Diag(Shader->getLocation(), diag::err_hlsl_entry_shader_attr_mismatch)
843 << Shader;
844 FD->setInvalidDecl();
845 }
846 } else {
847 // Implicitly add the shader attribute if the entry function isn't
848 // explicitly annotated.
849 FD->addAttr(HLSLShaderAttr::CreateImplicit(getASTContext(), Env,
850 FD->getBeginLoc()));
851 }
852 } else {
853 switch (Env) {
854 case llvm::Triple::UnknownEnvironment:
855 case llvm::Triple::Library:
856 break;
857 case llvm::Triple::RootSignature:
858 llvm_unreachable("rootsig environment has no functions");
859 default:
860 llvm_unreachable("Unhandled environment in triple");
861 }
862 }
863}
864
865static bool isVkPipelineBuiltin(const ASTContext &AstContext, FunctionDecl *FD,
866 HLSLAppliedSemanticAttr *Semantic,
867 bool IsInput) {
868 if (AstContext.getTargetInfo().getTriple().getOS() != llvm::Triple::Vulkan)
869 return false;
870
871 const auto *ShaderAttr = FD->getAttr<HLSLShaderAttr>();
872 assert(ShaderAttr && "Entry point has no shader attribute");
873 llvm::Triple::EnvironmentType ST = ShaderAttr->getType();
874 auto SemanticName = Semantic->getSemanticName().upper();
875
876 // The SV_Position semantic is lowered to:
877 // - Position built-in for vertex output.
878 // - FragCoord built-in for fragment input.
879 if (SemanticName == "SV_POSITION") {
880 return (ST == llvm::Triple::Vertex && !IsInput) ||
881 (ST == llvm::Triple::Pixel && IsInput);
882 }
883 if (SemanticName == "SV_VERTEXID")
884 return true;
885
886 return false;
887}
888
889bool SemaHLSL::determineActiveSemanticOnScalar(FunctionDecl *FD,
890 DeclaratorDecl *OutputDecl,
892 SemanticInfo &ActiveSemantic,
893 SemaHLSL::SemanticContext &SC) {
894 if (ActiveSemantic.Semantic == nullptr) {
895 ActiveSemantic.Semantic = D->getAttr<HLSLParsedSemanticAttr>();
896 if (ActiveSemantic.Semantic)
897 ActiveSemantic.Index = ActiveSemantic.Semantic->getSemanticIndex();
898 }
899
900 if (!ActiveSemantic.Semantic) {
901 Diag(D->getLocation(), diag::err_hlsl_missing_semantic_annotation);
902 return false;
903 }
904
905 auto *A = ::new (getASTContext())
906 HLSLAppliedSemanticAttr(getASTContext(), *ActiveSemantic.Semantic,
907 ActiveSemantic.Semantic->getAttrName()->getName(),
908 ActiveSemantic.Index.value_or(0));
909 if (!A)
911
912 checkSemanticAnnotation(FD, D, A, SC);
913 OutputDecl->addAttr(A);
914
915 unsigned Location = ActiveSemantic.Index.value_or(0);
916
918 SC.CurrentIOType & IOType::In)) {
919 bool HasVkLocation = false;
920 if (auto *A = D->getAttr<HLSLVkLocationAttr>()) {
921 HasVkLocation = true;
922 Location = A->getLocation();
923 }
924
925 if (SC.UsesExplicitVkLocations.value_or(HasVkLocation) != HasVkLocation) {
926 Diag(D->getLocation(), diag::err_hlsl_semantic_partial_explicit_indexing);
927 return false;
928 }
929 SC.UsesExplicitVkLocations = HasVkLocation;
930 }
931
932 const ConstantArrayType *AT = dyn_cast<ConstantArrayType>(D->getType());
933 unsigned ElementCount = AT ? AT->getZExtSize() : 1;
934 ActiveSemantic.Index = Location + ElementCount;
935
936 Twine BaseName = Twine(ActiveSemantic.Semantic->getAttrName()->getName());
937 for (unsigned I = 0; I < ElementCount; ++I) {
938 Twine VariableName = BaseName.concat(Twine(Location + I));
939
940 auto [_, Inserted] = SC.ActiveSemantics.insert(VariableName.str());
941 if (!Inserted) {
942 Diag(D->getLocation(), diag::err_hlsl_semantic_index_overlap)
943 << VariableName.str();
944 return false;
945 }
946 }
947
948 return true;
949}
950
951bool SemaHLSL::determineActiveSemantic(FunctionDecl *FD,
952 DeclaratorDecl *OutputDecl,
954 SemanticInfo &ActiveSemantic,
955 SemaHLSL::SemanticContext &SC) {
956 if (ActiveSemantic.Semantic == nullptr) {
957 ActiveSemantic.Semantic = D->getAttr<HLSLParsedSemanticAttr>();
958 if (ActiveSemantic.Semantic)
959 ActiveSemantic.Index = ActiveSemantic.Semantic->getSemanticIndex();
960 }
961
962 const Type *T = D == FD ? &*FD->getReturnType() : &*D->getType();
964
965 const RecordType *RT = dyn_cast<RecordType>(T);
966 if (!RT)
967 return determineActiveSemanticOnScalar(FD, OutputDecl, D, ActiveSemantic,
968 SC);
969
970 const RecordDecl *RD = RT->getDecl();
971 for (FieldDecl *Field : RD->fields()) {
972 SemanticInfo Info = ActiveSemantic;
973 if (!determineActiveSemantic(FD, OutputDecl, Field, Info, SC)) {
974 Diag(Field->getLocation(), diag::note_hlsl_semantic_used_here) << Field;
975 return false;
976 }
977 if (ActiveSemantic.Semantic)
978 ActiveSemantic = Info;
979 }
980
981 return true;
982}
983
985 const auto *ShaderAttr = FD->getAttr<HLSLShaderAttr>();
986 assert(ShaderAttr && "Entry point has no shader attribute");
987 llvm::Triple::EnvironmentType ST = ShaderAttr->getType();
989 VersionTuple Ver = TargetInfo.getTriple().getOSVersion();
990 switch (ST) {
991 case llvm::Triple::Pixel:
992 case llvm::Triple::Vertex:
993 case llvm::Triple::Geometry:
994 case llvm::Triple::Hull:
995 case llvm::Triple::Domain:
996 case llvm::Triple::RayGeneration:
997 case llvm::Triple::Intersection:
998 case llvm::Triple::AnyHit:
999 case llvm::Triple::ClosestHit:
1000 case llvm::Triple::Miss:
1001 case llvm::Triple::Callable:
1002 if (const auto *NT = FD->getAttr<HLSLNumThreadsAttr>()) {
1003 diagnoseAttrStageMismatch(NT, ST,
1004 {llvm::Triple::Compute,
1005 llvm::Triple::Amplification,
1006 llvm::Triple::Mesh});
1007 FD->setInvalidDecl();
1008 }
1009 if (const auto *WS = FD->getAttr<HLSLWaveSizeAttr>()) {
1010 diagnoseAttrStageMismatch(WS, ST,
1011 {llvm::Triple::Compute,
1012 llvm::Triple::Amplification,
1013 llvm::Triple::Mesh});
1014 FD->setInvalidDecl();
1015 }
1016 break;
1017
1018 case llvm::Triple::Compute:
1019 case llvm::Triple::Amplification:
1020 case llvm::Triple::Mesh:
1021 if (!FD->hasAttr<HLSLNumThreadsAttr>()) {
1022 Diag(FD->getLocation(), diag::err_hlsl_missing_numthreads)
1023 << llvm::Triple::getEnvironmentTypeName(ST);
1024 FD->setInvalidDecl();
1025 }
1026 if (const auto *WS = FD->getAttr<HLSLWaveSizeAttr>()) {
1027 if (Ver < VersionTuple(6, 6)) {
1028 Diag(WS->getLocation(), diag::err_hlsl_attribute_in_wrong_shader_model)
1029 << WS << "6.6";
1030 FD->setInvalidDecl();
1031 } else if (WS->getSpelledArgsCount() > 1 && Ver < VersionTuple(6, 8)) {
1032 Diag(
1033 WS->getLocation(),
1034 diag::err_hlsl_attribute_number_arguments_insufficient_shader_model)
1035 << WS << WS->getSpelledArgsCount() << "6.8";
1036 FD->setInvalidDecl();
1037 }
1038 }
1039 break;
1040 case llvm::Triple::RootSignature:
1041 llvm_unreachable("rootsig environment has no function entry point");
1042 default:
1043 llvm_unreachable("Unhandled environment in triple");
1044 }
1045
1046 SemaHLSL::SemanticContext InputSC = {};
1047 InputSC.CurrentIOType = IOType::In;
1048
1049 for (ParmVarDecl *Param : FD->parameters()) {
1050 SemanticInfo ActiveSemantic;
1051 ActiveSemantic.Semantic = Param->getAttr<HLSLParsedSemanticAttr>();
1052 if (ActiveSemantic.Semantic)
1053 ActiveSemantic.Index = ActiveSemantic.Semantic->getSemanticIndex();
1054
1055 // FIXME: Verify output semantics in parameters.
1056 if (!determineActiveSemantic(FD, Param, Param, ActiveSemantic, InputSC)) {
1057 Diag(Param->getLocation(), diag::note_previous_decl) << Param;
1058 FD->setInvalidDecl();
1059 }
1060 }
1061
1062 SemanticInfo ActiveSemantic;
1063 SemaHLSL::SemanticContext OutputSC = {};
1064 OutputSC.CurrentIOType = IOType::Out;
1065 ActiveSemantic.Semantic = FD->getAttr<HLSLParsedSemanticAttr>();
1066 if (ActiveSemantic.Semantic)
1067 ActiveSemantic.Index = ActiveSemantic.Semantic->getSemanticIndex();
1068 if (!FD->getReturnType()->isVoidType())
1069 determineActiveSemantic(FD, FD, FD, ActiveSemantic, OutputSC);
1070}
1071
1072void SemaHLSL::checkSemanticAnnotation(
1073 FunctionDecl *EntryPoint, const Decl *Param,
1074 const HLSLAppliedSemanticAttr *SemanticAttr, const SemanticContext &SC) {
1075 auto *ShaderAttr = EntryPoint->getAttr<HLSLShaderAttr>();
1076 assert(ShaderAttr && "Entry point has no shader attribute");
1077 llvm::Triple::EnvironmentType ST = ShaderAttr->getType();
1078
1079 auto SemanticName = SemanticAttr->getSemanticName().upper();
1080 if (SemanticName == "SV_DISPATCHTHREADID" ||
1081 SemanticName == "SV_GROUPINDEX" || SemanticName == "SV_GROUPTHREADID" ||
1082 SemanticName == "SV_GROUPID") {
1083
1084 if (ST != llvm::Triple::Compute)
1085 diagnoseSemanticStageMismatch(SemanticAttr, ST, SC.CurrentIOType,
1086 {{llvm::Triple::Compute, IOType::In}});
1087
1088 if (SemanticAttr->getSemanticIndex() != 0) {
1089 std::string PrettyName =
1090 "'" + SemanticAttr->getSemanticName().str() + "'";
1091 Diag(SemanticAttr->getLoc(),
1092 diag::err_hlsl_semantic_indexing_not_supported)
1093 << PrettyName;
1094 }
1095 return;
1096 }
1097
1098 if (SemanticName == "SV_POSITION") {
1099 // SV_Position can be an input or output in vertex shaders,
1100 // but only an input in pixel shaders.
1101 diagnoseSemanticStageMismatch(SemanticAttr, ST, SC.CurrentIOType,
1102 {{llvm::Triple::Vertex, IOType::InOut},
1103 {llvm::Triple::Pixel, IOType::In}});
1104 return;
1105 }
1106 if (SemanticName == "SV_VERTEXID") {
1107 diagnoseSemanticStageMismatch(SemanticAttr, ST, SC.CurrentIOType,
1108 {{llvm::Triple::Vertex, IOType::In}});
1109 return;
1110 }
1111
1112 if (SemanticName == "SV_TARGET") {
1113 diagnoseSemanticStageMismatch(SemanticAttr, ST, SC.CurrentIOType,
1114 {{llvm::Triple::Pixel, IOType::Out}});
1115 return;
1116 }
1117
1118 // FIXME: catch-all for non-implemented system semantics reaching this
1119 // location.
1120 if (SemanticAttr->getAttrName()->getName().starts_with_insensitive("SV_"))
1121 llvm_unreachable("Unknown SemanticAttr");
1122}
1123
1124void SemaHLSL::diagnoseAttrStageMismatch(
1125 const Attr *A, llvm::Triple::EnvironmentType Stage,
1126 std::initializer_list<llvm::Triple::EnvironmentType> AllowedStages) {
1127 SmallVector<StringRef, 8> StageStrings;
1128 llvm::transform(AllowedStages, std::back_inserter(StageStrings),
1129 [](llvm::Triple::EnvironmentType ST) {
1130 return StringRef(
1131 HLSLShaderAttr::ConvertEnvironmentTypeToStr(ST));
1132 });
1133 Diag(A->getLoc(), diag::err_hlsl_attr_unsupported_in_stage)
1134 << A->getAttrName() << llvm::Triple::getEnvironmentTypeName(Stage)
1135 << (AllowedStages.size() != 1) << join(StageStrings, ", ");
1136}
1137
1138void SemaHLSL::diagnoseSemanticStageMismatch(
1139 const Attr *A, llvm::Triple::EnvironmentType Stage, IOType CurrentIOType,
1140 std::initializer_list<SemanticStageInfo> Allowed) {
1141
1142 for (auto &Case : Allowed) {
1143 if (Case.Stage != Stage)
1144 continue;
1145
1146 if (CurrentIOType & Case.AllowedIOTypesMask)
1147 return;
1148
1149 SmallVector<std::string, 8> ValidCases;
1150 llvm::transform(
1151 Allowed, std::back_inserter(ValidCases), [](SemanticStageInfo Case) {
1152 SmallVector<std::string, 2> ValidType;
1153 if (Case.AllowedIOTypesMask & IOType::In)
1154 ValidType.push_back("input");
1155 if (Case.AllowedIOTypesMask & IOType::Out)
1156 ValidType.push_back("output");
1157 return std::string(
1158 HLSLShaderAttr::ConvertEnvironmentTypeToStr(Case.Stage)) +
1159 " " + join(ValidType, "/");
1160 });
1161 Diag(A->getLoc(), diag::err_hlsl_semantic_unsupported_iotype_for_stage)
1162 << A->getAttrName() << (CurrentIOType & IOType::In ? "input" : "output")
1163 << llvm::Triple::getEnvironmentTypeName(Case.Stage)
1164 << join(ValidCases, ", ");
1165 return;
1166 }
1167
1168 SmallVector<StringRef, 8> StageStrings;
1169 llvm::transform(
1170 Allowed, std::back_inserter(StageStrings), [](SemanticStageInfo Case) {
1171 return StringRef(
1172 HLSLShaderAttr::ConvertEnvironmentTypeToStr(Case.Stage));
1173 });
1174
1175 Diag(A->getLoc(), diag::err_hlsl_attr_unsupported_in_stage)
1176 << A->getAttrName() << llvm::Triple::getEnvironmentTypeName(Stage)
1177 << (Allowed.size() != 1) << join(StageStrings, ", ");
1178}
1179
1180template <CastKind Kind>
1181static void castVector(Sema &S, ExprResult &E, QualType &Ty, unsigned Sz) {
1182 if (const auto *VTy = Ty->getAs<VectorType>())
1183 Ty = VTy->getElementType();
1184 Ty = S.getASTContext().getExtVectorType(Ty, Sz);
1185 E = S.ImpCastExprToType(E.get(), Ty, Kind);
1186}
1187
1188template <CastKind Kind>
1190 E = S.ImpCastExprToType(E.get(), Ty, Kind);
1191 return Ty;
1192}
1193
1195 Sema &SemaRef, ExprResult &LHS, ExprResult &RHS, QualType LHSType,
1196 QualType RHSType, QualType LElTy, QualType RElTy, bool IsCompAssign) {
1197 bool LHSFloat = LElTy->isRealFloatingType();
1198 bool RHSFloat = RElTy->isRealFloatingType();
1199
1200 if (LHSFloat && RHSFloat) {
1201 if (IsCompAssign ||
1202 SemaRef.getASTContext().getFloatingTypeOrder(LElTy, RElTy) > 0)
1203 return castElement<CK_FloatingCast>(SemaRef, RHS, LHSType);
1204
1205 return castElement<CK_FloatingCast>(SemaRef, LHS, RHSType);
1206 }
1207
1208 if (LHSFloat)
1209 return castElement<CK_IntegralToFloating>(SemaRef, RHS, LHSType);
1210
1211 assert(RHSFloat);
1212 if (IsCompAssign)
1213 return castElement<clang::CK_FloatingToIntegral>(SemaRef, RHS, LHSType);
1214
1215 return castElement<CK_IntegralToFloating>(SemaRef, LHS, RHSType);
1216}
1217
1219 Sema &SemaRef, ExprResult &LHS, ExprResult &RHS, QualType LHSType,
1220 QualType RHSType, QualType LElTy, QualType RElTy, bool IsCompAssign) {
1221
1222 int IntOrder = SemaRef.Context.getIntegerTypeOrder(LElTy, RElTy);
1223 bool LHSSigned = LElTy->hasSignedIntegerRepresentation();
1224 bool RHSSigned = RElTy->hasSignedIntegerRepresentation();
1225 auto &Ctx = SemaRef.getASTContext();
1226
1227 // If both types have the same signedness, use the higher ranked type.
1228 if (LHSSigned == RHSSigned) {
1229 if (IsCompAssign || IntOrder >= 0)
1230 return castElement<CK_IntegralCast>(SemaRef, RHS, LHSType);
1231
1232 return castElement<CK_IntegralCast>(SemaRef, LHS, RHSType);
1233 }
1234
1235 // If the unsigned type has greater than or equal rank of the signed type, use
1236 // the unsigned type.
1237 if (IntOrder != (LHSSigned ? 1 : -1)) {
1238 if (IsCompAssign || RHSSigned)
1239 return castElement<CK_IntegralCast>(SemaRef, RHS, LHSType);
1240 return castElement<CK_IntegralCast>(SemaRef, LHS, RHSType);
1241 }
1242
1243 // At this point the signed type has higher rank than the unsigned type, which
1244 // means it will be the same size or bigger. If the signed type is bigger, it
1245 // can represent all the values of the unsigned type, so select it.
1246 if (Ctx.getIntWidth(LElTy) != Ctx.getIntWidth(RElTy)) {
1247 if (IsCompAssign || LHSSigned)
1248 return castElement<CK_IntegralCast>(SemaRef, RHS, LHSType);
1249 return castElement<CK_IntegralCast>(SemaRef, LHS, RHSType);
1250 }
1251
1252 // This is a bit of an odd duck case in HLSL. It shouldn't happen, but can due
1253 // to C/C++ leaking through. The place this happens today is long vs long
1254 // long. When arguments are vector<unsigned long, N> and vector<long long, N>,
1255 // the long long has higher rank than long even though they are the same size.
1256
1257 // If this is a compound assignment cast the right hand side to the left hand
1258 // side's type.
1259 if (IsCompAssign)
1260 return castElement<CK_IntegralCast>(SemaRef, RHS, LHSType);
1261
1262 // If this isn't a compound assignment we convert to unsigned long long.
1263 QualType ElTy = Ctx.getCorrespondingUnsignedType(LHSSigned ? LElTy : RElTy);
1264 QualType NewTy = Ctx.getExtVectorType(
1265 ElTy, RHSType->castAs<VectorType>()->getNumElements());
1266 (void)castElement<CK_IntegralCast>(SemaRef, RHS, NewTy);
1267
1268 return castElement<CK_IntegralCast>(SemaRef, LHS, NewTy);
1269}
1270
1272 QualType SrcTy) {
1273 if (DestTy->isRealFloatingType() && SrcTy->isRealFloatingType())
1274 return CK_FloatingCast;
1275 if (DestTy->isIntegralType(Ctx) && SrcTy->isIntegralType(Ctx))
1276 return CK_IntegralCast;
1277 if (DestTy->isRealFloatingType())
1278 return CK_IntegralToFloating;
1279 assert(SrcTy->isRealFloatingType() && DestTy->isIntegralType(Ctx));
1280 return CK_FloatingToIntegral;
1281}
1282
1284 QualType LHSType,
1285 QualType RHSType,
1286 bool IsCompAssign) {
1287 const auto *LVecTy = LHSType->getAs<VectorType>();
1288 const auto *RVecTy = RHSType->getAs<VectorType>();
1289 auto &Ctx = getASTContext();
1290
1291 // If the LHS is not a vector and this is a compound assignment, we truncate
1292 // the argument to a scalar then convert it to the LHS's type.
1293 if (!LVecTy && IsCompAssign) {
1294 QualType RElTy = RHSType->castAs<VectorType>()->getElementType();
1295 RHS = SemaRef.ImpCastExprToType(RHS.get(), RElTy, CK_HLSLVectorTruncation);
1296 RHSType = RHS.get()->getType();
1297 if (Ctx.hasSameUnqualifiedType(LHSType, RHSType))
1298 return LHSType;
1299 RHS = SemaRef.ImpCastExprToType(RHS.get(), LHSType,
1300 getScalarCastKind(Ctx, LHSType, RHSType));
1301 return LHSType;
1302 }
1303
1304 unsigned EndSz = std::numeric_limits<unsigned>::max();
1305 unsigned LSz = 0;
1306 if (LVecTy)
1307 LSz = EndSz = LVecTy->getNumElements();
1308 if (RVecTy)
1309 EndSz = std::min(RVecTy->getNumElements(), EndSz);
1310 assert(EndSz != std::numeric_limits<unsigned>::max() &&
1311 "one of the above should have had a value");
1312
1313 // In a compound assignment, the left operand does not change type, the right
1314 // operand is converted to the type of the left operand.
1315 if (IsCompAssign && LSz != EndSz) {
1316 Diag(LHS.get()->getBeginLoc(),
1317 diag::err_hlsl_vector_compound_assignment_truncation)
1318 << LHSType << RHSType;
1319 return QualType();
1320 }
1321
1322 if (RVecTy && RVecTy->getNumElements() > EndSz)
1323 castVector<CK_HLSLVectorTruncation>(SemaRef, RHS, RHSType, EndSz);
1324 if (!IsCompAssign && LVecTy && LVecTy->getNumElements() > EndSz)
1325 castVector<CK_HLSLVectorTruncation>(SemaRef, LHS, LHSType, EndSz);
1326
1327 if (!RVecTy)
1328 castVector<CK_VectorSplat>(SemaRef, RHS, RHSType, EndSz);
1329 if (!IsCompAssign && !LVecTy)
1330 castVector<CK_VectorSplat>(SemaRef, LHS, LHSType, EndSz);
1331
1332 // If we're at the same type after resizing we can stop here.
1333 if (Ctx.hasSameUnqualifiedType(LHSType, RHSType))
1334 return Ctx.getCommonSugaredType(LHSType, RHSType);
1335
1336 QualType LElTy = LHSType->castAs<VectorType>()->getElementType();
1337 QualType RElTy = RHSType->castAs<VectorType>()->getElementType();
1338
1339 // Handle conversion for floating point vectors.
1340 if (LElTy->isRealFloatingType() || RElTy->isRealFloatingType())
1341 return handleFloatVectorBinOpConversion(SemaRef, LHS, RHS, LHSType, RHSType,
1342 LElTy, RElTy, IsCompAssign);
1343
1344 assert(LElTy->isIntegralType(Ctx) && RElTy->isIntegralType(Ctx) &&
1345 "HLSL Vectors can only contain integer or floating point types");
1346 return handleIntegerVectorBinOpConversion(SemaRef, LHS, RHS, LHSType, RHSType,
1347 LElTy, RElTy, IsCompAssign);
1348}
1349
1351 BinaryOperatorKind Opc) {
1352 assert((Opc == BO_LOr || Opc == BO_LAnd) &&
1353 "Called with non-logical operator");
1355 llvm::raw_svector_ostream OS(Buff);
1356 PrintingPolicy PP(SemaRef.getLangOpts());
1357 StringRef NewFnName = Opc == BO_LOr ? "or" : "and";
1358 OS << NewFnName << "(";
1359 LHS->printPretty(OS, nullptr, PP);
1360 OS << ", ";
1361 RHS->printPretty(OS, nullptr, PP);
1362 OS << ")";
1363 SourceRange FullRange = SourceRange(LHS->getBeginLoc(), RHS->getEndLoc());
1364 SemaRef.Diag(LHS->getBeginLoc(), diag::note_function_suggestion)
1365 << NewFnName << FixItHint::CreateReplacement(FullRange, OS.str());
1366}
1367
1368std::pair<IdentifierInfo *, bool>
1370 llvm::hash_code Hash = llvm::hash_value(Signature);
1371 std::string IdStr = "__hlsl_rootsig_decl_" + std::to_string(Hash);
1372 IdentifierInfo *DeclIdent = &(getASTContext().Idents.get(IdStr));
1373
1374 // Check if we have already found a decl of the same name.
1375 LookupResult R(SemaRef, DeclIdent, SourceLocation(),
1377 bool Found = SemaRef.LookupQualifiedName(R, SemaRef.CurContext);
1378 return {DeclIdent, Found};
1379}
1380
1382 SourceLocation Loc, IdentifierInfo *DeclIdent,
1384
1385 if (handleRootSignatureElements(RootElements))
1386 return;
1387
1389 for (auto &RootSigElement : RootElements)
1390 Elements.push_back(RootSigElement.getElement());
1391
1392 auto *SignatureDecl = HLSLRootSignatureDecl::Create(
1393 SemaRef.getASTContext(), /*DeclContext=*/SemaRef.CurContext, Loc,
1394 DeclIdent, SemaRef.getLangOpts().HLSLRootSigVer, Elements);
1395
1396 SignatureDecl->setImplicit();
1397 SemaRef.PushOnScopeChains(SignatureDecl, SemaRef.getCurScope());
1398}
1399
1402 if (RootSigOverrideIdent) {
1403 LookupResult R(SemaRef, RootSigOverrideIdent, SourceLocation(),
1405 if (SemaRef.LookupQualifiedName(R, DC))
1406 return dyn_cast<HLSLRootSignatureDecl>(R.getFoundDecl());
1407 }
1408
1409 return nullptr;
1410}
1411
1412namespace {
1413
1414struct PerVisibilityBindingChecker {
1415 SemaHLSL *S;
1416 // We need one builder per `llvm::dxbc::ShaderVisibility` value.
1417 std::array<llvm::hlsl::BindingInfoBuilder, 8> Builders;
1418
1419 struct ElemInfo {
1420 const hlsl::RootSignatureElement *Elem;
1421 llvm::dxbc::ShaderVisibility Vis;
1422 bool Diagnosed;
1423 };
1424 llvm::SmallVector<ElemInfo> ElemInfoMap;
1425
1426 PerVisibilityBindingChecker(SemaHLSL *S) : S(S) {}
1427
1428 void trackBinding(llvm::dxbc::ShaderVisibility Visibility,
1429 llvm::dxil::ResourceClass RC, uint32_t Space,
1430 uint32_t LowerBound, uint32_t UpperBound,
1431 const hlsl::RootSignatureElement *Elem) {
1432 uint32_t BuilderIndex = llvm::to_underlying(Visibility);
1433 assert(BuilderIndex < Builders.size() &&
1434 "Not enough builders for visibility type");
1435 Builders[BuilderIndex].trackBinding(RC, Space, LowerBound, UpperBound,
1436 static_cast<const void *>(Elem));
1437
1438 static_assert(llvm::to_underlying(llvm::dxbc::ShaderVisibility::All) == 0,
1439 "'All' visibility must come first");
1440 if (Visibility == llvm::dxbc::ShaderVisibility::All)
1441 for (size_t I = 1, E = Builders.size(); I < E; ++I)
1442 Builders[I].trackBinding(RC, Space, LowerBound, UpperBound,
1443 static_cast<const void *>(Elem));
1444
1445 ElemInfoMap.push_back({Elem, Visibility, false});
1446 }
1447
1448 ElemInfo &getInfo(const hlsl::RootSignatureElement *Elem) {
1449 auto It = llvm::lower_bound(
1450 ElemInfoMap, Elem,
1451 [](const auto &LHS, const auto &RHS) { return LHS.Elem < RHS; });
1452 assert(It->Elem == Elem && "Element not in map");
1453 return *It;
1454 }
1455
1456 bool checkOverlap() {
1457 llvm::sort(ElemInfoMap, [](const auto &LHS, const auto &RHS) {
1458 return LHS.Elem < RHS.Elem;
1459 });
1460
1461 bool HadOverlap = false;
1462
1463 using llvm::hlsl::BindingInfoBuilder;
1464 auto ReportOverlap = [this,
1465 &HadOverlap](const BindingInfoBuilder &Builder,
1466 const llvm::hlsl::Binding &Reported) {
1467 HadOverlap = true;
1468
1469 const auto *Elem =
1470 static_cast<const hlsl::RootSignatureElement *>(Reported.Cookie);
1471 const llvm::hlsl::Binding &Previous = Builder.findOverlapping(Reported);
1472 const auto *PrevElem =
1473 static_cast<const hlsl::RootSignatureElement *>(Previous.Cookie);
1474
1475 ElemInfo &Info = getInfo(Elem);
1476 // We will have already diagnosed this binding if there's overlap in the
1477 // "All" visibility as well as any particular visibility.
1478 if (Info.Diagnosed)
1479 return;
1480 Info.Diagnosed = true;
1481
1482 ElemInfo &PrevInfo = getInfo(PrevElem);
1483 llvm::dxbc::ShaderVisibility CommonVis =
1484 Info.Vis == llvm::dxbc::ShaderVisibility::All ? PrevInfo.Vis
1485 : Info.Vis;
1486
1487 this->S->Diag(Elem->getLocation(), diag::err_hlsl_resource_range_overlap)
1488 << llvm::to_underlying(Reported.RC) << Reported.LowerBound
1489 << Reported.isUnbounded() << Reported.UpperBound
1490 << llvm::to_underlying(Previous.RC) << Previous.LowerBound
1491 << Previous.isUnbounded() << Previous.UpperBound << Reported.Space
1492 << CommonVis;
1493
1494 this->S->Diag(PrevElem->getLocation(),
1495 diag::note_hlsl_resource_range_here);
1496 };
1497
1498 for (BindingInfoBuilder &Builder : Builders)
1499 Builder.calculateBindingInfo(ReportOverlap);
1500
1501 return HadOverlap;
1502 }
1503};
1504
1505static CXXMethodDecl *lookupMethod(Sema &S, CXXRecordDecl *RecordDecl,
1506 StringRef Name, SourceLocation Loc) {
1507 DeclarationName DeclName(&S.getASTContext().Idents.get(Name));
1508 LookupResult Result(S, DeclName, Loc, Sema::LookupMemberName);
1509 if (!S.LookupQualifiedName(Result, static_cast<DeclContext *>(RecordDecl)))
1510 return nullptr;
1511 return cast<CXXMethodDecl>(Result.getFoundDecl());
1512}
1513
1514} // end anonymous namespace
1515
1518 // Define some common error handling functions
1519 bool HadError = false;
1520 auto ReportError = [this, &HadError](SourceLocation Loc, uint32_t LowerBound,
1521 uint32_t UpperBound) {
1522 HadError = true;
1523 this->Diag(Loc, diag::err_hlsl_invalid_rootsig_value)
1524 << LowerBound << UpperBound;
1525 };
1526
1527 auto ReportFloatError = [this, &HadError](SourceLocation Loc,
1528 float LowerBound,
1529 float UpperBound) {
1530 HadError = true;
1531 this->Diag(Loc, diag::err_hlsl_invalid_rootsig_value)
1532 << llvm::formatv("{0:f}", LowerBound).sstr<6>()
1533 << llvm::formatv("{0:f}", UpperBound).sstr<6>();
1534 };
1535
1536 auto VerifyRegister = [ReportError](SourceLocation Loc, uint32_t Register) {
1537 if (!llvm::hlsl::rootsig::verifyRegisterValue(Register))
1538 ReportError(Loc, 0, 0xfffffffe);
1539 };
1540
1541 auto VerifySpace = [ReportError](SourceLocation Loc, uint32_t Space) {
1542 if (!llvm::hlsl::rootsig::verifyRegisterSpace(Space))
1543 ReportError(Loc, 0, 0xffffffef);
1544 };
1545
1546 const uint32_t Version =
1547 llvm::to_underlying(SemaRef.getLangOpts().HLSLRootSigVer);
1548 const uint32_t VersionEnum = Version - 1;
1549 auto ReportFlagError = [this, &HadError, VersionEnum](SourceLocation Loc) {
1550 HadError = true;
1551 this->Diag(Loc, diag::err_hlsl_invalid_rootsig_flag)
1552 << /*version minor*/ VersionEnum;
1553 };
1554
1555 // Iterate through the elements and do basic validations
1556 for (const hlsl::RootSignatureElement &RootSigElem : Elements) {
1557 SourceLocation Loc = RootSigElem.getLocation();
1558 const llvm::hlsl::rootsig::RootElement &Elem = RootSigElem.getElement();
1559 if (const auto *Descriptor =
1560 std::get_if<llvm::hlsl::rootsig::RootDescriptor>(&Elem)) {
1561 VerifyRegister(Loc, Descriptor->Reg.Number);
1562 VerifySpace(Loc, Descriptor->Space);
1563
1564 if (!llvm::hlsl::rootsig::verifyRootDescriptorFlag(Version,
1565 Descriptor->Flags))
1566 ReportFlagError(Loc);
1567 } else if (const auto *Constants =
1568 std::get_if<llvm::hlsl::rootsig::RootConstants>(&Elem)) {
1569 VerifyRegister(Loc, Constants->Reg.Number);
1570 VerifySpace(Loc, Constants->Space);
1571 } else if (const auto *Sampler =
1572 std::get_if<llvm::hlsl::rootsig::StaticSampler>(&Elem)) {
1573 VerifyRegister(Loc, Sampler->Reg.Number);
1574 VerifySpace(Loc, Sampler->Space);
1575
1576 assert(!std::isnan(Sampler->MaxLOD) && !std::isnan(Sampler->MinLOD) &&
1577 "By construction, parseFloatParam can't produce a NaN from a "
1578 "float_literal token");
1579
1580 if (!llvm::hlsl::rootsig::verifyMaxAnisotropy(Sampler->MaxAnisotropy))
1581 ReportError(Loc, 0, 16);
1582 if (!llvm::hlsl::rootsig::verifyMipLODBias(Sampler->MipLODBias))
1583 ReportFloatError(Loc, -16.f, 15.99f);
1584 } else if (const auto *Clause =
1585 std::get_if<llvm::hlsl::rootsig::DescriptorTableClause>(
1586 &Elem)) {
1587 VerifyRegister(Loc, Clause->Reg.Number);
1588 VerifySpace(Loc, Clause->Space);
1589
1590 if (!llvm::hlsl::rootsig::verifyNumDescriptors(Clause->NumDescriptors)) {
1591 // NumDescriptor could techincally be ~0u but that is reserved for
1592 // unbounded, so the diagnostic will not report that as a valid int
1593 // value
1594 ReportError(Loc, 1, 0xfffffffe);
1595 }
1596
1597 if (!llvm::hlsl::rootsig::verifyDescriptorRangeFlag(Version, Clause->Type,
1598 Clause->Flags))
1599 ReportFlagError(Loc);
1600 }
1601 }
1602
1603 PerVisibilityBindingChecker BindingChecker(this);
1604 SmallVector<std::pair<const llvm::hlsl::rootsig::DescriptorTableClause *,
1606 UnboundClauses;
1607
1608 for (const hlsl::RootSignatureElement &RootSigElem : Elements) {
1609 const llvm::hlsl::rootsig::RootElement &Elem = RootSigElem.getElement();
1610 if (const auto *Descriptor =
1611 std::get_if<llvm::hlsl::rootsig::RootDescriptor>(&Elem)) {
1612 uint32_t LowerBound(Descriptor->Reg.Number);
1613 uint32_t UpperBound(LowerBound); // inclusive range
1614
1615 BindingChecker.trackBinding(
1616 Descriptor->Visibility,
1617 static_cast<llvm::dxil::ResourceClass>(Descriptor->Type),
1618 Descriptor->Space, LowerBound, UpperBound, &RootSigElem);
1619 } else if (const auto *Constants =
1620 std::get_if<llvm::hlsl::rootsig::RootConstants>(&Elem)) {
1621 uint32_t LowerBound(Constants->Reg.Number);
1622 uint32_t UpperBound(LowerBound); // inclusive range
1623
1624 BindingChecker.trackBinding(
1625 Constants->Visibility, llvm::dxil::ResourceClass::CBuffer,
1626 Constants->Space, LowerBound, UpperBound, &RootSigElem);
1627 } else if (const auto *Sampler =
1628 std::get_if<llvm::hlsl::rootsig::StaticSampler>(&Elem)) {
1629 uint32_t LowerBound(Sampler->Reg.Number);
1630 uint32_t UpperBound(LowerBound); // inclusive range
1631
1632 BindingChecker.trackBinding(
1633 Sampler->Visibility, llvm::dxil::ResourceClass::Sampler,
1634 Sampler->Space, LowerBound, UpperBound, &RootSigElem);
1635 } else if (const auto *Clause =
1636 std::get_if<llvm::hlsl::rootsig::DescriptorTableClause>(
1637 &Elem)) {
1638 // We'll process these once we see the table element.
1639 UnboundClauses.emplace_back(Clause, &RootSigElem);
1640 } else if (const auto *Table =
1641 std::get_if<llvm::hlsl::rootsig::DescriptorTable>(&Elem)) {
1642 assert(UnboundClauses.size() == Table->NumClauses &&
1643 "Number of unbound elements must match the number of clauses");
1644 bool HasAnySampler = false;
1645 bool HasAnyNonSampler = false;
1646 uint64_t Offset = 0;
1647 bool IsPrevUnbound = false;
1648 for (const auto &[Clause, ClauseElem] : UnboundClauses) {
1649 SourceLocation Loc = ClauseElem->getLocation();
1650 if (Clause->Type == llvm::dxil::ResourceClass::Sampler)
1651 HasAnySampler = true;
1652 else
1653 HasAnyNonSampler = true;
1654
1655 if (HasAnySampler && HasAnyNonSampler)
1656 Diag(Loc, diag::err_hlsl_invalid_mixed_resources);
1657
1658 // Relevant error will have already been reported above and needs to be
1659 // fixed before we can conduct further analysis, so shortcut error
1660 // return
1661 if (Clause->NumDescriptors == 0)
1662 return true;
1663
1664 bool IsAppending =
1665 Clause->Offset == llvm::hlsl::rootsig::DescriptorTableOffsetAppend;
1666 if (!IsAppending)
1667 Offset = Clause->Offset;
1668
1669 uint64_t RangeBound = llvm::hlsl::rootsig::computeRangeBound(
1670 Offset, Clause->NumDescriptors);
1671
1672 if (IsPrevUnbound && IsAppending)
1673 Diag(Loc, diag::err_hlsl_appending_onto_unbound);
1674 else if (!llvm::hlsl::rootsig::verifyNoOverflowedOffset(RangeBound))
1675 Diag(Loc, diag::err_hlsl_offset_overflow) << Offset << RangeBound;
1676
1677 // Update offset to be 1 past this range's bound
1678 Offset = RangeBound + 1;
1679 IsPrevUnbound = Clause->NumDescriptors ==
1680 llvm::hlsl::rootsig::NumDescriptorsUnbounded;
1681
1682 // Compute the register bounds and track resource binding
1683 uint32_t LowerBound(Clause->Reg.Number);
1684 uint32_t UpperBound = llvm::hlsl::rootsig::computeRangeBound(
1685 LowerBound, Clause->NumDescriptors);
1686
1687 BindingChecker.trackBinding(
1688 Table->Visibility,
1689 static_cast<llvm::dxil::ResourceClass>(Clause->Type), Clause->Space,
1690 LowerBound, UpperBound, ClauseElem);
1691 }
1692 UnboundClauses.clear();
1693 }
1694 }
1695
1696 return BindingChecker.checkOverlap();
1697}
1698
1700 if (AL.getNumArgs() != 1) {
1701 Diag(AL.getLoc(), diag::err_attribute_wrong_number_arguments) << AL << 1;
1702 return;
1703 }
1704
1706 if (auto *RS = D->getAttr<RootSignatureAttr>()) {
1707 if (RS->getSignatureIdent() != Ident) {
1708 Diag(AL.getLoc(), diag::err_disallowed_duplicate_attribute) << RS;
1709 return;
1710 }
1711
1712 Diag(AL.getLoc(), diag::warn_duplicate_attribute_exact) << RS;
1713 return;
1714 }
1715
1717 if (SemaRef.LookupQualifiedName(R, D->getDeclContext()))
1718 if (auto *SignatureDecl =
1719 dyn_cast<HLSLRootSignatureDecl>(R.getFoundDecl())) {
1720 D->addAttr(::new (getASTContext()) RootSignatureAttr(
1721 getASTContext(), AL, Ident, SignatureDecl));
1722 }
1723}
1724
1726 llvm::VersionTuple SMVersion =
1727 getASTContext().getTargetInfo().getTriple().getOSVersion();
1728 bool IsDXIL = getASTContext().getTargetInfo().getTriple().getArch() ==
1729 llvm::Triple::dxil;
1730
1731 uint32_t ZMax = 1024;
1732 uint32_t ThreadMax = 1024;
1733 if (IsDXIL && SMVersion.getMajor() <= 4) {
1734 ZMax = 1;
1735 ThreadMax = 768;
1736 } else if (IsDXIL && SMVersion.getMajor() == 5) {
1737 ZMax = 64;
1738 ThreadMax = 1024;
1739 }
1740
1741 uint32_t X;
1742 if (!SemaRef.checkUInt32Argument(AL, AL.getArgAsExpr(0), X))
1743 return;
1744 if (X > 1024) {
1745 Diag(AL.getArgAsExpr(0)->getExprLoc(),
1746 diag::err_hlsl_numthreads_argument_oor)
1747 << 0 << 1024;
1748 return;
1749 }
1750 uint32_t Y;
1751 if (!SemaRef.checkUInt32Argument(AL, AL.getArgAsExpr(1), Y))
1752 return;
1753 if (Y > 1024) {
1754 Diag(AL.getArgAsExpr(1)->getExprLoc(),
1755 diag::err_hlsl_numthreads_argument_oor)
1756 << 1 << 1024;
1757 return;
1758 }
1759 uint32_t Z;
1760 if (!SemaRef.checkUInt32Argument(AL, AL.getArgAsExpr(2), Z))
1761 return;
1762 if (Z > ZMax) {
1763 SemaRef.Diag(AL.getArgAsExpr(2)->getExprLoc(),
1764 diag::err_hlsl_numthreads_argument_oor)
1765 << 2 << ZMax;
1766 return;
1767 }
1768
1769 if (X * Y * Z > ThreadMax) {
1770 Diag(AL.getLoc(), diag::err_hlsl_numthreads_invalid) << ThreadMax;
1771 return;
1772 }
1773
1774 HLSLNumThreadsAttr *NewAttr = mergeNumThreadsAttr(D, AL, X, Y, Z);
1775 if (NewAttr)
1776 D->addAttr(NewAttr);
1777}
1778
1779static bool isValidWaveSizeValue(unsigned Value) {
1780 return llvm::isPowerOf2_32(Value) && Value >= 4 && Value <= 128;
1781}
1782
1784 // validate that the wavesize argument is a power of 2 between 4 and 128
1785 // inclusive
1786 unsigned SpelledArgsCount = AL.getNumArgs();
1787 if (SpelledArgsCount == 0 || SpelledArgsCount > 3)
1788 return;
1789
1790 uint32_t Min;
1791 if (!SemaRef.checkUInt32Argument(AL, AL.getArgAsExpr(0), Min))
1792 return;
1793
1794 uint32_t Max = 0;
1795 if (SpelledArgsCount > 1 &&
1796 !SemaRef.checkUInt32Argument(AL, AL.getArgAsExpr(1), Max))
1797 return;
1798
1799 uint32_t Preferred = 0;
1800 if (SpelledArgsCount > 2 &&
1801 !SemaRef.checkUInt32Argument(AL, AL.getArgAsExpr(2), Preferred))
1802 return;
1803
1804 if (SpelledArgsCount > 2) {
1805 if (!isValidWaveSizeValue(Preferred)) {
1806 Diag(AL.getArgAsExpr(2)->getExprLoc(),
1807 diag::err_attribute_power_of_two_in_range)
1808 << AL << llvm::dxil::MinWaveSize << llvm::dxil::MaxWaveSize
1809 << Preferred;
1810 return;
1811 }
1812 // Preferred not in range.
1813 if (Preferred < Min || Preferred > Max) {
1814 Diag(AL.getArgAsExpr(2)->getExprLoc(),
1815 diag::err_attribute_power_of_two_in_range)
1816 << AL << Min << Max << Preferred;
1817 return;
1818 }
1819 } else if (SpelledArgsCount > 1) {
1820 if (!isValidWaveSizeValue(Max)) {
1821 Diag(AL.getArgAsExpr(1)->getExprLoc(),
1822 diag::err_attribute_power_of_two_in_range)
1823 << AL << llvm::dxil::MinWaveSize << llvm::dxil::MaxWaveSize << Max;
1824 return;
1825 }
1826 if (Max < Min) {
1827 Diag(AL.getLoc(), diag::err_attribute_argument_invalid) << AL << 1;
1828 return;
1829 } else if (Max == Min) {
1830 Diag(AL.getLoc(), diag::warn_attr_min_eq_max) << AL;
1831 }
1832 } else {
1833 if (!isValidWaveSizeValue(Min)) {
1834 Diag(AL.getArgAsExpr(0)->getExprLoc(),
1835 diag::err_attribute_power_of_two_in_range)
1836 << AL << llvm::dxil::MinWaveSize << llvm::dxil::MaxWaveSize << Min;
1837 return;
1838 }
1839 }
1840
1841 HLSLWaveSizeAttr *NewAttr =
1842 mergeWaveSizeAttr(D, AL, Min, Max, Preferred, SpelledArgsCount);
1843 if (NewAttr)
1844 D->addAttr(NewAttr);
1845}
1846
1848 uint32_t ID;
1849 if (!SemaRef.checkUInt32Argument(AL, AL.getArgAsExpr(0), ID))
1850 return;
1851 D->addAttr(::new (getASTContext())
1852 HLSLVkExtBuiltinInputAttr(getASTContext(), AL, ID));
1853}
1854
1856 uint32_t ID;
1857 if (!SemaRef.checkUInt32Argument(AL, AL.getArgAsExpr(0), ID))
1858 return;
1859 D->addAttr(::new (getASTContext())
1860 HLSLVkExtBuiltinOutputAttr(getASTContext(), AL, ID));
1861}
1862
1864 D->addAttr(::new (getASTContext())
1865 HLSLVkPushConstantAttr(getASTContext(), AL));
1866}
1867
1869 uint32_t Id;
1870 if (!SemaRef.checkUInt32Argument(AL, AL.getArgAsExpr(0), Id))
1871 return;
1872 HLSLVkConstantIdAttr *NewAttr = mergeVkConstantIdAttr(D, AL, Id);
1873 if (NewAttr)
1874 D->addAttr(NewAttr);
1875}
1876
1878 uint32_t Binding = 0;
1879 if (!SemaRef.checkUInt32Argument(AL, AL.getArgAsExpr(0), Binding))
1880 return;
1881 uint32_t Set = 0;
1882 if (AL.getNumArgs() > 1 &&
1883 !SemaRef.checkUInt32Argument(AL, AL.getArgAsExpr(1), Set))
1884 return;
1885
1886 D->addAttr(::new (getASTContext())
1887 HLSLVkBindingAttr(getASTContext(), AL, Binding, Set));
1888}
1889
1891 uint32_t Location;
1892 if (!SemaRef.checkUInt32Argument(AL, AL.getArgAsExpr(0), Location))
1893 return;
1894
1895 D->addAttr(::new (getASTContext())
1896 HLSLVkLocationAttr(getASTContext(), AL, Location));
1897}
1898
1900 const auto *VT = T->getAs<VectorType>();
1901
1902 if (!T->hasUnsignedIntegerRepresentation() ||
1903 (VT && VT->getNumElements() > 3)) {
1904 Diag(AL.getLoc(), diag::err_hlsl_attr_invalid_type)
1905 << AL << "uint/uint2/uint3";
1906 return false;
1907 }
1908
1909 return true;
1910}
1911
1913 const auto *VT = T->getAs<VectorType>();
1914 if (!T->hasFloatingRepresentation() || (VT && VT->getNumElements() > 4)) {
1915 Diag(AL.getLoc(), diag::err_hlsl_attr_invalid_type)
1916 << AL << "float/float1/float2/float3/float4";
1917 return false;
1918 }
1919
1920 return true;
1921}
1922
1924 std::optional<unsigned> Index) {
1925 std::string SemanticName = AL.getAttrName()->getName().upper();
1926
1927 auto *VD = cast<ValueDecl>(D);
1928 QualType ValueType = VD->getType();
1929 if (auto *FD = dyn_cast<FunctionDecl>(D))
1930 ValueType = FD->getReturnType();
1931
1932 bool IsOutput = false;
1933 if (HLSLParamModifierAttr *MA = D->getAttr<HLSLParamModifierAttr>()) {
1934 if (MA->isOut()) {
1935 IsOutput = true;
1936 ValueType = cast<ReferenceType>(ValueType)->getPointeeType();
1937 }
1938 }
1939
1940 if (SemanticName == "SV_DISPATCHTHREADID") {
1941 diagnoseInputIDType(ValueType, AL);
1942 if (IsOutput)
1943 Diag(AL.getLoc(), diag::err_hlsl_semantic_output_not_supported) << AL;
1944 if (Index.has_value())
1945 Diag(AL.getLoc(), diag::err_hlsl_semantic_indexing_not_supported) << AL;
1947 return;
1948 }
1949
1950 if (SemanticName == "SV_GROUPINDEX") {
1951 if (IsOutput)
1952 Diag(AL.getLoc(), diag::err_hlsl_semantic_output_not_supported) << AL;
1953 if (Index.has_value())
1954 Diag(AL.getLoc(), diag::err_hlsl_semantic_indexing_not_supported) << AL;
1956 return;
1957 }
1958
1959 if (SemanticName == "SV_GROUPTHREADID") {
1960 diagnoseInputIDType(ValueType, AL);
1961 if (IsOutput)
1962 Diag(AL.getLoc(), diag::err_hlsl_semantic_output_not_supported) << AL;
1963 if (Index.has_value())
1964 Diag(AL.getLoc(), diag::err_hlsl_semantic_indexing_not_supported) << AL;
1966 return;
1967 }
1968
1969 if (SemanticName == "SV_GROUPID") {
1970 diagnoseInputIDType(ValueType, AL);
1971 if (IsOutput)
1972 Diag(AL.getLoc(), diag::err_hlsl_semantic_output_not_supported) << AL;
1973 if (Index.has_value())
1974 Diag(AL.getLoc(), diag::err_hlsl_semantic_indexing_not_supported) << AL;
1976 return;
1977 }
1978
1979 if (SemanticName == "SV_POSITION") {
1980 const auto *VT = ValueType->getAs<VectorType>();
1981 if (!ValueType->hasFloatingRepresentation() ||
1982 (VT && VT->getNumElements() > 4))
1983 Diag(AL.getLoc(), diag::err_hlsl_attr_invalid_type)
1984 << AL << "float/float1/float2/float3/float4";
1986 return;
1987 }
1988
1989 if (SemanticName == "SV_VERTEXID") {
1990 uint64_t SizeInBits = SemaRef.Context.getTypeSize(ValueType);
1991 if (!ValueType->isUnsignedIntegerType() || SizeInBits != 32)
1992 Diag(AL.getLoc(), diag::err_hlsl_attr_invalid_type) << AL << "uint";
1994 return;
1995 }
1996
1997 if (SemanticName == "SV_TARGET") {
1998 const auto *VT = ValueType->getAs<VectorType>();
1999 if (!ValueType->hasFloatingRepresentation() ||
2000 (VT && VT->getNumElements() > 4))
2001 Diag(AL.getLoc(), diag::err_hlsl_attr_invalid_type)
2002 << AL << "float/float1/float2/float3/float4";
2004 return;
2005 }
2006
2007 Diag(AL.getLoc(), diag::err_hlsl_unknown_semantic) << AL;
2008}
2009
2011 uint32_t IndexValue(0), ExplicitIndex(0);
2012 if (!SemaRef.checkUInt32Argument(AL, AL.getArgAsExpr(0), IndexValue) ||
2013 !SemaRef.checkUInt32Argument(AL, AL.getArgAsExpr(1), ExplicitIndex)) {
2014 assert(0 && "HLSLUnparsedSemantic is expected to have 2 int arguments.");
2015 }
2016 assert(IndexValue > 0 ? ExplicitIndex : true);
2017 std::optional<unsigned> Index =
2018 ExplicitIndex ? std::optional<unsigned>(IndexValue) : std::nullopt;
2019
2020 if (AL.getAttrName()->getName().starts_with_insensitive("SV_"))
2021 diagnoseSystemSemanticAttr(D, AL, Index);
2022 else
2024}
2025
2028 Diag(AL.getLoc(), diag::err_hlsl_attr_invalid_ast_node)
2029 << AL << "shader constant in a constant buffer";
2030 return;
2031 }
2032
2033 uint32_t SubComponent;
2034 if (!SemaRef.checkUInt32Argument(AL, AL.getArgAsExpr(0), SubComponent))
2035 return;
2036 uint32_t Component;
2037 if (!SemaRef.checkUInt32Argument(AL, AL.getArgAsExpr(1), Component))
2038 return;
2039
2040 QualType T = cast<VarDecl>(D)->getType().getCanonicalType();
2041 // Check if T is an array or struct type.
2042 // TODO: mark matrix type as aggregate type.
2043 bool IsAggregateTy = (T->isArrayType() || T->isStructureType());
2044
2045 // Check Component is valid for T.
2046 if (Component) {
2047 unsigned Size = getASTContext().getTypeSize(T);
2048 if (IsAggregateTy) {
2049 Diag(AL.getLoc(), diag::err_hlsl_invalid_register_or_packoffset);
2050 return;
2051 } else {
2052 // Make sure Component + sizeof(T) <= 4.
2053 if ((Component * 32 + Size) > 128) {
2054 Diag(AL.getLoc(), diag::err_hlsl_packoffset_cross_reg_boundary);
2055 return;
2056 }
2057 QualType EltTy = T;
2058 if (const auto *VT = T->getAs<VectorType>())
2059 EltTy = VT->getElementType();
2060 unsigned Align = getASTContext().getTypeAlign(EltTy);
2061 if (Align > 32 && Component == 1) {
2062 // NOTE: Component 3 will hit err_hlsl_packoffset_cross_reg_boundary.
2063 // So we only need to check Component 1 here.
2064 Diag(AL.getLoc(), diag::err_hlsl_packoffset_alignment_mismatch)
2065 << Align << EltTy;
2066 return;
2067 }
2068 }
2069 }
2070
2071 D->addAttr(::new (getASTContext()) HLSLPackOffsetAttr(
2072 getASTContext(), AL, SubComponent, Component));
2073}
2074
2076 StringRef Str;
2077 SourceLocation ArgLoc;
2078 if (!SemaRef.checkStringLiteralArgumentAttr(AL, 0, Str, &ArgLoc))
2079 return;
2080
2081 llvm::Triple::EnvironmentType ShaderType;
2082 if (!HLSLShaderAttr::ConvertStrToEnvironmentType(Str, ShaderType)) {
2083 Diag(AL.getLoc(), diag::warn_attribute_type_not_supported)
2084 << AL << Str << ArgLoc;
2085 return;
2086 }
2087
2088 // FIXME: check function match the shader stage.
2089
2090 HLSLShaderAttr *NewAttr = mergeShaderAttr(D, AL, ShaderType);
2091 if (NewAttr)
2092 D->addAttr(NewAttr);
2093}
2094
2096 Sema &S, QualType Wrapped, ArrayRef<const Attr *> AttrList,
2097 QualType &ResType, HLSLAttributedResourceLocInfo *LocInfo) {
2098 assert(AttrList.size() && "expected list of resource attributes");
2099
2100 QualType ContainedTy = QualType();
2101 TypeSourceInfo *ContainedTyInfo = nullptr;
2102 SourceLocation LocBegin = AttrList[0]->getRange().getBegin();
2103 SourceLocation LocEnd = AttrList[0]->getRange().getEnd();
2104
2105 HLSLAttributedResourceType::Attributes ResAttrs;
2106
2107 bool HasResourceClass = false;
2108 bool HasResourceDimension = false;
2109 for (const Attr *A : AttrList) {
2110 if (!A)
2111 continue;
2112 LocEnd = A->getRange().getEnd();
2113 switch (A->getKind()) {
2114 case attr::HLSLResourceClass: {
2115 ResourceClass RC = cast<HLSLResourceClassAttr>(A)->getResourceClass();
2116 if (HasResourceClass) {
2117 S.Diag(A->getLocation(), ResAttrs.ResourceClass == RC
2118 ? diag::warn_duplicate_attribute_exact
2119 : diag::warn_duplicate_attribute)
2120 << A;
2121 return false;
2122 }
2123 ResAttrs.ResourceClass = RC;
2124 HasResourceClass = true;
2125 break;
2126 }
2127 case attr::HLSLResourceDimension: {
2128 llvm::dxil::ResourceDimension RD =
2129 cast<HLSLResourceDimensionAttr>(A)->getDimension();
2130 if (HasResourceDimension) {
2131 S.Diag(A->getLocation(), ResAttrs.ResourceDimension == RD
2132 ? diag::warn_duplicate_attribute_exact
2133 : diag::warn_duplicate_attribute)
2134 << A;
2135 return false;
2136 }
2137 ResAttrs.ResourceDimension = RD;
2138 HasResourceDimension = true;
2139 break;
2140 }
2141 case attr::HLSLROV:
2142 if (ResAttrs.IsROV) {
2143 S.Diag(A->getLocation(), diag::warn_duplicate_attribute_exact) << A;
2144 return false;
2145 }
2146 ResAttrs.IsROV = true;
2147 break;
2148 case attr::HLSLRawBuffer:
2149 if (ResAttrs.RawBuffer) {
2150 S.Diag(A->getLocation(), diag::warn_duplicate_attribute_exact) << A;
2151 return false;
2152 }
2153 ResAttrs.RawBuffer = true;
2154 break;
2155 case attr::HLSLIsArray:
2156 if (ResAttrs.IsArray) {
2157 S.Diag(A->getLocation(), diag::warn_duplicate_attribute_exact) << A;
2158 return false;
2159 }
2160 ResAttrs.IsArray = true;
2161 break;
2162 case attr::HLSLIsCounter:
2163 if (ResAttrs.IsCounter) {
2164 S.Diag(A->getLocation(), diag::warn_duplicate_attribute_exact) << A;
2165 return false;
2166 }
2167 ResAttrs.IsCounter = true;
2168 break;
2169 case attr::HLSLContainedType: {
2170 const HLSLContainedTypeAttr *CTAttr = cast<HLSLContainedTypeAttr>(A);
2171 QualType Ty = CTAttr->getType();
2172 if (!ContainedTy.isNull()) {
2173 S.Diag(A->getLocation(), ContainedTy == Ty
2174 ? diag::warn_duplicate_attribute_exact
2175 : diag::warn_duplicate_attribute)
2176 << A;
2177 return false;
2178 }
2179 ContainedTy = Ty;
2180 ContainedTyInfo = CTAttr->getTypeLoc();
2181 break;
2182 }
2183 default:
2184 llvm_unreachable("unhandled resource attribute type");
2185 }
2186 }
2187
2188 if (!HasResourceClass) {
2189 S.Diag(AttrList.back()->getRange().getEnd(),
2190 diag::err_hlsl_missing_resource_class);
2191 return false;
2192 }
2193
2195 Wrapped, ContainedTy, ResAttrs);
2196
2197 if (LocInfo && ContainedTyInfo) {
2198 LocInfo->Range = SourceRange(LocBegin, LocEnd);
2199 LocInfo->ContainedTyInfo = ContainedTyInfo;
2200 }
2201 return true;
2202}
2203
2204// Validates and creates an HLSL attribute that is applied as type attribute on
2205// HLSL resource. The attributes are collected in HLSLResourcesTypeAttrs and at
2206// the end of the declaration they are applied to the declaration type by
2207// wrapping it in HLSLAttributedResourceType.
2209 // only allow resource type attributes on intangible types
2210 if (!T->isHLSLResourceType()) {
2211 Diag(AL.getLoc(), diag::err_hlsl_attribute_needs_intangible_type)
2212 << AL << getASTContext().HLSLResourceTy;
2213 return false;
2214 }
2215
2216 // validate number of arguments
2217 if (!AL.checkExactlyNumArgs(SemaRef, AL.getMinArgs()))
2218 return false;
2219
2220 Attr *A = nullptr;
2221
2225 {
2226 AttributeCommonInfo::AS_CXX11, 0, false /*IsAlignas*/,
2227 false /*IsRegularKeywordAttribute*/
2228 });
2229
2230 switch (AL.getKind()) {
2231 case ParsedAttr::AT_HLSLResourceClass: {
2232 if (!AL.isArgIdent(0)) {
2233 Diag(AL.getLoc(), diag::err_attribute_argument_type)
2234 << AL << AANT_ArgumentIdentifier;
2235 return false;
2236 }
2237
2238 IdentifierLoc *Loc = AL.getArgAsIdent(0);
2239 StringRef Identifier = Loc->getIdentifierInfo()->getName();
2240 SourceLocation ArgLoc = Loc->getLoc();
2241
2242 // Validate resource class value
2243 ResourceClass RC;
2244 if (!HLSLResourceClassAttr::ConvertStrToResourceClass(Identifier, RC)) {
2245 Diag(ArgLoc, diag::warn_attribute_type_not_supported)
2246 << "ResourceClass" << Identifier;
2247 return false;
2248 }
2249 A = HLSLResourceClassAttr::Create(getASTContext(), RC, ACI);
2250 break;
2251 }
2252
2253 case ParsedAttr::AT_HLSLResourceDimension: {
2254 StringRef Identifier;
2255 SourceLocation ArgLoc;
2256 if (!SemaRef.checkStringLiteralArgumentAttr(AL, 0, Identifier, &ArgLoc))
2257 return false;
2258
2259 // Validate resource dimension value
2260 llvm::dxil::ResourceDimension RD;
2261 if (!HLSLResourceDimensionAttr::ConvertStrToResourceDimension(Identifier,
2262 RD)) {
2263 Diag(ArgLoc, diag::warn_attribute_type_not_supported)
2264 << "ResourceDimension" << Identifier;
2265 return false;
2266 }
2267 A = HLSLResourceDimensionAttr::Create(getASTContext(), RD, ACI);
2268 break;
2269 }
2270
2271 case ParsedAttr::AT_HLSLROV:
2272 A = HLSLROVAttr::Create(getASTContext(), ACI);
2273 break;
2274
2275 case ParsedAttr::AT_HLSLRawBuffer:
2276 A = HLSLRawBufferAttr::Create(getASTContext(), ACI);
2277 break;
2278
2279 case ParsedAttr::AT_HLSLIsCounter:
2280 A = HLSLIsCounterAttr::Create(getASTContext(), ACI);
2281 break;
2282
2283 case ParsedAttr::AT_HLSLIsArray:
2284 A = HLSLIsArrayAttr::Create(getASTContext(), ACI);
2285 break;
2286
2287 case ParsedAttr::AT_HLSLContainedType: {
2288 if (AL.getNumArgs() != 1 && !AL.hasParsedType()) {
2289 Diag(AL.getLoc(), diag::err_attribute_wrong_number_arguments) << AL << 1;
2290 return false;
2291 }
2292
2293 TypeSourceInfo *TSI = nullptr;
2294 QualType QT = SemaRef.GetTypeFromParser(AL.getTypeArg(), &TSI);
2295 assert(TSI && "no type source info for attribute argument");
2296 if (SemaRef.RequireCompleteType(TSI->getTypeLoc().getBeginLoc(), QT,
2297 diag::err_incomplete_type))
2298 return false;
2299 A = HLSLContainedTypeAttr::Create(getASTContext(), TSI, ACI);
2300 break;
2301 }
2302
2303 default:
2304 llvm_unreachable("unhandled HLSL attribute");
2305 }
2306
2307 HLSLResourcesTypeAttrs.emplace_back(A);
2308 return true;
2309}
2310
2311// Combines all resource type attributes and creates HLSLAttributedResourceType.
2313 if (!HLSLResourcesTypeAttrs.size())
2314 return CurrentType;
2315
2316 QualType QT = CurrentType;
2319 HLSLResourcesTypeAttrs, QT, &LocInfo)) {
2320 const HLSLAttributedResourceType *RT =
2322
2323 // Temporarily store TypeLoc information for the new type.
2324 // It will be transferred to HLSLAttributesResourceTypeLoc
2325 // shortly after the type is created by TypeSpecLocFiller which
2326 // will call the TakeLocForHLSLAttribute method below.
2327 LocsForHLSLAttributedResources.insert(std::pair(RT, LocInfo));
2328 }
2329 HLSLResourcesTypeAttrs.clear();
2330 return QT;
2331}
2332
2333// Returns source location for the HLSLAttributedResourceType
2335SemaHLSL::TakeLocForHLSLAttribute(const HLSLAttributedResourceType *RT) {
2336 HLSLAttributedResourceLocInfo LocInfo = {};
2337 auto I = LocsForHLSLAttributedResources.find(RT);
2338 if (I != LocsForHLSLAttributedResources.end()) {
2339 LocInfo = I->second;
2340 LocsForHLSLAttributedResources.erase(I);
2341 return LocInfo;
2342 }
2343 LocInfo.Range = SourceRange();
2344 return LocInfo;
2345}
2346
2347// Walks though the global variable declaration, collects all resource binding
2348// requirements and adds them to Bindings
2349void SemaHLSL::collectResourceBindingsOnUserRecordDecl(const VarDecl *VD,
2350 const RecordType *RT) {
2351 const RecordDecl *RD = RT->getDecl()->getDefinitionOrSelf();
2352 for (FieldDecl *FD : RD->fields()) {
2353 const Type *Ty = FD->getType()->getUnqualifiedDesugaredType();
2354
2355 // Unwrap arrays
2356 // FIXME: Calculate array size while unwrapping
2357 assert(!Ty->isIncompleteArrayType() &&
2358 "incomplete arrays inside user defined types are not supported");
2359 while (Ty->isConstantArrayType()) {
2362 }
2363
2364 if (!Ty->isRecordType())
2365 continue;
2366
2367 if (const HLSLAttributedResourceType *AttrResType =
2368 HLSLAttributedResourceType::findHandleTypeOnResource(Ty)) {
2369 // Add a new DeclBindingInfo to Bindings if it does not already exist
2370 ResourceClass RC = AttrResType->getAttrs().ResourceClass;
2371 DeclBindingInfo *DBI = Bindings.getDeclBindingInfo(VD, RC);
2372 if (!DBI)
2373 Bindings.addDeclBindingInfo(VD, RC);
2374 } else if (const RecordType *RT = dyn_cast<RecordType>(Ty)) {
2375 // Recursively scan embedded struct or class; it would be nice to do this
2376 // without recursion, but tricky to correctly calculate the size of the
2377 // binding, which is something we are probably going to need to do later
2378 // on. Hopefully nesting of structs in structs too many levels is
2379 // unlikely.
2380 collectResourceBindingsOnUserRecordDecl(VD, RT);
2381 }
2382 }
2383}
2384
2385// Diagnose localized register binding errors for a single binding; does not
2386// diagnose resource binding on user record types, that will be done later
2387// in processResourceBindingOnDecl based on the information collected in
2388// collectResourceBindingsOnVarDecl.
2389// Returns false if the register binding is not valid.
2391 Decl *D, RegisterType RegType,
2392 bool SpecifiedSpace) {
2393 int RegTypeNum = static_cast<int>(RegType);
2394
2395 // check if the decl type is groupshared
2396 if (D->hasAttr<HLSLGroupSharedAddressSpaceAttr>()) {
2397 S.Diag(ArgLoc, diag::err_hlsl_binding_type_mismatch) << RegTypeNum;
2398 return false;
2399 }
2400
2401 // Cbuffers and Tbuffers are HLSLBufferDecl types
2402 if (HLSLBufferDecl *CBufferOrTBuffer = dyn_cast<HLSLBufferDecl>(D)) {
2403 ResourceClass RC = CBufferOrTBuffer->isCBuffer() ? ResourceClass::CBuffer
2404 : ResourceClass::SRV;
2405 if (RegType == getRegisterType(RC))
2406 return true;
2407
2408 S.Diag(D->getLocation(), diag::err_hlsl_binding_type_mismatch)
2409 << RegTypeNum;
2410 return false;
2411 }
2412
2413 // Samplers, UAVs, and SRVs are VarDecl types
2414 assert(isa<VarDecl>(D) && "D is expected to be VarDecl or HLSLBufferDecl");
2415 VarDecl *VD = cast<VarDecl>(D);
2416
2417 // Resource
2418 if (const HLSLAttributedResourceType *AttrResType =
2419 HLSLAttributedResourceType::findHandleTypeOnResource(
2420 VD->getType().getTypePtr())) {
2421 if (RegType == getRegisterType(AttrResType))
2422 return true;
2423
2424 S.Diag(D->getLocation(), diag::err_hlsl_binding_type_mismatch)
2425 << RegTypeNum;
2426 return false;
2427 }
2428
2429 const clang::Type *Ty = VD->getType().getTypePtr();
2430 while (Ty->isArrayType())
2432
2433 // Basic types
2434 if (Ty->isArithmeticType() || Ty->isVectorType()) {
2435 bool DeclaredInCOrTBuffer = isa<HLSLBufferDecl>(D->getDeclContext());
2436 if (SpecifiedSpace && !DeclaredInCOrTBuffer)
2437 S.Diag(ArgLoc, diag::err_hlsl_space_on_global_constant);
2438
2439 if (!DeclaredInCOrTBuffer && (Ty->isIntegralType(S.getASTContext()) ||
2440 Ty->isFloatingType() || Ty->isVectorType())) {
2441 // Register annotation on default constant buffer declaration ($Globals)
2442 if (RegType == RegisterType::CBuffer)
2443 S.Diag(ArgLoc, diag::warn_hlsl_deprecated_register_type_b);
2444 else if (RegType != RegisterType::C)
2445 S.Diag(ArgLoc, diag::err_hlsl_binding_type_mismatch) << RegTypeNum;
2446 else
2447 return true;
2448 } else {
2449 if (RegType == RegisterType::C)
2450 S.Diag(ArgLoc, diag::warn_hlsl_register_type_c_packoffset);
2451 else
2452 S.Diag(ArgLoc, diag::err_hlsl_binding_type_mismatch) << RegTypeNum;
2453 }
2454 return false;
2455 }
2456 if (Ty->isRecordType())
2457 // RecordTypes will be diagnosed in processResourceBindingOnDecl
2458 // that is called from ActOnVariableDeclarator
2459 return true;
2460
2461 // Anything else is an error
2462 S.Diag(ArgLoc, diag::err_hlsl_binding_type_mismatch) << RegTypeNum;
2463 return false;
2464}
2465
2467 RegisterType regType) {
2468 // make sure that there are no two register annotations
2469 // applied to the decl with the same register type
2470 bool RegisterTypesDetected[5] = {false};
2471 RegisterTypesDetected[static_cast<int>(regType)] = true;
2472
2473 for (auto it = TheDecl->attr_begin(); it != TheDecl->attr_end(); ++it) {
2474 if (HLSLResourceBindingAttr *attr =
2475 dyn_cast<HLSLResourceBindingAttr>(*it)) {
2476
2477 RegisterType otherRegType = attr->getRegisterType();
2478 if (RegisterTypesDetected[static_cast<int>(otherRegType)]) {
2479 int otherRegTypeNum = static_cast<int>(otherRegType);
2480 S.Diag(TheDecl->getLocation(),
2481 diag::err_hlsl_duplicate_register_annotation)
2482 << otherRegTypeNum;
2483 return false;
2484 }
2485 RegisterTypesDetected[static_cast<int>(otherRegType)] = true;
2486 }
2487 }
2488 return true;
2489}
2490
2492 Decl *D, RegisterType RegType,
2493 bool SpecifiedSpace) {
2494
2495 // exactly one of these two types should be set
2496 assert(((isa<VarDecl>(D) && !isa<HLSLBufferDecl>(D)) ||
2497 (!isa<VarDecl>(D) && isa<HLSLBufferDecl>(D))) &&
2498 "expecting VarDecl or HLSLBufferDecl");
2499
2500 // check if the declaration contains resource matching the register type
2501 if (!DiagnoseLocalRegisterBinding(S, ArgLoc, D, RegType, SpecifiedSpace))
2502 return false;
2503
2504 // next, if multiple register annotations exist, check that none conflict.
2505 return ValidateMultipleRegisterAnnotations(S, D, RegType);
2506}
2507
2508// return false if the slot count exceeds the limit, true otherwise
2509static bool AccumulateHLSLResourceSlots(QualType Ty, uint64_t &StartSlot,
2510 const uint64_t &Limit,
2511 const ResourceClass ResClass,
2512 ASTContext &Ctx,
2513 uint64_t ArrayCount = 1) {
2514 Ty = Ty.getCanonicalType();
2515 const Type *T = Ty.getTypePtr();
2516
2517 // Early exit if already overflowed
2518 if (StartSlot > Limit)
2519 return false;
2520
2521 // Case 1: array type
2522 if (const auto *AT = dyn_cast<ArrayType>(T)) {
2523 uint64_t Count = 1;
2524
2525 if (const auto *CAT = dyn_cast<ConstantArrayType>(AT))
2526 Count = CAT->getSize().getZExtValue();
2527
2528 QualType ElemTy = AT->getElementType();
2529 return AccumulateHLSLResourceSlots(ElemTy, StartSlot, Limit, ResClass, Ctx,
2530 ArrayCount * Count);
2531 }
2532
2533 // Case 2: resource leaf
2534 if (auto ResTy = dyn_cast<HLSLAttributedResourceType>(T)) {
2535 // First ensure this resource counts towards the corresponding
2536 // register type limit.
2537 if (ResTy->getAttrs().ResourceClass != ResClass)
2538 return true;
2539
2540 // Validate highest slot used
2541 uint64_t EndSlot = StartSlot + ArrayCount - 1;
2542 if (EndSlot > Limit)
2543 return false;
2544
2545 // Advance SlotCount past the consumed range
2546 StartSlot = EndSlot + 1;
2547 return true;
2548 }
2549
2550 // Case 3: struct / record
2551 if (const auto *RT = dyn_cast<RecordType>(T)) {
2552 const RecordDecl *RD = RT->getDecl();
2553
2554 if (const auto *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
2555 for (const CXXBaseSpecifier &Base : CXXRD->bases()) {
2556 if (!AccumulateHLSLResourceSlots(Base.getType(), StartSlot, Limit,
2557 ResClass, Ctx, ArrayCount))
2558 return false;
2559 }
2560 }
2561
2562 for (const FieldDecl *Field : RD->fields()) {
2563 if (!AccumulateHLSLResourceSlots(Field->getType(), StartSlot, Limit,
2564 ResClass, Ctx, ArrayCount))
2565 return false;
2566 }
2567
2568 return true;
2569 }
2570
2571 // Case 4: everything else
2572 return true;
2573}
2574
2575// return true if there is something invalid, false otherwise
2576static bool ValidateRegisterNumber(uint64_t SlotNum, Decl *TheDecl,
2577 ASTContext &Ctx, RegisterType RegTy) {
2578 const uint64_t Limit = UINT32_MAX;
2579 if (SlotNum > Limit)
2580 return true;
2581
2582 // after verifying the number doesn't exceed uint32max, we don't need
2583 // to look further into c or i register types
2584 if (RegTy == RegisterType::C || RegTy == RegisterType::I)
2585 return false;
2586
2587 if (VarDecl *VD = dyn_cast<VarDecl>(TheDecl)) {
2588 uint64_t BaseSlot = SlotNum;
2589
2590 if (!AccumulateHLSLResourceSlots(VD->getType(), SlotNum, Limit,
2591 getResourceClass(RegTy), Ctx))
2592 return true;
2593
2594 // After AccumulateHLSLResourceSlots runs, SlotNum is now
2595 // the first free slot; last used was SlotNum - 1
2596 return (BaseSlot > Limit);
2597 }
2598 // handle the cbuffer/tbuffer case
2599 if (isa<HLSLBufferDecl>(TheDecl))
2600 // resources cannot be put within a cbuffer, so no need
2601 // to analyze the structure since the register number
2602 // won't be pushed any higher.
2603 return (SlotNum > Limit);
2604
2605 // we don't expect any other decl type, so fail
2606 llvm_unreachable("unexpected decl type");
2607}
2608
2610 if (VarDecl *VD = dyn_cast<VarDecl>(TheDecl)) {
2611 QualType Ty = VD->getType();
2612 if (const auto *IAT = dyn_cast<IncompleteArrayType>(Ty))
2613 Ty = IAT->getElementType();
2614 if (SemaRef.RequireCompleteType(TheDecl->getBeginLoc(), Ty,
2615 diag::err_incomplete_type))
2616 return;
2617 }
2618
2619 StringRef Slot = "";
2620 StringRef Space = "";
2621 SourceLocation SlotLoc, SpaceLoc;
2622
2623 if (!AL.isArgIdent(0)) {
2624 Diag(AL.getLoc(), diag::err_attribute_argument_type)
2625 << AL << AANT_ArgumentIdentifier;
2626 return;
2627 }
2628 IdentifierLoc *Loc = AL.getArgAsIdent(0);
2629
2630 if (AL.getNumArgs() == 2) {
2631 Slot = Loc->getIdentifierInfo()->getName();
2632 SlotLoc = Loc->getLoc();
2633 if (!AL.isArgIdent(1)) {
2634 Diag(AL.getLoc(), diag::err_attribute_argument_type)
2635 << AL << AANT_ArgumentIdentifier;
2636 return;
2637 }
2638 Loc = AL.getArgAsIdent(1);
2639 Space = Loc->getIdentifierInfo()->getName();
2640 SpaceLoc = Loc->getLoc();
2641 } else {
2642 StringRef Str = Loc->getIdentifierInfo()->getName();
2643 if (Str.starts_with("space")) {
2644 Space = Str;
2645 SpaceLoc = Loc->getLoc();
2646 } else {
2647 Slot = Str;
2648 SlotLoc = Loc->getLoc();
2649 Space = "space0";
2650 }
2651 }
2652
2653 RegisterType RegType = RegisterType::SRV;
2654 std::optional<unsigned> SlotNum;
2655 unsigned SpaceNum = 0;
2656
2657 // Validate slot
2658 if (!Slot.empty()) {
2659 if (!convertToRegisterType(Slot, &RegType)) {
2660 Diag(SlotLoc, diag::err_hlsl_binding_type_invalid) << Slot.substr(0, 1);
2661 return;
2662 }
2663 if (RegType == RegisterType::I) {
2664 Diag(SlotLoc, diag::warn_hlsl_deprecated_register_type_i);
2665 return;
2666 }
2667 const StringRef SlotNumStr = Slot.substr(1);
2668
2669 uint64_t N;
2670
2671 // validate that the slot number is a non-empty number
2672 if (SlotNumStr.getAsInteger(10, N)) {
2673 Diag(SlotLoc, diag::err_hlsl_unsupported_register_number);
2674 return;
2675 }
2676
2677 // Validate register number. It should not exceed UINT32_MAX,
2678 // including if the resource type is an array that starts
2679 // before UINT32_MAX, but ends afterwards.
2680 if (ValidateRegisterNumber(N, TheDecl, getASTContext(), RegType)) {
2681 Diag(SlotLoc, diag::err_hlsl_register_number_too_large);
2682 return;
2683 }
2684
2685 // the slot number has been validated and does not exceed UINT32_MAX
2686 SlotNum = (unsigned)N;
2687 }
2688
2689 // Validate space
2690 if (!Space.starts_with("space")) {
2691 Diag(SpaceLoc, diag::err_hlsl_expected_space) << Space;
2692 return;
2693 }
2694 StringRef SpaceNumStr = Space.substr(5);
2695 if (SpaceNumStr.getAsInteger(10, SpaceNum)) {
2696 Diag(SpaceLoc, diag::err_hlsl_expected_space) << Space;
2697 return;
2698 }
2699
2700 // If we have slot, diagnose it is the right register type for the decl
2701 if (SlotNum.has_value())
2702 if (!DiagnoseHLSLRegisterAttribute(SemaRef, SlotLoc, TheDecl, RegType,
2703 !SpaceLoc.isInvalid()))
2704 return;
2705
2706 HLSLResourceBindingAttr *NewAttr =
2707 HLSLResourceBindingAttr::Create(getASTContext(), Slot, Space, AL);
2708 if (NewAttr) {
2709 NewAttr->setBinding(RegType, SlotNum, SpaceNum);
2710 TheDecl->addAttr(NewAttr);
2711 }
2712}
2713
2715 HLSLParamModifierAttr *NewAttr = mergeParamModifierAttr(
2716 D, AL,
2717 static_cast<HLSLParamModifierAttr::Spelling>(AL.getSemanticSpelling()));
2718 if (NewAttr)
2719 D->addAttr(NewAttr);
2720}
2721
2722static bool isMatrixOrArrayOfMatrix(const ASTContext &Ctx, QualType QT) {
2723 const Type *Ty = QT->getUnqualifiedDesugaredType();
2724 while (isa<ArrayType>(Ty))
2726 return Ty->isDependentType() || Ty->isConstantMatrixType();
2727}
2728
2729/// Walks the existing AttributedType sugar of \p T looking for a previously
2730/// applied HLSLRowMajor/HLSLColumnMajor marker. If one is found, populates
2731/// \p ExistingKind with its attr::Kind and returns true.
2733 attr::Kind &ExistingKind) {
2734 QualType Cur = T;
2735 while (const auto *AT = Cur->getAs<AttributedType>()) {
2736 attr::Kind K = AT->getAttrKind();
2737 if (K == attr::HLSLRowMajor || K == attr::HLSLColumnMajor) {
2738 ExistingKind = K;
2739 return true;
2740 }
2741 Cur = AT->getModifiedType();
2742 }
2743 return false;
2744}
2745
2747 if (T.isNull())
2748 return nullptr;
2749
2750 ASTContext &Ctx = getASTContext();
2751 attr::Kind AttrK = AL.getKind() == ParsedAttr::AT_HLSLRowMajor
2752 ? attr::HLSLRowMajor
2753 : attr::HLSLColumnMajor;
2754
2755 // For non-dependent types, the operand must be a matrix (or array of
2756 // matrices).
2757 if (!T->isDependentType() && !isMatrixOrArrayOfMatrix(Ctx, T)) {
2758 Diag(AL.getLoc(), diag::err_hlsl_matrix_layout_non_matrix)
2759 << AL.getAttrName();
2760 AL.setInvalid();
2761 return nullptr;
2762 }
2763
2764 // Conflict / duplicate detection by walking existing sugar.
2765 attr::Kind ExistingKind;
2766 if (findExistingMatrixLayoutMarker(T, ExistingKind)) {
2767 if (ExistingKind == AttrK) {
2768 Diag(AL.getLoc(), diag::warn_duplicate_attribute_exact)
2769 << AL.getAttrName();
2770 Diag(AL.getLoc(), diag::note_previous_attribute);
2771 return nullptr;
2772 }
2773 IdentifierInfo *ExistingII = &Ctx.Idents.get(
2774 ExistingKind == attr::HLSLRowMajor ? "row_major" : "column_major");
2775 Diag(AL.getLoc(), diag::err_hlsl_matrix_layout_conflict)
2776 << AL.getAttrName() << ExistingII;
2777 Diag(AL.getLoc(), diag::note_conflicting_attribute);
2778 AL.setInvalid();
2779 return nullptr;
2780 }
2781
2782 if (AttrK == attr::HLSLRowMajor)
2783 return ::new (Ctx) HLSLRowMajorAttr(Ctx, AL);
2784 return ::new (Ctx) HLSLColumnMajorAttr(Ctx, AL);
2785}
2786
2787// Re-validates an HLSL `row_major` / `column_major` attribute after template
2788// substitution. The parse-time check in `buildMatrixLayoutTypeAttr` is skipped
2789// for dependent types; `TransformAttributedType` calls this once the type is
2790// concrete. Returns `true` (and emits a diagnostic) if the substituted type is
2791// not a matrix or array of matrices, signaling the caller to abort the
2792// transform.
2794 SourceLocation Loc) {
2795 if (K != attr::HLSLRowMajor && K != attr::HLSLColumnMajor)
2796 return false;
2797 if (T.isNull() || T->isDependentType())
2798 return false;
2800 return false;
2802 K == attr::HLSLRowMajor ? "row_major" : "column_major");
2803 Diag(Loc, diag::err_hlsl_matrix_layout_non_matrix) << II;
2804 return true;
2805}
2806
2807namespace {
2808
2809/// This class implements HLSL availability diagnostics for default
2810/// and relaxed mode
2811///
2812/// The goal of this diagnostic is to emit an error or warning when an
2813/// unavailable API is found in code that is reachable from the shader
2814/// entry function or from an exported function (when compiling a shader
2815/// library).
2816///
2817/// This is done by traversing the AST of all shader entry point functions
2818/// and of all exported functions, and any functions that are referenced
2819/// from this AST. In other words, any functions that are reachable from
2820/// the entry points.
2821class DiagnoseHLSLAvailability : public DynamicRecursiveASTVisitor {
2822 Sema &SemaRef;
2823
2824 // Stack of functions to be scaned
2826
2827 // Tracks which environments functions have been scanned in.
2828 //
2829 // Maps FunctionDecl to an unsigned number that represents the set of shader
2830 // environments the function has been scanned for.
2831 // The llvm::Triple::EnvironmentType enum values for shader stages guaranteed
2832 // to be numbered from llvm::Triple::Pixel to llvm::Triple::Amplification
2833 // (verified by static_asserts in Triple.cpp), we can use it to index
2834 // individual bits in the set, as long as we shift the values to start with 0
2835 // by subtracting the value of llvm::Triple::Pixel first.
2836 //
2837 // The N'th bit in the set will be set if the function has been scanned
2838 // in shader environment whose llvm::Triple::EnvironmentType integer value
2839 // equals (llvm::Triple::Pixel + N).
2840 //
2841 // For example, if a function has been scanned in compute and pixel stage
2842 // environment, the value will be 0x21 (100001 binary) because:
2843 //
2844 // (int)(llvm::Triple::Pixel - llvm::Triple::Pixel) == 0
2845 // (int)(llvm::Triple::Compute - llvm::Triple::Pixel) == 5
2846 //
2847 // A FunctionDecl is mapped to 0 (or not included in the map) if it has not
2848 // been scanned in any environment.
2849 llvm::DenseMap<const FunctionDecl *, unsigned> ScannedDecls;
2850
2851 // Do not access these directly, use the get/set methods below to make
2852 // sure the values are in sync
2853 llvm::Triple::EnvironmentType CurrentShaderEnvironment;
2854 unsigned CurrentShaderStageBit;
2855
2856 // True if scanning a function that was already scanned in a different
2857 // shader stage context, and therefore we should not report issues that
2858 // depend only on shader model version because they would be duplicate.
2859 bool ReportOnlyShaderStageIssues;
2860
2861 // Helper methods for dealing with current stage context / environment
2862 void SetShaderStageContext(llvm::Triple::EnvironmentType ShaderType) {
2863 static_assert(sizeof(unsigned) >= 4);
2864 assert(HLSLShaderAttr::isValidShaderType(ShaderType));
2865 assert((unsigned)(ShaderType - llvm::Triple::Pixel) < 31 &&
2866 "ShaderType is too big for this bitmap"); // 31 is reserved for
2867 // "unknown"
2868
2869 unsigned bitmapIndex = ShaderType - llvm::Triple::Pixel;
2870 CurrentShaderEnvironment = ShaderType;
2871 CurrentShaderStageBit = (1 << bitmapIndex);
2872 }
2873
2874 void SetUnknownShaderStageContext() {
2875 CurrentShaderEnvironment = llvm::Triple::UnknownEnvironment;
2876 CurrentShaderStageBit = (1 << 31);
2877 }
2878
2879 llvm::Triple::EnvironmentType GetCurrentShaderEnvironment() const {
2880 return CurrentShaderEnvironment;
2881 }
2882
2883 bool InUnknownShaderStageContext() const {
2884 return CurrentShaderEnvironment == llvm::Triple::UnknownEnvironment;
2885 }
2886
2887 // Helper methods for dealing with shader stage bitmap
2888 void AddToScannedFunctions(const FunctionDecl *FD) {
2889 unsigned &ScannedStages = ScannedDecls[FD];
2890 ScannedStages |= CurrentShaderStageBit;
2891 }
2892
2893 unsigned GetScannedStages(const FunctionDecl *FD) { return ScannedDecls[FD]; }
2894
2895 bool WasAlreadyScannedInCurrentStage(const FunctionDecl *FD) {
2896 return WasAlreadyScannedInCurrentStage(GetScannedStages(FD));
2897 }
2898
2899 bool WasAlreadyScannedInCurrentStage(unsigned ScannerStages) {
2900 return ScannerStages & CurrentShaderStageBit;
2901 }
2902
2903 static bool NeverBeenScanned(unsigned ScannedStages) {
2904 return ScannedStages == 0;
2905 }
2906
2907 // Scanning methods
2908 void HandleFunctionOrMethodRef(FunctionDecl *FD, Expr *RefExpr);
2909 void CheckDeclAvailability(NamedDecl *D, const AvailabilityAttr *AA,
2910 SourceRange Range);
2911 const AvailabilityAttr *FindAvailabilityAttr(const Decl *D);
2912 bool HasMatchingEnvironmentOrNone(const AvailabilityAttr *AA);
2913
2914public:
2915 DiagnoseHLSLAvailability(Sema &SemaRef)
2916 : SemaRef(SemaRef),
2917 CurrentShaderEnvironment(llvm::Triple::UnknownEnvironment),
2918 CurrentShaderStageBit(0), ReportOnlyShaderStageIssues(false) {}
2919
2920 // AST traversal methods
2921 void RunOnTranslationUnit(const TranslationUnitDecl *TU);
2922 void RunOnFunction(const FunctionDecl *FD);
2923
2924 bool VisitDeclRefExpr(DeclRefExpr *DRE) override {
2925 FunctionDecl *FD = llvm::dyn_cast<FunctionDecl>(DRE->getDecl());
2926 if (FD)
2927 HandleFunctionOrMethodRef(FD, DRE);
2928 return true;
2929 }
2930
2931 bool VisitMemberExpr(MemberExpr *ME) override {
2932 FunctionDecl *FD = llvm::dyn_cast<FunctionDecl>(ME->getMemberDecl());
2933 if (FD)
2934 HandleFunctionOrMethodRef(FD, ME);
2935 return true;
2936 }
2937};
2938
2939void DiagnoseHLSLAvailability::HandleFunctionOrMethodRef(FunctionDecl *FD,
2940 Expr *RefExpr) {
2941 assert((isa<DeclRefExpr>(RefExpr) || isa<MemberExpr>(RefExpr)) &&
2942 "expected DeclRefExpr or MemberExpr");
2943
2944 // has a definition -> add to stack to be scanned
2945 const FunctionDecl *FDWithBody = nullptr;
2946 if (FD->hasBody(FDWithBody)) {
2947 if (!WasAlreadyScannedInCurrentStage(FDWithBody))
2948 DeclsToScan.push_back(FDWithBody);
2949 return;
2950 }
2951
2952 // no body -> diagnose availability
2953 const AvailabilityAttr *AA = FindAvailabilityAttr(FD);
2954 if (AA)
2955 CheckDeclAvailability(
2956 FD, AA, SourceRange(RefExpr->getBeginLoc(), RefExpr->getEndLoc()));
2957}
2958
2959void DiagnoseHLSLAvailability::RunOnTranslationUnit(
2960 const TranslationUnitDecl *TU) {
2961
2962 // Iterate over all shader entry functions and library exports, and for those
2963 // that have a body (definiton), run diag scan on each, setting appropriate
2964 // shader environment context based on whether it is a shader entry function
2965 // or an exported function. Exported functions can be in namespaces and in
2966 // export declarations so we need to scan those declaration contexts as well.
2968 DeclContextsToScan.push_back(TU);
2969
2970 while (!DeclContextsToScan.empty()) {
2971 const DeclContext *DC = DeclContextsToScan.pop_back_val();
2972 for (auto &D : DC->decls()) {
2973 // do not scan implicit declaration generated by the implementation
2974 if (D->isImplicit())
2975 continue;
2976
2977 // for namespace or export declaration add the context to the list to be
2978 // scanned later
2979 if (llvm::dyn_cast<NamespaceDecl>(D) || llvm::dyn_cast<ExportDecl>(D)) {
2980 DeclContextsToScan.push_back(llvm::dyn_cast<DeclContext>(D));
2981 continue;
2982 }
2983
2984 // skip over other decls or function decls without body
2985 const FunctionDecl *FD = llvm::dyn_cast<FunctionDecl>(D);
2986 if (!FD || !FD->isThisDeclarationADefinition())
2987 continue;
2988
2989 // shader entry point
2990 if (HLSLShaderAttr *ShaderAttr = FD->getAttr<HLSLShaderAttr>()) {
2991 SetShaderStageContext(ShaderAttr->getType());
2992 RunOnFunction(FD);
2993 continue;
2994 }
2995 // exported library function
2996 // FIXME: replace this loop with external linkage check once issue #92071
2997 // is resolved
2998 bool isExport = FD->isInExportDeclContext();
2999 if (!isExport) {
3000 for (const auto *Redecl : FD->redecls()) {
3001 if (Redecl->isInExportDeclContext()) {
3002 isExport = true;
3003 break;
3004 }
3005 }
3006 }
3007 if (isExport) {
3008 SetUnknownShaderStageContext();
3009 RunOnFunction(FD);
3010 continue;
3011 }
3012 }
3013 }
3014}
3015
3016void DiagnoseHLSLAvailability::RunOnFunction(const FunctionDecl *FD) {
3017 assert(DeclsToScan.empty() && "DeclsToScan should be empty");
3018 DeclsToScan.push_back(FD);
3019
3020 while (!DeclsToScan.empty()) {
3021 // Take one decl from the stack and check it by traversing its AST.
3022 // For any CallExpr found during the traversal add it's callee to the top of
3023 // the stack to be processed next. Functions already processed are stored in
3024 // ScannedDecls.
3025 const FunctionDecl *FD = DeclsToScan.pop_back_val();
3026
3027 // Decl was already scanned
3028 const unsigned ScannedStages = GetScannedStages(FD);
3029 if (WasAlreadyScannedInCurrentStage(ScannedStages))
3030 continue;
3031
3032 ReportOnlyShaderStageIssues = !NeverBeenScanned(ScannedStages);
3033
3034 AddToScannedFunctions(FD);
3035 TraverseStmt(FD->getBody());
3036 }
3037}
3038
3039bool DiagnoseHLSLAvailability::HasMatchingEnvironmentOrNone(
3040 const AvailabilityAttr *AA) {
3041 const IdentifierInfo *IIEnvironment = AA->getEnvironment();
3042 if (!IIEnvironment)
3043 return true;
3044
3045 llvm::Triple::EnvironmentType CurrentEnv = GetCurrentShaderEnvironment();
3046 if (CurrentEnv == llvm::Triple::UnknownEnvironment)
3047 return false;
3048
3049 llvm::Triple::EnvironmentType AttrEnv =
3050 AvailabilityAttr::getEnvironmentType(IIEnvironment->getName());
3051
3052 return CurrentEnv == AttrEnv;
3053}
3054
3055const AvailabilityAttr *
3056DiagnoseHLSLAvailability::FindAvailabilityAttr(const Decl *D) {
3057 AvailabilityAttr const *PartialMatch = nullptr;
3058 // Check each AvailabilityAttr to find the one for this platform.
3059 // For multiple attributes with the same platform try to find one for this
3060 // environment.
3061 for (const auto *A : D->attrs()) {
3062 if (const auto *Avail = dyn_cast<AvailabilityAttr>(A)) {
3063 const AvailabilityAttr *EffectiveAvail = Avail->getEffectiveAttr();
3064 StringRef AttrPlatform = EffectiveAvail->getPlatform()->getName();
3065 StringRef TargetPlatform =
3067
3068 // Match the platform name.
3069 if (AttrPlatform == TargetPlatform) {
3070 // Find the best matching attribute for this environment
3071 if (HasMatchingEnvironmentOrNone(EffectiveAvail))
3072 return Avail;
3073 PartialMatch = Avail;
3074 }
3075 }
3076 }
3077 return PartialMatch;
3078}
3079
3080// Check availability against target shader model version and current shader
3081// stage and emit diagnostic
3082void DiagnoseHLSLAvailability::CheckDeclAvailability(NamedDecl *D,
3083 const AvailabilityAttr *AA,
3084 SourceRange Range) {
3085
3086 const IdentifierInfo *IIEnv = AA->getEnvironment();
3087
3088 if (!IIEnv) {
3089 // The availability attribute does not have environment -> it depends only
3090 // on shader model version and not on specific the shader stage.
3091
3092 // Skip emitting the diagnostics if the diagnostic mode is set to
3093 // strict (-fhlsl-strict-availability) because all relevant diagnostics
3094 // were already emitted in the DiagnoseUnguardedAvailability scan
3095 // (SemaAvailability.cpp).
3096 if (SemaRef.getLangOpts().HLSLStrictAvailability)
3097 return;
3098
3099 // Do not report shader-stage-independent issues if scanning a function
3100 // that was already scanned in a different shader stage context (they would
3101 // be duplicate)
3102 if (ReportOnlyShaderStageIssues)
3103 return;
3104
3105 } else {
3106 // The availability attribute has environment -> we need to know
3107 // the current stage context to property diagnose it.
3108 if (InUnknownShaderStageContext())
3109 return;
3110 }
3111
3112 // Check introduced version and if environment matches
3113 bool EnvironmentMatches = HasMatchingEnvironmentOrNone(AA);
3114 VersionTuple Introduced = AA->getIntroduced();
3115 VersionTuple TargetVersion =
3117
3118 if (TargetVersion >= Introduced && EnvironmentMatches)
3119 return;
3120
3121 // Emit diagnostic message
3122 const TargetInfo &TI = SemaRef.getASTContext().getTargetInfo();
3123 llvm::StringRef PlatformName(
3124 AvailabilityAttr::getPrettyPlatformName(TI.getPlatformName()));
3125
3126 llvm::StringRef CurrentEnvStr =
3127 llvm::Triple::getEnvironmentTypeName(GetCurrentShaderEnvironment());
3128
3129 llvm::StringRef AttrEnvStr =
3130 AA->getEnvironment() ? AA->getEnvironment()->getName() : "";
3131 bool UseEnvironment = !AttrEnvStr.empty();
3132
3133 if (EnvironmentMatches) {
3134 SemaRef.Diag(Range.getBegin(), diag::warn_hlsl_availability)
3135 << Range << D << PlatformName << Introduced.getAsString()
3136 << UseEnvironment << CurrentEnvStr;
3137 } else {
3138 SemaRef.Diag(Range.getBegin(), diag::warn_hlsl_availability_unavailable)
3139 << Range << D;
3140 }
3141
3142 SemaRef.Diag(D->getLocation(), diag::note_partial_availability_specified_here)
3143 << D << PlatformName << Introduced.getAsString()
3144 << SemaRef.Context.getTargetInfo().getPlatformMinVersion().getAsString()
3145 << UseEnvironment << AttrEnvStr << CurrentEnvStr;
3146}
3147
3148} // namespace
3149
3151 // process default CBuffer - create buffer layout struct and invoke codegenCGH
3152 if (!DefaultCBufferDecls.empty()) {
3154 SemaRef.getASTContext(), SemaRef.getCurLexicalContext(),
3155 DefaultCBufferDecls);
3156 addImplicitBindingAttrToDecl(SemaRef, DefaultCBuffer, RegisterType::CBuffer,
3158 SemaRef.getCurLexicalContext()->addDecl(DefaultCBuffer);
3160
3161 // Set HasValidPackoffset if any of the decls has a register(c#) annotation;
3162 for (const Decl *VD : DefaultCBufferDecls) {
3163 const HLSLResourceBindingAttr *RBA =
3164 VD->getAttr<HLSLResourceBindingAttr>();
3165 if (RBA && RBA->hasRegisterSlot() &&
3166 RBA->getRegisterType() == HLSLResourceBindingAttr::RegisterType::C) {
3167 DefaultCBuffer->setHasValidPackoffset(true);
3168 break;
3169 }
3170 }
3171
3172 DeclGroupRef DG(DefaultCBuffer);
3173 SemaRef.Consumer.HandleTopLevelDecl(DG);
3174 }
3175 diagnoseAvailabilityViolations(TU);
3176}
3177
3178// For resource member access through a global struct array, verify that the
3179// array index selecting the struct element is a constant integer expression.
3180// Returns false if the member expression is invalid.
3182 assert((ME->getType()->isHLSLResourceRecord() ||
3184 "expected member expr to have resource record type or array of them");
3185
3186 // Walk the AST from MemberExpr to the VarDecl of the parent struct instance
3187 // and take note of any non-constant array indexing along the way. If the
3188 // VarDecl we find is a global variable, report error if there was any
3189 // non-constant array index in the resource member access along the way.
3190 const Expr *NonConstIndexExpr = nullptr;
3191 const Expr *E = ME->getBase();
3192 while (E) {
3193 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
3194 if (!NonConstIndexExpr)
3195 return true;
3196
3197 const VarDecl *VD = cast<VarDecl>(DRE->getDecl());
3198 if (!VD->hasGlobalStorage())
3199 return true;
3200
3201 SemaRef.Diag(NonConstIndexExpr->getExprLoc(),
3202 diag::err_hlsl_resource_member_array_access_not_constant);
3203 return false;
3204 }
3205
3206 if (const auto *ASE = dyn_cast<ArraySubscriptExpr>(E)) {
3207 const Expr *IdxExpr = ASE->getIdx();
3208 if (!IdxExpr->isIntegerConstantExpr(SemaRef.getASTContext()))
3209 NonConstIndexExpr = IdxExpr;
3210 E = ASE->getBase();
3211 } else if (const auto *SubME = dyn_cast<MemberExpr>(E)) {
3212 E = SubME->getBase();
3213 } else if (const auto *ICE = dyn_cast<ImplicitCastExpr>(E)) {
3214 E = ICE->getSubExpr();
3215 } else {
3216 llvm_unreachable("unexpected expr type in resource member access");
3217 }
3218 }
3219 return true;
3220}
3221
3223 CXXRecordDecl *RD) {
3224 QualType AddrSpaceType =
3225 SemaRef.Context.getCanonicalType(SemaRef.Context.getAddrSpaceQualType(
3226 Type.withConst(), LangAS::hlsl_constant));
3227 QualType ReturnTy = SemaRef.Context.getCanonicalType(
3228 SemaRef.Context.getLValueReferenceType(AddrSpaceType));
3229
3230 DeclarationName ConvName =
3231 SemaRef.Context.DeclarationNames.getCXXConversionFunctionName(
3232 CanQualType::CreateUnsafe(ReturnTy));
3233 LookupResult ConvR(SemaRef, ConvName, SourceLocation(),
3235 [[maybe_unused]] bool LookupSucceeded =
3236 SemaRef.LookupQualifiedName(ConvR, RD);
3237 assert(LookupSucceeded);
3238
3239 for (NamedDecl *D : ConvR) {
3241 return D;
3242 }
3243 return nullptr;
3244}
3245
3246std::optional<ExprResult>
3248 QualType BaseType = BaseExpr.get()->getType();
3249 const HLSLAttributedResourceType *ResTy =
3250 HLSLAttributedResourceType::findHandleTypeOnResource(
3251 BaseType.getTypePtr());
3252 if (!ResTy ||
3253 ResTy->getAttrs().ResourceClass != llvm::dxil::ResourceClass::CBuffer)
3254 return std::nullopt;
3255
3256 QualType TemplateType = ResTy->getContainedType();
3257
3258 NamedDecl *NamedConversionDecl = getConstantBufferConversionFunction(
3259 TemplateType, BaseType->getAsCXXRecordDecl());
3260 assert(NamedConversionDecl &&
3261 "Could not find conversion function for ConstantBuffer.");
3262 auto *ConversionDecl =
3263 cast<CXXConversionDecl>(NamedConversionDecl->getUnderlyingDecl());
3264
3265 return SemaRef.BuildCXXMemberCallExpr(BaseExpr.get(), NamedConversionDecl,
3266 ConversionDecl,
3267 /*HadMultipleCandidates=*/false);
3268}
3269
3270void SemaHLSL::diagnoseAvailabilityViolations(TranslationUnitDecl *TU) {
3271 // Skip running the diagnostics scan if the diagnostic mode is
3272 // strict (-fhlsl-strict-availability) and the target shader stage is known
3273 // because all relevant diagnostics were already emitted in the
3274 // DiagnoseUnguardedAvailability scan (SemaAvailability.cpp).
3276 if (SemaRef.getLangOpts().HLSLStrictAvailability &&
3277 TI.getTriple().getEnvironment() != llvm::Triple::EnvironmentType::Library)
3278 return;
3279
3280 DiagnoseHLSLAvailability(SemaRef).RunOnTranslationUnit(TU);
3281}
3282
3283static bool CheckAllArgsHaveSameType(Sema *S, CallExpr *TheCall) {
3284 assert(TheCall->getNumArgs() > 1);
3285 QualType ArgTy0 = TheCall->getArg(0)->getType();
3286
3287 for (unsigned I = 1, N = TheCall->getNumArgs(); I < N; ++I) {
3289 ArgTy0, TheCall->getArg(I)->getType())) {
3290 S->Diag(TheCall->getBeginLoc(), diag::err_vec_builtin_incompatible_vector)
3291 << TheCall->getDirectCallee() << /*useAllTerminology*/ true
3292 << SourceRange(TheCall->getArg(0)->getBeginLoc(),
3293 TheCall->getArg(N - 1)->getEndLoc());
3294 return true;
3295 }
3296 }
3297 return false;
3298}
3299
3301 QualType ArgType = Arg->getType();
3303 S->Diag(Arg->getBeginLoc(), diag::err_typecheck_convert_incompatible)
3304 << ArgType << ExpectedType << 1 << 0 << 0;
3305 return true;
3306 }
3307 return false;
3308}
3309
3311 Sema *S, CallExpr *TheCall,
3312 llvm::function_ref<bool(Sema *S, SourceLocation Loc, int ArgOrdinal,
3313 clang::QualType PassedType)>
3314 Check) {
3315 for (unsigned I = 0; I < TheCall->getNumArgs(); ++I) {
3316 Expr *Arg = TheCall->getArg(I);
3317 if (Check(S, Arg->getBeginLoc(), I + 1, Arg->getType()))
3318 return true;
3319 }
3320 return false;
3321}
3322
3324 int ArgOrdinal,
3325 clang::QualType PassedType) {
3326 clang::QualType BaseType =
3327 PassedType->isVectorType()
3328 ? PassedType->castAs<clang::VectorType>()->getElementType()
3329 : PassedType;
3330 if (!BaseType->isFloat32Type())
3331 return S->Diag(Loc, diag::err_builtin_invalid_arg_type)
3332 << ArgOrdinal << /* scalar or vector of */ 5 << /* no int */ 0
3333 << /* float */ 1 << PassedType;
3334 return false;
3335}
3336
3338 int ArgOrdinal,
3339 clang::QualType PassedType) {
3340 clang::QualType BaseType = PassedType;
3341 if (const auto *VT = PassedType->getAs<clang::VectorType>())
3342 BaseType = VT->getElementType();
3343 else if (const auto *MT = PassedType->getAs<clang::MatrixType>())
3344 BaseType = MT->getElementType();
3345
3346 if (!BaseType->isHalfType() && !BaseType->isFloat32Type())
3347 return S->Diag(Loc, diag::err_builtin_invalid_arg_type)
3348 << ArgOrdinal << /* scalar or vector of */ 5 << /* no int */ 0
3349 << /* half or float */ 2 << PassedType;
3350 return false;
3351}
3352
3354 int ArgOrdinal,
3355 clang::QualType PassedType) {
3356 clang::QualType BaseType =
3357 PassedType->isVectorType()
3358 ? PassedType->castAs<clang::VectorType>()->getElementType()
3359 : PassedType->isMatrixType()
3360 ? PassedType->castAs<clang::MatrixType>()->getElementType()
3361 : PassedType;
3362 if (!BaseType->isDoubleType()) {
3363 // FIXME: adopt standard `err_builtin_invalid_arg_type` instead of using
3364 // this custom error.
3365 return S->Diag(Loc, diag::err_builtin_requires_double_type)
3366 << ArgOrdinal << PassedType;
3367 }
3368
3369 return false;
3370}
3371
3372static bool CheckModifiableLValue(Sema *S, CallExpr *TheCall,
3373 unsigned ArgIndex) {
3374 auto *Arg = TheCall->getArg(ArgIndex);
3375 SourceLocation OrigLoc = Arg->getExprLoc();
3376 if (Arg->IgnoreCasts()->isModifiableLvalue(S->Context, &OrigLoc) ==
3378 return false;
3379 S->Diag(OrigLoc, diag::error_hlsl_inout_lvalue) << Arg << 0;
3380 return true;
3381}
3382
3383// Verifies that the argument at `ArgIndex` of `TheCall` refers to memory in
3384// one of `AllowedSpaces`. Intended for HLSL builtins (e.g. atomics).
3385static bool CheckArgAddrSpaceOneOf(Sema *S, CallExpr *TheCall,
3386 unsigned ArgIndex,
3387 ArrayRef<LangAS> AllowedSpaces) {
3388 Expr *Arg = TheCall->getArg(ArgIndex);
3389 QualType LValueTy = Arg->IgnoreCasts()->getType();
3390 if (llvm::is_contained(AllowedSpaces, LValueTy.getAddressSpace()))
3391 return false;
3392 S->Diag(Arg->getBeginLoc(), diag::err_hlsl_atomic_arg_addr_space)
3393 << (ArgIndex + 1) << LValueTy;
3394 return true;
3395}
3396
3397static bool CheckNoDoubleVectors(Sema *S, SourceLocation Loc, int ArgOrdinal,
3398 clang::QualType PassedType) {
3399 const auto *VecTy = PassedType->getAs<VectorType>();
3400 if (!VecTy)
3401 return false;
3402
3403 if (VecTy->getElementType()->isDoubleType())
3404 return S->Diag(Loc, diag::err_builtin_invalid_arg_type)
3405 << ArgOrdinal << /* scalar */ 1 << /* no int */ 0 << /* fp */ 1
3406 << PassedType;
3407 return false;
3408}
3409
3411 int ArgOrdinal,
3412 clang::QualType PassedType) {
3413 if (!PassedType->hasIntegerRepresentation() &&
3414 !PassedType->hasFloatingRepresentation())
3415 return S->Diag(Loc, diag::err_builtin_invalid_arg_type)
3416 << ArgOrdinal << /* scalar or vector of */ 5 << /* integer */ 1
3417 << /* fp */ 1 << PassedType;
3418 return false;
3419}
3420
3422 int ArgOrdinal,
3423 clang::QualType PassedType) {
3424 if (auto *VecTy = PassedType->getAs<VectorType>())
3425 if (VecTy->getElementType()->isUnsignedIntegerType())
3426 return false;
3427
3428 return S->Diag(Loc, diag::err_builtin_invalid_arg_type)
3429 << ArgOrdinal << /* vector of */ 4 << /* uint */ 3 << /* no fp */ 0
3430 << PassedType;
3431}
3432
3433// checks for unsigned ints of all sizes
3435 int ArgOrdinal,
3436 clang::QualType PassedType) {
3437 if (!PassedType->hasUnsignedIntegerRepresentation())
3438 return S->Diag(Loc, diag::err_builtin_invalid_arg_type)
3439 << ArgOrdinal << /* scalar or vector of */ 5 << /* unsigned int */ 3
3440 << /* no fp */ 0 << PassedType;
3441 return false;
3442}
3443
3444static bool CheckExpectedBitWidth(Sema *S, CallExpr *TheCall,
3445 unsigned ArgOrdinal, unsigned Width) {
3446 QualType ArgTy = TheCall->getArg(0)->getType();
3447 if (auto *VTy = ArgTy->getAs<VectorType>())
3448 ArgTy = VTy->getElementType();
3449 // ensure arg type has expected bit width
3450 uint64_t ElementBitCount =
3452 if (ElementBitCount != Width) {
3453 S->Diag(TheCall->getArg(0)->getBeginLoc(),
3454 diag::err_integer_incorrect_bit_count)
3455 << Width << ElementBitCount;
3456 return true;
3457 }
3458 return false;
3459}
3460
3462 QualType ReturnType) {
3463 auto *VecTyA = TheCall->getArg(0)->getType()->getAs<VectorType>();
3464 if (VecTyA)
3465 ReturnType =
3466 S->Context.getExtVectorType(ReturnType, VecTyA->getNumElements());
3467
3468 TheCall->setType(ReturnType);
3469}
3470
3471static bool CheckScalarOrVector(Sema *S, CallExpr *TheCall, QualType Scalar,
3472 unsigned ArgIndex) {
3473 assert(TheCall->getNumArgs() >= ArgIndex);
3474 QualType ArgType = TheCall->getArg(ArgIndex)->getType();
3475 auto *VTy = ArgType->getAs<VectorType>();
3476 // not the scalar or vector<scalar>
3477 if (!(S->Context.hasSameUnqualifiedType(ArgType, Scalar) ||
3478 (VTy &&
3479 S->Context.hasSameUnqualifiedType(VTy->getElementType(), Scalar)))) {
3480 S->Diag(TheCall->getArg(0)->getBeginLoc(),
3481 diag::err_typecheck_expect_scalar_or_vector)
3482 << ArgType << Scalar;
3483 return true;
3484 }
3485 return false;
3486}
3487
3489 QualType Scalar, unsigned ArgIndex) {
3490 assert(TheCall->getNumArgs() > ArgIndex);
3491
3492 Expr *Arg = TheCall->getArg(ArgIndex);
3493 QualType ArgType = Arg->getType();
3494
3495 // Scalar: T
3496 if (S->Context.hasSameUnqualifiedType(ArgType, Scalar))
3497 return false;
3498
3499 // Vector: vector<T>
3500 if (const auto *VTy = ArgType->getAs<VectorType>()) {
3501 if (S->Context.hasSameUnqualifiedType(VTy->getElementType(), Scalar))
3502 return false;
3503 }
3504
3505 // Matrix: ConstantMatrixType with element type T
3506 if (const auto *MTy = ArgType->getAs<ConstantMatrixType>()) {
3507 if (S->Context.hasSameUnqualifiedType(MTy->getElementType(), Scalar))
3508 return false;
3509 }
3510
3511 // Not a scalar/vector/matrix-of-scalar
3512 S->Diag(Arg->getBeginLoc(),
3513 diag::err_typecheck_expect_scalar_or_vector_or_matrix)
3514 << ArgType << Scalar;
3515 return true;
3516}
3517
3518static bool CheckAnyScalarOrVector(Sema *S, CallExpr *TheCall,
3519 unsigned ArgIndex) {
3520 assert(TheCall->getNumArgs() >= ArgIndex);
3521 QualType ArgType = TheCall->getArg(ArgIndex)->getType();
3522 auto *VTy = ArgType->getAs<VectorType>();
3523 // not the scalar or vector<scalar>
3524 if (!(ArgType->isScalarType() ||
3525 (VTy && VTy->getElementType()->isScalarType()))) {
3526 S->Diag(TheCall->getArg(0)->getBeginLoc(),
3527 diag::err_typecheck_expect_any_scalar_or_vector)
3528 << ArgType << 1;
3529 return true;
3530 }
3531 return false;
3532}
3533
3534// Check that the argument is not a bool or vector<bool>
3535// Returns true on error
3537 unsigned ArgIndex) {
3538 QualType BoolType = S->getASTContext().BoolTy;
3539 assert(ArgIndex < TheCall->getNumArgs());
3540 QualType ArgType = TheCall->getArg(ArgIndex)->getType();
3541 auto *VTy = ArgType->getAs<VectorType>();
3542 // is the bool or vector<bool>
3543 if (S->Context.hasSameUnqualifiedType(ArgType, BoolType) ||
3544 (VTy &&
3545 S->Context.hasSameUnqualifiedType(VTy->getElementType(), BoolType))) {
3546 S->Diag(TheCall->getArg(0)->getBeginLoc(),
3547 diag::err_typecheck_expect_any_scalar_or_vector)
3548 << ArgType << 0;
3549 return true;
3550 }
3551 return false;
3552}
3553
3554static bool CheckWaveActive(Sema *S, CallExpr *TheCall) {
3555 if (CheckNotBoolScalarOrVector(S, TheCall, 0))
3556 return true;
3557 return false;
3558}
3559
3560static bool CheckWavePrefix(Sema *S, CallExpr *TheCall) {
3561 if (CheckNotBoolScalarOrVector(S, TheCall, 0))
3562 return true;
3563 return false;
3564}
3565
3566static bool CheckBoolSelect(Sema *S, CallExpr *TheCall) {
3567 assert(TheCall->getNumArgs() == 3);
3568 Expr *Arg1 = TheCall->getArg(1);
3569 Expr *Arg2 = TheCall->getArg(2);
3570 if (!S->Context.hasSameUnqualifiedType(Arg1->getType(), Arg2->getType())) {
3571 S->Diag(TheCall->getBeginLoc(),
3572 diag::err_typecheck_call_different_arg_types)
3573 << Arg1->getType() << Arg2->getType() << Arg1->getSourceRange()
3574 << Arg2->getSourceRange();
3575 return true;
3576 }
3577
3578 TheCall->setType(Arg1->getType());
3579 return false;
3580}
3581
3582static bool CheckVectorSelect(Sema *S, CallExpr *TheCall) {
3583 assert(TheCall->getNumArgs() == 3);
3584 Expr *Arg1 = TheCall->getArg(1);
3585 QualType Arg1Ty = Arg1->getType();
3586 Expr *Arg2 = TheCall->getArg(2);
3587 QualType Arg2Ty = Arg2->getType();
3588
3589 QualType Arg1ScalarTy = Arg1Ty;
3590 if (auto VTy = Arg1ScalarTy->getAs<VectorType>())
3591 Arg1ScalarTy = VTy->getElementType();
3592
3593 QualType Arg2ScalarTy = Arg2Ty;
3594 if (auto VTy = Arg2ScalarTy->getAs<VectorType>())
3595 Arg2ScalarTy = VTy->getElementType();
3596
3597 if (!S->Context.hasSameUnqualifiedType(Arg1ScalarTy, Arg2ScalarTy))
3598 S->Diag(Arg1->getBeginLoc(), diag::err_hlsl_builtin_scalar_vector_mismatch)
3599 << /* second and third */ 1 << TheCall->getCallee() << Arg1Ty << Arg2Ty;
3600
3601 QualType Arg0Ty = TheCall->getArg(0)->getType();
3602 unsigned Arg0Length = Arg0Ty->getAs<VectorType>()->getNumElements();
3603 unsigned Arg1Length = Arg1Ty->isVectorType()
3604 ? Arg1Ty->getAs<VectorType>()->getNumElements()
3605 : 0;
3606 unsigned Arg2Length = Arg2Ty->isVectorType()
3607 ? Arg2Ty->getAs<VectorType>()->getNumElements()
3608 : 0;
3609 if (Arg1Length > 0 && Arg0Length != Arg1Length) {
3610 S->Diag(TheCall->getBeginLoc(),
3611 diag::err_typecheck_vector_lengths_not_equal)
3612 << Arg0Ty << Arg1Ty << TheCall->getArg(0)->getSourceRange()
3613 << Arg1->getSourceRange();
3614 return true;
3615 }
3616
3617 if (Arg2Length > 0 && Arg0Length != Arg2Length) {
3618 S->Diag(TheCall->getBeginLoc(),
3619 diag::err_typecheck_vector_lengths_not_equal)
3620 << Arg0Ty << Arg2Ty << TheCall->getArg(0)->getSourceRange()
3621 << Arg2->getSourceRange();
3622 return true;
3623 }
3624
3625 TheCall->setType(
3626 S->getASTContext().getExtVectorType(Arg1ScalarTy, Arg0Length));
3627 return false;
3628}
3629
3630static bool CheckIndexType(Sema *S, CallExpr *TheCall, unsigned IndexArgIndex) {
3631 assert(TheCall->getNumArgs() > IndexArgIndex && "Index argument missing");
3632 QualType ArgType = TheCall->getArg(IndexArgIndex)->getType();
3633 QualType IndexTy = ArgType;
3634 unsigned int ActualDim = 1;
3635 if (const auto *VTy = IndexTy->getAs<VectorType>()) {
3636 ActualDim = VTy->getNumElements();
3637 IndexTy = VTy->getElementType();
3638 }
3639 if (!IndexTy->isIntegerType()) {
3640 S->Diag(TheCall->getArg(IndexArgIndex)->getBeginLoc(),
3641 diag::err_typecheck_expect_int)
3642 << ArgType;
3643 return true;
3644 }
3645
3646 QualType ResourceArgTy = TheCall->getArg(0)->getType();
3647 const HLSLAttributedResourceType *ResTy =
3648 ResourceArgTy.getTypePtr()->getAs<HLSLAttributedResourceType>();
3649 assert(ResTy && "Resource argument must be a resource");
3650 HLSLAttributedResourceType::Attributes ResAttrs = ResTy->getAttrs();
3651
3652 unsigned int ExpectedDim = 1;
3653 if (ResAttrs.ResourceDimension != llvm::dxil::ResourceDimension::Unknown)
3654 ExpectedDim = getResourceDimensions(ResAttrs.ResourceDimension);
3655
3656 if (ActualDim != ExpectedDim) {
3657 S->Diag(TheCall->getArg(IndexArgIndex)->getBeginLoc(),
3658 diag::err_hlsl_builtin_resource_coordinate_dimension_mismatch)
3659 << cast<NamedDecl>(TheCall->getCalleeDecl()) << ExpectedDim
3660 << ActualDim;
3661 return true;
3662 }
3663
3664 return false;
3665}
3666
3668 Sema *S, CallExpr *TheCall, unsigned ArgIndex,
3669 llvm::function_ref<bool(const HLSLAttributedResourceType *ResType)> Check =
3670 nullptr) {
3671 assert(TheCall->getNumArgs() >= ArgIndex);
3672 QualType ArgType = TheCall->getArg(ArgIndex)->getType();
3673 const HLSLAttributedResourceType *ResTy =
3674 ArgType.getTypePtr()->getAs<HLSLAttributedResourceType>();
3675 if (!ResTy) {
3676 S->Diag(TheCall->getArg(ArgIndex)->getBeginLoc(),
3677 diag::err_typecheck_expect_hlsl_resource)
3678 << ArgType;
3679 return true;
3680 }
3681 if (Check && Check(ResTy)) {
3682 S->Diag(TheCall->getArg(ArgIndex)->getExprLoc(),
3683 diag::err_invalid_hlsl_resource_type)
3684 << ArgType;
3685 return true;
3686 }
3687 return false;
3688}
3689
3690static bool CheckVectorElementCount(Sema *S, QualType PassedType,
3691 QualType BaseType, unsigned ExpectedCount,
3692 SourceLocation Loc) {
3693 unsigned PassedCount = 1;
3694 if (const auto *VecTy = PassedType->getAs<VectorType>())
3695 PassedCount = VecTy->getNumElements();
3696
3697 if (PassedCount != ExpectedCount) {
3699 S->Context.getExtVectorType(BaseType, ExpectedCount);
3700 S->Diag(Loc, diag::err_typecheck_convert_incompatible)
3701 << PassedType << ExpectedType << 1 << 0 << 0;
3702 return true;
3703 }
3704 return false;
3705}
3706
3707enum class SampleKind { Sample, Bias, Grad, Level, Cmp, CmpLevelZero };
3708
3710 // Check the texture handle.
3711 if (CheckResourceHandle(&S, TheCall, 0,
3712 [](const HLSLAttributedResourceType *ResType) {
3713 return ResType->getAttrs().ResourceDimension ==
3714 llvm::dxil::ResourceDimension::Unknown;
3715 }))
3716 return true;
3717
3718 // Check the sampler handle.
3719 if (CheckResourceHandle(&S, TheCall, 1,
3720 [](const HLSLAttributedResourceType *ResType) {
3721 return ResType->getAttrs().ResourceClass !=
3722 llvm::hlsl::ResourceClass::Sampler;
3723 }))
3724 return true;
3725
3726 auto *ResourceTy =
3727 TheCall->getArg(0)->getType()->castAs<HLSLAttributedResourceType>();
3728
3729 // Check the location.
3730 unsigned ExpectedDim =
3731 getResourceDimensions(ResourceTy->getAttrs().ResourceDimension);
3732 if (CheckVectorElementCount(&S, TheCall->getArg(2)->getType(),
3733 S.Context.FloatTy, ExpectedDim,
3734 TheCall->getBeginLoc()))
3735 return true;
3736
3737 return false;
3738}
3739
3740static bool CheckCalculateLodBuiltin(Sema &S, CallExpr *TheCall) {
3741 if (S.checkArgCount(TheCall, 3))
3742 return true;
3743
3744 if (CheckTextureSamplerAndLocation(S, TheCall))
3745 return true;
3746
3747 TheCall->setType(S.Context.FloatTy);
3748 return false;
3749}
3750
3751static bool CheckGatherBuiltin(Sema &S, CallExpr *TheCall, bool IsCmp) {
3752 if (S.checkArgCountRange(TheCall, IsCmp ? 5 : 4, IsCmp ? 6 : 5))
3753 return true;
3754
3755 if (CheckTextureSamplerAndLocation(S, TheCall))
3756 return true;
3757
3758 unsigned NextIdx = 3;
3759 if (IsCmp) {
3760 // Check the compare value.
3761 QualType CmpTy = TheCall->getArg(NextIdx)->getType();
3762 if (!CmpTy->isFloatingType() || CmpTy->isVectorType()) {
3763 S.Diag(TheCall->getArg(NextIdx)->getBeginLoc(),
3764 diag::err_typecheck_convert_incompatible)
3765 << CmpTy << S.Context.FloatTy << 1 << 0 << 0;
3766 return true;
3767 }
3768 NextIdx++;
3769 }
3770
3771 // Check the component operand.
3772 Expr *ComponentArg = TheCall->getArg(NextIdx);
3773 QualType ComponentTy = ComponentArg->getType();
3774 if (!ComponentTy->isIntegerType() || ComponentTy->isVectorType()) {
3775 S.Diag(ComponentArg->getBeginLoc(),
3776 diag::err_typecheck_convert_incompatible)
3777 << ComponentTy << S.Context.UnsignedIntTy << 1 << 0 << 0;
3778 return true;
3779 }
3780
3781 // GatherCmp operations on Vulkan target must use component 0 (Red).
3782 if (IsCmp && S.getASTContext().getTargetInfo().getTriple().isSPIRV()) {
3783 std::optional<llvm::APSInt> ComponentOpt =
3784 ComponentArg->getIntegerConstantExpr(S.getASTContext());
3785 if (ComponentOpt) {
3786 int64_t ComponentVal = ComponentOpt->getSExtValue();
3787 if (ComponentVal != 0) {
3788 // Issue an error if the component is not 0 (Red).
3789 // 0 -> Red, 1 -> Green, 2 -> Blue, 3 -> Alpha
3790 assert(ComponentVal >= 0 && ComponentVal <= 3 &&
3791 "The component is not in the expected range.");
3792 S.Diag(ComponentArg->getBeginLoc(),
3793 diag::err_hlsl_gathercmp_invalid_component)
3794 << ComponentVal;
3795 return true;
3796 }
3797 }
3798 }
3799
3800 NextIdx++;
3801
3802 // Check the offset operand.
3803 const HLSLAttributedResourceType *ResourceTy =
3804 TheCall->getArg(0)->getType()->castAs<HLSLAttributedResourceType>();
3805 if (TheCall->getNumArgs() > NextIdx) {
3806 unsigned ExpectedDim =
3807 getResourceDimensions(ResourceTy->getAttrs().ResourceDimension);
3808 if (CheckVectorElementCount(&S, TheCall->getArg(NextIdx)->getType(),
3809 S.Context.IntTy, ExpectedDim,
3810 TheCall->getArg(NextIdx)->getBeginLoc()))
3811 return true;
3812 NextIdx++;
3813 }
3814
3815 assert(ResourceTy->hasContainedType() &&
3816 "Expecting a contained type for resource with a dimension "
3817 "attribute.");
3818 QualType ReturnType = ResourceTy->getContainedType();
3819
3820 if (IsCmp) {
3821 if (!ReturnType->hasFloatingRepresentation()) {
3822 S.Diag(TheCall->getBeginLoc(), diag::err_hlsl_samplecmp_requires_float);
3823 return true;
3824 }
3825 }
3826
3827 if (const auto *VecTy = ReturnType->getAs<VectorType>())
3828 ReturnType = VecTy->getElementType();
3829 ReturnType = S.Context.getExtVectorType(ReturnType, 4);
3830
3831 TheCall->setType(ReturnType);
3832
3833 return false;
3834}
3835static bool CheckLoadLevelBuiltin(Sema &S, CallExpr *TheCall) {
3836 if (S.checkArgCountRange(TheCall, 2, 3))
3837 return true;
3838
3839 // Check the texture handle.
3840 if (CheckResourceHandle(&S, TheCall, 0,
3841 [](const HLSLAttributedResourceType *ResType) {
3842 return ResType->getAttrs().ResourceDimension ==
3843 llvm::dxil::ResourceDimension::Unknown;
3844 }))
3845 return true;
3846
3847 auto *ResourceTy =
3848 TheCall->getArg(0)->getType()->castAs<HLSLAttributedResourceType>();
3849
3850 // Check the location + lod (int3 for Texture2D).
3851 unsigned ExpectedDim =
3852 getResourceDimensions(ResourceTy->getAttrs().ResourceDimension);
3853 QualType CoordLODTy = TheCall->getArg(1)->getType();
3854 if (CheckVectorElementCount(&S, CoordLODTy, S.Context.IntTy, ExpectedDim + 1,
3855 TheCall->getArg(1)->getBeginLoc()))
3856 return true;
3857
3858 QualType EltTy = CoordLODTy;
3859 if (const auto *VTy = EltTy->getAs<VectorType>())
3860 EltTy = VTy->getElementType();
3861 if (!EltTy->isIntegerType()) {
3862 S.Diag(TheCall->getArg(1)->getBeginLoc(), diag::err_typecheck_expect_int)
3863 << CoordLODTy;
3864 return true;
3865 }
3866
3867 // Check the offset operand.
3868 if (TheCall->getNumArgs() > 2) {
3869 if (CheckVectorElementCount(&S, TheCall->getArg(2)->getType(),
3870 S.Context.IntTy, ExpectedDim,
3871 TheCall->getArg(2)->getBeginLoc()))
3872 return true;
3873 }
3874
3875 TheCall->setType(ResourceTy->getContainedType());
3876 return false;
3877}
3878
3879static bool CheckSamplingBuiltin(Sema &S, CallExpr *TheCall, SampleKind Kind) {
3880 unsigned MinArgs, MaxArgs;
3881 if (Kind == SampleKind::Sample) {
3882 MinArgs = 3;
3883 MaxArgs = 5;
3884 } else if (Kind == SampleKind::Bias) {
3885 MinArgs = 4;
3886 MaxArgs = 6;
3887 } else if (Kind == SampleKind::Grad) {
3888 MinArgs = 5;
3889 MaxArgs = 7;
3890 } else if (Kind == SampleKind::Level) {
3891 MinArgs = 4;
3892 MaxArgs = 5;
3893 } else if (Kind == SampleKind::Cmp) {
3894 MinArgs = 4;
3895 MaxArgs = 6;
3896 } else {
3897 assert(Kind == SampleKind::CmpLevelZero);
3898 MinArgs = 4;
3899 MaxArgs = 5;
3900 }
3901
3902 if (S.checkArgCountRange(TheCall, MinArgs, MaxArgs))
3903 return true;
3904
3905 if (CheckTextureSamplerAndLocation(S, TheCall))
3906 return true;
3907
3908 const HLSLAttributedResourceType *ResourceTy =
3909 TheCall->getArg(0)->getType()->castAs<HLSLAttributedResourceType>();
3910 unsigned ExpectedDim =
3911 getResourceDimensions(ResourceTy->getAttrs().ResourceDimension);
3912
3913 unsigned NextIdx = 3;
3914 if (Kind == SampleKind::Bias || Kind == SampleKind::Level ||
3915 Kind == SampleKind::Cmp || Kind == SampleKind::CmpLevelZero) {
3916 // Check the bias, lod level, or compare value, depending on the kind.
3917 // All of them must be a scalar float value.
3918 QualType BiasOrLODOrCmpTy = TheCall->getArg(NextIdx)->getType();
3919 if (!BiasOrLODOrCmpTy->isFloatingType() ||
3920 BiasOrLODOrCmpTy->isVectorType()) {
3921 S.Diag(TheCall->getArg(NextIdx)->getBeginLoc(),
3922 diag::err_typecheck_convert_incompatible)
3923 << BiasOrLODOrCmpTy << S.Context.FloatTy << 1 << 0 << 0;
3924 return true;
3925 }
3926 NextIdx++;
3927 } else if (Kind == SampleKind::Grad) {
3928 // Check the DDX operand.
3929 if (CheckVectorElementCount(&S, TheCall->getArg(NextIdx)->getType(),
3930 S.Context.FloatTy, ExpectedDim,
3931 TheCall->getArg(NextIdx)->getBeginLoc()))
3932 return true;
3933
3934 // Check the DDY operand.
3935 if (CheckVectorElementCount(&S, TheCall->getArg(NextIdx + 1)->getType(),
3936 S.Context.FloatTy, ExpectedDim,
3937 TheCall->getArg(NextIdx + 1)->getBeginLoc()))
3938 return true;
3939 NextIdx += 2;
3940 }
3941
3942 // Check the offset operand.
3943 if (TheCall->getNumArgs() > NextIdx) {
3944 if (CheckVectorElementCount(&S, TheCall->getArg(NextIdx)->getType(),
3945 S.Context.IntTy, ExpectedDim,
3946 TheCall->getArg(NextIdx)->getBeginLoc()))
3947 return true;
3948 NextIdx++;
3949 }
3950
3951 // Check the clamp operand.
3952 if (Kind != SampleKind::Level && Kind != SampleKind::CmpLevelZero &&
3953 TheCall->getNumArgs() > NextIdx) {
3954 QualType ClampTy = TheCall->getArg(NextIdx)->getType();
3955 if (!ClampTy->isFloatingType() || ClampTy->isVectorType()) {
3956 S.Diag(TheCall->getArg(NextIdx)->getBeginLoc(),
3957 diag::err_typecheck_convert_incompatible)
3958 << ClampTy << S.Context.FloatTy << 1 << 0 << 0;
3959 return true;
3960 }
3961 }
3962
3963 assert(ResourceTy->hasContainedType() &&
3964 "Expecting a contained type for resource with a dimension "
3965 "attribute.");
3966 QualType ReturnType = ResourceTy->getContainedType();
3967 if (Kind == SampleKind::Cmp || Kind == SampleKind::CmpLevelZero) {
3968 if (!ReturnType->hasFloatingRepresentation()) {
3969 S.Diag(TheCall->getBeginLoc(), diag::err_hlsl_samplecmp_requires_float);
3970 return true;
3971 }
3972 ReturnType = S.Context.FloatTy;
3973 }
3974 TheCall->setType(ReturnType);
3975
3976 return false;
3977}
3978
3979// Note: returning true in this case results in CheckBuiltinFunctionCall
3980// returning an ExprError
3981bool SemaHLSL::CheckBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
3982 switch (BuiltinID) {
3983 case Builtin::BI__builtin_hlsl_adduint64: {
3984 if (SemaRef.checkArgCount(TheCall, 2))
3985 return true;
3986
3987 if (CheckAllArgTypesAreCorrect(&SemaRef, TheCall,
3989 return true;
3990
3991 // ensure arg integers are 32-bits
3992 if (CheckExpectedBitWidth(&SemaRef, TheCall, 0, 32))
3993 return true;
3994
3995 // ensure both args are vectors of total bit size of a multiple of 64
3996 auto *VTy = TheCall->getArg(0)->getType()->getAs<VectorType>();
3997 int NumElementsArg = VTy->getNumElements();
3998 if (NumElementsArg != 2 && NumElementsArg != 4) {
3999 SemaRef.Diag(TheCall->getBeginLoc(), diag::err_vector_incorrect_bit_count)
4000 << 1 /*a multiple of*/ << 64 << NumElementsArg * 32;
4001 return true;
4002 }
4003
4004 // ensure first arg and second arg have the same type
4005 if (CheckAllArgsHaveSameType(&SemaRef, TheCall))
4006 return true;
4007
4008 ExprResult A = TheCall->getArg(0);
4009 QualType ArgTyA = A.get()->getType();
4010 // return type is the same as the input type
4011 TheCall->setType(ArgTyA);
4012 break;
4013 }
4014 case Builtin::BI__builtin_hlsl_resource_getpointer: {
4015 if (SemaRef.checkArgCountRange(TheCall, 1, 2) ||
4016 CheckResourceHandle(&SemaRef, TheCall, 0) ||
4017 (TheCall->getNumArgs() == 2 && CheckIndexType(&SemaRef, TheCall, 1)))
4018 return true;
4019
4020 auto *ResourceTy =
4021 TheCall->getArg(0)->getType()->castAs<HLSLAttributedResourceType>();
4022 QualType ContainedTy = ResourceTy->getContainedType();
4023 auto ReturnType = SemaRef.Context.getAddrSpaceQualType(
4024 ContainedTy,
4025 getLangASFromResourceClass(ResourceTy->getAttrs().ResourceClass));
4026 ReturnType = SemaRef.Context.getPointerType(ReturnType);
4027 TheCall->setType(ReturnType);
4028
4029 break;
4030 }
4031 case Builtin::BI__builtin_hlsl_resource_getpointer_typed: {
4032 if (SemaRef.checkArgCount(TheCall, 3) ||
4033 CheckResourceHandle(&SemaRef, TheCall, 0) ||
4034 CheckIndexType(&SemaRef, TheCall, 1))
4035 return true;
4036
4037 QualType ElementTy = TheCall->getArg(2)->getType();
4038 assert(ElementTy->isPointerType() &&
4039 "expected pointer type for second argument");
4040 ElementTy = ElementTy->getPointeeType();
4041
4042 // Reject array types
4043 if (ElementTy->isArrayType())
4044 return SemaRef.Diag(
4045 cast<FunctionDecl>(SemaRef.CurContext)->getPointOfInstantiation(),
4046 diag::err_invalid_use_of_array_type);
4047
4048 auto *ResourceTy =
4049 TheCall->getArg(0)->getType()->castAs<HLSLAttributedResourceType>();
4050 auto ReturnType = SemaRef.Context.getAddrSpaceQualType(
4051 ElementTy,
4052 getLangASFromResourceClass(ResourceTy->getAttrs().ResourceClass));
4053 ReturnType = SemaRef.Context.getPointerType(ReturnType);
4054 TheCall->setType(ReturnType);
4055
4056 break;
4057 }
4058 case Builtin::BI__builtin_hlsl_resource_load_with_status: {
4059 if (SemaRef.checkArgCount(TheCall, 3) ||
4060 CheckResourceHandle(&SemaRef, TheCall, 0) ||
4061 CheckArgTypeMatches(&SemaRef, TheCall->getArg(1),
4062 SemaRef.getASTContext().UnsignedIntTy) ||
4063 CheckArgTypeMatches(&SemaRef, TheCall->getArg(2),
4064 SemaRef.getASTContext().UnsignedIntTy) ||
4065 CheckModifiableLValue(&SemaRef, TheCall, 2))
4066 return true;
4067
4068 auto *ResourceTy =
4069 TheCall->getArg(0)->getType()->castAs<HLSLAttributedResourceType>();
4070 QualType ReturnType = ResourceTy->getContainedType();
4071 TheCall->setType(ReturnType);
4072
4073 break;
4074 }
4075 case Builtin::BI__builtin_hlsl_resource_load_with_status_typed: {
4076 if (SemaRef.checkArgCount(TheCall, 4) ||
4077 CheckResourceHandle(&SemaRef, TheCall, 0) ||
4078 CheckArgTypeMatches(&SemaRef, TheCall->getArg(1),
4079 SemaRef.getASTContext().UnsignedIntTy) ||
4080 CheckArgTypeMatches(&SemaRef, TheCall->getArg(2),
4081 SemaRef.getASTContext().UnsignedIntTy) ||
4082 CheckModifiableLValue(&SemaRef, TheCall, 2))
4083 return true;
4084
4085 QualType ReturnType = TheCall->getArg(3)->getType();
4086 assert(ReturnType->isPointerType() &&
4087 "expected pointer type for second argument");
4088 ReturnType = ReturnType->getPointeeType();
4089
4090 // Reject array types
4091 if (ReturnType->isArrayType())
4092 return SemaRef.Diag(
4093 cast<FunctionDecl>(SemaRef.CurContext)->getPointOfInstantiation(),
4094 diag::err_invalid_use_of_array_type);
4095
4096 TheCall->setType(ReturnType);
4097
4098 break;
4099 }
4100 case Builtin::BI__builtin_hlsl_resource_load_level:
4101 return CheckLoadLevelBuiltin(SemaRef, TheCall);
4102 case Builtin::BI__builtin_hlsl_resource_sample:
4104 case Builtin::BI__builtin_hlsl_resource_sample_bias:
4106 case Builtin::BI__builtin_hlsl_resource_sample_grad:
4108 case Builtin::BI__builtin_hlsl_resource_sample_level:
4110 case Builtin::BI__builtin_hlsl_resource_sample_cmp:
4112 case Builtin::BI__builtin_hlsl_resource_sample_cmp_level_zero:
4114 case Builtin::BI__builtin_hlsl_resource_calculate_lod:
4115 case Builtin::BI__builtin_hlsl_resource_calculate_lod_unclamped:
4116 return CheckCalculateLodBuiltin(SemaRef, TheCall);
4117 case Builtin::BI__builtin_hlsl_resource_gather:
4118 return CheckGatherBuiltin(SemaRef, TheCall, /*IsCmp=*/false);
4119 case Builtin::BI__builtin_hlsl_resource_gather_cmp:
4120 return CheckGatherBuiltin(SemaRef, TheCall, /*IsCmp=*/true);
4121 case Builtin::BI__builtin_hlsl_resource_uninitializedhandle: {
4122 assert(TheCall->getNumArgs() == 1 && "expected 1 arg");
4123 // Update return type to be the attributed resource type from arg0.
4124 QualType ResourceTy = TheCall->getArg(0)->getType();
4125 TheCall->setType(ResourceTy);
4126 break;
4127 }
4128 case Builtin::BI__builtin_hlsl_resource_handlefrombinding: {
4129 assert(TheCall->getNumArgs() == 6 && "expected 6 args");
4130 // Update return type to be the attributed resource type from arg0.
4131 QualType ResourceTy = TheCall->getArg(0)->getType();
4132 TheCall->setType(ResourceTy);
4133 break;
4134 }
4135 case Builtin::BI__builtin_hlsl_resource_handlefromimplicitbinding: {
4136 assert(TheCall->getNumArgs() == 6 && "expected 6 args");
4137 // Update return type to be the attributed resource type from arg0.
4138 QualType ResourceTy = TheCall->getArg(0)->getType();
4139 TheCall->setType(ResourceTy);
4140 break;
4141 }
4142 case Builtin::BI__builtin_hlsl_resource_counterhandlefromimplicitbinding: {
4143 assert(TheCall->getNumArgs() == 3 && "expected 3 args");
4144 ASTContext &AST = SemaRef.getASTContext();
4145 QualType MainHandleTy = TheCall->getArg(0)->getType();
4146 auto *MainResType = MainHandleTy->getAs<HLSLAttributedResourceType>();
4147 auto MainAttrs = MainResType->getAttrs();
4148 assert(!MainAttrs.IsCounter && "cannot create a counter from a counter");
4149 MainAttrs.IsCounter = true;
4150 QualType CounterHandleTy = AST.getHLSLAttributedResourceType(
4151 MainResType->getWrappedType(), MainResType->getContainedType(),
4152 MainAttrs);
4153 // Update return type to be the attributed resource type from arg0
4154 // with added IsCounter flag.
4155 TheCall->setType(CounterHandleTy);
4156 break;
4157 }
4158 case Builtin::BI__builtin_hlsl_and:
4159 case Builtin::BI__builtin_hlsl_or: {
4160 if (SemaRef.checkArgCount(TheCall, 2))
4161 return true;
4162 if (CheckScalarOrVectorOrMatrix(&SemaRef, TheCall, getASTContext().BoolTy,
4163 0))
4164 return true;
4165 if (CheckAllArgsHaveSameType(&SemaRef, TheCall))
4166 return true;
4167
4168 ExprResult A = TheCall->getArg(0);
4169 QualType ArgTyA = A.get()->getType();
4170 // return type is the same as the input type
4171 TheCall->setType(ArgTyA);
4172 break;
4173 }
4174 case Builtin::BI__builtin_hlsl_all:
4175 case Builtin::BI__builtin_hlsl_any: {
4176 if (SemaRef.checkArgCount(TheCall, 1))
4177 return true;
4178 if (CheckAnyScalarOrVector(&SemaRef, TheCall, 0))
4179 return true;
4180 break;
4181 }
4182 case Builtin::BI__builtin_hlsl_asdouble: {
4183 if (SemaRef.checkArgCount(TheCall, 2))
4184 return true;
4186 &SemaRef, TheCall,
4187 /*only check for uint*/ SemaRef.Context.UnsignedIntTy,
4188 /* arg index */ 0))
4189 return true;
4191 &SemaRef, TheCall,
4192 /*only check for uint*/ SemaRef.Context.UnsignedIntTy,
4193 /* arg index */ 1))
4194 return true;
4195 if (CheckAllArgsHaveSameType(&SemaRef, TheCall))
4196 return true;
4197
4198 SetElementTypeAsReturnType(&SemaRef, TheCall, getASTContext().DoubleTy);
4199 break;
4200 }
4201 case Builtin::BI__builtin_hlsl_elementwise_clamp: {
4202 if (SemaRef.BuiltinElementwiseTernaryMath(
4203 TheCall, /*ArgTyRestr=*/
4205 return true;
4206 break;
4207 }
4208 case Builtin::BI__builtin_hlsl_dot: {
4209 // arg count is checked by BuiltinVectorToScalarMath
4210 if (SemaRef.BuiltinVectorToScalarMath(TheCall))
4211 return true;
4213 return true;
4214 break;
4215 }
4216 case Builtin::BI__builtin_hlsl_elementwise_firstbithigh:
4217 case Builtin::BI__builtin_hlsl_elementwise_firstbitlow: {
4218 if (SemaRef.PrepareBuiltinElementwiseMathOneArgCall(TheCall))
4219 return true;
4220
4221 const Expr *Arg = TheCall->getArg(0);
4222 QualType ArgTy = Arg->getType();
4223 QualType EltTy = ArgTy;
4224
4225 QualType ResTy = SemaRef.Context.UnsignedIntTy;
4226
4227 if (auto *VecTy = EltTy->getAs<VectorType>()) {
4228 EltTy = VecTy->getElementType();
4229 ResTy = SemaRef.Context.getExtVectorType(ResTy, VecTy->getNumElements());
4230 }
4231
4232 if (!EltTy->isIntegerType()) {
4233 Diag(Arg->getBeginLoc(), diag::err_builtin_invalid_arg_type)
4234 << 1 << /* scalar or vector of */ 5 << /* integer ty */ 1
4235 << /* no fp */ 0 << ArgTy;
4236 return true;
4237 }
4238
4239 TheCall->setType(ResTy);
4240 break;
4241 }
4242 case Builtin::BI__builtin_hlsl_select: {
4243 if (SemaRef.checkArgCount(TheCall, 3))
4244 return true;
4245 if (CheckScalarOrVector(&SemaRef, TheCall, getASTContext().BoolTy, 0))
4246 return true;
4247 QualType ArgTy = TheCall->getArg(0)->getType();
4248 if (ArgTy->isBooleanType() && CheckBoolSelect(&SemaRef, TheCall))
4249 return true;
4250 auto *VTy = ArgTy->getAs<VectorType>();
4251 if (VTy && VTy->getElementType()->isBooleanType() &&
4252 CheckVectorSelect(&SemaRef, TheCall))
4253 return true;
4254 break;
4255 }
4256 case Builtin::BI__builtin_hlsl_elementwise_saturate:
4257 case Builtin::BI__builtin_hlsl_elementwise_rcp: {
4258 if (SemaRef.checkArgCount(TheCall, 1))
4259 return true;
4260 if (!TheCall->getArg(0)
4261 ->getType()
4262 ->hasFloatingRepresentation()) // half or float or double
4263 return SemaRef.Diag(TheCall->getArg(0)->getBeginLoc(),
4264 diag::err_builtin_invalid_arg_type)
4265 << /* ordinal */ 1 << /* scalar or vector */ 5 << /* no int */ 0
4266 << /* fp */ 1 << TheCall->getArg(0)->getType();
4267 if (SemaRef.PrepareBuiltinElementwiseMathOneArgCall(TheCall))
4268 return true;
4269 break;
4270 }
4271 case Builtin::BI__builtin_hlsl_elementwise_degrees:
4272 case Builtin::BI__builtin_hlsl_elementwise_radians:
4273 case Builtin::BI__builtin_hlsl_elementwise_rsqrt:
4274 case Builtin::BI__builtin_hlsl_elementwise_frac:
4275 case Builtin::BI__builtin_hlsl_elementwise_ddx_coarse:
4276 case Builtin::BI__builtin_hlsl_elementwise_ddy_coarse:
4277 case Builtin::BI__builtin_hlsl_elementwise_ddx_fine:
4278 case Builtin::BI__builtin_hlsl_elementwise_ddy_fine: {
4279 if (SemaRef.checkArgCount(TheCall, 1))
4280 return true;
4281 if (CheckAllArgTypesAreCorrect(&SemaRef, TheCall,
4283 return true;
4284 if (SemaRef.PrepareBuiltinElementwiseMathOneArgCall(TheCall))
4285 return true;
4286 break;
4287 }
4288 case Builtin::BI__builtin_hlsl_elementwise_isinf:
4289 case Builtin::BI__builtin_hlsl_elementwise_isnan: {
4290 if (SemaRef.checkArgCount(TheCall, 1))
4291 return true;
4292 if (CheckAllArgTypesAreCorrect(&SemaRef, TheCall,
4294 return true;
4295 if (SemaRef.PrepareBuiltinElementwiseMathOneArgCall(TheCall))
4296 return true;
4298 break;
4299 }
4300 case Builtin::BI__builtin_hlsl_lerp: {
4301 if (SemaRef.checkArgCount(TheCall, 3))
4302 return true;
4303 if (CheckAllArgTypesAreCorrect(&SemaRef, TheCall,
4305 return true;
4306 if (CheckAllArgsHaveSameType(&SemaRef, TheCall))
4307 return true;
4308 if (SemaRef.BuiltinElementwiseTernaryMath(TheCall))
4309 return true;
4310 break;
4311 }
4312 case Builtin::BI__builtin_hlsl_mad: {
4313 if (SemaRef.BuiltinElementwiseTernaryMath(
4314 TheCall, /*ArgTyRestr=*/
4316 return true;
4317 break;
4318 }
4319 case Builtin::BI__builtin_hlsl_mul: {
4320 if (SemaRef.checkArgCount(TheCall, 2))
4321 return true;
4322
4323 Expr *Arg0 = TheCall->getArg(0);
4324 Expr *Arg1 = TheCall->getArg(1);
4325 QualType Ty0 = Arg0->getType();
4326 QualType Ty1 = Arg1->getType();
4327
4328 auto getElemType = [](QualType T) -> QualType {
4329 if (const auto *VTy = T->getAs<VectorType>())
4330 return VTy->getElementType();
4331 if (const auto *MTy = T->getAs<ConstantMatrixType>())
4332 return MTy->getElementType();
4333 return T;
4334 };
4335
4336 QualType EltTy0 = getElemType(Ty0);
4337
4338 bool IsVec0 = Ty0->isVectorType();
4339 bool IsMat0 = Ty0->isConstantMatrixType();
4340 bool IsVec1 = Ty1->isVectorType();
4341 bool IsMat1 = Ty1->isConstantMatrixType();
4342
4343 QualType RetTy;
4344
4345 if (IsVec0 && IsMat1) {
4346 auto *MatTy = Ty1->castAs<ConstantMatrixType>();
4347 RetTy = getASTContext().getExtVectorType(EltTy0, MatTy->getNumColumns());
4348 } else if (IsMat0 && IsVec1) {
4349 auto *MatTy = Ty0->castAs<ConstantMatrixType>();
4350 RetTy = getASTContext().getExtVectorType(EltTy0, MatTy->getNumRows());
4351 } else {
4352 assert(IsMat0 && IsMat1);
4353 auto *MatTy0 = Ty0->castAs<ConstantMatrixType>();
4354 auto *MatTy1 = Ty1->castAs<ConstantMatrixType>();
4356 EltTy0, MatTy0->getNumRows(), MatTy1->getNumColumns());
4357 }
4358
4359 TheCall->setType(RetTy);
4360 break;
4361 }
4362 case Builtin::BI__builtin_hlsl_normalize: {
4363 if (SemaRef.checkArgCount(TheCall, 1))
4364 return true;
4365 if (CheckAllArgTypesAreCorrect(&SemaRef, TheCall,
4367 return true;
4368 ExprResult A = TheCall->getArg(0);
4369 QualType ArgTyA = A.get()->getType();
4370 // return type is the same as the input type
4371 TheCall->setType(ArgTyA);
4372 break;
4373 }
4374 case Builtin::BI__builtin_elementwise_fma: {
4375 if (SemaRef.checkArgCount(TheCall, 3) ||
4376 CheckAllArgsHaveSameType(&SemaRef, TheCall)) {
4377 return true;
4378 }
4379
4380 if (CheckAllArgTypesAreCorrect(&SemaRef, TheCall,
4382 return true;
4383
4384 ExprResult A = TheCall->getArg(0);
4385 QualType ArgTyA = A.get()->getType();
4386 // return type is the same as input type
4387 TheCall->setType(ArgTyA);
4388 break;
4389 }
4390 case Builtin::BI__builtin_hlsl_transpose: {
4391 if (SemaRef.checkArgCount(TheCall, 1))
4392 return true;
4393
4394 Expr *Arg = TheCall->getArg(0);
4395 QualType ArgTy = Arg->getType();
4396
4397 const auto *MatTy = ArgTy->getAs<ConstantMatrixType>();
4398 if (!MatTy) {
4399 SemaRef.Diag(Arg->getBeginLoc(), diag::err_builtin_invalid_arg_type)
4400 << 1 << /* matrix */ 3 << /* no int */ 0 << /* no fp */ 0 << ArgTy;
4401 return true;
4402 }
4403
4405 MatTy->getElementType(), MatTy->getNumColumns(), MatTy->getNumRows());
4406 TheCall->setType(RetTy);
4407 break;
4408 }
4409 case Builtin::BI__builtin_hlsl_elementwise_sign: {
4410 if (SemaRef.PrepareBuiltinElementwiseMathOneArgCall(TheCall))
4411 return true;
4412 if (CheckAllArgTypesAreCorrect(&SemaRef, TheCall,
4414 return true;
4416 break;
4417 }
4418 case Builtin::BI__builtin_hlsl_step: {
4419 if (SemaRef.checkArgCount(TheCall, 2))
4420 return true;
4421 if (CheckAllArgTypesAreCorrect(&SemaRef, TheCall,
4423 return true;
4424
4425 ExprResult A = TheCall->getArg(0);
4426 QualType ArgTyA = A.get()->getType();
4427 // return type is the same as the input type
4428 TheCall->setType(ArgTyA);
4429 break;
4430 }
4431 case Builtin::BI__builtin_hlsl_wave_active_all_equal: {
4432 if (SemaRef.checkArgCount(TheCall, 1))
4433 return true;
4434
4435 // Ensure input expr type is a scalar/vector
4436 if (CheckAnyScalarOrVector(&SemaRef, TheCall, 0))
4437 return true;
4438
4439 QualType InputTy = TheCall->getArg(0)->getType();
4440 ASTContext &Ctx = getASTContext();
4441
4442 QualType RetTy;
4443
4444 // If vector, construct bool vector of same size
4445 if (const auto *VecTy = InputTy->getAs<ExtVectorType>()) {
4446 unsigned NumElts = VecTy->getNumElements();
4447 RetTy = Ctx.getExtVectorType(Ctx.BoolTy, NumElts);
4448 } else {
4449 // Scalar case
4450 RetTy = Ctx.BoolTy;
4451 }
4452
4453 TheCall->setType(RetTy);
4454 break;
4455 }
4456 case Builtin::BI__builtin_hlsl_wave_active_max:
4457 case Builtin::BI__builtin_hlsl_wave_active_min:
4458 case Builtin::BI__builtin_hlsl_wave_active_sum:
4459 case Builtin::BI__builtin_hlsl_wave_active_product: {
4460 if (SemaRef.checkArgCount(TheCall, 1))
4461 return true;
4462
4463 // Ensure input expr type is a scalar/vector and the same as the return type
4464 if (CheckAnyScalarOrVector(&SemaRef, TheCall, 0))
4465 return true;
4466 if (CheckWaveActive(&SemaRef, TheCall))
4467 return true;
4468 ExprResult Expr = TheCall->getArg(0);
4469 QualType ArgTyExpr = Expr.get()->getType();
4470 TheCall->setType(ArgTyExpr);
4471 break;
4472 }
4473 case Builtin::BI__builtin_hlsl_wave_active_bit_or:
4474 case Builtin::BI__builtin_hlsl_wave_active_bit_xor:
4475 case Builtin::BI__builtin_hlsl_wave_active_bit_and: {
4476 if (SemaRef.checkArgCount(TheCall, 1))
4477 return true;
4478
4479 // Ensure input expr type is a scalar/vector
4480 if (CheckAnyScalarOrVector(&SemaRef, TheCall, 0))
4481 return true;
4482
4483 if (CheckWaveActive(&SemaRef, TheCall))
4484 return true;
4485
4486 // Ensure the expr type is interpretable as a uint or vector<uint>
4487 ExprResult Expr = TheCall->getArg(0);
4488 QualType ArgTyExpr = Expr.get()->getType();
4489 auto *VTy = ArgTyExpr->getAs<VectorType>();
4490 if (!(ArgTyExpr->isIntegerType() ||
4491 (VTy && VTy->getElementType()->isIntegerType()))) {
4492 SemaRef.Diag(TheCall->getArg(0)->getBeginLoc(),
4493 diag::err_builtin_invalid_arg_type)
4494 << ArgTyExpr << SemaRef.Context.UnsignedIntTy << 1 << 0 << 0;
4495 return true;
4496 }
4497
4498 // Ensure input expr type is the same as the return type
4499 TheCall->setType(ArgTyExpr);
4500 break;
4501 }
4502 case Builtin::BI__builtin_hlsl_interlocked_add: {
4503 // The builtin's prototype in Builtins.td is `void (...)`, so direct calls
4504 // to `__builtin_hlsl_interlocked_add` bypass argument checking entirely.
4505 // When reached via the synthesized `InterlockedAdd` overload set in
4506 // HLSLExternalSemaSource, overload resolution has already enforced the
4507 // argument count, integer-type matching, and the address-space requirement
4508 // on `dest`. The checks below are a safety net for callers that invoke the
4509 // builtin by its mangled name and would otherwise reach CodeGen unchecked.
4510 if (TheCall->getNumArgs() < 2) {
4511 SemaRef.Diag(TheCall->getEndLoc(),
4512 diag::err_typecheck_call_too_few_args_at_least)
4513 << /*callee_type=*/0 << /*min_arg_count=*/2 << TheCall->getNumArgs()
4514 << /*is_non_object=*/0 << TheCall->getSourceRange();
4515 return true;
4516 }
4517 if (SemaRef.checkArgCountAtMost(TheCall, 3))
4518 return true;
4519
4520 QualType DestTy = TheCall->getArg(0)->getType().getUnqualifiedType();
4521 if (!DestTy->isIntegerType()) {
4522 SemaRef.Diag(TheCall->getArg(0)->getBeginLoc(),
4523 diag::err_builtin_invalid_arg_type)
4524 << /*ordinal=*/1 << /*scalar*/ 1 << /*integer*/ 1 << /*no float*/ 0
4525 << DestTy;
4526 return true;
4527 }
4528
4529 if (CheckModifiableLValue(&SemaRef, TheCall, 0))
4530 return true;
4531
4532 if (CheckArgAddrSpaceOneOf(&SemaRef, TheCall, 0,
4534 return true;
4535
4536 if (CheckArgTypeMatches(&SemaRef, TheCall->getArg(1), DestTy))
4537 return true;
4538
4539 if (TheCall->getNumArgs() == 3) {
4540 if (CheckArgTypeMatches(&SemaRef, TheCall->getArg(2), DestTy))
4541 return true;
4542 if (CheckModifiableLValue(&SemaRef, TheCall, 2))
4543 return true;
4544 }
4545
4546 TheCall->setType(SemaRef.Context.VoidTy);
4547 break;
4548 }
4549 // Note these are llvm builtins that we want to catch invalid intrinsic
4550 // generation. Normal handling of these builtins will occur elsewhere.
4551 case Builtin::BI__builtin_elementwise_bitreverse: {
4552 // does not include a check for number of arguments
4553 // because that is done previously
4554 if (CheckAllArgTypesAreCorrect(&SemaRef, TheCall,
4556 return true;
4557 break;
4558 }
4559 case Builtin::BI__builtin_hlsl_wave_prefix_count_bits: {
4560 if (SemaRef.checkArgCount(TheCall, 1))
4561 return true;
4562
4563 QualType ArgType = TheCall->getArg(0)->getType();
4564
4565 if (!(ArgType->isScalarType())) {
4566 SemaRef.Diag(TheCall->getArg(0)->getBeginLoc(),
4567 diag::err_typecheck_expect_any_scalar_or_vector)
4568 << ArgType << 0;
4569 return true;
4570 }
4571
4572 if (!(ArgType->isBooleanType())) {
4573 SemaRef.Diag(TheCall->getArg(0)->getBeginLoc(),
4574 diag::err_typecheck_expect_any_scalar_or_vector)
4575 << ArgType << 0;
4576 return true;
4577 }
4578
4579 break;
4580 }
4581 case Builtin::BI__builtin_hlsl_wave_read_lane_at: {
4582 if (SemaRef.checkArgCount(TheCall, 2))
4583 return true;
4584
4585 // Ensure index parameter type can be interpreted as a uint
4586 ExprResult Index = TheCall->getArg(1);
4587 QualType ArgTyIndex = Index.get()->getType();
4588 if (!ArgTyIndex->isIntegerType()) {
4589 SemaRef.Diag(TheCall->getArg(1)->getBeginLoc(),
4590 diag::err_typecheck_convert_incompatible)
4591 << ArgTyIndex << SemaRef.Context.UnsignedIntTy << 1 << 0 << 0;
4592 return true;
4593 }
4594
4595 // Ensure input expr type is a scalar/vector and the same as the return type
4596 if (CheckAnyScalarOrVector(&SemaRef, TheCall, 0))
4597 return true;
4598
4599 ExprResult Expr = TheCall->getArg(0);
4600 QualType ArgTyExpr = Expr.get()->getType();
4601 TheCall->setType(ArgTyExpr);
4602 break;
4603 }
4604 case Builtin::BI__builtin_hlsl_wave_get_lane_index: {
4605 if (SemaRef.checkArgCount(TheCall, 0))
4606 return true;
4607 break;
4608 }
4609 case Builtin::BI__builtin_hlsl_wave_prefix_sum:
4610 case Builtin::BI__builtin_hlsl_wave_prefix_product: {
4611 if (SemaRef.checkArgCount(TheCall, 1))
4612 return true;
4613
4614 // Ensure input expr type is a scalar/vector and the same as the return type
4615 if (CheckAnyScalarOrVector(&SemaRef, TheCall, 0))
4616 return true;
4617 if (CheckWavePrefix(&SemaRef, TheCall))
4618 return true;
4619 ExprResult Expr = TheCall->getArg(0);
4620 QualType ArgTyExpr = Expr.get()->getType();
4621 TheCall->setType(ArgTyExpr);
4622 break;
4623 }
4624 case Builtin::BI__builtin_hlsl_quad_read_across_x:
4625 case Builtin::BI__builtin_hlsl_quad_read_across_y: {
4626 if (SemaRef.checkArgCount(TheCall, 1))
4627 return true;
4628
4629 if (CheckAnyScalarOrVector(&SemaRef, TheCall, 0))
4630 return true;
4631 if (CheckNotBoolScalarOrVector(&SemaRef, TheCall, 0))
4632 return true;
4633 ExprResult Expr = TheCall->getArg(0);
4634 QualType ArgTyExpr = Expr.get()->getType();
4635 TheCall->setType(ArgTyExpr);
4636 break;
4637 }
4638 case Builtin::BI__builtin_hlsl_elementwise_splitdouble: {
4639 if (SemaRef.checkArgCount(TheCall, 3))
4640 return true;
4641
4642 if (CheckScalarOrVectorOrMatrix(&SemaRef, TheCall, SemaRef.Context.DoubleTy,
4643 0) ||
4645 SemaRef.Context.UnsignedIntTy, 1) ||
4647 SemaRef.Context.UnsignedIntTy, 2))
4648 return true;
4649
4650 if (CheckModifiableLValue(&SemaRef, TheCall, 1) ||
4651 CheckModifiableLValue(&SemaRef, TheCall, 2))
4652 return true;
4653 break;
4654 }
4655 case Builtin::BI__builtin_hlsl_elementwise_clip: {
4656 if (SemaRef.checkArgCount(TheCall, 1))
4657 return true;
4658
4659 if (CheckScalarOrVector(&SemaRef, TheCall, SemaRef.Context.FloatTy, 0))
4660 return true;
4661 break;
4662 }
4663 case Builtin::BI__builtin_elementwise_acos:
4664 case Builtin::BI__builtin_elementwise_asin:
4665 case Builtin::BI__builtin_elementwise_atan:
4666 case Builtin::BI__builtin_elementwise_atan2:
4667 case Builtin::BI__builtin_elementwise_ceil:
4668 case Builtin::BI__builtin_elementwise_cos:
4669 case Builtin::BI__builtin_elementwise_cosh:
4670 case Builtin::BI__builtin_elementwise_exp:
4671 case Builtin::BI__builtin_elementwise_exp2:
4672 case Builtin::BI__builtin_elementwise_exp10:
4673 case Builtin::BI__builtin_elementwise_floor:
4674 case Builtin::BI__builtin_elementwise_fmod:
4675 case Builtin::BI__builtin_elementwise_log:
4676 case Builtin::BI__builtin_elementwise_log2:
4677 case Builtin::BI__builtin_elementwise_log10:
4678 case Builtin::BI__builtin_elementwise_pow:
4679 case Builtin::BI__builtin_elementwise_roundeven:
4680 case Builtin::BI__builtin_elementwise_sin:
4681 case Builtin::BI__builtin_elementwise_sinh:
4682 case Builtin::BI__builtin_elementwise_sqrt:
4683 case Builtin::BI__builtin_elementwise_tan:
4684 case Builtin::BI__builtin_elementwise_tanh:
4685 case Builtin::BI__builtin_elementwise_trunc: {
4686 if (CheckAllArgTypesAreCorrect(&SemaRef, TheCall,
4688 return true;
4689 break;
4690 }
4691 case Builtin::BI__builtin_hlsl_buffer_update_counter: {
4692 assert(TheCall->getNumArgs() == 2 && "expected 2 args");
4693 auto checkResTy = [](const HLSLAttributedResourceType *ResTy) -> bool {
4694 return !(ResTy->getAttrs().ResourceClass == ResourceClass::UAV &&
4695 ResTy->getAttrs().RawBuffer && ResTy->hasContainedType());
4696 };
4697 if (CheckResourceHandle(&SemaRef, TheCall, 0, checkResTy))
4698 return true;
4699 Expr *OffsetExpr = TheCall->getArg(1);
4700 std::optional<llvm::APSInt> Offset =
4701 OffsetExpr->getIntegerConstantExpr(SemaRef.getASTContext());
4702 if (!Offset.has_value() || std::abs(Offset->getExtValue()) != 1) {
4703 SemaRef.Diag(TheCall->getArg(1)->getBeginLoc(),
4704 diag::err_hlsl_expect_arg_const_int_one_or_neg_one)
4705 << 1;
4706 return true;
4707 }
4708 break;
4709 }
4710 case Builtin::BI__builtin_hlsl_elementwise_f16tof32: {
4711 if (SemaRef.checkArgCount(TheCall, 1))
4712 return true;
4713 if (CheckAllArgTypesAreCorrect(&SemaRef, TheCall,
4715 return true;
4716 // ensure arg integers are 32 bits
4717 if (CheckExpectedBitWidth(&SemaRef, TheCall, 0, 32))
4718 return true;
4719 // check it wasn't a bool type
4720 QualType ArgTy = TheCall->getArg(0)->getType();
4721 if (auto *VTy = ArgTy->getAs<VectorType>())
4722 ArgTy = VTy->getElementType();
4723 if (ArgTy->isBooleanType()) {
4724 SemaRef.Diag(TheCall->getArg(0)->getBeginLoc(),
4725 diag::err_builtin_invalid_arg_type)
4726 << 1 << /* scalar or vector of */ 5 << /* unsigned int */ 3
4727 << /* no fp */ 0 << TheCall->getArg(0)->getType();
4728 return true;
4729 }
4730
4731 SetElementTypeAsReturnType(&SemaRef, TheCall, getASTContext().FloatTy);
4732 break;
4733 }
4734 case Builtin::BI__builtin_hlsl_elementwise_f32tof16: {
4735 if (SemaRef.checkArgCount(TheCall, 1))
4736 return true;
4738 return true;
4740 getASTContext().UnsignedIntTy);
4741 break;
4742 }
4743 }
4744 return false;
4745}
4746
4750 WorkList.push_back(BaseTy);
4751 while (!WorkList.empty()) {
4752 QualType T = WorkList.pop_back_val();
4753 T = T.getCanonicalType().getUnqualifiedType();
4754 if (const auto *AT = dyn_cast<ConstantArrayType>(T)) {
4755 llvm::SmallVector<QualType, 16> ElementFields;
4756 // Generally I've avoided recursion in this algorithm, but arrays of
4757 // structs could be time-consuming to flatten and churn through on the
4758 // work list. Hopefully nesting arrays of structs containing arrays
4759 // of structs too many levels deep is unlikely.
4760 BuildFlattenedTypeList(AT->getElementType(), ElementFields);
4761 // Repeat the element's field list n times.
4762 for (uint64_t Ct = 0; Ct < AT->getZExtSize(); ++Ct)
4763 llvm::append_range(List, ElementFields);
4764 continue;
4765 }
4766 // Vectors can only have element types that are builtin types, so this can
4767 // add directly to the list instead of to the WorkList.
4768 if (const auto *VT = dyn_cast<VectorType>(T)) {
4769 List.insert(List.end(), VT->getNumElements(), VT->getElementType());
4770 continue;
4771 }
4772 if (const auto *MT = dyn_cast<ConstantMatrixType>(T)) {
4773 List.insert(List.end(), MT->getNumElementsFlattened(),
4774 MT->getElementType());
4775 continue;
4776 }
4777 if (const auto *RD = T->getAsCXXRecordDecl()) {
4778 if (RD->isStandardLayout())
4779 RD = RD->getStandardLayoutBaseWithFields();
4780
4781 // For types that we shouldn't decompose (unions and non-aggregates), just
4782 // add the type itself to the list.
4783 if (RD->isUnion() || !RD->isAggregate()) {
4784 List.push_back(T);
4785 continue;
4786 }
4787
4789 for (const auto *FD : RD->fields())
4790 if (!FD->isUnnamedBitField())
4791 FieldTypes.push_back(FD->getType());
4792 // Reverse the newly added sub-range.
4793 std::reverse(FieldTypes.begin(), FieldTypes.end());
4794 llvm::append_range(WorkList, FieldTypes);
4795
4796 // If this wasn't a standard layout type we may also have some base
4797 // classes to deal with.
4798 if (!RD->isStandardLayout()) {
4799 FieldTypes.clear();
4800 for (const auto &Base : RD->bases())
4801 FieldTypes.push_back(Base.getType());
4802 std::reverse(FieldTypes.begin(), FieldTypes.end());
4803 llvm::append_range(WorkList, FieldTypes);
4804 }
4805 continue;
4806 }
4807 List.push_back(T);
4808 }
4809}
4810
4812 if (QT.isNull())
4813 return false;
4814
4815 // Must be a class/struct.
4816 const auto *RD = QT->getAsCXXRecordDecl();
4817 if (!RD || RD->isUnion())
4818 return false;
4819
4820 // Cannot be a resource type or contain one.
4821 return !QT->isHLSLIntangibleType();
4822}
4823
4825 // null and array types are not allowed.
4826 if (QT.isNull() || QT->isArrayType())
4827 return false;
4828
4829 // UDT types are not allowed
4830 if (QT->isRecordType())
4831 return false;
4832
4833 if (QT->isBooleanType() || QT->isEnumeralType())
4834 return false;
4835
4836 // the only other valid builtin types are scalars or vectors
4837 if (QT->isArithmeticType()) {
4838 if (SemaRef.Context.getTypeSize(QT) / 8 > 16)
4839 return false;
4840 return true;
4841 }
4842
4843 if (const VectorType *VT = QT->getAs<VectorType>()) {
4844 int ArraySize = VT->getNumElements();
4845
4846 if (ArraySize > 4)
4847 return false;
4848
4849 QualType ElTy = VT->getElementType();
4850 if (ElTy->isBooleanType())
4851 return false;
4852
4853 if (SemaRef.Context.getTypeSize(QT) / 8 > 16)
4854 return false;
4855 return true;
4856 }
4857
4858 return false;
4859}
4860
4862 if (T1.isNull() || T2.isNull())
4863 return false;
4864
4867
4868 // If both types are the same canonical type, they're obviously compatible.
4869 if (SemaRef.getASTContext().hasSameType(T1, T2))
4870 return true;
4871
4873 BuildFlattenedTypeList(T1, T1Types);
4875 BuildFlattenedTypeList(T2, T2Types);
4876
4877 // Check the flattened type list
4878 return llvm::equal(T1Types, T2Types,
4879 [this](QualType LHS, QualType RHS) -> bool {
4880 return SemaRef.IsLayoutCompatible(LHS, RHS);
4881 });
4882}
4883
4885 FunctionDecl *Old) {
4886 if (New->getNumParams() != Old->getNumParams())
4887 return true;
4888
4889 bool HadError = false;
4890
4891 for (unsigned i = 0, e = New->getNumParams(); i != e; ++i) {
4892 ParmVarDecl *NewParam = New->getParamDecl(i);
4893 ParmVarDecl *OldParam = Old->getParamDecl(i);
4894
4895 // HLSL parameter declarations for inout and out must match between
4896 // declarations. In HLSL inout and out are ambiguous at the call site,
4897 // but have different calling behavior, so you cannot overload a
4898 // method based on a difference between inout and out annotations.
4899 const auto *NDAttr = NewParam->getAttr<HLSLParamModifierAttr>();
4900 unsigned NSpellingIdx = (NDAttr ? NDAttr->getSpellingListIndex() : 0);
4901 const auto *ODAttr = OldParam->getAttr<HLSLParamModifierAttr>();
4902 unsigned OSpellingIdx = (ODAttr ? ODAttr->getSpellingListIndex() : 0);
4903
4904 if (NSpellingIdx != OSpellingIdx) {
4905 SemaRef.Diag(NewParam->getLocation(),
4906 diag::err_hlsl_param_qualifier_mismatch)
4907 << NDAttr << NewParam;
4908 SemaRef.Diag(OldParam->getLocation(), diag::note_previous_declaration_as)
4909 << ODAttr;
4910 HadError = true;
4911 }
4912 }
4913 return HadError;
4914}
4915
4916// Generally follows PerformScalarCast, with cases reordered for
4917// clarity of what types are supported
4919
4920 if (!SrcTy->isScalarType() || !DestTy->isScalarType())
4921 return false;
4922
4923 if (SemaRef.getASTContext().hasSameUnqualifiedType(SrcTy, DestTy))
4924 return true;
4925
4926 switch (SrcTy->getScalarTypeKind()) {
4927 case Type::STK_Bool: // casting from bool is like casting from an integer
4928 case Type::STK_Integral:
4929 switch (DestTy->getScalarTypeKind()) {
4930 case Type::STK_Bool:
4931 case Type::STK_Integral:
4932 case Type::STK_Floating:
4933 return true;
4934 case Type::STK_CPointer:
4938 llvm_unreachable("HLSL doesn't support pointers.");
4941 llvm_unreachable("HLSL doesn't support complex types.");
4943 llvm_unreachable("HLSL doesn't support fixed point types.");
4944 }
4945 llvm_unreachable("Should have returned before this");
4946
4947 case Type::STK_Floating:
4948 switch (DestTy->getScalarTypeKind()) {
4949 case Type::STK_Floating:
4950 case Type::STK_Bool:
4951 case Type::STK_Integral:
4952 return true;
4955 llvm_unreachable("HLSL doesn't support complex types.");
4957 llvm_unreachable("HLSL doesn't support fixed point types.");
4958 case Type::STK_CPointer:
4962 llvm_unreachable("HLSL doesn't support pointers.");
4963 }
4964 llvm_unreachable("Should have returned before this");
4965
4967 case Type::STK_CPointer:
4970 llvm_unreachable("HLSL doesn't support pointers.");
4971
4973 llvm_unreachable("HLSL doesn't support fixed point types.");
4974
4977 llvm_unreachable("HLSL doesn't support complex types.");
4978 }
4979
4980 llvm_unreachable("Unhandled scalar cast");
4981}
4982
4983// Can perform an HLSL Aggregate splat cast if the Dest is an aggregate and the
4984// Src is a scalar, a vector of length 1, or a 1x1 matrix
4985// Or if Dest is a vector and Src is a vector of length 1 or a 1x1 matrix
4987
4988 QualType SrcTy = Src->getType();
4989 // Not a valid HLSL Aggregate Splat cast if Dest is a scalar or if this is
4990 // going to be a vector splat from a scalar.
4991 if ((SrcTy->isScalarType() && DestTy->isVectorType()) ||
4992 DestTy->isScalarType())
4993 return false;
4994
4995 const VectorType *SrcVecTy = SrcTy->getAs<VectorType>();
4996 const ConstantMatrixType *SrcMatTy = SrcTy->getAs<ConstantMatrixType>();
4997
4998 // Src isn't a scalar, a vector of length 1, or a 1x1 matrix
4999 if (!SrcTy->isScalarType() &&
5000 !(SrcVecTy && SrcVecTy->getNumElements() == 1) &&
5001 !(SrcMatTy && SrcMatTy->getNumElementsFlattened() == 1))
5002 return false;
5003
5004 if (SrcVecTy)
5005 SrcTy = SrcVecTy->getElementType();
5006 else if (SrcMatTy)
5007 SrcTy = SrcMatTy->getElementType();
5008
5010 BuildFlattenedTypeList(DestTy, DestTypes);
5011
5012 for (unsigned I = 0, Size = DestTypes.size(); I < Size; ++I) {
5013 if (DestTypes[I]->isUnionType())
5014 return false;
5015 if (!CanPerformScalarCast(SrcTy, DestTypes[I]))
5016 return false;
5017 }
5018 return true;
5019}
5020
5021// Can we perform an HLSL Elementwise cast?
5023
5024 // Don't handle casts where LHS and RHS are any combination of scalar/vector
5025 // There must be an aggregate somewhere
5026 QualType SrcTy = Src->getType();
5027 if (SrcTy->isScalarType()) // always a splat and this cast doesn't handle that
5028 return false;
5029
5030 if (SrcTy->isVectorType() &&
5031 (DestTy->isScalarType() || DestTy->isVectorType()))
5032 return false;
5033
5034 if (SrcTy->isConstantMatrixType() &&
5035 (DestTy->isScalarType() || DestTy->isConstantMatrixType()))
5036 return false;
5037
5039 BuildFlattenedTypeList(DestTy, DestTypes);
5041 BuildFlattenedTypeList(SrcTy, SrcTypes);
5042
5043 // Usually the size of SrcTypes must be greater than or equal to the size of
5044 // DestTypes.
5045 if (SrcTypes.size() < DestTypes.size())
5046 return false;
5047
5048 unsigned SrcSize = SrcTypes.size();
5049 unsigned DstSize = DestTypes.size();
5050 unsigned I;
5051 for (I = 0; I < DstSize && I < SrcSize; I++) {
5052 if (SrcTypes[I]->isUnionType() || DestTypes[I]->isUnionType())
5053 return false;
5054 if (!CanPerformScalarCast(SrcTypes[I], DestTypes[I])) {
5055 return false;
5056 }
5057 }
5058
5059 // check the rest of the source type for unions.
5060 for (; I < SrcSize; I++) {
5061 if (SrcTypes[I]->isUnionType())
5062 return false;
5063 }
5064 return true;
5065}
5066
5068 assert(Param->hasAttr<HLSLParamModifierAttr>() &&
5069 "We should not get here without a parameter modifier expression");
5070 const auto *Attr = Param->getAttr<HLSLParamModifierAttr>();
5071 if (Attr->getABI() == ParameterABI::Ordinary)
5072 return ExprResult(Arg);
5073
5074 bool IsInOut = Attr->getABI() == ParameterABI::HLSLInOut;
5075 if (!Arg->isLValue()) {
5076 SemaRef.Diag(Arg->getBeginLoc(), diag::error_hlsl_inout_lvalue)
5077 << Arg << (IsInOut ? 1 : 0);
5078 return ExprError();
5079 }
5080
5081 ASTContext &Ctx = SemaRef.getASTContext();
5082
5083 QualType Ty = Param->getType().getNonLValueExprType(Ctx);
5084
5085 // HLSL allows implicit conversions from scalars to vectors, but not the
5086 // inverse, so we need to disallow `inout` with scalar->vector or
5087 // scalar->matrix conversions.
5088 if (Arg->getType()->isScalarType() != Ty->isScalarType()) {
5089 SemaRef.Diag(Arg->getBeginLoc(), diag::error_hlsl_inout_scalar_extension)
5090 << Arg << (IsInOut ? 1 : 0);
5091 return ExprError();
5092 }
5093
5094 auto *ArgOpV = new (Ctx) OpaqueValueExpr(Param->getBeginLoc(), Arg->getType(),
5095 VK_LValue, OK_Ordinary, Arg);
5096
5097 // Parameters are initialized via copy initialization. This allows for
5098 // overload resolution of argument constructors.
5099 InitializedEntity Entity =
5101 ExprResult Res =
5102 SemaRef.PerformCopyInitialization(Entity, Param->getBeginLoc(), ArgOpV);
5103 if (Res.isInvalid())
5104 return ExprError();
5105 Expr *Base = Res.get();
5106 // After the cast, drop the reference type when creating the exprs.
5107 Ty = Ty.getNonLValueExprType(Ctx);
5108 auto *OpV = new (Ctx)
5109 OpaqueValueExpr(Param->getBeginLoc(), Ty, VK_LValue, OK_Ordinary, Base);
5110
5111 // Writebacks are performed with `=` binary operator, which allows for
5112 // overload resolution on writeback result expressions.
5113 Res = SemaRef.ActOnBinOp(SemaRef.getCurScope(), Param->getBeginLoc(),
5114 tok::equal, ArgOpV, OpV);
5115
5116 if (Res.isInvalid())
5117 return ExprError();
5118 Expr *Writeback = Res.get();
5119 auto *OutExpr =
5120 HLSLOutArgExpr::Create(Ctx, Ty, ArgOpV, OpV, Writeback, IsInOut);
5121
5122 return ExprResult(OutExpr);
5123}
5124
5126 // If HLSL gains support for references, all the cites that use this will need
5127 // to be updated with semantic checking to produce errors for
5128 // pointers/references.
5129 assert(!Ty->isReferenceType() &&
5130 "Pointer and reference types cannot be inout or out parameters");
5131 Ty = SemaRef.getASTContext().getLValueReferenceType(Ty);
5132 Ty.addRestrict();
5133 return Ty;
5134}
5135
5136// Returns true if the type has a non-empty constant buffer layout (if it is
5137// scalar, vector or matrix, or if it contains any of these.
5139 const Type *Ty = QT->getUnqualifiedDesugaredType();
5140 if (Ty->isScalarType() || Ty->isVectorType() || Ty->isMatrixType())
5141 return true;
5142
5144 return false;
5145
5146 if (const auto *RD = Ty->getAsCXXRecordDecl()) {
5147 for (const auto *FD : RD->fields()) {
5149 return true;
5150 }
5151 assert(RD->getNumBases() <= 1 &&
5152 "HLSL doesn't support multiple inheritance");
5153 return RD->getNumBases()
5154 ? hasConstantBufferLayout(RD->bases_begin()->getType())
5155 : false;
5156 }
5157
5158 if (const auto *AT = dyn_cast<ArrayType>(Ty)) {
5159 if (const auto *CAT = dyn_cast<ConstantArrayType>(AT))
5160 if (isZeroSizedArray(CAT))
5161 return false;
5163 }
5164
5165 return false;
5166}
5167
5168static bool IsDefaultBufferConstantDecl(const ASTContext &Ctx, VarDecl *VD) {
5169 bool IsVulkan =
5170 Ctx.getTargetInfo().getTriple().getOS() == llvm::Triple::Vulkan;
5171 bool IsVKPushConstant = IsVulkan && VD->hasAttr<HLSLVkPushConstantAttr>();
5172 QualType QT = VD->getType();
5173 return VD->getDeclContext()->isTranslationUnit() &&
5174 QT.getAddressSpace() == LangAS::Default &&
5175 VD->getStorageClass() != SC_Static &&
5176 !VD->hasAttr<HLSLVkConstantIdAttr>() && !IsVKPushConstant &&
5178}
5179
5181 // The variable already has an address space (groupshared for ex).
5182 if (Decl->getType().hasAddressSpace())
5183 return;
5184
5185 if (Decl->getType()->isDependentType())
5186 return;
5187
5188 QualType Type = Decl->getType();
5189
5190 if (Decl->hasAttr<HLSLVkExtBuiltinInputAttr>()) {
5191 LangAS ImplAS = LangAS::hlsl_input;
5192 Type = SemaRef.getASTContext().getAddrSpaceQualType(Type, ImplAS);
5193 Decl->setType(Type);
5194 return;
5195 }
5196
5197 if (Decl->hasAttr<HLSLVkExtBuiltinOutputAttr>()) {
5198 LangAS ImplAS = LangAS::hlsl_output;
5199 Type = SemaRef.getASTContext().getAddrSpaceQualType(Type, ImplAS);
5200 Decl->setType(Type);
5201
5202 // HLSL uses `static` differently than C++. For BuiltIn output, the static
5203 // does not imply private to the module scope.
5204 // Marking it as external to reflect the semantic this attribute brings.
5205 // See https://github.com/microsoft/hlsl-specs/issues/350
5206 Decl->setStorageClass(SC_Extern);
5207 return;
5208 }
5209
5210 bool IsVulkan = getASTContext().getTargetInfo().getTriple().getOS() ==
5211 llvm::Triple::Vulkan;
5212 if (IsVulkan && Decl->hasAttr<HLSLVkPushConstantAttr>()) {
5213 if (HasDeclaredAPushConstant)
5214 SemaRef.Diag(Decl->getLocation(), diag::err_hlsl_push_constant_unique);
5215
5217 Type = SemaRef.getASTContext().getAddrSpaceQualType(Type, ImplAS);
5218 Decl->setType(Type);
5219 HasDeclaredAPushConstant = true;
5220 return;
5221 }
5222
5223 if (Type->isSamplerT() || Type->isVoidType())
5224 return;
5225
5226 // Resource handles.
5228 return;
5229
5230 // Only static globals belong to the Private address space.
5231 // Non-static globals belongs to the cbuffer.
5232 if (Decl->getStorageClass() != SC_Static && !Decl->isStaticDataMember())
5233 return;
5234
5236 Type = SemaRef.getASTContext().getAddrSpaceQualType(Type, ImplAS);
5237 Decl->setType(Type);
5238}
5239
5240namespace {
5241
5242// Helper class for assigning bindings to resources declared within a struct.
5243// It keeps track of all binding attributes declared on a struct instance, and
5244// the offsets for each register type that have been assigned so far.
5245// Handles both explicit and implicit bindings.
5246class StructBindingContext {
5247 // Bindings and offsets per register type. We only need to support four
5248 // register types - SRV (u), UAV (t), CBuffer (c), and Sampler (s).
5249 HLSLResourceBindingAttr *RegBindingsAttrs[4];
5250 unsigned RegBindingOffset[4];
5251
5252 // Make sure the RegisterType values are what we expect
5253 static_assert(static_cast<unsigned>(RegisterType::SRV) == 0 &&
5254 static_cast<unsigned>(RegisterType::UAV) == 1 &&
5255 static_cast<unsigned>(RegisterType::CBuffer) == 2 &&
5256 static_cast<unsigned>(RegisterType::Sampler) == 3,
5257 "unexpected register type values");
5258
5259 // Vulkan binding attribute does not vary by register type.
5260 HLSLVkBindingAttr *VkBindingAttr;
5261 unsigned VkBindingOffset;
5262
5263public:
5264 // Constructor: gather all binding attributes on a struct instance and
5265 // initialize offsets.
5266 StructBindingContext(VarDecl *VD) {
5267 for (unsigned i = 0; i < 4; ++i) {
5268 RegBindingsAttrs[i] = nullptr;
5269 RegBindingOffset[i] = 0;
5270 }
5271 VkBindingAttr = nullptr;
5272 VkBindingOffset = 0;
5273
5274 ASTContext &AST = VD->getASTContext();
5275 bool IsSpirv = AST.getTargetInfo().getTriple().isSPIRV();
5276
5277 for (Attr *A : VD->attrs()) {
5278 if (auto *RBA = dyn_cast<HLSLResourceBindingAttr>(A)) {
5279 RegisterType RegType = RBA->getRegisterType();
5280 unsigned RegTypeIdx = static_cast<unsigned>(RegType);
5281 // Ignore unsupported register annotations, such as 'c' or 'i'.
5282 if (RegTypeIdx < 4)
5283 RegBindingsAttrs[RegTypeIdx] = RBA;
5284 continue;
5285 }
5286 // Gather the Vulkan binding attributes only if the target is SPIR-V.
5287 if (IsSpirv) {
5288 if (auto *VBA = dyn_cast<HLSLVkBindingAttr>(A))
5289 VkBindingAttr = VBA;
5290 }
5291 }
5292 }
5293
5294 // Creates a binding attribute for a resource based on the gathered attributes
5295 // and the required register type and range.
5296 Attr *createBindingAttr(SemaHLSL &S, ASTContext &AST, RegisterType RegType,
5297 unsigned Range, bool HasCounter) {
5298 assert(static_cast<unsigned>(RegType) < 4 && "unexpected register type");
5299
5300 if (VkBindingAttr) {
5301 unsigned Offset = VkBindingOffset;
5302 VkBindingOffset += Range;
5303 return HLSLVkBindingAttr::CreateImplicit(
5304 AST, VkBindingAttr->getBinding() + Offset, VkBindingAttr->getSet(),
5305 VkBindingAttr->getRange());
5306 }
5307
5308 HLSLResourceBindingAttr *RBA =
5309 RegBindingsAttrs[static_cast<unsigned>(RegType)];
5310 HLSLResourceBindingAttr *NewAttr = nullptr;
5311
5312 if (RBA && RBA->hasRegisterSlot()) {
5313 // Explicit binding - create a new attribute with offseted slot number
5314 // based on the required register type.
5315 unsigned Offset = RegBindingOffset[static_cast<unsigned>(RegType)];
5316 RegBindingOffset[static_cast<unsigned>(RegType)] += Range;
5317
5318 unsigned NewSlotNumber = RBA->getSlotNumber() + Offset;
5319 StringRef NewSlotNumberStr =
5320 createRegisterString(AST, RBA->getRegisterType(), NewSlotNumber);
5321 NewAttr = HLSLResourceBindingAttr::CreateImplicit(
5322 AST, NewSlotNumberStr, RBA->getSpace(), RBA->getRange());
5323 NewAttr->setBinding(RegType, NewSlotNumber, RBA->getSpaceNumber());
5324 } else {
5325 // No binding attribute or space-only binding - create a binding
5326 // attribute for implicit binding.
5327 NewAttr = HLSLResourceBindingAttr::CreateImplicit(AST, "", "0", {});
5328 NewAttr->setBinding(RegType, std::nullopt,
5329 RBA ? RBA->getSpaceNumber() : 0);
5330 NewAttr->setImplicitBindingOrderID(S.getNextImplicitBindingOrderID());
5331 }
5332 if (HasCounter)
5333 NewAttr->setImplicitCounterBindingOrderID(
5335 return NewAttr;
5336 }
5337};
5338
5339// Creates a global variable declaration for a resource field embedded in a
5340// struct, assigns it a binding, initializes it, and associates it with the
5341// struct declaration via an HLSLAssociatedResourceDeclAttr.
5342static void createGlobalResourceDeclForStruct(
5343 Sema &S, VarDecl *ParentVD, SourceLocation Loc, IdentifierInfo *Id,
5344 QualType ResTy, StructBindingContext &BindingCtx) {
5345 assert(isResourceRecordTypeOrArrayOf(ResTy) &&
5346 "expected resource type or array of resources");
5347
5348 DeclContext *DC = ParentVD->getNonTransparentDeclContext();
5349 assert(DC->isTranslationUnit() && "expected translation unit decl context");
5350
5351 ASTContext &AST = S.getASTContext();
5352 VarDecl *ResDecl =
5353 VarDecl::Create(AST, DC, Loc, Loc, Id, ResTy, nullptr, SC_None);
5354
5355 unsigned Range = 1;
5356 const Type *SingleResTy = ResTy.getTypePtr()->getUnqualifiedDesugaredType();
5357 while (const auto *AT = dyn_cast<ArrayType>(SingleResTy)) {
5358 const auto *CAT = dyn_cast<ConstantArrayType>(AT);
5359 Range = CAT ? (Range * CAT->getSize().getZExtValue()) : 0;
5360 SingleResTy =
5362 }
5363 const HLSLAttributedResourceType *ResHandleTy =
5364 HLSLAttributedResourceType::findHandleTypeOnResource(SingleResTy);
5365
5366 // Add a binding attribute to the global resource declaration.
5367 bool HasCounter = hasCounterHandle(SingleResTy->getAsCXXRecordDecl());
5368 Attr *BindingAttr = BindingCtx.createBindingAttr(
5369 S.HLSL(), AST, getRegisterType(ResHandleTy), Range, HasCounter);
5370 ResDecl->addAttr(BindingAttr);
5371 ResDecl->addAttr(InternalLinkageAttr::CreateImplicit(AST));
5372 ResDecl->setImplicit();
5373
5374 if (Range == 1)
5375 S.HLSL().initGlobalResourceDecl(ResDecl);
5376 else
5377 S.HLSL().initGlobalResourceArrayDecl(ResDecl);
5378
5379 ParentVD->addAttr(
5380 HLSLAssociatedResourceDeclAttr::CreateImplicit(AST, ResDecl));
5381 DC->addDecl(ResDecl);
5382
5383 DeclGroupRef DG(ResDecl);
5385}
5386
5387static void handleArrayOfStructWithResources(
5388 Sema &S, VarDecl *ParentVD, const ConstantArrayType *CAT,
5389 EmbeddedResourceNameBuilder &NameBuilder, StructBindingContext &BindingCtx);
5390
5391// Scans base and all fields of a struct/class type to find all embedded
5392// resources or resource arrays. Creates a global variable for each resource
5393// found.
5394static void handleStructWithResources(Sema &S, VarDecl *ParentVD,
5395 const CXXRecordDecl *RD,
5396 EmbeddedResourceNameBuilder &NameBuilder,
5397 StructBindingContext &BindingCtx) {
5398
5399 // Scan the base classes.
5400 assert(RD->getNumBases() <= 1 && "HLSL doesn't support multiple inheritance");
5401 const auto *BasesIt = RD->bases_begin();
5402 if (BasesIt != RD->bases_end()) {
5403 QualType QT = BasesIt->getType();
5404 if (QT->isHLSLIntangibleType()) {
5405 CXXRecordDecl *BaseRD = QT->getAsCXXRecordDecl();
5406 NameBuilder.pushBaseName(BaseRD->getName());
5407 handleStructWithResources(S, ParentVD, BaseRD, NameBuilder, BindingCtx);
5408 NameBuilder.pop();
5409 }
5410 }
5411 // Process this class fields.
5412 for (const FieldDecl *FD : RD->fields()) {
5413 QualType FDTy = FD->getType().getCanonicalType();
5414 if (!FDTy->isHLSLIntangibleType())
5415 continue;
5416
5417 NameBuilder.pushName(FD->getName());
5418
5420 IdentifierInfo *II = NameBuilder.getNameAsIdentifier(S.getASTContext());
5421 createGlobalResourceDeclForStruct(S, ParentVD, FD->getLocation(), II,
5422 FDTy, BindingCtx);
5423 } else if (const auto *RD = FDTy->getAsCXXRecordDecl()) {
5424 handleStructWithResources(S, ParentVD, RD, NameBuilder, BindingCtx);
5425
5426 } else if (const auto *ArrayTy = dyn_cast<ConstantArrayType>(FDTy)) {
5427 assert(!FDTy->isHLSLResourceRecordArray() &&
5428 "resource arrays should have been already handled");
5429 handleArrayOfStructWithResources(S, ParentVD, ArrayTy, NameBuilder,
5430 BindingCtx);
5431 }
5432 NameBuilder.pop();
5433 }
5434}
5435
5436// Processes array of structs with resources.
5437static void
5438handleArrayOfStructWithResources(Sema &S, VarDecl *ParentVD,
5439 const ConstantArrayType *CAT,
5440 EmbeddedResourceNameBuilder &NameBuilder,
5441 StructBindingContext &BindingCtx) {
5442
5443 QualType ElementTy = CAT->getElementType().getCanonicalType();
5444 assert(ElementTy->isHLSLIntangibleType() && "Expected HLSL intangible type");
5445
5446 const ConstantArrayType *SubCAT = dyn_cast<ConstantArrayType>(ElementTy);
5447 const CXXRecordDecl *ElementRD = ElementTy->getAsCXXRecordDecl();
5448
5449 if (!SubCAT && !ElementRD)
5450 return;
5451
5452 for (unsigned I = 0, E = CAT->getSize().getZExtValue(); I < E; ++I) {
5453 NameBuilder.pushArrayIndex(I);
5454 if (ElementRD)
5455 handleStructWithResources(S, ParentVD, ElementRD, NameBuilder,
5456 BindingCtx);
5457 else
5458 handleArrayOfStructWithResources(S, ParentVD, SubCAT, NameBuilder,
5459 BindingCtx);
5460 NameBuilder.pop();
5461 }
5462}
5463
5464} // namespace
5465
5466// Scans all fields of a user-defined struct (or array of structs)
5467// to find all embedded resources or resource arrays. For each resource
5468// a global variable of the resource type is created and associated
5469// with the parent declaration (VD) through a HLSLAssociatedResourceDeclAttr
5470// attribute.
5471void SemaHLSL::handleGlobalStructOrArrayOfWithResources(VarDecl *VD) {
5472 EmbeddedResourceNameBuilder NameBuilder(VD->getName());
5473 StructBindingContext BindingCtx(VD);
5474
5475 const Type *VDTy = VD->getType().getTypePtr();
5476 assert(VDTy->isHLSLIntangibleType() && !isResourceRecordTypeOrArrayOf(VD) &&
5477 "Expected non-resource struct or array type");
5478
5479 if (const CXXRecordDecl *RD = VDTy->getAsCXXRecordDecl()) {
5480 handleStructWithResources(SemaRef, VD, RD, NameBuilder, BindingCtx);
5481 return;
5482 }
5483
5484 if (const auto *CAT = dyn_cast<ConstantArrayType>(VDTy)) {
5485 handleArrayOfStructWithResources(SemaRef, VD, CAT, NameBuilder, BindingCtx);
5486 return;
5487 }
5488}
5489
5491 if (VD->hasGlobalStorage()) {
5492 // make sure the declaration has a complete type
5493 if (SemaRef.RequireCompleteType(
5494 VD->getLocation(),
5495 SemaRef.getASTContext().getBaseElementType(VD->getType()),
5496 diag::err_typecheck_decl_incomplete_type)) {
5497 VD->setInvalidDecl();
5499 return;
5500 }
5501
5502 // Global variables outside a cbuffer block that are not a resource, static,
5503 // groupshared, or an empty array or struct belong to the default constant
5504 // buffer $Globals (to be created at the end of the translation unit).
5506 // update address space to hlsl_constant
5509 VD->setType(NewTy);
5510 DefaultCBufferDecls.push_back(VD);
5511 }
5512
5513 // find all resources bindings on decl
5514 if (VD->getType()->isHLSLIntangibleType())
5515 collectResourceBindingsOnVarDecl(VD);
5516
5517 if (VD->hasAttr<HLSLVkConstantIdAttr>())
5519
5521 VD->getStorageClass() != SC_Static) {
5522 // Add internal linkage attribute to non-static resource variables. The
5523 // global externally visible storage is accessed through the handle, which
5524 // is a member. The variable itself is not externally visible.
5525 VD->addAttr(InternalLinkageAttr::CreateImplicit(getASTContext()));
5526 }
5527
5528 // process explicit bindings
5529 processExplicitBindingsOnDecl(VD);
5530
5531 // Add implicit binding attribute to non-static resource arrays.
5532 if (VD->getType()->isHLSLResourceRecordArray() &&
5533 VD->getStorageClass() != SC_Static) {
5534 // If the resource array does not have an explicit binding attribute,
5535 // create an implicit one. It will be used to transfer implicit binding
5536 // order_ID to codegen.
5537 ResourceBindingAttrs Binding(VD);
5538 if (!Binding.isExplicit()) {
5539 uint32_t OrderID = getNextImplicitBindingOrderID();
5540 if (Binding.hasBinding())
5541 Binding.setImplicitOrderID(OrderID);
5542 else {
5545 OrderID);
5546 // Re-create the binding object to pick up the new attribute.
5547 Binding = ResourceBindingAttrs(VD);
5548 }
5549 }
5550
5551 // Get to the base type of a potentially multi-dimensional array.
5553
5554 const CXXRecordDecl *RD = Ty->getAsCXXRecordDecl();
5555 if (hasCounterHandle(RD)) {
5556 if (!Binding.hasCounterImplicitOrderID()) {
5557 uint32_t OrderID = getNextImplicitBindingOrderID();
5558 Binding.setCounterImplicitOrderID(OrderID);
5559 }
5560 }
5561 }
5562
5563 // Process resources in user-defined structs, or arrays of such structs.
5564 const Type *VDTy = VD->getType().getTypePtr();
5565 if (VD->getStorageClass() != SC_Static && VDTy->isHLSLIntangibleType() &&
5567 handleGlobalStructOrArrayOfWithResources(VD);
5568
5569 // Mark groupshared variables as extern so they will have
5570 // external storage and won't be default initialized
5571 if (VD->hasAttr<HLSLGroupSharedAddressSpaceAttr>())
5573 }
5574
5576}
5577
5579 assert(VD->getType()->isHLSLResourceRecord() &&
5580 "expected resource record type");
5581
5582 ASTContext &AST = SemaRef.getASTContext();
5583 uint64_t UIntTySize = AST.getTypeSize(AST.UnsignedIntTy);
5584 uint64_t IntTySize = AST.getTypeSize(AST.IntTy);
5585
5586 // Gather resource binding attributes.
5587 ResourceBindingAttrs Binding(VD);
5588
5589 // Find correct initialization method and create its arguments.
5590 QualType ResourceTy = VD->getType();
5591 CXXRecordDecl *ResourceDecl = ResourceTy->getAsCXXRecordDecl();
5592 CXXMethodDecl *CreateMethod = nullptr;
5594
5595 bool HasCounter = hasCounterHandle(ResourceDecl);
5596 const char *CreateMethodName;
5597 if (Binding.isExplicit())
5598 CreateMethodName = HasCounter ? "__createFromBindingWithImplicitCounter"
5599 : "__createFromBinding";
5600 else
5601 CreateMethodName = HasCounter
5602 ? "__createFromImplicitBindingWithImplicitCounter"
5603 : "__createFromImplicitBinding";
5604
5605 CreateMethod =
5606 lookupMethod(SemaRef, ResourceDecl, CreateMethodName, VD->getLocation());
5607
5608 if (!CreateMethod) {
5609 // This can happen if someone creates a struct that looks like an HLSL
5610 // resource record but does not have the required static create method.
5611 // No binding will be generated for it.
5612 assert(!ResourceDecl->isImplicit() &&
5613 "create method lookup should always succeed for built-in resource "
5614 "records");
5615 return false;
5616 }
5617
5618 if (Binding.isExplicit()) {
5619 IntegerLiteral *RegSlot =
5620 IntegerLiteral::Create(AST, llvm::APInt(UIntTySize, Binding.getSlot()),
5622 Args.push_back(RegSlot);
5623 } else {
5624 uint32_t OrderID = (Binding.hasImplicitOrderID())
5625 ? Binding.getImplicitOrderID()
5627 IntegerLiteral *OrderId =
5628 IntegerLiteral::Create(AST, llvm::APInt(UIntTySize, OrderID),
5630 Args.push_back(OrderId);
5631 }
5632
5633 IntegerLiteral *Space =
5634 IntegerLiteral::Create(AST, llvm::APInt(UIntTySize, Binding.getSpace()),
5636 Args.push_back(Space);
5637
5639 AST, llvm::APInt(IntTySize, 1), AST.IntTy, SourceLocation());
5640 Args.push_back(RangeSize);
5641
5643 AST, llvm::APInt(UIntTySize, 0), AST.UnsignedIntTy, SourceLocation());
5644 Args.push_back(Index);
5645
5646 StringRef VarName = VD->getName();
5648 AST, VarName, StringLiteralKind::Ordinary, false,
5649 AST.getStringLiteralArrayType(AST.CharTy.withConst(), VarName.size()),
5650 SourceLocation());
5652 AST, AST.getPointerType(AST.CharTy.withConst()), CK_ArrayToPointerDecay,
5653 Name, nullptr, VK_PRValue, FPOptionsOverride());
5654 Args.push_back(NameCast);
5655
5656 if (HasCounter) {
5657 // Will this be in the correct order?
5658 uint32_t CounterOrderID = getNextImplicitBindingOrderID();
5659 IntegerLiteral *CounterId =
5660 IntegerLiteral::Create(AST, llvm::APInt(UIntTySize, CounterOrderID),
5662 Args.push_back(CounterId);
5663 }
5664
5665 // Make sure the create method template is instantiated and emitted.
5666 if (!CreateMethod->isDefined() && CreateMethod->isTemplateInstantiation())
5667 SemaRef.InstantiateFunctionDefinition(VD->getLocation(), CreateMethod,
5668 true);
5669
5670 // Create CallExpr with a call to the static method and set it as the decl
5671 // initialization.
5673 AST, NestedNameSpecifierLoc(), SourceLocation(), CreateMethod, false,
5674 CreateMethod->getNameInfo(), CreateMethod->getType(), VK_PRValue);
5675
5676 auto *ImpCast = ImplicitCastExpr::Create(
5677 AST, AST.getPointerType(CreateMethod->getType()),
5678 CK_FunctionToPointerDecay, DRE, nullptr, VK_PRValue, FPOptionsOverride());
5679
5680 CallExpr *InitExpr =
5681 CallExpr::Create(AST, ImpCast, Args, ResourceTy, VK_PRValue,
5683 VD->setInit(InitExpr);
5685 SemaRef.CheckCompleteVariableDeclaration(VD);
5686 return true;
5687}
5688
5690 assert(VD->getType()->isHLSLResourceRecordArray() &&
5691 "expected array of resource records");
5692
5693 // Individual resources in a resource array are not initialized here. They
5694 // are initialized later on during codegen when the individual resources are
5695 // accessed. Codegen will emit a call to the resource initialization method
5696 // with the specified array index. We need to make sure though that the method
5697 // for the specific resource type is instantiated, so codegen can emit a call
5698 // to it when the array element is accessed.
5699
5700 // Find correct initialization method based on the resource binding
5701 // information.
5702 ASTContext &AST = SemaRef.getASTContext();
5703 QualType ResElementTy = AST.getBaseElementType(VD->getType());
5704 CXXRecordDecl *ResourceDecl = ResElementTy->getAsCXXRecordDecl();
5705 CXXMethodDecl *CreateMethod = nullptr;
5706
5707 bool HasCounter = hasCounterHandle(ResourceDecl);
5708 ResourceBindingAttrs ResourceAttrs(VD);
5709 if (ResourceAttrs.isExplicit())
5710 // Resource has explicit binding.
5711 CreateMethod =
5712 lookupMethod(SemaRef, ResourceDecl,
5713 HasCounter ? "__createFromBindingWithImplicitCounter"
5714 : "__createFromBinding",
5715 VD->getLocation());
5716 else
5717 // Resource has implicit binding.
5718 CreateMethod = lookupMethod(
5719 SemaRef, ResourceDecl,
5720 HasCounter ? "__createFromImplicitBindingWithImplicitCounter"
5721 : "__createFromImplicitBinding",
5722 VD->getLocation());
5723
5724 if (!CreateMethod)
5725 return false;
5726
5727 // Make sure the create method template is instantiated and emitted.
5728 if (!CreateMethod->isDefined() && CreateMethod->isTemplateInstantiation())
5729 SemaRef.InstantiateFunctionDefinition(VD->getLocation(), CreateMethod,
5730 true);
5731 return true;
5732}
5733
5734// Returns true if the initialization has been handled.
5735// Returns false to use default initialization.
5737 // Objects in the hlsl_constant address space are initialized
5738 // externally, so don't synthesize an implicit initializer.
5740 return true;
5741
5742 if (VD->hasGlobalStorage() && VD->getStorageClass() != SC_Static) {
5743 const Type *Ty = VD->getType().getTypePtr();
5745 return true;
5747 return true;
5748 }
5749
5750 // User-defined structs/classes do not have constructors.
5751 // When declared at a global scope, they are part of the constant buffer
5752 // and should not be initialized by the compiler.
5753 // When declared at a local scope, they are not initialized.
5754 // Also applies to arrays of user-defined structs/classes.
5755 const Type *Ty = VD->getType()->getUnqualifiedDesugaredType();
5756 while (Ty->isArrayType())
5758 if (CXXRecordDecl *RD = Ty->getAsCXXRecordDecl())
5759 return !RD->isHLSLBuiltinRecord();
5760
5761 return false;
5762}
5763
5764std::optional<const DeclBindingInfo *> SemaHLSL::inferGlobalBinding(Expr *E) {
5765 if (auto *Ternary = dyn_cast<ConditionalOperator>(E)) {
5766 auto TrueInfo = inferGlobalBinding(Ternary->getTrueExpr());
5767 auto FalseInfo = inferGlobalBinding(Ternary->getFalseExpr());
5768 if (!TrueInfo || !FalseInfo)
5769 return std::nullopt;
5770 if (*TrueInfo != *FalseInfo)
5771 return std::nullopt;
5772 return TrueInfo;
5773 }
5774
5775 if (auto *ASE = dyn_cast<ArraySubscriptExpr>(E))
5776 E = ASE->getBase()->IgnoreParenImpCasts();
5777
5778 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParens()))
5779 if (VarDecl *VD = dyn_cast<VarDecl>(DRE->getDecl())) {
5780 const Type *Ty = VD->getType()->getUnqualifiedDesugaredType();
5781 if (Ty->isArrayType())
5783
5784 if (const auto *AttrResType =
5785 HLSLAttributedResourceType::findHandleTypeOnResource(Ty)) {
5786 ResourceClass RC = AttrResType->getAttrs().ResourceClass;
5787 return Bindings.getDeclBindingInfo(VD, RC);
5788 }
5789 }
5790
5791 return nullptr;
5792}
5793
5794void SemaHLSL::trackLocalResource(VarDecl *VD, Expr *E) {
5795 std::optional<const DeclBindingInfo *> ExprBinding = inferGlobalBinding(E);
5796 if (!ExprBinding) {
5797 SemaRef.Diag(E->getBeginLoc(),
5798 diag::warn_hlsl_assigning_local_resource_is_not_unique)
5799 << E << VD;
5800 return; // Expr use multiple resources
5801 }
5802
5803 if (*ExprBinding == nullptr)
5804 return; // No binding could be inferred to track, return without error
5805
5806 auto PrevBinding = Assigns.find(VD);
5807 if (PrevBinding == Assigns.end()) {
5808 // No previous binding recorded, simply record the new assignment
5809 Assigns.insert({VD, *ExprBinding});
5810 return;
5811 }
5812
5813 // Otherwise, warn if the assignment implies different resource bindings
5814 if (*ExprBinding != PrevBinding->second) {
5815 SemaRef.Diag(E->getBeginLoc(),
5816 diag::warn_hlsl_assigning_local_resource_is_not_unique)
5817 << E << VD;
5818 SemaRef.Diag(VD->getLocation(), diag::note_var_declared_here) << VD;
5819 return;
5820 }
5821
5822 return;
5823}
5824
5826 Expr *RHSExpr, SourceLocation Loc) {
5827 assert((LHSExpr->getType()->isHLSLResourceRecord() ||
5828 LHSExpr->getType()->isHLSLResourceRecordArray()) &&
5829 "expected LHS to be a resource record or array of resource records");
5830 if (Opc != BO_Assign)
5831 return true;
5832
5833 // If LHS is an array subscript, get the underlying declaration.
5834 Expr *E = LHSExpr;
5835 while (auto *ASE = dyn_cast<ArraySubscriptExpr>(E))
5836 E = ASE->getBase()->IgnoreParenImpCasts();
5837
5838 // Report error if LHS is a non-static resource declared at a global scope.
5839 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParens())) {
5840 if (VarDecl *VD = dyn_cast<VarDecl>(DRE->getDecl())) {
5841 if (VD->hasGlobalStorage() && VD->getStorageClass() != SC_Static) {
5842 // assignment to global resource is not allowed
5843 SemaRef.Diag(Loc, diag::err_hlsl_assign_to_global_resource) << VD;
5844 SemaRef.Diag(VD->getLocation(), diag::note_var_declared_here) << VD;
5845 return false;
5846 }
5847
5848 trackLocalResource(VD, RHSExpr);
5849 }
5850 }
5851 return true;
5852}
5853
5854// Returns true if the given type can have an overload of the given
5855// binary operator.
5857 CXXRecordDecl *RD = LHSTy->getAsCXXRecordDecl();
5858 if (!RD)
5859 return true;
5860 return RD->isHLSLBuiltinRecord() || Opc != BO_Assign;
5861}
5862
5863// Walks though the global variable declaration, collects all resource binding
5864// requirements and adds them to Bindings
5865void SemaHLSL::collectResourceBindingsOnVarDecl(VarDecl *VD) {
5866 assert(VD->hasGlobalStorage() && VD->getType()->isHLSLIntangibleType() &&
5867 "expected global variable that contains HLSL resource");
5868
5869 // Cbuffers and Tbuffers are HLSLBufferDecl types
5870 if (const HLSLBufferDecl *CBufferOrTBuffer = dyn_cast<HLSLBufferDecl>(VD)) {
5871 Bindings.addDeclBindingInfo(VD, CBufferOrTBuffer->isCBuffer()
5872 ? ResourceClass::CBuffer
5873 : ResourceClass::SRV);
5874 return;
5875 }
5876
5877 // Unwrap arrays
5878 // FIXME: Calculate array size while unwrapping
5879 const Type *Ty = VD->getType()->getUnqualifiedDesugaredType();
5880 while (Ty->isArrayType()) {
5881 const ArrayType *AT = cast<ArrayType>(Ty);
5883 }
5884
5885 // Resource (or array of resources)
5886 if (const HLSLAttributedResourceType *AttrResType =
5887 HLSLAttributedResourceType::findHandleTypeOnResource(Ty)) {
5888 Bindings.addDeclBindingInfo(VD, AttrResType->getAttrs().ResourceClass);
5889 return;
5890 }
5891
5892 // User defined record type
5893 if (const RecordType *RT = dyn_cast<RecordType>(Ty))
5894 collectResourceBindingsOnUserRecordDecl(VD, RT);
5895}
5896
5897// Walks though the explicit resource binding attributes on the declaration,
5898// and makes sure there is a resource that matched the binding and updates
5899// DeclBindingInfoLists
5900void SemaHLSL::processExplicitBindingsOnDecl(VarDecl *VD) {
5901 assert(VD->hasGlobalStorage() && "expected global variable");
5902
5903 bool HasBinding = false;
5904 for (Attr *A : VD->attrs()) {
5905 if (isa<HLSLVkBindingAttr>(A)) {
5906 HasBinding = true;
5907 if (auto PA = VD->getAttr<HLSLVkPushConstantAttr>())
5908 Diag(PA->getLoc(), diag::err_hlsl_attr_incompatible) << A << PA;
5909 }
5910
5911 HLSLResourceBindingAttr *RBA = dyn_cast<HLSLResourceBindingAttr>(A);
5912 if (!RBA || !RBA->hasRegisterSlot())
5913 continue;
5914 HasBinding = true;
5915
5916 RegisterType RT = RBA->getRegisterType();
5917 assert(RT != RegisterType::I && "invalid or obsolete register type should "
5918 "never have an attribute created");
5919
5920 if (RT == RegisterType::C) {
5921 if (Bindings.hasBindingInfoForDecl(VD))
5922 SemaRef.Diag(VD->getLocation(),
5923 diag::warn_hlsl_user_defined_type_missing_member)
5924 << static_cast<int>(RT);
5925 continue;
5926 }
5927
5928 // Find DeclBindingInfo for this binding and update it, or report error
5929 // if it does not exist (user type does to contain resources with the
5930 // expected resource class).
5932 if (DeclBindingInfo *BI = Bindings.getDeclBindingInfo(VD, RC)) {
5933 // update binding info
5934 BI->setBindingAttribute(RBA, BindingType::Explicit);
5935 } else {
5936 SemaRef.Diag(VD->getLocation(),
5937 diag::warn_hlsl_user_defined_type_missing_member)
5938 << static_cast<int>(RT);
5939 }
5940 }
5941
5942 if (!HasBinding && isResourceRecordTypeOrArrayOf(VD))
5943 SemaRef.Diag(VD->getLocation(), diag::warn_hlsl_implicit_binding);
5944}
5945namespace {
5946class InitListTransformer {
5947 Sema &S;
5948 ASTContext &Ctx;
5949 QualType InitTy;
5950 QualType *DstIt = nullptr;
5951 Expr **ArgIt = nullptr;
5952 // Is wrapping the destination type iterator required? This is only used for
5953 // incomplete array types where we loop over the destination type since we
5954 // don't know the full number of elements from the declaration.
5955 bool Wrap;
5956
5957 bool castInitializer(Expr *E) {
5958 assert(DstIt && "This should always be something!");
5959 if (DstIt == DestTypes.end()) {
5960 if (!Wrap) {
5961 ArgExprs.push_back(E);
5962 // This is odd, but it isn't technically a failure due to conversion, we
5963 // handle mismatched counts of arguments differently.
5964 return true;
5965 }
5966 DstIt = DestTypes.begin();
5967 }
5968 InitializedEntity Entity = InitializedEntity::InitializeParameter(
5969 Ctx, *DstIt, /* Consumed (ObjC) */ false);
5970 ExprResult Res = S.PerformCopyInitialization(Entity, E->getBeginLoc(), E);
5971 if (Res.isInvalid())
5972 return false;
5973 Expr *Init = Res.get();
5974 ArgExprs.push_back(Init);
5975 DstIt++;
5976 return true;
5977 }
5978
5979 bool buildInitializerListImpl(Expr *E) {
5980 // If this is an initialization list, traverse the sub initializers.
5981 if (auto *Init = dyn_cast<InitListExpr>(E)) {
5982 for (auto *SubInit : Init->inits())
5983 if (!buildInitializerListImpl(SubInit))
5984 return false;
5985 return true;
5986 }
5987
5988 // If this is a scalar type, just enqueue the expression.
5989 QualType Ty = E->getType().getDesugaredType(Ctx);
5990
5991 if (Ty->isScalarType() || (Ty->isRecordType() && !Ty->isAggregateType()) ||
5993 return castInitializer(E);
5994
5995 // If this is an aggregate type and a prvalue, create an xvalue temporary
5996 // so the member accesses will be xvalues. Wrap it in OpaqueExpr to make
5997 // sure codegen will not generate duplicate copies.
5998 if (E->isPRValue() && Ty->isAggregateType()) {
6000 if (TmpExpr.isInvalid())
6001 return false;
6002 E = TmpExpr.get();
6003 E = new (Ctx) OpaqueValueExpr(E->getBeginLoc(), E->getType(),
6004 E->getValueKind(), E->getObjectKind(), E);
6005 }
6006
6007 if (auto *VecTy = Ty->getAs<VectorType>()) {
6008 uint64_t Size = VecTy->getNumElements();
6009
6010 QualType SizeTy = Ctx.getSizeType();
6011 uint64_t SizeTySize = Ctx.getTypeSize(SizeTy);
6012 for (uint64_t I = 0; I < Size; ++I) {
6013 auto *Idx = IntegerLiteral::Create(Ctx, llvm::APInt(SizeTySize, I),
6014 SizeTy, SourceLocation());
6015
6017 E, E->getBeginLoc(), Idx, E->getEndLoc());
6018 if (ElExpr.isInvalid())
6019 return false;
6020 if (!castInitializer(ElExpr.get()))
6021 return false;
6022 }
6023 return true;
6024 }
6025 if (auto *MTy = Ty->getAs<ConstantMatrixType>()) {
6026 unsigned Rows = MTy->getNumRows();
6027 unsigned Cols = MTy->getNumColumns();
6028 QualType ElemTy = MTy->getElementType();
6029
6030 for (unsigned R = 0; R < Rows; ++R) {
6031 for (unsigned C = 0; C < Cols; ++C) {
6032 // row index literal
6033 Expr *RowIdx = IntegerLiteral::Create(
6034 Ctx, llvm::APInt(Ctx.getIntWidth(Ctx.IntTy), R), Ctx.IntTy,
6035 E->getBeginLoc());
6036 // column index literal
6037 Expr *ColIdx = IntegerLiteral::Create(
6038 Ctx, llvm::APInt(Ctx.getIntWidth(Ctx.IntTy), C), Ctx.IntTy,
6039 E->getBeginLoc());
6041 E, RowIdx, ColIdx, E->getEndLoc());
6042 if (ElExpr.isInvalid())
6043 return false;
6044 if (!castInitializer(ElExpr.get()))
6045 return false;
6046 ElExpr.get()->setType(ElemTy);
6047 }
6048 }
6049 return true;
6050 }
6051
6052 if (auto *ArrTy = dyn_cast<ConstantArrayType>(Ty.getTypePtr())) {
6053 uint64_t Size = ArrTy->getZExtSize();
6054 QualType SizeTy = Ctx.getSizeType();
6055 uint64_t SizeTySize = Ctx.getTypeSize(SizeTy);
6056 for (uint64_t I = 0; I < Size; ++I) {
6057 auto *Idx = IntegerLiteral::Create(Ctx, llvm::APInt(SizeTySize, I),
6058 SizeTy, SourceLocation());
6060 E, E->getBeginLoc(), Idx, E->getEndLoc());
6061 if (ElExpr.isInvalid())
6062 return false;
6063 if (!buildInitializerListImpl(ElExpr.get()))
6064 return false;
6065 }
6066 return true;
6067 }
6068
6069 if (auto *RD = Ty->getAsCXXRecordDecl()) {
6070 llvm::SmallVector<CXXRecordDecl *> RecordDecls;
6071 RecordDecls.push_back(RD);
6072 while (RecordDecls.back()->getNumBases()) {
6073 CXXRecordDecl *D = RecordDecls.back();
6074 assert(D->getNumBases() == 1 &&
6075 "HLSL doesn't support multiple inheritance");
6076 RecordDecls.push_back(
6078 }
6079 while (!RecordDecls.empty()) {
6080 CXXRecordDecl *RD = RecordDecls.pop_back_val();
6081 for (auto *FD : RD->fields()) {
6082 if (FD->isUnnamedBitField())
6083 continue;
6084 DeclAccessPair Found = DeclAccessPair::make(FD, FD->getAccess());
6085 DeclarationNameInfo NameInfo(FD->getDeclName(), E->getBeginLoc());
6087 E, false, E->getBeginLoc(), CXXScopeSpec(), FD, Found, NameInfo);
6088 if (Res.isInvalid())
6089 return false;
6090 if (!buildInitializerListImpl(Res.get()))
6091 return false;
6092 }
6093 }
6094 }
6095 return true;
6096 }
6097
6098 Expr *generateInitListsImpl(QualType Ty) {
6099 Ty = Ty.getDesugaredType(Ctx);
6100 assert(ArgIt != ArgExprs.end() && "Something is off in iteration!");
6101 if (Ty->isScalarType() || (Ty->isRecordType() && !Ty->isAggregateType()) ||
6103 return *(ArgIt++);
6104
6105 llvm::SmallVector<Expr *> Inits;
6106 if (Ty->isVectorType() || Ty->isConstantArrayType() ||
6107 Ty->isConstantMatrixType()) {
6108 QualType ElTy;
6109 uint64_t Size = 0;
6110 if (auto *ATy = Ty->getAs<VectorType>()) {
6111 ElTy = ATy->getElementType();
6112 Size = ATy->getNumElements();
6113 } else if (auto *CMTy = Ty->getAs<ConstantMatrixType>()) {
6114 ElTy = CMTy->getElementType();
6115 Size = CMTy->getNumElementsFlattened();
6116 } else {
6117 auto *VTy = cast<ConstantArrayType>(Ty.getTypePtr());
6118 ElTy = VTy->getElementType();
6119 Size = VTy->getZExtSize();
6120 }
6121 for (uint64_t I = 0; I < Size; ++I)
6122 Inits.push_back(generateInitListsImpl(ElTy));
6123 }
6124 if (auto *RD = Ty->getAsCXXRecordDecl()) {
6125 llvm::SmallVector<CXXRecordDecl *> RecordDecls;
6126 RecordDecls.push_back(RD);
6127 while (RecordDecls.back()->getNumBases()) {
6128 CXXRecordDecl *D = RecordDecls.back();
6129 assert(D->getNumBases() == 1 &&
6130 "HLSL doesn't support multiple inheritance");
6131 RecordDecls.push_back(
6133 }
6134 while (!RecordDecls.empty()) {
6135 CXXRecordDecl *RD = RecordDecls.pop_back_val();
6136 for (auto *FD : RD->fields())
6137 if (!FD->isUnnamedBitField())
6138 Inits.push_back(generateInitListsImpl(FD->getType()));
6139 }
6140 }
6141 auto *NewInit =
6142 new (Ctx) InitListExpr(Ctx, Inits.front()->getBeginLoc(), Inits,
6143 Inits.back()->getEndLoc(), /*isExplicit=*/false);
6144 NewInit->setType(Ty);
6145 return NewInit;
6146 }
6147
6148public:
6149 llvm::SmallVector<QualType, 16> DestTypes;
6150 llvm::SmallVector<Expr *, 16> ArgExprs;
6151 InitListTransformer(Sema &SemaRef, const InitializedEntity &Entity)
6152 : S(SemaRef), Ctx(SemaRef.getASTContext()),
6153 Wrap(Entity.getType()->isIncompleteArrayType()) {
6154 InitTy = Entity.getType().getNonReferenceType();
6155 // When we're generating initializer lists for incomplete array types we
6156 // need to wrap around both when building the initializers and when
6157 // generating the final initializer lists.
6158 if (Wrap) {
6159 assert(InitTy->isIncompleteArrayType());
6160 const IncompleteArrayType *IAT = Ctx.getAsIncompleteArrayType(InitTy);
6161 InitTy = IAT->getElementType();
6162 }
6163 BuildFlattenedTypeList(InitTy, DestTypes);
6164 DstIt = DestTypes.begin();
6165 }
6166
6167 bool buildInitializerList(Expr *E) { return buildInitializerListImpl(E); }
6168
6169 Expr *generateInitLists() {
6170 assert(!ArgExprs.empty() &&
6171 "Call buildInitializerList to generate argument expressions.");
6172 ArgIt = ArgExprs.begin();
6173 if (!Wrap)
6174 return generateInitListsImpl(InitTy);
6175 llvm::SmallVector<Expr *> Inits;
6176 while (ArgIt != ArgExprs.end())
6177 Inits.push_back(generateInitListsImpl(InitTy));
6178
6179 auto *NewInit =
6180 new (Ctx) InitListExpr(Ctx, Inits.front()->getBeginLoc(), Inits,
6181 Inits.back()->getEndLoc(), /*isExplicit=*/false);
6182 llvm::APInt ArySize(64, Inits.size());
6183 NewInit->setType(Ctx.getConstantArrayType(InitTy, ArySize, nullptr,
6184 ArraySizeModifier::Normal, 0));
6185 return NewInit;
6186 }
6187};
6188} // namespace
6189
6190// Recursively detect any incomplete array anywhere in the type graph,
6191// including arrays, struct fields, and base classes.
6193 Ty = Ty.getCanonicalType();
6194
6195 // Array types
6196 if (const ArrayType *AT = dyn_cast<ArrayType>(Ty)) {
6198 return true;
6200 }
6201
6202 // Record (struct/class) types
6203 if (const auto *RT = Ty->getAs<RecordType>()) {
6204 const RecordDecl *RD = RT->getDecl();
6205
6206 // Walk base classes (for C++ / HLSL structs with inheritance)
6207 if (const auto *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
6208 for (const CXXBaseSpecifier &Base : CXXRD->bases()) {
6209 if (containsIncompleteArrayType(Base.getType()))
6210 return true;
6211 }
6212 }
6213
6214 // Walk fields
6215 for (const FieldDecl *F : RD->fields()) {
6216 if (containsIncompleteArrayType(F->getType()))
6217 return true;
6218 }
6219 }
6220
6221 return false;
6222}
6223
6225 InitListExpr *Init) {
6226 // If the initializer is a scalar, just return it.
6227 if (Init->getType()->isScalarType())
6228 return true;
6229 ASTContext &Ctx = SemaRef.getASTContext();
6230 InitListTransformer ILT(SemaRef, Entity);
6231
6232 for (unsigned I = 0; I < Init->getNumInits(); ++I) {
6233 Expr *E = Init->getInit(I);
6234 if (E->HasSideEffects(Ctx)) {
6235 QualType Ty = E->getType();
6236 if (Ty->isRecordType())
6237 E = new (Ctx) MaterializeTemporaryExpr(Ty, E, E->isLValue());
6238 E = new (Ctx) OpaqueValueExpr(E->getBeginLoc(), Ty, E->getValueKind(),
6239 E->getObjectKind(), E);
6240 Init->setInit(I, E);
6241 }
6242 if (!ILT.buildInitializerList(E))
6243 return false;
6244 }
6245 size_t ExpectedSize = ILT.DestTypes.size();
6246 size_t ActualSize = ILT.ArgExprs.size();
6247 if (ExpectedSize == 0 && ActualSize == 0)
6248 return true;
6249
6250 // Reject empty initializer if *any* incomplete array exists structurally
6251 if (ActualSize == 0 && containsIncompleteArrayType(Entity.getType())) {
6252 QualType InitTy = Entity.getType().getNonReferenceType();
6253 if (InitTy.hasAddressSpace())
6254 InitTy = SemaRef.getASTContext().removeAddrSpaceQualType(InitTy);
6255
6256 SemaRef.Diag(Init->getBeginLoc(), diag::err_hlsl_incorrect_num_initializers)
6257 << /*TooManyOrFew=*/(int)(ExpectedSize < ActualSize) << InitTy
6258 << /*ExpectedSize=*/ExpectedSize << /*ActualSize=*/ActualSize;
6259 return false;
6260 }
6261
6262 // We infer size after validating legality.
6263 // For incomplete arrays it is completely arbitrary to choose whether we think
6264 // the user intended fewer or more elements. This implementation assumes that
6265 // the user intended more, and errors that there are too few initializers to
6266 // complete the final element.
6267 if (Entity.getType()->isIncompleteArrayType()) {
6268 assert(ExpectedSize > 0 &&
6269 "The expected size of an incomplete array type must be at least 1.");
6270 ExpectedSize =
6271 ((ActualSize + ExpectedSize - 1) / ExpectedSize) * ExpectedSize;
6272 }
6273
6274 // An initializer list might be attempting to initialize a reference or
6275 // rvalue-reference. When checking the initializer we should look through
6276 // the reference.
6277 QualType InitTy = Entity.getType().getNonReferenceType();
6278 if (InitTy.hasAddressSpace())
6279 InitTy = SemaRef.getASTContext().removeAddrSpaceQualType(InitTy);
6280 if (ExpectedSize != ActualSize) {
6281 int TooManyOrFew = ActualSize > ExpectedSize ? 1 : 0;
6282 SemaRef.Diag(Init->getBeginLoc(), diag::err_hlsl_incorrect_num_initializers)
6283 << TooManyOrFew << InitTy << ExpectedSize << ActualSize;
6284 return false;
6285 }
6286
6287 // generateInitListsImpl will always return an InitListExpr here, because the
6288 // scalar case is handled above.
6289 auto *NewInit = cast<InitListExpr>(ILT.generateInitLists());
6290 Init->resizeInits(Ctx, NewInit->getNumInits());
6291 for (unsigned I = 0; I < NewInit->getNumInits(); ++I)
6292 Init->updateInit(Ctx, I, NewInit->getInit(I));
6293 return true;
6294}
6295
6296static QualType ReportMatrixInvalidMember(Sema &S, StringRef Name,
6297 StringRef Expected,
6298 SourceLocation OpLoc,
6299 SourceLocation CompLoc) {
6300 S.Diag(OpLoc, diag::err_builtin_matrix_invalid_member)
6301 << Name << Expected << SourceRange(CompLoc);
6302 return QualType();
6303}
6304
6307 const IdentifierInfo *CompName,
6308 SourceLocation CompLoc) {
6309 const auto *MT = baseType->castAs<ConstantMatrixType>();
6310 StringRef AccessorName = CompName->getName();
6311 assert(!AccessorName.empty() && "Matrix Accessor must have a name");
6312
6313 unsigned Rows = MT->getNumRows();
6314 unsigned Cols = MT->getNumColumns();
6315 bool IsZeroBasedAccessor = false;
6316 unsigned ChunkLen = 0;
6317 if (AccessorName.size() < 2)
6318 return ReportMatrixInvalidMember(S, AccessorName,
6319 "length 4 for zero based: \'_mRC\' or "
6320 "length 3 for one-based: \'_RC\' accessor",
6321 OpLoc, CompLoc);
6322
6323 if (AccessorName[0] == '_') {
6324 if (AccessorName[1] == 'm') {
6325 IsZeroBasedAccessor = true;
6326 ChunkLen = 4; // zero-based: "_mRC"
6327 } else {
6328 ChunkLen = 3; // one-based: "_RC"
6329 }
6330 } else
6332 S, AccessorName, "zero based: \'_mRC\' or one-based: \'_RC\' accessor",
6333 OpLoc, CompLoc);
6334
6335 if (AccessorName.size() % ChunkLen != 0) {
6336 const llvm::StringRef Expected = IsZeroBasedAccessor
6337 ? "zero based: '_mRC' accessor"
6338 : "one-based: '_RC' accessor";
6339
6340 return ReportMatrixInvalidMember(S, AccessorName, Expected, OpLoc, CompLoc);
6341 }
6342
6343 auto isDigit = [](char c) { return c >= '0' && c <= '9'; };
6344 auto isZeroBasedIndex = [](unsigned i) { return i <= 3; };
6345 auto isOneBasedIndex = [](unsigned i) { return i >= 1 && i <= 4; };
6346
6347 bool HasRepeated = false;
6348 SmallVector<bool, 16> Seen(Rows * Cols, false);
6349 unsigned NumComponents = 0;
6350 const char *Begin = AccessorName.data();
6351
6352 for (unsigned I = 0, E = AccessorName.size(); I < E; I += ChunkLen) {
6353 const char *Chunk = Begin + I;
6354 char RowChar = 0, ColChar = 0;
6355 if (IsZeroBasedAccessor) {
6356 // Zero-based: "_mRC"
6357 if (Chunk[0] != '_' || Chunk[1] != 'm') {
6358 char Bad = (Chunk[0] != '_') ? Chunk[0] : Chunk[1];
6360 S, StringRef(&Bad, 1), "\'_m\' prefix",
6361 OpLoc.getLocWithOffset(I + (Bad == Chunk[0] ? 1 : 2)), CompLoc);
6362 }
6363 RowChar = Chunk[2];
6364 ColChar = Chunk[3];
6365 } else {
6366 // One-based: "_RC"
6367 if (Chunk[0] != '_')
6369 S, StringRef(&Chunk[0], 1), "\'_\' prefix",
6370 OpLoc.getLocWithOffset(I + 1), CompLoc);
6371 RowChar = Chunk[1];
6372 ColChar = Chunk[2];
6373 }
6374
6375 // Must be digits.
6376 bool IsDigitsError = false;
6377 if (!isDigit(RowChar)) {
6378 unsigned BadPos = IsZeroBasedAccessor ? 2 : 1;
6379 ReportMatrixInvalidMember(S, StringRef(&RowChar, 1), "row as integer",
6380 OpLoc.getLocWithOffset(I + BadPos + 1),
6381 CompLoc);
6382 IsDigitsError = true;
6383 }
6384
6385 if (!isDigit(ColChar)) {
6386 unsigned BadPos = IsZeroBasedAccessor ? 3 : 2;
6387 ReportMatrixInvalidMember(S, StringRef(&ColChar, 1), "column as integer",
6388 OpLoc.getLocWithOffset(I + BadPos + 1),
6389 CompLoc);
6390 IsDigitsError = true;
6391 }
6392 if (IsDigitsError)
6393 return QualType();
6394
6395 unsigned Row = RowChar - '0';
6396 unsigned Col = ColChar - '0';
6397
6398 bool HasIndexingError = false;
6399 if (IsZeroBasedAccessor) {
6400 // 0-based [0..3]
6401 if (!isZeroBasedIndex(Row)) {
6402 S.Diag(OpLoc, diag::err_hlsl_matrix_element_not_in_bounds)
6403 << /*row*/ 0 << /*zero-based*/ 0 << SourceRange(CompLoc);
6404 HasIndexingError = true;
6405 }
6406 if (!isZeroBasedIndex(Col)) {
6407 S.Diag(OpLoc, diag::err_hlsl_matrix_element_not_in_bounds)
6408 << /*col*/ 1 << /*zero-based*/ 0 << SourceRange(CompLoc);
6409 HasIndexingError = true;
6410 }
6411 } else {
6412 // 1-based [1..4]
6413 if (!isOneBasedIndex(Row)) {
6414 S.Diag(OpLoc, diag::err_hlsl_matrix_element_not_in_bounds)
6415 << /*row*/ 0 << /*one-based*/ 1 << SourceRange(CompLoc);
6416 HasIndexingError = true;
6417 }
6418 if (!isOneBasedIndex(Col)) {
6419 S.Diag(OpLoc, diag::err_hlsl_matrix_element_not_in_bounds)
6420 << /*col*/ 1 << /*one-based*/ 1 << SourceRange(CompLoc);
6421 HasIndexingError = true;
6422 }
6423 // Convert to 0-based after range checking.
6424 --Row;
6425 --Col;
6426 }
6427
6428 if (HasIndexingError)
6429 return QualType();
6430
6431 // Note: matrix swizzle index is hard coded. That means Row and Col can
6432 // potentially be larger than Rows and Cols if matrix size is less than
6433 // the max index size.
6434 bool HasBoundsError = false;
6435 if (Row >= Rows) {
6436 Diag(OpLoc, diag::err_hlsl_matrix_index_out_of_bounds)
6437 << /*Row*/ 0 << Row << Rows << SourceRange(CompLoc);
6438 HasBoundsError = true;
6439 }
6440 if (Col >= Cols) {
6441 Diag(OpLoc, diag::err_hlsl_matrix_index_out_of_bounds)
6442 << /*Col*/ 1 << Col << Cols << SourceRange(CompLoc);
6443 HasBoundsError = true;
6444 }
6445 if (HasBoundsError)
6446 return QualType();
6447
6448 unsigned FlatIndex = Row * Cols + Col;
6449 if (Seen[FlatIndex])
6450 HasRepeated = true;
6451 Seen[FlatIndex] = true;
6452 ++NumComponents;
6453 }
6454 if (NumComponents == 0 || NumComponents > 4) {
6455 S.Diag(OpLoc, diag::err_hlsl_matrix_swizzle_invalid_length)
6456 << NumComponents << SourceRange(CompLoc);
6457 return QualType();
6458 }
6459
6460 QualType ElemTy = MT->getElementType();
6461 if (NumComponents == 1)
6462 return ElemTy;
6463 QualType VT = S.Context.getExtVectorType(ElemTy, NumComponents);
6464 if (HasRepeated)
6465 VK = VK_PRValue;
6466
6467 for (Sema::ExtVectorDeclsType::iterator
6469 E = S.ExtVectorDecls.end();
6470 I != E; ++I) {
6471 if ((*I)->getUnderlyingType() == VT)
6473 /*Qualifier=*/std::nullopt, *I);
6474 }
6475
6476 return VT;
6477}
6478
6480 // If initializing a local resource, track the resource binding it is using
6481 if (VDecl->getType()->isHLSLResourceRecord() && !VDecl->hasGlobalStorage())
6482 trackLocalResource(VDecl, Init);
6483
6484 const HLSLVkConstantIdAttr *ConstIdAttr =
6485 VDecl->getAttr<HLSLVkConstantIdAttr>();
6486 if (!ConstIdAttr)
6487 return true;
6488
6489 ASTContext &Context = SemaRef.getASTContext();
6490
6491 APValue InitValue;
6492 if (!Init->isCXX11ConstantExpr(Context, &InitValue)) {
6493 Diag(VDecl->getLocation(), diag::err_specialization_const);
6494 VDecl->setInvalidDecl();
6495 return false;
6496 }
6497
6498 Builtin::ID BID =
6500
6501 // Argument 1: The ID from the attribute
6502 int ConstantID = ConstIdAttr->getId();
6503 llvm::APInt IDVal(Context.getIntWidth(Context.IntTy), ConstantID);
6504 Expr *IdExpr = IntegerLiteral::Create(Context, IDVal, Context.IntTy,
6505 ConstIdAttr->getLocation());
6506
6507 SmallVector<Expr *, 2> Args = {IdExpr, Init};
6508 Expr *C = SemaRef.BuildBuiltinCallExpr(Init->getExprLoc(), BID, Args);
6509 if (C->getType()->getCanonicalTypeUnqualified() !=
6511 C = SemaRef
6512 .BuildCStyleCastExpr(SourceLocation(),
6513 Context.getTrivialTypeSourceInfo(
6514 Init->getType(), Init->getExprLoc()),
6515 SourceLocation(), C)
6516 .get();
6517 }
6518 Init = C;
6519 return true;
6520}
6521
6523 SourceLocation NameLoc) {
6524 if (!Template)
6525 return QualType();
6526
6527 DeclContext *DC = Template->getDeclContext();
6528 if (!DC->isNamespace() || !cast<NamespaceDecl>(DC)->getIdentifier() ||
6529 cast<NamespaceDecl>(DC)->getName() != "hlsl")
6530 return QualType();
6531
6532 TemplateParameterList *Params = Template->getTemplateParameters();
6533 if (!Params || Params->size() != 1)
6534 return QualType();
6535
6536 if (!Template->isImplicit())
6537 return QualType();
6538
6539 // We manually extract default arguments here instead of letting
6540 // CheckTemplateIdType handle it. This ensures that for resource types that
6541 // lack a default argument (like Buffer), we return a null QualType, which
6542 // triggers the "requires template arguments" error rather than a less
6543 // descriptive "too few template arguments" error.
6544 TemplateArgumentListInfo TemplateArgs(NameLoc, NameLoc);
6545 for (NamedDecl *P : *Params) {
6546 if (auto *TTP = dyn_cast<TemplateTypeParmDecl>(P)) {
6547 if (TTP->hasDefaultArgument()) {
6548 TemplateArgs.addArgument(TTP->getDefaultArgument());
6549 continue;
6550 }
6551 } else if (auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(P)) {
6552 if (NTTP->hasDefaultArgument()) {
6553 TemplateArgs.addArgument(NTTP->getDefaultArgument());
6554 continue;
6555 }
6556 } else if (auto *TTPD = dyn_cast<TemplateTemplateParmDecl>(P)) {
6557 if (TTPD->hasDefaultArgument()) {
6558 TemplateArgs.addArgument(TTPD->getDefaultArgument());
6559 continue;
6560 }
6561 }
6562 return QualType();
6563 }
6564
6565 return SemaRef.CheckTemplateIdType(
6567 TemplateArgs, nullptr, /*ForNestedNameSpecifier=*/false);
6568}
Defines the clang::ASTContext interface.
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....
TokenType getType() const
Returns the token's type, e.g.
FormatToken * Previous
The previous token in the unwrapped line.
Defines the clang::IdentifierInfo, clang::IdentifierTable, and clang::Selector interfaces.
#define X(type, name)
Definition Value.h:97
Forward-declares and imports various common LLVM datatypes that clang wants to use unqualified.
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)
Definition SemaHLSL.cpp:95
static StringRef createRegisterString(ASTContext &AST, RegisterType RegType, unsigned N)
Definition SemaHLSL.cpp:197
static bool CheckWaveActive(Sema *S, CallExpr *TheCall)
static void createHostLayoutStructForBuffer(Sema &S, HLSLBufferDecl *BufDecl)
Definition SemaHLSL.cpp:633
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 unsigned calculateLegacyCbufferFieldAlign(const ASTContext &Context, QualType T)
Definition SemaHLSL.cpp:259
static bool isZeroSizedArray(const ConstantArrayType *CAT)
Definition SemaHLSL.cpp:378
static bool DiagnoseHLSLRegisterAttribute(Sema &S, SourceLocation &ArgLoc, Decl *D, RegisterType RegType, bool SpecifiedSpace)
static bool hasConstantBufferLayout(QualType QT)
static FieldDecl * createFieldForHostLayoutStruct(Sema &S, const Type *Ty, IdentifierInfo *II, CXXRecordDecl *LayoutStruct)
Definition SemaHLSL.cpp:541
static bool CheckUnsignedIntVecRepresentation(Sema *S, SourceLocation Loc, int ArgOrdinal, clang::QualType PassedType)
SampleKind
static bool isInvalidConstantBufferLeafElementType(const Type *Ty)
Definition SemaHLSL.cpp:412
static bool CheckCalculateLodBuiltin(Sema &S, CallExpr *TheCall)
static Builtin::ID getSpecConstBuiltinId(const Type *Type)
Definition SemaHLSL.cpp:163
static bool CheckFloatingOrIntRepresentation(Sema *S, SourceLocation Loc, int ArgOrdinal, clang::QualType PassedType)
static const Type * createHostLayoutType(Sema &S, const Type *Ty)
Definition SemaHLSL.cpp:503
static bool CheckAnyScalarOrVector(Sema *S, CallExpr *TheCall, unsigned ArgIndex)
static const HLSLAttributedResourceType * getResourceArrayHandleType(QualType QT)
Definition SemaHLSL.cpp:394
static IdentifierInfo * getHostLayoutStructName(Sema &S, NamedDecl *BaseDecl, bool MustBeUnique)
Definition SemaHLSL.cpp:468
static bool CheckArgAddrSpaceOneOf(Sema *S, CallExpr *TheCall, unsigned ArgIndex, ArrayRef< LangAS > AllowedSpaces)
static void addImplicitBindingAttrToDecl(Sema &S, Decl *D, RegisterType RT, uint32_t ImplicitBindingOrderID)
Definition SemaHLSL.cpp:677
static void SetElementTypeAsReturnType(Sema *S, CallExpr *TheCall, QualType ReturnType)
static unsigned calculateLegacyCbufferSize(const ASTContext &Context, QualType T)
Definition SemaHLSL.cpp:278
static bool CheckLoadLevelBuiltin(Sema &S, CallExpr *TheCall)
static RegisterType getRegisterType(ResourceClass RC)
Definition SemaHLSL.cpp:62
static bool ValidateRegisterNumber(uint64_t SlotNum, Decl *TheDecl, ASTContext &Ctx, RegisterType RegTy)
static bool isVkPipelineBuiltin(const ASTContext &AstContext, FunctionDecl *FD, HLSLAppliedSemanticAttr *Semantic, bool IsInput)
Definition SemaHLSL.cpp:865
static bool CheckVectorElementCount(Sema *S, QualType PassedType, QualType BaseType, unsigned ExpectedCount, SourceLocation Loc)
static bool CheckModifiableLValue(Sema *S, CallExpr *TheCall, unsigned ArgIndex)
static QualType castElement(Sema &S, ExprResult &E, QualType Ty)
static char getRegisterTypeChar(RegisterType RT)
Definition SemaHLSL.cpp:127
static bool CheckNotBoolScalarOrVector(Sema *S, CallExpr *TheCall, unsigned ArgIndex)
static bool isMatrixOrArrayOfMatrix(const ASTContext &Ctx, QualType QT)
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)
Definition SemaHLSL.cpp:451
static bool CheckWavePrefix(Sema *S, CallExpr *TheCall)
static bool CheckExpectedBitWidth(Sema *S, CallExpr *TheCall, unsigned ArgOrdinal, unsigned Width)
static LangAS getLangASFromResourceClass(ResourceClass RC)
Definition SemaHLSL.cpp:80
static bool CheckVectorSelect(Sema *S, CallExpr *TheCall)
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)
Definition SemaHLSL.cpp:532
static ResourceClass getResourceClass(RegisterType RT)
Definition SemaHLSL.cpp:145
static CXXRecordDecl * createHostLayoutStruct(Sema &S, CXXRecordDecl *StructDecl)
Definition SemaHLSL.cpp:568
static bool CheckScalarOrVector(Sema *S, CallExpr *TheCall, QualType Scalar, unsigned ArgIndex)
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)
Definition SemaHLSL.cpp:431
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)
Definition SemaHLSL.cpp:325
static bool IsDefaultBufferConstantDecl(const ASTContext &Ctx, VarDecl *VD)
HLSLResourceBindingAttr::RegisterType RegisterType
Definition SemaHLSL.cpp:57
static CastKind getScalarCastKind(ASTContext &Ctx, QualType DestTy, QualType SrcTy)
static bool CheckGatherBuiltin(Sema &S, CallExpr *TheCall, bool IsCmp)
static bool isValidWaveSizeValue(unsigned Value)
static bool isResourceRecordTypeOrArrayOf(QualType Ty)
Definition SemaHLSL.cpp:385
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 CheckTextureSamplerAndLocation(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)
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)
Definition Types.cpp:44
return(__x > > __y)|(__x<<(32 - __y))
APValue - This class implements a discriminated union of [uninitialized] [APSInt] [APFloat],...
Definition APValue.h:122
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 ...
Definition ASTContext.h:223
unsigned getIntWidth(QualType T) const
int getIntegerTypeOrder(QualType LHS, QualType RHS) const
Return the highest ranked integer type, see C99 6.3.1.8p1.
CanQualType FloatTy
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
IdentifierTable & Idents
Definition ASTContext.h:802
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.
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....
CanQualType BoolTy
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.
CanQualType CharTy
CanQualType IntTy
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.
llvm::StringRef backupStr(llvm::StringRef S) const
Definition ASTContext.h:884
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
Definition ASTContext.h:921
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.
QualType getConstantMatrixType(QualType ElementType, unsigned NumRows, unsigned NumColumns) const
Return the unique reference to the matrix type of the specified element type and size.
unsigned getTypeAlign(QualType T) const
Return the ABI-specified alignment of a (complete) type T, in bits.
PtrTy get() const
Definition Ownership.h:171
bool isInvalid() const
Definition Ownership.h:167
Represents an array type, per C99 6.7.5.2 - Array Declarators.
Definition TypeBase.h:3786
QualType getElementType() const
Definition TypeBase.h:3798
Attr - This represents one attribute.
Definition Attr.h:46
attr::Kind getKind() const
Definition Attr.h:92
SourceLocation getLocation() const
Definition Attr.h:99
SourceLocation getScopeLoc() const
const IdentifierInfo * getScopeName() const
SourceLocation getLoc() const
const IdentifierInfo * getAttrName() const
Represents a base class of a C++ class.
Definition DeclCXX.h:146
QualType getType() const
Retrieves the type of the base class.
Definition DeclCXX.h:249
Represents a static or instance method of a struct/union/class.
Definition DeclCXX.h:2145
Represents a C++ struct/union/class.
Definition DeclCXX.h:258
bool isHLSLIntangible() const
Returns true if the class contains HLSL intangible type, either as a field or in base class.
Definition DeclCXX.h:1561
static CXXRecordDecl * Create(const ASTContext &C, TagKind TK, DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc, IdentifierInfo *Id, CXXRecordDecl *PrevDecl=nullptr)
Definition DeclCXX.cpp:133
void setBases(CXXBaseSpecifier const *const *Bases, unsigned NumBases)
Sets the base classes of this struct or class.
Definition DeclCXX.cpp:185
base_class_iterator bases_end()
Definition DeclCXX.h:617
void completeDefinition() override
Indicates that the definition of this class is now complete.
Definition DeclCXX.cpp:2245
base_class_range bases()
Definition DeclCXX.h:608
unsigned getNumBases() const
Retrieves the number of base classes of this class.
Definition DeclCXX.h:602
bool isHLSLBuiltinRecord() const
Returns true if the class is a built-in HLSL record.
Definition DeclCXX.h:1564
base_class_iterator bases_begin()
Definition DeclCXX.h:615
bool isEmpty() const
Determine whether this is an empty class in the sense of (C++11 [meta.unary.prop]).
Definition DeclCXX.h:1191
CallExpr - Represents a function call (C99 6.5.2.2, C++ [expr.call]).
Definition Expr.h:2946
Expr * getArg(unsigned Arg)
getArg - Return the specified argument.
Definition Expr.h:3150
SourceLocation getBeginLoc() const
Definition Expr.h:3280
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.
Definition Expr.cpp:1523
FunctionDecl * getDirectCallee()
If the callee is a FunctionDecl, return it. Otherwise return null.
Definition Expr.h:3129
Expr * getCallee()
Definition Expr.h:3093
unsigned getNumArgs() const
getNumArgs - Return the number of actual arguments to this call.
Definition Expr.h:3137
SourceLocation getEndLoc() const
Definition Expr.h:3299
Decl * getCalleeDecl()
Definition Expr.h:3123
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
getQuantity - Get the raw integer representation of this quantity.
Definition CharUnits.h:185
Represents the canonical version of C arrays with a specified constant size.
Definition TypeBase.h:3824
bool isZeroSize() const
Return true if the size is zero.
Definition TypeBase.h:3894
llvm::APInt getSize() const
Return the constant array size as an APInt.
Definition TypeBase.h:3880
uint64_t getZExtSize() const
Return the size zero-extended as a uint64_t.
Definition TypeBase.h:3900
Represents a concrete matrix type with constant number of rows and columns.
Definition TypeBase.h:4451
unsigned getNumColumns() const
Returns the number of columns in the matrix.
Definition TypeBase.h:4470
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...
Definition DeclBase.h:1462
bool isNamespace() const
Definition DeclBase.h:2211
lookup_result lookup(DeclarationName Name) const
lookup - Find the declarations (if any) with the given Name in this context.
bool isTranslationUnit() const
Definition DeclBase.h:2198
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.
Definition DeclBase.h:2386
DeclContext * getNonTransparentContext()
A reference to a declared variable, function, enum, etc.
Definition Expr.h:1273
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)
Definition Expr.cpp:494
ValueDecl * getDecl()
Definition Expr.h:1341
Decl - This represents one declaration (or definition), e.g.
Definition DeclBase.h:86
T * getAttr() const
Definition DeclBase.h:581
ASTContext & getASTContext() const LLVM_READONLY
Definition DeclBase.cpp:547
void addAttr(Attr *A)
attr_iterator attr_end() const
Definition DeclBase.h:550
bool isImplicit() const
isImplicit - Indicates whether the declaration was implicitly generated by the implementation.
Definition DeclBase.h:601
void setInvalidDecl(bool Invalid=true)
setInvalidDecl - Indicates the Decl had a semantic error.
Definition DeclBase.cpp:178
bool isInExportDeclContext() const
Whether this declaration was exported in a lexical context.
attr_iterator attr_begin() const
Definition DeclBase.h:547
DeclContext * getNonTransparentDeclContext()
Return the non transparent context.
SourceLocation getLocation() const
Definition DeclBase.h:447
void setImplicit(bool I=true)
Definition DeclBase.h:602
DeclContext * getDeclContext()
Definition DeclBase.h:456
attr_range attrs() const
Definition DeclBase.h:543
AccessSpecifier getAccess() const
Definition DeclBase.h:515
SourceLocation getBeginLoc() const LLVM_READONLY
Definition DeclBase.h:439
void dropAttr()
Definition DeclBase.h:564
bool hasAttr() const
Definition DeclBase.h:585
The name of a declaration.
Represents a ValueDecl that came out of a declarator.
Definition Decl.h:780
SourceLocation getBeginLoc() const LLVM_READONLY
Definition Decl.h:831
This represents one expression.
Definition Expr.h:112
bool isIntegerConstantExpr(const ASTContext &Ctx) const
void setType(QualType t)
Definition Expr.h:145
ExprValueKind getValueKind() const
getValueKind - The value kind that this expression produces.
Definition Expr.h:447
Expr * IgnoreParenImpCasts() LLVM_READONLY
Skip past any parentheses and implicit casts which might surround this expression until reaching a fi...
Definition Expr.cpp:3099
Expr * IgnoreParens() LLVM_READONLY
Skip past any parentheses which might surround this expression until reaching a fixed point.
Definition Expr.cpp:3095
std::optional< llvm::APSInt > getIntegerConstantExpr(const ASTContext &Ctx) const
isIntegerConstantExpr - Return the value if this expression is a valid integer constant expression.
bool isPRValue() const
Definition Expr.h:285
bool isLValue() const
isLValue - True if this expression is an "l-value" according to the rules of the current language.
Definition Expr.h:284
ExprObjectKind getObjectKind() const
getObjectKind - The object kind that this expression produces.
Definition Expr.h:454
Expr * IgnoreCasts() LLVM_READONLY
Skip past any casts which might surround this expression until reaching a fixed point.
Definition Expr.cpp:3083
bool HasSideEffects(const ASTContext &Ctx, bool IncludePossibleEffects=true) const
HasSideEffects - This routine returns true for all those expressions which have any effect other than...
Definition Expr.cpp:3697
SourceLocation getExprLoc() const LLVM_READONLY
getExprLoc - Return the preferred location for the arrow when diagnosing a problem with a generic exp...
Definition Expr.cpp:283
@ MLV_Valid
Definition Expr.h:306
QualType getType() const
Definition Expr.h:144
ExtVectorType - Extended vector type.
Definition TypeBase.h:4331
Represents difference between two FPOptions values.
Represents a member of a struct/union/class.
Definition Decl.h:3182
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)
Definition Decl.cpp:4694
static FixItHint CreateReplacement(CharSourceRange RemoveRange, StringRef Code)
Create a code modification hint that replaces the given source range with the given code string.
Definition Diagnostic.h:141
Represents a function declaration or definition.
Definition Decl.h:2018
const ParmVarDecl * getParamDecl(unsigned i) const
Definition Decl.h:2815
Stmt * getBody(const FunctionDecl *&Definition) const
Retrieve the body (definition) of the function.
Definition Decl.cpp:3253
bool isThisDeclarationADefinition() const
Returns whether this specific declaration of the function is also a definition that does not contain ...
Definition Decl.h:2332
QualType getReturnType() const
Definition Decl.h:2863
ArrayRef< ParmVarDecl * > parameters() const
Definition Decl.h:2792
bool isTemplateInstantiation() const
Determines if the given function was instantiated from a function template.
Definition Decl.cpp:4231
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.
Definition Decl.cpp:3800
DeclarationNameInfo getNameInfo() const
Definition Decl.h:2229
bool hasBody(const FunctionDecl *&Definition) const
Returns true if the function has a body.
Definition Decl.cpp:3173
bool isDefined(const FunctionDecl *&Definition, bool CheckForPendingFriendDefinition=false) const
Returns true if the function has a definition that does not need to be instantiated.
Definition Decl.cpp:3220
HLSLBufferDecl - Represent a cbuffer or tbuffer declaration.
Definition Decl.h:5216
static HLSLBufferDecl * Create(ASTContext &C, DeclContext *LexicalParent, bool CBuffer, SourceLocation KwLoc, IdentifierInfo *ID, SourceLocation IDLoc, SourceLocation LBrace)
Definition Decl.cpp:5904
void addLayoutStruct(CXXRecordDecl *LS)
Definition Decl.cpp:5944
void setHasValidPackoffset(bool PO)
Definition Decl.h:5261
static HLSLBufferDecl * CreateDefaultCBuffer(ASTContext &C, DeclContext *LexicalParent, ArrayRef< Decl * > DefaultCBufferDecls)
Definition Decl.cpp:5927
buffer_decl_range buffer_decls() const
Definition Decl.h:5291
static HLSLOutArgExpr * Create(const ASTContext &C, QualType Ty, OpaqueValueExpr *Base, OpaqueValueExpr *OpV, Expr *WB, bool IsInOut)
Definition Expr.cpp:5655
static HLSLRootSignatureDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation Loc, IdentifierInfo *ID, llvm::dxbc::RootSignatureVersion Version, ArrayRef< llvm::hlsl::rootsig::RootElement > RootElements)
Definition Decl.cpp:5990
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 ...
Definition Expr.h:3856
static ImplicitCastExpr * Create(const ASTContext &Context, QualType T, CastKind Kind, Expr *Operand, const CXXCastPath *BasePath, ExprValueKind Cat, FPOptionsOverride FPO)
Definition Expr.cpp:2079
Describes an C or C++ initializer list.
Definition Expr.h:5302
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'.
Definition Expr.cpp:981
iterator begin(Source *source, bool LocalOnly=false)
Represents the results of name lookup.
Definition Lookup.h:147
Represents a prvalue temporary that is written into memory so that a reference can bind to it.
Definition ExprCXX.h:4920
Represents a matrix type, as defined in the Matrix Types clang extensions.
Definition TypeBase.h:4401
MemberExpr - [C99 6.5.2.3] Structure and Union Members.
Definition Expr.h:3367
ValueDecl * getMemberDecl() const
Retrieve the member declaration to which this expression refers.
Definition Expr.h:3450
Expr * getBase() const
Definition Expr.h:3444
This represents a decl that may have a name.
Definition Decl.h:274
NamedDecl * getUnderlyingDecl()
Looks through UsingDecls and ObjCCompatibleAliasDecls for the underlying named decl.
Definition Decl.h:487
IdentifierInfo * getIdentifier() const
Get the identifier that names this declaration, if there is one.
Definition Decl.h:295
StringRef getName() const
Get the name of identifier for this declaration as a StringRef.
Definition Decl.h:301
DeclarationName getDeclName() const
Get the actual, stored name of the declaration, which may be a special name.
Definition Decl.h:340
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.
Definition Expr.h:1181
Represents a parameter to a function.
Definition Decl.h:1808
ParsedAttr - Represents a syntactic attribute.
Definition ParsedAttr.h:119
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
Definition ParsedAttr.h:389
bool hasParsedType() const
Definition ParsedAttr.h:337
void setInvalid(bool b=true) const
Definition ParsedAttr.h:345
const ParsedType & getTypeArg() const
Definition ParsedAttr.h:459
unsigned getNumArgs() const
getNumArgs - Return the number of actual arguments to this attribute.
Definition ParsedAttr.h:371
bool isArgIdent(unsigned Arg) const
Definition ParsedAttr.h:385
Expr * getArgAsExpr(unsigned Arg) const
Definition ParsedAttr.h:383
AttributeCommonInfo::Kind getKind() const
Definition ParsedAttr.h:610
A (possibly-)qualified type.
Definition TypeBase.h:937
void addRestrict()
Add the restrict qualifier to this QualType.
Definition TypeBase.h:1187
QualType getNonLValueExprType(const ASTContext &Context) const
Determine the type of a (typically non-lvalue) expression with the specified result type.
Definition Type.cpp:3683
QualType getDesugaredType(const ASTContext &Context) const
Return the specified type with any "sugar" removed from the type.
Definition TypeBase.h:1311
bool isNull() const
Return true if this QualType doesn't point to a type yet.
Definition TypeBase.h:1004
const Type * getTypePtr() const
Retrieves a pointer to the underlying (unqualified) type.
Definition TypeBase.h:8447
LangAS getAddressSpace() const
Return the address space of this type.
Definition TypeBase.h:8573
QualType getNonReferenceType() const
If Type is a reference type (e.g., const int&), returns the type that the reference refers to ("const...
Definition TypeBase.h:8632
QualType getCanonicalType() const
Definition TypeBase.h:8499
QualType getUnqualifiedType() const
Retrieve the unqualified variant of the given type, removing as little sugar as possible.
Definition TypeBase.h:8541
bool hasAddressSpace() const
Check if this type has any address space qualifier.
Definition TypeBase.h:8568
Represents a struct/union/class.
Definition Decl.h:4347
field_range fields() const
Definition Decl.h:4550
RecordDecl * getDefinitionOrSelf() const
Definition Decl.h:4535
bool field_empty() const
Definition Decl.h:4558
bool hasBindingInfoForDecl(const VarDecl *VD) const
Definition SemaHLSL.cpp:233
DeclBindingInfo * getDeclBindingInfo(const VarDecl *VD, ResourceClass ResClass)
Definition SemaHLSL.cpp:219
DeclBindingInfo * addDeclBindingInfo(const VarDecl *VD, ResourceClass ResClass)
Definition SemaHLSL.cpp:206
Scope - A scope is a transient data structure that is used while parsing the program.
Definition Scope.h:41
SemaBase(Sema &S)
Definition SemaBase.cpp:7
ASTContext & getASTContext() const
Definition SemaBase.cpp:9
Sema & SemaRef
Definition SemaBase.h:40
SemaDiagnosticBuilder Diag(SourceLocation Loc, unsigned DiagID)
Emit a diagnostic.
Definition SemaBase.cpp:61
ExprResult ActOnOutParamExpr(ParmVarDecl *Param, Expr *Arg)
HLSLRootSignatureDecl * lookupRootSignatureOverrideDecl(DeclContext *DC) const
bool CanPerformElementwiseCast(Expr *Src, QualType DestType)
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 handleShaderAttr(Decl *D, const ParsedAttr &AL)
uint32_t getNextImplicitBindingOrderID()
Definition SemaHLSL.h:247
void CheckEntryPoint(FunctionDecl *FD)
Definition SemaHLSL.cpp:984
void handleVkExtBuiltinOutputAttr(Decl *D, const ParsedAttr &AL)
void emitLogicalOperatorFixIt(Expr *LHS, Expr *RHS, BinaryOperatorKind Opc)
T * createSemanticAttr(const AttributeCommonInfo &ACI, std::optional< unsigned > Location)
Definition SemaHLSL.h:198
bool initGlobalResourceDecl(VarDecl *VD)
void ActOnEndOfTranslationUnit(TranslationUnitDecl *TU)
bool initGlobalResourceArrayDecl(VarDecl *VD)
HLSLVkConstantIdAttr * mergeVkConstantIdAttr(Decl *D, const AttributeCommonInfo &AL, int Id)
Definition SemaHLSL.cpp:748
HLSLNumThreadsAttr * mergeNumThreadsAttr(Decl *D, const AttributeCommonInfo &AL, int X, int Y, int Z)
Definition SemaHLSL.cpp:714
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)
std::optional< ExprResult > tryPerformConstantBufferConversion(ExprResult &BaseExpr)
bool diagnosePositionType(QualType T, const ParsedAttr &AL)
bool handleInitialization(VarDecl *VDecl, Expr *&Init)
bool diagnoseInputIDType(QualType T, const ParsedAttr &AL)
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 diagnoseSystemSemanticAttr(Decl *D, const ParsedAttr &AL, std::optional< unsigned > Index)
void handleRootSignatureAttr(Decl *D, const ParsedAttr &AL)
bool CheckCompatibleParameterABI(FunctionDecl *New, FunctionDecl *Old)
QualType handleVectorBinOpConversion(ExprResult &LHS, ExprResult &RHS, QualType LHSType, QualType RHSType, bool IsCompAssign)
QualType checkMatrixComponent(Sema &S, QualType baseType, ExprValueKind &VK, SourceLocation OpLoc, const IdentifierInfo *CompName, SourceLocation CompLoc)
bool IsConstantBufferElementCompatible(QualType T1)
void handleResourceBindingAttr(Decl *D, const ParsedAttr &AL)
bool IsTypedResourceElementCompatible(QualType T1)
bool transformInitList(const InitializedEntity &Entity, InitListExpr *Init)
void handleNumThreadsAttr(Decl *D, const ParsedAttr &AL)
bool ActOnUninitializedVarDecl(VarDecl *D)
void handleVkExtBuiltinInputAttr(Decl *D, const ParsedAttr &AL)
bool canHaveOverloadedBinOp(QualType Ty, BinaryOperatorKind Opc)
void ActOnTopLevelFunction(FunctionDecl *FD)
Definition SemaHLSL.cpp:817
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)
Definition SemaHLSL.cpp:784
NamedDecl * getConstantBufferConversionFunction(QualType Type, CXXRecordDecl *RD)
void ActOnFinishBuffer(Decl *Dcl, SourceLocation RBrace)
Definition SemaHLSL.cpp:687
void handleVkBindingAttr(Decl *D, const ParsedAttr &AL)
HLSLParamModifierAttr * mergeParamModifierAttr(Decl *D, const AttributeCommonInfo &AL, HLSLParamModifierAttr::Spelling Spelling)
Definition SemaHLSL.cpp:797
QualType getInoutParameterType(QualType Ty)
SemaHLSL(Sema &S)
Definition SemaHLSL.cpp:237
void handleVkConstantIdAttr(Decl *D, const ParsedAttr &AL)
Decl * ActOnStartBuffer(Scope *BufferScope, bool CBuffer, SourceLocation KwLoc, IdentifierInfo *Ident, SourceLocation IdentLoc, SourceLocation LBrace)
Definition SemaHLSL.cpp:239
bool diagnoseMatrixLayoutInstantiation(attr::Kind K, QualType T, SourceLocation Loc)
HLSLWaveSizeAttr * mergeWaveSizeAttr(Decl *D, const AttributeCommonInfo &AL, int Min, int Max, int Preferred, int SpelledArgsCount)
Definition SemaHLSL.cpp:728
bool handleRootSignatureElements(ArrayRef< hlsl::RootSignatureElement > Elements)
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.
Definition Sema.h:868
@ LookupOrdinaryName
Ordinary name lookup, which finds ordinary names (functions, variables, typedefs, etc....
Definition Sema.h:9420
@ LookupMemberName
Member name lookup, which finds the names of class/struct/union members.
Definition Sema.h:9428
ExtVectorDeclsType ExtVectorDecls
ExtVectorDecls - This is a list all the extended vector types.
Definition Sema.h:4955
ASTContext & Context
Definition Sema.h:1308
ASTContext & getASTContext() const
Definition Sema.h:939
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.
Definition Sema.cpp:762
const LangOptions & getLangOpts() const
Definition Sema.h:932
ExprResult TemporaryMaterializationConversion(Expr *E)
If E is a prvalue denoting an unmaterialized temporary, materialize it as an xvalue.
SemaHLSL & HLSL()
Definition Sema.h:1483
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
Definition Sema.h:942
ASTConsumer & Consumer
Definition Sema.h:1309
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.
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
Definition Stmt.cpp:367
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...
Definition Stmt.cpp:343
SourceLocation getBeginLoc() const LLVM_READONLY
Definition Stmt.cpp:355
StringLiteral - This represents a string literal expression, e.g.
Definition Expr.h:1802
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...
Definition Expr.cpp:1194
void startDefinition()
Starts the definition of this tag declaration.
Definition Decl.cpp:4900
bool isUnion() const
Definition Decl.h:3950
bool isClass() const
Definition Decl.h:3949
Exposes information about the current target.
Definition TargetInfo.h:227
TargetOptions & getTargetOpts() const
Retrieve the target options.
Definition TargetInfo.h:327
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.
Definition Decl.h:105
SourceLocation getBeginLoc() const
Get the begin source location.
Definition TypeLoc.cpp:193
A container of type source information.
Definition TypeBase.h:8418
TypeLoc getTypeLoc() const
Return the TypeLoc wrapper for the type source info.
Definition TypeLoc.h:267
The base class of the type hierarchy.
Definition TypeBase.h:1875
bool isVoidType() const
Definition TypeBase.h:9050
bool isBooleanType() const
Definition TypeBase.h:9187
bool isIncompleteArrayType() const
Definition TypeBase.h:8791
CXXRecordDecl * getAsCXXRecordDecl() const
Retrieves the CXXRecordDecl that this type refers to, either because the type is a RecordType or beca...
Definition Type.h:26
bool isConstantArrayType() const
Definition TypeBase.h:8787
bool hasIntegerRepresentation() const
Determine whether this type has an integer representation of some sort, e.g., it is an integer type o...
Definition Type.cpp:2120
bool isArrayType() const
Definition TypeBase.h:8783
CXXRecordDecl * castAsCXXRecordDecl() const
Definition Type.h:36
bool isArithmeticType() const
Definition Type.cpp:2423
bool isConstantMatrixType() const
Definition TypeBase.h:8851
bool isHLSLBuiltinIntangibleType() const
Definition TypeBase.h:8995
bool isPointerType() const
Definition TypeBase.h:8684
CanQualType getCanonicalTypeUnqualified() const
bool isIntegerType() const
isIntegerType() does not include complex integers (a GCC extension).
Definition TypeBase.h:9094
const T * castAs() const
Member-template castAs<specific type>.
Definition TypeBase.h:9344
bool isReferenceType() const
Definition TypeBase.h:8708
bool isHLSLIntangibleType() const
Definition Type.cpp:5524
bool isEnumeralType() const
Definition TypeBase.h:8815
bool isScalarType() const
Definition TypeBase.h:9156
bool isIntegralType(const ASTContext &Ctx) const
Determine whether this type is an integral type.
Definition Type.cpp:2157
const Type * getArrayElementTypeNoTypeQual() const
If this is an array type, return the element type of the array, potentially with type qualifiers miss...
Definition Type.cpp:509
QualType getPointeeType() const
If this is a pointer, ObjC object pointer, or block pointer, this returns the respective pointee.
Definition Type.cpp:790
bool hasUnsignedIntegerRepresentation() const
Determine whether this type has an unsigned integer representation of some sort, e....
Definition Type.cpp:2377
bool isDependentType() const
Whether this type is a dependent type, meaning that its definition somehow depends on a template para...
Definition TypeBase.h:2846
bool isAggregateType() const
Determines whether the type is a C++ aggregate type or C aggregate or union type.
Definition Type.cpp:2504
ScalarTypeKind getScalarTypeKind() const
Given that this is a scalar type, classify it.
Definition Type.cpp:2455
bool hasSignedIntegerRepresentation() const
Determine whether this type has an signed integer representation of some sort, e.g....
Definition Type.cpp:2311
bool isMatrixType() const
Definition TypeBase.h:8847
bool isHLSLResourceRecord() const
Definition Type.cpp:5511
bool hasFloatingRepresentation() const
Determine whether this type has a floating-point representation of some sort, e.g....
Definition Type.cpp:2398
bool isVectorType() const
Definition TypeBase.h:8823
bool isRealFloatingType() const
Floating point categories.
Definition Type.cpp:2406
bool isHLSLAttributedResourceType() const
Definition TypeBase.h:9007
@ STK_FloatingComplex
Definition TypeBase.h:2828
@ STK_ObjCObjectPointer
Definition TypeBase.h:2822
@ STK_IntegralComplex
Definition TypeBase.h:2827
@ STK_MemberPointer
Definition TypeBase.h:2823
bool isFloatingType() const
Definition Type.cpp:2390
bool isSamplerT() const
Definition TypeBase.h:8928
const T * getAs() const
Member-template getAs<specific type>'.
Definition TypeBase.h:9277
const Type * getUnqualifiedDesugaredType() const
Return the specified type with any "sugar" removed from the type, removing any typedefs,...
Definition Type.cpp:691
bool isRecordType() const
Definition TypeBase.h:8811
bool isHLSLResourceRecordArray() const
Definition Type.cpp:5515
void setType(QualType newType)
Definition Decl.h:724
QualType getType() const
Definition Decl.h:723
Represents a variable declaration or definition.
Definition Decl.h:924
static VarDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc, const IdentifierInfo *Id, QualType T, TypeSourceInfo *TInfo, StorageClass S)
Definition Decl.cpp:2130
void setInitStyle(InitializationStyle Style)
Definition Decl.h:1465
@ CallInit
Call-style initialization (C++98)
Definition Decl.h:932
void setStorageClass(StorageClass SC)
Definition Decl.cpp:2142
bool hasGlobalStorage() const
Returns true for all variables that do not have local storage.
Definition Decl.h:1239
void setInit(Expr *I)
Definition Decl.cpp:2456
StorageClass getStorageClass() const
Returns the storage class as written in the source.
Definition Decl.h:1166
Represents a GCC generic vector type.
Definition TypeBase.h:4239
unsigned getNumElements() const
Definition TypeBase.h:4254
QualType getElementType() const
Definition TypeBase.h:4253
IdentifierInfo * getNameAsIdentifier(ASTContext &AST) const
Defines the clang::TargetInfo interface.
Definition SPIR.cpp:47
uint32_t getResourceDimensions(llvm::dxil::ResourceDimension Dim)
bool hasCounterHandle(const CXXRecordDecl *RD)
llvm::ImmutableSet< T > join(llvm::ImmutableSet< T > A, llvm::ImmutableSet< T > B, typename llvm::ImmutableSet< T >::Factory &F)
Computes the union of two ImmutableSets.
Definition Utils.h:39
The JSON file list parser is used to communicate input to InstallAPI.
bool isa(CodeGen::Address addr)
Definition Address.h:330
if(T->getSizeExpr()) TRY_TO(TraverseStmt(const_cast< Expr * >(T -> getSizeExpr())))
static bool CheckFloatOrHalfRepresentation(Sema *S, SourceLocation Loc, int ArgOrdinal, clang::QualType PassedType)
Definition SemaSPIRV.cpp:66
@ ICIS_NoInit
No in-class initializer.
Definition Specifiers.h:273
@ TemplateName
The identifier is a template name. FIXME: Add an annotation for that.
Definition Parser.h:61
@ OK_Ordinary
An ordinary object is located at an address in memory.
Definition Specifiers.h:152
static bool CheckAllArgTypesAreCorrect(Sema *S, CallExpr *TheCall, llvm::ArrayRef< llvm::function_ref< bool(Sema *, SourceLocation, int, QualType)> > Checks)
Definition SemaSPIRV.cpp:49
@ AS_public
Definition Specifiers.h:125
@ AS_none
Definition Specifiers.h:128
@ SC_Extern
Definition Specifiers.h:252
@ SC_Static
Definition Specifiers.h:253
@ SC_None
Definition Specifiers.h:251
@ AANT_ArgumentIdentifier
@ Result
The result type of a method or function.
Definition TypeBase.h:905
@ Ordinary
This parameter uses ordinary ABI rules for its type.
Definition Specifiers.h:383
llvm::Expected< QualType > ExpectedType
@ Template
We are parsing a template declaration.
Definition Parser.h:81
LLVM_READONLY bool isDigit(unsigned char c)
Return true if this character is an ASCII digit: [0-9].
Definition CharInfo.h:114
static bool CheckAllArgsHaveSameType(Sema *S, CallExpr *TheCall)
Definition SemaSPIRV.cpp:32
ExprResult ExprError()
Definition Ownership.h:265
@ Type
The name was classified as a type.
Definition Sema.h:564
LangAS
Defines the address space values used by the address space qualifier of QualType.
bool CreateHLSLAttributedResourceType(Sema &S, QualType Wrapped, ArrayRef< const Attr * > AttrList, QualType &ResType, HLSLAttributedResourceLocInfo *LocInfo=nullptr)
CastKind
CastKind - The kind of operation required for a conversion.
ExprValueKind
The categorization of expression values, currently following the C++11 scheme.
Definition Specifiers.h:133
@ VK_PRValue
A pr-value expression (in the C++11 taxonomy) produces a temporary value.
Definition Specifiers.h:136
@ VK_LValue
An l-value expression is a reference to an object with independent storage.
Definition Specifiers.h:140
DynamicRecursiveASTVisitorBase< false > DynamicRecursiveASTVisitor
U cast(CodeGen::Address addr)
Definition Address.h:327
@ None
No keyword precedes the qualified type name.
Definition TypeBase.h:5991
ActionResult< Expr * > ExprResult
Definition Ownership.h:249
Visibility
Describes the different kinds of visibility that a declaration may have.
Definition Visibility.h:34
unsigned long uint64_t
hash_code hash_value(const clang::dependencies::ModuleID &ID)
__DEVICE__ bool isnan(float __x)
__DEVICE__ _Tp abs(const std::complex< _Tp > &__c)
__packed_splat4 __packed_splat2 __packed_splat8 __packed_splat4 __packed_splat2 __packed_splat4 __packed_splat2 __packed_splat8 __packed_splat4 uint32_t
#define false
Definition stdbool.h:26
Describes how types, statements, expressions, and declarations should be printed.
void setCounterImplicitOrderID(unsigned Value) const
void setImplicitOrderID(unsigned Value) const
const SourceLocation & getLocation() const
Definition SemaHLSL.h:48
const llvm::hlsl::rootsig::RootElement & getElement() const
Definition SemaHLSL.h:47