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