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