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