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