1//===- Type.cpp - Type representation and manipulation --------------------===//
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//
9// This file implements type-related functionality.
10//
11//===----------------------------------------------------------------------===//
12
13#include "clang/AST/Type.h"
14#include "Linkage.h"
15#include "clang/AST/ASTContext.h"
16#include "clang/AST/Attr.h"
17#include "clang/AST/CharUnits.h"
18#include "clang/AST/Decl.h"
19#include "clang/AST/DeclBase.h"
20#include "clang/AST/DeclCXX.h"
21#include "clang/AST/DeclFriend.h"
22#include "clang/AST/DeclObjC.h"
23#include "clang/AST/DeclTemplate.h"
24#include "clang/AST/DependenceFlags.h"
25#include "clang/AST/Expr.h"
26#include "clang/AST/NestedNameSpecifier.h"
27#include "clang/AST/PrettyPrinter.h"
28#include "clang/AST/TemplateBase.h"
29#include "clang/AST/TemplateName.h"
30#include "clang/AST/TypeVisitor.h"
31#include "clang/Basic/AddressSpaces.h"
32#include "clang/Basic/ExceptionSpecificationType.h"
33#include "clang/Basic/IdentifierTable.h"
34#include "clang/Basic/LLVM.h"
35#include "clang/Basic/LangOptions.h"
36#include "clang/Basic/Linkage.h"
37#include "clang/Basic/Specifiers.h"
38#include "clang/Basic/TargetCXXABI.h"
39#include "clang/Basic/TargetInfo.h"
40#include "clang/Basic/Visibility.h"
41#include "llvm/ADT/APInt.h"
42#include "llvm/ADT/APSInt.h"
43#include "llvm/ADT/ArrayRef.h"
44#include "llvm/ADT/FoldingSet.h"
45#include "llvm/ADT/STLExtras.h"
46#include "llvm/ADT/SmallVector.h"
47#include "llvm/Support/ErrorHandling.h"
48#include "llvm/Support/MathExtras.h"
49#include <algorithm>
50#include <cassert>
51#include <cstdint>
52#include <cstring>
53#include <optional>
54
55using namespace clang;
56
57bool Qualifiers::isStrictSupersetOf(Qualifiers Other) const {
58 return (*this != Other) &&
59 // CVR qualifiers superset
60 (((Mask & CVRMask) | (Other.Mask & CVRMask)) == (Mask & CVRMask)) &&
61 // ObjC GC qualifiers superset
62 ((getObjCGCAttr() == Other.getObjCGCAttr()) ||
63 (hasObjCGCAttr() && !Other.hasObjCGCAttr())) &&
64 // Address space superset.
65 ((getAddressSpace() == Other.getAddressSpace()) ||
66 (hasAddressSpace() && !Other.hasAddressSpace())) &&
67 // Lifetime qualifier superset.
68 ((getObjCLifetime() == Other.getObjCLifetime()) ||
69 (hasObjCLifetime() && !Other.hasObjCLifetime()));
70}
71
72bool Qualifiers::isTargetAddressSpaceSupersetOf(LangAS A, LangAS B,
73 const ASTContext &Ctx) {
74 // In OpenCLC v2.0 s6.5.5: every address space except for __constant can be
75 // used as __generic.
76 return (A == LangAS::opencl_generic && B != LangAS::opencl_constant) ||
77 // We also define global_device and global_host address spaces,
78 // to distinguish global pointers allocated on host from pointers
79 // allocated on device, which are a subset of __global.
80 (A == LangAS::opencl_global && (B == LangAS::opencl_global_device ||
81 B == LangAS::opencl_global_host)) ||
82 (A == LangAS::sycl_global &&
83 (B == LangAS::sycl_global_device || B == LangAS::sycl_global_host)) ||
84 // Consider pointer size address spaces to be equivalent to default.
85 ((isPtrSizeAddressSpace(AS: A) || A == LangAS::Default) &&
86 (isPtrSizeAddressSpace(AS: B) || B == LangAS::Default)) ||
87 // Default is a superset of SYCL address spaces.
88 (A == LangAS::Default &&
89 (B == LangAS::sycl_private || B == LangAS::sycl_local ||
90 B == LangAS::sycl_global || B == LangAS::sycl_global_device ||
91 B == LangAS::sycl_global_host)) ||
92 // In HIP device compilation, any cuda address space is allowed
93 // to implicitly cast into the default address space.
94 (A == LangAS::Default &&
95 (B == LangAS::cuda_constant || B == LangAS::cuda_device ||
96 B == LangAS::cuda_shared || B == LangAS::amdgpu_barrier)) ||
97 // In HLSL, the this pointer for member functions points to the default
98 // address space. This causes a problem if the structure is in
99 // a different address space. We want to allow casting from these
100 // address spaces to default to work around this problem.
101 (A == LangAS::Default && B == LangAS::hlsl_private) ||
102 (A == LangAS::Default && B == LangAS::hlsl_device) ||
103 (A == LangAS::Default && B == LangAS::hlsl_input) ||
104 (A == LangAS::Default && B == LangAS::hlsl_output) ||
105 (A == LangAS::Default && B == LangAS::hlsl_push_constant) ||
106 // Conversions from target specific address spaces may be legal
107 // depending on the target information.
108 Ctx.getTargetInfo().isAddressSpaceSupersetOf(A, B);
109}
110
111const IdentifierInfo *QualType::getBaseTypeIdentifier() const {
112 const Type *ty = getTypePtr();
113 NamedDecl *ND = nullptr;
114 if (const auto *DNT = ty->getAs<DependentNameType>())
115 return DNT->getIdentifier();
116 if (ty->isPointerOrReferenceType())
117 return ty->getPointeeType().getBaseTypeIdentifier();
118 if (const auto *TT = ty->getAs<TagType>())
119 ND = TT->getDecl();
120 else if (ty->getTypeClass() == Type::Typedef)
121 ND = ty->castAs<TypedefType>()->getDecl();
122 else if (ty->isArrayType())
123 return ty->castAsArrayTypeUnsafe()
124 ->getElementType()
125 .getBaseTypeIdentifier();
126
127 if (ND)
128 return ND->getIdentifier();
129 return nullptr;
130}
131
132bool QualType::hasPostfixDeclaratorSyntax() const {
133 QualType QT = *this;
134 while (true) {
135 const Type *T = QT.getTypePtr();
136 switch (T->getTypeClass()) {
137 default:
138 return false;
139 case Type::Pointer:
140 QT = cast<PointerType>(Val: T)->getPointeeType();
141 break;
142 case Type::BlockPointer:
143 QT = cast<BlockPointerType>(Val: T)->getPointeeType();
144 break;
145 case Type::MemberPointer:
146 QT = cast<MemberPointerType>(Val: T)->getPointeeType();
147 break;
148 case Type::LValueReference:
149 case Type::RValueReference:
150 QT = cast<ReferenceType>(Val: T)->getPointeeType();
151 break;
152 case Type::PackExpansion:
153 QT = cast<PackExpansionType>(Val: T)->getPattern();
154 break;
155 case Type::Paren:
156 case Type::ConstantArray:
157 case Type::DependentSizedArray:
158 case Type::IncompleteArray:
159 case Type::VariableArray:
160 case Type::FunctionProto:
161 case Type::FunctionNoProto:
162 return true;
163 }
164 }
165}
166
167bool QualType::mayBeDynamicClass() const {
168 const auto *ClassDecl = getTypePtr()->getPointeeCXXRecordDecl();
169 return ClassDecl && ClassDecl->mayBeDynamicClass();
170}
171
172bool QualType::mayBeNotDynamicClass() const {
173 const auto *ClassDecl = getTypePtr()->getPointeeCXXRecordDecl();
174 return !ClassDecl || ClassDecl->mayBeNonDynamicClass();
175}
176
177bool QualType::isConstant(QualType T, const ASTContext &Ctx) {
178 if (T.isConstQualified())
179 return true;
180
181 if (const ArrayType *AT = Ctx.getAsArrayType(T))
182 return AT->getElementType().isConstant(Ctx);
183
184 return T.getAddressSpace() == LangAS::opencl_constant;
185}
186
187std::optional<QualType::NonConstantStorageReason>
188QualType::isNonConstantStorage(const ASTContext &Ctx, bool ExcludeCtor,
189 bool ExcludeDtor) {
190 if (!isConstant(Ctx) && !(*this)->isReferenceType())
191 return NonConstantStorageReason::NonConstNonReferenceType;
192 if (!Ctx.getLangOpts().CPlusPlus)
193 return std::nullopt;
194 if (const CXXRecordDecl *Record =
195 Ctx.getBaseElementType(QT: *this)->getAsCXXRecordDecl()) {
196 if (!ExcludeCtor)
197 return NonConstantStorageReason::NonTrivialCtor;
198 if (Record->hasMutableFields())
199 return NonConstantStorageReason::MutableField;
200 if (!Record->hasTrivialDestructor() && !ExcludeDtor)
201 return NonConstantStorageReason::NonTrivialDtor;
202 }
203 return std::nullopt;
204}
205
206// C++ [temp.dep.type]p1:
207// A type is dependent if it is...
208// - an array type constructed from any dependent type or whose
209// size is specified by a constant expression that is
210// value-dependent,
211ArrayType::ArrayType(TypeClass tc, QualType et, QualType can,
212 ArraySizeModifier sm, unsigned tq, const Expr *sz)
213 // Note, we need to check for DependentSizedArrayType explicitly here
214 // because we use a DependentSizedArrayType with no size expression as the
215 // type of a dependent array of unknown bound with a dependent braced
216 // initializer:
217 //
218 // template<int ...N> int arr[] = {N...};
219 : Type(tc, can,
220 et->getDependence() |
221 (sz ? toTypeDependence(
222 D: turnValueToTypeDependence(D: sz->getDependence()))
223 : TypeDependence::None) |
224 (tc == VariableArray ? TypeDependence::VariablyModified
225 : TypeDependence::None) |
226 (tc == DependentSizedArray
227 ? TypeDependence::DependentInstantiation
228 : TypeDependence::None)),
229 ElementType(et) {
230 ArrayTypeBits.IndexTypeQuals = tq;
231 ArrayTypeBits.SizeModifier = llvm::to_underlying(E: sm);
232}
233
234ConstantArrayType *
235ConstantArrayType::Create(const ASTContext &Ctx, QualType ET, QualType Can,
236 const llvm::APInt &Sz, const Expr *SzExpr,
237 ArraySizeModifier SzMod, unsigned Qual) {
238 bool NeedsExternalSize = SzExpr != nullptr || Sz.ugt(RHS: 0x0FFFFFFFFFFFFFFF) ||
239 Sz.getBitWidth() > 0xFF;
240 if (!NeedsExternalSize)
241 return new (Ctx, alignof(ConstantArrayType)) ConstantArrayType(
242 ET, Can, Sz.getBitWidth(), Sz.getZExtValue(), SzMod, Qual);
243
244 auto *SzPtr = new (Ctx, alignof(ConstantArrayType::ExternalSize))
245 ConstantArrayType::ExternalSize(Sz, SzExpr);
246 return new (Ctx, alignof(ConstantArrayType))
247 ConstantArrayType(ET, Can, SzPtr, SzMod, Qual);
248}
249
250unsigned
251ConstantArrayType::getNumAddressingBits(const ASTContext &Context,
252 QualType ElementType,
253 const llvm::APInt &NumElements) {
254 uint64_t ElementSize = Context.getTypeSizeInChars(T: ElementType).getQuantity();
255
256 // Fast path the common cases so we can avoid the conservative computation
257 // below, which in common cases allocates "large" APSInt values, which are
258 // slow.
259
260 // If the element size is a power of 2, we can directly compute the additional
261 // number of addressing bits beyond those required for the element count.
262 if (llvm::isPowerOf2_64(Value: ElementSize)) {
263 return NumElements.getActiveBits() + llvm::Log2_64(Value: ElementSize);
264 }
265
266 // If both the element count and element size fit in 32-bits, we can do the
267 // computation directly in 64-bits.
268 if ((ElementSize >> 32) == 0 && NumElements.getBitWidth() <= 64 &&
269 (NumElements.getZExtValue() >> 32) == 0) {
270 uint64_t TotalSize = NumElements.getZExtValue() * ElementSize;
271 return llvm::bit_width(Value: TotalSize);
272 }
273
274 // Otherwise, use APSInt to handle arbitrary sized values.
275 llvm::APSInt SizeExtended(NumElements, true);
276 unsigned SizeTypeBits = Context.getTypeSize(T: Context.getSizeType());
277 SizeExtended = SizeExtended.extend(
278 width: std::max(a: SizeTypeBits, b: SizeExtended.getBitWidth()) * 2);
279
280 llvm::APSInt TotalSize(llvm::APInt(SizeExtended.getBitWidth(), ElementSize));
281 TotalSize *= SizeExtended;
282
283 return TotalSize.getActiveBits();
284}
285
286unsigned
287ConstantArrayType::getNumAddressingBits(const ASTContext &Context) const {
288 return getNumAddressingBits(Context, ElementType: getElementType(), NumElements: getSize());
289}
290
291unsigned ConstantArrayType::getMaxSizeBits(const ASTContext &Context) {
292 unsigned Bits = Context.getTypeSize(T: Context.getSizeType());
293
294 // Limit the number of bits in size_t so that maximal bit size fits 64 bit
295 // integer (see PR8256). We can do this as currently there is no hardware
296 // that supports full 64-bit virtual space.
297 if (Bits > 61)
298 Bits = 61;
299
300 return Bits;
301}
302
303void ConstantArrayType::Profile(llvm::FoldingSetNodeID &ID,
304 const ASTContext &Context, QualType ET,
305 uint64_t ArraySize, const Expr *SizeExpr,
306 ArraySizeModifier SizeMod, unsigned TypeQuals) {
307 ID.AddPointer(Ptr: ET.getAsOpaquePtr());
308 ID.AddInteger(I: ArraySize);
309 ID.AddInteger(I: llvm::to_underlying(E: SizeMod));
310 ID.AddInteger(I: TypeQuals);
311 ID.AddBoolean(B: SizeExpr != nullptr);
312 if (SizeExpr)
313 SizeExpr->Profile(ID, Context, Canonical: true);
314}
315
316QualType ArrayParameterType::getConstantArrayType(const ASTContext &Ctx) const {
317 return Ctx.getConstantArrayType(EltTy: getElementType(), ArySize: getSize(), SizeExpr: getSizeExpr(),
318 ASM: getSizeModifier(),
319 IndexTypeQuals: getIndexTypeQualifiers().getAsOpaqueValue());
320}
321
322DependentSizedArrayType::DependentSizedArrayType(QualType et, QualType can,
323 Expr *e, ArraySizeModifier sm,
324 unsigned tq)
325 : ArrayType(DependentSizedArray, et, can, sm, tq, e), SizeExpr((Stmt *)e) {}
326
327void DependentSizedArrayType::Profile(llvm::FoldingSetNodeID &ID,
328 const ASTContext &Context, QualType ET,
329 ArraySizeModifier SizeMod,
330 unsigned TypeQuals, Expr *E) {
331 ID.AddPointer(Ptr: ET.getAsOpaquePtr());
332 ID.AddInteger(I: llvm::to_underlying(E: SizeMod));
333 ID.AddInteger(I: TypeQuals);
334 if (E)
335 E->Profile(ID, Context, Canonical: true);
336}
337
338DependentVectorType::DependentVectorType(QualType ElementType,
339 QualType CanonType, Expr *SizeExpr,
340 SourceLocation Loc, VectorKind VecKind)
341 : Type(DependentVector, CanonType,
342 TypeDependence::DependentInstantiation |
343 ElementType->getDependence() |
344 (SizeExpr ? toTypeDependence(D: SizeExpr->getDependence())
345 : TypeDependence::None)),
346 ElementType(ElementType), SizeExpr(SizeExpr), Loc(Loc) {
347 VectorTypeBits.VecKind = llvm::to_underlying(E: VecKind);
348}
349
350void DependentVectorType::Profile(llvm::FoldingSetNodeID &ID,
351 const ASTContext &Context,
352 QualType ElementType, const Expr *SizeExpr,
353 VectorKind VecKind) {
354 ID.AddPointer(Ptr: ElementType.getAsOpaquePtr());
355 ID.AddInteger(I: llvm::to_underlying(E: VecKind));
356 SizeExpr->Profile(ID, Context, Canonical: true);
357}
358
359DependentSizedExtVectorType::DependentSizedExtVectorType(QualType ElementType,
360 QualType can,
361 Expr *SizeExpr,
362 SourceLocation loc)
363 : Type(DependentSizedExtVector, can,
364 TypeDependence::DependentInstantiation |
365 ElementType->getDependence() |
366 (SizeExpr ? toTypeDependence(D: SizeExpr->getDependence())
367 : TypeDependence::None)),
368 SizeExpr(SizeExpr), ElementType(ElementType), loc(loc) {}
369
370void DependentSizedExtVectorType::Profile(llvm::FoldingSetNodeID &ID,
371 const ASTContext &Context,
372 QualType ElementType,
373 Expr *SizeExpr) {
374 ID.AddPointer(Ptr: ElementType.getAsOpaquePtr());
375 SizeExpr->Profile(ID, Context, Canonical: true);
376}
377
378DependentAddressSpaceType::DependentAddressSpaceType(QualType PointeeType,
379 QualType can,
380 Expr *AddrSpaceExpr,
381 SourceLocation loc)
382 : Type(DependentAddressSpace, can,
383 TypeDependence::DependentInstantiation |
384 PointeeType->getDependence() |
385 (AddrSpaceExpr ? toTypeDependence(D: AddrSpaceExpr->getDependence())
386 : TypeDependence::None)),
387 AddrSpaceExpr(AddrSpaceExpr), PointeeType(PointeeType), loc(loc) {}
388
389void DependentAddressSpaceType::Profile(llvm::FoldingSetNodeID &ID,
390 const ASTContext &Context,
391 QualType PointeeType,
392 Expr *AddrSpaceExpr) {
393 ID.AddPointer(Ptr: PointeeType.getAsOpaquePtr());
394 AddrSpaceExpr->Profile(ID, Context, Canonical: true);
395}
396
397MatrixType::MatrixType(TypeClass tc, QualType matrixType, QualType canonType,
398 const Expr *RowExpr, const Expr *ColumnExpr)
399 : Type(tc, canonType,
400 (RowExpr ? (matrixType->getDependence() | TypeDependence::Dependent |
401 TypeDependence::Instantiation |
402 (matrixType->isVariablyModifiedType()
403 ? TypeDependence::VariablyModified
404 : TypeDependence::None) |
405 (matrixType->containsUnexpandedParameterPack() ||
406 (RowExpr &&
407 RowExpr->containsUnexpandedParameterPack()) ||
408 (ColumnExpr &&
409 ColumnExpr->containsUnexpandedParameterPack())
410 ? TypeDependence::UnexpandedPack
411 : TypeDependence::None))
412 : matrixType->getDependence())),
413 ElementType(matrixType) {}
414
415ConstantMatrixType::ConstantMatrixType(QualType matrixType, unsigned nRows,
416 unsigned nColumns, QualType canonType)
417 : ConstantMatrixType(ConstantMatrix, matrixType, nRows, nColumns,
418 canonType) {}
419
420ConstantMatrixType::ConstantMatrixType(TypeClass tc, QualType matrixType,
421 unsigned nRows, unsigned nColumns,
422 QualType canonType)
423 : MatrixType(tc, matrixType, canonType), NumRows(nRows),
424 NumColumns(nColumns) {}
425
426DependentSizedMatrixType::DependentSizedMatrixType(QualType ElementType,
427 QualType CanonicalType,
428 Expr *RowExpr,
429 Expr *ColumnExpr,
430 SourceLocation loc)
431 : MatrixType(DependentSizedMatrix, ElementType, CanonicalType, RowExpr,
432 ColumnExpr),
433 RowExpr(RowExpr), ColumnExpr(ColumnExpr), loc(loc) {}
434
435void DependentSizedMatrixType::Profile(llvm::FoldingSetNodeID &ID,
436 const ASTContext &CTX,
437 QualType ElementType, Expr *RowExpr,
438 Expr *ColumnExpr) {
439 ID.AddPointer(Ptr: ElementType.getAsOpaquePtr());
440 RowExpr->Profile(ID, Context: CTX, Canonical: true);
441 ColumnExpr->Profile(ID, Context: CTX, Canonical: true);
442}
443
444VectorType::VectorType(QualType vecType, unsigned nElements, QualType canonType,
445 VectorKind vecKind)
446 : VectorType(Vector, vecType, nElements, canonType, vecKind) {}
447
448VectorType::VectorType(TypeClass tc, QualType vecType, unsigned nElements,
449 QualType canonType, VectorKind vecKind)
450 : Type(tc, canonType, vecType->getDependence()), ElementType(vecType) {
451 VectorTypeBits.VecKind = llvm::to_underlying(E: vecKind);
452 VectorTypeBits.NumElements = nElements;
453}
454
455bool Type::isPackedVectorBoolType(const ASTContext &ctx) const {
456 if (ctx.getLangOpts().HLSL)
457 return false;
458 return isExtVectorBoolType();
459}
460
461BitIntType::BitIntType(bool IsUnsigned, unsigned NumBits)
462 : Type(BitInt, QualType{}, TypeDependence::None), IsUnsigned(IsUnsigned),
463 NumBits(NumBits) {}
464
465DependentBitIntType::DependentBitIntType(bool IsUnsigned, Expr *NumBitsExpr)
466 : Type(DependentBitInt, QualType{},
467 toTypeDependence(D: NumBitsExpr->getDependence())),
468 ExprAndUnsigned(NumBitsExpr, IsUnsigned) {}
469
470bool DependentBitIntType::isUnsigned() const {
471 return ExprAndUnsigned.getInt();
472}
473
474clang::Expr *DependentBitIntType::getNumBitsExpr() const {
475 return ExprAndUnsigned.getPointer();
476}
477
478void DependentBitIntType::Profile(llvm::FoldingSetNodeID &ID,
479 const ASTContext &Context, bool IsUnsigned,
480 Expr *NumBitsExpr) {
481 ID.AddBoolean(B: IsUnsigned);
482 NumBitsExpr->Profile(ID, Context, Canonical: true);
483}
484
485bool BoundsAttributedType::referencesFieldDecls() const {
486 return llvm::any_of(Range: dependent_decls(),
487 P: [](const TypeCoupledDeclRefInfo &Info) {
488 return isa<FieldDecl>(Val: Info.getDecl());
489 });
490}
491
492void CountAttributedType::Profile(llvm::FoldingSetNodeID &ID,
493 QualType WrappedTy, Expr *CountExpr,
494 bool CountInBytes, bool OrNull) {
495 ID.AddPointer(Ptr: WrappedTy.getAsOpaquePtr());
496 ID.AddBoolean(B: CountInBytes);
497 ID.AddBoolean(B: OrNull);
498 // We profile it as a pointer as the StmtProfiler considers parameter
499 // expressions on function declaration and function definition as the
500 // same, resulting in count expression being evaluated with ParamDecl
501 // not in the function scope.
502 ID.AddPointer(Ptr: CountExpr);
503}
504
505/// getArrayElementTypeNoTypeQual - If this is an array type, return the
506/// element type of the array, potentially with type qualifiers missing.
507/// This method should never be used when type qualifiers are meaningful.
508const Type *Type::getArrayElementTypeNoTypeQual() const {
509 // If this is directly an array type, return it.
510 if (const auto *ATy = dyn_cast<ArrayType>(Val: this))
511 return ATy->getElementType().getTypePtr();
512
513 // If the canonical form of this type isn't the right kind, reject it.
514 if (!isa<ArrayType>(Val: CanonicalType))
515 return nullptr;
516
517 // If this is a typedef for an array type, strip the typedef off without
518 // losing all typedef information.
519 return cast<ArrayType>(Val: getUnqualifiedDesugaredType())
520 ->getElementType()
521 .getTypePtr();
522}
523
524/// getDesugaredType - Return the specified type with any "sugar" removed from
525/// the type. This takes off typedefs, typeof's etc. If the outer level of
526/// the type is already concrete, it returns it unmodified. This is similar
527/// to getting the canonical type, but it doesn't remove *all* typedefs. For
528/// example, it returns "T*" as "T*", (not as "int*"), because the pointer is
529/// concrete.
530QualType QualType::getDesugaredType(QualType T, const ASTContext &Context) {
531 SplitQualType split = getSplitDesugaredType(T);
532 return Context.getQualifiedType(T: split.Ty, Qs: split.Quals);
533}
534
535QualType QualType::getSingleStepDesugaredTypeImpl(QualType type,
536 const ASTContext &Context) {
537 SplitQualType split = type.split();
538 QualType desugar = split.Ty->getLocallyUnqualifiedSingleStepDesugaredType();
539 return Context.getQualifiedType(T: desugar, Qs: split.Quals);
540}
541
542// Check that no type class is polymorphic. LLVM style RTTI should be used
543// instead. If absolutely needed an exception can still be added here by
544// defining the appropriate macro (but please don't do this).
545#define TYPE(CLASS, BASE) \
546 static_assert(!std::is_polymorphic<CLASS##Type>::value, \
547 #CLASS "Type should not be polymorphic!");
548#include "clang/AST/TypeNodes.inc"
549
550// Check that no type class has a non-trival destructor. Types are
551// allocated with the BumpPtrAllocator from ASTContext and therefore
552// their destructor is not executed.
553#define TYPE(CLASS, BASE) \
554 static_assert(std::is_trivially_destructible<CLASS##Type>::value, \
555 #CLASS "Type should be trivially destructible!");
556#include "clang/AST/TypeNodes.inc"
557
558QualType Type::getLocallyUnqualifiedSingleStepDesugaredType() const {
559 switch (getTypeClass()) {
560#define ABSTRACT_TYPE(Class, Parent)
561#define TYPE(Class, Parent) \
562 case Type::Class: { \
563 const auto *ty = cast<Class##Type>(this); \
564 if (!ty->isSugared()) \
565 return QualType(ty, 0); \
566 return ty->desugar(); \
567 }
568#include "clang/AST/TypeNodes.inc"
569 }
570 llvm_unreachable("bad type kind!");
571}
572
573SplitQualType QualType::getSplitDesugaredType(QualType T) {
574 QualifierCollector Qs;
575
576 QualType Cur = T;
577 while (true) {
578 const Type *CurTy = Qs.strip(type: Cur);
579 switch (CurTy->getTypeClass()) {
580#define ABSTRACT_TYPE(Class, Parent)
581#define TYPE(Class, Parent) \
582 case Type::Class: { \
583 const auto *Ty = cast<Class##Type>(CurTy); \
584 if (!Ty->isSugared()) \
585 return SplitQualType(Ty, Qs); \
586 Cur = Ty->desugar(); \
587 break; \
588 }
589#include "clang/AST/TypeNodes.inc"
590 }
591 }
592}
593
594SplitQualType QualType::getSplitUnqualifiedTypeImpl(QualType type) {
595 SplitQualType split = type.split();
596
597 // All the qualifiers we've seen so far.
598 Qualifiers quals = split.Quals;
599
600 // The last type node we saw with any nodes inside it.
601 const Type *lastTypeWithQuals = split.Ty;
602
603 while (true) {
604 QualType next;
605
606 // Do a single-step desugar, aborting the loop if the type isn't
607 // sugared.
608 switch (split.Ty->getTypeClass()) {
609#define ABSTRACT_TYPE(Class, Parent)
610#define TYPE(Class, Parent) \
611 case Type::Class: { \
612 const auto *ty = cast<Class##Type>(split.Ty); \
613 if (!ty->isSugared()) \
614 goto done; \
615 next = ty->desugar(); \
616 break; \
617 }
618#include "clang/AST/TypeNodes.inc"
619 }
620
621 // Otherwise, split the underlying type. If that yields qualifiers,
622 // update the information.
623 split = next.split();
624 if (!split.Quals.empty()) {
625 lastTypeWithQuals = split.Ty;
626 quals.addConsistentQualifiers(qs: split.Quals);
627 }
628 }
629
630done:
631 return SplitQualType(lastTypeWithQuals, quals);
632}
633
634QualType QualType::IgnoreParens(QualType T) {
635 // FIXME: this seems inherently un-qualifiers-safe.
636 while (const auto *PT = T->getAs<ParenType>())
637 T = PT->getInnerType();
638 return T;
639}
640
641/// This will check for a T (which should be a Type which can act as
642/// sugar, such as a TypedefType) by removing any existing sugar until it
643/// reaches a T or a non-sugared type.
644template <typename T> static const T *getAsSugar(const Type *Cur) {
645 while (true) {
646 if (const auto *Sugar = dyn_cast<T>(Cur))
647 return Sugar;
648 switch (Cur->getTypeClass()) {
649#define ABSTRACT_TYPE(Class, Parent)
650#define TYPE(Class, Parent) \
651 case Type::Class: { \
652 const auto *Ty = cast<Class##Type>(Cur); \
653 if (!Ty->isSugared()) \
654 return 0; \
655 Cur = Ty->desugar().getTypePtr(); \
656 break; \
657 }
658#include "clang/AST/TypeNodes.inc"
659 }
660 }
661}
662
663template <> const TypedefType *Type::getAs() const {
664 return getAsSugar<TypedefType>(Cur: this);
665}
666
667template <> const UsingType *Type::getAs() const {
668 return getAsSugar<UsingType>(Cur: this);
669}
670
671template <> const TemplateSpecializationType *Type::getAs() const {
672 return getAsSugar<TemplateSpecializationType>(Cur: this);
673}
674
675template <> const AttributedType *Type::getAs() const {
676 return getAsSugar<AttributedType>(Cur: this);
677}
678
679template <> const BoundsAttributedType *Type::getAs() const {
680 return getAsSugar<BoundsAttributedType>(Cur: this);
681}
682
683template <> const CountAttributedType *Type::getAs() const {
684 return getAsSugar<CountAttributedType>(Cur: this);
685}
686
687/// getUnqualifiedDesugaredType - Pull any qualifiers and syntactic
688/// sugar off the given type. This should produce an object of the
689/// same dynamic type as the canonical type.
690const Type *Type::getUnqualifiedDesugaredType() const {
691 const Type *Cur = this;
692
693 while (true) {
694 switch (Cur->getTypeClass()) {
695#define ABSTRACT_TYPE(Class, Parent)
696#define TYPE(Class, Parent) \
697 case Class: { \
698 const auto *Ty = cast<Class##Type>(Cur); \
699 if (!Ty->isSugared()) \
700 return Cur; \
701 Cur = Ty->desugar().getTypePtr(); \
702 break; \
703 }
704#include "clang/AST/TypeNodes.inc"
705 }
706 }
707}
708
709bool Type::isClassType() const {
710 if (const auto *RT = getAsCanonical<RecordType>())
711 return RT->getDecl()->isClass();
712 return false;
713}
714
715bool Type::isStructureType() const {
716 if (const auto *RT = getAsCanonical<RecordType>())
717 return RT->getDecl()->isStruct();
718 return false;
719}
720
721bool Type::isStructureTypeWithFlexibleArrayMember() const {
722 const auto *RT = getAsCanonical<RecordType>();
723 if (!RT)
724 return false;
725 const auto *Decl = RT->getDecl();
726 if (!Decl->isStruct())
727 return false;
728 return Decl->getDefinitionOrSelf()->hasFlexibleArrayMember();
729}
730
731bool Type::isObjCBoxableRecordType() const {
732 if (const auto *RD = getAsRecordDecl())
733 return RD->hasAttr<ObjCBoxableAttr>();
734 return false;
735}
736
737bool Type::isInterfaceType() const {
738 if (const auto *RT = getAsCanonical<RecordType>())
739 return RT->getDecl()->isInterface();
740 return false;
741}
742
743bool Type::isStructureOrClassType() const {
744 if (const auto *RT = getAsCanonical<RecordType>())
745 return RT->getDecl()->isStructureOrClass();
746 return false;
747}
748
749bool Type::isVoidPointerType() const {
750 if (const auto *PT = getAsCanonical<PointerType>())
751 return PT->getPointeeType()->isVoidType();
752 return false;
753}
754
755bool Type::isUnionType() const {
756 if (const auto *RT = getAsCanonical<RecordType>())
757 return RT->getDecl()->isUnion();
758 return false;
759}
760
761bool Type::isComplexType() const {
762 if (const auto *CT = getAsCanonical<ComplexType>())
763 return CT->getElementType()->isFloatingType();
764 return false;
765}
766
767bool Type::isComplexIntegerType() const {
768 // Check for GCC complex integer extension.
769 return getAsComplexIntegerType();
770}
771
772bool Type::isScopedEnumeralType() const {
773 if (const auto *ET = getAsCanonical<EnumType>())
774 return ET->getDecl()->isScoped();
775 return false;
776}
777
778bool Type::isCountAttributedType() const {
779 return getAs<CountAttributedType>();
780}
781
782const ComplexType *Type::getAsComplexIntegerType() const {
783 if (const auto *Complex = getAs<ComplexType>())
784 if (Complex->getElementType()->isIntegerType())
785 return Complex;
786 return nullptr;
787}
788
789QualType Type::getPointeeType() const {
790 if (const auto *PT = getAs<PointerType>())
791 return PT->getPointeeType();
792 if (const auto *OPT = getAs<ObjCObjectPointerType>())
793 return OPT->getPointeeType();
794 if (const auto *BPT = getAs<BlockPointerType>())
795 return BPT->getPointeeType();
796 if (const auto *RT = getAs<ReferenceType>())
797 return RT->getPointeeType();
798 if (const auto *MPT = getAs<MemberPointerType>())
799 return MPT->getPointeeType();
800 if (const auto *DT = getAs<DecayedType>())
801 return DT->getPointeeType();
802 return {};
803}
804
805const RecordType *Type::getAsStructureType() const {
806 // If this is directly a structure type, return it.
807 if (const auto *RT = dyn_cast<RecordType>(Val: this)) {
808 if (RT->getDecl()->isStruct())
809 return RT;
810 }
811
812 // If the canonical form of this type isn't the right kind, reject it.
813 if (const auto *RT = dyn_cast<RecordType>(Val: CanonicalType)) {
814 if (!RT->getDecl()->isStruct())
815 return nullptr;
816
817 // If this is a typedef for a structure type, strip the typedef off without
818 // losing all typedef information.
819 return cast<RecordType>(Val: getUnqualifiedDesugaredType());
820 }
821 return nullptr;
822}
823
824const RecordType *Type::getAsUnionType() const {
825 // If this is directly a union type, return it.
826 if (const auto *RT = dyn_cast<RecordType>(Val: this)) {
827 if (RT->getDecl()->isUnion())
828 return RT;
829 }
830
831 // If the canonical form of this type isn't the right kind, reject it.
832 if (const auto *RT = dyn_cast<RecordType>(Val: CanonicalType)) {
833 if (!RT->getDecl()->isUnion())
834 return nullptr;
835
836 // If this is a typedef for a union type, strip the typedef off without
837 // losing all typedef information.
838 return cast<RecordType>(Val: getUnqualifiedDesugaredType());
839 }
840
841 return nullptr;
842}
843
844bool Type::isObjCIdOrObjectKindOfType(const ASTContext &ctx,
845 const ObjCObjectType *&bound) const {
846 bound = nullptr;
847
848 const auto *OPT = getAs<ObjCObjectPointerType>();
849 if (!OPT)
850 return false;
851
852 // Easy case: id.
853 if (OPT->isObjCIdType())
854 return true;
855
856 // If it's not a __kindof type, reject it now.
857 if (!OPT->isKindOfType())
858 return false;
859
860 // If it's Class or qualified Class, it's not an object type.
861 if (OPT->isObjCClassType() || OPT->isObjCQualifiedClassType())
862 return false;
863
864 // Figure out the type bound for the __kindof type.
865 bound = OPT->getObjectType()
866 ->stripObjCKindOfTypeAndQuals(ctx)
867 ->getAs<ObjCObjectType>();
868 return true;
869}
870
871bool Type::isObjCClassOrClassKindOfType() const {
872 const auto *OPT = getAs<ObjCObjectPointerType>();
873 if (!OPT)
874 return false;
875
876 // Easy case: Class.
877 if (OPT->isObjCClassType())
878 return true;
879
880 // If it's not a __kindof type, reject it now.
881 if (!OPT->isKindOfType())
882 return false;
883
884 // If it's Class or qualified Class, it's a class __kindof type.
885 return OPT->isObjCClassType() || OPT->isObjCQualifiedClassType();
886}
887
888ObjCTypeParamType::ObjCTypeParamType(const ObjCTypeParamDecl *D, QualType can,
889 ArrayRef<ObjCProtocolDecl *> protocols)
890 : Type(ObjCTypeParam, can, toSemanticDependence(D: can->getDependence())),
891 OTPDecl(const_cast<ObjCTypeParamDecl *>(D)) {
892 initialize(protocols);
893}
894
895ObjCObjectType::ObjCObjectType(QualType Canonical, QualType Base,
896 ArrayRef<QualType> typeArgs,
897 ArrayRef<ObjCProtocolDecl *> protocols,
898 bool isKindOf)
899 : Type(ObjCObject, Canonical, Base->getDependence()), BaseType(Base) {
900 ObjCObjectTypeBits.IsKindOf = isKindOf;
901
902 ObjCObjectTypeBits.NumTypeArgs = typeArgs.size();
903 assert(getTypeArgsAsWritten().size() == typeArgs.size() &&
904 "bitfield overflow in type argument count");
905 if (!typeArgs.empty())
906 memcpy(dest: getTypeArgStorage(), src: typeArgs.data(),
907 n: typeArgs.size() * sizeof(QualType));
908
909 for (auto typeArg : typeArgs) {
910 addDependence(D: typeArg->getDependence() & ~TypeDependence::VariablyModified);
911 }
912 // Initialize the protocol qualifiers. The protocol storage is known
913 // after we set number of type arguments.
914 initialize(protocols);
915}
916
917bool ObjCObjectType::isSpecialized() const {
918 // If we have type arguments written here, the type is specialized.
919 if (ObjCObjectTypeBits.NumTypeArgs > 0)
920 return true;
921
922 // Otherwise, check whether the base type is specialized.
923 if (const auto objcObject = getBaseType()->getAs<ObjCObjectType>()) {
924 // Terminate when we reach an interface type.
925 if (isa<ObjCInterfaceType>(Val: objcObject))
926 return false;
927
928 return objcObject->isSpecialized();
929 }
930
931 // Not specialized.
932 return false;
933}
934
935ArrayRef<QualType> ObjCObjectType::getTypeArgs() const {
936 // We have type arguments written on this type.
937 if (isSpecializedAsWritten())
938 return getTypeArgsAsWritten();
939
940 // Look at the base type, which might have type arguments.
941 if (const auto objcObject = getBaseType()->getAs<ObjCObjectType>()) {
942 // Terminate when we reach an interface type.
943 if (isa<ObjCInterfaceType>(Val: objcObject))
944 return {};
945
946 return objcObject->getTypeArgs();
947 }
948
949 // No type arguments.
950 return {};
951}
952
953bool ObjCObjectType::isKindOfType() const {
954 if (isKindOfTypeAsWritten())
955 return true;
956
957 // Look at the base type, which might have type arguments.
958 if (const auto objcObject = getBaseType()->getAs<ObjCObjectType>()) {
959 // Terminate when we reach an interface type.
960 if (isa<ObjCInterfaceType>(Val: objcObject))
961 return false;
962
963 return objcObject->isKindOfType();
964 }
965
966 // Not a "__kindof" type.
967 return false;
968}
969
970QualType
971ObjCObjectType::stripObjCKindOfTypeAndQuals(const ASTContext &ctx) const {
972 if (!isKindOfType() && qual_empty())
973 return QualType(this, 0);
974
975 // Recursively strip __kindof.
976 SplitQualType splitBaseType = getBaseType().split();
977 QualType baseType(splitBaseType.Ty, 0);
978 if (const auto *baseObj = splitBaseType.Ty->getAs<ObjCObjectType>())
979 baseType = baseObj->stripObjCKindOfTypeAndQuals(ctx);
980
981 return ctx.getObjCObjectType(
982 Base: ctx.getQualifiedType(T: baseType, Qs: splitBaseType.Quals),
983 typeArgs: getTypeArgsAsWritten(),
984 /*protocols=*/{},
985 /*isKindOf=*/false);
986}
987
988ObjCInterfaceDecl *ObjCInterfaceType::getDecl() const {
989 ObjCInterfaceDecl *Canon = Decl->getCanonicalDecl();
990 if (ObjCInterfaceDecl *Def = Canon->getDefinition())
991 return Def;
992 return Canon;
993}
994
995const ObjCObjectPointerType *ObjCObjectPointerType::stripObjCKindOfTypeAndQuals(
996 const ASTContext &ctx) const {
997 if (!isKindOfType() && qual_empty())
998 return this;
999
1000 QualType obj = getObjectType()->stripObjCKindOfTypeAndQuals(ctx);
1001 return ctx.getObjCObjectPointerType(OIT: obj)->castAs<ObjCObjectPointerType>();
1002}
1003
1004namespace {
1005
1006/// Visitor used to perform a simple type transformation that does not change
1007/// the semantics of the type.
1008template <typename Derived>
1009struct SimpleTransformVisitor : public TypeVisitor<Derived, QualType> {
1010 ASTContext &Ctx;
1011
1012 QualType recurse(QualType type) {
1013 // Split out the qualifiers from the type.
1014 SplitQualType splitType = type.split();
1015
1016 // Visit the type itself.
1017 QualType result = static_cast<Derived *>(this)->Visit(splitType.Ty);
1018 if (result.isNull())
1019 return result;
1020
1021 // Reconstruct the transformed type by applying the local qualifiers
1022 // from the split type.
1023 return Ctx.getQualifiedType(T: result, Qs: splitType.Quals);
1024 }
1025
1026public:
1027 explicit SimpleTransformVisitor(ASTContext &ctx) : Ctx(ctx) {}
1028
1029 // None of the clients of this transformation can occur where
1030 // there are dependent types, so skip dependent types.
1031#define TYPE(Class, Base)
1032#define DEPENDENT_TYPE(Class, Base) \
1033 QualType Visit##Class##Type(const Class##Type *T) { return QualType(T, 0); }
1034#include "clang/AST/TypeNodes.inc"
1035
1036#define TRIVIAL_TYPE_CLASS(Class) \
1037 QualType Visit##Class##Type(const Class##Type *T) { return QualType(T, 0); }
1038#define SUGARED_TYPE_CLASS(Class) \
1039 QualType Visit##Class##Type(const Class##Type *T) { \
1040 if (!T->isSugared()) \
1041 return QualType(T, 0); \
1042 QualType desugaredType = recurse(T->desugar()); \
1043 if (desugaredType.isNull()) \
1044 return {}; \
1045 if (desugaredType.getAsOpaquePtr() == T->desugar().getAsOpaquePtr()) \
1046 return QualType(T, 0); \
1047 return desugaredType; \
1048 }
1049
1050 TRIVIAL_TYPE_CLASS(Builtin)
1051
1052 QualType VisitComplexType(const ComplexType *T) {
1053 QualType elementType = recurse(type: T->getElementType());
1054 if (elementType.isNull())
1055 return {};
1056
1057 if (elementType.getAsOpaquePtr() == T->getElementType().getAsOpaquePtr())
1058 return QualType(T, 0);
1059
1060 return Ctx.getComplexType(T: elementType);
1061 }
1062
1063 QualType VisitPointerType(const PointerType *T) {
1064 QualType pointeeType = recurse(type: T->getPointeeType());
1065 if (pointeeType.isNull())
1066 return {};
1067
1068 if (pointeeType.getAsOpaquePtr() == T->getPointeeType().getAsOpaquePtr())
1069 return QualType(T, 0);
1070
1071 return Ctx.getPointerType(T: pointeeType);
1072 }
1073
1074 QualType VisitBlockPointerType(const BlockPointerType *T) {
1075 QualType pointeeType = recurse(type: T->getPointeeType());
1076 if (pointeeType.isNull())
1077 return {};
1078
1079 if (pointeeType.getAsOpaquePtr() == T->getPointeeType().getAsOpaquePtr())
1080 return QualType(T, 0);
1081
1082 return Ctx.getBlockPointerType(T: pointeeType);
1083 }
1084
1085 QualType VisitLValueReferenceType(const LValueReferenceType *T) {
1086 QualType pointeeType = recurse(type: T->getPointeeTypeAsWritten());
1087 if (pointeeType.isNull())
1088 return {};
1089
1090 if (pointeeType.getAsOpaquePtr() ==
1091 T->getPointeeTypeAsWritten().getAsOpaquePtr())
1092 return QualType(T, 0);
1093
1094 return Ctx.getLValueReferenceType(T: pointeeType, SpelledAsLValue: T->isSpelledAsLValue());
1095 }
1096
1097 QualType VisitRValueReferenceType(const RValueReferenceType *T) {
1098 QualType pointeeType = recurse(type: T->getPointeeTypeAsWritten());
1099 if (pointeeType.isNull())
1100 return {};
1101
1102 if (pointeeType.getAsOpaquePtr() ==
1103 T->getPointeeTypeAsWritten().getAsOpaquePtr())
1104 return QualType(T, 0);
1105
1106 return Ctx.getRValueReferenceType(T: pointeeType);
1107 }
1108
1109 QualType VisitMemberPointerType(const MemberPointerType *T) {
1110 QualType pointeeType = recurse(type: T->getPointeeType());
1111 if (pointeeType.isNull())
1112 return {};
1113
1114 if (pointeeType.getAsOpaquePtr() == T->getPointeeType().getAsOpaquePtr())
1115 return QualType(T, 0);
1116
1117 return Ctx.getMemberPointerType(T: pointeeType, Qualifier: T->getQualifier(),
1118 Cls: T->getMostRecentCXXRecordDecl());
1119 }
1120
1121 QualType VisitConstantArrayType(const ConstantArrayType *T) {
1122 QualType elementType = recurse(type: T->getElementType());
1123 if (elementType.isNull())
1124 return {};
1125
1126 if (elementType.getAsOpaquePtr() == T->getElementType().getAsOpaquePtr())
1127 return QualType(T, 0);
1128
1129 return Ctx.getConstantArrayType(EltTy: elementType, ArySize: T->getSize(), SizeExpr: T->getSizeExpr(),
1130 ASM: T->getSizeModifier(),
1131 IndexTypeQuals: T->getIndexTypeCVRQualifiers());
1132 }
1133
1134 QualType VisitVariableArrayType(const VariableArrayType *T) {
1135 QualType elementType = recurse(type: T->getElementType());
1136 if (elementType.isNull())
1137 return {};
1138
1139 if (elementType.getAsOpaquePtr() == T->getElementType().getAsOpaquePtr())
1140 return QualType(T, 0);
1141
1142 return Ctx.getVariableArrayType(EltTy: elementType, NumElts: T->getSizeExpr(),
1143 ASM: T->getSizeModifier(),
1144 IndexTypeQuals: T->getIndexTypeCVRQualifiers());
1145 }
1146
1147 QualType VisitIncompleteArrayType(const IncompleteArrayType *T) {
1148 QualType elementType = recurse(type: T->getElementType());
1149 if (elementType.isNull())
1150 return {};
1151
1152 if (elementType.getAsOpaquePtr() == T->getElementType().getAsOpaquePtr())
1153 return QualType(T, 0);
1154
1155 return Ctx.getIncompleteArrayType(EltTy: elementType, ASM: T->getSizeModifier(),
1156 IndexTypeQuals: T->getIndexTypeCVRQualifiers());
1157 }
1158
1159 QualType VisitVectorType(const VectorType *T) {
1160 QualType elementType = recurse(type: T->getElementType());
1161 if (elementType.isNull())
1162 return {};
1163
1164 if (elementType.getAsOpaquePtr() == T->getElementType().getAsOpaquePtr())
1165 return QualType(T, 0);
1166
1167 return Ctx.getVectorType(VectorType: elementType, NumElts: T->getNumElements(),
1168 VecKind: T->getVectorKind());
1169 }
1170
1171 QualType VisitExtVectorType(const ExtVectorType *T) {
1172 QualType elementType = recurse(type: T->getElementType());
1173 if (elementType.isNull())
1174 return {};
1175
1176 if (elementType.getAsOpaquePtr() == T->getElementType().getAsOpaquePtr())
1177 return QualType(T, 0);
1178
1179 return Ctx.getExtVectorType(VectorType: elementType, NumElts: T->getNumElements());
1180 }
1181
1182 QualType VisitConstantMatrixType(const ConstantMatrixType *T) {
1183 QualType elementType = recurse(type: T->getElementType());
1184 if (elementType.isNull())
1185 return {};
1186 if (elementType.getAsOpaquePtr() == T->getElementType().getAsOpaquePtr())
1187 return QualType(T, 0);
1188
1189 return Ctx.getConstantMatrixType(ElementType: elementType, NumRows: T->getNumRows(),
1190 NumColumns: T->getNumColumns());
1191 }
1192
1193 QualType VisitOverflowBehaviorType(const OverflowBehaviorType *T) {
1194 QualType UnderlyingType = recurse(type: T->getUnderlyingType());
1195 if (UnderlyingType.isNull())
1196 return {};
1197
1198 if (UnderlyingType.getAsOpaquePtr() ==
1199 T->getUnderlyingType().getAsOpaquePtr())
1200 return QualType(T, 0);
1201
1202 return Ctx.getOverflowBehaviorType(Kind: T->getBehaviorKind(), Wrapped: UnderlyingType);
1203 }
1204
1205 QualType VisitFunctionNoProtoType(const FunctionNoProtoType *T) {
1206 QualType returnType = recurse(type: T->getReturnType());
1207 if (returnType.isNull())
1208 return {};
1209
1210 if (returnType.getAsOpaquePtr() == T->getReturnType().getAsOpaquePtr())
1211 return QualType(T, 0);
1212
1213 return Ctx.getFunctionNoProtoType(ResultTy: returnType, Info: T->getExtInfo());
1214 }
1215
1216 QualType VisitFunctionProtoType(const FunctionProtoType *T) {
1217 QualType returnType = recurse(type: T->getReturnType());
1218 if (returnType.isNull())
1219 return {};
1220
1221 // Transform parameter types.
1222 SmallVector<QualType, 4> paramTypes;
1223 bool paramChanged = false;
1224 for (auto paramType : T->getParamTypes()) {
1225 QualType newParamType = recurse(type: paramType);
1226 if (newParamType.isNull())
1227 return {};
1228
1229 if (newParamType.getAsOpaquePtr() != paramType.getAsOpaquePtr())
1230 paramChanged = true;
1231
1232 paramTypes.push_back(Elt: newParamType);
1233 }
1234
1235 // Transform extended info.
1236 FunctionProtoType::ExtProtoInfo info = T->getExtProtoInfo();
1237 bool exceptionChanged = false;
1238 if (info.ExceptionSpec.Type == EST_Dynamic) {
1239 SmallVector<QualType, 4> exceptionTypes;
1240 for (auto exceptionType : info.ExceptionSpec.Exceptions) {
1241 QualType newExceptionType = recurse(type: exceptionType);
1242 if (newExceptionType.isNull())
1243 return {};
1244
1245 if (newExceptionType.getAsOpaquePtr() != exceptionType.getAsOpaquePtr())
1246 exceptionChanged = true;
1247
1248 exceptionTypes.push_back(Elt: newExceptionType);
1249 }
1250
1251 if (exceptionChanged) {
1252 info.ExceptionSpec.Exceptions =
1253 llvm::ArrayRef(exceptionTypes).copy(A&: Ctx);
1254 }
1255 }
1256
1257 if (returnType.getAsOpaquePtr() == T->getReturnType().getAsOpaquePtr() &&
1258 !paramChanged && !exceptionChanged)
1259 return QualType(T, 0);
1260
1261 return Ctx.getFunctionType(ResultTy: returnType, Args: paramTypes, EPI: info);
1262 }
1263
1264 QualType VisitParenType(const ParenType *T) {
1265 QualType innerType = recurse(type: T->getInnerType());
1266 if (innerType.isNull())
1267 return {};
1268
1269 if (innerType.getAsOpaquePtr() == T->getInnerType().getAsOpaquePtr())
1270 return QualType(T, 0);
1271
1272 return Ctx.getParenType(NamedType: innerType);
1273 }
1274
1275 SUGARED_TYPE_CLASS(Typedef)
1276 SUGARED_TYPE_CLASS(ObjCTypeParam)
1277 SUGARED_TYPE_CLASS(MacroQualified)
1278
1279 QualType VisitAdjustedType(const AdjustedType *T) {
1280 QualType originalType = recurse(type: T->getOriginalType());
1281 if (originalType.isNull())
1282 return {};
1283
1284 QualType adjustedType = recurse(type: T->getAdjustedType());
1285 if (adjustedType.isNull())
1286 return {};
1287
1288 if (originalType.getAsOpaquePtr() ==
1289 T->getOriginalType().getAsOpaquePtr() &&
1290 adjustedType.getAsOpaquePtr() == T->getAdjustedType().getAsOpaquePtr())
1291 return QualType(T, 0);
1292
1293 return Ctx.getAdjustedType(Orig: originalType, New: adjustedType);
1294 }
1295
1296 QualType VisitDecayedType(const DecayedType *T) {
1297 QualType originalType = recurse(type: T->getOriginalType());
1298 if (originalType.isNull())
1299 return {};
1300
1301 if (originalType.getAsOpaquePtr() == T->getOriginalType().getAsOpaquePtr())
1302 return QualType(T, 0);
1303
1304 return Ctx.getDecayedType(T: originalType);
1305 }
1306
1307 QualType VisitArrayParameterType(const ArrayParameterType *T) {
1308 QualType ArrTy = VisitConstantArrayType(T);
1309 if (ArrTy.isNull())
1310 return {};
1311
1312 return Ctx.getArrayParameterType(Ty: ArrTy);
1313 }
1314
1315 SUGARED_TYPE_CLASS(TypeOfExpr)
1316 SUGARED_TYPE_CLASS(TypeOf)
1317 SUGARED_TYPE_CLASS(Decltype)
1318 SUGARED_TYPE_CLASS(UnaryTransform)
1319 TRIVIAL_TYPE_CLASS(Record)
1320 TRIVIAL_TYPE_CLASS(Enum)
1321
1322 QualType VisitAttributedType(const AttributedType *T) {
1323 QualType modifiedType = recurse(type: T->getModifiedType());
1324 if (modifiedType.isNull())
1325 return {};
1326
1327 QualType equivalentType = recurse(type: T->getEquivalentType());
1328 if (equivalentType.isNull())
1329 return {};
1330
1331 if (modifiedType.getAsOpaquePtr() ==
1332 T->getModifiedType().getAsOpaquePtr() &&
1333 equivalentType.getAsOpaquePtr() ==
1334 T->getEquivalentType().getAsOpaquePtr())
1335 return QualType(T, 0);
1336
1337 return Ctx.getAttributedType(attrKind: T->getAttrKind(), modifiedType, equivalentType,
1338 attr: T->getAttr());
1339 }
1340
1341 QualType VisitSubstTemplateTypeParmType(const SubstTemplateTypeParmType *T) {
1342 QualType replacementType = recurse(type: T->getReplacementType());
1343 if (replacementType.isNull())
1344 return {};
1345
1346 if (replacementType.getAsOpaquePtr() ==
1347 T->getReplacementType().getAsOpaquePtr())
1348 return QualType(T, 0);
1349
1350 return Ctx.getSubstTemplateTypeParmType(
1351 Replacement: replacementType, AssociatedDecl: T->getAssociatedDecl(), Index: T->getIndex(),
1352 PackIndex: T->getPackIndex(), Final: T->getFinal());
1353 }
1354
1355 // FIXME: Non-trivial to implement, but important for C++
1356 SUGARED_TYPE_CLASS(TemplateSpecialization)
1357
1358 QualType VisitAutoType(const AutoType *T) {
1359 if (!T->isDeduced())
1360 return QualType(T, 0);
1361
1362 QualType deducedType = recurse(type: T->getDeducedType());
1363 if (deducedType.isNull())
1364 return {};
1365
1366 if (deducedType == T->getDeducedType())
1367 return QualType(T, 0);
1368
1369 return Ctx.getAutoType(DK: T->getDeducedKind(), DeducedAsType: deducedType, Keyword: T->getKeyword(),
1370 TypeConstraintConcept: T->getTypeConstraintConcept(),
1371 TypeConstraintArgs: T->getTypeConstraintArguments());
1372 }
1373
1374 QualType VisitObjCObjectType(const ObjCObjectType *T) {
1375 QualType baseType = recurse(type: T->getBaseType());
1376 if (baseType.isNull())
1377 return {};
1378
1379 // Transform type arguments.
1380 bool typeArgChanged = false;
1381 SmallVector<QualType, 4> typeArgs;
1382 for (auto typeArg : T->getTypeArgsAsWritten()) {
1383 QualType newTypeArg = recurse(type: typeArg);
1384 if (newTypeArg.isNull())
1385 return {};
1386
1387 if (newTypeArg.getAsOpaquePtr() != typeArg.getAsOpaquePtr())
1388 typeArgChanged = true;
1389
1390 typeArgs.push_back(Elt: newTypeArg);
1391 }
1392
1393 if (baseType.getAsOpaquePtr() == T->getBaseType().getAsOpaquePtr() &&
1394 !typeArgChanged)
1395 return QualType(T, 0);
1396
1397 return Ctx.getObjCObjectType(
1398 Base: baseType, typeArgs,
1399 protocols: llvm::ArrayRef(T->qual_begin(), T->getNumProtocols()),
1400 isKindOf: T->isKindOfTypeAsWritten());
1401 }
1402
1403 TRIVIAL_TYPE_CLASS(ObjCInterface)
1404
1405 QualType VisitObjCObjectPointerType(const ObjCObjectPointerType *T) {
1406 QualType pointeeType = recurse(type: T->getPointeeType());
1407 if (pointeeType.isNull())
1408 return {};
1409
1410 if (pointeeType.getAsOpaquePtr() == T->getPointeeType().getAsOpaquePtr())
1411 return QualType(T, 0);
1412
1413 return Ctx.getObjCObjectPointerType(OIT: pointeeType);
1414 }
1415
1416 QualType VisitAtomicType(const AtomicType *T) {
1417 QualType valueType = recurse(type: T->getValueType());
1418 if (valueType.isNull())
1419 return {};
1420
1421 if (valueType.getAsOpaquePtr() == T->getValueType().getAsOpaquePtr())
1422 return QualType(T, 0);
1423
1424 return Ctx.getAtomicType(T: valueType);
1425 }
1426
1427#undef TRIVIAL_TYPE_CLASS
1428#undef SUGARED_TYPE_CLASS
1429};
1430
1431struct SubstObjCTypeArgsVisitor
1432 : public SimpleTransformVisitor<SubstObjCTypeArgsVisitor> {
1433 using BaseType = SimpleTransformVisitor<SubstObjCTypeArgsVisitor>;
1434
1435 ArrayRef<QualType> TypeArgs;
1436 ObjCSubstitutionContext SubstContext;
1437
1438 SubstObjCTypeArgsVisitor(ASTContext &ctx, ArrayRef<QualType> typeArgs,
1439 ObjCSubstitutionContext context)
1440 : BaseType(ctx), TypeArgs(typeArgs), SubstContext(context) {}
1441
1442 QualType VisitObjCTypeParamType(const ObjCTypeParamType *OTPTy) {
1443 // Replace an Objective-C type parameter reference with the corresponding
1444 // type argument.
1445 ObjCTypeParamDecl *typeParam = OTPTy->getDecl();
1446 // If we have type arguments, use them.
1447 if (!TypeArgs.empty()) {
1448 QualType argType = TypeArgs[typeParam->getIndex()];
1449 if (OTPTy->qual_empty())
1450 return argType;
1451
1452 // Apply protocol lists if exists.
1453 bool hasError;
1454 SmallVector<ObjCProtocolDecl *, 8> protocolsVec;
1455 protocolsVec.append(in_start: OTPTy->qual_begin(), in_end: OTPTy->qual_end());
1456 ArrayRef<ObjCProtocolDecl *> protocolsToApply = protocolsVec;
1457 return Ctx.applyObjCProtocolQualifiers(
1458 type: argType, protocols: protocolsToApply, hasError, allowOnPointerType: true /*allowOnPointerType*/);
1459 }
1460
1461 switch (SubstContext) {
1462 case ObjCSubstitutionContext::Ordinary:
1463 case ObjCSubstitutionContext::Parameter:
1464 case ObjCSubstitutionContext::Superclass:
1465 // Substitute the bound.
1466 return typeParam->getUnderlyingType();
1467
1468 case ObjCSubstitutionContext::Result:
1469 case ObjCSubstitutionContext::Property: {
1470 // Substitute the __kindof form of the underlying type.
1471 const auto *objPtr =
1472 typeParam->getUnderlyingType()->castAs<ObjCObjectPointerType>();
1473
1474 // __kindof types, id, and Class don't need an additional
1475 // __kindof.
1476 if (objPtr->isKindOfType() || objPtr->isObjCIdOrClassType())
1477 return typeParam->getUnderlyingType();
1478
1479 // Add __kindof.
1480 const auto *obj = objPtr->getObjectType();
1481 QualType resultTy = Ctx.getObjCObjectType(
1482 Base: obj->getBaseType(), typeArgs: obj->getTypeArgsAsWritten(), protocols: obj->getProtocols(),
1483 /*isKindOf=*/true);
1484
1485 // Rebuild object pointer type.
1486 return Ctx.getObjCObjectPointerType(OIT: resultTy);
1487 }
1488 }
1489 llvm_unreachable("Unexpected ObjCSubstitutionContext!");
1490 }
1491
1492 QualType VisitFunctionType(const FunctionType *funcType) {
1493 // If we have a function type, update the substitution context
1494 // appropriately.
1495
1496 // Substitute result type.
1497 QualType returnType = funcType->getReturnType().substObjCTypeArgs(
1498 ctx&: Ctx, typeArgs: TypeArgs, context: ObjCSubstitutionContext::Result);
1499 if (returnType.isNull())
1500 return {};
1501
1502 // Handle non-prototyped functions, which only substitute into the result
1503 // type.
1504 if (isa<FunctionNoProtoType>(Val: funcType)) {
1505 // If the return type was unchanged, do nothing.
1506 if (returnType.getAsOpaquePtr() ==
1507 funcType->getReturnType().getAsOpaquePtr())
1508 return BaseType::VisitFunctionType(T: funcType);
1509
1510 // Otherwise, build a new type.
1511 return Ctx.getFunctionNoProtoType(ResultTy: returnType, Info: funcType->getExtInfo());
1512 }
1513
1514 const auto *funcProtoType = cast<FunctionProtoType>(Val: funcType);
1515
1516 // Transform parameter types.
1517 SmallVector<QualType, 4> paramTypes;
1518 bool paramChanged = false;
1519 for (auto paramType : funcProtoType->getParamTypes()) {
1520 QualType newParamType = paramType.substObjCTypeArgs(
1521 ctx&: Ctx, typeArgs: TypeArgs, context: ObjCSubstitutionContext::Parameter);
1522 if (newParamType.isNull())
1523 return {};
1524
1525 if (newParamType.getAsOpaquePtr() != paramType.getAsOpaquePtr())
1526 paramChanged = true;
1527
1528 paramTypes.push_back(Elt: newParamType);
1529 }
1530
1531 // Transform extended info.
1532 FunctionProtoType::ExtProtoInfo info = funcProtoType->getExtProtoInfo();
1533 bool exceptionChanged = false;
1534 if (info.ExceptionSpec.Type == EST_Dynamic) {
1535 SmallVector<QualType, 4> exceptionTypes;
1536 for (auto exceptionType : info.ExceptionSpec.Exceptions) {
1537 QualType newExceptionType = exceptionType.substObjCTypeArgs(
1538 ctx&: Ctx, typeArgs: TypeArgs, context: ObjCSubstitutionContext::Ordinary);
1539 if (newExceptionType.isNull())
1540 return {};
1541
1542 if (newExceptionType.getAsOpaquePtr() != exceptionType.getAsOpaquePtr())
1543 exceptionChanged = true;
1544
1545 exceptionTypes.push_back(Elt: newExceptionType);
1546 }
1547
1548 if (exceptionChanged) {
1549 info.ExceptionSpec.Exceptions =
1550 llvm::ArrayRef(exceptionTypes).copy(A&: Ctx);
1551 }
1552 }
1553
1554 if (returnType.getAsOpaquePtr() ==
1555 funcProtoType->getReturnType().getAsOpaquePtr() &&
1556 !paramChanged && !exceptionChanged)
1557 return BaseType::VisitFunctionType(T: funcType);
1558
1559 return Ctx.getFunctionType(ResultTy: returnType, Args: paramTypes, EPI: info);
1560 }
1561
1562 QualType VisitObjCObjectType(const ObjCObjectType *objcObjectType) {
1563 // Substitute into the type arguments of a specialized Objective-C object
1564 // type.
1565 if (objcObjectType->isSpecializedAsWritten()) {
1566 SmallVector<QualType, 4> newTypeArgs;
1567 bool anyChanged = false;
1568 for (auto typeArg : objcObjectType->getTypeArgsAsWritten()) {
1569 QualType newTypeArg = typeArg.substObjCTypeArgs(
1570 ctx&: Ctx, typeArgs: TypeArgs, context: ObjCSubstitutionContext::Ordinary);
1571 if (newTypeArg.isNull())
1572 return {};
1573
1574 if (newTypeArg.getAsOpaquePtr() != typeArg.getAsOpaquePtr()) {
1575 // If we're substituting based on an unspecialized context type,
1576 // produce an unspecialized type.
1577 ArrayRef<ObjCProtocolDecl *> protocols(
1578 objcObjectType->qual_begin(), objcObjectType->getNumProtocols());
1579 if (TypeArgs.empty() &&
1580 SubstContext != ObjCSubstitutionContext::Superclass) {
1581 return Ctx.getObjCObjectType(
1582 Base: objcObjectType->getBaseType(), typeArgs: {}, protocols,
1583 isKindOf: objcObjectType->isKindOfTypeAsWritten());
1584 }
1585
1586 anyChanged = true;
1587 }
1588
1589 newTypeArgs.push_back(Elt: newTypeArg);
1590 }
1591
1592 if (anyChanged) {
1593 ArrayRef<ObjCProtocolDecl *> protocols(
1594 objcObjectType->qual_begin(), objcObjectType->getNumProtocols());
1595 return Ctx.getObjCObjectType(Base: objcObjectType->getBaseType(), typeArgs: newTypeArgs,
1596 protocols,
1597 isKindOf: objcObjectType->isKindOfTypeAsWritten());
1598 }
1599 }
1600
1601 return BaseType::VisitObjCObjectType(T: objcObjectType);
1602 }
1603
1604 QualType VisitAttributedType(const AttributedType *attrType) {
1605 QualType newType = BaseType::VisitAttributedType(T: attrType);
1606 if (newType.isNull())
1607 return {};
1608
1609 const auto *newAttrType = dyn_cast<AttributedType>(Val: newType.getTypePtr());
1610 if (!newAttrType || newAttrType->getAttrKind() != attr::ObjCKindOf)
1611 return newType;
1612
1613 // Find out if it's an Objective-C object or object pointer type;
1614 QualType newEquivType = newAttrType->getEquivalentType();
1615 const ObjCObjectPointerType *ptrType =
1616 newEquivType->getAs<ObjCObjectPointerType>();
1617 const ObjCObjectType *objType = ptrType
1618 ? ptrType->getObjectType()
1619 : newEquivType->getAs<ObjCObjectType>();
1620 if (!objType)
1621 return newType;
1622
1623 // Rebuild the "equivalent" type, which pushes __kindof down into
1624 // the object type.
1625 newEquivType = Ctx.getObjCObjectType(
1626 Base: objType->getBaseType(), typeArgs: objType->getTypeArgsAsWritten(),
1627 protocols: objType->getProtocols(),
1628 // There is no need to apply kindof on an unqualified id type.
1629 /*isKindOf=*/objType->isObjCUnqualifiedId() ? false : true);
1630
1631 // If we started with an object pointer type, rebuild it.
1632 if (ptrType)
1633 newEquivType = Ctx.getObjCObjectPointerType(OIT: newEquivType);
1634
1635 // Rebuild the attributed type.
1636 return Ctx.getAttributedType(attrKind: newAttrType->getAttrKind(),
1637 modifiedType: newAttrType->getModifiedType(), equivalentType: newEquivType,
1638 attr: newAttrType->getAttr());
1639 }
1640};
1641
1642struct StripNullabilityTypeVisitor
1643 : public SimpleTransformVisitor<StripNullabilityTypeVisitor> {
1644 using BaseType = SimpleTransformVisitor<StripNullabilityTypeVisitor>;
1645
1646 explicit StripNullabilityTypeVisitor(ASTContext &ctx) : BaseType(ctx) {}
1647
1648 QualType VisitAttributedType(const AttributedType *attrType) {
1649 QualType type(attrType, 0);
1650 if (AttributedType::stripOuterNullability(T&: type)) {
1651 while (AttributedType::stripOuterNullability(T&: type)) {
1652 }
1653 return BaseType::recurse(type);
1654 }
1655
1656 return BaseType::VisitAttributedType(T: attrType);
1657 }
1658};
1659
1660struct StripObjCKindOfTypeVisitor
1661 : public SimpleTransformVisitor<StripObjCKindOfTypeVisitor> {
1662 using BaseType = SimpleTransformVisitor<StripObjCKindOfTypeVisitor>;
1663
1664 explicit StripObjCKindOfTypeVisitor(ASTContext &ctx) : BaseType(ctx) {}
1665
1666 QualType VisitObjCObjectType(const ObjCObjectType *objType) {
1667 if (!objType->isKindOfType())
1668 return BaseType::VisitObjCObjectType(T: objType);
1669
1670 QualType baseType = objType->getBaseType().stripObjCKindOfType(ctx: Ctx);
1671 return Ctx.getObjCObjectType(Base: baseType, typeArgs: objType->getTypeArgsAsWritten(),
1672 protocols: objType->getProtocols(),
1673 /*isKindOf=*/false);
1674 }
1675};
1676
1677} // namespace
1678
1679bool QualType::UseExcessPrecision(const ASTContext &Ctx) {
1680 const BuiltinType *BT = getTypePtr()->getAs<BuiltinType>();
1681 if (!BT) {
1682 const VectorType *VT = getTypePtr()->getAs<VectorType>();
1683 if (VT) {
1684 QualType ElementType = VT->getElementType();
1685 return ElementType.UseExcessPrecision(Ctx);
1686 }
1687 } else {
1688 switch (BT->getKind()) {
1689 case BuiltinType::Kind::Float16: {
1690 const TargetInfo &TI = Ctx.getTargetInfo();
1691 if (TI.hasFloat16Type() && !TI.hasFastHalfType() &&
1692 Ctx.getLangOpts().getFloat16ExcessPrecision() !=
1693 Ctx.getLangOpts().ExcessPrecisionKind::FPP_None)
1694 return true;
1695 break;
1696 }
1697 case BuiltinType::Kind::BFloat16: {
1698 const TargetInfo &TI = Ctx.getTargetInfo();
1699 if (TI.hasBFloat16Type() && !TI.hasFullBFloat16Type() &&
1700 Ctx.getLangOpts().getBFloat16ExcessPrecision() !=
1701 Ctx.getLangOpts().ExcessPrecisionKind::FPP_None)
1702 return true;
1703 break;
1704 }
1705 default:
1706 return false;
1707 }
1708 }
1709 return false;
1710}
1711
1712/// Substitute the given type arguments for Objective-C type
1713/// parameters within the given type, recursively.
1714QualType QualType::substObjCTypeArgs(ASTContext &ctx,
1715 ArrayRef<QualType> typeArgs,
1716 ObjCSubstitutionContext context) const {
1717 SubstObjCTypeArgsVisitor visitor(ctx, typeArgs, context);
1718 return visitor.recurse(type: *this);
1719}
1720
1721QualType QualType::substObjCMemberType(QualType objectType,
1722 const DeclContext *dc,
1723 ObjCSubstitutionContext context) const {
1724 if (auto subs = objectType->getObjCSubstitutions(dc))
1725 return substObjCTypeArgs(ctx&: dc->getParentASTContext(), typeArgs: *subs, context);
1726
1727 return *this;
1728}
1729
1730QualType QualType::stripObjCKindOfType(const ASTContext &constCtx) const {
1731 // FIXME: Because ASTContext::getAttributedType() is non-const.
1732 auto &ctx = const_cast<ASTContext &>(constCtx);
1733 StripObjCKindOfTypeVisitor visitor(ctx);
1734 return visitor.recurse(type: *this);
1735}
1736
1737QualType QualType::stripNullability(const ASTContext &constCtx) const {
1738 // FIXME: SimpleTransformVisitor currently takes a non-const ASTContext
1739 // because some rebuild paths use non-const ASTContext factory APIs.
1740 auto &ctx = const_cast<ASTContext &>(constCtx);
1741 StripNullabilityTypeVisitor visitor(ctx);
1742 return visitor.recurse(type: *this);
1743}
1744
1745QualType QualType::getAtomicUnqualifiedType() const {
1746 QualType T = *this;
1747 if (const auto AT = T.getTypePtr()->getAs<AtomicType>())
1748 T = AT->getValueType();
1749 return T.getUnqualifiedType();
1750}
1751
1752std::optional<ArrayRef<QualType>>
1753Type::getObjCSubstitutions(const DeclContext *dc) const {
1754 // Look through method scopes.
1755 if (const auto method = dyn_cast<ObjCMethodDecl>(Val: dc))
1756 dc = method->getDeclContext();
1757
1758 // Find the class or category in which the type we're substituting
1759 // was declared.
1760 const auto *dcClassDecl = dyn_cast<ObjCInterfaceDecl>(Val: dc);
1761 const ObjCCategoryDecl *dcCategoryDecl = nullptr;
1762 ObjCTypeParamList *dcTypeParams = nullptr;
1763 if (dcClassDecl) {
1764 // If the class does not have any type parameters, there's no
1765 // substitution to do.
1766 dcTypeParams = dcClassDecl->getTypeParamList();
1767 if (!dcTypeParams)
1768 return std::nullopt;
1769 } else {
1770 // If we are in neither a class nor a category, there's no
1771 // substitution to perform.
1772 dcCategoryDecl = dyn_cast<ObjCCategoryDecl>(Val: dc);
1773 if (!dcCategoryDecl)
1774 return std::nullopt;
1775
1776 // If the category does not have any type parameters, there's no
1777 // substitution to do.
1778 dcTypeParams = dcCategoryDecl->getTypeParamList();
1779 if (!dcTypeParams)
1780 return std::nullopt;
1781
1782 dcClassDecl = dcCategoryDecl->getClassInterface();
1783 if (!dcClassDecl)
1784 return std::nullopt;
1785 }
1786 assert(dcTypeParams && "No substitutions to perform");
1787 assert(dcClassDecl && "No class context");
1788
1789 // Find the underlying object type.
1790 const ObjCObjectType *objectType;
1791 if (const auto *objectPointerType = getAs<ObjCObjectPointerType>()) {
1792 objectType = objectPointerType->getObjectType();
1793 } else if (getAs<BlockPointerType>()) {
1794 ASTContext &ctx = dc->getParentASTContext();
1795 objectType = ctx.getObjCObjectType(Base: ctx.ObjCBuiltinIdTy, Protocols: {}, NumProtocols: {})
1796 ->castAs<ObjCObjectType>();
1797 } else {
1798 objectType = getAs<ObjCObjectType>();
1799 }
1800
1801 /// Extract the class from the receiver object type.
1802 ObjCInterfaceDecl *curClassDecl =
1803 objectType ? objectType->getInterface() : nullptr;
1804 if (!curClassDecl) {
1805 // If we don't have a context type (e.g., this is "id" or some
1806 // variant thereof), substitute the bounds.
1807 return llvm::ArrayRef<QualType>();
1808 }
1809
1810 // Follow the superclass chain until we've mapped the receiver type
1811 // to the same class as the context.
1812 while (curClassDecl != dcClassDecl) {
1813 // Map to the superclass type.
1814 QualType superType = objectType->getSuperClassType();
1815 if (superType.isNull()) {
1816 objectType = nullptr;
1817 break;
1818 }
1819
1820 objectType = superType->castAs<ObjCObjectType>();
1821 curClassDecl = objectType->getInterface();
1822 }
1823
1824 // If we don't have a receiver type, or the receiver type does not
1825 // have type arguments, substitute in the defaults.
1826 if (!objectType || objectType->isUnspecialized()) {
1827 return llvm::ArrayRef<QualType>();
1828 }
1829
1830 // The receiver type has the type arguments we want.
1831 return objectType->getTypeArgs();
1832}
1833
1834bool Type::acceptsObjCTypeParams() const {
1835 if (auto *IfaceT = getAsObjCInterfaceType()) {
1836 if (auto *ID = IfaceT->getInterface()) {
1837 if (ID->getTypeParamList())
1838 return true;
1839 }
1840 }
1841
1842 return false;
1843}
1844
1845void ObjCObjectType::computeSuperClassTypeSlow() const {
1846 // Retrieve the class declaration for this type. If there isn't one
1847 // (e.g., this is some variant of "id" or "Class"), then there is no
1848 // superclass type.
1849 ObjCInterfaceDecl *classDecl = getInterface();
1850 if (!classDecl) {
1851 CachedSuperClassType.setInt(true);
1852 return;
1853 }
1854
1855 // Extract the superclass type.
1856 const ObjCObjectType *superClassObjTy = classDecl->getSuperClassType();
1857 if (!superClassObjTy) {
1858 CachedSuperClassType.setInt(true);
1859 return;
1860 }
1861
1862 ObjCInterfaceDecl *superClassDecl = superClassObjTy->getInterface();
1863 if (!superClassDecl) {
1864 CachedSuperClassType.setInt(true);
1865 return;
1866 }
1867
1868 // If the superclass doesn't have type parameters, then there is no
1869 // substitution to perform.
1870 QualType superClassType(superClassObjTy, 0);
1871 ObjCTypeParamList *superClassTypeParams = superClassDecl->getTypeParamList();
1872 if (!superClassTypeParams) {
1873 CachedSuperClassType.setPointerAndInt(
1874 PtrVal: superClassType->castAs<ObjCObjectType>(), IntVal: true);
1875 return;
1876 }
1877
1878 // If the superclass reference is unspecialized, return it.
1879 if (superClassObjTy->isUnspecialized()) {
1880 CachedSuperClassType.setPointerAndInt(PtrVal: superClassObjTy, IntVal: true);
1881 return;
1882 }
1883
1884 // If the subclass is not parameterized, there aren't any type
1885 // parameters in the superclass reference to substitute.
1886 ObjCTypeParamList *typeParams = classDecl->getTypeParamList();
1887 if (!typeParams) {
1888 CachedSuperClassType.setPointerAndInt(
1889 PtrVal: superClassType->castAs<ObjCObjectType>(), IntVal: true);
1890 return;
1891 }
1892
1893 // If the subclass type isn't specialized, return the unspecialized
1894 // superclass.
1895 if (isUnspecialized()) {
1896 QualType unspecializedSuper =
1897 classDecl->getASTContext().getObjCInterfaceType(
1898 Decl: superClassObjTy->getInterface());
1899 CachedSuperClassType.setPointerAndInt(
1900 PtrVal: unspecializedSuper->castAs<ObjCObjectType>(), IntVal: true);
1901 return;
1902 }
1903
1904 // Substitute the provided type arguments into the superclass type.
1905 ArrayRef<QualType> typeArgs = getTypeArgs();
1906 assert(typeArgs.size() == typeParams->size());
1907 CachedSuperClassType.setPointerAndInt(
1908 PtrVal: superClassType
1909 .substObjCTypeArgs(ctx&: classDecl->getASTContext(), typeArgs,
1910 context: ObjCSubstitutionContext::Superclass)
1911 ->castAs<ObjCObjectType>(),
1912 IntVal: true);
1913}
1914
1915const ObjCInterfaceType *ObjCObjectPointerType::getInterfaceType() const {
1916 if (auto interfaceDecl = getObjectType()->getInterface()) {
1917 return interfaceDecl->getASTContext()
1918 .getObjCInterfaceType(Decl: interfaceDecl)
1919 ->castAs<ObjCInterfaceType>();
1920 }
1921
1922 return nullptr;
1923}
1924
1925QualType ObjCObjectPointerType::getSuperClassType() const {
1926 QualType superObjectType = getObjectType()->getSuperClassType();
1927 if (superObjectType.isNull())
1928 return superObjectType;
1929
1930 ASTContext &ctx = getInterfaceDecl()->getASTContext();
1931 return ctx.getObjCObjectPointerType(OIT: superObjectType);
1932}
1933
1934const ObjCObjectType *Type::getAsObjCQualifiedInterfaceType() const {
1935 // There is no sugar for ObjCObjectType's, just return the canonical
1936 // type pointer if it is the right class. There is no typedef information to
1937 // return and these cannot be Address-space qualified.
1938 if (const auto *T = getAs<ObjCObjectType>())
1939 if (T->getNumProtocols() && T->getInterface())
1940 return T;
1941 return nullptr;
1942}
1943
1944bool Type::isObjCQualifiedInterfaceType() const {
1945 return getAsObjCQualifiedInterfaceType() != nullptr;
1946}
1947
1948const ObjCObjectPointerType *Type::getAsObjCQualifiedIdType() const {
1949 // There is no sugar for ObjCQualifiedIdType's, just return the canonical
1950 // type pointer if it is the right class.
1951 if (const auto *OPT = getAs<ObjCObjectPointerType>()) {
1952 if (OPT->isObjCQualifiedIdType())
1953 return OPT;
1954 }
1955 return nullptr;
1956}
1957
1958const ObjCObjectPointerType *Type::getAsObjCQualifiedClassType() const {
1959 // There is no sugar for ObjCQualifiedClassType's, just return the canonical
1960 // type pointer if it is the right class.
1961 if (const auto *OPT = getAs<ObjCObjectPointerType>()) {
1962 if (OPT->isObjCQualifiedClassType())
1963 return OPT;
1964 }
1965 return nullptr;
1966}
1967
1968const ObjCObjectType *Type::getAsObjCInterfaceType() const {
1969 if (const auto *OT = getAs<ObjCObjectType>()) {
1970 if (OT->getInterface())
1971 return OT;
1972 }
1973 return nullptr;
1974}
1975
1976const ObjCObjectPointerType *Type::getAsObjCInterfacePointerType() const {
1977 if (const auto *OPT = getAs<ObjCObjectPointerType>()) {
1978 if (OPT->getInterfaceType())
1979 return OPT;
1980 }
1981 return nullptr;
1982}
1983
1984const CXXRecordDecl *Type::getPointeeCXXRecordDecl() const {
1985 QualType PointeeType;
1986 if (const auto *PT = getAsCanonical<PointerType>())
1987 PointeeType = PT->getPointeeType();
1988 else if (const auto *RT = getAsCanonical<ReferenceType>())
1989 PointeeType = RT->getPointeeType();
1990 else
1991 return nullptr;
1992 return PointeeType->getAsCXXRecordDecl();
1993}
1994
1995const TemplateSpecializationType *
1996Type::getAsNonAliasTemplateSpecializationType() const {
1997 const auto *TST = getAs<TemplateSpecializationType>();
1998 while (TST && TST->isTypeAlias())
1999 TST = TST->desugar()->getAs<TemplateSpecializationType>();
2000 return TST;
2001}
2002
2003NestedNameSpecifier Type::getPrefix() const {
2004 switch (getTypeClass()) {
2005 case Type::DependentName:
2006 return cast<DependentNameType>(Val: this)->getQualifier();
2007 case Type::TemplateSpecialization:
2008 return cast<TemplateSpecializationType>(Val: this)
2009 ->getTemplateName()
2010 .getQualifier();
2011 case Type::Enum:
2012 case Type::Record:
2013 case Type::InjectedClassName:
2014 return cast<TagType>(Val: this)->getQualifier();
2015 case Type::Typedef:
2016 return cast<TypedefType>(Val: this)->getQualifier();
2017 case Type::UnresolvedUsing:
2018 return cast<UnresolvedUsingType>(Val: this)->getQualifier();
2019 case Type::Using:
2020 return cast<UsingType>(Val: this)->getQualifier();
2021 default:
2022 return std::nullopt;
2023 }
2024}
2025
2026bool Type::hasAttr(attr::Kind AK) const {
2027 const Type *Cur = this;
2028 while (const auto *AT = Cur->getAs<AttributedType>()) {
2029 if (AT->getAttrKind() == AK)
2030 return true;
2031 Cur = AT->getEquivalentType().getTypePtr();
2032 }
2033 return false;
2034}
2035
2036namespace {
2037
2038class GetContainedDeducedTypeVisitor
2039 : public TypeVisitor<GetContainedDeducedTypeVisitor, Type *> {
2040 bool Syntactic;
2041
2042public:
2043 GetContainedDeducedTypeVisitor(bool Syntactic = false)
2044 : Syntactic(Syntactic) {}
2045
2046 using TypeVisitor<GetContainedDeducedTypeVisitor, Type *>::Visit;
2047
2048 Type *Visit(QualType T) {
2049 if (T.isNull())
2050 return nullptr;
2051 return Visit(T: T.getTypePtr());
2052 }
2053
2054 // The deduced type itself.
2055 Type *VisitDeducedType(const DeducedType *AT) {
2056 return const_cast<DeducedType *>(AT);
2057 }
2058
2059 // Only these types can contain the desired 'auto' type.
2060 Type *VisitSubstTemplateTypeParmType(const SubstTemplateTypeParmType *T) {
2061 return Visit(T: T->getReplacementType());
2062 }
2063
2064 Type *VisitPointerType(const PointerType *T) {
2065 return Visit(T: T->getPointeeType());
2066 }
2067
2068 Type *VisitBlockPointerType(const BlockPointerType *T) {
2069 return Visit(T: T->getPointeeType());
2070 }
2071
2072 Type *VisitReferenceType(const ReferenceType *T) {
2073 return Visit(T: T->getPointeeTypeAsWritten());
2074 }
2075
2076 Type *VisitMemberPointerType(const MemberPointerType *T) {
2077 return Visit(T: T->getPointeeType());
2078 }
2079
2080 Type *VisitArrayType(const ArrayType *T) {
2081 return Visit(T: T->getElementType());
2082 }
2083
2084 Type *VisitDependentSizedExtVectorType(const DependentSizedExtVectorType *T) {
2085 return Visit(T: T->getElementType());
2086 }
2087
2088 Type *VisitVectorType(const VectorType *T) {
2089 return Visit(T: T->getElementType());
2090 }
2091
2092 Type *VisitDependentSizedMatrixType(const DependentSizedMatrixType *T) {
2093 return Visit(T: T->getElementType());
2094 }
2095
2096 Type *VisitConstantMatrixType(const ConstantMatrixType *T) {
2097 return Visit(T: T->getElementType());
2098 }
2099
2100 Type *VisitFunctionProtoType(const FunctionProtoType *T) {
2101 if (Syntactic && T->hasTrailingReturn())
2102 return const_cast<FunctionProtoType *>(T);
2103 return VisitFunctionType(T);
2104 }
2105
2106 Type *VisitFunctionType(const FunctionType *T) {
2107 return Visit(T: T->getReturnType());
2108 }
2109
2110 Type *VisitParenType(const ParenType *T) { return Visit(T: T->getInnerType()); }
2111
2112 Type *VisitAttributedType(const AttributedType *T) {
2113 return Visit(T: T->getModifiedType());
2114 }
2115
2116 Type *VisitMacroQualifiedType(const MacroQualifiedType *T) {
2117 return Visit(T: T->getUnderlyingType());
2118 }
2119
2120 Type *VisitOverflowBehaviorType(const OverflowBehaviorType *T) {
2121 return Visit(T: T->getUnderlyingType());
2122 }
2123
2124 Type *VisitAdjustedType(const AdjustedType *T) {
2125 return Visit(T: T->getOriginalType());
2126 }
2127
2128 Type *VisitPackExpansionType(const PackExpansionType *T) {
2129 return Visit(T: T->getPattern());
2130 }
2131
2132 Type *VisitAtomicType(const AtomicType *T) {
2133 return Visit(T: T->getValueType());
2134 }
2135};
2136
2137} // namespace
2138
2139DeducedType *Type::getContainedDeducedType() const {
2140 return cast_or_null<DeducedType>(
2141 Val: GetContainedDeducedTypeVisitor().Visit(T: this));
2142}
2143
2144bool Type::hasAutoForTrailingReturnType() const {
2145 return isa_and_nonnull<FunctionType>(
2146 Val: GetContainedDeducedTypeVisitor(true).Visit(T: this));
2147}
2148
2149bool Type::hasIntegerRepresentation() const {
2150 if (const auto *VT = dyn_cast<VectorType>(Val: CanonicalType))
2151 return VT->getElementType()->isIntegerType();
2152 if (CanonicalType->isSveVLSBuiltinType()) {
2153 const auto *VT = cast<BuiltinType>(Val: CanonicalType);
2154 return VT->getKind() == BuiltinType::SveBool ||
2155 (VT->getKind() >= BuiltinType::SveInt8 &&
2156 VT->getKind() <= BuiltinType::SveUint64);
2157 }
2158 if (CanonicalType->isRVVVLSBuiltinType()) {
2159 const auto *VT = cast<BuiltinType>(Val: CanonicalType);
2160 return (VT->getKind() >= BuiltinType::RvvInt8mf8 &&
2161 VT->getKind() <= BuiltinType::RvvUint64m8);
2162 }
2163
2164 return isIntegerType();
2165}
2166
2167/// Determine whether this type is an integral type.
2168///
2169/// This routine determines whether the given type is an integral type per
2170/// C++ [basic.fundamental]p7. Although the C standard does not define the
2171/// term "integral type", it has a similar term "integer type", and in C++
2172/// the two terms are equivalent. However, C's "integer type" includes
2173/// enumeration types, while C++'s "integer type" does not. The \c ASTContext
2174/// parameter is used to determine whether we should be following the C or
2175/// C++ rules when determining whether this type is an integral/integer type.
2176///
2177/// For cases where C permits "an integer type" and C++ permits "an integral
2178/// type", use this routine.
2179///
2180/// For cases where C permits "an integer type" and C++ permits "an integral
2181/// or enumeration type", use \c isIntegralOrEnumerationType() instead.
2182///
2183/// \param Ctx The context in which this type occurs.
2184///
2185/// \returns true if the type is considered an integral type, false otherwise.
2186bool Type::isIntegralType(const ASTContext &Ctx) const {
2187 if (const auto *BT = dyn_cast<BuiltinType>(Val: CanonicalType))
2188 return BT->isInteger();
2189
2190 // Complete enum types are integral in C.
2191 if (!Ctx.getLangOpts().CPlusPlus) {
2192 if (const auto *ET = dyn_cast<EnumType>(Val: CanonicalType))
2193 return IsEnumDeclComplete(ED: ET->getDecl());
2194
2195 if (const OverflowBehaviorType *OBT =
2196 dyn_cast<OverflowBehaviorType>(Val: CanonicalType))
2197 return OBT->getUnderlyingType()->isIntegralOrEnumerationType();
2198 }
2199
2200 return isBitIntType();
2201}
2202
2203bool Type::isIntegralOrUnscopedEnumerationType() const {
2204 if (const auto *BT = dyn_cast<BuiltinType>(Val: CanonicalType))
2205 return BT->isInteger();
2206
2207 if (const auto *OBT = dyn_cast<OverflowBehaviorType>(Val: CanonicalType))
2208 return OBT->getUnderlyingType()->isIntegerType();
2209
2210 if (isBitIntType())
2211 return true;
2212
2213 return isUnscopedEnumerationType();
2214}
2215
2216bool Type::isUnscopedEnumerationType() const {
2217 if (const auto *ET = dyn_cast<EnumType>(Val: CanonicalType))
2218 return !ET->getDecl()->isScoped();
2219
2220 return false;
2221}
2222
2223bool Type::isCharType() const {
2224 if (const auto *BT = dyn_cast<BuiltinType>(Val: CanonicalType))
2225 return BT->getKind() == BuiltinType::Char_U ||
2226 BT->getKind() == BuiltinType::UChar ||
2227 BT->getKind() == BuiltinType::Char_S ||
2228 BT->getKind() == BuiltinType::SChar;
2229 return false;
2230}
2231
2232bool Type::isWideCharType() const {
2233 if (const auto *BT = dyn_cast<BuiltinType>(Val: CanonicalType))
2234 return BT->getKind() == BuiltinType::WChar_S ||
2235 BT->getKind() == BuiltinType::WChar_U;
2236 return false;
2237}
2238
2239bool Type::isChar8Type() const {
2240 if (const BuiltinType *BT = dyn_cast<BuiltinType>(Val: CanonicalType))
2241 return BT->getKind() == BuiltinType::Char8;
2242 return false;
2243}
2244
2245bool Type::isChar16Type() const {
2246 if (const auto *BT = dyn_cast<BuiltinType>(Val: CanonicalType))
2247 return BT->getKind() == BuiltinType::Char16;
2248 return false;
2249}
2250
2251bool Type::isChar32Type() const {
2252 if (const auto *BT = dyn_cast<BuiltinType>(Val: CanonicalType))
2253 return BT->getKind() == BuiltinType::Char32;
2254 return false;
2255}
2256
2257/// Determine whether this type is any of the built-in character
2258/// types.
2259bool Type::isAnyCharacterType() const {
2260 const auto *BT = dyn_cast<BuiltinType>(Val: CanonicalType);
2261 if (!BT)
2262 return false;
2263 switch (BT->getKind()) {
2264 default:
2265 return false;
2266 case BuiltinType::Char_U:
2267 case BuiltinType::UChar:
2268 case BuiltinType::WChar_U:
2269 case BuiltinType::Char8:
2270 case BuiltinType::Char16:
2271 case BuiltinType::Char32:
2272 case BuiltinType::Char_S:
2273 case BuiltinType::SChar:
2274 case BuiltinType::WChar_S:
2275 return true;
2276 }
2277}
2278
2279bool Type::isUnicodeCharacterType() const {
2280 const auto *BT = dyn_cast<BuiltinType>(Val: CanonicalType);
2281 if (!BT)
2282 return false;
2283 switch (BT->getKind()) {
2284 default:
2285 return false;
2286 case BuiltinType::Char8:
2287 case BuiltinType::Char16:
2288 case BuiltinType::Char32:
2289 return true;
2290 }
2291}
2292
2293/// isSignedIntegerType - Return true if this is an integer type that is
2294/// signed, according to C99 6.2.5p4 [char, signed char, short, int, long..],
2295/// an enum decl which has a signed representation
2296bool Type::isSignedIntegerType() const {
2297 if (const auto *BT = dyn_cast<BuiltinType>(Val: CanonicalType))
2298 return BT->isSignedInteger();
2299
2300 if (const auto *ED = getAsEnumDecl()) {
2301 // Incomplete enum types are not treated as integer types.
2302 // FIXME: In C++, enum types are never integer types.
2303 if (!ED->isComplete() || ED->isScoped())
2304 return false;
2305 return ED->getIntegerType()->isSignedIntegerType();
2306 }
2307
2308 if (const auto *IT = dyn_cast<BitIntType>(Val: CanonicalType))
2309 return IT->isSigned();
2310 if (const auto *IT = dyn_cast<DependentBitIntType>(Val: CanonicalType))
2311 return IT->isSigned();
2312
2313 if (const auto *OBT = dyn_cast<OverflowBehaviorType>(Val: CanonicalType))
2314 return OBT->getUnderlyingType()->isSignedIntegerType();
2315
2316 return false;
2317}
2318
2319bool Type::isSignedIntegerOrEnumerationType() const {
2320 if (const auto *BT = dyn_cast<BuiltinType>(Val: CanonicalType))
2321 return BT->isSignedInteger();
2322
2323 if (const auto *ED = getAsEnumDecl()) {
2324 if (!ED->isComplete())
2325 return false;
2326 return ED->getIntegerType()->isSignedIntegerType();
2327 }
2328
2329 if (const auto *IT = dyn_cast<BitIntType>(Val: CanonicalType))
2330 return IT->isSigned();
2331 if (const auto *IT = dyn_cast<DependentBitIntType>(Val: CanonicalType))
2332 return IT->isSigned();
2333
2334 if (const auto *OBT = dyn_cast<OverflowBehaviorType>(Val: CanonicalType))
2335 return OBT->getUnderlyingType()->isSignedIntegerOrEnumerationType();
2336
2337 return false;
2338}
2339
2340bool Type::hasSignedIntegerRepresentation() const {
2341 if (const auto *VT = dyn_cast<VectorType>(Val: CanonicalType))
2342 return VT->getElementType()->isSignedIntegerOrEnumerationType();
2343 if (const auto *MT = dyn_cast<MatrixType>(Val: CanonicalType))
2344 return MT->getElementType()->isSignedIntegerOrEnumerationType();
2345
2346 if (const auto *BT = dyn_cast<BuiltinType>(Val: CanonicalType)) {
2347 switch (BT->getKind()) {
2348#define SVE_VECTOR_TYPE_INT(Name, MangledName, Id, SingletonId, NumEls, \
2349 ElBits, NF, IsSigned) \
2350 case BuiltinType::Id: \
2351 return IsSigned;
2352#include "clang/Basic/AArch64ACLETypes.def"
2353 default:
2354 break;
2355 }
2356 }
2357
2358 return isSignedIntegerOrEnumerationType();
2359}
2360
2361/// isUnsignedIntegerType - Return true if this is an integer type that is
2362/// unsigned, according to C99 6.2.5p6 [which returns true for _Bool], an enum
2363/// decl which has an unsigned representation
2364bool Type::isUnsignedIntegerType() const {
2365 if (const auto *BT = dyn_cast<BuiltinType>(Val: CanonicalType))
2366 return BT->isUnsignedInteger();
2367
2368 if (const auto *ED = getAsEnumDecl()) {
2369 // Incomplete enum types are not treated as integer types.
2370 // FIXME: In C++, enum types are never integer types.
2371 if (!ED->isComplete() || ED->isScoped())
2372 return false;
2373 return ED->getIntegerType()->isUnsignedIntegerType();
2374 }
2375
2376 if (const auto *IT = dyn_cast<BitIntType>(Val: CanonicalType))
2377 return IT->isUnsigned();
2378 if (const auto *IT = dyn_cast<DependentBitIntType>(Val: CanonicalType))
2379 return IT->isUnsigned();
2380
2381 if (const auto *OBT = dyn_cast<OverflowBehaviorType>(Val: CanonicalType))
2382 return OBT->getUnderlyingType()->isUnsignedIntegerType();
2383
2384 return false;
2385}
2386
2387bool Type::isUnsignedIntegerOrEnumerationType() const {
2388 if (const auto *BT = dyn_cast<BuiltinType>(Val: CanonicalType))
2389 return BT->isUnsignedInteger();
2390
2391 if (const auto *ED = getAsEnumDecl()) {
2392 if (!ED->isComplete())
2393 return false;
2394 return ED->getIntegerType()->isUnsignedIntegerType();
2395 }
2396
2397 if (const auto *IT = dyn_cast<BitIntType>(Val: CanonicalType))
2398 return IT->isUnsigned();
2399 if (const auto *IT = dyn_cast<DependentBitIntType>(Val: CanonicalType))
2400 return IT->isUnsigned();
2401
2402 if (const auto *OBT = dyn_cast<OverflowBehaviorType>(Val: CanonicalType))
2403 return OBT->getUnderlyingType()->isUnsignedIntegerOrEnumerationType();
2404
2405 return false;
2406}
2407
2408bool Type::hasUnsignedIntegerRepresentation() const {
2409 if (const auto *VT = dyn_cast<VectorType>(Val: CanonicalType))
2410 return VT->getElementType()->isUnsignedIntegerOrEnumerationType();
2411 if (const auto *VT = dyn_cast<MatrixType>(Val: CanonicalType))
2412 return VT->getElementType()->isUnsignedIntegerOrEnumerationType();
2413 if (CanonicalType->isSveVLSBuiltinType()) {
2414 const auto *VT = cast<BuiltinType>(Val: CanonicalType);
2415 return VT->getKind() >= BuiltinType::SveUint8 &&
2416 VT->getKind() <= BuiltinType::SveUint64;
2417 }
2418 return isUnsignedIntegerOrEnumerationType();
2419}
2420
2421bool Type::isFloatingType() const {
2422 if (const auto *BT = dyn_cast<BuiltinType>(Val: CanonicalType))
2423 return BT->isFloatingPoint();
2424 if (const auto *CT = dyn_cast<ComplexType>(Val: CanonicalType))
2425 return CT->getElementType()->isFloatingType();
2426 return false;
2427}
2428
2429bool Type::hasFloatingRepresentation() const {
2430 if (const auto *VT = dyn_cast<VectorType>(Val: CanonicalType))
2431 return VT->getElementType()->isFloatingType();
2432 if (const auto *MT = dyn_cast<MatrixType>(Val: CanonicalType))
2433 return MT->getElementType()->isFloatingType();
2434 return isFloatingType();
2435}
2436
2437bool Type::isRealFloatingType() const {
2438 if (const auto *BT = dyn_cast<BuiltinType>(Val: CanonicalType))
2439 return BT->isFloatingPoint();
2440 return false;
2441}
2442
2443bool Type::isRealType() const {
2444 if (const auto *BT = dyn_cast<BuiltinType>(Val: CanonicalType))
2445 return BT->getKind() >= BuiltinType::Bool &&
2446 BT->getKind() <= BuiltinType::Ibm128;
2447 if (const auto *ET = dyn_cast<EnumType>(Val: CanonicalType)) {
2448 const auto *ED = ET->getDecl();
2449 return !ED->isScoped() && ED->getDefinitionOrSelf()->isComplete();
2450 }
2451 return isBitIntType();
2452}
2453
2454bool Type::isArithmeticType() const {
2455 if (const auto *BT = dyn_cast<BuiltinType>(Val: CanonicalType))
2456 return BT->getKind() >= BuiltinType::Bool &&
2457 BT->getKind() <= BuiltinType::Ibm128;
2458 if (const auto *ET = dyn_cast<EnumType>(Val: CanonicalType)) {
2459 // GCC allows forward declaration of enum types (forbid by C99 6.7.2.3p2).
2460 // If a body isn't seen by the time we get here, return false.
2461 //
2462 // C++0x: Enumerations are not arithmetic types. For now, just return
2463 // false for scoped enumerations since that will disable any
2464 // unwanted implicit conversions.
2465 const auto *ED = ET->getDecl();
2466 return !ED->isScoped() && ED->getDefinitionOrSelf()->isComplete();
2467 }
2468
2469 if (isOverflowBehaviorType() &&
2470 getAs<OverflowBehaviorType>()->getUnderlyingType()->isArithmeticType())
2471 return true;
2472
2473 return isa<ComplexType>(Val: CanonicalType) || isBitIntType();
2474}
2475
2476bool Type::hasBooleanRepresentation() const {
2477 if (const auto *VT = dyn_cast<VectorType>(Val: CanonicalType))
2478 return VT->getElementType()->isBooleanType();
2479 if (const auto *ED = getAsEnumDecl())
2480 return ED->isComplete() && ED->getIntegerType()->isBooleanType();
2481 if (const auto *IT = dyn_cast<BitIntType>(Val: CanonicalType))
2482 return IT->getNumBits() == 1;
2483 return isBooleanType();
2484}
2485
2486Type::ScalarTypeKind Type::getScalarTypeKind() const {
2487 assert(isScalarType());
2488
2489 const Type *T = CanonicalType.getTypePtr();
2490 if (const auto *BT = dyn_cast<BuiltinType>(Val: T)) {
2491 if (BT->getKind() == BuiltinType::Bool)
2492 return STK_Bool;
2493 if (BT->getKind() == BuiltinType::NullPtr)
2494 return STK_CPointer;
2495 if (BT->isInteger())
2496 return STK_Integral;
2497 if (BT->isFloatingPoint())
2498 return STK_Floating;
2499 if (BT->isFixedPointType())
2500 return STK_FixedPoint;
2501 llvm_unreachable("unknown scalar builtin type");
2502 } else if (isa<PointerType>(Val: T)) {
2503 return STK_CPointer;
2504 } else if (isa<BlockPointerType>(Val: T)) {
2505 return STK_BlockPointer;
2506 } else if (isa<ObjCObjectPointerType>(Val: T)) {
2507 return STK_ObjCObjectPointer;
2508 } else if (isa<MemberPointerType>(Val: T)) {
2509 return STK_MemberPointer;
2510 } else if (isa<EnumType>(Val: T)) {
2511 assert(T->castAsEnumDecl()->isComplete());
2512 return STK_Integral;
2513 } else if (const auto *CT = dyn_cast<ComplexType>(Val: T)) {
2514 if (CT->getElementType()->isRealFloatingType())
2515 return STK_FloatingComplex;
2516 return STK_IntegralComplex;
2517 } else if (isBitIntType()) {
2518 return STK_Integral;
2519 } else if (isa<OverflowBehaviorType>(Val: T)) {
2520 return STK_Integral;
2521 }
2522
2523 llvm_unreachable("unknown scalar type");
2524}
2525
2526/// Determines whether the type is a C++ aggregate type or C
2527/// aggregate or union type.
2528///
2529/// An aggregate type is an array or a class type (struct, union, or
2530/// class) that has no user-declared constructors, no private or
2531/// protected non-static data members, no base classes, and no virtual
2532/// functions (C++ [dcl.init.aggr]p1). The notion of an aggregate type
2533/// subsumes the notion of C aggregates (C99 6.2.5p21) because it also
2534/// includes union types.
2535bool Type::isAggregateType() const {
2536 if (const auto *Record = dyn_cast<RecordType>(Val: CanonicalType)) {
2537 if (const auto *ClassDecl = dyn_cast<CXXRecordDecl>(Val: Record->getDecl()))
2538 return ClassDecl->isAggregate();
2539
2540 return true;
2541 }
2542
2543 return isa<ArrayType>(Val: CanonicalType);
2544}
2545
2546/// isConstantSizeType - Return true if this is not a variable sized type,
2547/// according to the rules of C99 6.7.5p3. It is not legal to call this on
2548/// incomplete types or dependent types.
2549bool Type::isConstantSizeType() const {
2550 assert(!isIncompleteType() && "This doesn't make sense for incomplete types");
2551 assert(!isDependentType() && "This doesn't make sense for dependent types");
2552 // The VAT must have a size, as it is known to be complete.
2553 return !isa<VariableArrayType>(Val: CanonicalType);
2554}
2555
2556/// isIncompleteType - Return true if this is an incomplete type (C99 6.2.5p1)
2557/// - a type that can describe objects, but which lacks information needed to
2558/// determine its size.
2559bool Type::isIncompleteType(NamedDecl **Def) const {
2560 if (Def)
2561 *Def = nullptr;
2562
2563 switch (CanonicalType->getTypeClass()) {
2564 default:
2565 return false;
2566 case Builtin:
2567 // Void is the only incomplete builtin type. Per C99 6.2.5p19, it can never
2568 // be completed.
2569 return isVoidType();
2570 case Enum: {
2571 auto *EnumD = castAsEnumDecl();
2572 if (Def)
2573 *Def = EnumD;
2574 return !EnumD->isComplete();
2575 }
2576 case Record: {
2577 // A tagged type (struct/union/enum/class) is incomplete if the decl is a
2578 // forward declaration, but not a full definition (C99 6.2.5p22).
2579 auto *Rec = castAsRecordDecl();
2580 if (Def)
2581 *Def = Rec;
2582 return !Rec->isCompleteDefinition();
2583 }
2584 case InjectedClassName: {
2585 auto *Rec = castAsCXXRecordDecl();
2586 if (!Rec->isBeingDefined())
2587 return false;
2588 if (Def)
2589 *Def = Rec;
2590 return true;
2591 }
2592 case ConstantArray:
2593 case VariableArray:
2594 // An array is incomplete if its element type is incomplete
2595 // (C++ [dcl.array]p1).
2596 // We don't handle dependent-sized arrays (dependent types are never treated
2597 // as incomplete).
2598 return cast<ArrayType>(Val: CanonicalType)
2599 ->getElementType()
2600 ->isIncompleteType(Def);
2601 case IncompleteArray:
2602 // An array of unknown size is an incomplete type (C99 6.2.5p22).
2603 return true;
2604 case MemberPointer: {
2605 // Member pointers in the MS ABI have special behavior in
2606 // RequireCompleteType: they attach a MSInheritanceAttr to the CXXRecordDecl
2607 // to indicate which inheritance model to use.
2608 // The inheritance attribute might only be present on the most recent
2609 // CXXRecordDecl.
2610 const CXXRecordDecl *RD =
2611 cast<MemberPointerType>(Val: CanonicalType)->getMostRecentCXXRecordDecl();
2612 // Member pointers with dependent class types don't get special treatment.
2613 if (!RD || RD->isDependentType())
2614 return false;
2615 ASTContext &Context = RD->getASTContext();
2616 // Member pointers not in the MS ABI don't get special treatment.
2617 if (!Context.getTargetInfo().getCXXABI().isMicrosoft())
2618 return false;
2619 // Nothing interesting to do if the inheritance attribute is already set.
2620 if (RD->hasAttr<MSInheritanceAttr>())
2621 return false;
2622 return true;
2623 }
2624 case ObjCObject:
2625 return cast<ObjCObjectType>(Val: CanonicalType)
2626 ->getBaseType()
2627 ->isIncompleteType(Def);
2628 case ObjCInterface: {
2629 // ObjC interfaces are incomplete if they are @class, not @interface.
2630 ObjCInterfaceDecl *Interface =
2631 cast<ObjCInterfaceType>(Val: CanonicalType)->getDecl();
2632 if (Def)
2633 *Def = Interface;
2634 return !Interface->hasDefinition();
2635 }
2636 }
2637}
2638
2639bool Type::isAlwaysIncompleteType() const {
2640 if (!isIncompleteType())
2641 return false;
2642
2643 // Forward declarations of structs, classes, enums, and unions could be later
2644 // completed in a compilation unit by providing a type definition.
2645 if (isa<TagType>(Val: CanonicalType))
2646 return false;
2647
2648 // Other types are incompletable.
2649 //
2650 // E.g. `char[]` and `void`. The type is incomplete and no future
2651 // type declarations can make the type complete.
2652 return true;
2653}
2654
2655bool Type::isSizelessBuiltinType() const {
2656 if (isSizelessVectorType())
2657 return true;
2658
2659 if (const BuiltinType *BT = getAs<BuiltinType>()) {
2660 switch (BT->getKind()) {
2661 // WebAssembly reference types
2662#define WASM_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
2663#include "clang/Basic/WebAssemblyReferenceTypes.def"
2664 // HLSL intangible types
2665#define HLSL_INTANGIBLE_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
2666#include "clang/Basic/HLSLIntangibleTypes.def"
2667 // AMDGPU feature predicate type
2668 case BuiltinType::AMDGPUFeaturePredicate:
2669 return true;
2670 default:
2671 return false;
2672 }
2673 }
2674 return false;
2675}
2676
2677bool Type::isWebAssemblyExternrefType() const {
2678 if (const auto *BT = getAs<BuiltinType>())
2679 return BT->getKind() == BuiltinType::WasmExternRef;
2680 return false;
2681}
2682
2683bool Type::isWebAssemblyTableType() const {
2684 if (const auto *ATy = dyn_cast<ArrayType>(Val: this))
2685 return ATy->getElementType().isWebAssemblyReferenceType();
2686
2687 if (const auto *PTy = dyn_cast<PointerType>(Val: this))
2688 return PTy->getPointeeType().isWebAssemblyReferenceType();
2689
2690 return false;
2691}
2692
2693bool Type::isSizelessType() const { return isSizelessBuiltinType(); }
2694
2695bool Type::isSizelessVectorType() const {
2696 return isSVESizelessBuiltinType() || isRVVSizelessBuiltinType();
2697}
2698
2699bool Type::isSVESizelessBuiltinType() const {
2700 if (const BuiltinType *BT = getAs<BuiltinType>()) {
2701 switch (BT->getKind()) {
2702 // SVE Types
2703#define SVE_VECTOR_TYPE(Name, MangledName, Id, SingletonId) \
2704 case BuiltinType::Id: \
2705 return true;
2706#define SVE_OPAQUE_TYPE(Name, MangledName, Id, SingletonId) \
2707 case BuiltinType::Id: \
2708 return true;
2709#define SVE_PREDICATE_TYPE(Name, MangledName, Id, SingletonId) \
2710 case BuiltinType::Id: \
2711 return true;
2712#include "clang/Basic/AArch64ACLETypes.def"
2713 default:
2714 return false;
2715 }
2716 }
2717 return false;
2718}
2719
2720bool Type::isRVVSizelessBuiltinType() const {
2721 if (const BuiltinType *BT = getAs<BuiltinType>()) {
2722 switch (BT->getKind()) {
2723#define RVV_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
2724#include "clang/Basic/RISCVVTypes.def"
2725 return true;
2726 default:
2727 return false;
2728 }
2729 }
2730 return false;
2731}
2732
2733bool Type::isSveVLSBuiltinType() const {
2734 if (const BuiltinType *BT = getAs<BuiltinType>()) {
2735 switch (BT->getKind()) {
2736 case BuiltinType::SveInt8:
2737 case BuiltinType::SveInt16:
2738 case BuiltinType::SveInt32:
2739 case BuiltinType::SveInt64:
2740 case BuiltinType::SveUint8:
2741 case BuiltinType::SveUint16:
2742 case BuiltinType::SveUint32:
2743 case BuiltinType::SveUint64:
2744 case BuiltinType::SveFloat16:
2745 case BuiltinType::SveFloat32:
2746 case BuiltinType::SveFloat64:
2747 case BuiltinType::SveBFloat16:
2748 case BuiltinType::SveBool:
2749 case BuiltinType::SveBoolx2:
2750 case BuiltinType::SveBoolx4:
2751 case BuiltinType::SveMFloat8:
2752 return true;
2753 default:
2754 return false;
2755 }
2756 }
2757 return false;
2758}
2759
2760QualType Type::getSizelessVectorEltType(const ASTContext &Ctx) const {
2761 assert(isSizelessVectorType() && "Must be sizeless vector type");
2762 // Currently supports SVE and RVV
2763 if (isSVESizelessBuiltinType())
2764 return getSveEltType(Ctx);
2765
2766 if (isRVVSizelessBuiltinType())
2767 return getRVVEltType(Ctx);
2768
2769 llvm_unreachable("Unhandled type");
2770}
2771
2772QualType Type::getSveEltType(const ASTContext &Ctx) const {
2773 assert(isSveVLSBuiltinType() && "unsupported type!");
2774
2775 const BuiltinType *BTy = castAs<BuiltinType>();
2776 if (BTy->getKind() == BuiltinType::SveBool)
2777 // Represent predicates as i8 rather than i1 to avoid any layout issues.
2778 // The type is bitcasted to a scalable predicate type when casting between
2779 // scalable and fixed-length vectors.
2780 return Ctx.UnsignedCharTy;
2781 else
2782 return Ctx.getBuiltinVectorTypeInfo(VecTy: BTy).ElementType;
2783}
2784
2785bool Type::isRVVVLSBuiltinType() const {
2786 if (const BuiltinType *BT = getAs<BuiltinType>()) {
2787 switch (BT->getKind()) {
2788#define RVV_VECTOR_TYPE(Name, Id, SingletonId, NumEls, ElBits, NF, IsSigned, \
2789 IsFP, IsBF) \
2790 case BuiltinType::Id: \
2791 return NF == 1;
2792#define RVV_PREDICATE_TYPE(Name, Id, SingletonId, NumEls) \
2793 case BuiltinType::Id: \
2794 return true;
2795#include "clang/Basic/RISCVVTypes.def"
2796 default:
2797 return false;
2798 }
2799 }
2800 return false;
2801}
2802
2803QualType Type::getRVVEltType(const ASTContext &Ctx) const {
2804 assert(isRVVVLSBuiltinType() && "unsupported type!");
2805
2806 const BuiltinType *BTy = castAs<BuiltinType>();
2807
2808 switch (BTy->getKind()) {
2809#define RVV_PREDICATE_TYPE(Name, Id, SingletonId, NumEls) \
2810 case BuiltinType::Id: \
2811 return Ctx.UnsignedCharTy;
2812 default:
2813 return Ctx.getBuiltinVectorTypeInfo(VecTy: BTy).ElementType;
2814#include "clang/Basic/RISCVVTypes.def"
2815 }
2816
2817 llvm_unreachable("Unhandled type");
2818}
2819
2820bool QualType::isPODType(const ASTContext &Context) const {
2821 if (Context.getLangOpts().HLSL &&
2822 getTypePtr()->isHLSLStandardLayoutRecordOrArrayOf())
2823 return true;
2824
2825 // C++11 has a more relaxed definition of POD.
2826 if (Context.getLangOpts().CPlusPlus11)
2827 return isCXX11PODType(Context);
2828
2829 return isCXX98PODType(Context);
2830}
2831
2832bool QualType::isCXX98PODType(const ASTContext &Context) const {
2833 // The compiler shouldn't query this for incomplete types, but the user might.
2834 // We return false for that case. Except for incomplete arrays of PODs, which
2835 // are PODs according to the standard.
2836 if (isNull())
2837 return false;
2838
2839 if ((*this)->isIncompleteArrayType())
2840 return Context.getBaseElementType(QT: *this).isCXX98PODType(Context);
2841
2842 if ((*this)->isIncompleteType())
2843 return false;
2844
2845 if (hasNonTrivialObjCLifetime())
2846 return false;
2847
2848 QualType CanonicalType = getTypePtr()->CanonicalType;
2849
2850 // Any type that is, or contains, address discriminated data is never POD.
2851 if (Context.containsAddressDiscriminatedPointerAuth(T: CanonicalType))
2852 return false;
2853
2854 switch (CanonicalType->getTypeClass()) {
2855 // Everything not explicitly mentioned is not POD.
2856 default:
2857 return false;
2858 case Type::VariableArray:
2859 case Type::ConstantArray:
2860 // IncompleteArray is handled above.
2861 return Context.getBaseElementType(QT: *this).isCXX98PODType(Context);
2862
2863 case Type::ObjCObjectPointer:
2864 case Type::BlockPointer:
2865 case Type::Builtin:
2866 case Type::Complex:
2867 case Type::Pointer:
2868 case Type::MemberPointer:
2869 case Type::Vector:
2870 case Type::ExtVector:
2871 case Type::BitInt:
2872 case Type::OverflowBehavior:
2873 return true;
2874
2875 case Type::Enum:
2876 return true;
2877
2878 case Type::Record:
2879 if (const auto *ClassDecl =
2880 dyn_cast<CXXRecordDecl>(Val: cast<RecordType>(Val&: CanonicalType)->getDecl()))
2881 return ClassDecl->isPOD();
2882
2883 // C struct/union is POD.
2884 return true;
2885 }
2886}
2887
2888bool QualType::isTrivialType(const ASTContext &Context) const {
2889 // The compiler shouldn't query this for incomplete types, but the user might.
2890 // We return false for that case. Except for incomplete arrays of PODs, which
2891 // are PODs according to the standard.
2892 if (isNull())
2893 return false;
2894
2895 if ((*this)->isArrayType())
2896 return Context.getBaseElementType(QT: *this).isTrivialType(Context);
2897
2898 if ((*this)->isSizelessBuiltinType())
2899 return true;
2900
2901 // Return false for incomplete types after skipping any incomplete array
2902 // types which are expressly allowed by the standard and thus our API.
2903 if ((*this)->isIncompleteType())
2904 return false;
2905
2906 if (hasNonTrivialObjCLifetime())
2907 return false;
2908
2909 QualType CanonicalType = getTypePtr()->CanonicalType;
2910 if (CanonicalType->isDependentType())
2911 return false;
2912
2913 // Any type that is, or contains, address discriminated data is never a
2914 // trivial type.
2915 if (Context.containsAddressDiscriminatedPointerAuth(T: CanonicalType))
2916 return false;
2917
2918 // C++0x [basic.types]p9:
2919 // Scalar types, trivial class types, arrays of such types, and
2920 // cv-qualified versions of these types are collectively called trivial
2921 // types.
2922
2923 // As an extension, Clang treats vector types as Scalar types.
2924 if (CanonicalType->isScalarType() || CanonicalType->isVectorType())
2925 return true;
2926
2927 if (const auto *ClassDecl = CanonicalType->getAsCXXRecordDecl()) {
2928 // C++20 [class]p6:
2929 // A trivial class is a class that is trivially copyable, and
2930 // has one or more eligible default constructors such that each is
2931 // trivial.
2932 // FIXME: We should merge this definition of triviality into
2933 // CXXRecordDecl::isTrivial. Currently it computes the wrong thing.
2934 return ClassDecl->hasTrivialDefaultConstructor() &&
2935 !ClassDecl->hasNonTrivialDefaultConstructor() &&
2936 ClassDecl->isTriviallyCopyable();
2937 }
2938
2939 if (isa<RecordType>(Val: CanonicalType))
2940 return true;
2941
2942 // No other types can match.
2943 return false;
2944}
2945
2946static bool isTriviallyCopyableTypeImpl(const QualType &type,
2947 const ASTContext &Context,
2948 bool IsCopyConstructible) {
2949 if (type->isArrayType())
2950 return isTriviallyCopyableTypeImpl(type: Context.getBaseElementType(QT: type),
2951 Context, IsCopyConstructible);
2952
2953 if (type.hasNonTrivialObjCLifetime())
2954 return false;
2955
2956 // C++11 [basic.types]p9 - See Core 2094
2957 // Scalar types, trivially copyable class types, arrays of such types, and
2958 // cv-qualified versions of these types are collectively
2959 // called trivially copy constructible types.
2960
2961 QualType CanonicalType = type.getCanonicalType();
2962 if (CanonicalType->isDependentType())
2963 return false;
2964
2965 if (CanonicalType->isSizelessBuiltinType())
2966 return true;
2967
2968 // Return false for incomplete types after skipping any incomplete array types
2969 // which are expressly allowed by the standard and thus our API.
2970 if (CanonicalType->isIncompleteType())
2971 return false;
2972
2973 if (CanonicalType.hasAddressDiscriminatedPointerAuth())
2974 return false;
2975
2976 // As an extension, Clang treats vector and matrix types as Scalar types.
2977 if (CanonicalType->isScalarType() || CanonicalType->isVectorType() ||
2978 CanonicalType->isMatrixType())
2979 return true;
2980
2981 // Mfloat8 type is a special case as it not scalar, but is still trivially
2982 // copyable.
2983 if (CanonicalType->isMFloat8Type())
2984 return true;
2985
2986 if (const auto *RD = CanonicalType->getAsRecordDecl()) {
2987 if (const auto *ClassDecl = dyn_cast<CXXRecordDecl>(Val: RD)) {
2988 if (IsCopyConstructible)
2989 return ClassDecl->isTriviallyCopyConstructible();
2990 return ClassDecl->isTriviallyCopyable();
2991 }
2992 return !RD->isNonTrivialToPrimitiveCopy();
2993 }
2994 // No other types can match.
2995 return false;
2996}
2997
2998bool QualType::isTriviallyCopyableType(const ASTContext &Context) const {
2999 return isTriviallyCopyableTypeImpl(type: *this, Context,
3000 /*IsCopyConstructible=*/false);
3001}
3002
3003// FIXME: each call will trigger a full computation, cache the result.
3004bool QualType::isBitwiseCloneableType(const ASTContext &Context) const {
3005 auto CanonicalType = getCanonicalType();
3006 if (CanonicalType.hasNonTrivialObjCLifetime())
3007 return false;
3008 if (CanonicalType->isArrayType())
3009 return Context.getBaseElementType(QT: CanonicalType)
3010 .isBitwiseCloneableType(Context);
3011
3012 if (CanonicalType->isIncompleteType())
3013 return false;
3014
3015 // Any type that is, or contains, address discriminated data is never
3016 // bitwise clonable.
3017 if (Context.containsAddressDiscriminatedPointerAuth(T: CanonicalType))
3018 return false;
3019
3020 const auto *RD = CanonicalType->getAsRecordDecl(); // struct/union/class
3021 if (!RD)
3022 return true;
3023
3024 if (RD->isInvalidDecl())
3025 return false;
3026
3027 // Never allow memcpy when we're adding poisoned padding bits to the struct.
3028 // Accessing these posioned bits will trigger false alarms on
3029 // SanitizeAddressFieldPadding etc.
3030 if (RD->mayInsertExtraPadding())
3031 return false;
3032
3033 for (auto *const Field : RD->fields()) {
3034 if (!Field->getType().isBitwiseCloneableType(Context))
3035 return false;
3036 }
3037
3038 if (const auto *CXXRD = dyn_cast<CXXRecordDecl>(Val: RD)) {
3039 for (auto Base : CXXRD->bases())
3040 if (!Base.getType().isBitwiseCloneableType(Context))
3041 return false;
3042 for (auto VBase : CXXRD->vbases())
3043 if (!VBase.getType().isBitwiseCloneableType(Context))
3044 return false;
3045 }
3046 return true;
3047}
3048
3049bool QualType::isTriviallyCopyConstructibleType(
3050 const ASTContext &Context) const {
3051 return isTriviallyCopyableTypeImpl(type: *this, Context,
3052 /*IsCopyConstructible=*/true);
3053}
3054
3055bool QualType::isNonWeakInMRRWithObjCWeak(const ASTContext &Context) const {
3056 return !Context.getLangOpts().ObjCAutoRefCount &&
3057 Context.getLangOpts().ObjCWeak &&
3058 getObjCLifetime() != Qualifiers::OCL_Weak;
3059}
3060
3061bool QualType::hasNonTrivialToPrimitiveDefaultInitializeCUnion(
3062 const RecordDecl *RD) {
3063 return RD->hasNonTrivialToPrimitiveDefaultInitializeCUnion();
3064}
3065
3066bool QualType::hasNonTrivialToPrimitiveDestructCUnion(const RecordDecl *RD) {
3067 return RD->hasNonTrivialToPrimitiveDestructCUnion();
3068}
3069
3070bool QualType::hasNonTrivialToPrimitiveCopyCUnion(const RecordDecl *RD) {
3071 return RD->hasNonTrivialToPrimitiveCopyCUnion();
3072}
3073
3074bool QualType::isWebAssemblyReferenceType() const {
3075 return isWebAssemblyExternrefType() || isWebAssemblyFuncrefType();
3076}
3077
3078bool QualType::isWebAssemblyExternrefType() const {
3079 return getTypePtr()->isWebAssemblyExternrefType();
3080}
3081
3082bool QualType::isWebAssemblyFuncrefType() const {
3083 return getTypePtr()->isFunctionPointerType() &&
3084 (getTypePtr()->getPointeeType().getAddressSpace() ==
3085 LangAS::wasm_funcref);
3086}
3087
3088bool QualType::isWrapType() const {
3089 if (const auto *OBT = getCanonicalType()->getAs<OverflowBehaviorType>())
3090 return OBT->getBehaviorKind() ==
3091 OverflowBehaviorType::OverflowBehaviorKind::Wrap;
3092
3093 return false;
3094}
3095
3096bool QualType::isTrapType() const {
3097 if (const auto *OBT = getCanonicalType()->getAs<OverflowBehaviorType>())
3098 return OBT->getBehaviorKind() ==
3099 OverflowBehaviorType::OverflowBehaviorKind::Trap;
3100
3101 return false;
3102}
3103
3104QualType::PrimitiveDefaultInitializeKind
3105QualType::isNonTrivialToPrimitiveDefaultInitialize() const {
3106 if (const auto *RD =
3107 getTypePtr()->getBaseElementTypeUnsafe()->getAsRecordDecl())
3108 if (RD->isNonTrivialToPrimitiveDefaultInitialize())
3109 return PDIK_Struct;
3110
3111 switch (getQualifiers().getObjCLifetime()) {
3112 case Qualifiers::OCL_Strong:
3113 return PDIK_ARCStrong;
3114 case Qualifiers::OCL_Weak:
3115 return PDIK_ARCWeak;
3116 default:
3117 return PDIK_Trivial;
3118 }
3119}
3120
3121QualType::PrimitiveCopyKind QualType::isNonTrivialToPrimitiveCopy() const {
3122 if (const auto *RD =
3123 getTypePtr()->getBaseElementTypeUnsafe()->getAsRecordDecl())
3124 if (RD->isNonTrivialToPrimitiveCopy())
3125 return PCK_Struct;
3126
3127 Qualifiers Qs = getQualifiers();
3128 switch (Qs.getObjCLifetime()) {
3129 case Qualifiers::OCL_Strong:
3130 return PCK_ARCStrong;
3131 case Qualifiers::OCL_Weak:
3132 return PCK_ARCWeak;
3133 default:
3134 if (hasAddressDiscriminatedPointerAuth())
3135 return PCK_PtrAuth;
3136 return Qs.hasVolatile() ? PCK_VolatileTrivial : PCK_Trivial;
3137 }
3138}
3139
3140QualType::PrimitiveCopyKind
3141QualType::isNonTrivialToPrimitiveDestructiveMove() const {
3142 return isNonTrivialToPrimitiveCopy();
3143}
3144
3145bool Type::isLiteralType(const ASTContext &Ctx) const {
3146 if (isDependentType())
3147 return false;
3148
3149 // C++1y [basic.types]p10:
3150 // A type is a literal type if it is:
3151 // -- cv void; or
3152 if (Ctx.getLangOpts().CPlusPlus14 && isVoidType())
3153 return true;
3154
3155 // C++11 [basic.types]p10:
3156 // A type is a literal type if it is:
3157 // [...]
3158 // -- an array of literal type other than an array of runtime bound; or
3159 if (isVariableArrayType())
3160 return false;
3161 const Type *BaseTy = getBaseElementTypeUnsafe();
3162 assert(BaseTy && "NULL element type");
3163
3164 // Return false for incomplete types after skipping any incomplete array
3165 // types; those are expressly allowed by the standard and thus our API.
3166 if (BaseTy->isIncompleteType())
3167 return false;
3168
3169 // C++11 [basic.types]p10:
3170 // A type is a literal type if it is:
3171 // -- a scalar type; or
3172 // As an extension, Clang treats vector types and complex types as
3173 // literal types.
3174 if (BaseTy->isScalarType() || BaseTy->isVectorType() ||
3175 BaseTy->isAnyComplexType())
3176 return true;
3177 // Matrices with constant numbers of rows and columns are also literal types
3178 // in HLSL.
3179 if (Ctx.getLangOpts().HLSL && BaseTy->isConstantMatrixType())
3180 return true;
3181 // -- a reference type; or
3182 if (BaseTy->isReferenceType())
3183 return true;
3184 // -- a class type that has all of the following properties:
3185 if (const auto *RD = BaseTy->getAsRecordDecl()) {
3186 // -- a trivial destructor,
3187 // -- every constructor call and full-expression in the
3188 // brace-or-equal-initializers for non-static data members (if any)
3189 // is a constant expression,
3190 // -- it is an aggregate type or has at least one constexpr
3191 // constructor or constructor template that is not a copy or move
3192 // constructor, and
3193 // -- all non-static data members and base classes of literal types
3194 //
3195 // We resolve DR1361 by ignoring the second bullet.
3196 if (const auto *ClassDecl = dyn_cast<CXXRecordDecl>(Val: RD))
3197 return ClassDecl->isLiteral();
3198
3199 return true;
3200 }
3201
3202 // We treat _Atomic T as a literal type if T is a literal type.
3203 if (const auto *AT = BaseTy->getAs<AtomicType>())
3204 return AT->getValueType()->isLiteralType(Ctx);
3205
3206 if (const auto *OBT = BaseTy->getAs<OverflowBehaviorType>())
3207 return OBT->getUnderlyingType()->isLiteralType(Ctx);
3208
3209 // If this type hasn't been deduced yet, then conservatively assume that
3210 // it'll work out to be a literal type.
3211 if (isa<AutoType>(Val: BaseTy->getCanonicalTypeInternal()))
3212 return true;
3213
3214 return false;
3215}
3216
3217bool Type::isStructuralType() const {
3218 // C++20 [temp.param]p6:
3219 // A structural type is one of the following:
3220 // -- a scalar type; or
3221 // -- a vector type [Clang extension]; or
3222 if (isScalarType() || isVectorType())
3223 return true;
3224 // -- an lvalue reference type; or
3225 if (isLValueReferenceType())
3226 return true;
3227 // -- a literal class type [...under some conditions]
3228 if (const CXXRecordDecl *RD = getAsCXXRecordDecl())
3229 return RD->isStructural();
3230 return false;
3231}
3232
3233bool Type::isStandardLayoutType() const {
3234 if (isDependentType())
3235 return false;
3236
3237 // C++0x [basic.types]p9:
3238 // Scalar types, standard-layout class types, arrays of such types, and
3239 // cv-qualified versions of these types are collectively called
3240 // standard-layout types.
3241 const Type *BaseTy = getBaseElementTypeUnsafe();
3242 assert(BaseTy && "NULL element type");
3243
3244 // Return false for incomplete types after skipping any incomplete array
3245 // types which are expressly allowed by the standard and thus our API.
3246 if (BaseTy->isIncompleteType())
3247 return false;
3248
3249 // As an extension, Clang treats vector types as Scalar types.
3250 if (BaseTy->isScalarType() || BaseTy->isVectorType())
3251 return true;
3252 if (const auto *RD = BaseTy->getAsRecordDecl()) {
3253 if (const auto *ClassDecl = dyn_cast<CXXRecordDecl>(Val: RD);
3254 ClassDecl && !ClassDecl->isStandardLayout())
3255 return false;
3256
3257 // Default to 'true' for non-C++ class types.
3258 // FIXME: This is a bit dubious, but plain C structs should trivially meet
3259 // all the requirements of standard layout classes.
3260 return true;
3261 }
3262
3263 // No other types can match.
3264 return false;
3265}
3266
3267// This is effectively the intersection of isTrivialType and
3268// isStandardLayoutType. We implement it directly to avoid redundant
3269// conversions from a type to a CXXRecordDecl.
3270bool QualType::isCXX11PODType(const ASTContext &Context) const {
3271 const Type *ty = getTypePtr();
3272 if (ty->isDependentType())
3273 return false;
3274
3275 if (hasNonTrivialObjCLifetime())
3276 return false;
3277
3278 // C++11 [basic.types]p9:
3279 // Scalar types, POD classes, arrays of such types, and cv-qualified
3280 // versions of these types are collectively called trivial types.
3281 const Type *BaseTy = ty->getBaseElementTypeUnsafe();
3282 assert(BaseTy && "NULL element type");
3283
3284 if (BaseTy->isSizelessBuiltinType())
3285 return true;
3286
3287 // Return false for incomplete types after skipping any incomplete array
3288 // types which are expressly allowed by the standard and thus our API.
3289 if (BaseTy->isIncompleteType())
3290 return false;
3291
3292 // Any type that is, or contains, address discriminated data is non-POD.
3293 if (Context.containsAddressDiscriminatedPointerAuth(T: *this))
3294 return false;
3295
3296 // As an extension, Clang treats vector types as Scalar types.
3297 if (BaseTy->isScalarType() || BaseTy->isVectorType())
3298 return true;
3299 if (const auto *RD = BaseTy->getAsRecordDecl()) {
3300 if (const auto *ClassDecl = dyn_cast<CXXRecordDecl>(Val: RD)) {
3301 // C++11 [class]p10:
3302 // A POD struct is a non-union class that is both a trivial class [...]
3303 if (!ClassDecl->isTrivial())
3304 return false;
3305
3306 // C++11 [class]p10:
3307 // A POD struct is a non-union class that is both a trivial class and
3308 // a standard-layout class [...]
3309 if (!ClassDecl->isStandardLayout())
3310 return false;
3311
3312 // C++11 [class]p10:
3313 // A POD struct is a non-union class that is both a trivial class and
3314 // a standard-layout class, and has no non-static data members of type
3315 // non-POD struct, non-POD union (or array of such types). [...]
3316 //
3317 // We don't directly query the recursive aspect as the requirements for
3318 // both standard-layout classes and trivial classes apply recursively
3319 // already.
3320 }
3321
3322 return true;
3323 }
3324
3325 // No other types can match.
3326 return false;
3327}
3328
3329bool Type::isNothrowT() const {
3330 if (const auto *RD = getAsCXXRecordDecl()) {
3331 IdentifierInfo *II = RD->getIdentifier();
3332 if (II && II->isStr(Str: "nothrow_t") && RD->isInStdNamespace())
3333 return true;
3334 }
3335 return false;
3336}
3337
3338bool Type::isAlignValT() const {
3339 if (const auto *ET = getAsCanonical<EnumType>()) {
3340 const auto *ED = ET->getDecl();
3341 IdentifierInfo *II = ED->getIdentifier();
3342 if (II && II->isStr(Str: "align_val_t") && ED->isInStdNamespace())
3343 return true;
3344 }
3345 return false;
3346}
3347
3348bool Type::isStdByteType() const {
3349 if (const auto *ET = getAsCanonical<EnumType>()) {
3350 const auto *ED = ET->getDecl();
3351 IdentifierInfo *II = ED->getIdentifier();
3352 if (II && II->isStr(Str: "byte") && ED->isInStdNamespace())
3353 return true;
3354 }
3355 return false;
3356}
3357
3358bool Type::isSpecifierType() const {
3359 // Note that this intentionally does not use the canonical type.
3360 switch (getTypeClass()) {
3361 case Builtin:
3362 case Record:
3363 case Enum:
3364 case Typedef:
3365 case Complex:
3366 case TypeOfExpr:
3367 case TypeOf:
3368 case TemplateTypeParm:
3369 case SubstTemplateTypeParm:
3370 case TemplateSpecialization:
3371 case DependentName:
3372 case ObjCInterface:
3373 case ObjCObject:
3374 return true;
3375 default:
3376 return false;
3377 }
3378}
3379
3380ElaboratedTypeKeyword KeywordHelpers::getKeywordForTypeSpec(unsigned TypeSpec) {
3381 switch (TypeSpec) {
3382 default:
3383 return ElaboratedTypeKeyword::None;
3384 case TST_typename:
3385 return ElaboratedTypeKeyword::Typename;
3386 case TST_class:
3387 return ElaboratedTypeKeyword::Class;
3388 case TST_struct:
3389 return ElaboratedTypeKeyword::Struct;
3390 case TST_interface:
3391 return ElaboratedTypeKeyword::Interface;
3392 case TST_union:
3393 return ElaboratedTypeKeyword::Union;
3394 case TST_enum:
3395 return ElaboratedTypeKeyword::Enum;
3396 }
3397}
3398
3399TagTypeKind KeywordHelpers::getTagTypeKindForTypeSpec(unsigned TypeSpec) {
3400 switch (TypeSpec) {
3401 case TST_class:
3402 return TagTypeKind::Class;
3403 case TST_struct:
3404 return TagTypeKind::Struct;
3405 case TST_interface:
3406 return TagTypeKind::Interface;
3407 case TST_union:
3408 return TagTypeKind::Union;
3409 case TST_enum:
3410 return TagTypeKind::Enum;
3411 }
3412
3413 llvm_unreachable("Type specifier is not a tag type kind.");
3414}
3415
3416ElaboratedTypeKeyword
3417KeywordHelpers::getKeywordForTagTypeKind(TagTypeKind Kind) {
3418 switch (Kind) {
3419 case TagTypeKind::Class:
3420 return ElaboratedTypeKeyword::Class;
3421 case TagTypeKind::Struct:
3422 return ElaboratedTypeKeyword::Struct;
3423 case TagTypeKind::Interface:
3424 return ElaboratedTypeKeyword::Interface;
3425 case TagTypeKind::Union:
3426 return ElaboratedTypeKeyword::Union;
3427 case TagTypeKind::Enum:
3428 return ElaboratedTypeKeyword::Enum;
3429 }
3430 llvm_unreachable("Unknown tag type kind.");
3431}
3432
3433TagTypeKind
3434KeywordHelpers::getTagTypeKindForKeyword(ElaboratedTypeKeyword Keyword) {
3435 switch (Keyword) {
3436 case ElaboratedTypeKeyword::Class:
3437 return TagTypeKind::Class;
3438 case ElaboratedTypeKeyword::Struct:
3439 return TagTypeKind::Struct;
3440 case ElaboratedTypeKeyword::Interface:
3441 return TagTypeKind::Interface;
3442 case ElaboratedTypeKeyword::Union:
3443 return TagTypeKind::Union;
3444 case ElaboratedTypeKeyword::Enum:
3445 return TagTypeKind::Enum;
3446 case ElaboratedTypeKeyword::None: // Fall through.
3447 case ElaboratedTypeKeyword::Typename:
3448 llvm_unreachable("Elaborated type keyword is not a tag type kind.");
3449 }
3450 llvm_unreachable("Unknown elaborated type keyword.");
3451}
3452
3453bool KeywordHelpers::KeywordIsTagTypeKind(ElaboratedTypeKeyword Keyword) {
3454 switch (Keyword) {
3455 case ElaboratedTypeKeyword::None:
3456 case ElaboratedTypeKeyword::Typename:
3457 return false;
3458 case ElaboratedTypeKeyword::Class:
3459 case ElaboratedTypeKeyword::Struct:
3460 case ElaboratedTypeKeyword::Interface:
3461 case ElaboratedTypeKeyword::Union:
3462 case ElaboratedTypeKeyword::Enum:
3463 return true;
3464 }
3465 llvm_unreachable("Unknown elaborated type keyword.");
3466}
3467
3468StringRef KeywordHelpers::getKeywordName(ElaboratedTypeKeyword Keyword) {
3469 switch (Keyword) {
3470 case ElaboratedTypeKeyword::None:
3471 return {};
3472 case ElaboratedTypeKeyword::Typename:
3473 return "typename";
3474 case ElaboratedTypeKeyword::Class:
3475 return "class";
3476 case ElaboratedTypeKeyword::Struct:
3477 return "struct";
3478 case ElaboratedTypeKeyword::Interface:
3479 return "__interface";
3480 case ElaboratedTypeKeyword::Union:
3481 return "union";
3482 case ElaboratedTypeKeyword::Enum:
3483 return "enum";
3484 }
3485
3486 llvm_unreachable("Unknown elaborated type keyword.");
3487}
3488
3489bool Type::isElaboratedTypeSpecifier() const {
3490 ElaboratedTypeKeyword Keyword;
3491 if (const auto *TST = dyn_cast<TemplateSpecializationType>(Val: this))
3492 Keyword = TST->getKeyword();
3493 else if (const auto *DepName = dyn_cast<DependentNameType>(Val: this))
3494 Keyword = DepName->getKeyword();
3495 else if (const auto *T = dyn_cast<TagType>(Val: this))
3496 Keyword = T->getKeyword();
3497 else if (const auto *T = dyn_cast<TypedefType>(Val: this))
3498 Keyword = T->getKeyword();
3499 else if (const auto *T = dyn_cast<UnresolvedUsingType>(Val: this))
3500 Keyword = T->getKeyword();
3501 else if (const auto *T = dyn_cast<UsingType>(Val: this))
3502 Keyword = T->getKeyword();
3503 else
3504 return false;
3505
3506 return TypeWithKeyword::KeywordIsTagTypeKind(Keyword);
3507}
3508
3509const char *Type::getTypeClassName() const {
3510 switch (TypeBits.TC) {
3511#define ABSTRACT_TYPE(Derived, Base)
3512#define TYPE(Derived, Base) \
3513 case Derived: \
3514 return #Derived;
3515#include "clang/AST/TypeNodes.inc"
3516 }
3517
3518 llvm_unreachable("Invalid type class.");
3519}
3520
3521StringRef BuiltinType::getName(const PrintingPolicy &Policy) const {
3522 switch (getKind()) {
3523 case Void:
3524 return "void";
3525 case Bool:
3526 return Policy.Bool ? "bool" : "_Bool";
3527 case Char_S:
3528 return "char";
3529 case Char_U:
3530 return "char";
3531 case SChar:
3532 return "signed char";
3533 case Short:
3534 return "short";
3535 case Int:
3536 return "int";
3537 case Long:
3538 return "long";
3539 case LongLong:
3540 return "long long";
3541 case Int128:
3542 return "__int128";
3543 case UChar:
3544 return "unsigned char";
3545 case UShort:
3546 return "unsigned short";
3547 case UInt:
3548 return "unsigned int";
3549 case ULong:
3550 return "unsigned long";
3551 case ULongLong:
3552 return "unsigned long long";
3553 case UInt128:
3554 return "unsigned __int128";
3555 case Half:
3556 return Policy.Half ? "half" : "__fp16";
3557 case BFloat16:
3558 return "__bf16";
3559 case Float:
3560 return "float";
3561 case Double:
3562 return "double";
3563 case LongDouble:
3564 return "long double";
3565 case ShortAccum:
3566 return "short _Accum";
3567 case Accum:
3568 return "_Accum";
3569 case LongAccum:
3570 return "long _Accum";
3571 case UShortAccum:
3572 return "unsigned short _Accum";
3573 case UAccum:
3574 return "unsigned _Accum";
3575 case ULongAccum:
3576 return "unsigned long _Accum";
3577 case BuiltinType::ShortFract:
3578 return "short _Fract";
3579 case BuiltinType::Fract:
3580 return "_Fract";
3581 case BuiltinType::LongFract:
3582 return "long _Fract";
3583 case BuiltinType::UShortFract:
3584 return "unsigned short _Fract";
3585 case BuiltinType::UFract:
3586 return "unsigned _Fract";
3587 case BuiltinType::ULongFract:
3588 return "unsigned long _Fract";
3589 case BuiltinType::SatShortAccum:
3590 return "_Sat short _Accum";
3591 case BuiltinType::SatAccum:
3592 return "_Sat _Accum";
3593 case BuiltinType::SatLongAccum:
3594 return "_Sat long _Accum";
3595 case BuiltinType::SatUShortAccum:
3596 return "_Sat unsigned short _Accum";
3597 case BuiltinType::SatUAccum:
3598 return "_Sat unsigned _Accum";
3599 case BuiltinType::SatULongAccum:
3600 return "_Sat unsigned long _Accum";
3601 case BuiltinType::SatShortFract:
3602 return "_Sat short _Fract";
3603 case BuiltinType::SatFract:
3604 return "_Sat _Fract";
3605 case BuiltinType::SatLongFract:
3606 return "_Sat long _Fract";
3607 case BuiltinType::SatUShortFract:
3608 return "_Sat unsigned short _Fract";
3609 case BuiltinType::SatUFract:
3610 return "_Sat unsigned _Fract";
3611 case BuiltinType::SatULongFract:
3612 return "_Sat unsigned long _Fract";
3613 case Float16:
3614 return "_Float16";
3615 case Float128:
3616 return "__float128";
3617 case Ibm128:
3618 return "__ibm128";
3619 case WChar_S:
3620 case WChar_U:
3621 return Policy.MSWChar ? "__wchar_t" : "wchar_t";
3622 case Char8:
3623 return "char8_t";
3624 case Char16:
3625 return "char16_t";
3626 case Char32:
3627 return "char32_t";
3628 case NullPtr:
3629 return Policy.NullptrTypeInNamespace ? "std::nullptr_t" : "nullptr_t";
3630 case Overload:
3631 return "<overloaded function type>";
3632 case BoundMember:
3633 return "<bound member function type>";
3634 case UnresolvedTemplate:
3635 return "<unresolved template type>";
3636 case PseudoObject:
3637 return "<pseudo-object type>";
3638 case Dependent:
3639 return "<dependent type>";
3640 case UnknownAny:
3641 return "<unknown type>";
3642 case ARCUnbridgedCast:
3643 return "<ARC unbridged cast type>";
3644 case BuiltinFn:
3645 return "<builtin fn type>";
3646 case ObjCId:
3647 return "id";
3648 case ObjCClass:
3649 return "Class";
3650 case ObjCSel:
3651 return "SEL";
3652#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
3653 case Id: \
3654 return "__" #Access " " #ImgType "_t";
3655#include "clang/Basic/OpenCLImageTypes.def"
3656 case OCLSampler:
3657 return "sampler_t";
3658 case OCLEvent:
3659 return "event_t";
3660 case OCLClkEvent:
3661 return "clk_event_t";
3662 case OCLQueue:
3663 return "queue_t";
3664 case OCLReserveID:
3665 return "reserve_id_t";
3666 case IncompleteMatrixIdx:
3667 return "<incomplete matrix index type>";
3668 case ArraySection:
3669 return "<array section type>";
3670 case OMPArrayShaping:
3671 return "<OpenMP array shaping type>";
3672 case OMPIterator:
3673 return "<OpenMP iterator type>";
3674#define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
3675 case Id: \
3676 return #ExtType;
3677#include "clang/Basic/OpenCLExtensionTypes.def"
3678#define SVE_TYPE(Name, Id, SingletonId) \
3679 case Id: \
3680 return #Name;
3681#include "clang/Basic/AArch64ACLETypes.def"
3682#define PPC_VECTOR_TYPE(Name, Id, Size) \
3683 case Id: \
3684 return #Name;
3685#include "clang/Basic/PPCTypes.def"
3686#define RVV_TYPE(Name, Id, SingletonId) \
3687 case Id: \
3688 return Name;
3689#include "clang/Basic/RISCVVTypes.def"
3690#define WASM_TYPE(Name, Id, SingletonId) \
3691 case Id: \
3692 return Name;
3693#include "clang/Basic/WebAssemblyReferenceTypes.def"
3694#define AMDGPU_TYPE(Name, Id, SingletonId, Width, Align) \
3695 case Id: \
3696 return Name;
3697#include "clang/Basic/AMDGPUTypes.def"
3698#define HLSL_INTANGIBLE_TYPE(Name, Id, SingletonId) \
3699 case Id: \
3700 return #Name;
3701#include "clang/Basic/HLSLIntangibleTypes.def"
3702#define SPIRV_TYPE(Name, Id, SingletonId) \
3703 case Id: \
3704 return Name;
3705#include "clang/Basic/SPIRVTypes.def"
3706 }
3707
3708 llvm_unreachable("Invalid builtin type.");
3709}
3710
3711QualType QualType::getNonPackExpansionType() const {
3712 // We never wrap type sugar around a PackExpansionType.
3713 if (auto *PET = dyn_cast<PackExpansionType>(Val: getTypePtr()))
3714 return PET->getPattern();
3715 return *this;
3716}
3717
3718QualType QualType::getNonLValueExprType(const ASTContext &Context) const {
3719 if (const auto *RefType = getTypePtr()->getAs<ReferenceType>())
3720 return RefType->getPointeeType();
3721
3722 // C++0x [basic.lval]:
3723 // Class prvalues can have cv-qualified types; non-class prvalues always
3724 // have cv-unqualified types.
3725 //
3726 // See also C99 6.3.2.1p2.
3727 if (!Context.getLangOpts().CPlusPlus ||
3728 (!getTypePtr()->isDependentType() && !getTypePtr()->isRecordType()))
3729 return getUnqualifiedType();
3730
3731 return *this;
3732}
3733
3734bool FunctionType::getCFIUncheckedCalleeAttr() const {
3735 if (const auto *FPT = getAs<FunctionProtoType>())
3736 return FPT->hasCFIUncheckedCallee();
3737 return false;
3738}
3739
3740StringRef FunctionType::getNameForCallConv(CallingConv CC) {
3741 switch (CC) {
3742 case CC_C:
3743 return "cdecl";
3744 case CC_X86StdCall:
3745 return "stdcall";
3746 case CC_X86FastCall:
3747 return "fastcall";
3748 case CC_X86ThisCall:
3749 return "thiscall";
3750 case CC_X86Pascal:
3751 return "pascal";
3752 case CC_X86VectorCall:
3753 return "vectorcall";
3754 case CC_Win64:
3755 return "ms_abi";
3756 case CC_X86_64SysV:
3757 return "sysv_abi";
3758 case CC_X86RegCall:
3759 return "regcall";
3760 case CC_AAPCS:
3761 return "aapcs";
3762 case CC_AAPCS_VFP:
3763 return "aapcs-vfp";
3764 case CC_AArch64VectorCall:
3765 return "aarch64_vector_pcs";
3766 case CC_AArch64SVEPCS:
3767 return "aarch64_sve_pcs";
3768 case CC_IntelOclBicc:
3769 return "intel_ocl_bicc";
3770 case CC_DeviceKernel:
3771 return "device_kernel";
3772 case CC_Swift:
3773 return "swiftcall";
3774 case CC_SwiftAsync:
3775 return "swiftasynccall";
3776 case CC_PreserveMost:
3777 return "preserve_most";
3778 case CC_PreserveAll:
3779 return "preserve_all";
3780 case CC_M68kRTD:
3781 return "m68k_rtd";
3782 case CC_PreserveNone:
3783 return "preserve_none";
3784 // clang-format off
3785 case CC_RISCVVectorCall: return "riscv_vector_cc";
3786#define CC_VLS_CASE(ABI_VLEN) \
3787 case CC_RISCVVLSCall_##ABI_VLEN: return "riscv_vls_cc(" #ABI_VLEN ")";
3788 CC_VLS_CASE(32)
3789 CC_VLS_CASE(64)
3790 CC_VLS_CASE(128)
3791 CC_VLS_CASE(256)
3792 CC_VLS_CASE(512)
3793 CC_VLS_CASE(1024)
3794 CC_VLS_CASE(2048)
3795 CC_VLS_CASE(4096)
3796 CC_VLS_CASE(8192)
3797 CC_VLS_CASE(16384)
3798 CC_VLS_CASE(32768)
3799 CC_VLS_CASE(65536)
3800#undef CC_VLS_CASE
3801 // clang-format on
3802 }
3803
3804 llvm_unreachable("Invalid calling convention.");
3805}
3806
3807void FunctionProtoType::ExceptionSpecInfo::instantiate() {
3808 assert(Type == EST_Uninstantiated);
3809 NoexceptExpr =
3810 cast<FunctionProtoType>(Val: SourceTemplate->getType())->getNoexceptExpr();
3811 Type = EST_DependentNoexcept;
3812}
3813
3814FunctionProtoType::FunctionProtoType(QualType result, ArrayRef<QualType> params,
3815 QualType canonical,
3816 const ExtProtoInfo &epi)
3817 : FunctionType(FunctionProto, result, canonical, result->getDependence(),
3818 epi.ExtInfo) {
3819 FunctionTypeBits.FastTypeQuals = epi.TypeQuals.getFastQualifiers();
3820 FunctionTypeBits.RefQualifier = epi.RefQualifier;
3821 FunctionTypeBits.NumParams = params.size();
3822 assert(getNumParams() == params.size() && "NumParams overflow!");
3823 FunctionTypeBits.ExceptionSpecType = epi.ExceptionSpec.Type;
3824 FunctionTypeBits.HasExtParameterInfos = !!epi.ExtParameterInfos;
3825 FunctionTypeBits.Variadic = epi.Variadic;
3826 FunctionTypeBits.HasTrailingReturn = epi.HasTrailingReturn;
3827 FunctionTypeBits.CFIUncheckedCallee = epi.CFIUncheckedCallee;
3828
3829 if (epi.requiresFunctionProtoTypeExtraBitfields()) {
3830 FunctionTypeBits.HasExtraBitfields = true;
3831 auto &ExtraBits = *getTrailingObjects<FunctionTypeExtraBitfields>();
3832 ExtraBits = FunctionTypeExtraBitfields();
3833 } else {
3834 FunctionTypeBits.HasExtraBitfields = false;
3835 }
3836
3837 // Propagate any extra attribute information.
3838 if (epi.requiresFunctionProtoTypeExtraAttributeInfo()) {
3839 auto &ExtraAttrInfo = *getTrailingObjects<FunctionTypeExtraAttributeInfo>();
3840 ExtraAttrInfo.CFISalt = epi.ExtraAttributeInfo.CFISalt;
3841
3842 // Also set the bit in FunctionTypeExtraBitfields.
3843 auto &ExtraBits = *getTrailingObjects<FunctionTypeExtraBitfields>();
3844 ExtraBits.HasExtraAttributeInfo = true;
3845 }
3846
3847 if (epi.requiresFunctionProtoTypeArmAttributes()) {
3848 auto &ArmTypeAttrs = *getTrailingObjects<FunctionTypeArmAttributes>();
3849 ArmTypeAttrs = FunctionTypeArmAttributes();
3850
3851 // Also set the bit in FunctionTypeExtraBitfields
3852 auto &ExtraBits = *getTrailingObjects<FunctionTypeExtraBitfields>();
3853 ExtraBits.HasArmTypeAttributes = true;
3854 }
3855
3856 // Fill in the trailing argument array.
3857 auto *argSlot = getTrailingObjects<QualType>();
3858 for (unsigned i = 0; i != getNumParams(); ++i) {
3859 addDependence(D: params[i]->getDependence() &
3860 ~TypeDependence::VariablyModified);
3861 argSlot[i] = params[i];
3862 }
3863
3864 // Propagate the SME ACLE attributes.
3865 if (epi.AArch64SMEAttributes != SME_NormalFunction) {
3866 auto &ArmTypeAttrs = *getTrailingObjects<FunctionTypeArmAttributes>();
3867 assert(epi.AArch64SMEAttributes <= SME_AttributeMask &&
3868 "Not enough bits to encode SME attributes");
3869 ArmTypeAttrs.AArch64SMEAttributes = epi.AArch64SMEAttributes;
3870 }
3871
3872 // Fill in the exception type array if present.
3873 if (getExceptionSpecType() == EST_Dynamic) {
3874 auto &ExtraBits = *getTrailingObjects<FunctionTypeExtraBitfields>();
3875 size_t NumExceptions = epi.ExceptionSpec.Exceptions.size();
3876 assert(NumExceptions <= 1023 && "Not enough bits to encode exceptions");
3877 ExtraBits.NumExceptionType = NumExceptions;
3878
3879 assert(hasExtraBitfields() && "missing trailing extra bitfields!");
3880 auto *exnSlot =
3881 reinterpret_cast<QualType *>(getTrailingObjects<ExceptionType>());
3882 unsigned I = 0;
3883 for (QualType ExceptionType : epi.ExceptionSpec.Exceptions) {
3884 // Note that, before C++17, a dependent exception specification does
3885 // *not* make a type dependent; it's not even part of the C++ type
3886 // system.
3887 addDependence(
3888 D: ExceptionType->getDependence() &
3889 (TypeDependence::Instantiation | TypeDependence::UnexpandedPack));
3890
3891 exnSlot[I++] = ExceptionType;
3892 }
3893 }
3894 // Fill in the Expr * in the exception specification if present.
3895 else if (isComputedNoexcept(ESpecType: getExceptionSpecType())) {
3896 assert(epi.ExceptionSpec.NoexceptExpr && "computed noexcept with no expr");
3897 assert((getExceptionSpecType() == EST_DependentNoexcept) ==
3898 epi.ExceptionSpec.NoexceptExpr->isValueDependent());
3899
3900 // Store the noexcept expression and context.
3901 *getTrailingObjects<Expr *>() = epi.ExceptionSpec.NoexceptExpr;
3902
3903 addDependence(
3904 D: toTypeDependence(D: epi.ExceptionSpec.NoexceptExpr->getDependence()) &
3905 (TypeDependence::Instantiation | TypeDependence::UnexpandedPack));
3906 }
3907 // Fill in the FunctionDecl * in the exception specification if present.
3908 else if (getExceptionSpecType() == EST_Uninstantiated) {
3909 // Store the function decl from which we will resolve our
3910 // exception specification.
3911 auto **slot = getTrailingObjects<FunctionDecl *>();
3912 slot[0] = epi.ExceptionSpec.SourceDecl;
3913 slot[1] = epi.ExceptionSpec.SourceTemplate;
3914 // This exception specification doesn't make the type dependent, because
3915 // it's not instantiated as part of instantiating the type.
3916 } else if (getExceptionSpecType() == EST_Unevaluated) {
3917 // Store the function decl from which we will resolve our
3918 // exception specification.
3919 auto **slot = getTrailingObjects<FunctionDecl *>();
3920 slot[0] = epi.ExceptionSpec.SourceDecl;
3921 }
3922
3923 // If this is a canonical type, and its exception specification is dependent,
3924 // then it's a dependent type. This only happens in C++17 onwards.
3925 if (isCanonicalUnqualified()) {
3926 if (getExceptionSpecType() == EST_Dynamic ||
3927 getExceptionSpecType() == EST_DependentNoexcept) {
3928 assert(hasDependentExceptionSpec() && "type should not be canonical");
3929 addDependence(D: TypeDependence::DependentInstantiation);
3930 }
3931 } else if (getCanonicalTypeInternal()->isDependentType()) {
3932 // Ask our canonical type whether our exception specification was dependent.
3933 addDependence(D: TypeDependence::DependentInstantiation);
3934 }
3935
3936 // Fill in the extra parameter info if present.
3937 if (epi.ExtParameterInfos) {
3938 auto *extParamInfos = getTrailingObjects<ExtParameterInfo>();
3939 for (unsigned i = 0; i != getNumParams(); ++i)
3940 extParamInfos[i] = epi.ExtParameterInfos[i];
3941 }
3942
3943 if (epi.TypeQuals.hasNonFastQualifiers()) {
3944 FunctionTypeBits.HasExtQuals = 1;
3945 *getTrailingObjects<Qualifiers>() = epi.TypeQuals;
3946 } else {
3947 FunctionTypeBits.HasExtQuals = 0;
3948 }
3949
3950 // Fill in the Ellipsis location info if present.
3951 if (epi.Variadic) {
3952 auto &EllipsisLoc = *getTrailingObjects<SourceLocation>();
3953 EllipsisLoc = epi.EllipsisLoc;
3954 }
3955
3956 if (!epi.FunctionEffects.empty()) {
3957 auto &ExtraBits = *getTrailingObjects<FunctionTypeExtraBitfields>();
3958 size_t EffectsCount = epi.FunctionEffects.size();
3959 ExtraBits.NumFunctionEffects = EffectsCount;
3960 assert(ExtraBits.NumFunctionEffects == EffectsCount &&
3961 "effect bitfield overflow");
3962
3963 ArrayRef<FunctionEffect> SrcFX = epi.FunctionEffects.effects();
3964 auto *DestFX = getTrailingObjects<FunctionEffect>();
3965 llvm::uninitialized_copy(Src&: SrcFX, Dst: DestFX);
3966
3967 ArrayRef<EffectConditionExpr> SrcConds = epi.FunctionEffects.conditions();
3968 if (!SrcConds.empty()) {
3969 ExtraBits.EffectsHaveConditions = true;
3970 auto *DestConds = getTrailingObjects<EffectConditionExpr>();
3971 llvm::uninitialized_copy(Src&: SrcConds, Dst: DestConds);
3972 assert(llvm::any_of(SrcConds,
3973 [](const EffectConditionExpr &EC) {
3974 if (const Expr *E = EC.getCondition())
3975 return E->isTypeDependent() ||
3976 E->isValueDependent();
3977 return false;
3978 }) &&
3979 "expected a dependent expression among the conditions");
3980 addDependence(D: TypeDependence::DependentInstantiation);
3981 }
3982 }
3983}
3984
3985bool FunctionProtoType::hasDependentExceptionSpec() const {
3986 if (Expr *NE = getNoexceptExpr())
3987 return NE->isValueDependent();
3988 for (QualType ET : exceptions())
3989 // A pack expansion with a non-dependent pattern is still dependent,
3990 // because we don't know whether the pattern is in the exception spec
3991 // or not (that depends on whether the pack has 0 expansions).
3992 if (ET->isDependentType() || ET->getAs<PackExpansionType>())
3993 return true;
3994 return false;
3995}
3996
3997bool FunctionProtoType::hasInstantiationDependentExceptionSpec() const {
3998 if (Expr *NE = getNoexceptExpr())
3999 return NE->isInstantiationDependent();
4000 for (QualType ET : exceptions())
4001 if (ET->isInstantiationDependentType())
4002 return true;
4003 return false;
4004}
4005
4006CanThrowResult FunctionProtoType::canThrow() const {
4007 switch (getExceptionSpecType()) {
4008 case EST_Unparsed:
4009 case EST_Unevaluated:
4010 llvm_unreachable("should not call this with unresolved exception specs");
4011
4012 case EST_DynamicNone:
4013 case EST_BasicNoexcept:
4014 case EST_NoexceptTrue:
4015 case EST_NoThrow:
4016 return CT_Cannot;
4017
4018 case EST_None:
4019 case EST_MSAny:
4020 case EST_NoexceptFalse:
4021 return CT_Can;
4022
4023 case EST_Dynamic:
4024 // A dynamic exception specification is throwing unless every exception
4025 // type is an (unexpanded) pack expansion type.
4026 for (unsigned I = 0; I != getNumExceptions(); ++I)
4027 if (!getExceptionType(i: I)->getAs<PackExpansionType>())
4028 return CT_Can;
4029 return CT_Dependent;
4030
4031 case EST_Uninstantiated:
4032 case EST_DependentNoexcept:
4033 return CT_Dependent;
4034 }
4035
4036 llvm_unreachable("unexpected exception specification kind");
4037}
4038
4039bool FunctionProtoType::isTemplateVariadic() const {
4040 for (unsigned ArgIdx = getNumParams(); ArgIdx; --ArgIdx)
4041 if (isa<PackExpansionType>(Val: getParamType(i: ArgIdx - 1)))
4042 return true;
4043
4044 return false;
4045}
4046
4047void FunctionProtoType::Profile(llvm::FoldingSetNodeID &ID, QualType Result,
4048 const QualType *ArgTys, unsigned NumParams,
4049 const ExtProtoInfo &epi,
4050 const ASTContext &Context, bool Canonical) {
4051 // We have to be careful not to get ambiguous profile encodings.
4052 // Note that valid type pointers are never ambiguous with anything else.
4053 //
4054 // The encoding grammar begins:
4055 // type type* bool int bool
4056 // If that final bool is true, then there is a section for the EH spec:
4057 // bool type*
4058 // This is followed by an optional "consumed argument" section of the
4059 // same length as the first type sequence:
4060 // bool*
4061 // This is followed by the ext info:
4062 // int
4063 // Finally we have a trailing return type flag (bool)
4064 // combined with AArch64 SME Attributes and extra attribute info, to save
4065 // space:
4066 // int
4067 // combined with any FunctionEffects
4068 //
4069 // There is no ambiguity between the consumed arguments and an empty EH
4070 // spec because of the leading 'bool' which unambiguously indicates
4071 // whether the following bool is the EH spec or part of the arguments.
4072
4073 ID.AddPointer(Ptr: Result.getAsOpaquePtr());
4074 for (unsigned i = 0; i != NumParams; ++i)
4075 ID.AddPointer(Ptr: ArgTys[i].getAsOpaquePtr());
4076 // This method is relatively performance sensitive, so as a performance
4077 // shortcut, use one AddInteger call instead of four for the next four
4078 // fields.
4079 assert(!(unsigned(epi.Variadic) & ~1) && !(unsigned(epi.RefQualifier) & ~3) &&
4080 !(unsigned(epi.ExceptionSpec.Type) & ~15) &&
4081 "Values larger than expected.");
4082 ID.AddInteger(I: unsigned(epi.Variadic) + (epi.RefQualifier << 1) +
4083 (epi.ExceptionSpec.Type << 3));
4084 ID.Add(x: epi.TypeQuals);
4085 if (epi.ExceptionSpec.Type == EST_Dynamic) {
4086 for (QualType Ex : epi.ExceptionSpec.Exceptions)
4087 ID.AddPointer(Ptr: Ex.getAsOpaquePtr());
4088 } else if (isComputedNoexcept(ESpecType: epi.ExceptionSpec.Type)) {
4089 epi.ExceptionSpec.NoexceptExpr->Profile(ID, Context, Canonical);
4090 } else if (epi.ExceptionSpec.Type == EST_Uninstantiated ||
4091 epi.ExceptionSpec.Type == EST_Unevaluated) {
4092 ID.AddPointer(Ptr: epi.ExceptionSpec.SourceDecl->getCanonicalDecl());
4093 }
4094 if (epi.ExtParameterInfos) {
4095 for (unsigned i = 0; i != NumParams; ++i)
4096 ID.AddInteger(I: epi.ExtParameterInfos[i].getOpaqueValue());
4097 }
4098
4099 epi.ExtInfo.Profile(ID);
4100 epi.ExtraAttributeInfo.Profile(ID);
4101
4102 unsigned EffectCount = epi.FunctionEffects.size();
4103 bool HasConds = !epi.FunctionEffects.Conditions.empty();
4104
4105 ID.AddInteger(I: (EffectCount << 3) | (HasConds << 2) |
4106 (epi.AArch64SMEAttributes << 1) | epi.HasTrailingReturn);
4107 ID.AddInteger(I: epi.CFIUncheckedCallee);
4108
4109 for (unsigned Idx = 0; Idx != EffectCount; ++Idx) {
4110 ID.AddInteger(I: epi.FunctionEffects.Effects[Idx].toOpaqueInt32());
4111 if (HasConds)
4112 ID.AddPointer(Ptr: epi.FunctionEffects.Conditions[Idx].getCondition());
4113 }
4114}
4115
4116void FunctionProtoType::Profile(llvm::FoldingSetNodeID &ID,
4117 const ASTContext &Ctx) {
4118 Profile(ID, Result: getReturnType(), ArgTys: param_type_begin(), NumParams: getNumParams(),
4119 epi: getExtProtoInfo(), Context: Ctx, Canonical: isCanonicalUnqualified());
4120}
4121
4122TypeCoupledDeclRefInfo::TypeCoupledDeclRefInfo(ValueDecl *D, bool Deref)
4123 : Data(D, Deref << DerefShift) {}
4124
4125bool TypeCoupledDeclRefInfo::isDeref() const {
4126 return Data.getInt() & DerefMask;
4127}
4128ValueDecl *TypeCoupledDeclRefInfo::getDecl() const { return Data.getPointer(); }
4129unsigned TypeCoupledDeclRefInfo::getInt() const { return Data.getInt(); }
4130void *TypeCoupledDeclRefInfo::getOpaqueValue() const {
4131 return Data.getOpaqueValue();
4132}
4133bool TypeCoupledDeclRefInfo::operator==(
4134 const TypeCoupledDeclRefInfo &Other) const {
4135 return getOpaqueValue() == Other.getOpaqueValue();
4136}
4137void TypeCoupledDeclRefInfo::setFromOpaqueValue(void *V) {
4138 Data.setFromOpaqueValue(V);
4139}
4140
4141OverflowBehaviorType::OverflowBehaviorType(
4142 QualType Canon, QualType Underlying,
4143 OverflowBehaviorType::OverflowBehaviorKind Kind)
4144 : Type(OverflowBehavior, Canon, Underlying->getDependence()),
4145 UnderlyingType(Underlying), BehaviorKind(Kind) {}
4146
4147BoundsAttributedType::BoundsAttributedType(TypeClass TC, QualType Wrapped,
4148 QualType Canon)
4149 : Type(TC, Canon, Wrapped->getDependence()), WrappedTy(Wrapped) {}
4150
4151CountAttributedType::CountAttributedType(
4152 QualType Wrapped, QualType Canon, Expr *CountExpr, bool CountInBytes,
4153 bool OrNull, ArrayRef<TypeCoupledDeclRefInfo> CoupledDecls)
4154 : BoundsAttributedType(CountAttributed, Wrapped, Canon),
4155 CountExpr(CountExpr) {
4156 CountAttributedTypeBits.NumCoupledDecls = CoupledDecls.size();
4157 CountAttributedTypeBits.CountInBytes = CountInBytes;
4158 CountAttributedTypeBits.OrNull = OrNull;
4159 auto *DeclSlot = getTrailingObjects();
4160 llvm::copy(Range&: CoupledDecls, Out: DeclSlot);
4161 Decls = llvm::ArrayRef(DeclSlot, CoupledDecls.size());
4162}
4163
4164StringRef CountAttributedType::getAttributeName(bool WithMacroPrefix) const {
4165// TODO: This method isn't really ideal because it doesn't return the spelling
4166// of the attribute that was used in the user's code. This method is used for
4167// diagnostics so the fact it doesn't use the spelling of the attribute in
4168// the user's code could be confusing (#113585).
4169#define ENUMERATE_ATTRS(PREFIX) \
4170 do { \
4171 if (isCountInBytes()) { \
4172 if (isOrNull()) \
4173 return PREFIX "sized_by_or_null"; \
4174 return PREFIX "sized_by"; \
4175 } \
4176 if (isOrNull()) \
4177 return PREFIX "counted_by_or_null"; \
4178 return PREFIX "counted_by"; \
4179 } while (0)
4180
4181 if (WithMacroPrefix)
4182 ENUMERATE_ATTRS("__");
4183 else
4184 ENUMERATE_ATTRS("");
4185
4186#undef ENUMERATE_ATTRS
4187}
4188
4189TypedefType::TypedefType(TypeClass TC, ElaboratedTypeKeyword Keyword,
4190 NestedNameSpecifier Qualifier,
4191 const TypedefNameDecl *D, QualType UnderlyingType,
4192 bool HasTypeDifferentFromDecl)
4193 : TypeWithKeyword(
4194 Keyword, TC, UnderlyingType.getCanonicalType(),
4195 toSemanticDependence(D: UnderlyingType->getDependence()) |
4196 (Qualifier
4197 ? toTypeDependence(D: Qualifier.getDependence() &
4198 ~NestedNameSpecifierDependence::Dependent)
4199 : TypeDependence{})),
4200 Decl(const_cast<TypedefNameDecl *>(D)) {
4201 if ((TypedefBits.hasQualifier = !!Qualifier))
4202 *getTrailingObjects<NestedNameSpecifier>() = Qualifier;
4203 if ((TypedefBits.hasTypeDifferentFromDecl = HasTypeDifferentFromDecl))
4204 *getTrailingObjects<QualType>() = UnderlyingType;
4205}
4206
4207QualType TypedefType::desugar() const {
4208 return typeMatchesDecl() ? Decl->getUnderlyingType()
4209 : *getTrailingObjects<QualType>();
4210}
4211
4212UnresolvedUsingType::UnresolvedUsingType(ElaboratedTypeKeyword Keyword,
4213 NestedNameSpecifier Qualifier,
4214 const UnresolvedUsingTypenameDecl *D,
4215 const Type *CanonicalType)
4216 : TypeWithKeyword(
4217 Keyword, UnresolvedUsing, QualType(CanonicalType, 0),
4218 TypeDependence::DependentInstantiation |
4219 (Qualifier
4220 ? toTypeDependence(D: Qualifier.getDependence() &
4221 ~NestedNameSpecifierDependence::Dependent)
4222 : TypeDependence{})),
4223 Decl(const_cast<UnresolvedUsingTypenameDecl *>(D)) {
4224 if ((UnresolvedUsingBits.hasQualifier = !!Qualifier))
4225 *getTrailingObjects<NestedNameSpecifier>() = Qualifier;
4226}
4227
4228UsingType::UsingType(ElaboratedTypeKeyword Keyword,
4229 NestedNameSpecifier Qualifier, const UsingShadowDecl *D,
4230 QualType UnderlyingType)
4231 : TypeWithKeyword(Keyword, Using, UnderlyingType.getCanonicalType(),
4232 toSemanticDependence(D: UnderlyingType->getDependence())),
4233 D(const_cast<UsingShadowDecl *>(D)), UnderlyingType(UnderlyingType) {
4234 if ((UsingBits.hasQualifier = !!Qualifier))
4235 *getTrailingObjects() = Qualifier;
4236}
4237
4238QualType MacroQualifiedType::desugar() const { return getUnderlyingType(); }
4239
4240QualType MacroQualifiedType::getModifiedType() const {
4241 // Step over MacroQualifiedTypes from the same macro to find the type
4242 // ultimately qualified by the macro qualifier.
4243 QualType Inner = cast<AttributedType>(Val: getUnderlyingType())->getModifiedType();
4244 while (auto *InnerMQT = dyn_cast<MacroQualifiedType>(Val&: Inner)) {
4245 if (InnerMQT->getMacroIdentifier() != getMacroIdentifier())
4246 break;
4247 Inner = InnerMQT->getModifiedType();
4248 }
4249 return Inner;
4250}
4251
4252TypeOfExprType::TypeOfExprType(const ASTContext &Context, Expr *E,
4253 TypeOfKind Kind, QualType Can)
4254 : Type(TypeOfExpr,
4255 // We have to protect against 'Can' being invalid through its
4256 // default argument.
4257 Kind == TypeOfKind::Unqualified && !Can.isNull()
4258 ? Context.getUnqualifiedArrayType(T: Can).getAtomicUnqualifiedType()
4259 : Can,
4260 toTypeDependence(D: E->getDependence()) |
4261 (E->getType()->getDependence() &
4262 TypeDependence::VariablyModified)),
4263 TOExpr(E), Context(Context) {
4264 TypeOfBits.Kind = static_cast<unsigned>(Kind);
4265}
4266
4267bool TypeOfExprType::isSugared() const { return !TOExpr->isTypeDependent(); }
4268
4269QualType TypeOfExprType::desugar() const {
4270 if (isSugared()) {
4271 QualType QT = getUnderlyingExpr()->getType();
4272 return getKind() == TypeOfKind::Unqualified
4273 ? Context.getUnqualifiedArrayType(T: QT).getAtomicUnqualifiedType()
4274 : QT;
4275 }
4276 return QualType(this, 0);
4277}
4278
4279void DependentTypeOfExprType::Profile(llvm::FoldingSetNodeID &ID,
4280 const ASTContext &Context, Expr *E,
4281 bool IsUnqual) {
4282 E->Profile(ID, Context, Canonical: true);
4283 ID.AddBoolean(B: IsUnqual);
4284}
4285
4286TypeOfType::TypeOfType(const ASTContext &Context, QualType T, QualType Can,
4287 TypeOfKind Kind)
4288 : Type(TypeOf,
4289 Kind == TypeOfKind::Unqualified
4290 ? Context.getUnqualifiedArrayType(T: Can).getAtomicUnqualifiedType()
4291 : Can,
4292 T->getDependence()),
4293 TOType(T), Context(Context) {
4294 TypeOfBits.Kind = static_cast<unsigned>(Kind);
4295}
4296
4297QualType TypeOfType::desugar() const {
4298 QualType QT = getUnmodifiedType();
4299 return getKind() == TypeOfKind::Unqualified
4300 ? Context.getUnqualifiedArrayType(T: QT).getAtomicUnqualifiedType()
4301 : QT;
4302}
4303
4304DecltypeType::DecltypeType(Expr *E, QualType underlyingType, QualType can)
4305 // C++11 [temp.type]p2: "If an expression e involves a template parameter,
4306 // decltype(e) denotes a unique dependent type." Hence a decltype type is
4307 // type-dependent even if its expression is only instantiation-dependent.
4308 : Type(Decltype, can,
4309 toTypeDependence(D: E->getDependence()) |
4310 (E->isInstantiationDependent() ? TypeDependence::Dependent
4311 : TypeDependence::None) |
4312 (E->getType()->getDependence() &
4313 TypeDependence::VariablyModified)),
4314 E(E), UnderlyingType(underlyingType) {}
4315
4316bool DecltypeType::isSugared() const { return !E->isInstantiationDependent(); }
4317
4318QualType DecltypeType::desugar() const {
4319 if (isSugared())
4320 return getUnderlyingType();
4321
4322 return QualType(this, 0);
4323}
4324
4325DependentDecltypeType::DependentDecltypeType(Expr *E)
4326 : DecltypeType(E, QualType()) {}
4327
4328void DependentDecltypeType::Profile(llvm::FoldingSetNodeID &ID,
4329 const ASTContext &Context, Expr *E) {
4330 E->Profile(ID, Context, Canonical: true);
4331}
4332
4333PackIndexingType::PackIndexingType(QualType Canonical, QualType Pattern,
4334 Expr *IndexExpr, bool FullySubstituted,
4335 ArrayRef<QualType> Expansions)
4336 : Type(PackIndexing, Canonical,
4337 computeDependence(Pattern, IndexExpr, Expansions)),
4338 Pattern(Pattern), IndexExpr(IndexExpr), Size(Expansions.size()),
4339 FullySubstituted(FullySubstituted) {
4340
4341 llvm::uninitialized_copy(Src&: Expansions, Dst: getTrailingObjects());
4342}
4343
4344UnsignedOrNone PackIndexingType::getSelectedIndex() const {
4345 if (isInstantiationDependentType())
4346 return std::nullopt;
4347 // Should only be not a constant for error recovery.
4348 ConstantExpr *CE = dyn_cast<ConstantExpr>(Val: getIndexExpr());
4349 if (!CE)
4350 return std::nullopt;
4351 auto Index = CE->getResultAsAPSInt();
4352 assert(Index.isNonNegative() && "Invalid index");
4353 return static_cast<unsigned>(Index.getExtValue());
4354}
4355
4356TypeDependence
4357PackIndexingType::computeDependence(QualType Pattern, Expr *IndexExpr,
4358 ArrayRef<QualType> Expansions) {
4359 TypeDependence IndexD = toTypeDependence(D: IndexExpr->getDependence());
4360
4361 TypeDependence TD = IndexD | (IndexExpr->isInstantiationDependent()
4362 ? TypeDependence::DependentInstantiation
4363 : TypeDependence::None);
4364 if (Expansions.empty())
4365 TD |= Pattern->getDependence() & TypeDependence::DependentInstantiation;
4366 else
4367 for (const QualType &T : Expansions)
4368 TD |= T->getDependence();
4369
4370 if (!(IndexD & TypeDependence::UnexpandedPack))
4371 TD &= ~TypeDependence::UnexpandedPack;
4372
4373 // If the pattern does not contain an unexpended pack,
4374 // the type is still dependent, and invalid
4375 if (!Pattern->containsUnexpandedParameterPack())
4376 TD |= TypeDependence::Error | TypeDependence::DependentInstantiation;
4377
4378 return TD;
4379}
4380
4381void PackIndexingType::Profile(llvm::FoldingSetNodeID &ID,
4382 const ASTContext &Context) {
4383 Profile(ID, Context, Pattern: getPattern(), E: getIndexExpr(), FullySubstituted: isFullySubstituted(),
4384 Expansions: getExpansions());
4385}
4386
4387void PackIndexingType::Profile(llvm::FoldingSetNodeID &ID,
4388 const ASTContext &Context, QualType Pattern,
4389 Expr *E, bool FullySubstituted,
4390 ArrayRef<QualType> Expansions) {
4391
4392 E->Profile(ID, Context, Canonical: true);
4393 ID.AddBoolean(B: FullySubstituted);
4394 if (!Expansions.empty()) {
4395 ID.AddInteger(I: Expansions.size());
4396 for (QualType T : Expansions)
4397 T.getCanonicalType().Profile(ID);
4398 } else {
4399 Pattern.Profile(ID);
4400 }
4401}
4402
4403UnaryTransformType::UnaryTransformType(QualType BaseType,
4404 QualType UnderlyingType, UTTKind UKind,
4405 QualType CanonicalType)
4406 : Type(UnaryTransform, CanonicalType, BaseType->getDependence()),
4407 BaseType(BaseType), UnderlyingType(UnderlyingType), UKind(UKind) {}
4408
4409TagType::TagType(TypeClass TC, ElaboratedTypeKeyword Keyword,
4410 NestedNameSpecifier Qualifier, const TagDecl *Tag,
4411 bool OwnsTag, bool ISInjected, const Type *CanonicalType)
4412 : TypeWithKeyword(
4413 Keyword, TC, QualType(CanonicalType, 0),
4414 (Tag->isDependentType() ? TypeDependence::DependentInstantiation
4415 : TypeDependence::None) |
4416 (Qualifier
4417 ? toTypeDependence(D: Qualifier.getDependence() &
4418 ~NestedNameSpecifierDependence::Dependent)
4419 : TypeDependence{})),
4420 decl(const_cast<TagDecl *>(Tag)) {
4421 if ((TagTypeBits.HasQualifier = !!Qualifier))
4422 getTrailingQualifier() = Qualifier;
4423 TagTypeBits.OwnsTag = !!OwnsTag;
4424 TagTypeBits.IsInjected = ISInjected;
4425}
4426
4427void *TagType::getTrailingPointer() const {
4428 switch (getTypeClass()) {
4429 case Type::Enum:
4430 return const_cast<EnumType *>(cast<EnumType>(Val: this) + 1);
4431 case Type::Record:
4432 return const_cast<RecordType *>(cast<RecordType>(Val: this) + 1);
4433 case Type::InjectedClassName:
4434 return const_cast<InjectedClassNameType *>(
4435 cast<InjectedClassNameType>(Val: this) + 1);
4436 default:
4437 llvm_unreachable("unexpected type class");
4438 }
4439}
4440
4441NestedNameSpecifier &TagType::getTrailingQualifier() const {
4442 assert(TagTypeBits.HasQualifier);
4443 return *reinterpret_cast<NestedNameSpecifier *>(llvm::alignAddr(
4444 Addr: getTrailingPointer(), Alignment: llvm::Align::Of<NestedNameSpecifier *>()));
4445}
4446
4447NestedNameSpecifier TagType::getQualifier() const {
4448 return TagTypeBits.HasQualifier ? getTrailingQualifier() : std::nullopt;
4449}
4450
4451ClassTemplateDecl *TagType::getTemplateDecl() const {
4452 auto *Decl = dyn_cast<CXXRecordDecl>(Val: decl);
4453 if (!Decl)
4454 return nullptr;
4455 if (auto *RD = dyn_cast<ClassTemplateSpecializationDecl>(Val: Decl))
4456 return RD->getSpecializedTemplate();
4457 return Decl->getDescribedClassTemplate();
4458}
4459
4460TemplateName TagType::getTemplateName(const ASTContext &Ctx) const {
4461 auto *TD = getTemplateDecl();
4462 if (!TD)
4463 return TemplateName();
4464 if (isCanonicalUnqualified())
4465 return TemplateName(TD);
4466 return Ctx.getQualifiedTemplateName(Qualifier: getQualifier(), /*TemplateKeyword=*/false,
4467 Template: TemplateName(TD));
4468}
4469
4470ArrayRef<TemplateArgument>
4471TagType::getTemplateArgs(const ASTContext &Ctx) const {
4472 auto *Decl = dyn_cast<CXXRecordDecl>(Val: decl);
4473 if (!Decl)
4474 return {};
4475
4476 if (auto *RD = dyn_cast<ClassTemplateSpecializationDecl>(Val: Decl))
4477 return RD->getTemplateArgs().asArray();
4478 if (ClassTemplateDecl *TD = Decl->getDescribedClassTemplate())
4479 return TD->getTemplateParameters()->getInjectedTemplateArgs(Context: Ctx);
4480 return {};
4481}
4482
4483bool RecordType::hasConstFields() const {
4484 std::vector<const RecordType *> RecordTypeList;
4485 RecordTypeList.push_back(x: this);
4486 unsigned NextToCheckIndex = 0;
4487
4488 while (RecordTypeList.size() > NextToCheckIndex) {
4489 for (FieldDecl *FD : RecordTypeList[NextToCheckIndex]
4490 ->getDecl()
4491 ->getDefinitionOrSelf()
4492 ->fields()) {
4493 QualType FieldTy = FD->getType();
4494 if (FieldTy.isConstQualified())
4495 return true;
4496 FieldTy = FieldTy.getCanonicalType();
4497 if (const auto *FieldRecTy = FieldTy->getAsCanonical<RecordType>()) {
4498 if (!llvm::is_contained(Range&: RecordTypeList, Element: FieldRecTy))
4499 RecordTypeList.push_back(x: FieldRecTy);
4500 }
4501 }
4502 ++NextToCheckIndex;
4503 }
4504 return false;
4505}
4506
4507InjectedClassNameType::InjectedClassNameType(ElaboratedTypeKeyword Keyword,
4508 NestedNameSpecifier Qualifier,
4509 const TagDecl *TD, bool IsInjected,
4510 const Type *CanonicalType)
4511 : TagType(TypeClass::InjectedClassName, Keyword, Qualifier, TD,
4512 /*OwnsTag=*/false, IsInjected, CanonicalType) {}
4513
4514AttributedType::AttributedType(QualType canon, const Attr *attr,
4515 QualType modified, QualType equivalent)
4516 : AttributedType(canon, attr->getKind(), attr, modified, equivalent) {}
4517
4518AttributedType::AttributedType(QualType canon, attr::Kind attrKind,
4519 const Attr *attr, QualType modified,
4520 QualType equivalent)
4521 : Type(Attributed, canon, equivalent->getDependence()), Attribute(attr),
4522 ModifiedType(modified), EquivalentType(equivalent) {
4523 AttributedTypeBits.AttrKind = attrKind;
4524 assert(!attr || attr->getKind() == attrKind);
4525}
4526
4527bool AttributedType::isQualifier() const {
4528 // FIXME: Generate this with TableGen.
4529 switch (getAttrKind()) {
4530 // These are type qualifiers in the traditional C sense: they annotate
4531 // something about a specific value/variable of a type. (They aren't
4532 // always part of the canonical type, though.)
4533 case attr::ObjCGC:
4534 case attr::ObjCOwnership:
4535 case attr::ObjCInertUnsafeUnretained:
4536 case attr::TypeNonNull:
4537 case attr::TypeNullable:
4538 case attr::TypeNullableResult:
4539 case attr::TypeNullUnspecified:
4540 case attr::LifetimeBound:
4541 case attr::AddressSpace:
4542 return true;
4543
4544 // All other type attributes aren't qualifiers; they rewrite the modified
4545 // type to be a semantically different type.
4546 default:
4547 return false;
4548 }
4549}
4550
4551bool AttributedType::isMSTypeSpec() const {
4552 // FIXME: Generate this with TableGen?
4553 switch (getAttrKind()) {
4554 default:
4555 return false;
4556 case attr::Ptr32:
4557 case attr::Ptr64:
4558 case attr::SPtr:
4559 case attr::UPtr:
4560 return true;
4561 }
4562 llvm_unreachable("invalid attr kind");
4563}
4564
4565bool AttributedType::isWebAssemblyFuncrefSpec() const {
4566 return getAttrKind() == attr::WebAssemblyFuncref;
4567}
4568
4569bool AttributedType::isCallingConv() const {
4570 // FIXME: Generate this with TableGen.
4571 switch (getAttrKind()) {
4572 default:
4573 return false;
4574 case attr::Pcs:
4575 case attr::CDecl:
4576 case attr::FastCall:
4577 case attr::StdCall:
4578 case attr::ThisCall:
4579 case attr::RegCall:
4580 case attr::SwiftCall:
4581 case attr::SwiftAsyncCall:
4582 case attr::VectorCall:
4583 case attr::AArch64VectorPcs:
4584 case attr::AArch64SVEPcs:
4585 case attr::DeviceKernel:
4586 case attr::Pascal:
4587 case attr::MSABI:
4588 case attr::SysVABI:
4589 case attr::IntelOclBicc:
4590 case attr::PreserveMost:
4591 case attr::PreserveAll:
4592 case attr::M68kRTD:
4593 case attr::PreserveNone:
4594 case attr::RISCVVectorCC:
4595 case attr::RISCVVLSCC:
4596 return true;
4597 }
4598 llvm_unreachable("invalid attr kind");
4599}
4600
4601IdentifierInfo *TemplateTypeParmType::getIdentifier() const {
4602 return isCanonicalUnqualified() ? nullptr : getDecl()->getIdentifier();
4603}
4604
4605SubstTemplateTypeParmType::SubstTemplateTypeParmType(QualType Replacement,
4606 Decl *AssociatedDecl,
4607 unsigned Index,
4608 UnsignedOrNone PackIndex,
4609 bool Final)
4610 : Type(SubstTemplateTypeParm, Replacement.getCanonicalType(),
4611 Replacement->getDependence()),
4612 AssociatedDecl(AssociatedDecl) {
4613 SubstTemplateTypeParmTypeBits.HasNonCanonicalUnderlyingType =
4614 Replacement != getCanonicalTypeInternal();
4615 if (SubstTemplateTypeParmTypeBits.HasNonCanonicalUnderlyingType)
4616 *getTrailingObjects() = Replacement;
4617
4618 SubstTemplateTypeParmTypeBits.Index = Index;
4619 SubstTemplateTypeParmTypeBits.Final = Final;
4620 SubstTemplateTypeParmTypeBits.PackIndex =
4621 PackIndex.toInternalRepresentation();
4622 assert(AssociatedDecl != nullptr);
4623}
4624
4625const TemplateTypeParmDecl *
4626SubstTemplateTypeParmType::getReplacedParameter() const {
4627 return cast<TemplateTypeParmDecl>(Val: std::get<0>(
4628 t: getReplacedTemplateParameter(D: getAssociatedDecl(), Index: getIndex())));
4629}
4630
4631void SubstTemplateTypeParmType::Profile(llvm::FoldingSetNodeID &ID,
4632 QualType Replacement,
4633 const Decl *AssociatedDecl,
4634 unsigned Index,
4635 UnsignedOrNone PackIndex, bool Final) {
4636 Replacement.Profile(ID);
4637 ID.AddPointer(Ptr: AssociatedDecl);
4638 ID.AddInteger(I: Index);
4639 ID.AddInteger(I: PackIndex.toInternalRepresentation());
4640 ID.AddBoolean(B: Final);
4641}
4642
4643SubstPackType::SubstPackType(TypeClass Derived, QualType Canon,
4644 const TemplateArgument &ArgPack)
4645 : Type(Derived, Canon,
4646 TypeDependence::DependentInstantiation |
4647 TypeDependence::UnexpandedPack),
4648 Arguments(ArgPack.pack_begin()) {
4649 assert(llvm::all_of(
4650 ArgPack.pack_elements(),
4651 [](auto &P) { return P.getKind() == TemplateArgument::Type; }) &&
4652 "non-type argument to SubstPackType?");
4653 SubstPackTypeBits.NumArgs = ArgPack.pack_size();
4654}
4655
4656TemplateArgument SubstPackType::getArgumentPack() const {
4657 return TemplateArgument(llvm::ArrayRef(Arguments, getNumArgs()));
4658}
4659
4660void SubstPackType::Profile(llvm::FoldingSetNodeID &ID) {
4661 Profile(ID, ArgPack: getArgumentPack());
4662}
4663
4664void SubstPackType::Profile(llvm::FoldingSetNodeID &ID,
4665 const TemplateArgument &ArgPack) {
4666 ID.AddInteger(I: ArgPack.pack_size());
4667 for (const auto &P : ArgPack.pack_elements())
4668 ID.AddPointer(Ptr: P.getAsType().getAsOpaquePtr());
4669}
4670
4671SubstTemplateTypeParmPackType::SubstTemplateTypeParmPackType(
4672 QualType Canon, Decl *AssociatedDecl, unsigned Index, bool Final,
4673 const TemplateArgument &ArgPack)
4674 : SubstPackType(SubstTemplateTypeParmPack, Canon, ArgPack),
4675 AssociatedDeclAndFinal(AssociatedDecl, Final) {
4676 assert(AssociatedDecl != nullptr);
4677
4678 SubstPackTypeBits.SubstTemplTypeParmPackIndex = Index;
4679 assert(getNumArgs() == ArgPack.pack_size() &&
4680 "Parent bitfields in SubstPackType were overwritten."
4681 "Check NumSubstPackTypeBits.");
4682}
4683
4684Decl *SubstTemplateTypeParmPackType::getAssociatedDecl() const {
4685 return AssociatedDeclAndFinal.getPointer();
4686}
4687
4688bool SubstTemplateTypeParmPackType::getFinal() const {
4689 return AssociatedDeclAndFinal.getInt();
4690}
4691
4692const TemplateTypeParmDecl *
4693SubstTemplateTypeParmPackType::getReplacedParameter() const {
4694 return cast<TemplateTypeParmDecl>(Val: std::get<0>(
4695 t: getReplacedTemplateParameter(D: getAssociatedDecl(), Index: getIndex())));
4696}
4697
4698IdentifierInfo *SubstTemplateTypeParmPackType::getIdentifier() const {
4699 return getReplacedParameter()->getIdentifier();
4700}
4701
4702void SubstTemplateTypeParmPackType::Profile(llvm::FoldingSetNodeID &ID) {
4703 Profile(ID, AssociatedDecl: getAssociatedDecl(), Index: getIndex(), Final: getFinal(), ArgPack: getArgumentPack());
4704}
4705
4706void SubstTemplateTypeParmPackType::Profile(llvm::FoldingSetNodeID &ID,
4707 const Decl *AssociatedDecl,
4708 unsigned Index, bool Final,
4709 const TemplateArgument &ArgPack) {
4710 ID.AddPointer(Ptr: AssociatedDecl);
4711 ID.AddInteger(I: Index);
4712 ID.AddBoolean(B: Final);
4713 SubstPackType::Profile(ID, ArgPack);
4714}
4715
4716SubstBuiltinTemplatePackType::SubstBuiltinTemplatePackType(
4717 QualType Canon, const TemplateArgument &ArgPack)
4718 : SubstPackType(SubstBuiltinTemplatePack, Canon, ArgPack) {}
4719
4720bool TemplateSpecializationType::anyDependentTemplateArguments(
4721 const TemplateArgumentListInfo &Args,
4722 ArrayRef<TemplateArgument> Converted) {
4723 return anyDependentTemplateArguments(Args: Args.arguments(), Converted);
4724}
4725
4726bool TemplateSpecializationType::anyDependentTemplateArguments(
4727 ArrayRef<TemplateArgumentLoc> Args, ArrayRef<TemplateArgument> Converted) {
4728 for (const TemplateArgument &Arg : Converted)
4729 if (Arg.isDependent())
4730 return true;
4731 return false;
4732}
4733
4734bool TemplateSpecializationType::anyInstantiationDependentTemplateArguments(
4735 ArrayRef<TemplateArgumentLoc> Args) {
4736 for (const TemplateArgumentLoc &ArgLoc : Args) {
4737 if (ArgLoc.getArgument().isInstantiationDependent())
4738 return true;
4739 }
4740 return false;
4741}
4742
4743static TypeDependence
4744getTemplateSpecializationTypeDependence(QualType Underlying, TemplateName T) {
4745 TypeDependence D = Underlying.isNull()
4746 ? TypeDependence::DependentInstantiation
4747 : toSemanticDependence(D: Underlying->getDependence());
4748 D |= toTypeDependence(D: T.getDependence()) & TypeDependence::UnexpandedPack;
4749 if (isPackProducingBuiltinTemplateName(N: T)) {
4750 if (Underlying.isNull()) // Dependent, will produce a pack on substitution.
4751 D |= TypeDependence::UnexpandedPack;
4752 else
4753 D |= (Underlying->getDependence() & TypeDependence::UnexpandedPack);
4754 }
4755 return D;
4756}
4757
4758TemplateSpecializationType::TemplateSpecializationType(
4759 ElaboratedTypeKeyword Keyword, TemplateName T, bool IsAlias,
4760 ArrayRef<TemplateArgument> Args, QualType Underlying)
4761 : TypeWithKeyword(Keyword, TemplateSpecialization,
4762 Underlying.isNull() ? QualType(this, 0)
4763 : Underlying.getCanonicalType(),
4764 getTemplateSpecializationTypeDependence(Underlying, T)),
4765 Template(T) {
4766 TemplateSpecializationTypeBits.NumArgs = Args.size();
4767 TemplateSpecializationTypeBits.TypeAlias = IsAlias;
4768
4769 auto *TemplateArgs =
4770 const_cast<TemplateArgument *>(template_arguments().data());
4771 for (const TemplateArgument &Arg : Args) {
4772 // Update instantiation-dependent, variably-modified, and error bits.
4773 // If the canonical type exists and is non-dependent, the template
4774 // specialization type can be non-dependent even if one of the type
4775 // arguments is. Given:
4776 // template<typename T> using U = int;
4777 // U<T> is always non-dependent, irrespective of the type T.
4778 // However, U<Ts> contains an unexpanded parameter pack, even though
4779 // its expansion (and thus its desugared type) doesn't.
4780 addDependence(D: toTypeDependence(D: Arg.getDependence()) &
4781 ~TypeDependence::Dependent);
4782 if (Arg.getKind() == TemplateArgument::Type)
4783 addDependence(D: Arg.getAsType()->getDependence() &
4784 TypeDependence::VariablyModified);
4785 new (TemplateArgs++) TemplateArgument(Arg);
4786 }
4787
4788 // Store the aliased type after the template arguments, if this is a type
4789 // alias template specialization.
4790 if (IsAlias)
4791 *reinterpret_cast<QualType *>(TemplateArgs) = Underlying;
4792}
4793
4794QualType TemplateSpecializationType::getAliasedType() const {
4795 assert(isTypeAlias() && "not a type alias template specialization");
4796 return *reinterpret_cast<const QualType *>(template_arguments().end());
4797}
4798
4799bool clang::TemplateSpecializationType::isSugared() const {
4800 return !isDependentType() || isCurrentInstantiation() || isTypeAlias() ||
4801 (isPackProducingBuiltinTemplateName(N: Template) &&
4802 isa<SubstBuiltinTemplatePackType>(Val: *getCanonicalTypeInternal()));
4803}
4804
4805void TemplateSpecializationType::Profile(llvm::FoldingSetNodeID &ID,
4806 const ASTContext &Ctx) {
4807 Profile(ID, Keyword: getKeyword(), T: Template, Args: template_arguments(),
4808 Underlying: isSugared() ? desugar() : QualType(), Context: Ctx);
4809}
4810
4811void TemplateSpecializationType::Profile(llvm::FoldingSetNodeID &ID,
4812 ElaboratedTypeKeyword Keyword,
4813 TemplateName T,
4814 ArrayRef<TemplateArgument> Args,
4815 QualType Underlying,
4816 const ASTContext &Context) {
4817 ID.AddInteger(I: llvm::to_underlying(E: Keyword));
4818 T.Profile(ID);
4819 Underlying.Profile(ID);
4820
4821 ID.AddInteger(I: Args.size());
4822 for (const TemplateArgument &Arg : Args)
4823 Arg.Profile(ID, Context);
4824}
4825
4826QualType QualifierCollector::apply(const ASTContext &Context,
4827 QualType QT) const {
4828 if (!hasNonFastQualifiers())
4829 return QT.withFastQualifiers(TQs: getFastQualifiers());
4830
4831 return Context.getQualifiedType(T: QT, Qs: *this);
4832}
4833
4834QualType QualifierCollector::apply(const ASTContext &Context,
4835 const Type *T) const {
4836 if (!hasNonFastQualifiers())
4837 return QualType(T, getFastQualifiers());
4838
4839 return Context.getQualifiedType(T, Qs: *this);
4840}
4841
4842void ObjCObjectTypeImpl::Profile(llvm::FoldingSetNodeID &ID, QualType BaseType,
4843 ArrayRef<QualType> typeArgs,
4844 ArrayRef<ObjCProtocolDecl *> protocols,
4845 bool isKindOf) {
4846 ID.AddPointer(Ptr: BaseType.getAsOpaquePtr());
4847 ID.AddInteger(I: typeArgs.size());
4848 for (auto typeArg : typeArgs)
4849 ID.AddPointer(Ptr: typeArg.getAsOpaquePtr());
4850 ID.AddInteger(I: protocols.size());
4851 for (auto *proto : protocols)
4852 ID.AddPointer(Ptr: proto);
4853 ID.AddBoolean(B: isKindOf);
4854}
4855
4856void ObjCObjectTypeImpl::Profile(llvm::FoldingSetNodeID &ID) {
4857 Profile(ID, BaseType: getBaseType(), typeArgs: getTypeArgsAsWritten(),
4858 protocols: llvm::ArrayRef(qual_begin(), getNumProtocols()),
4859 isKindOf: isKindOfTypeAsWritten());
4860}
4861
4862void ObjCTypeParamType::Profile(llvm::FoldingSetNodeID &ID,
4863 const ObjCTypeParamDecl *OTPDecl,
4864 QualType CanonicalType,
4865 ArrayRef<ObjCProtocolDecl *> protocols) {
4866 ID.AddPointer(Ptr: OTPDecl);
4867 ID.AddPointer(Ptr: CanonicalType.getAsOpaquePtr());
4868 ID.AddInteger(I: protocols.size());
4869 for (auto *proto : protocols)
4870 ID.AddPointer(Ptr: proto);
4871}
4872
4873void ObjCTypeParamType::Profile(llvm::FoldingSetNodeID &ID) {
4874 Profile(ID, OTPDecl: getDecl(), CanonicalType: getCanonicalTypeInternal(),
4875 protocols: llvm::ArrayRef(qual_begin(), getNumProtocols()));
4876}
4877
4878namespace {
4879
4880/// The cached properties of a type.
4881class CachedProperties {
4882 Linkage L;
4883 bool local;
4884
4885public:
4886 CachedProperties(Linkage L, bool local) : L(L), local(local) {}
4887
4888 Linkage getLinkage() const { return L; }
4889 bool hasLocalOrUnnamedType() const { return local; }
4890
4891 friend CachedProperties merge(CachedProperties L, CachedProperties R) {
4892 Linkage MergedLinkage = minLinkage(L1: L.L, L2: R.L);
4893 return CachedProperties(MergedLinkage, L.hasLocalOrUnnamedType() ||
4894 R.hasLocalOrUnnamedType());
4895 }
4896};
4897
4898} // namespace
4899
4900static CachedProperties computeCachedProperties(const Type *T);
4901
4902namespace clang {
4903
4904/// The type-property cache. This is templated so as to be
4905/// instantiated at an internal type to prevent unnecessary symbol
4906/// leakage.
4907template <class Private> class TypePropertyCache {
4908public:
4909 static CachedProperties get(QualType T) { return get(T.getTypePtr()); }
4910
4911 static CachedProperties get(const Type *T) {
4912 ensure(T);
4913 return CachedProperties(T->TypeBits.getLinkage(),
4914 T->TypeBits.hasLocalOrUnnamedType());
4915 }
4916
4917 static void ensure(const Type *T) {
4918 // If the cache is valid, we're okay.
4919 if (T->TypeBits.isCacheValid())
4920 return;
4921
4922 // If this type is non-canonical, ask its canonical type for the
4923 // relevant information.
4924 if (!T->isCanonicalUnqualified()) {
4925 const Type *CT = T->getCanonicalTypeInternal().getTypePtr();
4926 ensure(T: CT);
4927 T->TypeBits.CacheValid = true;
4928 T->TypeBits.CachedLinkage = CT->TypeBits.CachedLinkage;
4929 T->TypeBits.CachedLocalOrUnnamed = CT->TypeBits.CachedLocalOrUnnamed;
4930 return;
4931 }
4932
4933 // Compute the cached properties and then set the cache.
4934 CachedProperties Result = computeCachedProperties(T);
4935 T->TypeBits.CacheValid = true;
4936 T->TypeBits.CachedLinkage = llvm::to_underlying(E: Result.getLinkage());
4937 T->TypeBits.CachedLocalOrUnnamed = Result.hasLocalOrUnnamedType();
4938 }
4939};
4940
4941} // namespace clang
4942
4943// Instantiate the friend template at a private class. In a
4944// reasonable implementation, these symbols will be internal.
4945// It is terrible that this is the best way to accomplish this.
4946namespace {
4947
4948class Private {};
4949
4950} // namespace
4951
4952using Cache = TypePropertyCache<Private>;
4953
4954static CachedProperties computeCachedProperties(const Type *T) {
4955 switch (T->getTypeClass()) {
4956#define TYPE(Class, Base)
4957#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
4958#include "clang/AST/TypeNodes.inc"
4959 llvm_unreachable("didn't expect a non-canonical type here");
4960
4961#define TYPE(Class, Base)
4962#define DEPENDENT_TYPE(Class, Base) case Type::Class:
4963#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class:
4964#include "clang/AST/TypeNodes.inc"
4965 // Treat instantiation-dependent types as external.
4966 assert(T->isInstantiationDependentType());
4967 return CachedProperties(Linkage::External, false);
4968
4969 case Type::Auto:
4970 case Type::DeducedTemplateSpecialization:
4971 // Give non-deduced 'auto' types external linkage. We should only see them
4972 // here in error recovery.
4973 return CachedProperties(Linkage::External, false);
4974
4975 case Type::BitInt:
4976 case Type::Builtin:
4977 // C++ [basic.link]p8:
4978 // A type is said to have linkage if and only if:
4979 // - it is a fundamental type (3.9.1); or
4980 return CachedProperties(Linkage::External, false);
4981
4982 case Type::Record:
4983 case Type::Enum: {
4984 const auto *Tag = cast<TagType>(Val: T)->getDecl()->getDefinitionOrSelf();
4985
4986 // C++ [basic.link]p8:
4987 // - it is a class or enumeration type that is named (or has a name
4988 // for linkage purposes (7.1.3)) and the name has linkage; or
4989 // - it is a specialization of a class template (14); or
4990 Linkage L = Tag->getLinkageInternal();
4991 bool IsLocalOrUnnamed = Tag->getDeclContext()->isFunctionOrMethod() ||
4992 !Tag->hasNameForLinkage();
4993 return CachedProperties(L, IsLocalOrUnnamed);
4994 }
4995
4996 // C++ [basic.link]p8:
4997 // - it is a compound type (3.9.2) other than a class or enumeration,
4998 // compounded exclusively from types that have linkage; or
4999 case Type::Complex:
5000 return Cache::get(T: cast<ComplexType>(Val: T)->getElementType());
5001 case Type::Pointer:
5002 return Cache::get(T: cast<PointerType>(Val: T)->getPointeeType());
5003 case Type::BlockPointer:
5004 return Cache::get(T: cast<BlockPointerType>(Val: T)->getPointeeType());
5005 case Type::LValueReference:
5006 case Type::RValueReference:
5007 return Cache::get(T: cast<ReferenceType>(Val: T)->getPointeeType());
5008 case Type::MemberPointer: {
5009 const auto *MPT = cast<MemberPointerType>(Val: T);
5010 CachedProperties Cls = [&] {
5011 if (MPT->isSugared())
5012 MPT = cast<MemberPointerType>(Val: MPT->getCanonicalTypeInternal());
5013 return Cache::get(T: MPT->getQualifier().getAsType());
5014 }();
5015 return merge(L: Cls, R: Cache::get(T: MPT->getPointeeType()));
5016 }
5017 case Type::ConstantArray:
5018 case Type::IncompleteArray:
5019 case Type::VariableArray:
5020 case Type::ArrayParameter:
5021 return Cache::get(T: cast<ArrayType>(Val: T)->getElementType());
5022 case Type::Vector:
5023 case Type::ExtVector:
5024 return Cache::get(T: cast<VectorType>(Val: T)->getElementType());
5025 case Type::ConstantMatrix:
5026 return Cache::get(T: cast<ConstantMatrixType>(Val: T)->getElementType());
5027 case Type::FunctionNoProto:
5028 return Cache::get(T: cast<FunctionType>(Val: T)->getReturnType());
5029 case Type::FunctionProto: {
5030 const auto *FPT = cast<FunctionProtoType>(Val: T);
5031 CachedProperties result = Cache::get(T: FPT->getReturnType());
5032 for (const auto &ai : FPT->param_types())
5033 result = merge(L: result, R: Cache::get(T: ai));
5034 return result;
5035 }
5036 case Type::ObjCInterface: {
5037 Linkage L = cast<ObjCInterfaceType>(Val: T)->getDecl()->getLinkageInternal();
5038 return CachedProperties(L, false);
5039 }
5040 case Type::ObjCObject:
5041 return Cache::get(T: cast<ObjCObjectType>(Val: T)->getBaseType());
5042 case Type::ObjCObjectPointer:
5043 return Cache::get(T: cast<ObjCObjectPointerType>(Val: T)->getPointeeType());
5044 case Type::Atomic:
5045 return Cache::get(T: cast<AtomicType>(Val: T)->getValueType());
5046 case Type::Pipe:
5047 return Cache::get(T: cast<PipeType>(Val: T)->getElementType());
5048 case Type::HLSLAttributedResource:
5049 return Cache::get(T: cast<HLSLAttributedResourceType>(Val: T)->getWrappedType());
5050 case Type::HLSLInlineSpirv:
5051 return CachedProperties(Linkage::External, false);
5052 case Type::OverflowBehavior:
5053 return Cache::get(T: cast<OverflowBehaviorType>(Val: T)->getUnderlyingType());
5054 }
5055
5056 llvm_unreachable("unhandled type class");
5057}
5058
5059/// Determine the linkage of this type.
5060Linkage Type::getLinkage() const {
5061 Cache::ensure(T: this);
5062 return TypeBits.getLinkage();
5063}
5064
5065bool Type::hasUnnamedOrLocalType() const {
5066 Cache::ensure(T: this);
5067 return TypeBits.hasLocalOrUnnamedType();
5068}
5069
5070LinkageInfo LinkageComputer::computeTypeLinkageInfo(const Type *T) {
5071 switch (T->getTypeClass()) {
5072#define TYPE(Class, Base)
5073#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
5074#include "clang/AST/TypeNodes.inc"
5075 llvm_unreachable("didn't expect a non-canonical type here");
5076
5077#define TYPE(Class, Base)
5078#define DEPENDENT_TYPE(Class, Base) case Type::Class:
5079#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class:
5080#include "clang/AST/TypeNodes.inc"
5081 // Treat instantiation-dependent types as external.
5082 assert(T->isInstantiationDependentType());
5083 return LinkageInfo::external();
5084
5085 case Type::BitInt:
5086 case Type::Builtin:
5087 return LinkageInfo::external();
5088
5089 case Type::Auto:
5090 case Type::DeducedTemplateSpecialization:
5091 return LinkageInfo::external();
5092
5093 case Type::Record:
5094 case Type::Enum:
5095 return getDeclLinkageAndVisibility(
5096 D: cast<TagType>(Val: T)->getDecl()->getDefinitionOrSelf());
5097
5098 case Type::Complex:
5099 return computeTypeLinkageInfo(T: cast<ComplexType>(Val: T)->getElementType());
5100 case Type::Pointer:
5101 return computeTypeLinkageInfo(T: cast<PointerType>(Val: T)->getPointeeType());
5102 case Type::BlockPointer:
5103 return computeTypeLinkageInfo(T: cast<BlockPointerType>(Val: T)->getPointeeType());
5104 case Type::LValueReference:
5105 case Type::RValueReference:
5106 return computeTypeLinkageInfo(T: cast<ReferenceType>(Val: T)->getPointeeType());
5107 case Type::MemberPointer: {
5108 const auto *MPT = cast<MemberPointerType>(Val: T);
5109 LinkageInfo LV;
5110 if (auto *D = MPT->getMostRecentCXXRecordDecl()) {
5111 LV.merge(other: getDeclLinkageAndVisibility(D));
5112 } else {
5113 LV.merge(other: computeTypeLinkageInfo(T: MPT->getQualifier().getAsType()));
5114 }
5115 LV.merge(other: computeTypeLinkageInfo(T: MPT->getPointeeType()));
5116 return LV;
5117 }
5118 case Type::ConstantArray:
5119 case Type::IncompleteArray:
5120 case Type::VariableArray:
5121 case Type::ArrayParameter:
5122 return computeTypeLinkageInfo(T: cast<ArrayType>(Val: T)->getElementType());
5123 case Type::Vector:
5124 case Type::ExtVector:
5125 return computeTypeLinkageInfo(T: cast<VectorType>(Val: T)->getElementType());
5126 case Type::ConstantMatrix:
5127 return computeTypeLinkageInfo(
5128 T: cast<ConstantMatrixType>(Val: T)->getElementType());
5129 case Type::FunctionNoProto:
5130 return computeTypeLinkageInfo(T: cast<FunctionType>(Val: T)->getReturnType());
5131 case Type::FunctionProto: {
5132 const auto *FPT = cast<FunctionProtoType>(Val: T);
5133 LinkageInfo LV = computeTypeLinkageInfo(T: FPT->getReturnType());
5134 for (const auto &ai : FPT->param_types())
5135 LV.merge(other: computeTypeLinkageInfo(T: ai));
5136 return LV;
5137 }
5138 case Type::ObjCInterface:
5139 return getDeclLinkageAndVisibility(D: cast<ObjCInterfaceType>(Val: T)->getDecl());
5140 case Type::ObjCObject:
5141 return computeTypeLinkageInfo(T: cast<ObjCObjectType>(Val: T)->getBaseType());
5142 case Type::ObjCObjectPointer:
5143 return computeTypeLinkageInfo(
5144 T: cast<ObjCObjectPointerType>(Val: T)->getPointeeType());
5145 case Type::Atomic:
5146 return computeTypeLinkageInfo(T: cast<AtomicType>(Val: T)->getValueType());
5147 case Type::Pipe:
5148 return computeTypeLinkageInfo(T: cast<PipeType>(Val: T)->getElementType());
5149 case Type::OverflowBehavior:
5150 return computeTypeLinkageInfo(
5151 T: cast<OverflowBehaviorType>(Val: T)->getUnderlyingType());
5152 case Type::HLSLAttributedResource:
5153 return computeTypeLinkageInfo(
5154 T: cast<HLSLAttributedResourceType>(Val: T)->getWrappedType());
5155 case Type::HLSLInlineSpirv:
5156 return LinkageInfo::external();
5157 }
5158
5159 llvm_unreachable("unhandled type class");
5160}
5161
5162bool Type::isLinkageValid() const {
5163 if (!TypeBits.isCacheValid())
5164 return true;
5165
5166 Linkage L = LinkageComputer{}
5167 .computeTypeLinkageInfo(T: getCanonicalTypeInternal())
5168 .getLinkage();
5169 return L == TypeBits.getLinkage();
5170}
5171
5172LinkageInfo LinkageComputer::getTypeLinkageAndVisibility(const Type *T) {
5173 if (!T->isCanonicalUnqualified())
5174 return computeTypeLinkageInfo(T: T->getCanonicalTypeInternal());
5175
5176 LinkageInfo LV = computeTypeLinkageInfo(T);
5177 assert(LV.getLinkage() == T->getLinkage());
5178 return LV;
5179}
5180
5181LinkageInfo Type::getLinkageAndVisibility() const {
5182 return LinkageComputer{}.getTypeLinkageAndVisibility(T: this);
5183}
5184
5185NullabilityKindOrNone Type::getNullability() const {
5186 QualType Type(this, 0);
5187 while (const auto *AT = Type->getAs<AttributedType>()) {
5188 // Check whether this is an attributed type with nullability
5189 // information.
5190 if (auto Nullability = AT->getImmediateNullability())
5191 return Nullability;
5192
5193 Type = AT->getEquivalentType();
5194 }
5195 return std::nullopt;
5196}
5197
5198bool Type::canHaveNullability(bool ResultIfUnknown) const {
5199 QualType type = getCanonicalTypeInternal();
5200
5201 switch (type->getTypeClass()) {
5202#define NON_CANONICAL_TYPE(Class, Parent) \
5203 /* We'll only see canonical types here. */ \
5204 case Type::Class: \
5205 llvm_unreachable("non-canonical type");
5206#define TYPE(Class, Parent)
5207#include "clang/AST/TypeNodes.inc"
5208
5209 // Pointer types.
5210 case Type::Pointer:
5211 case Type::BlockPointer:
5212 case Type::MemberPointer:
5213 case Type::ObjCObjectPointer:
5214 return true;
5215
5216 // Dependent types that could instantiate to pointer types.
5217 case Type::UnresolvedUsing:
5218 case Type::TypeOfExpr:
5219 case Type::TypeOf:
5220 case Type::Decltype:
5221 case Type::PackIndexing:
5222 case Type::UnaryTransform:
5223 case Type::TemplateTypeParm:
5224 case Type::SubstTemplateTypeParmPack:
5225 case Type::SubstBuiltinTemplatePack:
5226 case Type::DependentName:
5227 case Type::Auto:
5228 return ResultIfUnknown;
5229
5230 // Dependent template specializations could instantiate to pointer types.
5231 case Type::TemplateSpecialization:
5232 // If it's a known class template, we can already check if it's nullable.
5233 if (TemplateDecl *templateDecl =
5234 cast<TemplateSpecializationType>(Val: type.getTypePtr())
5235 ->getTemplateName()
5236 .getAsTemplateDecl())
5237 if (auto *CTD = dyn_cast<ClassTemplateDecl>(Val: templateDecl))
5238 return llvm::any_of(
5239 Range: CTD->redecls(), P: [](const RedeclarableTemplateDecl *RTD) {
5240 return RTD->getTemplatedDecl()->hasAttr<TypeNullableAttr>();
5241 });
5242 return ResultIfUnknown;
5243
5244 case Type::Builtin:
5245 switch (cast<BuiltinType>(Val: type.getTypePtr())->getKind()) {
5246 // Signed, unsigned, and floating-point types cannot have nullability.
5247#define SIGNED_TYPE(Id, SingletonId) case BuiltinType::Id:
5248#define UNSIGNED_TYPE(Id, SingletonId) case BuiltinType::Id:
5249#define FLOATING_TYPE(Id, SingletonId) case BuiltinType::Id:
5250#define BUILTIN_TYPE(Id, SingletonId)
5251#include "clang/AST/BuiltinTypes.def"
5252 return false;
5253
5254 case BuiltinType::UnresolvedTemplate:
5255 // Dependent types that could instantiate to a pointer type.
5256 case BuiltinType::Dependent:
5257 case BuiltinType::Overload:
5258 case BuiltinType::BoundMember:
5259 case BuiltinType::PseudoObject:
5260 case BuiltinType::UnknownAny:
5261 case BuiltinType::ARCUnbridgedCast:
5262 return ResultIfUnknown;
5263
5264 case BuiltinType::Void:
5265 case BuiltinType::ObjCId:
5266 case BuiltinType::ObjCClass:
5267 case BuiltinType::ObjCSel:
5268#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
5269 case BuiltinType::Id:
5270#include "clang/Basic/OpenCLImageTypes.def"
5271#define EXT_OPAQUE_TYPE(ExtType, Id, Ext) case BuiltinType::Id:
5272#include "clang/Basic/OpenCLExtensionTypes.def"
5273 case BuiltinType::OCLSampler:
5274 case BuiltinType::OCLEvent:
5275 case BuiltinType::OCLClkEvent:
5276 case BuiltinType::OCLQueue:
5277 case BuiltinType::OCLReserveID:
5278#define SVE_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
5279#include "clang/Basic/AArch64ACLETypes.def"
5280#define PPC_VECTOR_TYPE(Name, Id, Size) case BuiltinType::Id:
5281#include "clang/Basic/PPCTypes.def"
5282#define RVV_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
5283#include "clang/Basic/RISCVVTypes.def"
5284#define WASM_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
5285#include "clang/Basic/WebAssemblyReferenceTypes.def"
5286#define AMDGPU_TYPE(Name, Id, SingletonId, Width, Align) case BuiltinType::Id:
5287#include "clang/Basic/AMDGPUTypes.def"
5288#define HLSL_INTANGIBLE_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
5289#include "clang/Basic/HLSLIntangibleTypes.def"
5290#define SPIRV_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
5291#include "clang/Basic/SPIRVTypes.def"
5292 case BuiltinType::BuiltinFn:
5293 case BuiltinType::NullPtr:
5294 case BuiltinType::IncompleteMatrixIdx:
5295 case BuiltinType::ArraySection:
5296 case BuiltinType::OMPArrayShaping:
5297 case BuiltinType::OMPIterator:
5298 return false;
5299 }
5300 llvm_unreachable("unknown builtin type");
5301
5302 case Type::Record: {
5303 const auto *RD = cast<RecordType>(Val&: type)->getDecl();
5304 // For template specializations, look only at primary template attributes.
5305 // This is a consistent regardless of whether the instantiation is known.
5306 if (const auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(Val: RD))
5307 return llvm::any_of(
5308 Range: CTSD->getSpecializedTemplate()->redecls(),
5309 P: [](const RedeclarableTemplateDecl *RTD) {
5310 return RTD->getTemplatedDecl()->hasAttr<TypeNullableAttr>();
5311 });
5312 return llvm::any_of(Range: RD->redecls(), P: [](const TagDecl *RD) {
5313 return RD->hasAttr<TypeNullableAttr>();
5314 });
5315 }
5316
5317 // Non-pointer types.
5318 case Type::Complex:
5319 case Type::LValueReference:
5320 case Type::RValueReference:
5321 case Type::ConstantArray:
5322 case Type::IncompleteArray:
5323 case Type::VariableArray:
5324 case Type::DependentSizedArray:
5325 case Type::DependentVector:
5326 case Type::DependentSizedExtVector:
5327 case Type::Vector:
5328 case Type::ExtVector:
5329 case Type::ConstantMatrix:
5330 case Type::DependentSizedMatrix:
5331 case Type::DependentAddressSpace:
5332 case Type::FunctionProto:
5333 case Type::FunctionNoProto:
5334 case Type::DeducedTemplateSpecialization:
5335 case Type::Enum:
5336 case Type::InjectedClassName:
5337 case Type::PackExpansion:
5338 case Type::ObjCObject:
5339 case Type::ObjCInterface:
5340 case Type::Atomic:
5341 case Type::Pipe:
5342 case Type::BitInt:
5343 case Type::DependentBitInt:
5344 case Type::ArrayParameter:
5345 case Type::HLSLAttributedResource:
5346 case Type::HLSLInlineSpirv:
5347 case Type::OverflowBehavior:
5348 return false;
5349 }
5350 llvm_unreachable("bad type kind!");
5351}
5352
5353NullabilityKindOrNone AttributedType::getImmediateNullability() const {
5354 if (getAttrKind() == attr::TypeNonNull)
5355 return NullabilityKind::NonNull;
5356 if (getAttrKind() == attr::TypeNullable)
5357 return NullabilityKind::Nullable;
5358 if (getAttrKind() == attr::TypeNullUnspecified)
5359 return NullabilityKind::Unspecified;
5360 if (getAttrKind() == attr::TypeNullableResult)
5361 return NullabilityKind::NullableResult;
5362 return std::nullopt;
5363}
5364
5365NullabilityKindOrNone AttributedType::stripOuterNullability(QualType &T) {
5366 QualType AttrTy = T;
5367 if (auto MacroTy = dyn_cast<MacroQualifiedType>(Val&: T))
5368 AttrTy = MacroTy->getUnderlyingType();
5369
5370 if (auto attributed = dyn_cast<AttributedType>(Val&: AttrTy)) {
5371 if (auto nullability = attributed->getImmediateNullability()) {
5372 T = attributed->getModifiedType();
5373 return nullability;
5374 }
5375 }
5376
5377 return std::nullopt;
5378}
5379
5380void AttributedType::Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Ctx,
5381 Kind attrKind, QualType modified,
5382 QualType equivalent, const Attr *attr) {
5383 ID.AddInteger(I: attrKind);
5384 ID.AddPointer(Ptr: modified.getAsOpaquePtr());
5385 ID.AddPointer(Ptr: equivalent.getAsOpaquePtr());
5386 if (attr)
5387 attr->Profile(ID, Ctx);
5388}
5389
5390bool Type::isSignableIntegerType(const ASTContext &Ctx) const {
5391 if (!isIntegralType(Ctx) || isEnumeralType())
5392 return false;
5393 return Ctx.getTypeSize(T: this) == Ctx.getTypeSize(T: Ctx.VoidPtrTy);
5394}
5395
5396bool Type::isBlockCompatibleObjCPointerType(ASTContext &ctx) const {
5397 const auto *objcPtr = getAs<ObjCObjectPointerType>();
5398 if (!objcPtr)
5399 return false;
5400
5401 if (objcPtr->isObjCIdType()) {
5402 // id is always okay.
5403 return true;
5404 }
5405
5406 // Blocks are NSObjects.
5407 if (ObjCInterfaceDecl *iface = objcPtr->getInterfaceDecl()) {
5408 if (iface->getIdentifier() != ctx.getNSObjectName())
5409 return false;
5410
5411 // Continue to check qualifiers, below.
5412 } else if (objcPtr->isObjCQualifiedIdType()) {
5413 // Continue to check qualifiers, below.
5414 } else {
5415 return false;
5416 }
5417
5418 // Check protocol qualifiers.
5419 for (ObjCProtocolDecl *proto : objcPtr->quals()) {
5420 // Blocks conform to NSObject and NSCopying.
5421 if (proto->getIdentifier() != ctx.getNSObjectName() &&
5422 proto->getIdentifier() != ctx.getNSCopyingName())
5423 return false;
5424 }
5425
5426 return true;
5427}
5428
5429Qualifiers::ObjCLifetime Type::getObjCARCImplicitLifetime() const {
5430 if (isObjCARCImplicitlyUnretainedType())
5431 return Qualifiers::OCL_ExplicitNone;
5432 return Qualifiers::OCL_Strong;
5433}
5434
5435bool Type::isObjCARCImplicitlyUnretainedType() const {
5436 assert(isObjCLifetimeType() &&
5437 "cannot query implicit lifetime for non-inferrable type");
5438
5439 const Type *canon = getCanonicalTypeInternal().getTypePtr();
5440
5441 // Walk down to the base type. We don't care about qualifiers for this.
5442 while (const auto *array = dyn_cast<ArrayType>(Val: canon))
5443 canon = array->getElementType().getTypePtr();
5444
5445 if (const auto *opt = dyn_cast<ObjCObjectPointerType>(Val: canon)) {
5446 // Class and Class<Protocol> don't require retention.
5447 if (opt->getObjectType()->isObjCClass())
5448 return true;
5449 }
5450
5451 return false;
5452}
5453
5454bool Type::isObjCNSObjectType() const {
5455 if (const auto *typedefType = getAs<TypedefType>())
5456 return typedefType->getDecl()->hasAttr<ObjCNSObjectAttr>();
5457 return false;
5458}
5459
5460bool Type::isObjCIndependentClassType() const {
5461 if (const auto *typedefType = getAs<TypedefType>())
5462 return typedefType->getDecl()->hasAttr<ObjCIndependentClassAttr>();
5463 return false;
5464}
5465
5466bool Type::isObjCRetainableType() const {
5467 return isObjCObjectPointerType() || isBlockPointerType() ||
5468 isObjCNSObjectType();
5469}
5470
5471bool Type::isObjCIndirectLifetimeType() const {
5472 if (isObjCLifetimeType())
5473 return true;
5474 if (const auto *OPT = getAs<PointerType>())
5475 return OPT->getPointeeType()->isObjCIndirectLifetimeType();
5476 if (const auto *Ref = getAs<ReferenceType>())
5477 return Ref->getPointeeType()->isObjCIndirectLifetimeType();
5478 if (const auto *MemPtr = getAs<MemberPointerType>())
5479 return MemPtr->getPointeeType()->isObjCIndirectLifetimeType();
5480 return false;
5481}
5482
5483/// Returns true if objects of this type have lifetime semantics under
5484/// ARC.
5485bool Type::isObjCLifetimeType() const {
5486 const Type *type = this;
5487 while (const ArrayType *array = type->getAsArrayTypeUnsafe())
5488 type = array->getElementType().getTypePtr();
5489 return type->isObjCRetainableType();
5490}
5491
5492/// Determine whether the given type T is a "bridgable" Objective-C type,
5493/// which is either an Objective-C object pointer type or an
5494bool Type::isObjCARCBridgableType() const {
5495 return isObjCObjectPointerType() || isBlockPointerType();
5496}
5497
5498/// Determine whether the given type T is a "bridgeable" C type.
5499bool Type::isCARCBridgableType() const {
5500 const auto *Pointer = getAsCanonical<PointerType>();
5501 if (!Pointer)
5502 return false;
5503
5504 QualType Pointee = Pointer->getPointeeType();
5505 return Pointee->isVoidType() || Pointee->isRecordType();
5506}
5507
5508/// Check if the specified type is the CUDA device builtin surface type.
5509bool Type::isCUDADeviceBuiltinSurfaceType() const {
5510 if (const auto *RT = getAsCanonical<RecordType>())
5511 return RT->getDecl()
5512 ->getMostRecentDecl()
5513 ->hasAttr<CUDADeviceBuiltinSurfaceTypeAttr>();
5514 return false;
5515}
5516
5517/// Check if the specified type is the CUDA device builtin texture type.
5518bool Type::isCUDADeviceBuiltinTextureType() const {
5519 if (const auto *RT = getAsCanonical<RecordType>())
5520 return RT->getDecl()
5521 ->getMostRecentDecl()
5522 ->hasAttr<CUDADeviceBuiltinTextureTypeAttr>();
5523 return false;
5524}
5525
5526static bool isAMDGPUNamedBarrierTypeImpl(const Type *Ty, bool AllowWrappers) {
5527 // This query does not care about qualifiers at all.
5528 Ty = Ty->getUnqualifiedDesugaredType();
5529
5530 // Unwrap arrays.
5531 while (isa<ArrayType>(Val: Ty))
5532 Ty = Ty->getArrayElementTypeNoTypeQual()->getUnqualifiedDesugaredType();
5533
5534 if (const auto *BT = dyn_cast<BuiltinType>(Val: Ty))
5535 return BT->getKind() == BuiltinType::AMDGPUNamedWorkgroupBarrier;
5536 if (AllowWrappers) {
5537 if (const auto *RT = dyn_cast<RecordType>(Val: Ty))
5538 return RT->getDecl()->hasAttr<AMDGPUNamedBarrierWrapperAttr>();
5539 }
5540 return false;
5541}
5542
5543bool Type::isAMDGPUNamedBarrierType() const {
5544 return isAMDGPUNamedBarrierTypeImpl(Ty: this, /*AllowWrappers=*/false);
5545}
5546
5547bool Type::isAMDGPUNamedBarrierTypeOrWrapper() const {
5548 return isAMDGPUNamedBarrierTypeImpl(Ty: this, /*AllowWrappers=*/true);
5549}
5550
5551bool Type::hasSizedVLAType() const {
5552 if (!isVariablyModifiedType())
5553 return false;
5554
5555 if (const auto *ptr = getAs<PointerType>())
5556 return ptr->getPointeeType()->hasSizedVLAType();
5557 if (const auto *ref = getAs<ReferenceType>())
5558 return ref->getPointeeType()->hasSizedVLAType();
5559 if (const ArrayType *arr = getAsArrayTypeUnsafe()) {
5560 if (isa<VariableArrayType>(Val: arr) &&
5561 cast<VariableArrayType>(Val: arr)->getSizeExpr())
5562 return true;
5563
5564 return arr->getElementType()->hasSizedVLAType();
5565 }
5566
5567 return false;
5568}
5569
5570bool Type::isHLSLResourceRecord() const {
5571 return HLSLAttributedResourceType::findHandleTypeOnResource(RT: this) != nullptr;
5572}
5573
5574bool Type::isHLSLResourceRecordArray() const {
5575 const Type *Ty = getUnqualifiedDesugaredType();
5576 if (!Ty->isArrayType())
5577 return false;
5578 while (isa<ArrayType>(Val: Ty))
5579 Ty = Ty->getArrayElementTypeNoTypeQual();
5580 return Ty->isHLSLResourceRecord();
5581}
5582
5583bool Type::isHLSLIntangibleType() const {
5584 const Type *Ty = getUnqualifiedDesugaredType();
5585
5586 // check if it's a builtin type first
5587 if (Ty->isBuiltinType())
5588 return Ty->isHLSLBuiltinIntangibleType();
5589
5590 // unwrap arrays
5591 while (isa<ArrayType>(Val: Ty))
5592 Ty = Ty->getArrayElementTypeNoTypeQual();
5593
5594 const RecordType *RT =
5595 dyn_cast<RecordType>(Val: Ty->getUnqualifiedDesugaredType());
5596 if (!RT)
5597 return false;
5598
5599 CXXRecordDecl *RD = RT->getAsCXXRecordDecl();
5600 assert(RD != nullptr &&
5601 "all HLSL structs and classes should be CXXRecordDecl");
5602 assert(RD->isCompleteDefinition() && "expecting complete type");
5603 return RD->isHLSLIntangible();
5604}
5605
5606bool Type::isHLSLStandardLayoutRecordOrArrayOf() const {
5607 const Type *BaseTy = getBaseElementTypeUnsafe();
5608 if (const auto *RD =
5609 dyn_cast_or_null<CXXRecordDecl>(Val: BaseTy->getAsRecordDecl())) {
5610 if (!RD->isHLSLBuiltinRecord() && RD->isStandardLayout())
5611 return true;
5612 }
5613 return false;
5614}
5615
5616QualType::DestructionKind QualType::isDestructedTypeImpl(QualType type) {
5617 switch (type.getObjCLifetime()) {
5618 case Qualifiers::OCL_None:
5619 case Qualifiers::OCL_ExplicitNone:
5620 case Qualifiers::OCL_Autoreleasing:
5621 break;
5622
5623 case Qualifiers::OCL_Strong:
5624 return DK_objc_strong_lifetime;
5625 case Qualifiers::OCL_Weak:
5626 return DK_objc_weak_lifetime;
5627 }
5628
5629 if (const auto *RD = type->getBaseElementTypeUnsafe()->getAsRecordDecl()) {
5630 if (const auto *CXXRD = dyn_cast<CXXRecordDecl>(Val: RD)) {
5631 /// Check if this is a C++ object with a non-trivial destructor.
5632 if (CXXRD->hasDefinition() && !CXXRD->hasTrivialDestructor())
5633 return DK_cxx_destructor;
5634 } else {
5635 /// Check if this is a C struct that is non-trivial to destroy or an array
5636 /// that contains such a struct.
5637 if (RD->isNonTrivialToPrimitiveDestroy())
5638 return DK_nontrivial_c_struct;
5639 }
5640 }
5641
5642 return DK_none;
5643}
5644
5645static bool
5646requiresBuiltinLaunderImpl(const ASTContext &Context, QualType Ty,
5647 llvm::SmallPtrSetImpl<const Decl *> &Seen) {
5648 if (const auto *Arr = Context.getAsArrayType(T: Ty))
5649 Ty = Context.getBaseElementType(VAT: Arr);
5650
5651 if (const auto *AttrTy = Ty->getAs<AttributedType>())
5652 Ty = AttrTy->getModifiedType();
5653
5654 assert(!Ty->isIncompleteType() &&
5655 "Incomplete types cannot be evaluated for laundering");
5656
5657 const auto *Record = Ty->getAsCXXRecordDecl();
5658 if (!Record)
5659 return false;
5660
5661 // We've already checked this type, or are in the process of checking it.
5662 if (!Seen.insert(Ptr: Record).second)
5663 return false;
5664
5665 if (Record->isDynamicClass())
5666 return true;
5667
5668 for (FieldDecl *F : Record->fields()) {
5669 if (requiresBuiltinLaunderImpl(Context, Ty: F->getType(), Seen))
5670 return true;
5671 }
5672 return false;
5673}
5674
5675bool QualType::requiresBuiltinLaunder(const ASTContext &Context) const {
5676 llvm::SmallPtrSet<const Decl *, 16> Seen;
5677 return requiresBuiltinLaunderImpl(Context, Ty: *this, Seen);
5678}
5679
5680bool MemberPointerType::isSugared() const {
5681 CXXRecordDecl *D1 = getMostRecentCXXRecordDecl(),
5682 *D2 = getQualifier().getAsRecordDecl();
5683 assert(!D1 == !D2);
5684 return D1 != D2 && D1->getCanonicalDecl() != D2->getCanonicalDecl();
5685}
5686
5687void MemberPointerType::Profile(llvm::FoldingSetNodeID &ID, QualType Pointee,
5688 const NestedNameSpecifier Qualifier,
5689 const CXXRecordDecl *Cls) {
5690 ID.AddPointer(Ptr: Pointee.getAsOpaquePtr());
5691 Qualifier.Profile(ID);
5692 if (Cls)
5693 ID.AddPointer(Ptr: Cls->getCanonicalDecl());
5694}
5695
5696CXXRecordDecl *MemberPointerType::getCXXRecordDecl() const {
5697 return dyn_cast<MemberPointerType>(Val: getCanonicalTypeInternal())
5698 ->getQualifier()
5699 .getAsRecordDecl();
5700}
5701
5702CXXRecordDecl *MemberPointerType::getMostRecentCXXRecordDecl() const {
5703 auto *RD = getCXXRecordDecl();
5704 if (!RD)
5705 return nullptr;
5706 return RD->getMostRecentDecl();
5707}
5708
5709void clang::FixedPointValueToString(SmallVectorImpl<char> &Str,
5710 llvm::APSInt Val, unsigned Scale) {
5711 llvm::FixedPointSemantics FXSema(Val.getBitWidth(), Scale, Val.isSigned(),
5712 /*IsSaturated=*/false,
5713 /*HasUnsignedPadding=*/false);
5714 llvm::APFixedPoint(Val, FXSema).toString(Str);
5715}
5716
5717DeducedType::DeducedType(TypeClass TC, DeducedKind DK,
5718 QualType DeducedAsTypeOrCanon)
5719 : Type(TC, /*canon=*/DK == DeducedKind::Deduced
5720 ? DeducedAsTypeOrCanon.getCanonicalType()
5721 : DeducedAsTypeOrCanon,
5722 TypeDependence::None) {
5723 DeducedTypeBits.Kind = llvm::to_underlying(E: DK);
5724 switch (DK) {
5725 case DeducedKind::Undeduced:
5726 break;
5727 case DeducedKind::Deduced:
5728 assert(!DeducedAsTypeOrCanon.isNull() && "Deduced type cannot be null");
5729 addDependence(D: DeducedAsTypeOrCanon->getDependence() &
5730 ~TypeDependence::VariablyModified);
5731 DeducedAsType = DeducedAsTypeOrCanon;
5732 break;
5733 case DeducedKind::DeducedAsPack:
5734 addDependence(D: TypeDependence::UnexpandedPack);
5735 [[fallthrough]];
5736 case DeducedKind::DeducedAsDependent:
5737 addDependence(D: TypeDependence::DependentInstantiation);
5738 break;
5739 }
5740 assert(getDeducedKind() == DK && "DeducedKind does not match the type state");
5741}
5742
5743AutoType::AutoType(DeducedKind DK, QualType DeducedAsTypeOrCanon,
5744 AutoTypeKeyword Keyword, TemplateName TypeConstraintConcept,
5745 ArrayRef<TemplateArgument> TypeConstraintArgs)
5746 : DeducedType(Auto, DK, DeducedAsTypeOrCanon) {
5747 AutoTypeBits.Keyword = llvm::to_underlying(E: Keyword);
5748 AutoTypeBits.NumArgs = TypeConstraintArgs.size();
5749 this->TypeConstraintConcept = TypeConstraintConcept;
5750 assert(!TypeConstraintConcept.isNull() || AutoTypeBits.NumArgs == 0);
5751 if (!TypeConstraintConcept.isNull()) {
5752 assert(TypeConstraintConcept.isConceptName() &&
5753 "type-constraint does not name a concept");
5754
5755 auto Dep = toTypeDependence(D: TypeConstraintConcept.getDependence());
5756
5757 auto *ArgBuffer =
5758 const_cast<TemplateArgument *>(getTypeConstraintArguments().data());
5759 for (const TemplateArgument &Arg : TypeConstraintArgs) {
5760 Dep |= toTypeDependence(D: Arg.getDependence());
5761 new (ArgBuffer++) TemplateArgument(Arg);
5762 }
5763 // A deduced AutoType only syntactically depends on its constraints.
5764 if (DK == DeducedKind::Deduced)
5765 Dep = toSyntacticDependence(D: Dep);
5766 addDependence(D: Dep);
5767 }
5768}
5769
5770void AutoType::Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context,
5771 DeducedKind DK, QualType Deduced,
5772 AutoTypeKeyword Keyword, TemplateName CD,
5773 ArrayRef<TemplateArgument> Arguments) {
5774 DeducedType::Profile(ID, DK, Deduced);
5775 ID.AddInteger(I: llvm::to_underlying(E: Keyword));
5776 CD.Profile(ID);
5777 for (const TemplateArgument &Arg : Arguments)
5778 Arg.Profile(ID, Context);
5779}
5780
5781void AutoType::Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context) {
5782 Profile(ID, Context, DK: getDeducedKind(), Deduced: getDeducedType(), Keyword: getKeyword(),
5783 CD: getTypeConstraintConcept(), Arguments: getTypeConstraintArguments());
5784}
5785
5786FunctionEffect::Kind FunctionEffect::oppositeKind() const {
5787 switch (kind()) {
5788 case Kind::NonBlocking:
5789 return Kind::Blocking;
5790 case Kind::Blocking:
5791 return Kind::NonBlocking;
5792 case Kind::NonAllocating:
5793 return Kind::Allocating;
5794 case Kind::Allocating:
5795 return Kind::NonAllocating;
5796 }
5797 llvm_unreachable("unknown effect kind");
5798}
5799
5800StringRef FunctionEffect::name() const {
5801 switch (kind()) {
5802 case Kind::NonBlocking:
5803 return "nonblocking";
5804 case Kind::NonAllocating:
5805 return "nonallocating";
5806 case Kind::Blocking:
5807 return "blocking";
5808 case Kind::Allocating:
5809 return "allocating";
5810 }
5811 llvm_unreachable("unknown effect kind");
5812}
5813
5814std::optional<FunctionEffect> FunctionEffect::effectProhibitingInference(
5815 const Decl &Callee, FunctionEffectKindSet CalleeFX) const {
5816 switch (kind()) {
5817 case Kind::NonAllocating:
5818 case Kind::NonBlocking: {
5819 for (FunctionEffect Effect : CalleeFX) {
5820 // nonblocking/nonallocating cannot call allocating.
5821 if (Effect.kind() == Kind::Allocating)
5822 return Effect;
5823 // nonblocking cannot call blocking.
5824 if (kind() == Kind::NonBlocking && Effect.kind() == Kind::Blocking)
5825 return Effect;
5826 }
5827 return std::nullopt;
5828 }
5829
5830 case Kind::Allocating:
5831 case Kind::Blocking:
5832 assert(0 && "effectProhibitingInference with non-inferable effect kind");
5833 break;
5834 }
5835 llvm_unreachable("unknown effect kind");
5836}
5837
5838bool FunctionEffect::shouldDiagnoseFunctionCall(
5839 bool Direct, FunctionEffectKindSet CalleeFX) const {
5840 switch (kind()) {
5841 case Kind::NonAllocating:
5842 case Kind::NonBlocking: {
5843 const Kind CallerKind = kind();
5844 for (FunctionEffect Effect : CalleeFX) {
5845 const Kind EK = Effect.kind();
5846 // Does callee have same or stronger constraint?
5847 if (EK == CallerKind ||
5848 (CallerKind == Kind::NonAllocating && EK == Kind::NonBlocking)) {
5849 return false; // no diagnostic
5850 }
5851 }
5852 return true; // warning
5853 }
5854 case Kind::Allocating:
5855 case Kind::Blocking:
5856 return false;
5857 }
5858 llvm_unreachable("unknown effect kind");
5859}
5860
5861// =====
5862
5863bool FunctionEffectSet::insert(const FunctionEffectWithCondition &NewEC,
5864 Conflicts &Errs) {
5865 FunctionEffect::Kind NewOppositeKind = NewEC.Effect.oppositeKind();
5866 Expr *NewCondition = NewEC.Cond.getCondition();
5867
5868 // The index at which insertion will take place; default is at end
5869 // but we might find an earlier insertion point.
5870 unsigned InsertIdx = Effects.size();
5871 unsigned Idx = 0;
5872 for (const FunctionEffectWithCondition &EC : *this) {
5873 // Note about effects with conditions: They are considered distinct from
5874 // those without conditions; they are potentially unique, redundant, or
5875 // in conflict, but we can't tell which until the condition is evaluated.
5876 if (EC.Cond.getCondition() == nullptr && NewCondition == nullptr) {
5877 if (EC.Effect.kind() == NewEC.Effect.kind()) {
5878 // There is no condition, and the effect kind is already present,
5879 // so just fail to insert the new one (creating a duplicate),
5880 // and return success.
5881 return true;
5882 }
5883
5884 if (EC.Effect.kind() == NewOppositeKind) {
5885 Errs.push_back(Elt: {.Kept: EC, .Rejected: NewEC});
5886 return false;
5887 }
5888 }
5889
5890 if (NewEC.Effect.kind() < EC.Effect.kind() && InsertIdx > Idx)
5891 InsertIdx = Idx;
5892
5893 ++Idx;
5894 }
5895
5896 if (NewCondition || !Conditions.empty()) {
5897 if (Conditions.empty() && !Effects.empty())
5898 Conditions.resize(N: Effects.size());
5899 Conditions.insert(I: Conditions.begin() + InsertIdx,
5900 Elt: NewEC.Cond.getCondition());
5901 }
5902 Effects.insert(I: Effects.begin() + InsertIdx, Elt: NewEC.Effect);
5903 return true;
5904}
5905
5906bool FunctionEffectSet::insert(const FunctionEffectsRef &Set, Conflicts &Errs) {
5907 for (const auto &Item : Set)
5908 insert(NewEC: Item, Errs);
5909 return Errs.empty();
5910}
5911
5912FunctionEffectSet FunctionEffectSet::getIntersection(FunctionEffectsRef LHS,
5913 FunctionEffectsRef RHS) {
5914 FunctionEffectSet Result;
5915 FunctionEffectSet::Conflicts Errs;
5916
5917 // We could use std::set_intersection but that would require expanding the
5918 // container interface to include push_back, making it available to clients
5919 // who might fail to maintain invariants.
5920 auto IterA = LHS.begin(), EndA = LHS.end();
5921 auto IterB = RHS.begin(), EndB = RHS.end();
5922
5923 auto FEWCLess = [](const FunctionEffectWithCondition &LHS,
5924 const FunctionEffectWithCondition &RHS) {
5925 return std::tuple(LHS.Effect, uintptr_t(LHS.Cond.getCondition())) <
5926 std::tuple(RHS.Effect, uintptr_t(RHS.Cond.getCondition()));
5927 };
5928
5929 while (IterA != EndA && IterB != EndB) {
5930 FunctionEffectWithCondition A = *IterA;
5931 FunctionEffectWithCondition B = *IterB;
5932 if (FEWCLess(A, B))
5933 ++IterA;
5934 else if (FEWCLess(B, A))
5935 ++IterB;
5936 else {
5937 Result.insert(NewEC: A, Errs);
5938 ++IterA;
5939 ++IterB;
5940 }
5941 }
5942
5943 // Insertion shouldn't be able to fail; that would mean both input
5944 // sets contained conflicts.
5945 assert(Errs.empty() && "conflict shouldn't be possible in getIntersection");
5946
5947 return Result;
5948}
5949
5950FunctionEffectSet FunctionEffectSet::getUnion(FunctionEffectsRef LHS,
5951 FunctionEffectsRef RHS,
5952 Conflicts &Errs) {
5953 // Optimize for either of the two sets being empty (very common).
5954 if (LHS.empty())
5955 return FunctionEffectSet(RHS);
5956
5957 FunctionEffectSet Combined(LHS);
5958 Combined.insert(Set: RHS, Errs);
5959 return Combined;
5960}
5961
5962namespace clang {
5963
5964raw_ostream &operator<<(raw_ostream &OS,
5965 const FunctionEffectWithCondition &CFE) {
5966 OS << CFE.Effect.name();
5967 if (Expr *E = CFE.Cond.getCondition()) {
5968 OS << '(';
5969 E->dump();
5970 OS << ')';
5971 }
5972 return OS;
5973}
5974
5975} // namespace clang
5976
5977LLVM_DUMP_METHOD void FunctionEffectsRef::dump(llvm::raw_ostream &OS) const {
5978 OS << "Effects{";
5979 llvm::interleaveComma(c: *this, os&: OS);
5980 OS << "}";
5981}
5982
5983LLVM_DUMP_METHOD void FunctionEffectSet::dump(llvm::raw_ostream &OS) const {
5984 FunctionEffectsRef(*this).dump(OS);
5985}
5986
5987LLVM_DUMP_METHOD void FunctionEffectKindSet::dump(llvm::raw_ostream &OS) const {
5988 OS << "Effects{";
5989 llvm::interleaveComma(c: *this, os&: OS);
5990 OS << "}";
5991}
5992
5993FunctionEffectsRef
5994FunctionEffectsRef::create(ArrayRef<FunctionEffect> FX,
5995 ArrayRef<EffectConditionExpr> Conds) {
5996 assert(llvm::is_sorted(FX) && "effects should be sorted");
5997 assert((Conds.empty() || Conds.size() == FX.size()) &&
5998 "effects size should match conditions size");
5999 return FunctionEffectsRef(FX, Conds);
6000}
6001
6002std::string FunctionEffectWithCondition::description() const {
6003 std::string Result(Effect.name().str());
6004 if (Cond.getCondition() != nullptr)
6005 Result += "(expr)";
6006 return Result;
6007}
6008
6009TypeDependence
6010HLSLAttributedResourceType::computeDependence(QualType Contained,
6011 const Attributes &Attrs) {
6012 TypeDependence Deps = TypeDependence::None;
6013 if (!Contained.isNull())
6014 Deps |= Contained->getDependence();
6015 if (Attrs.SampleCountExpr)
6016 Deps |= toTypeDependence(D: Attrs.SampleCountExpr->getDependence());
6017 return Deps;
6018}
6019
6020HLSLAttributedResourceType::HLSLAttributedResourceType(QualType Wrapped,
6021 QualType Contained,
6022 const Attributes &Attrs)
6023 : Type(HLSLAttributedResource, QualType(),
6024 computeDependence(Contained, Attrs)),
6025 WrappedType(Wrapped), ContainedType(Contained), Attrs(Attrs) {}
6026
6027void HLSLAttributedResourceType::Profile(llvm::FoldingSetNodeID &ID,
6028 const ASTContext &Ctx,
6029 QualType Wrapped, QualType Contained,
6030 const Attributes &Attrs) {
6031 ID.AddPointer(Ptr: Wrapped.getAsOpaquePtr());
6032 ID.AddPointer(Ptr: Contained.getAsOpaquePtr());
6033 ID.AddInteger(I: static_cast<uint32_t>(Attrs.ResourceClass));
6034 ID.AddInteger(I: static_cast<uint32_t>(Attrs.ResourceDimension));
6035 ID.AddBoolean(B: Attrs.IsROV);
6036 ID.AddBoolean(B: Attrs.RawBuffer);
6037 ID.AddBoolean(B: Attrs.IsCounter);
6038 ID.AddBoolean(B: Attrs.IsArray);
6039 ID.AddBoolean(B: Attrs.SampleCountExpr != nullptr);
6040 if (Attrs.SampleCountExpr)
6041 Attrs.SampleCountExpr->Profile(ID, Context: Ctx, /*Canonical=*/true);
6042}
6043
6044const HLSLAttributedResourceType *
6045HLSLAttributedResourceType::findHandleTypeOnResource(const Type *RT) {
6046 // If the type RT is an HLSL resource class, the first field must
6047 // be the resource handle of type HLSLAttributedResourceType
6048 const clang::Type *Ty = RT->getUnqualifiedDesugaredType();
6049 if (const RecordDecl *RD = Ty->getAsCXXRecordDecl()) {
6050 if (!RD->fields().empty()) {
6051 const auto &FirstFD = RD->fields().begin();
6052 return dyn_cast<HLSLAttributedResourceType>(
6053 Val: FirstFD->getType().getTypePtr());
6054 }
6055 }
6056 return nullptr;
6057}
6058
6059StringRef PredefinedSugarType::getName(Kind KD) {
6060 switch (KD) {
6061 case Kind::SizeT:
6062 return "__size_t";
6063 case Kind::SignedSizeT:
6064 return "__signed_size_t";
6065 case Kind::PtrdiffT:
6066 return "__ptrdiff_t";
6067 }
6068 llvm_unreachable("unexpected kind");
6069}
6070