clang API Documentation

Type.cpp
Go to the documentation of this file.
00001 //===--- Type.cpp - Type representation and manipulation ------------------===//
00002 //
00003 //                     The LLVM Compiler Infrastructure
00004 //
00005 // This file is distributed under the University of Illinois Open Source
00006 // License. See LICENSE.TXT for details.
00007 //
00008 //===----------------------------------------------------------------------===//
00009 //
00010 //  This file implements type-related functionality.
00011 //
00012 //===----------------------------------------------------------------------===//
00013 
00014 #include "clang/AST/ASTContext.h"
00015 #include "clang/AST/CharUnits.h"
00016 #include "clang/AST/Type.h"
00017 #include "clang/AST/DeclCXX.h"
00018 #include "clang/AST/DeclObjC.h"
00019 #include "clang/AST/DeclTemplate.h"
00020 #include "clang/AST/Expr.h"
00021 #include "clang/AST/PrettyPrinter.h"
00022 #include "clang/AST/TypeVisitor.h"
00023 #include "clang/Basic/Specifiers.h"
00024 #include "llvm/ADT/APSInt.h"
00025 #include "llvm/ADT/StringExtras.h"
00026 #include "llvm/Support/raw_ostream.h"
00027 #include <algorithm>
00028 using namespace clang;
00029 
00030 bool Qualifiers::isStrictSupersetOf(Qualifiers Other) const {
00031   return (*this != Other) &&
00032     // CVR qualifiers superset
00033     (((Mask & CVRMask) | (Other.Mask & CVRMask)) == (Mask & CVRMask)) &&
00034     // ObjC GC qualifiers superset
00035     ((getObjCGCAttr() == Other.getObjCGCAttr()) ||
00036      (hasObjCGCAttr() && !Other.hasObjCGCAttr())) &&
00037     // Address space superset.
00038     ((getAddressSpace() == Other.getAddressSpace()) ||
00039      (hasAddressSpace()&& !Other.hasAddressSpace())) &&
00040     // Lifetime qualifier superset.
00041     ((getObjCLifetime() == Other.getObjCLifetime()) ||
00042      (hasObjCLifetime() && !Other.hasObjCLifetime()));
00043 }
00044 
00045 const IdentifierInfo* QualType::getBaseTypeIdentifier() const {
00046   const Type* ty = getTypePtr();
00047   NamedDecl *ND = NULL;
00048   if (ty->isPointerType() || ty->isReferenceType())
00049     return ty->getPointeeType().getBaseTypeIdentifier();
00050   else if (ty->isRecordType())
00051     ND = ty->getAs<RecordType>()->getDecl();
00052   else if (ty->isEnumeralType())
00053     ND = ty->getAs<EnumType>()->getDecl();
00054   else if (ty->getTypeClass() == Type::Typedef)
00055     ND = ty->getAs<TypedefType>()->getDecl();
00056   else if (ty->isArrayType())
00057     return ty->castAsArrayTypeUnsafe()->
00058         getElementType().getBaseTypeIdentifier();
00059 
00060   if (ND)
00061     return ND->getIdentifier();
00062   return NULL;
00063 }
00064 
00065 bool QualType::isConstant(QualType T, ASTContext &Ctx) {
00066   if (T.isConstQualified())
00067     return true;
00068 
00069   if (const ArrayType *AT = Ctx.getAsArrayType(T))
00070     return AT->getElementType().isConstant(Ctx);
00071 
00072   return false;
00073 }
00074 
00075 unsigned ConstantArrayType::getNumAddressingBits(ASTContext &Context,
00076                                                  QualType ElementType,
00077                                                const llvm::APInt &NumElements) {
00078   llvm::APSInt SizeExtended(NumElements, true);
00079   unsigned SizeTypeBits = Context.getTypeSize(Context.getSizeType());
00080   SizeExtended = SizeExtended.extend(std::max(SizeTypeBits,
00081                                               SizeExtended.getBitWidth()) * 2);
00082 
00083   uint64_t ElementSize
00084     = Context.getTypeSizeInChars(ElementType).getQuantity();
00085   llvm::APSInt TotalSize(llvm::APInt(SizeExtended.getBitWidth(), ElementSize));
00086   TotalSize *= SizeExtended;  
00087   
00088   return TotalSize.getActiveBits();
00089 }
00090 
00091 unsigned ConstantArrayType::getMaxSizeBits(ASTContext &Context) {
00092   unsigned Bits = Context.getTypeSize(Context.getSizeType());
00093   
00094   // GCC appears to only allow 63 bits worth of address space when compiling
00095   // for 64-bit, so we do the same.
00096   if (Bits == 64)
00097     --Bits;
00098   
00099   return Bits;
00100 }
00101 
00102 DependentSizedArrayType::DependentSizedArrayType(const ASTContext &Context, 
00103                                                  QualType et, QualType can,
00104                                                  Expr *e, ArraySizeModifier sm,
00105                                                  unsigned tq,
00106                                                  SourceRange brackets)
00107     : ArrayType(DependentSizedArray, et, can, sm, tq, 
00108                 (et->containsUnexpandedParameterPack() ||
00109                  (e && e->containsUnexpandedParameterPack()))),
00110       Context(Context), SizeExpr((Stmt*) e), Brackets(brackets) 
00111 {
00112 }
00113 
00114 void DependentSizedArrayType::Profile(llvm::FoldingSetNodeID &ID,
00115                                       const ASTContext &Context,
00116                                       QualType ET,
00117                                       ArraySizeModifier SizeMod,
00118                                       unsigned TypeQuals,
00119                                       Expr *E) {
00120   ID.AddPointer(ET.getAsOpaquePtr());
00121   ID.AddInteger(SizeMod);
00122   ID.AddInteger(TypeQuals);
00123   E->Profile(ID, Context, true);
00124 }
00125 
00126 DependentSizedExtVectorType::DependentSizedExtVectorType(const
00127                                                          ASTContext &Context,
00128                                                          QualType ElementType,
00129                                                          QualType can, 
00130                                                          Expr *SizeExpr, 
00131                                                          SourceLocation loc)
00132     : Type(DependentSizedExtVector, can, /*Dependent=*/true,
00133            /*InstantiationDependent=*/true,
00134            ElementType->isVariablyModifiedType(), 
00135            (ElementType->containsUnexpandedParameterPack() ||
00136             (SizeExpr && SizeExpr->containsUnexpandedParameterPack()))),
00137       Context(Context), SizeExpr(SizeExpr), ElementType(ElementType),
00138       loc(loc) 
00139 {
00140 }
00141 
00142 void
00143 DependentSizedExtVectorType::Profile(llvm::FoldingSetNodeID &ID,
00144                                      const ASTContext &Context,
00145                                      QualType ElementType, Expr *SizeExpr) {
00146   ID.AddPointer(ElementType.getAsOpaquePtr());
00147   SizeExpr->Profile(ID, Context, true);
00148 }
00149 
00150 VectorType::VectorType(QualType vecType, unsigned nElements, QualType canonType,
00151                        VectorKind vecKind)
00152   : Type(Vector, canonType, vecType->isDependentType(),
00153          vecType->isInstantiationDependentType(),
00154          vecType->isVariablyModifiedType(),
00155          vecType->containsUnexpandedParameterPack()),
00156     ElementType(vecType) 
00157 {
00158   VectorTypeBits.VecKind = vecKind;
00159   VectorTypeBits.NumElements = nElements;
00160 }
00161 
00162 VectorType::VectorType(TypeClass tc, QualType vecType, unsigned nElements,
00163                        QualType canonType, VectorKind vecKind)
00164   : Type(tc, canonType, vecType->isDependentType(),
00165          vecType->isInstantiationDependentType(),
00166          vecType->isVariablyModifiedType(),
00167          vecType->containsUnexpandedParameterPack()), 
00168     ElementType(vecType) 
00169 {
00170   VectorTypeBits.VecKind = vecKind;
00171   VectorTypeBits.NumElements = nElements;
00172 }
00173 
00174 /// getArrayElementTypeNoTypeQual - If this is an array type, return the
00175 /// element type of the array, potentially with type qualifiers missing.
00176 /// This method should never be used when type qualifiers are meaningful.
00177 const Type *Type::getArrayElementTypeNoTypeQual() const {
00178   // If this is directly an array type, return it.
00179   if (const ArrayType *ATy = dyn_cast<ArrayType>(this))
00180     return ATy->getElementType().getTypePtr();
00181 
00182   // If the canonical form of this type isn't the right kind, reject it.
00183   if (!isa<ArrayType>(CanonicalType))
00184     return 0;
00185 
00186   // If this is a typedef for an array type, strip the typedef off without
00187   // losing all typedef information.
00188   return cast<ArrayType>(getUnqualifiedDesugaredType())
00189     ->getElementType().getTypePtr();
00190 }
00191 
00192 /// getDesugaredType - Return the specified type with any "sugar" removed from
00193 /// the type.  This takes off typedefs, typeof's etc.  If the outer level of
00194 /// the type is already concrete, it returns it unmodified.  This is similar
00195 /// to getting the canonical type, but it doesn't remove *all* typedefs.  For
00196 /// example, it returns "T*" as "T*", (not as "int*"), because the pointer is
00197 /// concrete.
00198 QualType QualType::getDesugaredType(QualType T, const ASTContext &Context) {
00199   SplitQualType split = getSplitDesugaredType(T);
00200   return Context.getQualifiedType(split.Ty, split.Quals);
00201 }
00202 
00203 QualType QualType::getSingleStepDesugaredTypeImpl(QualType type,
00204                                                   const ASTContext &Context) {
00205   SplitQualType split = type.split();
00206   QualType desugar = split.Ty->getLocallyUnqualifiedSingleStepDesugaredType();
00207   return Context.getQualifiedType(desugar, split.Quals);
00208 }
00209 
00210 QualType Type::getLocallyUnqualifiedSingleStepDesugaredType() const {
00211   switch (getTypeClass()) {
00212 #define ABSTRACT_TYPE(Class, Parent)
00213 #define TYPE(Class, Parent) \
00214   case Type::Class: { \
00215     const Class##Type *ty = cast<Class##Type>(this); \
00216     if (!ty->isSugared()) return QualType(ty, 0); \
00217     return ty->desugar(); \
00218   }
00219 #include "clang/AST/TypeNodes.def"
00220   }
00221   llvm_unreachable("bad type kind!");
00222 }
00223 
00224 SplitQualType QualType::getSplitDesugaredType(QualType T) {
00225   QualifierCollector Qs;
00226 
00227   QualType Cur = T;
00228   while (true) {
00229     const Type *CurTy = Qs.strip(Cur);
00230     switch (CurTy->getTypeClass()) {
00231 #define ABSTRACT_TYPE(Class, Parent)
00232 #define TYPE(Class, Parent) \
00233     case Type::Class: { \
00234       const Class##Type *Ty = cast<Class##Type>(CurTy); \
00235       if (!Ty->isSugared()) \
00236         return SplitQualType(Ty, Qs); \
00237       Cur = Ty->desugar(); \
00238       break; \
00239     }
00240 #include "clang/AST/TypeNodes.def"
00241     }
00242   }
00243 }
00244 
00245 SplitQualType QualType::getSplitUnqualifiedTypeImpl(QualType type) {
00246   SplitQualType split = type.split();
00247 
00248   // All the qualifiers we've seen so far.
00249   Qualifiers quals = split.Quals;
00250 
00251   // The last type node we saw with any nodes inside it.
00252   const Type *lastTypeWithQuals = split.Ty;
00253 
00254   while (true) {
00255     QualType next;
00256 
00257     // Do a single-step desugar, aborting the loop if the type isn't
00258     // sugared.
00259     switch (split.Ty->getTypeClass()) {
00260 #define ABSTRACT_TYPE(Class, Parent)
00261 #define TYPE(Class, Parent) \
00262     case Type::Class: { \
00263       const Class##Type *ty = cast<Class##Type>(split.Ty); \
00264       if (!ty->isSugared()) goto done; \
00265       next = ty->desugar(); \
00266       break; \
00267     }
00268 #include "clang/AST/TypeNodes.def"
00269     }
00270 
00271     // Otherwise, split the underlying type.  If that yields qualifiers,
00272     // update the information.
00273     split = next.split();
00274     if (!split.Quals.empty()) {
00275       lastTypeWithQuals = split.Ty;
00276       quals.addConsistentQualifiers(split.Quals);
00277     }
00278   }
00279 
00280  done:
00281   return SplitQualType(lastTypeWithQuals, quals);
00282 }
00283 
00284 QualType QualType::IgnoreParens(QualType T) {
00285   // FIXME: this seems inherently un-qualifiers-safe.
00286   while (const ParenType *PT = T->getAs<ParenType>())
00287     T = PT->getInnerType();
00288   return T;
00289 }
00290 
00291 /// \brief This will check for a TypedefType by removing any existing sugar
00292 /// until it reaches a TypedefType or a non-sugared type.
00293 template <> const TypedefType *Type::getAs() const {
00294   const Type *Cur = this;
00295 
00296   while (true) {
00297     if (const TypedefType *TDT = dyn_cast<TypedefType>(Cur))
00298       return TDT;
00299     switch (Cur->getTypeClass()) {
00300 #define ABSTRACT_TYPE(Class, Parent)
00301 #define TYPE(Class, Parent) \
00302     case Class: { \
00303       const Class##Type *Ty = cast<Class##Type>(Cur); \
00304       if (!Ty->isSugared()) return 0; \
00305       Cur = Ty->desugar().getTypePtr(); \
00306       break; \
00307     }
00308 #include "clang/AST/TypeNodes.def"
00309     }
00310   }
00311 }
00312 
00313 /// getUnqualifiedDesugaredType - Pull any qualifiers and syntactic
00314 /// sugar off the given type.  This should produce an object of the
00315 /// same dynamic type as the canonical type.
00316 const Type *Type::getUnqualifiedDesugaredType() const {
00317   const Type *Cur = this;
00318 
00319   while (true) {
00320     switch (Cur->getTypeClass()) {
00321 #define ABSTRACT_TYPE(Class, Parent)
00322 #define TYPE(Class, Parent) \
00323     case Class: { \
00324       const Class##Type *Ty = cast<Class##Type>(Cur); \
00325       if (!Ty->isSugared()) return Cur; \
00326       Cur = Ty->desugar().getTypePtr(); \
00327       break; \
00328     }
00329 #include "clang/AST/TypeNodes.def"
00330     }
00331   }
00332 }
00333 
00334 bool Type::isDerivedType() const {
00335   switch (CanonicalType->getTypeClass()) {
00336   case Pointer:
00337   case VariableArray:
00338   case ConstantArray:
00339   case IncompleteArray:
00340   case FunctionProto:
00341   case FunctionNoProto:
00342   case LValueReference:
00343   case RValueReference:
00344   case Record:
00345     return true;
00346   default:
00347     return false;
00348   }
00349 }
00350 bool Type::isClassType() const {
00351   if (const RecordType *RT = getAs<RecordType>())
00352     return RT->getDecl()->isClass();
00353   return false;
00354 }
00355 bool Type::isStructureType() const {
00356   if (const RecordType *RT = getAs<RecordType>())
00357     return RT->getDecl()->isStruct();
00358   return false;
00359 }
00360 bool Type::isStructureOrClassType() const {
00361   if (const RecordType *RT = getAs<RecordType>())
00362     return RT->getDecl()->isStruct() || RT->getDecl()->isClass();
00363   return false;
00364 }
00365 bool Type::isVoidPointerType() const {
00366   if (const PointerType *PT = getAs<PointerType>())
00367     return PT->getPointeeType()->isVoidType();
00368   return false;
00369 }
00370 
00371 bool Type::isUnionType() const {
00372   if (const RecordType *RT = getAs<RecordType>())
00373     return RT->getDecl()->isUnion();
00374   return false;
00375 }
00376 
00377 bool Type::isComplexType() const {
00378   if (const ComplexType *CT = dyn_cast<ComplexType>(CanonicalType))
00379     return CT->getElementType()->isFloatingType();
00380   return false;
00381 }
00382 
00383 bool Type::isComplexIntegerType() const {
00384   // Check for GCC complex integer extension.
00385   return getAsComplexIntegerType();
00386 }
00387 
00388 const ComplexType *Type::getAsComplexIntegerType() const {
00389   if (const ComplexType *Complex = getAs<ComplexType>())
00390     if (Complex->getElementType()->isIntegerType())
00391       return Complex;
00392   return 0;
00393 }
00394 
00395 QualType Type::getPointeeType() const {
00396   if (const PointerType *PT = getAs<PointerType>())
00397     return PT->getPointeeType();
00398   if (const ObjCObjectPointerType *OPT = getAs<ObjCObjectPointerType>())
00399     return OPT->getPointeeType();
00400   if (const BlockPointerType *BPT = getAs<BlockPointerType>())
00401     return BPT->getPointeeType();
00402   if (const ReferenceType *RT = getAs<ReferenceType>())
00403     return RT->getPointeeType();
00404   return QualType();
00405 }
00406 
00407 const RecordType *Type::getAsStructureType() const {
00408   // If this is directly a structure type, return it.
00409   if (const RecordType *RT = dyn_cast<RecordType>(this)) {
00410     if (RT->getDecl()->isStruct())
00411       return RT;
00412   }
00413 
00414   // If the canonical form of this type isn't the right kind, reject it.
00415   if (const RecordType *RT = dyn_cast<RecordType>(CanonicalType)) {
00416     if (!RT->getDecl()->isStruct())
00417       return 0;
00418 
00419     // If this is a typedef for a structure type, strip the typedef off without
00420     // losing all typedef information.
00421     return cast<RecordType>(getUnqualifiedDesugaredType());
00422   }
00423   return 0;
00424 }
00425 
00426 const RecordType *Type::getAsUnionType() const {
00427   // If this is directly a union type, return it.
00428   if (const RecordType *RT = dyn_cast<RecordType>(this)) {
00429     if (RT->getDecl()->isUnion())
00430       return RT;
00431   }
00432 
00433   // If the canonical form of this type isn't the right kind, reject it.
00434   if (const RecordType *RT = dyn_cast<RecordType>(CanonicalType)) {
00435     if (!RT->getDecl()->isUnion())
00436       return 0;
00437 
00438     // If this is a typedef for a union type, strip the typedef off without
00439     // losing all typedef information.
00440     return cast<RecordType>(getUnqualifiedDesugaredType());
00441   }
00442 
00443   return 0;
00444 }
00445 
00446 ObjCObjectType::ObjCObjectType(QualType Canonical, QualType Base,
00447                                ObjCProtocolDecl * const *Protocols,
00448                                unsigned NumProtocols)
00449   : Type(ObjCObject, Canonical, false, false, false, false),
00450     BaseType(Base) 
00451 {
00452   ObjCObjectTypeBits.NumProtocols = NumProtocols;
00453   assert(getNumProtocols() == NumProtocols &&
00454          "bitfield overflow in protocol count");
00455   if (NumProtocols)
00456     memcpy(getProtocolStorage(), Protocols,
00457            NumProtocols * sizeof(ObjCProtocolDecl*));
00458 }
00459 
00460 const ObjCObjectType *Type::getAsObjCQualifiedInterfaceType() const {
00461   // There is no sugar for ObjCObjectType's, just return the canonical
00462   // type pointer if it is the right class.  There is no typedef information to
00463   // return and these cannot be Address-space qualified.
00464   if (const ObjCObjectType *T = getAs<ObjCObjectType>())
00465     if (T->getNumProtocols() && T->getInterface())
00466       return T;
00467   return 0;
00468 }
00469 
00470 bool Type::isObjCQualifiedInterfaceType() const {
00471   return getAsObjCQualifiedInterfaceType() != 0;
00472 }
00473 
00474 const ObjCObjectPointerType *Type::getAsObjCQualifiedIdType() const {
00475   // There is no sugar for ObjCQualifiedIdType's, just return the canonical
00476   // type pointer if it is the right class.
00477   if (const ObjCObjectPointerType *OPT = getAs<ObjCObjectPointerType>()) {
00478     if (OPT->isObjCQualifiedIdType())
00479       return OPT;
00480   }
00481   return 0;
00482 }
00483 
00484 const ObjCObjectPointerType *Type::getAsObjCQualifiedClassType() const {
00485   // There is no sugar for ObjCQualifiedClassType's, just return the canonical
00486   // type pointer if it is the right class.
00487   if (const ObjCObjectPointerType *OPT = getAs<ObjCObjectPointerType>()) {
00488     if (OPT->isObjCQualifiedClassType())
00489       return OPT;
00490   }
00491   return 0;
00492 }
00493 
00494 const ObjCObjectPointerType *Type::getAsObjCInterfacePointerType() const {
00495   if (const ObjCObjectPointerType *OPT = getAs<ObjCObjectPointerType>()) {
00496     if (OPT->getInterfaceType())
00497       return OPT;
00498   }
00499   return 0;
00500 }
00501 
00502 const CXXRecordDecl *Type::getCXXRecordDeclForPointerType() const {
00503   if (const PointerType *PT = getAs<PointerType>())
00504     if (const RecordType *RT = PT->getPointeeType()->getAs<RecordType>())
00505       return dyn_cast<CXXRecordDecl>(RT->getDecl());
00506   return 0;
00507 }
00508 
00509 CXXRecordDecl *Type::getAsCXXRecordDecl() const {
00510   if (const RecordType *RT = getAs<RecordType>())
00511     return dyn_cast<CXXRecordDecl>(RT->getDecl());
00512   else if (const InjectedClassNameType *Injected
00513                                   = getAs<InjectedClassNameType>())
00514     return Injected->getDecl();
00515   
00516   return 0;
00517 }
00518 
00519 namespace {
00520   class GetContainedAutoVisitor :
00521     public TypeVisitor<GetContainedAutoVisitor, AutoType*> {
00522   public:
00523     using TypeVisitor<GetContainedAutoVisitor, AutoType*>::Visit;
00524     AutoType *Visit(QualType T) {
00525       if (T.isNull())
00526         return 0;
00527       return Visit(T.getTypePtr());
00528     }
00529 
00530     // The 'auto' type itself.
00531     AutoType *VisitAutoType(const AutoType *AT) {
00532       return const_cast<AutoType*>(AT);
00533     }
00534 
00535     // Only these types can contain the desired 'auto' type.
00536     AutoType *VisitPointerType(const PointerType *T) {
00537       return Visit(T->getPointeeType());
00538     }
00539     AutoType *VisitBlockPointerType(const BlockPointerType *T) {
00540       return Visit(T->getPointeeType());
00541     }
00542     AutoType *VisitReferenceType(const ReferenceType *T) {
00543       return Visit(T->getPointeeTypeAsWritten());
00544     }
00545     AutoType *VisitMemberPointerType(const MemberPointerType *T) {
00546       return Visit(T->getPointeeType());
00547     }
00548     AutoType *VisitArrayType(const ArrayType *T) {
00549       return Visit(T->getElementType());
00550     }
00551     AutoType *VisitDependentSizedExtVectorType(
00552       const DependentSizedExtVectorType *T) {
00553       return Visit(T->getElementType());
00554     }
00555     AutoType *VisitVectorType(const VectorType *T) {
00556       return Visit(T->getElementType());
00557     }
00558     AutoType *VisitFunctionType(const FunctionType *T) {
00559       return Visit(T->getResultType());
00560     }
00561     AutoType *VisitParenType(const ParenType *T) {
00562       return Visit(T->getInnerType());
00563     }
00564     AutoType *VisitAttributedType(const AttributedType *T) {
00565       return Visit(T->getModifiedType());
00566     }
00567   };
00568 }
00569 
00570 AutoType *Type::getContainedAutoType() const {
00571   return GetContainedAutoVisitor().Visit(this);
00572 }
00573 
00574 bool Type::hasIntegerRepresentation() const {
00575   if (const VectorType *VT = dyn_cast<VectorType>(CanonicalType))
00576     return VT->getElementType()->isIntegerType();
00577   else
00578     return isIntegerType();
00579 }
00580 
00581 /// \brief Determine whether this type is an integral type.
00582 ///
00583 /// This routine determines whether the given type is an integral type per 
00584 /// C++ [basic.fundamental]p7. Although the C standard does not define the
00585 /// term "integral type", it has a similar term "integer type", and in C++
00586 /// the two terms are equivalent. However, C's "integer type" includes 
00587 /// enumeration types, while C++'s "integer type" does not. The \c ASTContext
00588 /// parameter is used to determine whether we should be following the C or
00589 /// C++ rules when determining whether this type is an integral/integer type.
00590 ///
00591 /// For cases where C permits "an integer type" and C++ permits "an integral
00592 /// type", use this routine.
00593 ///
00594 /// For cases where C permits "an integer type" and C++ permits "an integral
00595 /// or enumeration type", use \c isIntegralOrEnumerationType() instead. 
00596 ///
00597 /// \param Ctx The context in which this type occurs.
00598 ///
00599 /// \returns true if the type is considered an integral type, false otherwise.
00600 bool Type::isIntegralType(ASTContext &Ctx) const {
00601   if (const BuiltinType *BT = dyn_cast<BuiltinType>(CanonicalType))
00602     return BT->getKind() >= BuiltinType::Bool &&
00603     BT->getKind() <= BuiltinType::Int128;
00604   
00605   if (!Ctx.getLangOpts().CPlusPlus)
00606     if (const EnumType *ET = dyn_cast<EnumType>(CanonicalType))
00607       return ET->getDecl()->isComplete(); // Complete enum types are integral in C.
00608   
00609   return false;
00610 }
00611 
00612 
00613 bool Type::isIntegralOrUnscopedEnumerationType() const {
00614   if (const BuiltinType *BT = dyn_cast<BuiltinType>(CanonicalType))
00615     return BT->getKind() >= BuiltinType::Bool &&
00616            BT->getKind() <= BuiltinType::Int128;
00617 
00618   // Check for a complete enum type; incomplete enum types are not properly an
00619   // enumeration type in the sense required here.
00620   // C++0x: However, if the underlying type of the enum is fixed, it is
00621   // considered complete.
00622   if (const EnumType *ET = dyn_cast<EnumType>(CanonicalType))
00623     return ET->getDecl()->isComplete() && !ET->getDecl()->isScoped();
00624 
00625   return false;
00626 }
00627 
00628 
00629 
00630 bool Type::isCharType() const {
00631   if (const BuiltinType *BT = dyn_cast<BuiltinType>(CanonicalType))
00632     return BT->getKind() == BuiltinType::Char_U ||
00633            BT->getKind() == BuiltinType::UChar ||
00634            BT->getKind() == BuiltinType::Char_S ||
00635            BT->getKind() == BuiltinType::SChar;
00636   return false;
00637 }
00638 
00639 bool Type::isWideCharType() const {
00640   if (const BuiltinType *BT = dyn_cast<BuiltinType>(CanonicalType))
00641     return BT->getKind() == BuiltinType::WChar_S ||
00642            BT->getKind() == BuiltinType::WChar_U;
00643   return false;
00644 }
00645 
00646 bool Type::isChar16Type() const {
00647   if (const BuiltinType *BT = dyn_cast<BuiltinType>(CanonicalType))
00648     return BT->getKind() == BuiltinType::Char16;
00649   return false;
00650 }
00651 
00652 bool Type::isChar32Type() const {
00653   if (const BuiltinType *BT = dyn_cast<BuiltinType>(CanonicalType))
00654     return BT->getKind() == BuiltinType::Char32;
00655   return false;
00656 }
00657 
00658 /// \brief Determine whether this type is any of the built-in character
00659 /// types.
00660 bool Type::isAnyCharacterType() const {
00661   const BuiltinType *BT = dyn_cast<BuiltinType>(CanonicalType);
00662   if (BT == 0) return false;
00663   switch (BT->getKind()) {
00664   default: return false;
00665   case BuiltinType::Char_U:
00666   case BuiltinType::UChar:
00667   case BuiltinType::WChar_U:
00668   case BuiltinType::Char16:
00669   case BuiltinType::Char32:
00670   case BuiltinType::Char_S:
00671   case BuiltinType::SChar:
00672   case BuiltinType::WChar_S:
00673     return true;
00674   }
00675 }
00676 
00677 /// isSignedIntegerType - Return true if this is an integer type that is
00678 /// signed, according to C99 6.2.5p4 [char, signed char, short, int, long..],
00679 /// an enum decl which has a signed representation
00680 bool Type::isSignedIntegerType() const {
00681   if (const BuiltinType *BT = dyn_cast<BuiltinType>(CanonicalType)) {
00682     return BT->getKind() >= BuiltinType::Char_S &&
00683            BT->getKind() <= BuiltinType::Int128;
00684   }
00685 
00686   if (const EnumType *ET = dyn_cast<EnumType>(CanonicalType)) {
00687     // Incomplete enum types are not treated as integer types.
00688     // FIXME: In C++, enum types are never integer types.
00689     if (ET->getDecl()->isComplete() && !ET->getDecl()->isScoped())
00690       return ET->getDecl()->getIntegerType()->isSignedIntegerType();
00691   }
00692 
00693   return false;
00694 }
00695 
00696 bool Type::isSignedIntegerOrEnumerationType() const {
00697   if (const BuiltinType *BT = dyn_cast<BuiltinType>(CanonicalType)) {
00698     return BT->getKind() >= BuiltinType::Char_S &&
00699     BT->getKind() <= BuiltinType::Int128;
00700   }
00701   
00702   if (const EnumType *ET = dyn_cast<EnumType>(CanonicalType)) {
00703     if (ET->getDecl()->isComplete())
00704       return ET->getDecl()->getIntegerType()->isSignedIntegerType();
00705   }
00706   
00707   return false;
00708 }
00709 
00710 bool Type::hasSignedIntegerRepresentation() const {
00711   if (const VectorType *VT = dyn_cast<VectorType>(CanonicalType))
00712     return VT->getElementType()->isSignedIntegerType();
00713   else
00714     return isSignedIntegerType();
00715 }
00716 
00717 /// isUnsignedIntegerType - Return true if this is an integer type that is
00718 /// unsigned, according to C99 6.2.5p6 [which returns true for _Bool], an enum
00719 /// decl which has an unsigned representation
00720 bool Type::isUnsignedIntegerType() const {
00721   if (const BuiltinType *BT = dyn_cast<BuiltinType>(CanonicalType)) {
00722     return BT->getKind() >= BuiltinType::Bool &&
00723            BT->getKind() <= BuiltinType::UInt128;
00724   }
00725 
00726   if (const EnumType *ET = dyn_cast<EnumType>(CanonicalType)) {
00727     // Incomplete enum types are not treated as integer types.
00728     // FIXME: In C++, enum types are never integer types.
00729     if (ET->getDecl()->isComplete() && !ET->getDecl()->isScoped())
00730       return ET->getDecl()->getIntegerType()->isUnsignedIntegerType();
00731   }
00732 
00733   return false;
00734 }
00735 
00736 bool Type::isUnsignedIntegerOrEnumerationType() const {
00737   if (const BuiltinType *BT = dyn_cast<BuiltinType>(CanonicalType)) {
00738     return BT->getKind() >= BuiltinType::Bool &&
00739     BT->getKind() <= BuiltinType::UInt128;
00740   }
00741   
00742   if (const EnumType *ET = dyn_cast<EnumType>(CanonicalType)) {
00743     if (ET->getDecl()->isComplete())
00744       return ET->getDecl()->getIntegerType()->isUnsignedIntegerType();
00745   }
00746   
00747   return false;
00748 }
00749 
00750 bool Type::hasUnsignedIntegerRepresentation() const {
00751   if (const VectorType *VT = dyn_cast<VectorType>(CanonicalType))
00752     return VT->getElementType()->isUnsignedIntegerType();
00753   else
00754     return isUnsignedIntegerType();
00755 }
00756 
00757 bool Type::isFloatingType() const {
00758   if (const BuiltinType *BT = dyn_cast<BuiltinType>(CanonicalType))
00759     return BT->getKind() >= BuiltinType::Half &&
00760            BT->getKind() <= BuiltinType::LongDouble;
00761   if (const ComplexType *CT = dyn_cast<ComplexType>(CanonicalType))
00762     return CT->getElementType()->isFloatingType();
00763   return false;
00764 }
00765 
00766 bool Type::hasFloatingRepresentation() const {
00767   if (const VectorType *VT = dyn_cast<VectorType>(CanonicalType))
00768     return VT->getElementType()->isFloatingType();
00769   else
00770     return isFloatingType();
00771 }
00772 
00773 bool Type::isRealFloatingType() const {
00774   if (const BuiltinType *BT = dyn_cast<BuiltinType>(CanonicalType))
00775     return BT->isFloatingPoint();
00776   return false;
00777 }
00778 
00779 bool Type::isRealType() const {
00780   if (const BuiltinType *BT = dyn_cast<BuiltinType>(CanonicalType))
00781     return BT->getKind() >= BuiltinType::Bool &&
00782            BT->getKind() <= BuiltinType::LongDouble;
00783   if (const EnumType *ET = dyn_cast<EnumType>(CanonicalType))
00784       return ET->getDecl()->isComplete() && !ET->getDecl()->isScoped();
00785   return false;
00786 }
00787 
00788 bool Type::isArithmeticType() const {
00789   if (const BuiltinType *BT = dyn_cast<BuiltinType>(CanonicalType))
00790     return BT->getKind() >= BuiltinType::Bool &&
00791            BT->getKind() <= BuiltinType::LongDouble;
00792   if (const EnumType *ET = dyn_cast<EnumType>(CanonicalType))
00793     // GCC allows forward declaration of enum types (forbid by C99 6.7.2.3p2).
00794     // If a body isn't seen by the time we get here, return false.
00795     //
00796     // C++0x: Enumerations are not arithmetic types. For now, just return
00797     // false for scoped enumerations since that will disable any
00798     // unwanted implicit conversions.
00799     return !ET->getDecl()->isScoped() && ET->getDecl()->isComplete();
00800   return isa<ComplexType>(CanonicalType);
00801 }
00802 
00803 Type::ScalarTypeKind Type::getScalarTypeKind() const {
00804   assert(isScalarType());
00805 
00806   const Type *T = CanonicalType.getTypePtr();
00807   if (const BuiltinType *BT = dyn_cast<BuiltinType>(T)) {
00808     if (BT->getKind() == BuiltinType::Bool) return STK_Bool;
00809     if (BT->getKind() == BuiltinType::NullPtr) return STK_CPointer;
00810     if (BT->isInteger()) return STK_Integral;
00811     if (BT->isFloatingPoint()) return STK_Floating;
00812     llvm_unreachable("unknown scalar builtin type");
00813   } else if (isa<PointerType>(T)) {
00814     return STK_CPointer;
00815   } else if (isa<BlockPointerType>(T)) {
00816     return STK_BlockPointer;
00817   } else if (isa<ObjCObjectPointerType>(T)) {
00818     return STK_ObjCObjectPointer;
00819   } else if (isa<MemberPointerType>(T)) {
00820     return STK_MemberPointer;
00821   } else if (isa<EnumType>(T)) {
00822     assert(cast<EnumType>(T)->getDecl()->isComplete());
00823     return STK_Integral;
00824   } else if (const ComplexType *CT = dyn_cast<ComplexType>(T)) {
00825     if (CT->getElementType()->isRealFloatingType())
00826       return STK_FloatingComplex;
00827     return STK_IntegralComplex;
00828   }
00829 
00830   llvm_unreachable("unknown scalar type");
00831 }
00832 
00833 /// \brief Determines whether the type is a C++ aggregate type or C
00834 /// aggregate or union type.
00835 ///
00836 /// An aggregate type is an array or a class type (struct, union, or
00837 /// class) that has no user-declared constructors, no private or
00838 /// protected non-static data members, no base classes, and no virtual
00839 /// functions (C++ [dcl.init.aggr]p1). The notion of an aggregate type
00840 /// subsumes the notion of C aggregates (C99 6.2.5p21) because it also
00841 /// includes union types.
00842 bool Type::isAggregateType() const {
00843   if (const RecordType *Record = dyn_cast<RecordType>(CanonicalType)) {
00844     if (CXXRecordDecl *ClassDecl = dyn_cast<CXXRecordDecl>(Record->getDecl()))
00845       return ClassDecl->isAggregate();
00846 
00847     return true;
00848   }
00849 
00850   return isa<ArrayType>(CanonicalType);
00851 }
00852 
00853 /// isConstantSizeType - Return true if this is not a variable sized type,
00854 /// according to the rules of C99 6.7.5p3.  It is not legal to call this on
00855 /// incomplete types or dependent types.
00856 bool Type::isConstantSizeType() const {
00857   assert(!isIncompleteType() && "This doesn't make sense for incomplete types");
00858   assert(!isDependentType() && "This doesn't make sense for dependent types");
00859   // The VAT must have a size, as it is known to be complete.
00860   return !isa<VariableArrayType>(CanonicalType);
00861 }
00862 
00863 /// isIncompleteType - Return true if this is an incomplete type (C99 6.2.5p1)
00864 /// - a type that can describe objects, but which lacks information needed to
00865 /// determine its size.
00866 bool Type::isIncompleteType(NamedDecl **Def) const {
00867   if (Def)
00868     *Def = 0;
00869   
00870   switch (CanonicalType->getTypeClass()) {
00871   default: return false;
00872   case Builtin:
00873     // Void is the only incomplete builtin type.  Per C99 6.2.5p19, it can never
00874     // be completed.
00875     return isVoidType();
00876   case Enum: {
00877     EnumDecl *EnumD = cast<EnumType>(CanonicalType)->getDecl();
00878     if (Def)
00879       *Def = EnumD;
00880     
00881     // An enumeration with fixed underlying type is complete (C++0x 7.2p3).
00882     if (EnumD->isFixed())
00883       return false;
00884     
00885     return !EnumD->isCompleteDefinition();
00886   }
00887   case Record: {
00888     // A tagged type (struct/union/enum/class) is incomplete if the decl is a
00889     // forward declaration, but not a full definition (C99 6.2.5p22).
00890     RecordDecl *Rec = cast<RecordType>(CanonicalType)->getDecl();
00891     if (Def)
00892       *Def = Rec;
00893     return !Rec->isCompleteDefinition();
00894   }
00895   case ConstantArray:
00896     // An array is incomplete if its element type is incomplete
00897     // (C++ [dcl.array]p1).
00898     // We don't handle variable arrays (they're not allowed in C++) or
00899     // dependent-sized arrays (dependent types are never treated as incomplete).
00900     return cast<ArrayType>(CanonicalType)->getElementType()
00901              ->isIncompleteType(Def);
00902   case IncompleteArray:
00903     // An array of unknown size is an incomplete type (C99 6.2.5p22).
00904     return true;
00905   case ObjCObject:
00906     return cast<ObjCObjectType>(CanonicalType)->getBaseType()
00907              ->isIncompleteType(Def);
00908   case ObjCInterface: {
00909     // ObjC interfaces are incomplete if they are @class, not @interface.
00910     ObjCInterfaceDecl *Interface
00911       = cast<ObjCInterfaceType>(CanonicalType)->getDecl();
00912     if (Def)
00913       *Def = Interface;
00914     return !Interface->hasDefinition();
00915   }
00916   }
00917 }
00918 
00919 bool QualType::isPODType(ASTContext &Context) const {
00920   // C++11 has a more relaxed definition of POD.
00921   if (Context.getLangOpts().CPlusPlus0x)
00922     return isCXX11PODType(Context);
00923 
00924   return isCXX98PODType(Context);
00925 }
00926 
00927 bool QualType::isCXX98PODType(ASTContext &Context) const {
00928   // The compiler shouldn't query this for incomplete types, but the user might.
00929   // We return false for that case. Except for incomplete arrays of PODs, which
00930   // are PODs according to the standard.
00931   if (isNull())
00932     return 0;
00933   
00934   if ((*this)->isIncompleteArrayType())
00935     return Context.getBaseElementType(*this).isCXX98PODType(Context);
00936     
00937   if ((*this)->isIncompleteType())
00938     return false;
00939 
00940   if (Context.getLangOpts().ObjCAutoRefCount) {
00941     switch (getObjCLifetime()) {
00942     case Qualifiers::OCL_ExplicitNone:
00943       return true;
00944       
00945     case Qualifiers::OCL_Strong:
00946     case Qualifiers::OCL_Weak:
00947     case Qualifiers::OCL_Autoreleasing:
00948       return false;
00949 
00950     case Qualifiers::OCL_None:
00951       break;
00952     }        
00953   }
00954   
00955   QualType CanonicalType = getTypePtr()->CanonicalType;
00956   switch (CanonicalType->getTypeClass()) {
00957     // Everything not explicitly mentioned is not POD.
00958   default: return false;
00959   case Type::VariableArray:
00960   case Type::ConstantArray:
00961     // IncompleteArray is handled above.
00962     return Context.getBaseElementType(*this).isCXX98PODType(Context);
00963         
00964   case Type::ObjCObjectPointer:
00965   case Type::BlockPointer:
00966   case Type::Builtin:
00967   case Type::Complex:
00968   case Type::Pointer:
00969   case Type::MemberPointer:
00970   case Type::Vector:
00971   case Type::ExtVector:
00972     return true;
00973 
00974   case Type::Enum:
00975     return true;
00976 
00977   case Type::Record:
00978     if (CXXRecordDecl *ClassDecl
00979           = dyn_cast<CXXRecordDecl>(cast<RecordType>(CanonicalType)->getDecl()))
00980       return ClassDecl->isPOD();
00981 
00982     // C struct/union is POD.
00983     return true;
00984   }
00985 }
00986 
00987 bool QualType::isTrivialType(ASTContext &Context) const {
00988   // The compiler shouldn't query this for incomplete types, but the user might.
00989   // We return false for that case. Except for incomplete arrays of PODs, which
00990   // are PODs according to the standard.
00991   if (isNull())
00992     return 0;
00993   
00994   if ((*this)->isArrayType())
00995     return Context.getBaseElementType(*this).isTrivialType(Context);
00996   
00997   // Return false for incomplete types after skipping any incomplete array
00998   // types which are expressly allowed by the standard and thus our API.
00999   if ((*this)->isIncompleteType())
01000     return false;
01001   
01002   if (Context.getLangOpts().ObjCAutoRefCount) {
01003     switch (getObjCLifetime()) {
01004     case Qualifiers::OCL_ExplicitNone:
01005       return true;
01006       
01007     case Qualifiers::OCL_Strong:
01008     case Qualifiers::OCL_Weak:
01009     case Qualifiers::OCL_Autoreleasing:
01010       return false;
01011       
01012     case Qualifiers::OCL_None:
01013       if ((*this)->isObjCLifetimeType())
01014         return false;
01015       break;
01016     }        
01017   }
01018   
01019   QualType CanonicalType = getTypePtr()->CanonicalType;
01020   if (CanonicalType->isDependentType())
01021     return false;
01022   
01023   // C++0x [basic.types]p9:
01024   //   Scalar types, trivial class types, arrays of such types, and
01025   //   cv-qualified versions of these types are collectively called trivial
01026   //   types.
01027   
01028   // As an extension, Clang treats vector types as Scalar types.
01029   if (CanonicalType->isScalarType() || CanonicalType->isVectorType())
01030     return true;
01031   if (const RecordType *RT = CanonicalType->getAs<RecordType>()) {
01032     if (const CXXRecordDecl *ClassDecl =
01033         dyn_cast<CXXRecordDecl>(RT->getDecl())) {
01034       // C++0x [class]p5:
01035       //   A trivial class is a class that has a trivial default constructor
01036       if (!ClassDecl->hasTrivialDefaultConstructor()) return false;
01037       //   and is trivially copyable.
01038       if (!ClassDecl->isTriviallyCopyable()) return false;
01039     }
01040     
01041     return true;
01042   }
01043   
01044   // No other types can match.
01045   return false;
01046 }
01047 
01048 bool QualType::isTriviallyCopyableType(ASTContext &Context) const {
01049   if ((*this)->isArrayType())
01050     return Context.getBaseElementType(*this).isTrivialType(Context);
01051 
01052   if (Context.getLangOpts().ObjCAutoRefCount) {
01053     switch (getObjCLifetime()) {
01054     case Qualifiers::OCL_ExplicitNone:
01055       return true;
01056       
01057     case Qualifiers::OCL_Strong:
01058     case Qualifiers::OCL_Weak:
01059     case Qualifiers::OCL_Autoreleasing:
01060       return false;
01061       
01062     case Qualifiers::OCL_None:
01063       if ((*this)->isObjCLifetimeType())
01064         return false;
01065       break;
01066     }        
01067   }
01068 
01069   // C++0x [basic.types]p9
01070   //   Scalar types, trivially copyable class types, arrays of such types, and
01071   //   cv-qualified versions of these types are collectively called trivial
01072   //   types.
01073 
01074   QualType CanonicalType = getCanonicalType();
01075   if (CanonicalType->isDependentType())
01076     return false;
01077 
01078   // Return false for incomplete types after skipping any incomplete array types
01079   // which are expressly allowed by the standard and thus our API.
01080   if (CanonicalType->isIncompleteType())
01081     return false;
01082  
01083   // As an extension, Clang treats vector types as Scalar types.
01084   if (CanonicalType->isScalarType() || CanonicalType->isVectorType())
01085     return true;
01086 
01087   if (const RecordType *RT = CanonicalType->getAs<RecordType>()) {
01088     if (const CXXRecordDecl *ClassDecl =
01089           dyn_cast<CXXRecordDecl>(RT->getDecl())) {
01090       if (!ClassDecl->isTriviallyCopyable()) return false;
01091     }
01092 
01093     return true;
01094   }
01095 
01096   // No other types can match.
01097   return false;
01098 }
01099 
01100 
01101 
01102 bool Type::isLiteralType() const {
01103   if (isDependentType())
01104     return false;
01105 
01106   // C++0x [basic.types]p10:
01107   //   A type is a literal type if it is:
01108   //   [...]
01109   //   -- an array of literal type.
01110   // Extension: variable arrays cannot be literal types, since they're
01111   // runtime-sized.
01112   if (isVariableArrayType())
01113     return false;
01114   const Type *BaseTy = getBaseElementTypeUnsafe();
01115   assert(BaseTy && "NULL element type");
01116 
01117   // Return false for incomplete types after skipping any incomplete array
01118   // types; those are expressly allowed by the standard and thus our API.
01119   if (BaseTy->isIncompleteType())
01120     return false;
01121 
01122   // C++0x [basic.types]p10:
01123   //   A type is a literal type if it is:
01124   //    -- a scalar type; or
01125   // As an extension, Clang treats vector types and complex types as
01126   // literal types.
01127   if (BaseTy->isScalarType() || BaseTy->isVectorType() ||
01128       BaseTy->isAnyComplexType())
01129     return true;
01130   //    -- a reference type; or
01131   if (BaseTy->isReferenceType())
01132     return true;
01133   //    -- a class type that has all of the following properties:
01134   if (const RecordType *RT = BaseTy->getAs<RecordType>()) {
01135     //    -- a trivial destructor,
01136     //    -- every constructor call and full-expression in the
01137     //       brace-or-equal-initializers for non-static data members (if any)
01138     //       is a constant expression,
01139     //    -- it is an aggregate type or has at least one constexpr
01140     //       constructor or constructor template that is not a copy or move
01141     //       constructor, and
01142     //    -- all non-static data members and base classes of literal types
01143     //
01144     // We resolve DR1361 by ignoring the second bullet.
01145     if (const CXXRecordDecl *ClassDecl =
01146         dyn_cast<CXXRecordDecl>(RT->getDecl()))
01147       return ClassDecl->isLiteral();
01148 
01149     return true;
01150   }
01151 
01152   return false;
01153 }
01154 
01155 bool Type::isStandardLayoutType() const {
01156   if (isDependentType())
01157     return false;
01158 
01159   // C++0x [basic.types]p9:
01160   //   Scalar types, standard-layout class types, arrays of such types, and
01161   //   cv-qualified versions of these types are collectively called
01162   //   standard-layout types.
01163   const Type *BaseTy = getBaseElementTypeUnsafe();
01164   assert(BaseTy && "NULL element type");
01165 
01166   // Return false for incomplete types after skipping any incomplete array
01167   // types which are expressly allowed by the standard and thus our API.
01168   if (BaseTy->isIncompleteType())
01169     return false;
01170 
01171   // As an extension, Clang treats vector types as Scalar types.
01172   if (BaseTy->isScalarType() || BaseTy->isVectorType()) return true;
01173   if (const RecordType *RT = BaseTy->getAs<RecordType>()) {
01174     if (const CXXRecordDecl *ClassDecl =
01175         dyn_cast<CXXRecordDecl>(RT->getDecl()))
01176       if (!ClassDecl->isStandardLayout())
01177         return false;
01178 
01179     // Default to 'true' for non-C++ class types.
01180     // FIXME: This is a bit dubious, but plain C structs should trivially meet
01181     // all the requirements of standard layout classes.
01182     return true;
01183   }
01184 
01185   // No other types can match.
01186   return false;
01187 }
01188 
01189 // This is effectively the intersection of isTrivialType and
01190 // isStandardLayoutType. We implement it directly to avoid redundant
01191 // conversions from a type to a CXXRecordDecl.
01192 bool QualType::isCXX11PODType(ASTContext &Context) const {
01193   const Type *ty = getTypePtr();
01194   if (ty->isDependentType())
01195     return false;
01196 
01197   if (Context.getLangOpts().ObjCAutoRefCount) {
01198     switch (getObjCLifetime()) {
01199     case Qualifiers::OCL_ExplicitNone:
01200       return true;
01201       
01202     case Qualifiers::OCL_Strong:
01203     case Qualifiers::OCL_Weak:
01204     case Qualifiers::OCL_Autoreleasing:
01205       return false;
01206 
01207     case Qualifiers::OCL_None:
01208       if (ty->isObjCLifetimeType())
01209         return false;
01210       break;
01211     }        
01212   }
01213 
01214   // C++11 [basic.types]p9:
01215   //   Scalar types, POD classes, arrays of such types, and cv-qualified
01216   //   versions of these types are collectively called trivial types.
01217   const Type *BaseTy = ty->getBaseElementTypeUnsafe();
01218   assert(BaseTy && "NULL element type");
01219 
01220   // Return false for incomplete types after skipping any incomplete array
01221   // types which are expressly allowed by the standard and thus our API.
01222   if (BaseTy->isIncompleteType())
01223     return false;
01224 
01225   // As an extension, Clang treats vector types as Scalar types.
01226   if (BaseTy->isScalarType() || BaseTy->isVectorType()) return true;
01227   if (const RecordType *RT = BaseTy->getAs<RecordType>()) {
01228     if (const CXXRecordDecl *ClassDecl =
01229         dyn_cast<CXXRecordDecl>(RT->getDecl())) {
01230       // C++11 [class]p10:
01231       //   A POD struct is a non-union class that is both a trivial class [...]
01232       if (!ClassDecl->isTrivial()) return false;
01233 
01234       // C++11 [class]p10:
01235       //   A POD struct is a non-union class that is both a trivial class and
01236       //   a standard-layout class [...]
01237       if (!ClassDecl->isStandardLayout()) return false;
01238 
01239       // C++11 [class]p10:
01240       //   A POD struct is a non-union class that is both a trivial class and
01241       //   a standard-layout class, and has no non-static data members of type
01242       //   non-POD struct, non-POD union (or array of such types). [...]
01243       //
01244       // We don't directly query the recursive aspect as the requiremets for
01245       // both standard-layout classes and trivial classes apply recursively
01246       // already.
01247     }
01248 
01249     return true;
01250   }
01251 
01252   // No other types can match.
01253   return false;
01254 }
01255 
01256 bool Type::isPromotableIntegerType() const {
01257   if (const BuiltinType *BT = getAs<BuiltinType>())
01258     switch (BT->getKind()) {
01259     case BuiltinType::Bool:
01260     case BuiltinType::Char_S:
01261     case BuiltinType::Char_U:
01262     case BuiltinType::SChar:
01263     case BuiltinType::UChar:
01264     case BuiltinType::Short:
01265     case BuiltinType::UShort:
01266     case BuiltinType::WChar_S:
01267     case BuiltinType::WChar_U:
01268     case BuiltinType::Char16:
01269     case BuiltinType::Char32:
01270       return true;
01271     default:
01272       return false;
01273     }
01274 
01275   // Enumerated types are promotable to their compatible integer types
01276   // (C99 6.3.1.1) a.k.a. its underlying type (C++ [conv.prom]p2).
01277   if (const EnumType *ET = getAs<EnumType>()){
01278     if (this->isDependentType() || ET->getDecl()->getPromotionType().isNull()
01279         || ET->getDecl()->isScoped())
01280       return false;
01281     
01282     return true;
01283   }
01284   
01285   return false;
01286 }
01287 
01288 bool Type::isSpecifierType() const {
01289   // Note that this intentionally does not use the canonical type.
01290   switch (getTypeClass()) {
01291   case Builtin:
01292   case Record:
01293   case Enum:
01294   case Typedef:
01295   case Complex:
01296   case TypeOfExpr:
01297   case TypeOf:
01298   case TemplateTypeParm:
01299   case SubstTemplateTypeParm:
01300   case TemplateSpecialization:
01301   case Elaborated:
01302   case DependentName:
01303   case DependentTemplateSpecialization:
01304   case ObjCInterface:
01305   case ObjCObject:
01306   case ObjCObjectPointer: // FIXME: object pointers aren't really specifiers
01307     return true;
01308   default:
01309     return false;
01310   }
01311 }
01312 
01313 ElaboratedTypeKeyword
01314 TypeWithKeyword::getKeywordForTypeSpec(unsigned TypeSpec) {
01315   switch (TypeSpec) {
01316   default: return ETK_None;
01317   case TST_typename: return ETK_Typename;
01318   case TST_class: return ETK_Class;
01319   case TST_struct: return ETK_Struct;
01320   case TST_union: return ETK_Union;
01321   case TST_enum: return ETK_Enum;
01322   }
01323 }
01324 
01325 TagTypeKind
01326 TypeWithKeyword::getTagTypeKindForTypeSpec(unsigned TypeSpec) {
01327   switch(TypeSpec) {
01328   case TST_class: return TTK_Class;
01329   case TST_struct: return TTK_Struct;
01330   case TST_union: return TTK_Union;
01331   case TST_enum: return TTK_Enum;
01332   }
01333   
01334   llvm_unreachable("Type specifier is not a tag type kind.");
01335 }
01336 
01337 ElaboratedTypeKeyword
01338 TypeWithKeyword::getKeywordForTagTypeKind(TagTypeKind Kind) {
01339   switch (Kind) {
01340   case TTK_Class: return ETK_Class;
01341   case TTK_Struct: return ETK_Struct;
01342   case TTK_Union: return ETK_Union;
01343   case TTK_Enum: return ETK_Enum;
01344   }
01345   llvm_unreachable("Unknown tag type kind.");
01346 }
01347 
01348 TagTypeKind
01349 TypeWithKeyword::getTagTypeKindForKeyword(ElaboratedTypeKeyword Keyword) {
01350   switch (Keyword) {
01351   case ETK_Class: return TTK_Class;
01352   case ETK_Struct: return TTK_Struct;
01353   case ETK_Union: return TTK_Union;
01354   case ETK_Enum: return TTK_Enum;
01355   case ETK_None: // Fall through.
01356   case ETK_Typename:
01357     llvm_unreachable("Elaborated type keyword is not a tag type kind.");
01358   }
01359   llvm_unreachable("Unknown elaborated type keyword.");
01360 }
01361 
01362 bool
01363 TypeWithKeyword::KeywordIsTagTypeKind(ElaboratedTypeKeyword Keyword) {
01364   switch (Keyword) {
01365   case ETK_None:
01366   case ETK_Typename:
01367     return false;
01368   case ETK_Class:
01369   case ETK_Struct:
01370   case ETK_Union:
01371   case ETK_Enum:
01372     return true;
01373   }
01374   llvm_unreachable("Unknown elaborated type keyword.");
01375 }
01376 
01377 const char*
01378 TypeWithKeyword::getKeywordName(ElaboratedTypeKeyword Keyword) {
01379   switch (Keyword) {
01380   case ETK_None: return "";
01381   case ETK_Typename: return "typename";
01382   case ETK_Class:  return "class";
01383   case ETK_Struct: return "struct";
01384   case ETK_Union:  return "union";
01385   case ETK_Enum:   return "enum";
01386   }
01387 
01388   llvm_unreachable("Unknown elaborated type keyword.");
01389 }
01390 
01391 DependentTemplateSpecializationType::DependentTemplateSpecializationType(
01392                          ElaboratedTypeKeyword Keyword,
01393                          NestedNameSpecifier *NNS, const IdentifierInfo *Name,
01394                          unsigned NumArgs, const TemplateArgument *Args,
01395                          QualType Canon)
01396   : TypeWithKeyword(Keyword, DependentTemplateSpecialization, Canon, true, true,
01397                     /*VariablyModified=*/false,
01398                     NNS && NNS->containsUnexpandedParameterPack()),
01399     NNS(NNS), Name(Name), NumArgs(NumArgs) {
01400   assert((!NNS || NNS->isDependent()) &&
01401          "DependentTemplateSpecializatonType requires dependent qualifier");
01402   for (unsigned I = 0; I != NumArgs; ++I) {
01403     if (Args[I].containsUnexpandedParameterPack())
01404       setContainsUnexpandedParameterPack();
01405 
01406     new (&getArgBuffer()[I]) TemplateArgument(Args[I]);
01407   }
01408 }
01409 
01410 void
01411 DependentTemplateSpecializationType::Profile(llvm::FoldingSetNodeID &ID,
01412                                              const ASTContext &Context,
01413                                              ElaboratedTypeKeyword Keyword,
01414                                              NestedNameSpecifier *Qualifier,
01415                                              const IdentifierInfo *Name,
01416                                              unsigned NumArgs,
01417                                              const TemplateArgument *Args) {
01418   ID.AddInteger(Keyword);
01419   ID.AddPointer(Qualifier);
01420   ID.AddPointer(Name);
01421   for (unsigned Idx = 0; Idx < NumArgs; ++Idx)
01422     Args[Idx].Profile(ID, Context);
01423 }
01424 
01425 bool Type::isElaboratedTypeSpecifier() const {
01426   ElaboratedTypeKeyword Keyword;
01427   if (const ElaboratedType *Elab = dyn_cast<ElaboratedType>(this))
01428     Keyword = Elab->getKeyword();
01429   else if (const DependentNameType *DepName = dyn_cast<DependentNameType>(this))
01430     Keyword = DepName->getKeyword();
01431   else if (const DependentTemplateSpecializationType *DepTST =
01432              dyn_cast<DependentTemplateSpecializationType>(this))
01433     Keyword = DepTST->getKeyword();
01434   else
01435     return false;
01436 
01437   return TypeWithKeyword::KeywordIsTagTypeKind(Keyword);
01438 }
01439 
01440 const char *Type::getTypeClassName() const {
01441   switch (TypeBits.TC) {
01442 #define ABSTRACT_TYPE(Derived, Base)
01443 #define TYPE(Derived, Base) case Derived: return #Derived;
01444 #include "clang/AST/TypeNodes.def"
01445   }
01446   
01447   llvm_unreachable("Invalid type class.");
01448 }
01449 
01450 StringRef BuiltinType::getName(const PrintingPolicy &Policy) const {
01451   switch (getKind()) {
01452   case Void:              return "void";
01453   case Bool:              return Policy.Bool ? "bool" : "_Bool";
01454   case Char_S:            return "char";
01455   case Char_U:            return "char";
01456   case SChar:             return "signed char";
01457   case Short:             return "short";
01458   case Int:               return "int";
01459   case Long:              return "long";
01460   case LongLong:          return "long long";
01461   case Int128:            return "__int128";
01462   case UChar:             return "unsigned char";
01463   case UShort:            return "unsigned short";
01464   case UInt:              return "unsigned int";
01465   case ULong:             return "unsigned long";
01466   case ULongLong:         return "unsigned long long";
01467   case UInt128:           return "unsigned __int128";
01468   case Half:              return "half";
01469   case Float:             return "float";
01470   case Double:            return "double";
01471   case LongDouble:        return "long double";
01472   case WChar_S:
01473   case WChar_U:           return "wchar_t";
01474   case Char16:            return "char16_t";
01475   case Char32:            return "char32_t";
01476   case NullPtr:           return "nullptr_t";
01477   case Overload:          return "<overloaded function type>";
01478   case BoundMember:       return "<bound member function type>";
01479   case PseudoObject:      return "<pseudo-object type>";
01480   case Dependent:         return "<dependent type>";
01481   case UnknownAny:        return "<unknown type>";
01482   case ARCUnbridgedCast:  return "<ARC unbridged cast type>";
01483   case ObjCId:            return "id";
01484   case ObjCClass:         return "Class";
01485   case ObjCSel:           return "SEL";
01486   }
01487   
01488   llvm_unreachable("Invalid builtin type.");
01489 }
01490 
01491 QualType QualType::getNonLValueExprType(ASTContext &Context) const {
01492   if (const ReferenceType *RefType = getTypePtr()->getAs<ReferenceType>())
01493     return RefType->getPointeeType();
01494   
01495   // C++0x [basic.lval]:
01496   //   Class prvalues can have cv-qualified types; non-class prvalues always 
01497   //   have cv-unqualified types.
01498   //
01499   // See also C99 6.3.2.1p2.
01500   if (!Context.getLangOpts().CPlusPlus ||
01501       (!getTypePtr()->isDependentType() && !getTypePtr()->isRecordType()))
01502     return getUnqualifiedType();
01503   
01504   return *this;
01505 }
01506 
01507 StringRef FunctionType::getNameForCallConv(CallingConv CC) {
01508   switch (CC) {
01509   case CC_Default: 
01510     llvm_unreachable("no name for default cc");
01511 
01512   case CC_C: return "cdecl";
01513   case CC_X86StdCall: return "stdcall";
01514   case CC_X86FastCall: return "fastcall";
01515   case CC_X86ThisCall: return "thiscall";
01516   case CC_X86Pascal: return "pascal";
01517   case CC_AAPCS: return "aapcs";
01518   case CC_AAPCS_VFP: return "aapcs-vfp";
01519   }
01520 
01521   llvm_unreachable("Invalid calling convention.");
01522 }
01523 
01524 FunctionProtoType::FunctionProtoType(QualType result, const QualType *args,
01525                                      unsigned numArgs, QualType canonical,
01526                                      const ExtProtoInfo &epi)
01527   : FunctionType(FunctionProto, result, epi.TypeQuals, epi.RefQualifier,
01528                  canonical,
01529                  result->isDependentType(),
01530                  result->isInstantiationDependentType(),
01531                  result->isVariablyModifiedType(),
01532                  result->containsUnexpandedParameterPack(),
01533                  epi.ExtInfo),
01534     NumArgs(numArgs), NumExceptions(epi.NumExceptions),
01535     ExceptionSpecType(epi.ExceptionSpecType),
01536     HasAnyConsumedArgs(epi.ConsumedArguments != 0),
01537     Variadic(epi.Variadic), HasTrailingReturn(epi.HasTrailingReturn)
01538 {
01539   // Fill in the trailing argument array.
01540   QualType *argSlot = reinterpret_cast<QualType*>(this+1);
01541   for (unsigned i = 0; i != numArgs; ++i) {
01542     if (args[i]->isDependentType())
01543       setDependent();
01544     else if (args[i]->isInstantiationDependentType())
01545       setInstantiationDependent();
01546     
01547     if (args[i]->containsUnexpandedParameterPack())
01548       setContainsUnexpandedParameterPack();
01549 
01550     argSlot[i] = args[i];
01551   }
01552 
01553   if (getExceptionSpecType() == EST_Dynamic) {
01554     // Fill in the exception array.
01555     QualType *exnSlot = argSlot + numArgs;
01556     for (unsigned i = 0, e = epi.NumExceptions; i != e; ++i) {
01557       if (epi.Exceptions[i]->isDependentType())
01558         setDependent();
01559       else if (epi.Exceptions[i]->isInstantiationDependentType())
01560         setInstantiationDependent();
01561       
01562       if (epi.Exceptions[i]->containsUnexpandedParameterPack())
01563         setContainsUnexpandedParameterPack();
01564 
01565       exnSlot[i] = epi.Exceptions[i];
01566     }
01567   } else if (getExceptionSpecType() == EST_ComputedNoexcept) {
01568     // Store the noexcept expression and context.
01569     Expr **noexSlot = reinterpret_cast<Expr**>(argSlot + numArgs);
01570     *noexSlot = epi.NoexceptExpr;
01571     
01572     if (epi.NoexceptExpr) {
01573       if (epi.NoexceptExpr->isValueDependent() 
01574           || epi.NoexceptExpr->isTypeDependent())
01575         setDependent();
01576       else if (epi.NoexceptExpr->isInstantiationDependent())
01577         setInstantiationDependent();
01578     }
01579   } else if (getExceptionSpecType() == EST_Uninstantiated) {
01580     // Store the function decl from which we will resolve our
01581     // exception specification.
01582     FunctionDecl **slot = reinterpret_cast<FunctionDecl**>(argSlot + numArgs);
01583     slot[0] = epi.ExceptionSpecDecl;
01584     slot[1] = epi.ExceptionSpecTemplate;
01585     // This exception specification doesn't make the type dependent, because
01586     // it's not instantiated as part of instantiating the type.
01587   }
01588 
01589   if (epi.ConsumedArguments) {
01590     bool *consumedArgs = const_cast<bool*>(getConsumedArgsBuffer());
01591     for (unsigned i = 0; i != numArgs; ++i)
01592       consumedArgs[i] = epi.ConsumedArguments[i];
01593   }
01594 }
01595 
01596 FunctionProtoType::NoexceptResult
01597 FunctionProtoType::getNoexceptSpec(ASTContext &ctx) const {
01598   ExceptionSpecificationType est = getExceptionSpecType();
01599   if (est == EST_BasicNoexcept)
01600     return NR_Nothrow;
01601 
01602   if (est != EST_ComputedNoexcept)
01603     return NR_NoNoexcept;
01604 
01605   Expr *noexceptExpr = getNoexceptExpr();
01606   if (!noexceptExpr)
01607     return NR_BadNoexcept;
01608   if (noexceptExpr->isValueDependent())
01609     return NR_Dependent;
01610 
01611   llvm::APSInt value;
01612   bool isICE = noexceptExpr->isIntegerConstantExpr(value, ctx, 0,
01613                                                    /*evaluated*/false);
01614   (void)isICE;
01615   assert(isICE && "AST should not contain bad noexcept expressions.");
01616 
01617   return value.getBoolValue() ? NR_Nothrow : NR_Throw;
01618 }
01619 
01620 bool FunctionProtoType::isTemplateVariadic() const {
01621   for (unsigned ArgIdx = getNumArgs(); ArgIdx; --ArgIdx)
01622     if (isa<PackExpansionType>(getArgType(ArgIdx - 1)))
01623       return true;
01624   
01625   return false;
01626 }
01627 
01628 void FunctionProtoType::Profile(llvm::FoldingSetNodeID &ID, QualType Result,
01629                                 const QualType *ArgTys, unsigned NumArgs,
01630                                 const ExtProtoInfo &epi,
01631                                 const ASTContext &Context) {
01632 
01633   // We have to be careful not to get ambiguous profile encodings.
01634   // Note that valid type pointers are never ambiguous with anything else.
01635   //
01636   // The encoding grammar begins:
01637   //      type type* bool int bool 
01638   // If that final bool is true, then there is a section for the EH spec:
01639   //      bool type*
01640   // This is followed by an optional "consumed argument" section of the
01641   // same length as the first type sequence:
01642   //      bool*
01643   // Finally, we have the ext info and trailing return type flag:
01644   //      int bool
01645   // 
01646   // There is no ambiguity between the consumed arguments and an empty EH
01647   // spec because of the leading 'bool' which unambiguously indicates
01648   // whether the following bool is the EH spec or part of the arguments.
01649 
01650   ID.AddPointer(Result.getAsOpaquePtr());
01651   for (unsigned i = 0; i != NumArgs; ++i)
01652     ID.AddPointer(ArgTys[i].getAsOpaquePtr());
01653   // This method is relatively performance sensitive, so as a performance
01654   // shortcut, use one AddInteger call instead of four for the next four
01655   // fields.
01656   assert(!(unsigned(epi.Variadic) & ~1) &&
01657          !(unsigned(epi.TypeQuals) & ~255) &&
01658          !(unsigned(epi.RefQualifier) & ~3) &&
01659          !(unsigned(epi.ExceptionSpecType) & ~7) &&
01660          "Values larger than expected.");
01661   ID.AddInteger(unsigned(epi.Variadic) +
01662                 (epi.TypeQuals << 1) +
01663                 (epi.RefQualifier << 9) +
01664                 (epi.ExceptionSpecType << 11));
01665   if (epi.ExceptionSpecType == EST_Dynamic) {
01666     for (unsigned i = 0; i != epi.NumExceptions; ++i)
01667       ID.AddPointer(epi.Exceptions[i].getAsOpaquePtr());
01668   } else if (epi.ExceptionSpecType == EST_ComputedNoexcept && epi.NoexceptExpr){
01669     epi.NoexceptExpr->Profile(ID, Context, false);
01670   } else if (epi.ExceptionSpecType == EST_Uninstantiated) {
01671     ID.AddPointer(epi.ExceptionSpecDecl->getCanonicalDecl());
01672   }
01673   if (epi.ConsumedArguments) {
01674     for (unsigned i = 0; i != NumArgs; ++i)
01675       ID.AddBoolean(epi.ConsumedArguments[i]);
01676   }
01677   epi.ExtInfo.Profile(ID);
01678   ID.AddBoolean(epi.HasTrailingReturn);
01679 }
01680 
01681 void FunctionProtoType::Profile(llvm::FoldingSetNodeID &ID,
01682                                 const ASTContext &Ctx) {
01683   Profile(ID, getResultType(), arg_type_begin(), NumArgs, getExtProtoInfo(),
01684           Ctx);
01685 }
01686 
01687 QualType TypedefType::desugar() const {
01688   return getDecl()->getUnderlyingType();
01689 }
01690 
01691 TypeOfExprType::TypeOfExprType(Expr *E, QualType can)
01692   : Type(TypeOfExpr, can, E->isTypeDependent(), 
01693          E->isInstantiationDependent(),
01694          E->getType()->isVariablyModifiedType(),
01695          E->containsUnexpandedParameterPack()), 
01696     TOExpr(E) {
01697 }
01698 
01699 bool TypeOfExprType::isSugared() const {
01700   return !TOExpr->isTypeDependent();
01701 }
01702 
01703 QualType TypeOfExprType::desugar() const {
01704   if (isSugared())
01705     return getUnderlyingExpr()->getType();
01706   
01707   return QualType(this, 0);
01708 }
01709 
01710 void DependentTypeOfExprType::Profile(llvm::FoldingSetNodeID &ID,
01711                                       const ASTContext &Context, Expr *E) {
01712   E->Profile(ID, Context, true);
01713 }
01714 
01715 DecltypeType::DecltypeType(Expr *E, QualType underlyingType, QualType can)
01716   // C++11 [temp.type]p2: "If an expression e involves a template parameter,
01717   // decltype(e) denotes a unique dependent type." Hence a decltype type is
01718   // type-dependent even if its expression is only instantiation-dependent.
01719   : Type(Decltype, can, E->isInstantiationDependent(),
01720          E->isInstantiationDependent(),
01721          E->getType()->isVariablyModifiedType(), 
01722          E->containsUnexpandedParameterPack()), 
01723     E(E),
01724   UnderlyingType(underlyingType) {
01725 }
01726 
01727 bool DecltypeType::isSugared() const { return !E->isInstantiationDependent(); }
01728 
01729 QualType DecltypeType::desugar() const {
01730   if (isSugared())
01731     return getUnderlyingType();
01732   
01733   return QualType(this, 0);
01734 }
01735 
01736 DependentDecltypeType::DependentDecltypeType(const ASTContext &Context, Expr *E)
01737   : DecltypeType(E, Context.DependentTy), Context(Context) { }
01738 
01739 void DependentDecltypeType::Profile(llvm::FoldingSetNodeID &ID,
01740                                     const ASTContext &Context, Expr *E) {
01741   E->Profile(ID, Context, true);
01742 }
01743 
01744 TagType::TagType(TypeClass TC, const TagDecl *D, QualType can)
01745   : Type(TC, can, D->isDependentType(), 
01746          /*InstantiationDependent=*/D->isDependentType(),
01747          /*VariablyModified=*/false, 
01748          /*ContainsUnexpandedParameterPack=*/false),
01749     decl(const_cast<TagDecl*>(D)) {}
01750 
01751 static TagDecl *getInterestingTagDecl(TagDecl *decl) {
01752   for (TagDecl::redecl_iterator I = decl->redecls_begin(),
01753                                 E = decl->redecls_end();
01754        I != E; ++I) {
01755     if (I->isCompleteDefinition() || I->isBeingDefined())
01756       return *I;
01757   }
01758   // If there's no definition (not even in progress), return what we have.
01759   return decl;
01760 }
01761 
01762 UnaryTransformType::UnaryTransformType(QualType BaseType,
01763                                        QualType UnderlyingType,
01764                                        UTTKind UKind,
01765                                        QualType CanonicalType)
01766   : Type(UnaryTransform, CanonicalType, UnderlyingType->isDependentType(),
01767          UnderlyingType->isInstantiationDependentType(),
01768          UnderlyingType->isVariablyModifiedType(),
01769          BaseType->containsUnexpandedParameterPack())
01770   , BaseType(BaseType), UnderlyingType(UnderlyingType), UKind(UKind)
01771 {}
01772 
01773 TagDecl *TagType::getDecl() const {
01774   return getInterestingTagDecl(decl);
01775 }
01776 
01777 bool TagType::isBeingDefined() const {
01778   return getDecl()->isBeingDefined();
01779 }
01780 
01781 CXXRecordDecl *InjectedClassNameType::getDecl() const {
01782   return cast<CXXRecordDecl>(getInterestingTagDecl(Decl));
01783 }
01784 
01785 IdentifierInfo *TemplateTypeParmType::getIdentifier() const {
01786   return isCanonicalUnqualified() ? 0 : getDecl()->getIdentifier();
01787 }
01788 
01789 SubstTemplateTypeParmPackType::
01790 SubstTemplateTypeParmPackType(const TemplateTypeParmType *Param, 
01791                               QualType Canon,
01792                               const TemplateArgument &ArgPack)
01793   : Type(SubstTemplateTypeParmPack, Canon, true, true, false, true), 
01794     Replaced(Param), 
01795     Arguments(ArgPack.pack_begin()), NumArguments(ArgPack.pack_size()) 
01796 { 
01797 }
01798 
01799 TemplateArgument SubstTemplateTypeParmPackType::getArgumentPack() const {
01800   return TemplateArgument(Arguments, NumArguments);
01801 }
01802 
01803 void SubstTemplateTypeParmPackType::Profile(llvm::FoldingSetNodeID &ID) {
01804   Profile(ID, getReplacedParameter(), getArgumentPack());
01805 }
01806 
01807 void SubstTemplateTypeParmPackType::Profile(llvm::FoldingSetNodeID &ID,
01808                                            const TemplateTypeParmType *Replaced,
01809                                             const TemplateArgument &ArgPack) {
01810   ID.AddPointer(Replaced);
01811   ID.AddInteger(ArgPack.pack_size());
01812   for (TemplateArgument::pack_iterator P = ArgPack.pack_begin(), 
01813                                     PEnd = ArgPack.pack_end();
01814        P != PEnd; ++P)
01815     ID.AddPointer(P->getAsType().getAsOpaquePtr());
01816 }
01817 
01818 bool TemplateSpecializationType::
01819 anyDependentTemplateArguments(const TemplateArgumentListInfo &Args,
01820                               bool &InstantiationDependent) {
01821   return anyDependentTemplateArguments(Args.getArgumentArray(), Args.size(),
01822                                        InstantiationDependent);
01823 }
01824 
01825 bool TemplateSpecializationType::
01826 anyDependentTemplateArguments(const TemplateArgumentLoc *Args, unsigned N,
01827                               bool &InstantiationDependent) {
01828   for (unsigned i = 0; i != N; ++i) {
01829     if (Args[i].getArgument().isDependent()) {
01830       InstantiationDependent = true;
01831       return true;
01832     }
01833     
01834     if (Args[i].getArgument().isInstantiationDependent())
01835       InstantiationDependent = true;
01836   }
01837   return false;
01838 }
01839 
01840 bool TemplateSpecializationType::
01841 anyDependentTemplateArguments(const TemplateArgument *Args, unsigned N,
01842                               bool &InstantiationDependent) {
01843   for (unsigned i = 0; i != N; ++i) {
01844     if (Args[i].isDependent()) {
01845       InstantiationDependent = true;
01846       return true;
01847     }
01848     
01849     if (Args[i].isInstantiationDependent())
01850       InstantiationDependent = true;
01851   }
01852   return false;
01853 }
01854 
01855 TemplateSpecializationType::
01856 TemplateSpecializationType(TemplateName T,
01857                            const TemplateArgument *Args, unsigned NumArgs,
01858                            QualType Canon, QualType AliasedType)
01859   : Type(TemplateSpecialization,
01860          Canon.isNull()? QualType(this, 0) : Canon,
01861          Canon.isNull()? T.isDependent() : Canon->isDependentType(),
01862          Canon.isNull()? T.isDependent() 
01863                        : Canon->isInstantiationDependentType(),
01864          false,
01865          Canon.isNull()? T.containsUnexpandedParameterPack()
01866                        : Canon->containsUnexpandedParameterPack()),
01867     Template(T), NumArgs(NumArgs), TypeAlias(!AliasedType.isNull()) {
01868   assert(!T.getAsDependentTemplateName() && 
01869          "Use DependentTemplateSpecializationType for dependent template-name");
01870   assert((T.getKind() == TemplateName::Template ||
01871           T.getKind() == TemplateName::SubstTemplateTemplateParm ||
01872           T.getKind() == TemplateName::SubstTemplateTemplateParmPack) &&
01873          "Unexpected template name for TemplateSpecializationType");
01874   bool InstantiationDependent;
01875   (void)InstantiationDependent;
01876   assert((!Canon.isNull() ||
01877           T.isDependent() || 
01878           anyDependentTemplateArguments(Args, NumArgs, 
01879                                         InstantiationDependent)) &&
01880          "No canonical type for non-dependent class template specialization");
01881 
01882   TemplateArgument *TemplateArgs
01883     = reinterpret_cast<TemplateArgument *>(this + 1);
01884   for (unsigned Arg = 0; Arg < NumArgs; ++Arg) {
01885     // Update dependent and variably-modified bits.
01886     // If the canonical type exists and is non-dependent, the template
01887     // specialization type can be non-dependent even if one of the type
01888     // arguments is. Given:
01889     //   template<typename T> using U = int;
01890     // U<T> is always non-dependent, irrespective of the type T.
01891     if (Canon.isNull() && Args[Arg].isDependent())
01892       setDependent();
01893     else if (Args[Arg].isInstantiationDependent())
01894       setInstantiationDependent();
01895     
01896     if (Args[Arg].getKind() == TemplateArgument::Type &&
01897         Args[Arg].getAsType()->isVariablyModifiedType())
01898       setVariablyModified();
01899     if (Canon.isNull() && Args[Arg].containsUnexpandedParameterPack())
01900       setContainsUnexpandedParameterPack();
01901 
01902     new (&TemplateArgs[Arg]) TemplateArgument(Args[Arg]);
01903   }
01904 
01905   // Store the aliased type if this is a type alias template specialization.
01906   if (TypeAlias) {
01907     TemplateArgument *Begin = reinterpret_cast<TemplateArgument *>(this + 1);
01908     *reinterpret_cast<QualType*>(Begin + getNumArgs()) = AliasedType;
01909   }
01910 }
01911 
01912 void
01913 TemplateSpecializationType::Profile(llvm::FoldingSetNodeID &ID,
01914                                     TemplateName T,
01915                                     const TemplateArgument *Args,
01916                                     unsigned NumArgs,
01917                                     const ASTContext &Context) {
01918   T.Profile(ID);
01919   for (unsigned Idx = 0; Idx < NumArgs; ++Idx)
01920     Args[Idx].Profile(ID, Context);
01921 }
01922 
01923 QualType
01924 QualifierCollector::apply(const ASTContext &Context, QualType QT) const {
01925   if (!hasNonFastQualifiers())
01926     return QT.withFastQualifiers(getFastQualifiers());
01927 
01928   return Context.getQualifiedType(QT, *this);
01929 }
01930 
01931 QualType
01932 QualifierCollector::apply(const ASTContext &Context, const Type *T) const {
01933   if (!hasNonFastQualifiers())
01934     return QualType(T, getFastQualifiers());
01935 
01936   return Context.getQualifiedType(T, *this);
01937 }
01938 
01939 void ObjCObjectTypeImpl::Profile(llvm::FoldingSetNodeID &ID,
01940                                  QualType BaseType,
01941                                  ObjCProtocolDecl * const *Protocols,
01942                                  unsigned NumProtocols) {
01943   ID.AddPointer(BaseType.getAsOpaquePtr());
01944   for (unsigned i = 0; i != NumProtocols; i++)
01945     ID.AddPointer(Protocols[i]);
01946 }
01947 
01948 void ObjCObjectTypeImpl::Profile(llvm::FoldingSetNodeID &ID) {
01949   Profile(ID, getBaseType(), qual_begin(), getNumProtocols());
01950 }
01951 
01952 namespace {
01953 
01954 /// \brief The cached properties of a type.
01955 class CachedProperties {
01956   NamedDecl::LinkageInfo LV;
01957   bool local;
01958   
01959 public:
01960   CachedProperties(NamedDecl::LinkageInfo LV, bool local)
01961     : LV(LV), local(local) {}
01962   
01963   Linkage getLinkage() const { return LV.linkage(); }
01964   Visibility getVisibility() const { return LV.visibility(); }
01965   bool isVisibilityExplicit() const { return LV.visibilityExplicit(); }
01966   bool hasLocalOrUnnamedType() const { return local; }
01967   
01968   friend CachedProperties merge(CachedProperties L, CachedProperties R) {
01969     NamedDecl::LinkageInfo MergedLV = L.LV;
01970     MergedLV.merge(R.LV);
01971     return CachedProperties(MergedLV,
01972                          L.hasLocalOrUnnamedType() | R.hasLocalOrUnnamedType());
01973   }
01974 };
01975 }
01976 
01977 static CachedProperties computeCachedProperties(const Type *T);
01978 
01979 namespace clang {
01980 /// The type-property cache.  This is templated so as to be
01981 /// instantiated at an internal type to prevent unnecessary symbol
01982 /// leakage.
01983 template <class Private> class TypePropertyCache {
01984 public:
01985   static CachedProperties get(QualType T) {
01986     return get(T.getTypePtr());
01987   }
01988 
01989   static CachedProperties get(const Type *T) {
01990     ensure(T);
01991     NamedDecl::LinkageInfo LV(T->TypeBits.getLinkage(),
01992                               T->TypeBits.getVisibility(),
01993                               T->TypeBits.isVisibilityExplicit());
01994     return CachedProperties(LV, T->TypeBits.hasLocalOrUnnamedType());
01995   }
01996 
01997   static void ensure(const Type *T) {
01998     // If the cache is valid, we're okay.
01999     if (T->TypeBits.isCacheValid()) return;
02000 
02001     // If this type is non-canonical, ask its canonical type for the
02002     // relevant information.
02003     if (!T->isCanonicalUnqualified()) {
02004       const Type *CT = T->getCanonicalTypeInternal().getTypePtr();
02005       ensure(CT);
02006       T->TypeBits.CacheValidAndVisibility =
02007         CT->TypeBits.CacheValidAndVisibility;
02008       T->TypeBits.CachedExplicitVisibility =
02009         CT->TypeBits.CachedExplicitVisibility;
02010       T->TypeBits.CachedLinkage = CT->TypeBits.CachedLinkage;
02011       T->TypeBits.CachedLocalOrUnnamed = CT->TypeBits.CachedLocalOrUnnamed;
02012       return;
02013     }
02014 
02015     // Compute the cached properties and then set the cache.
02016     CachedProperties Result = computeCachedProperties(T);
02017     T->TypeBits.CacheValidAndVisibility = Result.getVisibility() + 1U;
02018     T->TypeBits.CachedExplicitVisibility = Result.isVisibilityExplicit();
02019     assert(T->TypeBits.isCacheValid() &&
02020            T->TypeBits.getVisibility() == Result.getVisibility());
02021     T->TypeBits.CachedLinkage = Result.getLinkage();
02022     T->TypeBits.CachedLocalOrUnnamed = Result.hasLocalOrUnnamedType();
02023   }
02024 };
02025 }
02026 
02027 // Instantiate the friend template at a private class.  In a
02028 // reasonable implementation, these symbols will be internal.
02029 // It is terrible that this is the best way to accomplish this.
02030 namespace { class Private {}; }
02031 typedef TypePropertyCache<Private> Cache;
02032 
02033 static CachedProperties computeCachedProperties(const Type *T) {
02034   switch (T->getTypeClass()) {
02035 #define TYPE(Class,Base)
02036 #define NON_CANONICAL_TYPE(Class,Base) case Type::Class:
02037 #include "clang/AST/TypeNodes.def"
02038     llvm_unreachable("didn't expect a non-canonical type here");
02039 
02040 #define TYPE(Class,Base)
02041 #define DEPENDENT_TYPE(Class,Base) case Type::Class:
02042 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class,Base) case Type::Class:
02043 #include "clang/AST/TypeNodes.def"
02044     // Treat instantiation-dependent types as external.
02045     assert(T->isInstantiationDependentType());
02046     return CachedProperties(NamedDecl::LinkageInfo(), false);
02047 
02048   case Type::Builtin:
02049     // C++ [basic.link]p8:
02050     //   A type is said to have linkage if and only if:
02051     //     - it is a fundamental type (3.9.1); or
02052     return CachedProperties(NamedDecl::LinkageInfo(), false);
02053 
02054   case Type::Record:
02055   case Type::Enum: {
02056     const TagDecl *Tag = cast<TagType>(T)->getDecl();
02057 
02058     // C++ [basic.link]p8:
02059     //     - it is a class or enumeration type that is named (or has a name
02060     //       for linkage purposes (7.1.3)) and the name has linkage; or
02061     //     -  it is a specialization of a class template (14); or
02062     NamedDecl::LinkageInfo LV = Tag->getLinkageAndVisibility();
02063     bool IsLocalOrUnnamed =
02064       Tag->getDeclContext()->isFunctionOrMethod() ||
02065       (!Tag->getIdentifier() && !Tag->getTypedefNameForAnonDecl());
02066     return CachedProperties(LV, IsLocalOrUnnamed);
02067   }
02068 
02069     // C++ [basic.link]p8:
02070     //   - it is a compound type (3.9.2) other than a class or enumeration, 
02071     //     compounded exclusively from types that have linkage; or
02072   case Type::Complex:
02073     return Cache::get(cast<ComplexType>(T)->getElementType());
02074   case Type::Pointer:
02075     return Cache::get(cast<PointerType>(T)->getPointeeType());
02076   case Type::BlockPointer:
02077     return Cache::get(cast<BlockPointerType>(T)->getPointeeType());
02078   case Type::LValueReference:
02079   case Type::RValueReference:
02080     return Cache::get(cast<ReferenceType>(T)->getPointeeType());
02081   case Type::MemberPointer: {
02082     const MemberPointerType *MPT = cast<MemberPointerType>(T);
02083     return merge(Cache::get(MPT->getClass()),
02084                  Cache::get(MPT->getPointeeType()));
02085   }
02086   case Type::ConstantArray:
02087   case Type::IncompleteArray:
02088   case Type::VariableArray:
02089     return Cache::get(cast<ArrayType>(T)->getElementType());
02090   case Type::Vector:
02091   case Type::ExtVector:
02092     return Cache::get(cast<VectorType>(T)->getElementType());
02093   case Type::FunctionNoProto:
02094     return Cache::get(cast<FunctionType>(T)->getResultType());
02095   case Type::FunctionProto: {
02096     const FunctionProtoType *FPT = cast<FunctionProtoType>(T);
02097     CachedProperties result = Cache::get(FPT->getResultType());
02098     for (FunctionProtoType::arg_type_iterator ai = FPT->arg_type_begin(),
02099            ae = FPT->arg_type_end(); ai != ae; ++ai)
02100       result = merge(result, Cache::get(*ai));
02101     return result;
02102   }
02103   case Type::ObjCInterface: {
02104     NamedDecl::LinkageInfo LV =
02105       cast<ObjCInterfaceType>(T)->getDecl()->getLinkageAndVisibility();
02106     return CachedProperties(LV, false);
02107   }
02108   case Type::ObjCObject:
02109     return Cache::get(cast<ObjCObjectType>(T)->getBaseType());
02110   case Type::ObjCObjectPointer:
02111     return Cache::get(cast<ObjCObjectPointerType>(T)->getPointeeType());
02112   case Type::Atomic:
02113     return Cache::get(cast<AtomicType>(T)->getValueType());
02114   }
02115 
02116   llvm_unreachable("unhandled type class");
02117 }
02118 
02119 /// \brief Determine the linkage of this type.
02120 Linkage Type::getLinkage() const {
02121   Cache::ensure(this);
02122   return TypeBits.getLinkage();
02123 }
02124 
02125 /// \brief Determine the linkage of this type.
02126 Visibility Type::getVisibility() const {
02127   Cache::ensure(this);
02128   return TypeBits.getVisibility();
02129 }
02130 
02131 bool Type::isVisibilityExplicit() const {
02132   Cache::ensure(this);
02133   return TypeBits.isVisibilityExplicit();
02134 }
02135 
02136 bool Type::hasUnnamedOrLocalType() const {
02137   Cache::ensure(this);
02138   return TypeBits.hasLocalOrUnnamedType();
02139 }
02140 
02141 std::pair<Linkage,Visibility> Type::getLinkageAndVisibility() const {
02142   Cache::ensure(this);
02143   return std::make_pair(TypeBits.getLinkage(), TypeBits.getVisibility());
02144 }
02145 
02146 void Type::ClearLinkageCache() {
02147   TypeBits.CacheValidAndVisibility = 0;
02148   if (QualType(this, 0) != CanonicalType)
02149     CanonicalType->TypeBits.CacheValidAndVisibility = 0;
02150 }
02151 
02152 Qualifiers::ObjCLifetime Type::getObjCARCImplicitLifetime() const {
02153   if (isObjCARCImplicitlyUnretainedType())
02154     return Qualifiers::OCL_ExplicitNone;
02155   return Qualifiers::OCL_Strong;
02156 }
02157 
02158 bool Type::isObjCARCImplicitlyUnretainedType() const {
02159   assert(isObjCLifetimeType() &&
02160          "cannot query implicit lifetime for non-inferrable type");
02161 
02162   const Type *canon = getCanonicalTypeInternal().getTypePtr();
02163 
02164   // Walk down to the base type.  We don't care about qualifiers for this.
02165   while (const ArrayType *array = dyn_cast<ArrayType>(canon))
02166     canon = array->getElementType().getTypePtr();
02167 
02168   if (const ObjCObjectPointerType *opt
02169         = dyn_cast<ObjCObjectPointerType>(canon)) {
02170     // Class and Class<Protocol> don't require retension.
02171     if (opt->getObjectType()->isObjCClass())
02172       return true;
02173   }
02174 
02175   return false;
02176 }
02177 
02178 bool Type::isObjCNSObjectType() const {
02179   if (const TypedefType *typedefType = dyn_cast<TypedefType>(this))
02180     return typedefType->getDecl()->hasAttr<ObjCNSObjectAttr>();
02181   return false;
02182 }
02183 bool Type::isObjCRetainableType() const {
02184   return isObjCObjectPointerType() ||
02185          isBlockPointerType() ||
02186          isObjCNSObjectType();
02187 }
02188 bool Type::isObjCIndirectLifetimeType() const {
02189   if (isObjCLifetimeType())
02190     return true;
02191   if (const PointerType *OPT = getAs<PointerType>())
02192     return OPT->getPointeeType()->isObjCIndirectLifetimeType();
02193   if (const ReferenceType *Ref = getAs<ReferenceType>())
02194     return Ref->getPointeeType()->isObjCIndirectLifetimeType();
02195   if (const MemberPointerType *MemPtr = getAs<MemberPointerType>())
02196     return MemPtr->getPointeeType()->isObjCIndirectLifetimeType();
02197   return false;
02198 }
02199 
02200 /// Returns true if objects of this type have lifetime semantics under
02201 /// ARC.
02202 bool Type::isObjCLifetimeType() const {
02203   const Type *type = this;
02204   while (const ArrayType *array = type->getAsArrayTypeUnsafe())
02205     type = array->getElementType().getTypePtr();
02206   return type->isObjCRetainableType();
02207 }
02208 
02209 /// \brief Determine whether the given type T is a "bridgable" Objective-C type,
02210 /// which is either an Objective-C object pointer type or an 
02211 bool Type::isObjCARCBridgableType() const {
02212   return isObjCObjectPointerType() || isBlockPointerType();
02213 }
02214 
02215 /// \brief Determine whether the given type T is a "bridgeable" C type.
02216 bool Type::isCARCBridgableType() const {
02217   const PointerType *Pointer = getAs<PointerType>();
02218   if (!Pointer)
02219     return false;
02220   
02221   QualType Pointee = Pointer->getPointeeType();
02222   return Pointee->isVoidType() || Pointee->isRecordType();
02223 }
02224 
02225 bool Type::hasSizedVLAType() const {
02226   if (!isVariablyModifiedType()) return false;
02227 
02228   if (const PointerType *ptr = getAs<PointerType>())
02229     return ptr->getPointeeType()->hasSizedVLAType();
02230   if (const ReferenceType *ref = getAs<ReferenceType>())
02231     return ref->getPointeeType()->hasSizedVLAType();
02232   if (const ArrayType *arr = getAsArrayTypeUnsafe()) {
02233     if (isa<VariableArrayType>(arr) && 
02234         cast<VariableArrayType>(arr)->getSizeExpr())
02235       return true;
02236 
02237     return arr->getElementType()->hasSizedVLAType();
02238   }
02239 
02240   return false;
02241 }
02242 
02243 QualType::DestructionKind QualType::isDestructedTypeImpl(QualType type) {
02244   switch (type.getObjCLifetime()) {
02245   case Qualifiers::OCL_None:
02246   case Qualifiers::OCL_ExplicitNone:
02247   case Qualifiers::OCL_Autoreleasing:
02248     break;
02249 
02250   case Qualifiers::OCL_Strong:
02251     return DK_objc_strong_lifetime;
02252   case Qualifiers::OCL_Weak:
02253     return DK_objc_weak_lifetime;
02254   }
02255 
02256   /// Currently, the only destruction kind we recognize is C++ objects
02257   /// with non-trivial destructors.
02258   const CXXRecordDecl *record =
02259     type->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
02260   if (record && record->hasDefinition() && !record->hasTrivialDestructor())
02261     return DK_cxx_destructor;
02262 
02263   return DK_none;
02264 }
02265 
02266 bool QualType::hasTrivialAssignment(ASTContext &Context, bool Copying) const {
02267   switch (getObjCLifetime()) {
02268   case Qualifiers::OCL_None:
02269     break;
02270       
02271   case Qualifiers::OCL_ExplicitNone:
02272     return true;
02273       
02274   case Qualifiers::OCL_Autoreleasing:
02275   case Qualifiers::OCL_Strong:
02276   case Qualifiers::OCL_Weak:
02277     return !Context.getLangOpts().ObjCAutoRefCount;
02278   }
02279   
02280   if (const CXXRecordDecl *Record 
02281             = getTypePtr()->getBaseElementTypeUnsafe()->getAsCXXRecordDecl())
02282     return Copying ? Record->hasTrivialCopyAssignment() :
02283                      Record->hasTrivialMoveAssignment();
02284   
02285   return true;
02286 }