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