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