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

source code of clang/lib/AST/Type.cpp