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