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