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