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