xref: /llvm-project-15.0.7/clang/lib/AST/Type.cpp (revision 2bb3a906)
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 false;
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   : Type(Vector, canonType, vecType->isDependentType(),
174          vecType->isInstantiationDependentType(),
175          vecType->isVariablyModifiedType(),
176          vecType->containsUnexpandedParameterPack()),
177     ElementType(vecType)
178 {
179   VectorTypeBits.VecKind = vecKind;
180   VectorTypeBits.NumElements = nElements;
181 }
182 
183 VectorType::VectorType(TypeClass tc, QualType vecType, unsigned nElements,
184                        QualType canonType, VectorKind vecKind)
185   : Type(tc, canonType, vecType->isDependentType(),
186          vecType->isInstantiationDependentType(),
187          vecType->isVariablyModifiedType(),
188          vecType->containsUnexpandedParameterPack()),
189     ElementType(vecType)
190 {
191   VectorTypeBits.VecKind = vecKind;
192   VectorTypeBits.NumElements = nElements;
193 }
194 
195 /// getArrayElementTypeNoTypeQual - If this is an array type, return the
196 /// element type of the array, potentially with type qualifiers missing.
197 /// This method should never be used when type qualifiers are meaningful.
198 const Type *Type::getArrayElementTypeNoTypeQual() const {
199   // If this is directly an array type, return it.
200   if (const ArrayType *ATy = dyn_cast<ArrayType>(this))
201     return ATy->getElementType().getTypePtr();
202 
203   // If the canonical form of this type isn't the right kind, reject it.
204   if (!isa<ArrayType>(CanonicalType))
205     return nullptr;
206 
207   // If this is a typedef for an array type, strip the typedef off without
208   // losing all typedef information.
209   return cast<ArrayType>(getUnqualifiedDesugaredType())
210     ->getElementType().getTypePtr();
211 }
212 
213 /// getDesugaredType - Return the specified type with any "sugar" removed from
214 /// the type.  This takes off typedefs, typeof's etc.  If the outer level of
215 /// the type is already concrete, it returns it unmodified.  This is similar
216 /// to getting the canonical type, but it doesn't remove *all* typedefs.  For
217 /// example, it returns "T*" as "T*", (not as "int*"), because the pointer is
218 /// concrete.
219 QualType QualType::getDesugaredType(QualType T, const ASTContext &Context) {
220   SplitQualType split = getSplitDesugaredType(T);
221   return Context.getQualifiedType(split.Ty, split.Quals);
222 }
223 
224 QualType QualType::getSingleStepDesugaredTypeImpl(QualType type,
225                                                   const ASTContext &Context) {
226   SplitQualType split = type.split();
227   QualType desugar = split.Ty->getLocallyUnqualifiedSingleStepDesugaredType();
228   return Context.getQualifiedType(desugar, split.Quals);
229 }
230 
231 QualType Type::getLocallyUnqualifiedSingleStepDesugaredType() const {
232   switch (getTypeClass()) {
233 #define ABSTRACT_TYPE(Class, Parent)
234 #define TYPE(Class, Parent) \
235   case Type::Class: { \
236     const Class##Type *ty = cast<Class##Type>(this); \
237     if (!ty->isSugared()) return QualType(ty, 0); \
238     return ty->desugar(); \
239   }
240 #include "clang/AST/TypeNodes.def"
241   }
242   llvm_unreachable("bad type kind!");
243 }
244 
245 SplitQualType QualType::getSplitDesugaredType(QualType T) {
246   QualifierCollector Qs;
247 
248   QualType Cur = T;
249   while (true) {
250     const Type *CurTy = Qs.strip(Cur);
251     switch (CurTy->getTypeClass()) {
252 #define ABSTRACT_TYPE(Class, Parent)
253 #define TYPE(Class, Parent) \
254     case Type::Class: { \
255       const Class##Type *Ty = cast<Class##Type>(CurTy); \
256       if (!Ty->isSugared()) \
257         return SplitQualType(Ty, Qs); \
258       Cur = Ty->desugar(); \
259       break; \
260     }
261 #include "clang/AST/TypeNodes.def"
262     }
263   }
264 }
265 
266 SplitQualType QualType::getSplitUnqualifiedTypeImpl(QualType type) {
267   SplitQualType split = type.split();
268 
269   // All the qualifiers we've seen so far.
270   Qualifiers quals = split.Quals;
271 
272   // The last type node we saw with any nodes inside it.
273   const Type *lastTypeWithQuals = split.Ty;
274 
275   while (true) {
276     QualType next;
277 
278     // Do a single-step desugar, aborting the loop if the type isn't
279     // sugared.
280     switch (split.Ty->getTypeClass()) {
281 #define ABSTRACT_TYPE(Class, Parent)
282 #define TYPE(Class, Parent) \
283     case Type::Class: { \
284       const Class##Type *ty = cast<Class##Type>(split.Ty); \
285       if (!ty->isSugared()) goto done; \
286       next = ty->desugar(); \
287       break; \
288     }
289 #include "clang/AST/TypeNodes.def"
290     }
291 
292     // Otherwise, split the underlying type.  If that yields qualifiers,
293     // update the information.
294     split = next.split();
295     if (!split.Quals.empty()) {
296       lastTypeWithQuals = split.Ty;
297       quals.addConsistentQualifiers(split.Quals);
298     }
299   }
300 
301  done:
302   return SplitQualType(lastTypeWithQuals, quals);
303 }
304 
305 QualType QualType::IgnoreParens(QualType T) {
306   // FIXME: this seems inherently un-qualifiers-safe.
307   while (const ParenType *PT = T->getAs<ParenType>())
308     T = PT->getInnerType();
309   return T;
310 }
311 
312 /// \brief This will check for a T (which should be a Type which can act as
313 /// sugar, such as a TypedefType) by removing any existing sugar until it
314 /// reaches a T or a non-sugared type.
315 template<typename T> static const T *getAsSugar(const Type *Cur) {
316   while (true) {
317     if (const T *Sugar = dyn_cast<T>(Cur))
318       return Sugar;
319     switch (Cur->getTypeClass()) {
320 #define ABSTRACT_TYPE(Class, Parent)
321 #define TYPE(Class, Parent) \
322     case Type::Class: { \
323       const Class##Type *Ty = cast<Class##Type>(Cur); \
324       if (!Ty->isSugared()) return 0; \
325       Cur = Ty->desugar().getTypePtr(); \
326       break; \
327     }
328 #include "clang/AST/TypeNodes.def"
329     }
330   }
331 }
332 
333 template <> const TypedefType *Type::getAs() const {
334   return getAsSugar<TypedefType>(this);
335 }
336 
337 template <> const TemplateSpecializationType *Type::getAs() const {
338   return getAsSugar<TemplateSpecializationType>(this);
339 }
340 
341 template <> const AttributedType *Type::getAs() const {
342   return getAsSugar<AttributedType>(this);
343 }
344 
345 /// getUnqualifiedDesugaredType - Pull any qualifiers and syntactic
346 /// sugar off the given type.  This should produce an object of the
347 /// same dynamic type as the canonical type.
348 const Type *Type::getUnqualifiedDesugaredType() const {
349   const Type *Cur = this;
350 
351   while (true) {
352     switch (Cur->getTypeClass()) {
353 #define ABSTRACT_TYPE(Class, Parent)
354 #define TYPE(Class, Parent) \
355     case Class: { \
356       const Class##Type *Ty = cast<Class##Type>(Cur); \
357       if (!Ty->isSugared()) return Cur; \
358       Cur = Ty->desugar().getTypePtr(); \
359       break; \
360     }
361 #include "clang/AST/TypeNodes.def"
362     }
363   }
364 }
365 bool Type::isClassType() const {
366   if (const RecordType *RT = getAs<RecordType>())
367     return RT->getDecl()->isClass();
368   return false;
369 }
370 bool Type::isStructureType() const {
371   if (const RecordType *RT = getAs<RecordType>())
372     return RT->getDecl()->isStruct();
373   return false;
374 }
375 bool Type::isInterfaceType() const {
376   if (const RecordType *RT = getAs<RecordType>())
377     return RT->getDecl()->isInterface();
378   return false;
379 }
380 bool Type::isStructureOrClassType() const {
381   if (const RecordType *RT = getAs<RecordType>())
382     return RT->getDecl()->isStruct() || RT->getDecl()->isClass() ||
383       RT->getDecl()->isInterface();
384   return false;
385 }
386 bool Type::isVoidPointerType() const {
387   if (const PointerType *PT = getAs<PointerType>())
388     return PT->getPointeeType()->isVoidType();
389   return false;
390 }
391 
392 bool Type::isUnionType() const {
393   if (const RecordType *RT = getAs<RecordType>())
394     return RT->getDecl()->isUnion();
395   return false;
396 }
397 
398 bool Type::isComplexType() const {
399   if (const ComplexType *CT = dyn_cast<ComplexType>(CanonicalType))
400     return CT->getElementType()->isFloatingType();
401   return false;
402 }
403 
404 bool Type::isComplexIntegerType() const {
405   // Check for GCC complex integer extension.
406   return getAsComplexIntegerType();
407 }
408 
409 const ComplexType *Type::getAsComplexIntegerType() const {
410   if (const ComplexType *Complex = getAs<ComplexType>())
411     if (Complex->getElementType()->isIntegerType())
412       return Complex;
413   return nullptr;
414 }
415 
416 QualType Type::getPointeeType() const {
417   if (const PointerType *PT = getAs<PointerType>())
418     return PT->getPointeeType();
419   if (const ObjCObjectPointerType *OPT = getAs<ObjCObjectPointerType>())
420     return OPT->getPointeeType();
421   if (const BlockPointerType *BPT = getAs<BlockPointerType>())
422     return BPT->getPointeeType();
423   if (const ReferenceType *RT = getAs<ReferenceType>())
424     return RT->getPointeeType();
425   if (const MemberPointerType *MPT = getAs<MemberPointerType>())
426     return MPT->getPointeeType();
427   if (const DecayedType *DT = getAs<DecayedType>())
428     return DT->getPointeeType();
429   return QualType();
430 }
431 
432 const RecordType *Type::getAsStructureType() const {
433   // If this is directly a structure type, return it.
434   if (const RecordType *RT = dyn_cast<RecordType>(this)) {
435     if (RT->getDecl()->isStruct())
436       return RT;
437   }
438 
439   // If the canonical form of this type isn't the right kind, reject it.
440   if (const RecordType *RT = dyn_cast<RecordType>(CanonicalType)) {
441     if (!RT->getDecl()->isStruct())
442       return nullptr;
443 
444     // If this is a typedef for a structure type, strip the typedef off without
445     // losing all typedef information.
446     return cast<RecordType>(getUnqualifiedDesugaredType());
447   }
448   return nullptr;
449 }
450 
451 const RecordType *Type::getAsUnionType() const {
452   // If this is directly a union type, return it.
453   if (const RecordType *RT = dyn_cast<RecordType>(this)) {
454     if (RT->getDecl()->isUnion())
455       return RT;
456   }
457 
458   // If the canonical form of this type isn't the right kind, reject it.
459   if (const RecordType *RT = dyn_cast<RecordType>(CanonicalType)) {
460     if (!RT->getDecl()->isUnion())
461       return nullptr;
462 
463     // If this is a typedef for a union type, strip the typedef off without
464     // losing all typedef information.
465     return cast<RecordType>(getUnqualifiedDesugaredType());
466   }
467 
468   return nullptr;
469 }
470 
471 ObjCObjectType::ObjCObjectType(QualType Canonical, QualType Base,
472                                ObjCProtocolDecl * const *Protocols,
473                                unsigned NumProtocols)
474   : Type(ObjCObject, Canonical, false, false, false, false),
475     BaseType(Base)
476 {
477   ObjCObjectTypeBits.NumProtocols = NumProtocols;
478   assert(getNumProtocols() == NumProtocols &&
479          "bitfield overflow in protocol count");
480   if (NumProtocols)
481     memcpy(getProtocolStorage(), Protocols,
482            NumProtocols * sizeof(ObjCProtocolDecl*));
483 }
484 
485 const ObjCObjectType *Type::getAsObjCQualifiedInterfaceType() const {
486   // There is no sugar for ObjCObjectType's, just return the canonical
487   // type pointer if it is the right class.  There is no typedef information to
488   // return and these cannot be Address-space qualified.
489   if (const ObjCObjectType *T = getAs<ObjCObjectType>())
490     if (T->getNumProtocols() && T->getInterface())
491       return T;
492   return nullptr;
493 }
494 
495 bool Type::isObjCQualifiedInterfaceType() const {
496   return getAsObjCQualifiedInterfaceType() != nullptr;
497 }
498 
499 const ObjCObjectPointerType *Type::getAsObjCQualifiedIdType() const {
500   // There is no sugar for ObjCQualifiedIdType's, just return the canonical
501   // type pointer if it is the right class.
502   if (const ObjCObjectPointerType *OPT = getAs<ObjCObjectPointerType>()) {
503     if (OPT->isObjCQualifiedIdType())
504       return OPT;
505   }
506   return nullptr;
507 }
508 
509 const ObjCObjectPointerType *Type::getAsObjCQualifiedClassType() const {
510   // There is no sugar for ObjCQualifiedClassType's, just return the canonical
511   // type pointer if it is the right class.
512   if (const ObjCObjectPointerType *OPT = getAs<ObjCObjectPointerType>()) {
513     if (OPT->isObjCQualifiedClassType())
514       return OPT;
515   }
516   return nullptr;
517 }
518 
519 const ObjCObjectPointerType *Type::getAsObjCInterfacePointerType() const {
520   if (const ObjCObjectPointerType *OPT = getAs<ObjCObjectPointerType>()) {
521     if (OPT->getInterfaceType())
522       return OPT;
523   }
524   return nullptr;
525 }
526 
527 const CXXRecordDecl *Type::getPointeeCXXRecordDecl() const {
528   QualType PointeeType;
529   if (const PointerType *PT = getAs<PointerType>())
530     PointeeType = PT->getPointeeType();
531   else if (const ReferenceType *RT = getAs<ReferenceType>())
532     PointeeType = RT->getPointeeType();
533   else
534     return nullptr;
535 
536   if (const RecordType *RT = PointeeType->getAs<RecordType>())
537     return dyn_cast<CXXRecordDecl>(RT->getDecl());
538 
539   return nullptr;
540 }
541 
542 CXXRecordDecl *Type::getAsCXXRecordDecl() const {
543   if (const RecordType *RT = getAs<RecordType>())
544     return dyn_cast<CXXRecordDecl>(RT->getDecl());
545   else if (const InjectedClassNameType *Injected
546                                   = getAs<InjectedClassNameType>())
547     return Injected->getDecl();
548 
549   return nullptr;
550 }
551 
552 namespace {
553   class GetContainedAutoVisitor :
554     public TypeVisitor<GetContainedAutoVisitor, AutoType*> {
555   public:
556     using TypeVisitor<GetContainedAutoVisitor, AutoType*>::Visit;
557     AutoType *Visit(QualType T) {
558       if (T.isNull())
559         return nullptr;
560       return Visit(T.getTypePtr());
561     }
562 
563     // The 'auto' type itself.
564     AutoType *VisitAutoType(const AutoType *AT) {
565       return const_cast<AutoType*>(AT);
566     }
567 
568     // Only these types can contain the desired 'auto' type.
569     AutoType *VisitPointerType(const PointerType *T) {
570       return Visit(T->getPointeeType());
571     }
572     AutoType *VisitBlockPointerType(const BlockPointerType *T) {
573       return Visit(T->getPointeeType());
574     }
575     AutoType *VisitReferenceType(const ReferenceType *T) {
576       return Visit(T->getPointeeTypeAsWritten());
577     }
578     AutoType *VisitMemberPointerType(const MemberPointerType *T) {
579       return Visit(T->getPointeeType());
580     }
581     AutoType *VisitArrayType(const ArrayType *T) {
582       return Visit(T->getElementType());
583     }
584     AutoType *VisitDependentSizedExtVectorType(
585       const DependentSizedExtVectorType *T) {
586       return Visit(T->getElementType());
587     }
588     AutoType *VisitVectorType(const VectorType *T) {
589       return Visit(T->getElementType());
590     }
591     AutoType *VisitFunctionType(const FunctionType *T) {
592       return Visit(T->getReturnType());
593     }
594     AutoType *VisitParenType(const ParenType *T) {
595       return Visit(T->getInnerType());
596     }
597     AutoType *VisitAttributedType(const AttributedType *T) {
598       return Visit(T->getModifiedType());
599     }
600     AutoType *VisitAdjustedType(const AdjustedType *T) {
601       return Visit(T->getOriginalType());
602     }
603   };
604 }
605 
606 AutoType *Type::getContainedAutoType() const {
607   return GetContainedAutoVisitor().Visit(this);
608 }
609 
610 bool Type::hasIntegerRepresentation() const {
611   if (const VectorType *VT = dyn_cast<VectorType>(CanonicalType))
612     return VT->getElementType()->isIntegerType();
613   else
614     return isIntegerType();
615 }
616 
617 /// \brief Determine whether this type is an integral type.
618 ///
619 /// This routine determines whether the given type is an integral type per
620 /// C++ [basic.fundamental]p7. Although the C standard does not define the
621 /// term "integral type", it has a similar term "integer type", and in C++
622 /// the two terms are equivalent. However, C's "integer type" includes
623 /// enumeration types, while C++'s "integer type" does not. The \c ASTContext
624 /// parameter is used to determine whether we should be following the C or
625 /// C++ rules when determining whether this type is an integral/integer type.
626 ///
627 /// For cases where C permits "an integer type" and C++ permits "an integral
628 /// type", use this routine.
629 ///
630 /// For cases where C permits "an integer type" and C++ permits "an integral
631 /// or enumeration type", use \c isIntegralOrEnumerationType() instead.
632 ///
633 /// \param Ctx The context in which this type occurs.
634 ///
635 /// \returns true if the type is considered an integral type, false otherwise.
636 bool Type::isIntegralType(ASTContext &Ctx) const {
637   if (const BuiltinType *BT = dyn_cast<BuiltinType>(CanonicalType))
638     return BT->getKind() >= BuiltinType::Bool &&
639     BT->getKind() <= BuiltinType::Int128;
640 
641   if (!Ctx.getLangOpts().CPlusPlus)
642     if (const EnumType *ET = dyn_cast<EnumType>(CanonicalType))
643       return ET->getDecl()->isComplete(); // Complete enum types are integral in C.
644 
645   return false;
646 }
647 
648 
649 bool Type::isIntegralOrUnscopedEnumerationType() const {
650   if (const BuiltinType *BT = dyn_cast<BuiltinType>(CanonicalType))
651     return BT->getKind() >= BuiltinType::Bool &&
652            BT->getKind() <= BuiltinType::Int128;
653 
654   // Check for a complete enum type; incomplete enum types are not properly an
655   // enumeration type in the sense required here.
656   // C++0x: However, if the underlying type of the enum is fixed, it is
657   // considered complete.
658   if (const EnumType *ET = dyn_cast<EnumType>(CanonicalType))
659     return ET->getDecl()->isComplete() && !ET->getDecl()->isScoped();
660 
661   return false;
662 }
663 
664 
665 
666 bool Type::isCharType() const {
667   if (const BuiltinType *BT = dyn_cast<BuiltinType>(CanonicalType))
668     return BT->getKind() == BuiltinType::Char_U ||
669            BT->getKind() == BuiltinType::UChar ||
670            BT->getKind() == BuiltinType::Char_S ||
671            BT->getKind() == BuiltinType::SChar;
672   return false;
673 }
674 
675 bool Type::isWideCharType() const {
676   if (const BuiltinType *BT = dyn_cast<BuiltinType>(CanonicalType))
677     return BT->getKind() == BuiltinType::WChar_S ||
678            BT->getKind() == BuiltinType::WChar_U;
679   return false;
680 }
681 
682 bool Type::isChar16Type() const {
683   if (const BuiltinType *BT = dyn_cast<BuiltinType>(CanonicalType))
684     return BT->getKind() == BuiltinType::Char16;
685   return false;
686 }
687 
688 bool Type::isChar32Type() const {
689   if (const BuiltinType *BT = dyn_cast<BuiltinType>(CanonicalType))
690     return BT->getKind() == BuiltinType::Char32;
691   return false;
692 }
693 
694 /// \brief Determine whether this type is any of the built-in character
695 /// types.
696 bool Type::isAnyCharacterType() const {
697   const BuiltinType *BT = dyn_cast<BuiltinType>(CanonicalType);
698   if (!BT) return false;
699   switch (BT->getKind()) {
700   default: return false;
701   case BuiltinType::Char_U:
702   case BuiltinType::UChar:
703   case BuiltinType::WChar_U:
704   case BuiltinType::Char16:
705   case BuiltinType::Char32:
706   case BuiltinType::Char_S:
707   case BuiltinType::SChar:
708   case BuiltinType::WChar_S:
709     return true;
710   }
711 }
712 
713 /// isSignedIntegerType - Return true if this is an integer type that is
714 /// signed, according to C99 6.2.5p4 [char, signed char, short, int, long..],
715 /// an enum decl which has a signed representation
716 bool Type::isSignedIntegerType() const {
717   if (const BuiltinType *BT = dyn_cast<BuiltinType>(CanonicalType)) {
718     return BT->getKind() >= BuiltinType::Char_S &&
719            BT->getKind() <= BuiltinType::Int128;
720   }
721 
722   if (const EnumType *ET = dyn_cast<EnumType>(CanonicalType)) {
723     // Incomplete enum types are not treated as integer types.
724     // FIXME: In C++, enum types are never integer types.
725     if (ET->getDecl()->isComplete() && !ET->getDecl()->isScoped())
726       return ET->getDecl()->getIntegerType()->isSignedIntegerType();
727   }
728 
729   return false;
730 }
731 
732 bool Type::isSignedIntegerOrEnumerationType() const {
733   if (const BuiltinType *BT = dyn_cast<BuiltinType>(CanonicalType)) {
734     return BT->getKind() >= BuiltinType::Char_S &&
735     BT->getKind() <= BuiltinType::Int128;
736   }
737 
738   if (const EnumType *ET = dyn_cast<EnumType>(CanonicalType)) {
739     if (ET->getDecl()->isComplete())
740       return ET->getDecl()->getIntegerType()->isSignedIntegerType();
741   }
742 
743   return false;
744 }
745 
746 bool Type::hasSignedIntegerRepresentation() const {
747   if (const VectorType *VT = dyn_cast<VectorType>(CanonicalType))
748     return VT->getElementType()->isSignedIntegerOrEnumerationType();
749   else
750     return isSignedIntegerOrEnumerationType();
751 }
752 
753 /// isUnsignedIntegerType - Return true if this is an integer type that is
754 /// unsigned, according to C99 6.2.5p6 [which returns true for _Bool], an enum
755 /// decl which has an unsigned representation
756 bool Type::isUnsignedIntegerType() const {
757   if (const BuiltinType *BT = dyn_cast<BuiltinType>(CanonicalType)) {
758     return BT->getKind() >= BuiltinType::Bool &&
759            BT->getKind() <= BuiltinType::UInt128;
760   }
761 
762   if (const EnumType *ET = dyn_cast<EnumType>(CanonicalType)) {
763     // Incomplete enum types are not treated as integer types.
764     // FIXME: In C++, enum types are never integer types.
765     if (ET->getDecl()->isComplete() && !ET->getDecl()->isScoped())
766       return ET->getDecl()->getIntegerType()->isUnsignedIntegerType();
767   }
768 
769   return false;
770 }
771 
772 bool Type::isUnsignedIntegerOrEnumerationType() const {
773   if (const BuiltinType *BT = dyn_cast<BuiltinType>(CanonicalType)) {
774     return BT->getKind() >= BuiltinType::Bool &&
775     BT->getKind() <= BuiltinType::UInt128;
776   }
777 
778   if (const EnumType *ET = dyn_cast<EnumType>(CanonicalType)) {
779     if (ET->getDecl()->isComplete())
780       return ET->getDecl()->getIntegerType()->isUnsignedIntegerType();
781   }
782 
783   return false;
784 }
785 
786 bool Type::hasUnsignedIntegerRepresentation() const {
787   if (const VectorType *VT = dyn_cast<VectorType>(CanonicalType))
788     return VT->getElementType()->isUnsignedIntegerOrEnumerationType();
789   else
790     return isUnsignedIntegerOrEnumerationType();
791 }
792 
793 bool Type::isFloatingType() const {
794   if (const BuiltinType *BT = dyn_cast<BuiltinType>(CanonicalType))
795     return BT->getKind() >= BuiltinType::Half &&
796            BT->getKind() <= BuiltinType::LongDouble;
797   if (const ComplexType *CT = dyn_cast<ComplexType>(CanonicalType))
798     return CT->getElementType()->isFloatingType();
799   return false;
800 }
801 
802 bool Type::hasFloatingRepresentation() const {
803   if (const VectorType *VT = dyn_cast<VectorType>(CanonicalType))
804     return VT->getElementType()->isFloatingType();
805   else
806     return isFloatingType();
807 }
808 
809 bool Type::isRealFloatingType() const {
810   if (const BuiltinType *BT = dyn_cast<BuiltinType>(CanonicalType))
811     return BT->isFloatingPoint();
812   return false;
813 }
814 
815 bool Type::isRealType() const {
816   if (const BuiltinType *BT = dyn_cast<BuiltinType>(CanonicalType))
817     return BT->getKind() >= BuiltinType::Bool &&
818            BT->getKind() <= BuiltinType::LongDouble;
819   if (const EnumType *ET = dyn_cast<EnumType>(CanonicalType))
820       return ET->getDecl()->isComplete() && !ET->getDecl()->isScoped();
821   return false;
822 }
823 
824 bool Type::isArithmeticType() const {
825   if (const BuiltinType *BT = dyn_cast<BuiltinType>(CanonicalType))
826     return BT->getKind() >= BuiltinType::Bool &&
827            BT->getKind() <= BuiltinType::LongDouble;
828   if (const EnumType *ET = dyn_cast<EnumType>(CanonicalType))
829     // GCC allows forward declaration of enum types (forbid by C99 6.7.2.3p2).
830     // If a body isn't seen by the time we get here, return false.
831     //
832     // C++0x: Enumerations are not arithmetic types. For now, just return
833     // false for scoped enumerations since that will disable any
834     // unwanted implicit conversions.
835     return !ET->getDecl()->isScoped() && ET->getDecl()->isComplete();
836   return isa<ComplexType>(CanonicalType);
837 }
838 
839 Type::ScalarTypeKind Type::getScalarTypeKind() const {
840   assert(isScalarType());
841 
842   const Type *T = CanonicalType.getTypePtr();
843   if (const BuiltinType *BT = dyn_cast<BuiltinType>(T)) {
844     if (BT->getKind() == BuiltinType::Bool) return STK_Bool;
845     if (BT->getKind() == BuiltinType::NullPtr) return STK_CPointer;
846     if (BT->isInteger()) return STK_Integral;
847     if (BT->isFloatingPoint()) return STK_Floating;
848     llvm_unreachable("unknown scalar builtin type");
849   } else if (isa<PointerType>(T)) {
850     return STK_CPointer;
851   } else if (isa<BlockPointerType>(T)) {
852     return STK_BlockPointer;
853   } else if (isa<ObjCObjectPointerType>(T)) {
854     return STK_ObjCObjectPointer;
855   } else if (isa<MemberPointerType>(T)) {
856     return STK_MemberPointer;
857   } else if (isa<EnumType>(T)) {
858     assert(cast<EnumType>(T)->getDecl()->isComplete());
859     return STK_Integral;
860   } else if (const ComplexType *CT = dyn_cast<ComplexType>(T)) {
861     if (CT->getElementType()->isRealFloatingType())
862       return STK_FloatingComplex;
863     return STK_IntegralComplex;
864   }
865 
866   llvm_unreachable("unknown scalar type");
867 }
868 
869 /// \brief Determines whether the type is a C++ aggregate type or C
870 /// aggregate or union type.
871 ///
872 /// An aggregate type is an array or a class type (struct, union, or
873 /// class) that has no user-declared constructors, no private or
874 /// protected non-static data members, no base classes, and no virtual
875 /// functions (C++ [dcl.init.aggr]p1). The notion of an aggregate type
876 /// subsumes the notion of C aggregates (C99 6.2.5p21) because it also
877 /// includes union types.
878 bool Type::isAggregateType() const {
879   if (const RecordType *Record = dyn_cast<RecordType>(CanonicalType)) {
880     if (CXXRecordDecl *ClassDecl = dyn_cast<CXXRecordDecl>(Record->getDecl()))
881       return ClassDecl->isAggregate();
882 
883     return true;
884   }
885 
886   return isa<ArrayType>(CanonicalType);
887 }
888 
889 /// isConstantSizeType - Return true if this is not a variable sized type,
890 /// according to the rules of C99 6.7.5p3.  It is not legal to call this on
891 /// incomplete types or dependent types.
892 bool Type::isConstantSizeType() const {
893   assert(!isIncompleteType() && "This doesn't make sense for incomplete types");
894   assert(!isDependentType() && "This doesn't make sense for dependent types");
895   // The VAT must have a size, as it is known to be complete.
896   return !isa<VariableArrayType>(CanonicalType);
897 }
898 
899 /// isIncompleteType - Return true if this is an incomplete type (C99 6.2.5p1)
900 /// - a type that can describe objects, but which lacks information needed to
901 /// determine its size.
902 bool Type::isIncompleteType(NamedDecl **Def) const {
903   if (Def)
904     *Def = nullptr;
905 
906   switch (CanonicalType->getTypeClass()) {
907   default: return false;
908   case Builtin:
909     // Void is the only incomplete builtin type.  Per C99 6.2.5p19, it can never
910     // be completed.
911     return isVoidType();
912   case Enum: {
913     EnumDecl *EnumD = cast<EnumType>(CanonicalType)->getDecl();
914     if (Def)
915       *Def = EnumD;
916 
917     // An enumeration with fixed underlying type is complete (C++0x 7.2p3).
918     if (EnumD->isFixed())
919       return false;
920 
921     return !EnumD->isCompleteDefinition();
922   }
923   case Record: {
924     // A tagged type (struct/union/enum/class) is incomplete if the decl is a
925     // forward declaration, but not a full definition (C99 6.2.5p22).
926     RecordDecl *Rec = cast<RecordType>(CanonicalType)->getDecl();
927     if (Def)
928       *Def = Rec;
929     return !Rec->isCompleteDefinition();
930   }
931   case ConstantArray:
932     // An array is incomplete if its element type is incomplete
933     // (C++ [dcl.array]p1).
934     // We don't handle variable arrays (they're not allowed in C++) or
935     // dependent-sized arrays (dependent types are never treated as incomplete).
936     return cast<ArrayType>(CanonicalType)->getElementType()
937              ->isIncompleteType(Def);
938   case IncompleteArray:
939     // An array of unknown size is an incomplete type (C99 6.2.5p22).
940     return true;
941   case ObjCObject:
942     return cast<ObjCObjectType>(CanonicalType)->getBaseType()
943              ->isIncompleteType(Def);
944   case ObjCInterface: {
945     // ObjC interfaces are incomplete if they are @class, not @interface.
946     ObjCInterfaceDecl *Interface
947       = cast<ObjCInterfaceType>(CanonicalType)->getDecl();
948     if (Def)
949       *Def = Interface;
950     return !Interface->hasDefinition();
951   }
952   }
953 }
954 
955 bool QualType::isPODType(ASTContext &Context) const {
956   // C++11 has a more relaxed definition of POD.
957   if (Context.getLangOpts().CPlusPlus11)
958     return isCXX11PODType(Context);
959 
960   return isCXX98PODType(Context);
961 }
962 
963 bool QualType::isCXX98PODType(ASTContext &Context) const {
964   // The compiler shouldn't query this for incomplete types, but the user might.
965   // We return false for that case. Except for incomplete arrays of PODs, which
966   // are PODs according to the standard.
967   if (isNull())
968     return 0;
969 
970   if ((*this)->isIncompleteArrayType())
971     return Context.getBaseElementType(*this).isCXX98PODType(Context);
972 
973   if ((*this)->isIncompleteType())
974     return false;
975 
976   if (Context.getLangOpts().ObjCAutoRefCount) {
977     switch (getObjCLifetime()) {
978     case Qualifiers::OCL_ExplicitNone:
979       return true;
980 
981     case Qualifiers::OCL_Strong:
982     case Qualifiers::OCL_Weak:
983     case Qualifiers::OCL_Autoreleasing:
984       return false;
985 
986     case Qualifiers::OCL_None:
987       break;
988     }
989   }
990 
991   QualType CanonicalType = getTypePtr()->CanonicalType;
992   switch (CanonicalType->getTypeClass()) {
993     // Everything not explicitly mentioned is not POD.
994   default: return false;
995   case Type::VariableArray:
996   case Type::ConstantArray:
997     // IncompleteArray is handled above.
998     return Context.getBaseElementType(*this).isCXX98PODType(Context);
999 
1000   case Type::ObjCObjectPointer:
1001   case Type::BlockPointer:
1002   case Type::Builtin:
1003   case Type::Complex:
1004   case Type::Pointer:
1005   case Type::MemberPointer:
1006   case Type::Vector:
1007   case Type::ExtVector:
1008     return true;
1009 
1010   case Type::Enum:
1011     return true;
1012 
1013   case Type::Record:
1014     if (CXXRecordDecl *ClassDecl
1015           = dyn_cast<CXXRecordDecl>(cast<RecordType>(CanonicalType)->getDecl()))
1016       return ClassDecl->isPOD();
1017 
1018     // C struct/union is POD.
1019     return true;
1020   }
1021 }
1022 
1023 bool QualType::isTrivialType(ASTContext &Context) const {
1024   // The compiler shouldn't query this for incomplete types, but the user might.
1025   // We return false for that case. Except for incomplete arrays of PODs, which
1026   // are PODs according to the standard.
1027   if (isNull())
1028     return 0;
1029 
1030   if ((*this)->isArrayType())
1031     return Context.getBaseElementType(*this).isTrivialType(Context);
1032 
1033   // Return false for incomplete types after skipping any incomplete array
1034   // types which are expressly allowed by the standard and thus our API.
1035   if ((*this)->isIncompleteType())
1036     return false;
1037 
1038   if (Context.getLangOpts().ObjCAutoRefCount) {
1039     switch (getObjCLifetime()) {
1040     case Qualifiers::OCL_ExplicitNone:
1041       return true;
1042 
1043     case Qualifiers::OCL_Strong:
1044     case Qualifiers::OCL_Weak:
1045     case Qualifiers::OCL_Autoreleasing:
1046       return false;
1047 
1048     case Qualifiers::OCL_None:
1049       if ((*this)->isObjCLifetimeType())
1050         return false;
1051       break;
1052     }
1053   }
1054 
1055   QualType CanonicalType = getTypePtr()->CanonicalType;
1056   if (CanonicalType->isDependentType())
1057     return false;
1058 
1059   // C++0x [basic.types]p9:
1060   //   Scalar types, trivial class types, arrays of such types, and
1061   //   cv-qualified versions of these types are collectively called trivial
1062   //   types.
1063 
1064   // As an extension, Clang treats vector types as Scalar types.
1065   if (CanonicalType->isScalarType() || CanonicalType->isVectorType())
1066     return true;
1067   if (const RecordType *RT = CanonicalType->getAs<RecordType>()) {
1068     if (const CXXRecordDecl *ClassDecl =
1069         dyn_cast<CXXRecordDecl>(RT->getDecl())) {
1070       // C++11 [class]p6:
1071       //   A trivial class is a class that has a default constructor,
1072       //   has no non-trivial default constructors, and is trivially
1073       //   copyable.
1074       return ClassDecl->hasDefaultConstructor() &&
1075              !ClassDecl->hasNonTrivialDefaultConstructor() &&
1076              ClassDecl->isTriviallyCopyable();
1077     }
1078 
1079     return true;
1080   }
1081 
1082   // No other types can match.
1083   return false;
1084 }
1085 
1086 bool QualType::isTriviallyCopyableType(ASTContext &Context) const {
1087   if ((*this)->isArrayType())
1088     return Context.getBaseElementType(*this).isTrivialType(Context);
1089 
1090   if (Context.getLangOpts().ObjCAutoRefCount) {
1091     switch (getObjCLifetime()) {
1092     case Qualifiers::OCL_ExplicitNone:
1093       return true;
1094 
1095     case Qualifiers::OCL_Strong:
1096     case Qualifiers::OCL_Weak:
1097     case Qualifiers::OCL_Autoreleasing:
1098       return false;
1099 
1100     case Qualifiers::OCL_None:
1101       if ((*this)->isObjCLifetimeType())
1102         return false;
1103       break;
1104     }
1105   }
1106 
1107   // C++11 [basic.types]p9
1108   //   Scalar types, trivially copyable class types, arrays of such types, and
1109   //   non-volatile const-qualified versions of these types are collectively
1110   //   called trivially copyable types.
1111 
1112   QualType CanonicalType = getCanonicalType();
1113   if (CanonicalType->isDependentType())
1114     return false;
1115 
1116   if (CanonicalType.isVolatileQualified())
1117     return false;
1118 
1119   // Return false for incomplete types after skipping any incomplete array types
1120   // which are expressly allowed by the standard and thus our API.
1121   if (CanonicalType->isIncompleteType())
1122     return false;
1123 
1124   // As an extension, Clang treats vector types as Scalar types.
1125   if (CanonicalType->isScalarType() || CanonicalType->isVectorType())
1126     return true;
1127 
1128   if (const RecordType *RT = CanonicalType->getAs<RecordType>()) {
1129     if (const CXXRecordDecl *ClassDecl =
1130           dyn_cast<CXXRecordDecl>(RT->getDecl())) {
1131       if (!ClassDecl->isTriviallyCopyable()) return false;
1132     }
1133 
1134     return true;
1135   }
1136 
1137   // No other types can match.
1138   return false;
1139 }
1140 
1141 
1142 
1143 bool Type::isLiteralType(const ASTContext &Ctx) const {
1144   if (isDependentType())
1145     return false;
1146 
1147   // C++1y [basic.types]p10:
1148   //   A type is a literal type if it is:
1149   //   -- cv void; or
1150   if (Ctx.getLangOpts().CPlusPlus1y && isVoidType())
1151     return true;
1152 
1153   // C++11 [basic.types]p10:
1154   //   A type is a literal type if it is:
1155   //   [...]
1156   //   -- an array of literal type other than an array of runtime bound; or
1157   if (isVariableArrayType())
1158     return false;
1159   const Type *BaseTy = getBaseElementTypeUnsafe();
1160   assert(BaseTy && "NULL element type");
1161 
1162   // Return false for incomplete types after skipping any incomplete array
1163   // types; those are expressly allowed by the standard and thus our API.
1164   if (BaseTy->isIncompleteType())
1165     return false;
1166 
1167   // C++11 [basic.types]p10:
1168   //   A type is a literal type if it is:
1169   //    -- a scalar type; or
1170   // As an extension, Clang treats vector types and complex types as
1171   // literal types.
1172   if (BaseTy->isScalarType() || BaseTy->isVectorType() ||
1173       BaseTy->isAnyComplexType())
1174     return true;
1175   //    -- a reference type; or
1176   if (BaseTy->isReferenceType())
1177     return true;
1178   //    -- a class type that has all of the following properties:
1179   if (const RecordType *RT = BaseTy->getAs<RecordType>()) {
1180     //    -- a trivial destructor,
1181     //    -- every constructor call and full-expression in the
1182     //       brace-or-equal-initializers for non-static data members (if any)
1183     //       is a constant expression,
1184     //    -- it is an aggregate type or has at least one constexpr
1185     //       constructor or constructor template that is not a copy or move
1186     //       constructor, and
1187     //    -- all non-static data members and base classes of literal types
1188     //
1189     // We resolve DR1361 by ignoring the second bullet.
1190     if (const CXXRecordDecl *ClassDecl =
1191         dyn_cast<CXXRecordDecl>(RT->getDecl()))
1192       return ClassDecl->isLiteral();
1193 
1194     return true;
1195   }
1196 
1197   // We treat _Atomic T as a literal type if T is a literal type.
1198   if (const AtomicType *AT = BaseTy->getAs<AtomicType>())
1199     return AT->getValueType()->isLiteralType(Ctx);
1200 
1201   // If this type hasn't been deduced yet, then conservatively assume that
1202   // it'll work out to be a literal type.
1203   if (isa<AutoType>(BaseTy->getCanonicalTypeInternal()))
1204     return true;
1205 
1206   return false;
1207 }
1208 
1209 bool Type::isStandardLayoutType() const {
1210   if (isDependentType())
1211     return false;
1212 
1213   // C++0x [basic.types]p9:
1214   //   Scalar types, standard-layout class types, arrays of such types, and
1215   //   cv-qualified versions of these types are collectively called
1216   //   standard-layout types.
1217   const Type *BaseTy = getBaseElementTypeUnsafe();
1218   assert(BaseTy && "NULL element type");
1219 
1220   // Return false for incomplete types after skipping any incomplete array
1221   // types which are expressly allowed by the standard and thus our API.
1222   if (BaseTy->isIncompleteType())
1223     return false;
1224 
1225   // As an extension, Clang treats vector types as Scalar types.
1226   if (BaseTy->isScalarType() || BaseTy->isVectorType()) return true;
1227   if (const RecordType *RT = BaseTy->getAs<RecordType>()) {
1228     if (const CXXRecordDecl *ClassDecl =
1229         dyn_cast<CXXRecordDecl>(RT->getDecl()))
1230       if (!ClassDecl->isStandardLayout())
1231         return false;
1232 
1233     // Default to 'true' for non-C++ class types.
1234     // FIXME: This is a bit dubious, but plain C structs should trivially meet
1235     // all the requirements of standard layout classes.
1236     return true;
1237   }
1238 
1239   // No other types can match.
1240   return false;
1241 }
1242 
1243 // This is effectively the intersection of isTrivialType and
1244 // isStandardLayoutType. We implement it directly to avoid redundant
1245 // conversions from a type to a CXXRecordDecl.
1246 bool QualType::isCXX11PODType(ASTContext &Context) const {
1247   const Type *ty = getTypePtr();
1248   if (ty->isDependentType())
1249     return false;
1250 
1251   if (Context.getLangOpts().ObjCAutoRefCount) {
1252     switch (getObjCLifetime()) {
1253     case Qualifiers::OCL_ExplicitNone:
1254       return true;
1255 
1256     case Qualifiers::OCL_Strong:
1257     case Qualifiers::OCL_Weak:
1258     case Qualifiers::OCL_Autoreleasing:
1259       return false;
1260 
1261     case Qualifiers::OCL_None:
1262       break;
1263     }
1264   }
1265 
1266   // C++11 [basic.types]p9:
1267   //   Scalar types, POD classes, arrays of such types, and cv-qualified
1268   //   versions of these types are collectively called trivial types.
1269   const Type *BaseTy = ty->getBaseElementTypeUnsafe();
1270   assert(BaseTy && "NULL element type");
1271 
1272   // Return false for incomplete types after skipping any incomplete array
1273   // types which are expressly allowed by the standard and thus our API.
1274   if (BaseTy->isIncompleteType())
1275     return false;
1276 
1277   // As an extension, Clang treats vector types as Scalar types.
1278   if (BaseTy->isScalarType() || BaseTy->isVectorType()) return true;
1279   if (const RecordType *RT = BaseTy->getAs<RecordType>()) {
1280     if (const CXXRecordDecl *ClassDecl =
1281         dyn_cast<CXXRecordDecl>(RT->getDecl())) {
1282       // C++11 [class]p10:
1283       //   A POD struct is a non-union class that is both a trivial class [...]
1284       if (!ClassDecl->isTrivial()) return false;
1285 
1286       // C++11 [class]p10:
1287       //   A POD struct is a non-union class that is both a trivial class and
1288       //   a standard-layout class [...]
1289       if (!ClassDecl->isStandardLayout()) return false;
1290 
1291       // C++11 [class]p10:
1292       //   A POD struct is a non-union class that is both a trivial class and
1293       //   a standard-layout class, and has no non-static data members of type
1294       //   non-POD struct, non-POD union (or array of such types). [...]
1295       //
1296       // We don't directly query the recursive aspect as the requiremets for
1297       // both standard-layout classes and trivial classes apply recursively
1298       // already.
1299     }
1300 
1301     return true;
1302   }
1303 
1304   // No other types can match.
1305   return false;
1306 }
1307 
1308 bool Type::isPromotableIntegerType() const {
1309   if (const BuiltinType *BT = getAs<BuiltinType>())
1310     switch (BT->getKind()) {
1311     case BuiltinType::Bool:
1312     case BuiltinType::Char_S:
1313     case BuiltinType::Char_U:
1314     case BuiltinType::SChar:
1315     case BuiltinType::UChar:
1316     case BuiltinType::Short:
1317     case BuiltinType::UShort:
1318     case BuiltinType::WChar_S:
1319     case BuiltinType::WChar_U:
1320     case BuiltinType::Char16:
1321     case BuiltinType::Char32:
1322       return true;
1323     default:
1324       return false;
1325     }
1326 
1327   // Enumerated types are promotable to their compatible integer types
1328   // (C99 6.3.1.1) a.k.a. its underlying type (C++ [conv.prom]p2).
1329   if (const EnumType *ET = getAs<EnumType>()){
1330     if (this->isDependentType() || ET->getDecl()->getPromotionType().isNull()
1331         || ET->getDecl()->isScoped())
1332       return false;
1333 
1334     return true;
1335   }
1336 
1337   return false;
1338 }
1339 
1340 bool Type::isSpecifierType() const {
1341   // Note that this intentionally does not use the canonical type.
1342   switch (getTypeClass()) {
1343   case Builtin:
1344   case Record:
1345   case Enum:
1346   case Typedef:
1347   case Complex:
1348   case TypeOfExpr:
1349   case TypeOf:
1350   case TemplateTypeParm:
1351   case SubstTemplateTypeParm:
1352   case TemplateSpecialization:
1353   case Elaborated:
1354   case DependentName:
1355   case DependentTemplateSpecialization:
1356   case ObjCInterface:
1357   case ObjCObject:
1358   case ObjCObjectPointer: // FIXME: object pointers aren't really specifiers
1359     return true;
1360   default:
1361     return false;
1362   }
1363 }
1364 
1365 ElaboratedTypeKeyword
1366 TypeWithKeyword::getKeywordForTypeSpec(unsigned TypeSpec) {
1367   switch (TypeSpec) {
1368   default: return ETK_None;
1369   case TST_typename: return ETK_Typename;
1370   case TST_class: return ETK_Class;
1371   case TST_struct: return ETK_Struct;
1372   case TST_interface: return ETK_Interface;
1373   case TST_union: return ETK_Union;
1374   case TST_enum: return ETK_Enum;
1375   }
1376 }
1377 
1378 TagTypeKind
1379 TypeWithKeyword::getTagTypeKindForTypeSpec(unsigned TypeSpec) {
1380   switch(TypeSpec) {
1381   case TST_class: return TTK_Class;
1382   case TST_struct: return TTK_Struct;
1383   case TST_interface: return TTK_Interface;
1384   case TST_union: return TTK_Union;
1385   case TST_enum: return TTK_Enum;
1386   }
1387 
1388   llvm_unreachable("Type specifier is not a tag type kind.");
1389 }
1390 
1391 ElaboratedTypeKeyword
1392 TypeWithKeyword::getKeywordForTagTypeKind(TagTypeKind Kind) {
1393   switch (Kind) {
1394   case TTK_Class: return ETK_Class;
1395   case TTK_Struct: return ETK_Struct;
1396   case TTK_Interface: return ETK_Interface;
1397   case TTK_Union: return ETK_Union;
1398   case TTK_Enum: return ETK_Enum;
1399   }
1400   llvm_unreachable("Unknown tag type kind.");
1401 }
1402 
1403 TagTypeKind
1404 TypeWithKeyword::getTagTypeKindForKeyword(ElaboratedTypeKeyword Keyword) {
1405   switch (Keyword) {
1406   case ETK_Class: return TTK_Class;
1407   case ETK_Struct: return TTK_Struct;
1408   case ETK_Interface: return TTK_Interface;
1409   case ETK_Union: return TTK_Union;
1410   case ETK_Enum: return TTK_Enum;
1411   case ETK_None: // Fall through.
1412   case ETK_Typename:
1413     llvm_unreachable("Elaborated type keyword is not a tag type kind.");
1414   }
1415   llvm_unreachable("Unknown elaborated type keyword.");
1416 }
1417 
1418 bool
1419 TypeWithKeyword::KeywordIsTagTypeKind(ElaboratedTypeKeyword Keyword) {
1420   switch (Keyword) {
1421   case ETK_None:
1422   case ETK_Typename:
1423     return false;
1424   case ETK_Class:
1425   case ETK_Struct:
1426   case ETK_Interface:
1427   case ETK_Union:
1428   case ETK_Enum:
1429     return true;
1430   }
1431   llvm_unreachable("Unknown elaborated type keyword.");
1432 }
1433 
1434 StringRef TypeWithKeyword::getKeywordName(ElaboratedTypeKeyword Keyword) {
1435   switch (Keyword) {
1436   case ETK_None: return "";
1437   case ETK_Typename: return "typename";
1438   case ETK_Class:  return "class";
1439   case ETK_Struct: return "struct";
1440   case ETK_Interface: return "__interface";
1441   case ETK_Union:  return "union";
1442   case ETK_Enum:   return "enum";
1443   }
1444 
1445   llvm_unreachable("Unknown elaborated type keyword.");
1446 }
1447 
1448 DependentTemplateSpecializationType::DependentTemplateSpecializationType(
1449                          ElaboratedTypeKeyword Keyword,
1450                          NestedNameSpecifier *NNS, const IdentifierInfo *Name,
1451                          unsigned NumArgs, const TemplateArgument *Args,
1452                          QualType Canon)
1453   : TypeWithKeyword(Keyword, DependentTemplateSpecialization, Canon, true, true,
1454                     /*VariablyModified=*/false,
1455                     NNS && NNS->containsUnexpandedParameterPack()),
1456     NNS(NNS), Name(Name), NumArgs(NumArgs) {
1457   assert((!NNS || NNS->isDependent()) &&
1458          "DependentTemplateSpecializatonType requires dependent qualifier");
1459   for (unsigned I = 0; I != NumArgs; ++I) {
1460     if (Args[I].containsUnexpandedParameterPack())
1461       setContainsUnexpandedParameterPack();
1462 
1463     new (&getArgBuffer()[I]) TemplateArgument(Args[I]);
1464   }
1465 }
1466 
1467 void
1468 DependentTemplateSpecializationType::Profile(llvm::FoldingSetNodeID &ID,
1469                                              const ASTContext &Context,
1470                                              ElaboratedTypeKeyword Keyword,
1471                                              NestedNameSpecifier *Qualifier,
1472                                              const IdentifierInfo *Name,
1473                                              unsigned NumArgs,
1474                                              const TemplateArgument *Args) {
1475   ID.AddInteger(Keyword);
1476   ID.AddPointer(Qualifier);
1477   ID.AddPointer(Name);
1478   for (unsigned Idx = 0; Idx < NumArgs; ++Idx)
1479     Args[Idx].Profile(ID, Context);
1480 }
1481 
1482 bool Type::isElaboratedTypeSpecifier() const {
1483   ElaboratedTypeKeyword Keyword;
1484   if (const ElaboratedType *Elab = dyn_cast<ElaboratedType>(this))
1485     Keyword = Elab->getKeyword();
1486   else if (const DependentNameType *DepName = dyn_cast<DependentNameType>(this))
1487     Keyword = DepName->getKeyword();
1488   else if (const DependentTemplateSpecializationType *DepTST =
1489              dyn_cast<DependentTemplateSpecializationType>(this))
1490     Keyword = DepTST->getKeyword();
1491   else
1492     return false;
1493 
1494   return TypeWithKeyword::KeywordIsTagTypeKind(Keyword);
1495 }
1496 
1497 const char *Type::getTypeClassName() const {
1498   switch (TypeBits.TC) {
1499 #define ABSTRACT_TYPE(Derived, Base)
1500 #define TYPE(Derived, Base) case Derived: return #Derived;
1501 #include "clang/AST/TypeNodes.def"
1502   }
1503 
1504   llvm_unreachable("Invalid type class.");
1505 }
1506 
1507 StringRef BuiltinType::getName(const PrintingPolicy &Policy) const {
1508   switch (getKind()) {
1509   case Void:              return "void";
1510   case Bool:              return Policy.Bool ? "bool" : "_Bool";
1511   case Char_S:            return "char";
1512   case Char_U:            return "char";
1513   case SChar:             return "signed char";
1514   case Short:             return "short";
1515   case Int:               return "int";
1516   case Long:              return "long";
1517   case LongLong:          return "long long";
1518   case Int128:            return "__int128";
1519   case UChar:             return "unsigned char";
1520   case UShort:            return "unsigned short";
1521   case UInt:              return "unsigned int";
1522   case ULong:             return "unsigned long";
1523   case ULongLong:         return "unsigned long long";
1524   case UInt128:           return "unsigned __int128";
1525   case Half:              return Policy.Half ? "half" : "__fp16";
1526   case Float:             return "float";
1527   case Double:            return "double";
1528   case LongDouble:        return "long double";
1529   case WChar_S:
1530   case WChar_U:           return Policy.MSWChar ? "__wchar_t" : "wchar_t";
1531   case Char16:            return "char16_t";
1532   case Char32:            return "char32_t";
1533   case NullPtr:           return "nullptr_t";
1534   case Overload:          return "<overloaded function type>";
1535   case BoundMember:       return "<bound member function type>";
1536   case PseudoObject:      return "<pseudo-object type>";
1537   case Dependent:         return "<dependent type>";
1538   case UnknownAny:        return "<unknown type>";
1539   case ARCUnbridgedCast:  return "<ARC unbridged cast type>";
1540   case BuiltinFn:         return "<builtin fn type>";
1541   case ObjCId:            return "id";
1542   case ObjCClass:         return "Class";
1543   case ObjCSel:           return "SEL";
1544   case OCLImage1d:        return "image1d_t";
1545   case OCLImage1dArray:   return "image1d_array_t";
1546   case OCLImage1dBuffer:  return "image1d_buffer_t";
1547   case OCLImage2d:        return "image2d_t";
1548   case OCLImage2dArray:   return "image2d_array_t";
1549   case OCLImage3d:        return "image3d_t";
1550   case OCLSampler:        return "sampler_t";
1551   case OCLEvent:          return "event_t";
1552   }
1553 
1554   llvm_unreachable("Invalid builtin type.");
1555 }
1556 
1557 QualType QualType::getNonLValueExprType(const ASTContext &Context) const {
1558   if (const ReferenceType *RefType = getTypePtr()->getAs<ReferenceType>())
1559     return RefType->getPointeeType();
1560 
1561   // C++0x [basic.lval]:
1562   //   Class prvalues can have cv-qualified types; non-class prvalues always
1563   //   have cv-unqualified types.
1564   //
1565   // See also C99 6.3.2.1p2.
1566   if (!Context.getLangOpts().CPlusPlus ||
1567       (!getTypePtr()->isDependentType() && !getTypePtr()->isRecordType()))
1568     return getUnqualifiedType();
1569 
1570   return *this;
1571 }
1572 
1573 StringRef FunctionType::getNameForCallConv(CallingConv CC) {
1574   switch (CC) {
1575   case CC_C: return "cdecl";
1576   case CC_X86StdCall: return "stdcall";
1577   case CC_X86FastCall: return "fastcall";
1578   case CC_X86ThisCall: return "thiscall";
1579   case CC_X86Pascal: return "pascal";
1580   case CC_X86_64Win64: return "ms_abi";
1581   case CC_X86_64SysV: return "sysv_abi";
1582   case CC_AAPCS: return "aapcs";
1583   case CC_AAPCS_VFP: return "aapcs-vfp";
1584   case CC_PnaclCall: return "pnaclcall";
1585   case CC_IntelOclBicc: return "intel_ocl_bicc";
1586   }
1587 
1588   llvm_unreachable("Invalid calling convention.");
1589 }
1590 
1591 FunctionProtoType::FunctionProtoType(QualType result, ArrayRef<QualType> params,
1592                                      QualType canonical,
1593                                      const ExtProtoInfo &epi)
1594     : FunctionType(FunctionProto, result, epi.TypeQuals, canonical,
1595                    result->isDependentType(),
1596                    result->isInstantiationDependentType(),
1597                    result->isVariablyModifiedType(),
1598                    result->containsUnexpandedParameterPack(), epi.ExtInfo),
1599       NumParams(params.size()),
1600       NumExceptions(epi.ExceptionSpec.Exceptions.size()),
1601       ExceptionSpecType(epi.ExceptionSpec.Type),
1602       HasAnyConsumedParams(epi.ConsumedParameters != nullptr),
1603       Variadic(epi.Variadic), HasTrailingReturn(epi.HasTrailingReturn),
1604       RefQualifier(epi.RefQualifier) {
1605   assert(NumParams == params.size() && "function has too many parameters");
1606 
1607   // Fill in the trailing argument array.
1608   QualType *argSlot = reinterpret_cast<QualType*>(this+1);
1609   for (unsigned i = 0; i != NumParams; ++i) {
1610     if (params[i]->isDependentType())
1611       setDependent();
1612     else if (params[i]->isInstantiationDependentType())
1613       setInstantiationDependent();
1614 
1615     if (params[i]->containsUnexpandedParameterPack())
1616       setContainsUnexpandedParameterPack();
1617 
1618     argSlot[i] = params[i];
1619   }
1620 
1621   if (getExceptionSpecType() == EST_Dynamic) {
1622     // Fill in the exception array.
1623     QualType *exnSlot = argSlot + NumParams;
1624     unsigned I = 0;
1625     for (QualType ExceptionType : epi.ExceptionSpec.Exceptions) {
1626       if (ExceptionType->isDependentType())
1627         setDependent();
1628       else if (ExceptionType->isInstantiationDependentType())
1629         setInstantiationDependent();
1630 
1631       if (ExceptionType->containsUnexpandedParameterPack())
1632         setContainsUnexpandedParameterPack();
1633 
1634       exnSlot[I++] = ExceptionType;
1635     }
1636   } else if (getExceptionSpecType() == EST_ComputedNoexcept) {
1637     // Store the noexcept expression and context.
1638     Expr **noexSlot = reinterpret_cast<Expr **>(argSlot + NumParams);
1639     *noexSlot = epi.ExceptionSpec.NoexceptExpr;
1640 
1641     if (epi.ExceptionSpec.NoexceptExpr) {
1642       if (epi.ExceptionSpec.NoexceptExpr->isValueDependent()
1643           || epi.ExceptionSpec.NoexceptExpr->isTypeDependent())
1644         setDependent();
1645       else if (epi.ExceptionSpec.NoexceptExpr->isInstantiationDependent())
1646         setInstantiationDependent();
1647     }
1648   } else if (getExceptionSpecType() == EST_Uninstantiated) {
1649     // Store the function decl from which we will resolve our
1650     // exception specification.
1651     FunctionDecl **slot =
1652         reinterpret_cast<FunctionDecl **>(argSlot + NumParams);
1653     slot[0] = epi.ExceptionSpec.SourceDecl;
1654     slot[1] = epi.ExceptionSpec.SourceTemplate;
1655     // This exception specification doesn't make the type dependent, because
1656     // it's not instantiated as part of instantiating the type.
1657   } else if (getExceptionSpecType() == EST_Unevaluated) {
1658     // Store the function decl from which we will resolve our
1659     // exception specification.
1660     FunctionDecl **slot =
1661         reinterpret_cast<FunctionDecl **>(argSlot + NumParams);
1662     slot[0] = epi.ExceptionSpec.SourceDecl;
1663   }
1664 
1665   if (epi.ConsumedParameters) {
1666     bool *consumedParams = const_cast<bool *>(getConsumedParamsBuffer());
1667     for (unsigned i = 0; i != NumParams; ++i)
1668       consumedParams[i] = epi.ConsumedParameters[i];
1669   }
1670 }
1671 
1672 FunctionProtoType::NoexceptResult
1673 FunctionProtoType::getNoexceptSpec(const ASTContext &ctx) const {
1674   ExceptionSpecificationType est = getExceptionSpecType();
1675   if (est == EST_BasicNoexcept)
1676     return NR_Nothrow;
1677 
1678   if (est != EST_ComputedNoexcept)
1679     return NR_NoNoexcept;
1680 
1681   Expr *noexceptExpr = getNoexceptExpr();
1682   if (!noexceptExpr)
1683     return NR_BadNoexcept;
1684   if (noexceptExpr->isValueDependent())
1685     return NR_Dependent;
1686 
1687   llvm::APSInt value;
1688   bool isICE = noexceptExpr->isIntegerConstantExpr(value, ctx, nullptr,
1689                                                    /*evaluated*/false);
1690   (void)isICE;
1691   assert(isICE && "AST should not contain bad noexcept expressions.");
1692 
1693   return value.getBoolValue() ? NR_Nothrow : NR_Throw;
1694 }
1695 
1696 bool FunctionProtoType::isNothrow(const ASTContext &Ctx,
1697                                   bool ResultIfDependent) const {
1698   ExceptionSpecificationType EST = getExceptionSpecType();
1699   assert(EST != EST_Unevaluated && EST != EST_Uninstantiated);
1700   if (EST == EST_DynamicNone || EST == EST_BasicNoexcept)
1701     return true;
1702 
1703   if (EST == EST_Dynamic && ResultIfDependent == true) {
1704     // A dynamic exception specification is throwing unless every exception
1705     // type is an (unexpanded) pack expansion type.
1706     for (unsigned I = 0, N = NumExceptions; I != N; ++I)
1707       if (!getExceptionType(I)->getAs<PackExpansionType>())
1708         return false;
1709     return ResultIfDependent;
1710   }
1711 
1712   if (EST != EST_ComputedNoexcept)
1713     return false;
1714 
1715   NoexceptResult NR = getNoexceptSpec(Ctx);
1716   if (NR == NR_Dependent)
1717     return ResultIfDependent;
1718   return NR == NR_Nothrow;
1719 }
1720 
1721 bool FunctionProtoType::isTemplateVariadic() const {
1722   for (unsigned ArgIdx = getNumParams(); ArgIdx; --ArgIdx)
1723     if (isa<PackExpansionType>(getParamType(ArgIdx - 1)))
1724       return true;
1725 
1726   return false;
1727 }
1728 
1729 void FunctionProtoType::Profile(llvm::FoldingSetNodeID &ID, QualType Result,
1730                                 const QualType *ArgTys, unsigned NumParams,
1731                                 const ExtProtoInfo &epi,
1732                                 const ASTContext &Context) {
1733 
1734   // We have to be careful not to get ambiguous profile encodings.
1735   // Note that valid type pointers are never ambiguous with anything else.
1736   //
1737   // The encoding grammar begins:
1738   //      type type* bool int bool
1739   // If that final bool is true, then there is a section for the EH spec:
1740   //      bool type*
1741   // This is followed by an optional "consumed argument" section of the
1742   // same length as the first type sequence:
1743   //      bool*
1744   // Finally, we have the ext info and trailing return type flag:
1745   //      int bool
1746   //
1747   // There is no ambiguity between the consumed arguments and an empty EH
1748   // spec because of the leading 'bool' which unambiguously indicates
1749   // whether the following bool is the EH spec or part of the arguments.
1750 
1751   ID.AddPointer(Result.getAsOpaquePtr());
1752   for (unsigned i = 0; i != NumParams; ++i)
1753     ID.AddPointer(ArgTys[i].getAsOpaquePtr());
1754   // This method is relatively performance sensitive, so as a performance
1755   // shortcut, use one AddInteger call instead of four for the next four
1756   // fields.
1757   assert(!(unsigned(epi.Variadic) & ~1) &&
1758          !(unsigned(epi.TypeQuals) & ~255) &&
1759          !(unsigned(epi.RefQualifier) & ~3) &&
1760          !(unsigned(epi.ExceptionSpec.Type) & ~7) &&
1761          "Values larger than expected.");
1762   ID.AddInteger(unsigned(epi.Variadic) +
1763                 (epi.TypeQuals << 1) +
1764                 (epi.RefQualifier << 9) +
1765                 (epi.ExceptionSpec.Type << 11));
1766   if (epi.ExceptionSpec.Type == EST_Dynamic) {
1767     for (QualType Ex : epi.ExceptionSpec.Exceptions)
1768       ID.AddPointer(Ex.getAsOpaquePtr());
1769   } else if (epi.ExceptionSpec.Type == EST_ComputedNoexcept &&
1770              epi.ExceptionSpec.NoexceptExpr) {
1771     epi.ExceptionSpec.NoexceptExpr->Profile(ID, Context, false);
1772   } else if (epi.ExceptionSpec.Type == EST_Uninstantiated ||
1773              epi.ExceptionSpec.Type == EST_Unevaluated) {
1774     ID.AddPointer(epi.ExceptionSpec.SourceDecl->getCanonicalDecl());
1775   }
1776   if (epi.ConsumedParameters) {
1777     for (unsigned i = 0; i != NumParams; ++i)
1778       ID.AddBoolean(epi.ConsumedParameters[i]);
1779   }
1780   epi.ExtInfo.Profile(ID);
1781   ID.AddBoolean(epi.HasTrailingReturn);
1782 }
1783 
1784 void FunctionProtoType::Profile(llvm::FoldingSetNodeID &ID,
1785                                 const ASTContext &Ctx) {
1786   Profile(ID, getReturnType(), param_type_begin(), NumParams, getExtProtoInfo(),
1787           Ctx);
1788 }
1789 
1790 QualType TypedefType::desugar() const {
1791   return getDecl()->getUnderlyingType();
1792 }
1793 
1794 TypeOfExprType::TypeOfExprType(Expr *E, QualType can)
1795   : Type(TypeOfExpr, can, E->isTypeDependent(),
1796          E->isInstantiationDependent(),
1797          E->getType()->isVariablyModifiedType(),
1798          E->containsUnexpandedParameterPack()),
1799     TOExpr(E) {
1800 }
1801 
1802 bool TypeOfExprType::isSugared() const {
1803   return !TOExpr->isTypeDependent();
1804 }
1805 
1806 QualType TypeOfExprType::desugar() const {
1807   if (isSugared())
1808     return getUnderlyingExpr()->getType();
1809 
1810   return QualType(this, 0);
1811 }
1812 
1813 void DependentTypeOfExprType::Profile(llvm::FoldingSetNodeID &ID,
1814                                       const ASTContext &Context, Expr *E) {
1815   E->Profile(ID, Context, true);
1816 }
1817 
1818 DecltypeType::DecltypeType(Expr *E, QualType underlyingType, QualType can)
1819   // C++11 [temp.type]p2: "If an expression e involves a template parameter,
1820   // decltype(e) denotes a unique dependent type." Hence a decltype type is
1821   // type-dependent even if its expression is only instantiation-dependent.
1822   : Type(Decltype, can, E->isInstantiationDependent(),
1823          E->isInstantiationDependent(),
1824          E->getType()->isVariablyModifiedType(),
1825          E->containsUnexpandedParameterPack()),
1826     E(E),
1827   UnderlyingType(underlyingType) {
1828 }
1829 
1830 bool DecltypeType::isSugared() const { return !E->isInstantiationDependent(); }
1831 
1832 QualType DecltypeType::desugar() const {
1833   if (isSugared())
1834     return getUnderlyingType();
1835 
1836   return QualType(this, 0);
1837 }
1838 
1839 DependentDecltypeType::DependentDecltypeType(const ASTContext &Context, Expr *E)
1840   : DecltypeType(E, Context.DependentTy), Context(Context) { }
1841 
1842 void DependentDecltypeType::Profile(llvm::FoldingSetNodeID &ID,
1843                                     const ASTContext &Context, Expr *E) {
1844   E->Profile(ID, Context, true);
1845 }
1846 
1847 TagType::TagType(TypeClass TC, const TagDecl *D, QualType can)
1848   : Type(TC, can, D->isDependentType(),
1849          /*InstantiationDependent=*/D->isDependentType(),
1850          /*VariablyModified=*/false,
1851          /*ContainsUnexpandedParameterPack=*/false),
1852     decl(const_cast<TagDecl*>(D)) {}
1853 
1854 static TagDecl *getInterestingTagDecl(TagDecl *decl) {
1855   for (auto I : decl->redecls()) {
1856     if (I->isCompleteDefinition() || I->isBeingDefined())
1857       return I;
1858   }
1859   // If there's no definition (not even in progress), return what we have.
1860   return decl;
1861 }
1862 
1863 UnaryTransformType::UnaryTransformType(QualType BaseType,
1864                                        QualType UnderlyingType,
1865                                        UTTKind UKind,
1866                                        QualType CanonicalType)
1867   : Type(UnaryTransform, CanonicalType, UnderlyingType->isDependentType(),
1868          UnderlyingType->isInstantiationDependentType(),
1869          UnderlyingType->isVariablyModifiedType(),
1870          BaseType->containsUnexpandedParameterPack())
1871   , BaseType(BaseType), UnderlyingType(UnderlyingType), UKind(UKind)
1872 {}
1873 
1874 TagDecl *TagType::getDecl() const {
1875   return getInterestingTagDecl(decl);
1876 }
1877 
1878 bool TagType::isBeingDefined() const {
1879   return getDecl()->isBeingDefined();
1880 }
1881 
1882 bool AttributedType::isMSTypeSpec() const {
1883   switch (getAttrKind()) {
1884   default:  return false;
1885   case attr_ptr32:
1886   case attr_ptr64:
1887   case attr_sptr:
1888   case attr_uptr:
1889     return true;
1890   }
1891   llvm_unreachable("invalid attr kind");
1892 }
1893 
1894 bool AttributedType::isCallingConv() const {
1895   switch (getAttrKind()) {
1896   case attr_ptr32:
1897   case attr_ptr64:
1898   case attr_sptr:
1899   case attr_uptr:
1900   case attr_address_space:
1901   case attr_regparm:
1902   case attr_vector_size:
1903   case attr_neon_vector_type:
1904   case attr_neon_polyvector_type:
1905   case attr_objc_gc:
1906   case attr_objc_ownership:
1907   case attr_noreturn:
1908       return false;
1909   case attr_pcs:
1910   case attr_pcs_vfp:
1911   case attr_cdecl:
1912   case attr_fastcall:
1913   case attr_stdcall:
1914   case attr_thiscall:
1915   case attr_pascal:
1916   case attr_ms_abi:
1917   case attr_sysv_abi:
1918   case attr_pnaclcall:
1919   case attr_inteloclbicc:
1920     return true;
1921   }
1922   llvm_unreachable("invalid attr kind");
1923 }
1924 
1925 CXXRecordDecl *InjectedClassNameType::getDecl() const {
1926   return cast<CXXRecordDecl>(getInterestingTagDecl(Decl));
1927 }
1928 
1929 IdentifierInfo *TemplateTypeParmType::getIdentifier() const {
1930   return isCanonicalUnqualified() ? nullptr : getDecl()->getIdentifier();
1931 }
1932 
1933 SubstTemplateTypeParmPackType::
1934 SubstTemplateTypeParmPackType(const TemplateTypeParmType *Param,
1935                               QualType Canon,
1936                               const TemplateArgument &ArgPack)
1937   : Type(SubstTemplateTypeParmPack, Canon, true, true, false, true),
1938     Replaced(Param),
1939     Arguments(ArgPack.pack_begin()), NumArguments(ArgPack.pack_size())
1940 {
1941 }
1942 
1943 TemplateArgument SubstTemplateTypeParmPackType::getArgumentPack() const {
1944   return TemplateArgument(Arguments, NumArguments);
1945 }
1946 
1947 void SubstTemplateTypeParmPackType::Profile(llvm::FoldingSetNodeID &ID) {
1948   Profile(ID, getReplacedParameter(), getArgumentPack());
1949 }
1950 
1951 void SubstTemplateTypeParmPackType::Profile(llvm::FoldingSetNodeID &ID,
1952                                            const TemplateTypeParmType *Replaced,
1953                                             const TemplateArgument &ArgPack) {
1954   ID.AddPointer(Replaced);
1955   ID.AddInteger(ArgPack.pack_size());
1956   for (const auto &P : ArgPack.pack_elements())
1957     ID.AddPointer(P.getAsType().getAsOpaquePtr());
1958 }
1959 
1960 bool TemplateSpecializationType::
1961 anyDependentTemplateArguments(const TemplateArgumentListInfo &Args,
1962                               bool &InstantiationDependent) {
1963   return anyDependentTemplateArguments(Args.getArgumentArray(), Args.size(),
1964                                        InstantiationDependent);
1965 }
1966 
1967 bool TemplateSpecializationType::
1968 anyDependentTemplateArguments(const TemplateArgumentLoc *Args, unsigned N,
1969                               bool &InstantiationDependent) {
1970   for (unsigned i = 0; i != N; ++i) {
1971     if (Args[i].getArgument().isDependent()) {
1972       InstantiationDependent = true;
1973       return true;
1974     }
1975 
1976     if (Args[i].getArgument().isInstantiationDependent())
1977       InstantiationDependent = true;
1978   }
1979   return false;
1980 }
1981 
1982 #ifndef NDEBUG
1983 static bool
1984 anyDependentTemplateArguments(const TemplateArgument *Args, unsigned N,
1985                               bool &InstantiationDependent) {
1986   for (unsigned i = 0; i != N; ++i) {
1987     if (Args[i].isDependent()) {
1988       InstantiationDependent = true;
1989       return true;
1990     }
1991 
1992     if (Args[i].isInstantiationDependent())
1993       InstantiationDependent = true;
1994   }
1995   return false;
1996 }
1997 #endif
1998 
1999 TemplateSpecializationType::
2000 TemplateSpecializationType(TemplateName T,
2001                            const TemplateArgument *Args, unsigned NumArgs,
2002                            QualType Canon, QualType AliasedType)
2003   : Type(TemplateSpecialization,
2004          Canon.isNull()? QualType(this, 0) : Canon,
2005          Canon.isNull()? T.isDependent() : Canon->isDependentType(),
2006          Canon.isNull()? T.isDependent()
2007                        : Canon->isInstantiationDependentType(),
2008          false,
2009          T.containsUnexpandedParameterPack()),
2010     Template(T), NumArgs(NumArgs), TypeAlias(!AliasedType.isNull()) {
2011   assert(!T.getAsDependentTemplateName() &&
2012          "Use DependentTemplateSpecializationType for dependent template-name");
2013   assert((T.getKind() == TemplateName::Template ||
2014           T.getKind() == TemplateName::SubstTemplateTemplateParm ||
2015           T.getKind() == TemplateName::SubstTemplateTemplateParmPack) &&
2016          "Unexpected template name for TemplateSpecializationType");
2017   bool InstantiationDependent;
2018   (void)InstantiationDependent;
2019   assert((!Canon.isNull() ||
2020           T.isDependent() ||
2021           ::anyDependentTemplateArguments(Args, NumArgs,
2022                                           InstantiationDependent)) &&
2023          "No canonical type for non-dependent class template specialization");
2024 
2025   TemplateArgument *TemplateArgs
2026     = reinterpret_cast<TemplateArgument *>(this + 1);
2027   for (unsigned Arg = 0; Arg < NumArgs; ++Arg) {
2028     // Update dependent and variably-modified bits.
2029     // If the canonical type exists and is non-dependent, the template
2030     // specialization type can be non-dependent even if one of the type
2031     // arguments is. Given:
2032     //   template<typename T> using U = int;
2033     // U<T> is always non-dependent, irrespective of the type T.
2034     // However, U<Ts> contains an unexpanded parameter pack, even though
2035     // its expansion (and thus its desugared type) doesn't.
2036     if (Canon.isNull() && Args[Arg].isDependent())
2037       setDependent();
2038     else if (Args[Arg].isInstantiationDependent())
2039       setInstantiationDependent();
2040 
2041     if (Args[Arg].getKind() == TemplateArgument::Type &&
2042         Args[Arg].getAsType()->isVariablyModifiedType())
2043       setVariablyModified();
2044     if (Args[Arg].containsUnexpandedParameterPack())
2045       setContainsUnexpandedParameterPack();
2046 
2047     new (&TemplateArgs[Arg]) TemplateArgument(Args[Arg]);
2048   }
2049 
2050   // Store the aliased type if this is a type alias template specialization.
2051   if (TypeAlias) {
2052     TemplateArgument *Begin = reinterpret_cast<TemplateArgument *>(this + 1);
2053     *reinterpret_cast<QualType*>(Begin + getNumArgs()) = AliasedType;
2054   }
2055 }
2056 
2057 void
2058 TemplateSpecializationType::Profile(llvm::FoldingSetNodeID &ID,
2059                                     TemplateName T,
2060                                     const TemplateArgument *Args,
2061                                     unsigned NumArgs,
2062                                     const ASTContext &Context) {
2063   T.Profile(ID);
2064   for (unsigned Idx = 0; Idx < NumArgs; ++Idx)
2065     Args[Idx].Profile(ID, Context);
2066 }
2067 
2068 QualType
2069 QualifierCollector::apply(const ASTContext &Context, QualType QT) const {
2070   if (!hasNonFastQualifiers())
2071     return QT.withFastQualifiers(getFastQualifiers());
2072 
2073   return Context.getQualifiedType(QT, *this);
2074 }
2075 
2076 QualType
2077 QualifierCollector::apply(const ASTContext &Context, const Type *T) const {
2078   if (!hasNonFastQualifiers())
2079     return QualType(T, getFastQualifiers());
2080 
2081   return Context.getQualifiedType(T, *this);
2082 }
2083 
2084 void ObjCObjectTypeImpl::Profile(llvm::FoldingSetNodeID &ID,
2085                                  QualType BaseType,
2086                                  ObjCProtocolDecl * const *Protocols,
2087                                  unsigned NumProtocols) {
2088   ID.AddPointer(BaseType.getAsOpaquePtr());
2089   for (unsigned i = 0; i != NumProtocols; i++)
2090     ID.AddPointer(Protocols[i]);
2091 }
2092 
2093 void ObjCObjectTypeImpl::Profile(llvm::FoldingSetNodeID &ID) {
2094   Profile(ID, getBaseType(), qual_begin(), getNumProtocols());
2095 }
2096 
2097 namespace {
2098 
2099 /// \brief The cached properties of a type.
2100 class CachedProperties {
2101   Linkage L;
2102   bool local;
2103 
2104 public:
2105   CachedProperties(Linkage L, bool local) : L(L), local(local) {}
2106 
2107   Linkage getLinkage() const { return L; }
2108   bool hasLocalOrUnnamedType() const { return local; }
2109 
2110   friend CachedProperties merge(CachedProperties L, CachedProperties R) {
2111     Linkage MergedLinkage = minLinkage(L.L, R.L);
2112     return CachedProperties(MergedLinkage,
2113                          L.hasLocalOrUnnamedType() | R.hasLocalOrUnnamedType());
2114   }
2115 };
2116 }
2117 
2118 static CachedProperties computeCachedProperties(const Type *T);
2119 
2120 namespace clang {
2121 /// The type-property cache.  This is templated so as to be
2122 /// instantiated at an internal type to prevent unnecessary symbol
2123 /// leakage.
2124 template <class Private> class TypePropertyCache {
2125 public:
2126   static CachedProperties get(QualType T) {
2127     return get(T.getTypePtr());
2128   }
2129 
2130   static CachedProperties get(const Type *T) {
2131     ensure(T);
2132     return CachedProperties(T->TypeBits.getLinkage(),
2133                             T->TypeBits.hasLocalOrUnnamedType());
2134   }
2135 
2136   static void ensure(const Type *T) {
2137     // If the cache is valid, we're okay.
2138     if (T->TypeBits.isCacheValid()) return;
2139 
2140     // If this type is non-canonical, ask its canonical type for the
2141     // relevant information.
2142     if (!T->isCanonicalUnqualified()) {
2143       const Type *CT = T->getCanonicalTypeInternal().getTypePtr();
2144       ensure(CT);
2145       T->TypeBits.CacheValid = true;
2146       T->TypeBits.CachedLinkage = CT->TypeBits.CachedLinkage;
2147       T->TypeBits.CachedLocalOrUnnamed = CT->TypeBits.CachedLocalOrUnnamed;
2148       return;
2149     }
2150 
2151     // Compute the cached properties and then set the cache.
2152     CachedProperties Result = computeCachedProperties(T);
2153     T->TypeBits.CacheValid = true;
2154     T->TypeBits.CachedLinkage = Result.getLinkage();
2155     T->TypeBits.CachedLocalOrUnnamed = Result.hasLocalOrUnnamedType();
2156   }
2157 };
2158 }
2159 
2160 // Instantiate the friend template at a private class.  In a
2161 // reasonable implementation, these symbols will be internal.
2162 // It is terrible that this is the best way to accomplish this.
2163 namespace { class Private {}; }
2164 typedef TypePropertyCache<Private> Cache;
2165 
2166 static CachedProperties computeCachedProperties(const Type *T) {
2167   switch (T->getTypeClass()) {
2168 #define TYPE(Class,Base)
2169 #define NON_CANONICAL_TYPE(Class,Base) case Type::Class:
2170 #include "clang/AST/TypeNodes.def"
2171     llvm_unreachable("didn't expect a non-canonical type here");
2172 
2173 #define TYPE(Class,Base)
2174 #define DEPENDENT_TYPE(Class,Base) case Type::Class:
2175 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class,Base) case Type::Class:
2176 #include "clang/AST/TypeNodes.def"
2177     // Treat instantiation-dependent types as external.
2178     assert(T->isInstantiationDependentType());
2179     return CachedProperties(ExternalLinkage, false);
2180 
2181   case Type::Auto:
2182     // Give non-deduced 'auto' types external linkage. We should only see them
2183     // here in error recovery.
2184     return CachedProperties(ExternalLinkage, false);
2185 
2186   case Type::Builtin:
2187     // C++ [basic.link]p8:
2188     //   A type is said to have linkage if and only if:
2189     //     - it is a fundamental type (3.9.1); or
2190     return CachedProperties(ExternalLinkage, false);
2191 
2192   case Type::Record:
2193   case Type::Enum: {
2194     const TagDecl *Tag = cast<TagType>(T)->getDecl();
2195 
2196     // C++ [basic.link]p8:
2197     //     - it is a class or enumeration type that is named (or has a name
2198     //       for linkage purposes (7.1.3)) and the name has linkage; or
2199     //     -  it is a specialization of a class template (14); or
2200     Linkage L = Tag->getLinkageInternal();
2201     bool IsLocalOrUnnamed =
2202       Tag->getDeclContext()->isFunctionOrMethod() ||
2203       !Tag->hasNameForLinkage();
2204     return CachedProperties(L, IsLocalOrUnnamed);
2205   }
2206 
2207     // C++ [basic.link]p8:
2208     //   - it is a compound type (3.9.2) other than a class or enumeration,
2209     //     compounded exclusively from types that have linkage; or
2210   case Type::Complex:
2211     return Cache::get(cast<ComplexType>(T)->getElementType());
2212   case Type::Pointer:
2213     return Cache::get(cast<PointerType>(T)->getPointeeType());
2214   case Type::BlockPointer:
2215     return Cache::get(cast<BlockPointerType>(T)->getPointeeType());
2216   case Type::LValueReference:
2217   case Type::RValueReference:
2218     return Cache::get(cast<ReferenceType>(T)->getPointeeType());
2219   case Type::MemberPointer: {
2220     const MemberPointerType *MPT = cast<MemberPointerType>(T);
2221     return merge(Cache::get(MPT->getClass()),
2222                  Cache::get(MPT->getPointeeType()));
2223   }
2224   case Type::ConstantArray:
2225   case Type::IncompleteArray:
2226   case Type::VariableArray:
2227     return Cache::get(cast<ArrayType>(T)->getElementType());
2228   case Type::Vector:
2229   case Type::ExtVector:
2230     return Cache::get(cast<VectorType>(T)->getElementType());
2231   case Type::FunctionNoProto:
2232     return Cache::get(cast<FunctionType>(T)->getReturnType());
2233   case Type::FunctionProto: {
2234     const FunctionProtoType *FPT = cast<FunctionProtoType>(T);
2235     CachedProperties result = Cache::get(FPT->getReturnType());
2236     for (const auto &ai : FPT->param_types())
2237       result = merge(result, Cache::get(ai));
2238     return result;
2239   }
2240   case Type::ObjCInterface: {
2241     Linkage L = cast<ObjCInterfaceType>(T)->getDecl()->getLinkageInternal();
2242     return CachedProperties(L, false);
2243   }
2244   case Type::ObjCObject:
2245     return Cache::get(cast<ObjCObjectType>(T)->getBaseType());
2246   case Type::ObjCObjectPointer:
2247     return Cache::get(cast<ObjCObjectPointerType>(T)->getPointeeType());
2248   case Type::Atomic:
2249     return Cache::get(cast<AtomicType>(T)->getValueType());
2250   }
2251 
2252   llvm_unreachable("unhandled type class");
2253 }
2254 
2255 /// \brief Determine the linkage of this type.
2256 Linkage Type::getLinkage() const {
2257   Cache::ensure(this);
2258   return TypeBits.getLinkage();
2259 }
2260 
2261 bool Type::hasUnnamedOrLocalType() const {
2262   Cache::ensure(this);
2263   return TypeBits.hasLocalOrUnnamedType();
2264 }
2265 
2266 static LinkageInfo computeLinkageInfo(QualType T);
2267 
2268 static LinkageInfo computeLinkageInfo(const Type *T) {
2269   switch (T->getTypeClass()) {
2270 #define TYPE(Class,Base)
2271 #define NON_CANONICAL_TYPE(Class,Base) case Type::Class:
2272 #include "clang/AST/TypeNodes.def"
2273     llvm_unreachable("didn't expect a non-canonical type here");
2274 
2275 #define TYPE(Class,Base)
2276 #define DEPENDENT_TYPE(Class,Base) case Type::Class:
2277 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class,Base) case Type::Class:
2278 #include "clang/AST/TypeNodes.def"
2279     // Treat instantiation-dependent types as external.
2280     assert(T->isInstantiationDependentType());
2281     return LinkageInfo::external();
2282 
2283   case Type::Builtin:
2284     return LinkageInfo::external();
2285 
2286   case Type::Auto:
2287     return LinkageInfo::external();
2288 
2289   case Type::Record:
2290   case Type::Enum:
2291     return cast<TagType>(T)->getDecl()->getLinkageAndVisibility();
2292 
2293   case Type::Complex:
2294     return computeLinkageInfo(cast<ComplexType>(T)->getElementType());
2295   case Type::Pointer:
2296     return computeLinkageInfo(cast<PointerType>(T)->getPointeeType());
2297   case Type::BlockPointer:
2298     return computeLinkageInfo(cast<BlockPointerType>(T)->getPointeeType());
2299   case Type::LValueReference:
2300   case Type::RValueReference:
2301     return computeLinkageInfo(cast<ReferenceType>(T)->getPointeeType());
2302   case Type::MemberPointer: {
2303     const MemberPointerType *MPT = cast<MemberPointerType>(T);
2304     LinkageInfo LV = computeLinkageInfo(MPT->getClass());
2305     LV.merge(computeLinkageInfo(MPT->getPointeeType()));
2306     return LV;
2307   }
2308   case Type::ConstantArray:
2309   case Type::IncompleteArray:
2310   case Type::VariableArray:
2311     return computeLinkageInfo(cast<ArrayType>(T)->getElementType());
2312   case Type::Vector:
2313   case Type::ExtVector:
2314     return computeLinkageInfo(cast<VectorType>(T)->getElementType());
2315   case Type::FunctionNoProto:
2316     return computeLinkageInfo(cast<FunctionType>(T)->getReturnType());
2317   case Type::FunctionProto: {
2318     const FunctionProtoType *FPT = cast<FunctionProtoType>(T);
2319     LinkageInfo LV = computeLinkageInfo(FPT->getReturnType());
2320     for (const auto &ai : FPT->param_types())
2321       LV.merge(computeLinkageInfo(ai));
2322     return LV;
2323   }
2324   case Type::ObjCInterface:
2325     return cast<ObjCInterfaceType>(T)->getDecl()->getLinkageAndVisibility();
2326   case Type::ObjCObject:
2327     return computeLinkageInfo(cast<ObjCObjectType>(T)->getBaseType());
2328   case Type::ObjCObjectPointer:
2329     return computeLinkageInfo(cast<ObjCObjectPointerType>(T)->getPointeeType());
2330   case Type::Atomic:
2331     return computeLinkageInfo(cast<AtomicType>(T)->getValueType());
2332   }
2333 
2334   llvm_unreachable("unhandled type class");
2335 }
2336 
2337 static LinkageInfo computeLinkageInfo(QualType T) {
2338   return computeLinkageInfo(T.getTypePtr());
2339 }
2340 
2341 bool Type::isLinkageValid() const {
2342   if (!TypeBits.isCacheValid())
2343     return true;
2344 
2345   return computeLinkageInfo(getCanonicalTypeInternal()).getLinkage() ==
2346     TypeBits.getLinkage();
2347 }
2348 
2349 LinkageInfo Type::getLinkageAndVisibility() const {
2350   if (!isCanonicalUnqualified())
2351     return computeLinkageInfo(getCanonicalTypeInternal());
2352 
2353   LinkageInfo LV = computeLinkageInfo(this);
2354   assert(LV.getLinkage() == getLinkage());
2355   return LV;
2356 }
2357 
2358 Qualifiers::ObjCLifetime Type::getObjCARCImplicitLifetime() const {
2359   if (isObjCARCImplicitlyUnretainedType())
2360     return Qualifiers::OCL_ExplicitNone;
2361   return Qualifiers::OCL_Strong;
2362 }
2363 
2364 bool Type::isObjCARCImplicitlyUnretainedType() const {
2365   assert(isObjCLifetimeType() &&
2366          "cannot query implicit lifetime for non-inferrable type");
2367 
2368   const Type *canon = getCanonicalTypeInternal().getTypePtr();
2369 
2370   // Walk down to the base type.  We don't care about qualifiers for this.
2371   while (const ArrayType *array = dyn_cast<ArrayType>(canon))
2372     canon = array->getElementType().getTypePtr();
2373 
2374   if (const ObjCObjectPointerType *opt
2375         = dyn_cast<ObjCObjectPointerType>(canon)) {
2376     // Class and Class<Protocol> don't require retension.
2377     if (opt->getObjectType()->isObjCClass())
2378       return true;
2379   }
2380 
2381   return false;
2382 }
2383 
2384 bool Type::isObjCNSObjectType() const {
2385   if (const TypedefType *typedefType = dyn_cast<TypedefType>(this))
2386     return typedefType->getDecl()->hasAttr<ObjCNSObjectAttr>();
2387   return false;
2388 }
2389 bool Type::isObjCRetainableType() const {
2390   return isObjCObjectPointerType() ||
2391          isBlockPointerType() ||
2392          isObjCNSObjectType();
2393 }
2394 bool Type::isObjCIndirectLifetimeType() const {
2395   if (isObjCLifetimeType())
2396     return true;
2397   if (const PointerType *OPT = getAs<PointerType>())
2398     return OPT->getPointeeType()->isObjCIndirectLifetimeType();
2399   if (const ReferenceType *Ref = getAs<ReferenceType>())
2400     return Ref->getPointeeType()->isObjCIndirectLifetimeType();
2401   if (const MemberPointerType *MemPtr = getAs<MemberPointerType>())
2402     return MemPtr->getPointeeType()->isObjCIndirectLifetimeType();
2403   return false;
2404 }
2405 
2406 /// Returns true if objects of this type have lifetime semantics under
2407 /// ARC.
2408 bool Type::isObjCLifetimeType() const {
2409   const Type *type = this;
2410   while (const ArrayType *array = type->getAsArrayTypeUnsafe())
2411     type = array->getElementType().getTypePtr();
2412   return type->isObjCRetainableType();
2413 }
2414 
2415 /// \brief Determine whether the given type T is a "bridgable" Objective-C type,
2416 /// which is either an Objective-C object pointer type or an
2417 bool Type::isObjCARCBridgableType() const {
2418   return isObjCObjectPointerType() || isBlockPointerType();
2419 }
2420 
2421 /// \brief Determine whether the given type T is a "bridgeable" C type.
2422 bool Type::isCARCBridgableType() const {
2423   const PointerType *Pointer = getAs<PointerType>();
2424   if (!Pointer)
2425     return false;
2426 
2427   QualType Pointee = Pointer->getPointeeType();
2428   return Pointee->isVoidType() || Pointee->isRecordType();
2429 }
2430 
2431 bool Type::hasSizedVLAType() const {
2432   if (!isVariablyModifiedType()) return false;
2433 
2434   if (const PointerType *ptr = getAs<PointerType>())
2435     return ptr->getPointeeType()->hasSizedVLAType();
2436   if (const ReferenceType *ref = getAs<ReferenceType>())
2437     return ref->getPointeeType()->hasSizedVLAType();
2438   if (const ArrayType *arr = getAsArrayTypeUnsafe()) {
2439     if (isa<VariableArrayType>(arr) &&
2440         cast<VariableArrayType>(arr)->getSizeExpr())
2441       return true;
2442 
2443     return arr->getElementType()->hasSizedVLAType();
2444   }
2445 
2446   return false;
2447 }
2448 
2449 QualType::DestructionKind QualType::isDestructedTypeImpl(QualType type) {
2450   switch (type.getObjCLifetime()) {
2451   case Qualifiers::OCL_None:
2452   case Qualifiers::OCL_ExplicitNone:
2453   case Qualifiers::OCL_Autoreleasing:
2454     break;
2455 
2456   case Qualifiers::OCL_Strong:
2457     return DK_objc_strong_lifetime;
2458   case Qualifiers::OCL_Weak:
2459     return DK_objc_weak_lifetime;
2460   }
2461 
2462   /// Currently, the only destruction kind we recognize is C++ objects
2463   /// with non-trivial destructors.
2464   const CXXRecordDecl *record =
2465     type->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
2466   if (record && record->hasDefinition() && !record->hasTrivialDestructor())
2467     return DK_cxx_destructor;
2468 
2469   return DK_none;
2470 }
2471 
2472 CXXRecordDecl *MemberPointerType::getMostRecentCXXRecordDecl() const {
2473   return getClass()->getAsCXXRecordDecl()->getMostRecentDecl();
2474 }
2475