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