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