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