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