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