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