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