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