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