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