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