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