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