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