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