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