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