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> 29 using namespace clang; 30 31 bool 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 46 const 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 66 bool 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 76 unsigned 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(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 111 unsigned 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 122 DependentSizedArrayType::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 134 void 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 146 DependentSizedExtVectorType::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 162 void 163 DependentSizedExtVectorType::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 170 VectorType::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 182 VectorType::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. 197 const 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. 218 QualType QualType::getDesugaredType(QualType T, const ASTContext &Context) { 219 SplitQualType split = getSplitDesugaredType(T); 220 return Context.getQualifiedType(split.Ty, split.Quals); 221 } 222 223 QualType 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 230 QualType 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 244 SplitQualType 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 265 SplitQualType 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 304 QualType 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. 314 template<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 332 template <> const TypedefType *Type::getAs() const { 333 return getAsSugar<TypedefType>(this); 334 } 335 336 template <> 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. 343 const 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 361 bool 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 } 377 bool Type::isClassType() const { 378 if (const RecordType *RT = getAs<RecordType>()) 379 return RT->getDecl()->isClass(); 380 return false; 381 } 382 bool Type::isStructureType() const { 383 if (const RecordType *RT = getAs<RecordType>()) 384 return RT->getDecl()->isStruct(); 385 return false; 386 } 387 bool Type::isInterfaceType() const { 388 if (const RecordType *RT = getAs<RecordType>()) 389 return RT->getDecl()->isInterface(); 390 return false; 391 } 392 bool 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 } 398 bool Type::isVoidPointerType() const { 399 if (const PointerType *PT = getAs<PointerType>()) 400 return PT->getPointeeType()->isVoidType(); 401 return false; 402 } 403 404 bool Type::isUnionType() const { 405 if (const RecordType *RT = getAs<RecordType>()) 406 return RT->getDecl()->isUnion(); 407 return false; 408 } 409 410 bool Type::isComplexType() const { 411 if (const ComplexType *CT = dyn_cast<ComplexType>(CanonicalType)) 412 return CT->getElementType()->isFloatingType(); 413 return false; 414 } 415 416 bool Type::isComplexIntegerType() const { 417 // Check for GCC complex integer extension. 418 return getAsComplexIntegerType(); 419 } 420 421 const ComplexType *Type::getAsComplexIntegerType() const { 422 if (const ComplexType *Complex = getAs<ComplexType>()) 423 if (Complex->getElementType()->isIntegerType()) 424 return Complex; 425 return 0; 426 } 427 428 QualType 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 440 const 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 459 const 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 479 ObjCObjectType::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 493 const 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 503 bool Type::isObjCQualifiedInterfaceType() const { 504 return getAsObjCQualifiedInterfaceType() != 0; 505 } 506 507 const 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 517 const 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 527 const ObjCObjectPointerType *Type::getAsObjCInterfacePointerType() const { 528 if (const ObjCObjectPointerType *OPT = getAs<ObjCObjectPointerType>()) { 529 if (OPT->getInterfaceType()) 530 return OPT; 531 } 532 return 0; 533 } 534 535 const 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 550 CXXRecordDecl *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 560 namespace { 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 611 AutoType *Type::getContainedAutoType() const { 612 return GetContainedAutoVisitor().Visit(this); 613 } 614 615 bool 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. 641 bool 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 654 bool 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 671 bool 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 680 bool 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 687 bool Type::isChar16Type() const { 688 if (const BuiltinType *BT = dyn_cast<BuiltinType>(CanonicalType)) 689 return BT->getKind() == BuiltinType::Char16; 690 return false; 691 } 692 693 bool 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. 701 bool 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 721 bool 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 737 bool 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 751 bool 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 761 bool 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 777 bool 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 791 bool Type::hasUnsignedIntegerRepresentation() const { 792 if (const VectorType *VT = dyn_cast<VectorType>(CanonicalType)) 793 return VT->getElementType()->isUnsignedIntegerType(); 794 else 795 return isUnsignedIntegerType(); 796 } 797 798 bool 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 807 bool Type::hasFloatingRepresentation() const { 808 if (const VectorType *VT = dyn_cast<VectorType>(CanonicalType)) 809 return VT->getElementType()->isFloatingType(); 810 else 811 return isFloatingType(); 812 } 813 814 bool Type::isRealFloatingType() const { 815 if (const BuiltinType *BT = dyn_cast<BuiltinType>(CanonicalType)) 816 return BT->isFloatingPoint(); 817 return false; 818 } 819 820 bool 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 829 bool 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 844 Type::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. 883 bool 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. 897 bool 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. 907 bool 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 960 bool 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 968 bool 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 1028 bool 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 1091 bool 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 1145 bool 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 // We treat _Atomic T as a literal type if T is a literal type. 1200 if (const AtomicType *AT = BaseTy->getAs<AtomicType>()) 1201 return AT->getValueType()->isLiteralType(Ctx); 1202 1203 // If this type hasn't been deduced yet, then conservatively assume that 1204 // it'll work out to be a literal type. 1205 if (isa<AutoType>(BaseTy->getCanonicalTypeInternal())) 1206 return true; 1207 1208 return false; 1209 } 1210 1211 bool Type::isStandardLayoutType() const { 1212 if (isDependentType()) 1213 return false; 1214 1215 // C++0x [basic.types]p9: 1216 // Scalar types, standard-layout class types, arrays of such types, and 1217 // cv-qualified versions of these types are collectively called 1218 // standard-layout types. 1219 const Type *BaseTy = getBaseElementTypeUnsafe(); 1220 assert(BaseTy && "NULL element type"); 1221 1222 // Return false for incomplete types after skipping any incomplete array 1223 // types which are expressly allowed by the standard and thus our API. 1224 if (BaseTy->isIncompleteType()) 1225 return false; 1226 1227 // As an extension, Clang treats vector types as Scalar types. 1228 if (BaseTy->isScalarType() || BaseTy->isVectorType()) return true; 1229 if (const RecordType *RT = BaseTy->getAs<RecordType>()) { 1230 if (const CXXRecordDecl *ClassDecl = 1231 dyn_cast<CXXRecordDecl>(RT->getDecl())) 1232 if (!ClassDecl->isStandardLayout()) 1233 return false; 1234 1235 // Default to 'true' for non-C++ class types. 1236 // FIXME: This is a bit dubious, but plain C structs should trivially meet 1237 // all the requirements of standard layout classes. 1238 return true; 1239 } 1240 1241 // No other types can match. 1242 return false; 1243 } 1244 1245 // This is effectively the intersection of isTrivialType and 1246 // isStandardLayoutType. We implement it directly to avoid redundant 1247 // conversions from a type to a CXXRecordDecl. 1248 bool QualType::isCXX11PODType(ASTContext &Context) const { 1249 const Type *ty = getTypePtr(); 1250 if (ty->isDependentType()) 1251 return false; 1252 1253 if (Context.getLangOpts().ObjCAutoRefCount) { 1254 switch (getObjCLifetime()) { 1255 case Qualifiers::OCL_ExplicitNone: 1256 return true; 1257 1258 case Qualifiers::OCL_Strong: 1259 case Qualifiers::OCL_Weak: 1260 case Qualifiers::OCL_Autoreleasing: 1261 return false; 1262 1263 case Qualifiers::OCL_None: 1264 break; 1265 } 1266 } 1267 1268 // C++11 [basic.types]p9: 1269 // Scalar types, POD classes, arrays of such types, and cv-qualified 1270 // versions of these types are collectively called trivial types. 1271 const Type *BaseTy = ty->getBaseElementTypeUnsafe(); 1272 assert(BaseTy && "NULL element type"); 1273 1274 // Return false for incomplete types after skipping any incomplete array 1275 // types which are expressly allowed by the standard and thus our API. 1276 if (BaseTy->isIncompleteType()) 1277 return false; 1278 1279 // As an extension, Clang treats vector types as Scalar types. 1280 if (BaseTy->isScalarType() || BaseTy->isVectorType()) return true; 1281 if (const RecordType *RT = BaseTy->getAs<RecordType>()) { 1282 if (const CXXRecordDecl *ClassDecl = 1283 dyn_cast<CXXRecordDecl>(RT->getDecl())) { 1284 // C++11 [class]p10: 1285 // A POD struct is a non-union class that is both a trivial class [...] 1286 if (!ClassDecl->isTrivial()) return false; 1287 1288 // C++11 [class]p10: 1289 // A POD struct is a non-union class that is both a trivial class and 1290 // a standard-layout class [...] 1291 if (!ClassDecl->isStandardLayout()) return false; 1292 1293 // C++11 [class]p10: 1294 // A POD struct is a non-union class that is both a trivial class and 1295 // a standard-layout class, and has no non-static data members of type 1296 // non-POD struct, non-POD union (or array of such types). [...] 1297 // 1298 // We don't directly query the recursive aspect as the requiremets for 1299 // both standard-layout classes and trivial classes apply recursively 1300 // already. 1301 } 1302 1303 return true; 1304 } 1305 1306 // No other types can match. 1307 return false; 1308 } 1309 1310 bool Type::isPromotableIntegerType() const { 1311 if (const BuiltinType *BT = getAs<BuiltinType>()) 1312 switch (BT->getKind()) { 1313 case BuiltinType::Bool: 1314 case BuiltinType::Char_S: 1315 case BuiltinType::Char_U: 1316 case BuiltinType::SChar: 1317 case BuiltinType::UChar: 1318 case BuiltinType::Short: 1319 case BuiltinType::UShort: 1320 case BuiltinType::WChar_S: 1321 case BuiltinType::WChar_U: 1322 case BuiltinType::Char16: 1323 case BuiltinType::Char32: 1324 return true; 1325 default: 1326 return false; 1327 } 1328 1329 // Enumerated types are promotable to their compatible integer types 1330 // (C99 6.3.1.1) a.k.a. its underlying type (C++ [conv.prom]p2). 1331 if (const EnumType *ET = getAs<EnumType>()){ 1332 if (this->isDependentType() || ET->getDecl()->getPromotionType().isNull() 1333 || ET->getDecl()->isScoped()) 1334 return false; 1335 1336 return true; 1337 } 1338 1339 return false; 1340 } 1341 1342 bool Type::isSpecifierType() const { 1343 // Note that this intentionally does not use the canonical type. 1344 switch (getTypeClass()) { 1345 case Builtin: 1346 case Record: 1347 case Enum: 1348 case Typedef: 1349 case Complex: 1350 case TypeOfExpr: 1351 case TypeOf: 1352 case TemplateTypeParm: 1353 case SubstTemplateTypeParm: 1354 case TemplateSpecialization: 1355 case Elaborated: 1356 case DependentName: 1357 case DependentTemplateSpecialization: 1358 case ObjCInterface: 1359 case ObjCObject: 1360 case ObjCObjectPointer: // FIXME: object pointers aren't really specifiers 1361 return true; 1362 default: 1363 return false; 1364 } 1365 } 1366 1367 ElaboratedTypeKeyword 1368 TypeWithKeyword::getKeywordForTypeSpec(unsigned TypeSpec) { 1369 switch (TypeSpec) { 1370 default: return ETK_None; 1371 case TST_typename: return ETK_Typename; 1372 case TST_class: return ETK_Class; 1373 case TST_struct: return ETK_Struct; 1374 case TST_interface: return ETK_Interface; 1375 case TST_union: return ETK_Union; 1376 case TST_enum: return ETK_Enum; 1377 } 1378 } 1379 1380 TagTypeKind 1381 TypeWithKeyword::getTagTypeKindForTypeSpec(unsigned TypeSpec) { 1382 switch(TypeSpec) { 1383 case TST_class: return TTK_Class; 1384 case TST_struct: return TTK_Struct; 1385 case TST_interface: return TTK_Interface; 1386 case TST_union: return TTK_Union; 1387 case TST_enum: return TTK_Enum; 1388 } 1389 1390 llvm_unreachable("Type specifier is not a tag type kind."); 1391 } 1392 1393 ElaboratedTypeKeyword 1394 TypeWithKeyword::getKeywordForTagTypeKind(TagTypeKind Kind) { 1395 switch (Kind) { 1396 case TTK_Class: return ETK_Class; 1397 case TTK_Struct: return ETK_Struct; 1398 case TTK_Interface: return ETK_Interface; 1399 case TTK_Union: return ETK_Union; 1400 case TTK_Enum: return ETK_Enum; 1401 } 1402 llvm_unreachable("Unknown tag type kind."); 1403 } 1404 1405 TagTypeKind 1406 TypeWithKeyword::getTagTypeKindForKeyword(ElaboratedTypeKeyword Keyword) { 1407 switch (Keyword) { 1408 case ETK_Class: return TTK_Class; 1409 case ETK_Struct: return TTK_Struct; 1410 case ETK_Interface: return TTK_Interface; 1411 case ETK_Union: return TTK_Union; 1412 case ETK_Enum: return TTK_Enum; 1413 case ETK_None: // Fall through. 1414 case ETK_Typename: 1415 llvm_unreachable("Elaborated type keyword is not a tag type kind."); 1416 } 1417 llvm_unreachable("Unknown elaborated type keyword."); 1418 } 1419 1420 bool 1421 TypeWithKeyword::KeywordIsTagTypeKind(ElaboratedTypeKeyword Keyword) { 1422 switch (Keyword) { 1423 case ETK_None: 1424 case ETK_Typename: 1425 return false; 1426 case ETK_Class: 1427 case ETK_Struct: 1428 case ETK_Interface: 1429 case ETK_Union: 1430 case ETK_Enum: 1431 return true; 1432 } 1433 llvm_unreachable("Unknown elaborated type keyword."); 1434 } 1435 1436 const char* 1437 TypeWithKeyword::getKeywordName(ElaboratedTypeKeyword Keyword) { 1438 switch (Keyword) { 1439 case ETK_None: return ""; 1440 case ETK_Typename: return "typename"; 1441 case ETK_Class: return "class"; 1442 case ETK_Struct: return "struct"; 1443 case ETK_Interface: return "__interface"; 1444 case ETK_Union: return "union"; 1445 case ETK_Enum: return "enum"; 1446 } 1447 1448 llvm_unreachable("Unknown elaborated type keyword."); 1449 } 1450 1451 DependentTemplateSpecializationType::DependentTemplateSpecializationType( 1452 ElaboratedTypeKeyword Keyword, 1453 NestedNameSpecifier *NNS, const IdentifierInfo *Name, 1454 unsigned NumArgs, const TemplateArgument *Args, 1455 QualType Canon) 1456 : TypeWithKeyword(Keyword, DependentTemplateSpecialization, Canon, true, true, 1457 /*VariablyModified=*/false, 1458 NNS && NNS->containsUnexpandedParameterPack()), 1459 NNS(NNS), Name(Name), NumArgs(NumArgs) { 1460 assert((!NNS || NNS->isDependent()) && 1461 "DependentTemplateSpecializatonType requires dependent qualifier"); 1462 for (unsigned I = 0; I != NumArgs; ++I) { 1463 if (Args[I].containsUnexpandedParameterPack()) 1464 setContainsUnexpandedParameterPack(); 1465 1466 new (&getArgBuffer()[I]) TemplateArgument(Args[I]); 1467 } 1468 } 1469 1470 void 1471 DependentTemplateSpecializationType::Profile(llvm::FoldingSetNodeID &ID, 1472 const ASTContext &Context, 1473 ElaboratedTypeKeyword Keyword, 1474 NestedNameSpecifier *Qualifier, 1475 const IdentifierInfo *Name, 1476 unsigned NumArgs, 1477 const TemplateArgument *Args) { 1478 ID.AddInteger(Keyword); 1479 ID.AddPointer(Qualifier); 1480 ID.AddPointer(Name); 1481 for (unsigned Idx = 0; Idx < NumArgs; ++Idx) 1482 Args[Idx].Profile(ID, Context); 1483 } 1484 1485 bool Type::isElaboratedTypeSpecifier() const { 1486 ElaboratedTypeKeyword Keyword; 1487 if (const ElaboratedType *Elab = dyn_cast<ElaboratedType>(this)) 1488 Keyword = Elab->getKeyword(); 1489 else if (const DependentNameType *DepName = dyn_cast<DependentNameType>(this)) 1490 Keyword = DepName->getKeyword(); 1491 else if (const DependentTemplateSpecializationType *DepTST = 1492 dyn_cast<DependentTemplateSpecializationType>(this)) 1493 Keyword = DepTST->getKeyword(); 1494 else 1495 return false; 1496 1497 return TypeWithKeyword::KeywordIsTagTypeKind(Keyword); 1498 } 1499 1500 const char *Type::getTypeClassName() const { 1501 switch (TypeBits.TC) { 1502 #define ABSTRACT_TYPE(Derived, Base) 1503 #define TYPE(Derived, Base) case Derived: return #Derived; 1504 #include "clang/AST/TypeNodes.def" 1505 } 1506 1507 llvm_unreachable("Invalid type class."); 1508 } 1509 1510 StringRef BuiltinType::getName(const PrintingPolicy &Policy) const { 1511 switch (getKind()) { 1512 case Void: return "void"; 1513 case Bool: return Policy.Bool ? "bool" : "_Bool"; 1514 case Char_S: return "char"; 1515 case Char_U: return "char"; 1516 case SChar: return "signed char"; 1517 case Short: return "short"; 1518 case Int: return "int"; 1519 case Long: return "long"; 1520 case LongLong: return "long long"; 1521 case Int128: return "__int128"; 1522 case UChar: return "unsigned char"; 1523 case UShort: return "unsigned short"; 1524 case UInt: return "unsigned int"; 1525 case ULong: return "unsigned long"; 1526 case ULongLong: return "unsigned long long"; 1527 case UInt128: return "unsigned __int128"; 1528 case Half: return "half"; 1529 case Float: return "float"; 1530 case Double: return "double"; 1531 case LongDouble: return "long double"; 1532 case WChar_S: 1533 case WChar_U: return Policy.MSWChar ? "__wchar_t" : "wchar_t"; 1534 case Char16: return "char16_t"; 1535 case Char32: return "char32_t"; 1536 case NullPtr: return "nullptr_t"; 1537 case Overload: return "<overloaded function type>"; 1538 case BoundMember: return "<bound member function type>"; 1539 case PseudoObject: return "<pseudo-object type>"; 1540 case Dependent: return "<dependent type>"; 1541 case UnknownAny: return "<unknown type>"; 1542 case ARCUnbridgedCast: return "<ARC unbridged cast type>"; 1543 case BuiltinFn: return "<builtin fn type>"; 1544 case ObjCId: return "id"; 1545 case ObjCClass: return "Class"; 1546 case ObjCSel: return "SEL"; 1547 case OCLImage1d: return "image1d_t"; 1548 case OCLImage1dArray: return "image1d_array_t"; 1549 case OCLImage1dBuffer: return "image1d_buffer_t"; 1550 case OCLImage2d: return "image2d_t"; 1551 case OCLImage2dArray: return "image2d_array_t"; 1552 case OCLImage3d: return "image3d_t"; 1553 case OCLSampler: return "sampler_t"; 1554 case OCLEvent: return "event_t"; 1555 } 1556 1557 llvm_unreachable("Invalid builtin type."); 1558 } 1559 1560 QualType QualType::getNonLValueExprType(ASTContext &Context) const { 1561 if (const ReferenceType *RefType = getTypePtr()->getAs<ReferenceType>()) 1562 return RefType->getPointeeType(); 1563 1564 // C++0x [basic.lval]: 1565 // Class prvalues can have cv-qualified types; non-class prvalues always 1566 // have cv-unqualified types. 1567 // 1568 // See also C99 6.3.2.1p2. 1569 if (!Context.getLangOpts().CPlusPlus || 1570 (!getTypePtr()->isDependentType() && !getTypePtr()->isRecordType())) 1571 return getUnqualifiedType(); 1572 1573 return *this; 1574 } 1575 1576 StringRef FunctionType::getNameForCallConv(CallingConv CC) { 1577 switch (CC) { 1578 case CC_Default: 1579 llvm_unreachable("no name for default cc"); 1580 1581 case CC_C: return "cdecl"; 1582 case CC_X86StdCall: return "stdcall"; 1583 case CC_X86FastCall: return "fastcall"; 1584 case CC_X86ThisCall: return "thiscall"; 1585 case CC_X86Pascal: return "pascal"; 1586 case CC_AAPCS: return "aapcs"; 1587 case CC_AAPCS_VFP: return "aapcs-vfp"; 1588 case CC_PnaclCall: return "pnaclcall"; 1589 case CC_IntelOclBicc: return "intel_ocl_bicc"; 1590 } 1591 1592 llvm_unreachable("Invalid calling convention."); 1593 } 1594 1595 FunctionProtoType::FunctionProtoType(QualType result, ArrayRef<QualType> args, 1596 QualType canonical, 1597 const ExtProtoInfo &epi) 1598 : FunctionType(FunctionProto, result, epi.TypeQuals, 1599 canonical, 1600 result->isDependentType(), 1601 result->isInstantiationDependentType(), 1602 result->isVariablyModifiedType(), 1603 result->containsUnexpandedParameterPack(), 1604 epi.ExtInfo), 1605 NumArgs(args.size()), NumExceptions(epi.NumExceptions), 1606 ExceptionSpecType(epi.ExceptionSpecType), 1607 HasAnyConsumedArgs(epi.ConsumedArguments != 0), 1608 Variadic(epi.Variadic), HasTrailingReturn(epi.HasTrailingReturn), 1609 RefQualifier(epi.RefQualifier) 1610 { 1611 assert(NumArgs == args.size() && "function has too many parameters"); 1612 1613 // Fill in the trailing argument array. 1614 QualType *argSlot = reinterpret_cast<QualType*>(this+1); 1615 for (unsigned i = 0; i != NumArgs; ++i) { 1616 if (args[i]->isDependentType()) 1617 setDependent(); 1618 else if (args[i]->isInstantiationDependentType()) 1619 setInstantiationDependent(); 1620 1621 if (args[i]->containsUnexpandedParameterPack()) 1622 setContainsUnexpandedParameterPack(); 1623 1624 argSlot[i] = args[i]; 1625 } 1626 1627 if (getExceptionSpecType() == EST_Dynamic) { 1628 // Fill in the exception array. 1629 QualType *exnSlot = argSlot + NumArgs; 1630 for (unsigned i = 0, e = epi.NumExceptions; i != e; ++i) { 1631 if (epi.Exceptions[i]->isDependentType()) 1632 setDependent(); 1633 else if (epi.Exceptions[i]->isInstantiationDependentType()) 1634 setInstantiationDependent(); 1635 1636 if (epi.Exceptions[i]->containsUnexpandedParameterPack()) 1637 setContainsUnexpandedParameterPack(); 1638 1639 exnSlot[i] = epi.Exceptions[i]; 1640 } 1641 } else if (getExceptionSpecType() == EST_ComputedNoexcept) { 1642 // Store the noexcept expression and context. 1643 Expr **noexSlot = reinterpret_cast<Expr**>(argSlot + NumArgs); 1644 *noexSlot = epi.NoexceptExpr; 1645 1646 if (epi.NoexceptExpr) { 1647 if (epi.NoexceptExpr->isValueDependent() 1648 || epi.NoexceptExpr->isTypeDependent()) 1649 setDependent(); 1650 else if (epi.NoexceptExpr->isInstantiationDependent()) 1651 setInstantiationDependent(); 1652 } 1653 } else if (getExceptionSpecType() == EST_Uninstantiated) { 1654 // Store the function decl from which we will resolve our 1655 // exception specification. 1656 FunctionDecl **slot = reinterpret_cast<FunctionDecl**>(argSlot + NumArgs); 1657 slot[0] = epi.ExceptionSpecDecl; 1658 slot[1] = epi.ExceptionSpecTemplate; 1659 // This exception specification doesn't make the type dependent, because 1660 // it's not instantiated as part of instantiating the type. 1661 } else if (getExceptionSpecType() == EST_Unevaluated) { 1662 // Store the function decl from which we will resolve our 1663 // exception specification. 1664 FunctionDecl **slot = reinterpret_cast<FunctionDecl**>(argSlot + NumArgs); 1665 slot[0] = epi.ExceptionSpecDecl; 1666 } 1667 1668 if (epi.ConsumedArguments) { 1669 bool *consumedArgs = const_cast<bool*>(getConsumedArgsBuffer()); 1670 for (unsigned i = 0; i != NumArgs; ++i) 1671 consumedArgs[i] = epi.ConsumedArguments[i]; 1672 } 1673 } 1674 1675 FunctionProtoType::NoexceptResult 1676 FunctionProtoType::getNoexceptSpec(ASTContext &ctx) const { 1677 ExceptionSpecificationType est = getExceptionSpecType(); 1678 if (est == EST_BasicNoexcept) 1679 return NR_Nothrow; 1680 1681 if (est != EST_ComputedNoexcept) 1682 return NR_NoNoexcept; 1683 1684 Expr *noexceptExpr = getNoexceptExpr(); 1685 if (!noexceptExpr) 1686 return NR_BadNoexcept; 1687 if (noexceptExpr->isValueDependent()) 1688 return NR_Dependent; 1689 1690 llvm::APSInt value; 1691 bool isICE = noexceptExpr->isIntegerConstantExpr(value, ctx, 0, 1692 /*evaluated*/false); 1693 (void)isICE; 1694 assert(isICE && "AST should not contain bad noexcept expressions."); 1695 1696 return value.getBoolValue() ? NR_Nothrow : NR_Throw; 1697 } 1698 1699 bool FunctionProtoType::isTemplateVariadic() const { 1700 for (unsigned ArgIdx = getNumArgs(); ArgIdx; --ArgIdx) 1701 if (isa<PackExpansionType>(getArgType(ArgIdx - 1))) 1702 return true; 1703 1704 return false; 1705 } 1706 1707 void FunctionProtoType::Profile(llvm::FoldingSetNodeID &ID, QualType Result, 1708 const QualType *ArgTys, unsigned NumArgs, 1709 const ExtProtoInfo &epi, 1710 const ASTContext &Context) { 1711 1712 // We have to be careful not to get ambiguous profile encodings. 1713 // Note that valid type pointers are never ambiguous with anything else. 1714 // 1715 // The encoding grammar begins: 1716 // type type* bool int bool 1717 // If that final bool is true, then there is a section for the EH spec: 1718 // bool type* 1719 // This is followed by an optional "consumed argument" section of the 1720 // same length as the first type sequence: 1721 // bool* 1722 // Finally, we have the ext info and trailing return type flag: 1723 // int bool 1724 // 1725 // There is no ambiguity between the consumed arguments and an empty EH 1726 // spec because of the leading 'bool' which unambiguously indicates 1727 // whether the following bool is the EH spec or part of the arguments. 1728 1729 ID.AddPointer(Result.getAsOpaquePtr()); 1730 for (unsigned i = 0; i != NumArgs; ++i) 1731 ID.AddPointer(ArgTys[i].getAsOpaquePtr()); 1732 // This method is relatively performance sensitive, so as a performance 1733 // shortcut, use one AddInteger call instead of four for the next four 1734 // fields. 1735 assert(!(unsigned(epi.Variadic) & ~1) && 1736 !(unsigned(epi.TypeQuals) & ~255) && 1737 !(unsigned(epi.RefQualifier) & ~3) && 1738 !(unsigned(epi.ExceptionSpecType) & ~7) && 1739 "Values larger than expected."); 1740 ID.AddInteger(unsigned(epi.Variadic) + 1741 (epi.TypeQuals << 1) + 1742 (epi.RefQualifier << 9) + 1743 (epi.ExceptionSpecType << 11)); 1744 if (epi.ExceptionSpecType == EST_Dynamic) { 1745 for (unsigned i = 0; i != epi.NumExceptions; ++i) 1746 ID.AddPointer(epi.Exceptions[i].getAsOpaquePtr()); 1747 } else if (epi.ExceptionSpecType == EST_ComputedNoexcept && epi.NoexceptExpr){ 1748 epi.NoexceptExpr->Profile(ID, Context, false); 1749 } else if (epi.ExceptionSpecType == EST_Uninstantiated || 1750 epi.ExceptionSpecType == EST_Unevaluated) { 1751 ID.AddPointer(epi.ExceptionSpecDecl->getCanonicalDecl()); 1752 } 1753 if (epi.ConsumedArguments) { 1754 for (unsigned i = 0; i != NumArgs; ++i) 1755 ID.AddBoolean(epi.ConsumedArguments[i]); 1756 } 1757 epi.ExtInfo.Profile(ID); 1758 ID.AddBoolean(epi.HasTrailingReturn); 1759 } 1760 1761 void FunctionProtoType::Profile(llvm::FoldingSetNodeID &ID, 1762 const ASTContext &Ctx) { 1763 Profile(ID, getResultType(), arg_type_begin(), NumArgs, getExtProtoInfo(), 1764 Ctx); 1765 } 1766 1767 QualType TypedefType::desugar() const { 1768 return getDecl()->getUnderlyingType(); 1769 } 1770 1771 TypeOfExprType::TypeOfExprType(Expr *E, QualType can) 1772 : Type(TypeOfExpr, can, E->isTypeDependent(), 1773 E->isInstantiationDependent(), 1774 E->getType()->isVariablyModifiedType(), 1775 E->containsUnexpandedParameterPack()), 1776 TOExpr(E) { 1777 } 1778 1779 bool TypeOfExprType::isSugared() const { 1780 return !TOExpr->isTypeDependent(); 1781 } 1782 1783 QualType TypeOfExprType::desugar() const { 1784 if (isSugared()) 1785 return getUnderlyingExpr()->getType(); 1786 1787 return QualType(this, 0); 1788 } 1789 1790 void DependentTypeOfExprType::Profile(llvm::FoldingSetNodeID &ID, 1791 const ASTContext &Context, Expr *E) { 1792 E->Profile(ID, Context, true); 1793 } 1794 1795 DecltypeType::DecltypeType(Expr *E, QualType underlyingType, QualType can) 1796 // C++11 [temp.type]p2: "If an expression e involves a template parameter, 1797 // decltype(e) denotes a unique dependent type." Hence a decltype type is 1798 // type-dependent even if its expression is only instantiation-dependent. 1799 : Type(Decltype, can, E->isInstantiationDependent(), 1800 E->isInstantiationDependent(), 1801 E->getType()->isVariablyModifiedType(), 1802 E->containsUnexpandedParameterPack()), 1803 E(E), 1804 UnderlyingType(underlyingType) { 1805 } 1806 1807 bool DecltypeType::isSugared() const { return !E->isInstantiationDependent(); } 1808 1809 QualType DecltypeType::desugar() const { 1810 if (isSugared()) 1811 return getUnderlyingType(); 1812 1813 return QualType(this, 0); 1814 } 1815 1816 DependentDecltypeType::DependentDecltypeType(const ASTContext &Context, Expr *E) 1817 : DecltypeType(E, Context.DependentTy), Context(Context) { } 1818 1819 void DependentDecltypeType::Profile(llvm::FoldingSetNodeID &ID, 1820 const ASTContext &Context, Expr *E) { 1821 E->Profile(ID, Context, true); 1822 } 1823 1824 TagType::TagType(TypeClass TC, const TagDecl *D, QualType can) 1825 : Type(TC, can, D->isDependentType(), 1826 /*InstantiationDependent=*/D->isDependentType(), 1827 /*VariablyModified=*/false, 1828 /*ContainsUnexpandedParameterPack=*/false), 1829 decl(const_cast<TagDecl*>(D)) {} 1830 1831 static TagDecl *getInterestingTagDecl(TagDecl *decl) { 1832 for (TagDecl::redecl_iterator I = decl->redecls_begin(), 1833 E = decl->redecls_end(); 1834 I != E; ++I) { 1835 if (I->isCompleteDefinition() || I->isBeingDefined()) 1836 return *I; 1837 } 1838 // If there's no definition (not even in progress), return what we have. 1839 return decl; 1840 } 1841 1842 UnaryTransformType::UnaryTransformType(QualType BaseType, 1843 QualType UnderlyingType, 1844 UTTKind UKind, 1845 QualType CanonicalType) 1846 : Type(UnaryTransform, CanonicalType, UnderlyingType->isDependentType(), 1847 UnderlyingType->isInstantiationDependentType(), 1848 UnderlyingType->isVariablyModifiedType(), 1849 BaseType->containsUnexpandedParameterPack()) 1850 , BaseType(BaseType), UnderlyingType(UnderlyingType), UKind(UKind) 1851 {} 1852 1853 TagDecl *TagType::getDecl() const { 1854 return getInterestingTagDecl(decl); 1855 } 1856 1857 bool TagType::isBeingDefined() const { 1858 return getDecl()->isBeingDefined(); 1859 } 1860 1861 CXXRecordDecl *InjectedClassNameType::getDecl() const { 1862 return cast<CXXRecordDecl>(getInterestingTagDecl(Decl)); 1863 } 1864 1865 IdentifierInfo *TemplateTypeParmType::getIdentifier() const { 1866 return isCanonicalUnqualified() ? 0 : getDecl()->getIdentifier(); 1867 } 1868 1869 SubstTemplateTypeParmPackType:: 1870 SubstTemplateTypeParmPackType(const TemplateTypeParmType *Param, 1871 QualType Canon, 1872 const TemplateArgument &ArgPack) 1873 : Type(SubstTemplateTypeParmPack, Canon, true, true, false, true), 1874 Replaced(Param), 1875 Arguments(ArgPack.pack_begin()), NumArguments(ArgPack.pack_size()) 1876 { 1877 } 1878 1879 TemplateArgument SubstTemplateTypeParmPackType::getArgumentPack() const { 1880 return TemplateArgument(Arguments, NumArguments); 1881 } 1882 1883 void SubstTemplateTypeParmPackType::Profile(llvm::FoldingSetNodeID &ID) { 1884 Profile(ID, getReplacedParameter(), getArgumentPack()); 1885 } 1886 1887 void SubstTemplateTypeParmPackType::Profile(llvm::FoldingSetNodeID &ID, 1888 const TemplateTypeParmType *Replaced, 1889 const TemplateArgument &ArgPack) { 1890 ID.AddPointer(Replaced); 1891 ID.AddInteger(ArgPack.pack_size()); 1892 for (TemplateArgument::pack_iterator P = ArgPack.pack_begin(), 1893 PEnd = ArgPack.pack_end(); 1894 P != PEnd; ++P) 1895 ID.AddPointer(P->getAsType().getAsOpaquePtr()); 1896 } 1897 1898 bool TemplateSpecializationType:: 1899 anyDependentTemplateArguments(const TemplateArgumentListInfo &Args, 1900 bool &InstantiationDependent) { 1901 return anyDependentTemplateArguments(Args.getArgumentArray(), Args.size(), 1902 InstantiationDependent); 1903 } 1904 1905 bool TemplateSpecializationType:: 1906 anyDependentTemplateArguments(const TemplateArgumentLoc *Args, unsigned N, 1907 bool &InstantiationDependent) { 1908 for (unsigned i = 0; i != N; ++i) { 1909 if (Args[i].getArgument().isDependent()) { 1910 InstantiationDependent = true; 1911 return true; 1912 } 1913 1914 if (Args[i].getArgument().isInstantiationDependent()) 1915 InstantiationDependent = true; 1916 } 1917 return false; 1918 } 1919 1920 bool TemplateSpecializationType:: 1921 anyDependentTemplateArguments(const TemplateArgument *Args, unsigned N, 1922 bool &InstantiationDependent) { 1923 for (unsigned i = 0; i != N; ++i) { 1924 if (Args[i].isDependent()) { 1925 InstantiationDependent = true; 1926 return true; 1927 } 1928 1929 if (Args[i].isInstantiationDependent()) 1930 InstantiationDependent = true; 1931 } 1932 return false; 1933 } 1934 1935 TemplateSpecializationType:: 1936 TemplateSpecializationType(TemplateName T, 1937 const TemplateArgument *Args, unsigned NumArgs, 1938 QualType Canon, QualType AliasedType) 1939 : Type(TemplateSpecialization, 1940 Canon.isNull()? QualType(this, 0) : Canon, 1941 Canon.isNull()? T.isDependent() : Canon->isDependentType(), 1942 Canon.isNull()? T.isDependent() 1943 : Canon->isInstantiationDependentType(), 1944 false, 1945 T.containsUnexpandedParameterPack()), 1946 Template(T), NumArgs(NumArgs), TypeAlias(!AliasedType.isNull()) { 1947 assert(!T.getAsDependentTemplateName() && 1948 "Use DependentTemplateSpecializationType for dependent template-name"); 1949 assert((T.getKind() == TemplateName::Template || 1950 T.getKind() == TemplateName::SubstTemplateTemplateParm || 1951 T.getKind() == TemplateName::SubstTemplateTemplateParmPack) && 1952 "Unexpected template name for TemplateSpecializationType"); 1953 bool InstantiationDependent; 1954 (void)InstantiationDependent; 1955 assert((!Canon.isNull() || 1956 T.isDependent() || 1957 anyDependentTemplateArguments(Args, NumArgs, 1958 InstantiationDependent)) && 1959 "No canonical type for non-dependent class template specialization"); 1960 1961 TemplateArgument *TemplateArgs 1962 = reinterpret_cast<TemplateArgument *>(this + 1); 1963 for (unsigned Arg = 0; Arg < NumArgs; ++Arg) { 1964 // Update dependent and variably-modified bits. 1965 // If the canonical type exists and is non-dependent, the template 1966 // specialization type can be non-dependent even if one of the type 1967 // arguments is. Given: 1968 // template<typename T> using U = int; 1969 // U<T> is always non-dependent, irrespective of the type T. 1970 // However, U<Ts> contains an unexpanded parameter pack, even though 1971 // its expansion (and thus its desugared type) doesn't. 1972 if (Canon.isNull() && Args[Arg].isDependent()) 1973 setDependent(); 1974 else if (Args[Arg].isInstantiationDependent()) 1975 setInstantiationDependent(); 1976 1977 if (Args[Arg].getKind() == TemplateArgument::Type && 1978 Args[Arg].getAsType()->isVariablyModifiedType()) 1979 setVariablyModified(); 1980 if (Args[Arg].containsUnexpandedParameterPack()) 1981 setContainsUnexpandedParameterPack(); 1982 1983 new (&TemplateArgs[Arg]) TemplateArgument(Args[Arg]); 1984 } 1985 1986 // Store the aliased type if this is a type alias template specialization. 1987 if (TypeAlias) { 1988 TemplateArgument *Begin = reinterpret_cast<TemplateArgument *>(this + 1); 1989 *reinterpret_cast<QualType*>(Begin + getNumArgs()) = AliasedType; 1990 } 1991 } 1992 1993 void 1994 TemplateSpecializationType::Profile(llvm::FoldingSetNodeID &ID, 1995 TemplateName T, 1996 const TemplateArgument *Args, 1997 unsigned NumArgs, 1998 const ASTContext &Context) { 1999 T.Profile(ID); 2000 for (unsigned Idx = 0; Idx < NumArgs; ++Idx) 2001 Args[Idx].Profile(ID, Context); 2002 } 2003 2004 QualType 2005 QualifierCollector::apply(const ASTContext &Context, QualType QT) const { 2006 if (!hasNonFastQualifiers()) 2007 return QT.withFastQualifiers(getFastQualifiers()); 2008 2009 return Context.getQualifiedType(QT, *this); 2010 } 2011 2012 QualType 2013 QualifierCollector::apply(const ASTContext &Context, const Type *T) const { 2014 if (!hasNonFastQualifiers()) 2015 return QualType(T, getFastQualifiers()); 2016 2017 return Context.getQualifiedType(T, *this); 2018 } 2019 2020 void ObjCObjectTypeImpl::Profile(llvm::FoldingSetNodeID &ID, 2021 QualType BaseType, 2022 ObjCProtocolDecl * const *Protocols, 2023 unsigned NumProtocols) { 2024 ID.AddPointer(BaseType.getAsOpaquePtr()); 2025 for (unsigned i = 0; i != NumProtocols; i++) 2026 ID.AddPointer(Protocols[i]); 2027 } 2028 2029 void ObjCObjectTypeImpl::Profile(llvm::FoldingSetNodeID &ID) { 2030 Profile(ID, getBaseType(), qual_begin(), getNumProtocols()); 2031 } 2032 2033 namespace { 2034 2035 /// \brief The cached properties of a type. 2036 class CachedProperties { 2037 Linkage L; 2038 bool local; 2039 2040 public: 2041 CachedProperties(Linkage L, bool local) : L(L), local(local) {} 2042 2043 Linkage getLinkage() const { return L; } 2044 bool hasLocalOrUnnamedType() const { return local; } 2045 2046 friend CachedProperties merge(CachedProperties L, CachedProperties R) { 2047 Linkage MergedLinkage = minLinkage(L.L, R.L); 2048 return CachedProperties(MergedLinkage, 2049 L.hasLocalOrUnnamedType() | R.hasLocalOrUnnamedType()); 2050 } 2051 }; 2052 } 2053 2054 static CachedProperties computeCachedProperties(const Type *T); 2055 2056 namespace clang { 2057 /// The type-property cache. This is templated so as to be 2058 /// instantiated at an internal type to prevent unnecessary symbol 2059 /// leakage. 2060 template <class Private> class TypePropertyCache { 2061 public: 2062 static CachedProperties get(QualType T) { 2063 return get(T.getTypePtr()); 2064 } 2065 2066 static CachedProperties get(const Type *T) { 2067 ensure(T); 2068 return CachedProperties(T->TypeBits.getLinkage(), 2069 T->TypeBits.hasLocalOrUnnamedType()); 2070 } 2071 2072 static void ensure(const Type *T) { 2073 // If the cache is valid, we're okay. 2074 if (T->TypeBits.isCacheValid()) return; 2075 2076 // If this type is non-canonical, ask its canonical type for the 2077 // relevant information. 2078 if (!T->isCanonicalUnqualified()) { 2079 const Type *CT = T->getCanonicalTypeInternal().getTypePtr(); 2080 ensure(CT); 2081 T->TypeBits.CacheValid = true; 2082 T->TypeBits.CachedLinkage = CT->TypeBits.CachedLinkage; 2083 T->TypeBits.CachedLocalOrUnnamed = CT->TypeBits.CachedLocalOrUnnamed; 2084 return; 2085 } 2086 2087 // Compute the cached properties and then set the cache. 2088 CachedProperties Result = computeCachedProperties(T); 2089 T->TypeBits.CacheValid = true; 2090 T->TypeBits.CachedLinkage = Result.getLinkage(); 2091 T->TypeBits.CachedLocalOrUnnamed = Result.hasLocalOrUnnamedType(); 2092 } 2093 }; 2094 } 2095 2096 // Instantiate the friend template at a private class. In a 2097 // reasonable implementation, these symbols will be internal. 2098 // It is terrible that this is the best way to accomplish this. 2099 namespace { class Private {}; } 2100 typedef TypePropertyCache<Private> Cache; 2101 2102 static CachedProperties computeCachedProperties(const Type *T) { 2103 switch (T->getTypeClass()) { 2104 #define TYPE(Class,Base) 2105 #define NON_CANONICAL_TYPE(Class,Base) case Type::Class: 2106 #include "clang/AST/TypeNodes.def" 2107 llvm_unreachable("didn't expect a non-canonical type here"); 2108 2109 #define TYPE(Class,Base) 2110 #define DEPENDENT_TYPE(Class,Base) case Type::Class: 2111 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class,Base) case Type::Class: 2112 #include "clang/AST/TypeNodes.def" 2113 // Treat instantiation-dependent types as external. 2114 assert(T->isInstantiationDependentType()); 2115 return CachedProperties(ExternalLinkage, false); 2116 2117 case Type::Auto: 2118 // Give non-deduced 'auto' types external linkage. We should only see them 2119 // here in error recovery. 2120 return CachedProperties(ExternalLinkage, false); 2121 2122 case Type::Builtin: 2123 // C++ [basic.link]p8: 2124 // A type is said to have linkage if and only if: 2125 // - it is a fundamental type (3.9.1); or 2126 return CachedProperties(ExternalLinkage, false); 2127 2128 case Type::Record: 2129 case Type::Enum: { 2130 const TagDecl *Tag = cast<TagType>(T)->getDecl(); 2131 2132 // C++ [basic.link]p8: 2133 // - it is a class or enumeration type that is named (or has a name 2134 // for linkage purposes (7.1.3)) and the name has linkage; or 2135 // - it is a specialization of a class template (14); or 2136 Linkage L = Tag->getLinkageInternal(); 2137 bool IsLocalOrUnnamed = 2138 Tag->getDeclContext()->isFunctionOrMethod() || 2139 !Tag->hasNameForLinkage(); 2140 return CachedProperties(L, IsLocalOrUnnamed); 2141 } 2142 2143 // C++ [basic.link]p8: 2144 // - it is a compound type (3.9.2) other than a class or enumeration, 2145 // compounded exclusively from types that have linkage; or 2146 case Type::Complex: 2147 return Cache::get(cast<ComplexType>(T)->getElementType()); 2148 case Type::Pointer: 2149 return Cache::get(cast<PointerType>(T)->getPointeeType()); 2150 case Type::BlockPointer: 2151 return Cache::get(cast<BlockPointerType>(T)->getPointeeType()); 2152 case Type::LValueReference: 2153 case Type::RValueReference: 2154 return Cache::get(cast<ReferenceType>(T)->getPointeeType()); 2155 case Type::MemberPointer: { 2156 const MemberPointerType *MPT = cast<MemberPointerType>(T); 2157 return merge(Cache::get(MPT->getClass()), 2158 Cache::get(MPT->getPointeeType())); 2159 } 2160 case Type::ConstantArray: 2161 case Type::IncompleteArray: 2162 case Type::VariableArray: 2163 return Cache::get(cast<ArrayType>(T)->getElementType()); 2164 case Type::Vector: 2165 case Type::ExtVector: 2166 return Cache::get(cast<VectorType>(T)->getElementType()); 2167 case Type::FunctionNoProto: 2168 return Cache::get(cast<FunctionType>(T)->getResultType()); 2169 case Type::FunctionProto: { 2170 const FunctionProtoType *FPT = cast<FunctionProtoType>(T); 2171 CachedProperties result = Cache::get(FPT->getResultType()); 2172 for (FunctionProtoType::arg_type_iterator ai = FPT->arg_type_begin(), 2173 ae = FPT->arg_type_end(); ai != ae; ++ai) 2174 result = merge(result, Cache::get(*ai)); 2175 return result; 2176 } 2177 case Type::ObjCInterface: { 2178 Linkage L = cast<ObjCInterfaceType>(T)->getDecl()->getLinkageInternal(); 2179 return CachedProperties(L, false); 2180 } 2181 case Type::ObjCObject: 2182 return Cache::get(cast<ObjCObjectType>(T)->getBaseType()); 2183 case Type::ObjCObjectPointer: 2184 return Cache::get(cast<ObjCObjectPointerType>(T)->getPointeeType()); 2185 case Type::Atomic: 2186 return Cache::get(cast<AtomicType>(T)->getValueType()); 2187 } 2188 2189 llvm_unreachable("unhandled type class"); 2190 } 2191 2192 /// \brief Determine the linkage of this type. 2193 Linkage Type::getLinkage() const { 2194 Cache::ensure(this); 2195 return TypeBits.getLinkage(); 2196 } 2197 2198 bool Type::hasUnnamedOrLocalType() const { 2199 Cache::ensure(this); 2200 return TypeBits.hasLocalOrUnnamedType(); 2201 } 2202 2203 static LinkageInfo computeLinkageInfo(QualType T); 2204 2205 static LinkageInfo computeLinkageInfo(const Type *T) { 2206 switch (T->getTypeClass()) { 2207 #define TYPE(Class,Base) 2208 #define NON_CANONICAL_TYPE(Class,Base) case Type::Class: 2209 #include "clang/AST/TypeNodes.def" 2210 llvm_unreachable("didn't expect a non-canonical type here"); 2211 2212 #define TYPE(Class,Base) 2213 #define DEPENDENT_TYPE(Class,Base) case Type::Class: 2214 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class,Base) case Type::Class: 2215 #include "clang/AST/TypeNodes.def" 2216 // Treat instantiation-dependent types as external. 2217 assert(T->isInstantiationDependentType()); 2218 return LinkageInfo::external(); 2219 2220 case Type::Builtin: 2221 return LinkageInfo::external(); 2222 2223 case Type::Auto: 2224 return LinkageInfo::external(); 2225 2226 case Type::Record: 2227 case Type::Enum: 2228 return cast<TagType>(T)->getDecl()->getLinkageAndVisibility(); 2229 2230 case Type::Complex: 2231 return computeLinkageInfo(cast<ComplexType>(T)->getElementType()); 2232 case Type::Pointer: 2233 return computeLinkageInfo(cast<PointerType>(T)->getPointeeType()); 2234 case Type::BlockPointer: 2235 return computeLinkageInfo(cast<BlockPointerType>(T)->getPointeeType()); 2236 case Type::LValueReference: 2237 case Type::RValueReference: 2238 return computeLinkageInfo(cast<ReferenceType>(T)->getPointeeType()); 2239 case Type::MemberPointer: { 2240 const MemberPointerType *MPT = cast<MemberPointerType>(T); 2241 LinkageInfo LV = computeLinkageInfo(MPT->getClass()); 2242 LV.merge(computeLinkageInfo(MPT->getPointeeType())); 2243 return LV; 2244 } 2245 case Type::ConstantArray: 2246 case Type::IncompleteArray: 2247 case Type::VariableArray: 2248 return computeLinkageInfo(cast<ArrayType>(T)->getElementType()); 2249 case Type::Vector: 2250 case Type::ExtVector: 2251 return computeLinkageInfo(cast<VectorType>(T)->getElementType()); 2252 case Type::FunctionNoProto: 2253 return computeLinkageInfo(cast<FunctionType>(T)->getResultType()); 2254 case Type::FunctionProto: { 2255 const FunctionProtoType *FPT = cast<FunctionProtoType>(T); 2256 LinkageInfo LV = computeLinkageInfo(FPT->getResultType()); 2257 for (FunctionProtoType::arg_type_iterator ai = FPT->arg_type_begin(), 2258 ae = FPT->arg_type_end(); ai != ae; ++ai) 2259 LV.merge(computeLinkageInfo(*ai)); 2260 return LV; 2261 } 2262 case Type::ObjCInterface: 2263 return cast<ObjCInterfaceType>(T)->getDecl()->getLinkageAndVisibility(); 2264 case Type::ObjCObject: 2265 return computeLinkageInfo(cast<ObjCObjectType>(T)->getBaseType()); 2266 case Type::ObjCObjectPointer: 2267 return computeLinkageInfo(cast<ObjCObjectPointerType>(T)->getPointeeType()); 2268 case Type::Atomic: 2269 return computeLinkageInfo(cast<AtomicType>(T)->getValueType()); 2270 } 2271 2272 llvm_unreachable("unhandled type class"); 2273 } 2274 2275 static LinkageInfo computeLinkageInfo(QualType T) { 2276 return computeLinkageInfo(T.getTypePtr()); 2277 } 2278 2279 bool Type::isLinkageValid() const { 2280 if (!TypeBits.isCacheValid()) 2281 return true; 2282 2283 return computeLinkageInfo(getCanonicalTypeInternal()).getLinkage() == 2284 TypeBits.getLinkage(); 2285 } 2286 2287 LinkageInfo Type::getLinkageAndVisibility() const { 2288 if (!isCanonicalUnqualified()) 2289 return computeLinkageInfo(getCanonicalTypeInternal()); 2290 2291 LinkageInfo LV = computeLinkageInfo(this); 2292 assert(LV.getLinkage() == getLinkage()); 2293 return LV; 2294 } 2295 2296 Qualifiers::ObjCLifetime Type::getObjCARCImplicitLifetime() const { 2297 if (isObjCARCImplicitlyUnretainedType()) 2298 return Qualifiers::OCL_ExplicitNone; 2299 return Qualifiers::OCL_Strong; 2300 } 2301 2302 bool Type::isObjCARCImplicitlyUnretainedType() const { 2303 assert(isObjCLifetimeType() && 2304 "cannot query implicit lifetime for non-inferrable type"); 2305 2306 const Type *canon = getCanonicalTypeInternal().getTypePtr(); 2307 2308 // Walk down to the base type. We don't care about qualifiers for this. 2309 while (const ArrayType *array = dyn_cast<ArrayType>(canon)) 2310 canon = array->getElementType().getTypePtr(); 2311 2312 if (const ObjCObjectPointerType *opt 2313 = dyn_cast<ObjCObjectPointerType>(canon)) { 2314 // Class and Class<Protocol> don't require retension. 2315 if (opt->getObjectType()->isObjCClass()) 2316 return true; 2317 } 2318 2319 return false; 2320 } 2321 2322 bool Type::isObjCNSObjectType() const { 2323 if (const TypedefType *typedefType = dyn_cast<TypedefType>(this)) 2324 return typedefType->getDecl()->hasAttr<ObjCNSObjectAttr>(); 2325 return false; 2326 } 2327 bool Type::isObjCRetainableType() const { 2328 return isObjCObjectPointerType() || 2329 isBlockPointerType() || 2330 isObjCNSObjectType(); 2331 } 2332 bool Type::isObjCIndirectLifetimeType() const { 2333 if (isObjCLifetimeType()) 2334 return true; 2335 if (const PointerType *OPT = getAs<PointerType>()) 2336 return OPT->getPointeeType()->isObjCIndirectLifetimeType(); 2337 if (const ReferenceType *Ref = getAs<ReferenceType>()) 2338 return Ref->getPointeeType()->isObjCIndirectLifetimeType(); 2339 if (const MemberPointerType *MemPtr = getAs<MemberPointerType>()) 2340 return MemPtr->getPointeeType()->isObjCIndirectLifetimeType(); 2341 return false; 2342 } 2343 2344 /// Returns true if objects of this type have lifetime semantics under 2345 /// ARC. 2346 bool Type::isObjCLifetimeType() const { 2347 const Type *type = this; 2348 while (const ArrayType *array = type->getAsArrayTypeUnsafe()) 2349 type = array->getElementType().getTypePtr(); 2350 return type->isObjCRetainableType(); 2351 } 2352 2353 /// \brief Determine whether the given type T is a "bridgable" Objective-C type, 2354 /// which is either an Objective-C object pointer type or an 2355 bool Type::isObjCARCBridgableType() const { 2356 return isObjCObjectPointerType() || isBlockPointerType(); 2357 } 2358 2359 /// \brief Determine whether the given type T is a "bridgeable" C type. 2360 bool Type::isCARCBridgableType() const { 2361 const PointerType *Pointer = getAs<PointerType>(); 2362 if (!Pointer) 2363 return false; 2364 2365 QualType Pointee = Pointer->getPointeeType(); 2366 return Pointee->isVoidType() || Pointee->isRecordType(); 2367 } 2368 2369 bool Type::hasSizedVLAType() const { 2370 if (!isVariablyModifiedType()) return false; 2371 2372 if (const PointerType *ptr = getAs<PointerType>()) 2373 return ptr->getPointeeType()->hasSizedVLAType(); 2374 if (const ReferenceType *ref = getAs<ReferenceType>()) 2375 return ref->getPointeeType()->hasSizedVLAType(); 2376 if (const ArrayType *arr = getAsArrayTypeUnsafe()) { 2377 if (isa<VariableArrayType>(arr) && 2378 cast<VariableArrayType>(arr)->getSizeExpr()) 2379 return true; 2380 2381 return arr->getElementType()->hasSizedVLAType(); 2382 } 2383 2384 return false; 2385 } 2386 2387 QualType::DestructionKind QualType::isDestructedTypeImpl(QualType type) { 2388 switch (type.getObjCLifetime()) { 2389 case Qualifiers::OCL_None: 2390 case Qualifiers::OCL_ExplicitNone: 2391 case Qualifiers::OCL_Autoreleasing: 2392 break; 2393 2394 case Qualifiers::OCL_Strong: 2395 return DK_objc_strong_lifetime; 2396 case Qualifiers::OCL_Weak: 2397 return DK_objc_weak_lifetime; 2398 } 2399 2400 /// Currently, the only destruction kind we recognize is C++ objects 2401 /// with non-trivial destructors. 2402 const CXXRecordDecl *record = 2403 type->getBaseElementTypeUnsafe()->getAsCXXRecordDecl(); 2404 if (record && record->hasDefinition() && !record->hasTrivialDestructor()) 2405 return DK_cxx_destructor; 2406 2407 return DK_none; 2408 } 2409