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/Type.h" 15 #include "clang/AST/ASTContext.h" 16 #include "clang/AST/Attr.h" 17 #include "clang/AST/CharUnits.h" 18 #include "clang/AST/DeclCXX.h" 19 #include "clang/AST/DeclObjC.h" 20 #include "clang/AST/DeclTemplate.h" 21 #include "clang/AST/Expr.h" 22 #include "clang/AST/PrettyPrinter.h" 23 #include "clang/AST/TypeVisitor.h" 24 #include "clang/Basic/Specifiers.h" 25 #include "clang/Basic/TargetInfo.h" 26 #include "llvm/ADT/APSInt.h" 27 #include "llvm/ADT/StringExtras.h" 28 #include <algorithm> 29 using namespace clang; 30 31 bool Qualifiers::isStrictSupersetOf(Qualifiers Other) const { 32 return (*this != Other) && 33 // CVR qualifiers superset 34 (((Mask & CVRMask) | (Other.Mask & CVRMask)) == (Mask & CVRMask)) && 35 // ObjC GC qualifiers superset 36 ((getObjCGCAttr() == Other.getObjCGCAttr()) || 37 (hasObjCGCAttr() && !Other.hasObjCGCAttr())) && 38 // Address space superset. 39 ((getAddressSpace() == Other.getAddressSpace()) || 40 (hasAddressSpace()&& !Other.hasAddressSpace())) && 41 // Lifetime qualifier superset. 42 ((getObjCLifetime() == Other.getObjCLifetime()) || 43 (hasObjCLifetime() && !Other.hasObjCLifetime())); 44 } 45 46 const IdentifierInfo* QualType::getBaseTypeIdentifier() const { 47 const Type* ty = getTypePtr(); 48 NamedDecl *ND = nullptr; 49 if (ty->isPointerType() || ty->isReferenceType()) 50 return ty->getPointeeType().getBaseTypeIdentifier(); 51 else if (ty->isRecordType()) 52 ND = ty->getAs<RecordType>()->getDecl(); 53 else if (ty->isEnumeralType()) 54 ND = ty->getAs<EnumType>()->getDecl(); 55 else if (ty->getTypeClass() == Type::Typedef) 56 ND = ty->getAs<TypedefType>()->getDecl(); 57 else if (ty->isArrayType()) 58 return ty->castAsArrayTypeUnsafe()-> 59 getElementType().getBaseTypeIdentifier(); 60 61 if (ND) 62 return ND->getIdentifier(); 63 return nullptr; 64 } 65 66 bool QualType::isConstant(QualType T, const ASTContext &Ctx) { 67 if (T.isConstQualified()) 68 return true; 69 70 if (const ArrayType *AT = Ctx.getAsArrayType(T)) 71 return AT->getElementType().isConstant(Ctx); 72 73 return T.getAddressSpace() == LangAS::opencl_constant; 74 } 75 76 unsigned ConstantArrayType::getNumAddressingBits(const ASTContext &Context, 77 QualType ElementType, 78 const llvm::APInt &NumElements) { 79 uint64_t ElementSize = Context.getTypeSizeInChars(ElementType).getQuantity(); 80 81 // Fast path the common cases so we can avoid the conservative computation 82 // below, which in common cases allocates "large" APSInt values, which are 83 // slow. 84 85 // If the element size is a power of 2, we can directly compute the additional 86 // number of addressing bits beyond those required for the element count. 87 if (llvm::isPowerOf2_64(ElementSize)) { 88 return NumElements.getActiveBits() + llvm::Log2_64(ElementSize); 89 } 90 91 // If both the element count and element size fit in 32-bits, we can do the 92 // computation directly in 64-bits. 93 if ((ElementSize >> 32) == 0 && NumElements.getBitWidth() <= 64 && 94 (NumElements.getZExtValue() >> 32) == 0) { 95 uint64_t TotalSize = NumElements.getZExtValue() * ElementSize; 96 return 64 - llvm::countLeadingZeros(TotalSize); 97 } 98 99 // Otherwise, use APSInt to handle arbitrary sized values. 100 llvm::APSInt SizeExtended(NumElements, true); 101 unsigned SizeTypeBits = Context.getTypeSize(Context.getSizeType()); 102 SizeExtended = SizeExtended.extend(std::max(SizeTypeBits, 103 SizeExtended.getBitWidth()) * 2); 104 105 llvm::APSInt TotalSize(llvm::APInt(SizeExtended.getBitWidth(), ElementSize)); 106 TotalSize *= SizeExtended; 107 108 return TotalSize.getActiveBits(); 109 } 110 111 unsigned ConstantArrayType::getMaxSizeBits(const ASTContext &Context) { 112 unsigned Bits = Context.getTypeSize(Context.getSizeType()); 113 114 // Limit the number of bits in size_t so that maximal bit size fits 64 bit 115 // integer (see PR8256). We can do this as currently there is no hardware 116 // that supports full 64-bit virtual space. 117 if (Bits > 61) 118 Bits = 61; 119 120 return Bits; 121 } 122 123 DependentSizedArrayType::DependentSizedArrayType(const ASTContext &Context, 124 QualType et, QualType can, 125 Expr *e, ArraySizeModifier sm, 126 unsigned tq, 127 SourceRange brackets) 128 : ArrayType(DependentSizedArray, et, can, sm, tq, 129 (et->containsUnexpandedParameterPack() || 130 (e && e->containsUnexpandedParameterPack()))), 131 Context(Context), SizeExpr((Stmt*) e), Brackets(brackets) 132 { 133 } 134 135 void DependentSizedArrayType::Profile(llvm::FoldingSetNodeID &ID, 136 const ASTContext &Context, 137 QualType ET, 138 ArraySizeModifier SizeMod, 139 unsigned TypeQuals, 140 Expr *E) { 141 ID.AddPointer(ET.getAsOpaquePtr()); 142 ID.AddInteger(SizeMod); 143 ID.AddInteger(TypeQuals); 144 E->Profile(ID, Context, true); 145 } 146 147 DependentSizedExtVectorType::DependentSizedExtVectorType(const 148 ASTContext &Context, 149 QualType ElementType, 150 QualType can, 151 Expr *SizeExpr, 152 SourceLocation loc) 153 : Type(DependentSizedExtVector, can, /*Dependent=*/true, 154 /*InstantiationDependent=*/true, 155 ElementType->isVariablyModifiedType(), 156 (ElementType->containsUnexpandedParameterPack() || 157 (SizeExpr && SizeExpr->containsUnexpandedParameterPack()))), 158 Context(Context), SizeExpr(SizeExpr), ElementType(ElementType), 159 loc(loc) 160 { 161 } 162 163 void 164 DependentSizedExtVectorType::Profile(llvm::FoldingSetNodeID &ID, 165 const ASTContext &Context, 166 QualType ElementType, Expr *SizeExpr) { 167 ID.AddPointer(ElementType.getAsOpaquePtr()); 168 SizeExpr->Profile(ID, Context, true); 169 } 170 171 VectorType::VectorType(QualType vecType, unsigned nElements, QualType canonType, 172 VectorKind vecKind) 173 : VectorType(Vector, vecType, nElements, canonType, vecKind) {} 174 175 VectorType::VectorType(TypeClass tc, QualType vecType, unsigned nElements, 176 QualType canonType, VectorKind vecKind) 177 : Type(tc, canonType, vecType->isDependentType(), 178 vecType->isInstantiationDependentType(), 179 vecType->isVariablyModifiedType(), 180 vecType->containsUnexpandedParameterPack()), 181 ElementType(vecType) 182 { 183 VectorTypeBits.VecKind = vecKind; 184 VectorTypeBits.NumElements = nElements; 185 } 186 187 /// getArrayElementTypeNoTypeQual - If this is an array type, return the 188 /// element type of the array, potentially with type qualifiers missing. 189 /// This method should never be used when type qualifiers are meaningful. 190 const Type *Type::getArrayElementTypeNoTypeQual() const { 191 // If this is directly an array type, return it. 192 if (const ArrayType *ATy = dyn_cast<ArrayType>(this)) 193 return ATy->getElementType().getTypePtr(); 194 195 // If the canonical form of this type isn't the right kind, reject it. 196 if (!isa<ArrayType>(CanonicalType)) 197 return nullptr; 198 199 // If this is a typedef for an array type, strip the typedef off without 200 // losing all typedef information. 201 return cast<ArrayType>(getUnqualifiedDesugaredType()) 202 ->getElementType().getTypePtr(); 203 } 204 205 /// getDesugaredType - Return the specified type with any "sugar" removed from 206 /// the type. This takes off typedefs, typeof's etc. If the outer level of 207 /// the type is already concrete, it returns it unmodified. This is similar 208 /// to getting the canonical type, but it doesn't remove *all* typedefs. For 209 /// example, it returns "T*" as "T*", (not as "int*"), because the pointer is 210 /// concrete. 211 QualType QualType::getDesugaredType(QualType T, const ASTContext &Context) { 212 SplitQualType split = getSplitDesugaredType(T); 213 return Context.getQualifiedType(split.Ty, split.Quals); 214 } 215 216 QualType QualType::getSingleStepDesugaredTypeImpl(QualType type, 217 const ASTContext &Context) { 218 SplitQualType split = type.split(); 219 QualType desugar = split.Ty->getLocallyUnqualifiedSingleStepDesugaredType(); 220 return Context.getQualifiedType(desugar, split.Quals); 221 } 222 223 QualType Type::getLocallyUnqualifiedSingleStepDesugaredType() const { 224 switch (getTypeClass()) { 225 #define ABSTRACT_TYPE(Class, Parent) 226 #define TYPE(Class, Parent) \ 227 case Type::Class: { \ 228 const Class##Type *ty = cast<Class##Type>(this); \ 229 if (!ty->isSugared()) return QualType(ty, 0); \ 230 return ty->desugar(); \ 231 } 232 #include "clang/AST/TypeNodes.def" 233 } 234 llvm_unreachable("bad type kind!"); 235 } 236 237 SplitQualType QualType::getSplitDesugaredType(QualType T) { 238 QualifierCollector Qs; 239 240 QualType Cur = T; 241 while (true) { 242 const Type *CurTy = Qs.strip(Cur); 243 switch (CurTy->getTypeClass()) { 244 #define ABSTRACT_TYPE(Class, Parent) 245 #define TYPE(Class, Parent) \ 246 case Type::Class: { \ 247 const Class##Type *Ty = cast<Class##Type>(CurTy); \ 248 if (!Ty->isSugared()) \ 249 return SplitQualType(Ty, Qs); \ 250 Cur = Ty->desugar(); \ 251 break; \ 252 } 253 #include "clang/AST/TypeNodes.def" 254 } 255 } 256 } 257 258 SplitQualType QualType::getSplitUnqualifiedTypeImpl(QualType type) { 259 SplitQualType split = type.split(); 260 261 // All the qualifiers we've seen so far. 262 Qualifiers quals = split.Quals; 263 264 // The last type node we saw with any nodes inside it. 265 const Type *lastTypeWithQuals = split.Ty; 266 267 while (true) { 268 QualType next; 269 270 // Do a single-step desugar, aborting the loop if the type isn't 271 // sugared. 272 switch (split.Ty->getTypeClass()) { 273 #define ABSTRACT_TYPE(Class, Parent) 274 #define TYPE(Class, Parent) \ 275 case Type::Class: { \ 276 const Class##Type *ty = cast<Class##Type>(split.Ty); \ 277 if (!ty->isSugared()) goto done; \ 278 next = ty->desugar(); \ 279 break; \ 280 } 281 #include "clang/AST/TypeNodes.def" 282 } 283 284 // Otherwise, split the underlying type. If that yields qualifiers, 285 // update the information. 286 split = next.split(); 287 if (!split.Quals.empty()) { 288 lastTypeWithQuals = split.Ty; 289 quals.addConsistentQualifiers(split.Quals); 290 } 291 } 292 293 done: 294 return SplitQualType(lastTypeWithQuals, quals); 295 } 296 297 QualType QualType::IgnoreParens(QualType T) { 298 // FIXME: this seems inherently un-qualifiers-safe. 299 while (const ParenType *PT = T->getAs<ParenType>()) 300 T = PT->getInnerType(); 301 return T; 302 } 303 304 /// \brief This will check for a T (which should be a Type which can act as 305 /// sugar, such as a TypedefType) by removing any existing sugar until it 306 /// reaches a T or a non-sugared type. 307 template<typename T> static const T *getAsSugar(const Type *Cur) { 308 while (true) { 309 if (const T *Sugar = dyn_cast<T>(Cur)) 310 return Sugar; 311 switch (Cur->getTypeClass()) { 312 #define ABSTRACT_TYPE(Class, Parent) 313 #define TYPE(Class, Parent) \ 314 case Type::Class: { \ 315 const Class##Type *Ty = cast<Class##Type>(Cur); \ 316 if (!Ty->isSugared()) return 0; \ 317 Cur = Ty->desugar().getTypePtr(); \ 318 break; \ 319 } 320 #include "clang/AST/TypeNodes.def" 321 } 322 } 323 } 324 325 template <> const TypedefType *Type::getAs() const { 326 return getAsSugar<TypedefType>(this); 327 } 328 329 template <> const TemplateSpecializationType *Type::getAs() const { 330 return getAsSugar<TemplateSpecializationType>(this); 331 } 332 333 template <> const AttributedType *Type::getAs() const { 334 return getAsSugar<AttributedType>(this); 335 } 336 337 /// getUnqualifiedDesugaredType - Pull any qualifiers and syntactic 338 /// sugar off the given type. This should produce an object of the 339 /// same dynamic type as the canonical type. 340 const Type *Type::getUnqualifiedDesugaredType() const { 341 const Type *Cur = this; 342 343 while (true) { 344 switch (Cur->getTypeClass()) { 345 #define ABSTRACT_TYPE(Class, Parent) 346 #define TYPE(Class, Parent) \ 347 case Class: { \ 348 const Class##Type *Ty = cast<Class##Type>(Cur); \ 349 if (!Ty->isSugared()) return Cur; \ 350 Cur = Ty->desugar().getTypePtr(); \ 351 break; \ 352 } 353 #include "clang/AST/TypeNodes.def" 354 } 355 } 356 } 357 bool Type::isClassType() const { 358 if (const RecordType *RT = getAs<RecordType>()) 359 return RT->getDecl()->isClass(); 360 return false; 361 } 362 bool Type::isStructureType() const { 363 if (const RecordType *RT = getAs<RecordType>()) 364 return RT->getDecl()->isStruct(); 365 return false; 366 } 367 bool Type::isObjCBoxableRecordType() const { 368 if (const RecordType *RT = getAs<RecordType>()) 369 return RT->getDecl()->hasAttr<ObjCBoxableAttr>(); 370 return false; 371 } 372 bool Type::isInterfaceType() const { 373 if (const RecordType *RT = getAs<RecordType>()) 374 return RT->getDecl()->isInterface(); 375 return false; 376 } 377 bool Type::isStructureOrClassType() const { 378 if (const RecordType *RT = getAs<RecordType>()) { 379 RecordDecl *RD = RT->getDecl(); 380 return RD->isStruct() || RD->isClass() || RD->isInterface(); 381 } 382 return false; 383 } 384 bool Type::isVoidPointerType() const { 385 if (const PointerType *PT = getAs<PointerType>()) 386 return PT->getPointeeType()->isVoidType(); 387 return false; 388 } 389 390 bool Type::isUnionType() const { 391 if (const RecordType *RT = getAs<RecordType>()) 392 return RT->getDecl()->isUnion(); 393 return false; 394 } 395 396 bool Type::isComplexType() const { 397 if (const ComplexType *CT = dyn_cast<ComplexType>(CanonicalType)) 398 return CT->getElementType()->isFloatingType(); 399 return false; 400 } 401 402 bool Type::isComplexIntegerType() const { 403 // Check for GCC complex integer extension. 404 return getAsComplexIntegerType(); 405 } 406 407 const ComplexType *Type::getAsComplexIntegerType() const { 408 if (const ComplexType *Complex = getAs<ComplexType>()) 409 if (Complex->getElementType()->isIntegerType()) 410 return Complex; 411 return nullptr; 412 } 413 414 QualType Type::getPointeeType() const { 415 if (const PointerType *PT = getAs<PointerType>()) 416 return PT->getPointeeType(); 417 if (const ObjCObjectPointerType *OPT = getAs<ObjCObjectPointerType>()) 418 return OPT->getPointeeType(); 419 if (const BlockPointerType *BPT = getAs<BlockPointerType>()) 420 return BPT->getPointeeType(); 421 if (const ReferenceType *RT = getAs<ReferenceType>()) 422 return RT->getPointeeType(); 423 if (const MemberPointerType *MPT = getAs<MemberPointerType>()) 424 return MPT->getPointeeType(); 425 if (const DecayedType *DT = getAs<DecayedType>()) 426 return DT->getPointeeType(); 427 return QualType(); 428 } 429 430 const RecordType *Type::getAsStructureType() const { 431 // If this is directly a structure type, return it. 432 if (const RecordType *RT = dyn_cast<RecordType>(this)) { 433 if (RT->getDecl()->isStruct()) 434 return RT; 435 } 436 437 // If the canonical form of this type isn't the right kind, reject it. 438 if (const RecordType *RT = dyn_cast<RecordType>(CanonicalType)) { 439 if (!RT->getDecl()->isStruct()) 440 return nullptr; 441 442 // If this is a typedef for a structure type, strip the typedef off without 443 // losing all typedef information. 444 return cast<RecordType>(getUnqualifiedDesugaredType()); 445 } 446 return nullptr; 447 } 448 449 const RecordType *Type::getAsUnionType() const { 450 // If this is directly a union type, return it. 451 if (const RecordType *RT = dyn_cast<RecordType>(this)) { 452 if (RT->getDecl()->isUnion()) 453 return RT; 454 } 455 456 // If the canonical form of this type isn't the right kind, reject it. 457 if (const RecordType *RT = dyn_cast<RecordType>(CanonicalType)) { 458 if (!RT->getDecl()->isUnion()) 459 return nullptr; 460 461 // If this is a typedef for a union type, strip the typedef off without 462 // losing all typedef information. 463 return cast<RecordType>(getUnqualifiedDesugaredType()); 464 } 465 466 return nullptr; 467 } 468 469 bool Type::isObjCIdOrObjectKindOfType(const ASTContext &ctx, 470 const ObjCObjectType *&bound) const { 471 bound = nullptr; 472 473 const ObjCObjectPointerType *OPT = getAs<ObjCObjectPointerType>(); 474 if (!OPT) 475 return false; 476 477 // Easy case: id. 478 if (OPT->isObjCIdType()) 479 return true; 480 481 // If it's not a __kindof type, reject it now. 482 if (!OPT->isKindOfType()) 483 return false; 484 485 // If it's Class or qualified Class, it's not an object type. 486 if (OPT->isObjCClassType() || OPT->isObjCQualifiedClassType()) 487 return false; 488 489 // Figure out the type bound for the __kindof type. 490 bound = OPT->getObjectType()->stripObjCKindOfTypeAndQuals(ctx) 491 ->getAs<ObjCObjectType>(); 492 return true; 493 } 494 495 bool Type::isObjCClassOrClassKindOfType() const { 496 const ObjCObjectPointerType *OPT = getAs<ObjCObjectPointerType>(); 497 if (!OPT) 498 return false; 499 500 // Easy case: Class. 501 if (OPT->isObjCClassType()) 502 return true; 503 504 // If it's not a __kindof type, reject it now. 505 if (!OPT->isKindOfType()) 506 return false; 507 508 // If it's Class or qualified Class, it's a class __kindof type. 509 return OPT->isObjCClassType() || OPT->isObjCQualifiedClassType(); 510 } 511 512 /// Was this type written with the special inert-in-MRC __unsafe_unretained 513 /// qualifier? 514 /// 515 /// This approximates the answer to the following question: if this 516 /// translation unit were compiled in ARC, would this type be qualified 517 /// with __unsafe_unretained? 518 bool Type::isObjCInertUnsafeUnretainedType() const { 519 const Type *cur = this; 520 while (true) { 521 if (auto attributed = dyn_cast<AttributedType>(cur)) { 522 if (attributed->getAttrKind() == 523 AttributedType::attr_objc_inert_unsafe_unretained) 524 return true; 525 } 526 527 // Single-step desugar until we run out of sugar. 528 QualType next = cur->getLocallyUnqualifiedSingleStepDesugaredType(); 529 if (next.getTypePtr() == cur) return false; 530 cur = next.getTypePtr(); 531 } 532 } 533 534 ObjCObjectType::ObjCObjectType(QualType Canonical, QualType Base, 535 ArrayRef<QualType> typeArgs, 536 ArrayRef<ObjCProtocolDecl *> protocols, 537 bool isKindOf) 538 : Type(ObjCObject, Canonical, Base->isDependentType(), 539 Base->isInstantiationDependentType(), 540 Base->isVariablyModifiedType(), 541 Base->containsUnexpandedParameterPack()), 542 BaseType(Base) 543 { 544 ObjCObjectTypeBits.IsKindOf = isKindOf; 545 546 ObjCObjectTypeBits.NumTypeArgs = typeArgs.size(); 547 assert(getTypeArgsAsWritten().size() == typeArgs.size() && 548 "bitfield overflow in type argument count"); 549 ObjCObjectTypeBits.NumProtocols = protocols.size(); 550 assert(getNumProtocols() == protocols.size() && 551 "bitfield overflow in protocol count"); 552 if (!typeArgs.empty()) 553 memcpy(getTypeArgStorage(), typeArgs.data(), 554 typeArgs.size() * sizeof(QualType)); 555 if (!protocols.empty()) 556 memcpy(getProtocolStorage(), protocols.data(), 557 protocols.size() * sizeof(ObjCProtocolDecl*)); 558 559 for (auto typeArg : typeArgs) { 560 if (typeArg->isDependentType()) 561 setDependent(); 562 else if (typeArg->isInstantiationDependentType()) 563 setInstantiationDependent(); 564 565 if (typeArg->containsUnexpandedParameterPack()) 566 setContainsUnexpandedParameterPack(); 567 } 568 } 569 570 bool ObjCObjectType::isSpecialized() const { 571 // If we have type arguments written here, the type is specialized. 572 if (ObjCObjectTypeBits.NumTypeArgs > 0) 573 return true; 574 575 // Otherwise, check whether the base type is specialized. 576 if (auto objcObject = getBaseType()->getAs<ObjCObjectType>()) { 577 // Terminate when we reach an interface type. 578 if (isa<ObjCInterfaceType>(objcObject)) 579 return false; 580 581 return objcObject->isSpecialized(); 582 } 583 584 // Not specialized. 585 return false; 586 } 587 588 ArrayRef<QualType> ObjCObjectType::getTypeArgs() const { 589 // We have type arguments written on this type. 590 if (isSpecializedAsWritten()) 591 return getTypeArgsAsWritten(); 592 593 // Look at the base type, which might have type arguments. 594 if (auto objcObject = getBaseType()->getAs<ObjCObjectType>()) { 595 // Terminate when we reach an interface type. 596 if (isa<ObjCInterfaceType>(objcObject)) 597 return { }; 598 599 return objcObject->getTypeArgs(); 600 } 601 602 // No type arguments. 603 return { }; 604 } 605 606 bool ObjCObjectType::isKindOfType() const { 607 if (isKindOfTypeAsWritten()) 608 return true; 609 610 // Look at the base type, which might have type arguments. 611 if (auto objcObject = getBaseType()->getAs<ObjCObjectType>()) { 612 // Terminate when we reach an interface type. 613 if (isa<ObjCInterfaceType>(objcObject)) 614 return false; 615 616 return objcObject->isKindOfType(); 617 } 618 619 // Not a "__kindof" type. 620 return false; 621 } 622 623 QualType ObjCObjectType::stripObjCKindOfTypeAndQuals( 624 const ASTContext &ctx) const { 625 if (!isKindOfType() && qual_empty()) 626 return QualType(this, 0); 627 628 // Recursively strip __kindof. 629 SplitQualType splitBaseType = getBaseType().split(); 630 QualType baseType(splitBaseType.Ty, 0); 631 if (const ObjCObjectType *baseObj 632 = splitBaseType.Ty->getAs<ObjCObjectType>()) { 633 baseType = baseObj->stripObjCKindOfTypeAndQuals(ctx); 634 } 635 636 return ctx.getObjCObjectType(ctx.getQualifiedType(baseType, 637 splitBaseType.Quals), 638 getTypeArgsAsWritten(), 639 /*protocols=*/{ }, 640 /*isKindOf=*/false); 641 } 642 643 const ObjCObjectPointerType *ObjCObjectPointerType::stripObjCKindOfTypeAndQuals( 644 const ASTContext &ctx) const { 645 if (!isKindOfType() && qual_empty()) 646 return this; 647 648 QualType obj = getObjectType()->stripObjCKindOfTypeAndQuals(ctx); 649 return ctx.getObjCObjectPointerType(obj)->castAs<ObjCObjectPointerType>(); 650 } 651 652 namespace { 653 654 template<typename F> 655 QualType simpleTransform(ASTContext &ctx, QualType type, F &&f); 656 657 /// Visitor used by simpleTransform() to perform the transformation. 658 template<typename F> 659 struct SimpleTransformVisitor 660 : public TypeVisitor<SimpleTransformVisitor<F>, QualType> { 661 ASTContext &Ctx; 662 F &&TheFunc; 663 664 QualType recurse(QualType type) { 665 return simpleTransform(Ctx, type, std::move(TheFunc)); 666 } 667 668 public: 669 SimpleTransformVisitor(ASTContext &ctx, F &&f) : Ctx(ctx), TheFunc(std::move(f)) { } 670 671 // None of the clients of this transformation can occur where 672 // there are dependent types, so skip dependent types. 673 #define TYPE(Class, Base) 674 #define DEPENDENT_TYPE(Class, Base) \ 675 QualType Visit##Class##Type(const Class##Type *T) { return QualType(T, 0); } 676 #include "clang/AST/TypeNodes.def" 677 678 #define TRIVIAL_TYPE_CLASS(Class) \ 679 QualType Visit##Class##Type(const Class##Type *T) { return QualType(T, 0); } 680 681 TRIVIAL_TYPE_CLASS(Builtin) 682 683 QualType VisitComplexType(const ComplexType *T) { 684 QualType elementType = recurse(T->getElementType()); 685 if (elementType.isNull()) 686 return QualType(); 687 688 if (elementType.getAsOpaquePtr() == T->getElementType().getAsOpaquePtr()) 689 return QualType(T, 0); 690 691 return Ctx.getComplexType(elementType); 692 } 693 694 QualType VisitPointerType(const PointerType *T) { 695 QualType pointeeType = recurse(T->getPointeeType()); 696 if (pointeeType.isNull()) 697 return QualType(); 698 699 if (pointeeType.getAsOpaquePtr() == T->getPointeeType().getAsOpaquePtr()) 700 return QualType(T, 0); 701 702 return Ctx.getPointerType(pointeeType); 703 } 704 705 QualType VisitBlockPointerType(const BlockPointerType *T) { 706 QualType pointeeType = recurse(T->getPointeeType()); 707 if (pointeeType.isNull()) 708 return QualType(); 709 710 if (pointeeType.getAsOpaquePtr() == T->getPointeeType().getAsOpaquePtr()) 711 return QualType(T, 0); 712 713 return Ctx.getBlockPointerType(pointeeType); 714 } 715 716 QualType VisitLValueReferenceType(const LValueReferenceType *T) { 717 QualType pointeeType = recurse(T->getPointeeTypeAsWritten()); 718 if (pointeeType.isNull()) 719 return QualType(); 720 721 if (pointeeType.getAsOpaquePtr() 722 == T->getPointeeTypeAsWritten().getAsOpaquePtr()) 723 return QualType(T, 0); 724 725 return Ctx.getLValueReferenceType(pointeeType, T->isSpelledAsLValue()); 726 } 727 728 QualType VisitRValueReferenceType(const RValueReferenceType *T) { 729 QualType pointeeType = recurse(T->getPointeeTypeAsWritten()); 730 if (pointeeType.isNull()) 731 return QualType(); 732 733 if (pointeeType.getAsOpaquePtr() 734 == T->getPointeeTypeAsWritten().getAsOpaquePtr()) 735 return QualType(T, 0); 736 737 return Ctx.getRValueReferenceType(pointeeType); 738 } 739 740 QualType VisitMemberPointerType(const MemberPointerType *T) { 741 QualType pointeeType = recurse(T->getPointeeType()); 742 if (pointeeType.isNull()) 743 return QualType(); 744 745 if (pointeeType.getAsOpaquePtr() == T->getPointeeType().getAsOpaquePtr()) 746 return QualType(T, 0); 747 748 return Ctx.getMemberPointerType(pointeeType, T->getClass()); 749 } 750 751 QualType VisitConstantArrayType(const ConstantArrayType *T) { 752 QualType elementType = recurse(T->getElementType()); 753 if (elementType.isNull()) 754 return QualType(); 755 756 if (elementType.getAsOpaquePtr() == T->getElementType().getAsOpaquePtr()) 757 return QualType(T, 0); 758 759 return Ctx.getConstantArrayType(elementType, T->getSize(), 760 T->getSizeModifier(), 761 T->getIndexTypeCVRQualifiers()); 762 } 763 764 QualType VisitVariableArrayType(const VariableArrayType *T) { 765 QualType elementType = recurse(T->getElementType()); 766 if (elementType.isNull()) 767 return QualType(); 768 769 if (elementType.getAsOpaquePtr() == T->getElementType().getAsOpaquePtr()) 770 return QualType(T, 0); 771 772 return Ctx.getVariableArrayType(elementType, T->getSizeExpr(), 773 T->getSizeModifier(), 774 T->getIndexTypeCVRQualifiers(), 775 T->getBracketsRange()); 776 } 777 778 QualType VisitIncompleteArrayType(const IncompleteArrayType *T) { 779 QualType elementType = recurse(T->getElementType()); 780 if (elementType.isNull()) 781 return QualType(); 782 783 if (elementType.getAsOpaquePtr() == T->getElementType().getAsOpaquePtr()) 784 return QualType(T, 0); 785 786 return Ctx.getIncompleteArrayType(elementType, T->getSizeModifier(), 787 T->getIndexTypeCVRQualifiers()); 788 } 789 790 QualType VisitVectorType(const VectorType *T) { 791 QualType elementType = recurse(T->getElementType()); 792 if (elementType.isNull()) 793 return QualType(); 794 795 if (elementType.getAsOpaquePtr() == T->getElementType().getAsOpaquePtr()) 796 return QualType(T, 0); 797 798 return Ctx.getVectorType(elementType, T->getNumElements(), 799 T->getVectorKind()); 800 } 801 802 QualType VisitExtVectorType(const ExtVectorType *T) { 803 QualType elementType = recurse(T->getElementType()); 804 if (elementType.isNull()) 805 return QualType(); 806 807 if (elementType.getAsOpaquePtr() == T->getElementType().getAsOpaquePtr()) 808 return QualType(T, 0); 809 810 return Ctx.getExtVectorType(elementType, T->getNumElements()); 811 } 812 813 QualType VisitFunctionNoProtoType(const FunctionNoProtoType *T) { 814 QualType returnType = recurse(T->getReturnType()); 815 if (returnType.isNull()) 816 return QualType(); 817 818 if (returnType.getAsOpaquePtr() == T->getReturnType().getAsOpaquePtr()) 819 return QualType(T, 0); 820 821 return Ctx.getFunctionNoProtoType(returnType, T->getExtInfo()); 822 } 823 824 QualType VisitFunctionProtoType(const FunctionProtoType *T) { 825 QualType returnType = recurse(T->getReturnType()); 826 if (returnType.isNull()) 827 return QualType(); 828 829 // Transform parameter types. 830 SmallVector<QualType, 4> paramTypes; 831 bool paramChanged = false; 832 for (auto paramType : T->getParamTypes()) { 833 QualType newParamType = recurse(paramType); 834 if (newParamType.isNull()) 835 return QualType(); 836 837 if (newParamType.getAsOpaquePtr() != paramType.getAsOpaquePtr()) 838 paramChanged = true; 839 840 paramTypes.push_back(newParamType); 841 } 842 843 // Transform extended info. 844 FunctionProtoType::ExtProtoInfo info = T->getExtProtoInfo(); 845 bool exceptionChanged = false; 846 if (info.ExceptionSpec.Type == EST_Dynamic) { 847 SmallVector<QualType, 4> exceptionTypes; 848 for (auto exceptionType : info.ExceptionSpec.Exceptions) { 849 QualType newExceptionType = recurse(exceptionType); 850 if (newExceptionType.isNull()) 851 return QualType(); 852 853 if (newExceptionType.getAsOpaquePtr() 854 != exceptionType.getAsOpaquePtr()) 855 exceptionChanged = true; 856 857 exceptionTypes.push_back(newExceptionType); 858 } 859 860 if (exceptionChanged) { 861 info.ExceptionSpec.Exceptions = 862 llvm::makeArrayRef(exceptionTypes).copy(Ctx); 863 } 864 } 865 866 if (returnType.getAsOpaquePtr() == T->getReturnType().getAsOpaquePtr() && 867 !paramChanged && !exceptionChanged) 868 return QualType(T, 0); 869 870 return Ctx.getFunctionType(returnType, paramTypes, info); 871 } 872 873 QualType VisitParenType(const ParenType *T) { 874 QualType innerType = recurse(T->getInnerType()); 875 if (innerType.isNull()) 876 return QualType(); 877 878 if (innerType.getAsOpaquePtr() == T->getInnerType().getAsOpaquePtr()) 879 return QualType(T, 0); 880 881 return Ctx.getParenType(innerType); 882 } 883 884 TRIVIAL_TYPE_CLASS(Typedef) 885 886 QualType VisitAdjustedType(const AdjustedType *T) { 887 QualType originalType = recurse(T->getOriginalType()); 888 if (originalType.isNull()) 889 return QualType(); 890 891 QualType adjustedType = recurse(T->getAdjustedType()); 892 if (adjustedType.isNull()) 893 return QualType(); 894 895 if (originalType.getAsOpaquePtr() 896 == T->getOriginalType().getAsOpaquePtr() && 897 adjustedType.getAsOpaquePtr() == T->getAdjustedType().getAsOpaquePtr()) 898 return QualType(T, 0); 899 900 return Ctx.getAdjustedType(originalType, adjustedType); 901 } 902 903 QualType VisitDecayedType(const DecayedType *T) { 904 QualType originalType = recurse(T->getOriginalType()); 905 if (originalType.isNull()) 906 return QualType(); 907 908 if (originalType.getAsOpaquePtr() 909 == T->getOriginalType().getAsOpaquePtr()) 910 return QualType(T, 0); 911 912 return Ctx.getDecayedType(originalType); 913 } 914 915 TRIVIAL_TYPE_CLASS(TypeOfExpr) 916 TRIVIAL_TYPE_CLASS(TypeOf) 917 TRIVIAL_TYPE_CLASS(Decltype) 918 TRIVIAL_TYPE_CLASS(UnaryTransform) 919 TRIVIAL_TYPE_CLASS(Record) 920 TRIVIAL_TYPE_CLASS(Enum) 921 922 // FIXME: Non-trivial to implement, but important for C++ 923 TRIVIAL_TYPE_CLASS(Elaborated) 924 925 QualType VisitAttributedType(const AttributedType *T) { 926 QualType modifiedType = recurse(T->getModifiedType()); 927 if (modifiedType.isNull()) 928 return QualType(); 929 930 QualType equivalentType = recurse(T->getEquivalentType()); 931 if (equivalentType.isNull()) 932 return QualType(); 933 934 if (modifiedType.getAsOpaquePtr() 935 == T->getModifiedType().getAsOpaquePtr() && 936 equivalentType.getAsOpaquePtr() 937 == T->getEquivalentType().getAsOpaquePtr()) 938 return QualType(T, 0); 939 940 return Ctx.getAttributedType(T->getAttrKind(), modifiedType, 941 equivalentType); 942 } 943 944 QualType VisitSubstTemplateTypeParmType(const SubstTemplateTypeParmType *T) { 945 QualType replacementType = recurse(T->getReplacementType()); 946 if (replacementType.isNull()) 947 return QualType(); 948 949 if (replacementType.getAsOpaquePtr() 950 == T->getReplacementType().getAsOpaquePtr()) 951 return QualType(T, 0); 952 953 return Ctx.getSubstTemplateTypeParmType(T->getReplacedParameter(), 954 replacementType); 955 } 956 957 // FIXME: Non-trivial to implement, but important for C++ 958 TRIVIAL_TYPE_CLASS(TemplateSpecialization) 959 960 QualType VisitAutoType(const AutoType *T) { 961 if (!T->isDeduced()) 962 return QualType(T, 0); 963 964 QualType deducedType = recurse(T->getDeducedType()); 965 if (deducedType.isNull()) 966 return QualType(); 967 968 if (deducedType.getAsOpaquePtr() 969 == T->getDeducedType().getAsOpaquePtr()) 970 return QualType(T, 0); 971 972 return Ctx.getAutoType(deducedType, T->getKeyword(), 973 T->isDependentType()); 974 } 975 976 // FIXME: Non-trivial to implement, but important for C++ 977 TRIVIAL_TYPE_CLASS(PackExpansion) 978 979 QualType VisitObjCObjectType(const ObjCObjectType *T) { 980 QualType baseType = recurse(T->getBaseType()); 981 if (baseType.isNull()) 982 return QualType(); 983 984 // Transform type arguments. 985 bool typeArgChanged = false; 986 SmallVector<QualType, 4> typeArgs; 987 for (auto typeArg : T->getTypeArgsAsWritten()) { 988 QualType newTypeArg = recurse(typeArg); 989 if (newTypeArg.isNull()) 990 return QualType(); 991 992 if (newTypeArg.getAsOpaquePtr() != typeArg.getAsOpaquePtr()) 993 typeArgChanged = true; 994 995 typeArgs.push_back(newTypeArg); 996 } 997 998 if (baseType.getAsOpaquePtr() == T->getBaseType().getAsOpaquePtr() && 999 !typeArgChanged) 1000 return QualType(T, 0); 1001 1002 return Ctx.getObjCObjectType(baseType, typeArgs, 1003 llvm::makeArrayRef(T->qual_begin(), 1004 T->getNumProtocols()), 1005 T->isKindOfTypeAsWritten()); 1006 } 1007 1008 TRIVIAL_TYPE_CLASS(ObjCInterface) 1009 1010 QualType VisitObjCObjectPointerType(const ObjCObjectPointerType *T) { 1011 QualType pointeeType = recurse(T->getPointeeType()); 1012 if (pointeeType.isNull()) 1013 return QualType(); 1014 1015 if (pointeeType.getAsOpaquePtr() 1016 == T->getPointeeType().getAsOpaquePtr()) 1017 return QualType(T, 0); 1018 1019 return Ctx.getObjCObjectPointerType(pointeeType); 1020 } 1021 1022 QualType VisitAtomicType(const AtomicType *T) { 1023 QualType valueType = recurse(T->getValueType()); 1024 if (valueType.isNull()) 1025 return QualType(); 1026 1027 if (valueType.getAsOpaquePtr() 1028 == T->getValueType().getAsOpaquePtr()) 1029 return QualType(T, 0); 1030 1031 return Ctx.getAtomicType(valueType); 1032 } 1033 1034 #undef TRIVIAL_TYPE_CLASS 1035 }; 1036 1037 /// Perform a simple type transformation that does not change the 1038 /// semantics of the type. 1039 template<typename F> 1040 QualType simpleTransform(ASTContext &ctx, QualType type, F &&f) { 1041 // Transform the type. If it changed, return the transformed result. 1042 QualType transformed = f(type); 1043 if (transformed.getAsOpaquePtr() != type.getAsOpaquePtr()) 1044 return transformed; 1045 1046 // Split out the qualifiers from the type. 1047 SplitQualType splitType = type.split(); 1048 1049 // Visit the type itself. 1050 SimpleTransformVisitor<F> visitor(ctx, std::move(f)); 1051 QualType result = visitor.Visit(splitType.Ty); 1052 if (result.isNull()) 1053 return result; 1054 1055 // Reconstruct the transformed type by applying the local qualifiers 1056 // from the split type. 1057 return ctx.getQualifiedType(result, splitType.Quals); 1058 } 1059 1060 } // end anonymous namespace 1061 1062 /// Substitute the given type arguments for Objective-C type 1063 /// parameters within the given type, recursively. 1064 QualType QualType::substObjCTypeArgs( 1065 ASTContext &ctx, 1066 ArrayRef<QualType> typeArgs, 1067 ObjCSubstitutionContext context) const { 1068 return simpleTransform(ctx, *this, 1069 [&](QualType type) -> QualType { 1070 SplitQualType splitType = type.split(); 1071 1072 // Replace an Objective-C type parameter reference with the corresponding 1073 // type argument. 1074 if (const auto *typedefTy = dyn_cast<TypedefType>(splitType.Ty)) { 1075 if (auto *typeParam = dyn_cast<ObjCTypeParamDecl>(typedefTy->getDecl())) { 1076 // If we have type arguments, use them. 1077 if (!typeArgs.empty()) { 1078 // FIXME: Introduce SubstObjCTypeParamType ? 1079 QualType argType = typeArgs[typeParam->getIndex()]; 1080 return ctx.getQualifiedType(argType, splitType.Quals); 1081 } 1082 1083 switch (context) { 1084 case ObjCSubstitutionContext::Ordinary: 1085 case ObjCSubstitutionContext::Parameter: 1086 case ObjCSubstitutionContext::Superclass: 1087 // Substitute the bound. 1088 return ctx.getQualifiedType(typeParam->getUnderlyingType(), 1089 splitType.Quals); 1090 1091 case ObjCSubstitutionContext::Result: 1092 case ObjCSubstitutionContext::Property: { 1093 // Substitute the __kindof form of the underlying type. 1094 const auto *objPtr = typeParam->getUnderlyingType() 1095 ->castAs<ObjCObjectPointerType>(); 1096 1097 // __kindof types, id, and Class don't need an additional 1098 // __kindof. 1099 if (objPtr->isKindOfType() || objPtr->isObjCIdOrClassType()) 1100 return ctx.getQualifiedType(typeParam->getUnderlyingType(), 1101 splitType.Quals); 1102 1103 // Add __kindof. 1104 const auto *obj = objPtr->getObjectType(); 1105 QualType resultTy = ctx.getObjCObjectType(obj->getBaseType(), 1106 obj->getTypeArgsAsWritten(), 1107 obj->getProtocols(), 1108 /*isKindOf=*/true); 1109 1110 // Rebuild object pointer type. 1111 resultTy = ctx.getObjCObjectPointerType(resultTy); 1112 return ctx.getQualifiedType(resultTy, splitType.Quals); 1113 } 1114 } 1115 } 1116 } 1117 1118 // If we have a function type, update the context appropriately. 1119 if (const auto *funcType = dyn_cast<FunctionType>(splitType.Ty)) { 1120 // Substitute result type. 1121 QualType returnType = funcType->getReturnType().substObjCTypeArgs( 1122 ctx, 1123 typeArgs, 1124 ObjCSubstitutionContext::Result); 1125 if (returnType.isNull()) 1126 return QualType(); 1127 1128 // Handle non-prototyped functions, which only substitute into the result 1129 // type. 1130 if (isa<FunctionNoProtoType>(funcType)) { 1131 // If the return type was unchanged, do nothing. 1132 if (returnType.getAsOpaquePtr() 1133 == funcType->getReturnType().getAsOpaquePtr()) 1134 return type; 1135 1136 // Otherwise, build a new type. 1137 return ctx.getFunctionNoProtoType(returnType, funcType->getExtInfo()); 1138 } 1139 1140 const auto *funcProtoType = cast<FunctionProtoType>(funcType); 1141 1142 // Transform parameter types. 1143 SmallVector<QualType, 4> paramTypes; 1144 bool paramChanged = false; 1145 for (auto paramType : funcProtoType->getParamTypes()) { 1146 QualType newParamType = paramType.substObjCTypeArgs( 1147 ctx, 1148 typeArgs, 1149 ObjCSubstitutionContext::Parameter); 1150 if (newParamType.isNull()) 1151 return QualType(); 1152 1153 if (newParamType.getAsOpaquePtr() != paramType.getAsOpaquePtr()) 1154 paramChanged = true; 1155 1156 paramTypes.push_back(newParamType); 1157 } 1158 1159 // Transform extended info. 1160 FunctionProtoType::ExtProtoInfo info = funcProtoType->getExtProtoInfo(); 1161 bool exceptionChanged = false; 1162 if (info.ExceptionSpec.Type == EST_Dynamic) { 1163 SmallVector<QualType, 4> exceptionTypes; 1164 for (auto exceptionType : info.ExceptionSpec.Exceptions) { 1165 QualType newExceptionType = exceptionType.substObjCTypeArgs( 1166 ctx, 1167 typeArgs, 1168 ObjCSubstitutionContext::Ordinary); 1169 if (newExceptionType.isNull()) 1170 return QualType(); 1171 1172 if (newExceptionType.getAsOpaquePtr() 1173 != exceptionType.getAsOpaquePtr()) 1174 exceptionChanged = true; 1175 1176 exceptionTypes.push_back(newExceptionType); 1177 } 1178 1179 if (exceptionChanged) { 1180 info.ExceptionSpec.Exceptions = 1181 llvm::makeArrayRef(exceptionTypes).copy(ctx); 1182 } 1183 } 1184 1185 if (returnType.getAsOpaquePtr() 1186 == funcProtoType->getReturnType().getAsOpaquePtr() && 1187 !paramChanged && !exceptionChanged) 1188 return type; 1189 1190 return ctx.getFunctionType(returnType, paramTypes, info); 1191 } 1192 1193 // Substitute into the type arguments of a specialized Objective-C object 1194 // type. 1195 if (const auto *objcObjectType = dyn_cast<ObjCObjectType>(splitType.Ty)) { 1196 if (objcObjectType->isSpecializedAsWritten()) { 1197 SmallVector<QualType, 4> newTypeArgs; 1198 bool anyChanged = false; 1199 for (auto typeArg : objcObjectType->getTypeArgsAsWritten()) { 1200 QualType newTypeArg = typeArg.substObjCTypeArgs( 1201 ctx, typeArgs, 1202 ObjCSubstitutionContext::Ordinary); 1203 if (newTypeArg.isNull()) 1204 return QualType(); 1205 1206 if (newTypeArg.getAsOpaquePtr() != typeArg.getAsOpaquePtr()) { 1207 // If we're substituting based on an unspecialized context type, 1208 // produce an unspecialized type. 1209 ArrayRef<ObjCProtocolDecl *> protocols( 1210 objcObjectType->qual_begin(), 1211 objcObjectType->getNumProtocols()); 1212 if (typeArgs.empty() && 1213 context != ObjCSubstitutionContext::Superclass) { 1214 return ctx.getObjCObjectType( 1215 objcObjectType->getBaseType(), { }, 1216 protocols, 1217 objcObjectType->isKindOfTypeAsWritten()); 1218 } 1219 1220 anyChanged = true; 1221 } 1222 1223 newTypeArgs.push_back(newTypeArg); 1224 } 1225 1226 if (anyChanged) { 1227 ArrayRef<ObjCProtocolDecl *> protocols( 1228 objcObjectType->qual_begin(), 1229 objcObjectType->getNumProtocols()); 1230 return ctx.getObjCObjectType(objcObjectType->getBaseType(), 1231 newTypeArgs, protocols, 1232 objcObjectType->isKindOfTypeAsWritten()); 1233 } 1234 } 1235 1236 return type; 1237 } 1238 1239 return type; 1240 }); 1241 } 1242 1243 QualType QualType::substObjCMemberType(QualType objectType, 1244 const DeclContext *dc, 1245 ObjCSubstitutionContext context) const { 1246 if (auto subs = objectType->getObjCSubstitutions(dc)) 1247 return substObjCTypeArgs(dc->getParentASTContext(), *subs, context); 1248 1249 return *this; 1250 } 1251 1252 QualType QualType::stripObjCKindOfType(const ASTContext &constCtx) const { 1253 // FIXME: Because ASTContext::getAttributedType() is non-const. 1254 auto &ctx = const_cast<ASTContext &>(constCtx); 1255 return simpleTransform(ctx, *this, 1256 [&](QualType type) -> QualType { 1257 SplitQualType splitType = type.split(); 1258 if (auto *objType = splitType.Ty->getAs<ObjCObjectType>()) { 1259 if (!objType->isKindOfType()) 1260 return type; 1261 1262 QualType baseType 1263 = objType->getBaseType().stripObjCKindOfType(ctx); 1264 return ctx.getQualifiedType( 1265 ctx.getObjCObjectType(baseType, 1266 objType->getTypeArgsAsWritten(), 1267 objType->getProtocols(), 1268 /*isKindOf=*/false), 1269 splitType.Quals); 1270 } 1271 1272 return type; 1273 }); 1274 } 1275 1276 QualType QualType::getAtomicUnqualifiedType() const { 1277 if (auto AT = getTypePtr()->getAs<AtomicType>()) 1278 return AT->getValueType().getUnqualifiedType(); 1279 return getUnqualifiedType(); 1280 } 1281 1282 Optional<ArrayRef<QualType>> Type::getObjCSubstitutions( 1283 const DeclContext *dc) const { 1284 // Look through method scopes. 1285 if (auto method = dyn_cast<ObjCMethodDecl>(dc)) 1286 dc = method->getDeclContext(); 1287 1288 // Find the class or category in which the type we're substituting 1289 // was declared. 1290 const ObjCInterfaceDecl *dcClassDecl = dyn_cast<ObjCInterfaceDecl>(dc); 1291 const ObjCCategoryDecl *dcCategoryDecl = nullptr; 1292 ObjCTypeParamList *dcTypeParams = nullptr; 1293 if (dcClassDecl) { 1294 // If the class does not have any type parameters, there's no 1295 // substitution to do. 1296 dcTypeParams = dcClassDecl->getTypeParamList(); 1297 if (!dcTypeParams) 1298 return None; 1299 } else { 1300 // If we are in neither a class nor a category, there's no 1301 // substitution to perform. 1302 dcCategoryDecl = dyn_cast<ObjCCategoryDecl>(dc); 1303 if (!dcCategoryDecl) 1304 return None; 1305 1306 // If the category does not have any type parameters, there's no 1307 // substitution to do. 1308 dcTypeParams = dcCategoryDecl->getTypeParamList(); 1309 if (!dcTypeParams) 1310 return None; 1311 1312 dcClassDecl = dcCategoryDecl->getClassInterface(); 1313 if (!dcClassDecl) 1314 return None; 1315 } 1316 assert(dcTypeParams && "No substitutions to perform"); 1317 assert(dcClassDecl && "No class context"); 1318 1319 // Find the underlying object type. 1320 const ObjCObjectType *objectType; 1321 if (const auto *objectPointerType = getAs<ObjCObjectPointerType>()) { 1322 objectType = objectPointerType->getObjectType(); 1323 } else if (getAs<BlockPointerType>()) { 1324 ASTContext &ctx = dc->getParentASTContext(); 1325 objectType = ctx.getObjCObjectType(ctx.ObjCBuiltinIdTy, { }, { }) 1326 ->castAs<ObjCObjectType>();; 1327 } else { 1328 objectType = getAs<ObjCObjectType>(); 1329 } 1330 1331 /// Extract the class from the receiver object type. 1332 ObjCInterfaceDecl *curClassDecl = objectType ? objectType->getInterface() 1333 : nullptr; 1334 if (!curClassDecl) { 1335 // If we don't have a context type (e.g., this is "id" or some 1336 // variant thereof), substitute the bounds. 1337 return llvm::ArrayRef<QualType>(); 1338 } 1339 1340 // Follow the superclass chain until we've mapped the receiver type 1341 // to the same class as the context. 1342 while (curClassDecl != dcClassDecl) { 1343 // Map to the superclass type. 1344 QualType superType = objectType->getSuperClassType(); 1345 if (superType.isNull()) { 1346 objectType = nullptr; 1347 break; 1348 } 1349 1350 objectType = superType->castAs<ObjCObjectType>(); 1351 curClassDecl = objectType->getInterface(); 1352 } 1353 1354 // If we don't have a receiver type, or the receiver type does not 1355 // have type arguments, substitute in the defaults. 1356 if (!objectType || objectType->isUnspecialized()) { 1357 return llvm::ArrayRef<QualType>(); 1358 } 1359 1360 // The receiver type has the type arguments we want. 1361 return objectType->getTypeArgs(); 1362 } 1363 1364 bool Type::acceptsObjCTypeParams() const { 1365 if (auto *IfaceT = getAsObjCInterfaceType()) { 1366 if (auto *ID = IfaceT->getInterface()) { 1367 if (ID->getTypeParamList()) 1368 return true; 1369 } 1370 } 1371 1372 return false; 1373 } 1374 1375 void ObjCObjectType::computeSuperClassTypeSlow() const { 1376 // Retrieve the class declaration for this type. If there isn't one 1377 // (e.g., this is some variant of "id" or "Class"), then there is no 1378 // superclass type. 1379 ObjCInterfaceDecl *classDecl = getInterface(); 1380 if (!classDecl) { 1381 CachedSuperClassType.setInt(true); 1382 return; 1383 } 1384 1385 // Extract the superclass type. 1386 const ObjCObjectType *superClassObjTy = classDecl->getSuperClassType(); 1387 if (!superClassObjTy) { 1388 CachedSuperClassType.setInt(true); 1389 return; 1390 } 1391 1392 ObjCInterfaceDecl *superClassDecl = superClassObjTy->getInterface(); 1393 if (!superClassDecl) { 1394 CachedSuperClassType.setInt(true); 1395 return; 1396 } 1397 1398 // If the superclass doesn't have type parameters, then there is no 1399 // substitution to perform. 1400 QualType superClassType(superClassObjTy, 0); 1401 ObjCTypeParamList *superClassTypeParams = superClassDecl->getTypeParamList(); 1402 if (!superClassTypeParams) { 1403 CachedSuperClassType.setPointerAndInt( 1404 superClassType->castAs<ObjCObjectType>(), true); 1405 return; 1406 } 1407 1408 // If the superclass reference is unspecialized, return it. 1409 if (superClassObjTy->isUnspecialized()) { 1410 CachedSuperClassType.setPointerAndInt(superClassObjTy, true); 1411 return; 1412 } 1413 1414 // If the subclass is not parameterized, there aren't any type 1415 // parameters in the superclass reference to substitute. 1416 ObjCTypeParamList *typeParams = classDecl->getTypeParamList(); 1417 if (!typeParams) { 1418 CachedSuperClassType.setPointerAndInt( 1419 superClassType->castAs<ObjCObjectType>(), true); 1420 return; 1421 } 1422 1423 // If the subclass type isn't specialized, return the unspecialized 1424 // superclass. 1425 if (isUnspecialized()) { 1426 QualType unspecializedSuper 1427 = classDecl->getASTContext().getObjCInterfaceType( 1428 superClassObjTy->getInterface()); 1429 CachedSuperClassType.setPointerAndInt( 1430 unspecializedSuper->castAs<ObjCObjectType>(), 1431 true); 1432 return; 1433 } 1434 1435 // Substitute the provided type arguments into the superclass type. 1436 ArrayRef<QualType> typeArgs = getTypeArgs(); 1437 assert(typeArgs.size() == typeParams->size()); 1438 CachedSuperClassType.setPointerAndInt( 1439 superClassType.substObjCTypeArgs(classDecl->getASTContext(), typeArgs, 1440 ObjCSubstitutionContext::Superclass) 1441 ->castAs<ObjCObjectType>(), 1442 true); 1443 } 1444 1445 const ObjCInterfaceType *ObjCObjectPointerType::getInterfaceType() const { 1446 if (auto interfaceDecl = getObjectType()->getInterface()) { 1447 return interfaceDecl->getASTContext().getObjCInterfaceType(interfaceDecl) 1448 ->castAs<ObjCInterfaceType>(); 1449 } 1450 1451 return nullptr; 1452 } 1453 1454 QualType ObjCObjectPointerType::getSuperClassType() const { 1455 QualType superObjectType = getObjectType()->getSuperClassType(); 1456 if (superObjectType.isNull()) 1457 return superObjectType; 1458 1459 ASTContext &ctx = getInterfaceDecl()->getASTContext(); 1460 return ctx.getObjCObjectPointerType(superObjectType); 1461 } 1462 1463 const ObjCObjectType *Type::getAsObjCQualifiedInterfaceType() const { 1464 // There is no sugar for ObjCObjectType's, just return the canonical 1465 // type pointer if it is the right class. There is no typedef information to 1466 // return and these cannot be Address-space qualified. 1467 if (const ObjCObjectType *T = getAs<ObjCObjectType>()) 1468 if (T->getNumProtocols() && T->getInterface()) 1469 return T; 1470 return nullptr; 1471 } 1472 1473 bool Type::isObjCQualifiedInterfaceType() const { 1474 return getAsObjCQualifiedInterfaceType() != nullptr; 1475 } 1476 1477 const ObjCObjectPointerType *Type::getAsObjCQualifiedIdType() const { 1478 // There is no sugar for ObjCQualifiedIdType's, just return the canonical 1479 // type pointer if it is the right class. 1480 if (const ObjCObjectPointerType *OPT = getAs<ObjCObjectPointerType>()) { 1481 if (OPT->isObjCQualifiedIdType()) 1482 return OPT; 1483 } 1484 return nullptr; 1485 } 1486 1487 const ObjCObjectPointerType *Type::getAsObjCQualifiedClassType() const { 1488 // There is no sugar for ObjCQualifiedClassType's, just return the canonical 1489 // type pointer if it is the right class. 1490 if (const ObjCObjectPointerType *OPT = getAs<ObjCObjectPointerType>()) { 1491 if (OPT->isObjCQualifiedClassType()) 1492 return OPT; 1493 } 1494 return nullptr; 1495 } 1496 1497 const ObjCObjectType *Type::getAsObjCInterfaceType() const { 1498 if (const ObjCObjectType *OT = getAs<ObjCObjectType>()) { 1499 if (OT->getInterface()) 1500 return OT; 1501 } 1502 return nullptr; 1503 } 1504 const ObjCObjectPointerType *Type::getAsObjCInterfacePointerType() const { 1505 if (const ObjCObjectPointerType *OPT = getAs<ObjCObjectPointerType>()) { 1506 if (OPT->getInterfaceType()) 1507 return OPT; 1508 } 1509 return nullptr; 1510 } 1511 1512 const CXXRecordDecl *Type::getPointeeCXXRecordDecl() const { 1513 QualType PointeeType; 1514 if (const PointerType *PT = getAs<PointerType>()) 1515 PointeeType = PT->getPointeeType(); 1516 else if (const ReferenceType *RT = getAs<ReferenceType>()) 1517 PointeeType = RT->getPointeeType(); 1518 else 1519 return nullptr; 1520 1521 if (const RecordType *RT = PointeeType->getAs<RecordType>()) 1522 return dyn_cast<CXXRecordDecl>(RT->getDecl()); 1523 1524 return nullptr; 1525 } 1526 1527 CXXRecordDecl *Type::getAsCXXRecordDecl() const { 1528 return dyn_cast_or_null<CXXRecordDecl>(getAsTagDecl()); 1529 } 1530 1531 TagDecl *Type::getAsTagDecl() const { 1532 if (const auto *TT = getAs<TagType>()) 1533 return cast<TagDecl>(TT->getDecl()); 1534 if (const auto *Injected = getAs<InjectedClassNameType>()) 1535 return Injected->getDecl(); 1536 1537 return nullptr; 1538 } 1539 1540 namespace { 1541 class GetContainedAutoVisitor : 1542 public TypeVisitor<GetContainedAutoVisitor, AutoType*> { 1543 public: 1544 using TypeVisitor<GetContainedAutoVisitor, AutoType*>::Visit; 1545 AutoType *Visit(QualType T) { 1546 if (T.isNull()) 1547 return nullptr; 1548 return Visit(T.getTypePtr()); 1549 } 1550 1551 // The 'auto' type itself. 1552 AutoType *VisitAutoType(const AutoType *AT) { 1553 return const_cast<AutoType*>(AT); 1554 } 1555 1556 // Only these types can contain the desired 'auto' type. 1557 AutoType *VisitPointerType(const PointerType *T) { 1558 return Visit(T->getPointeeType()); 1559 } 1560 AutoType *VisitBlockPointerType(const BlockPointerType *T) { 1561 return Visit(T->getPointeeType()); 1562 } 1563 AutoType *VisitReferenceType(const ReferenceType *T) { 1564 return Visit(T->getPointeeTypeAsWritten()); 1565 } 1566 AutoType *VisitMemberPointerType(const MemberPointerType *T) { 1567 return Visit(T->getPointeeType()); 1568 } 1569 AutoType *VisitArrayType(const ArrayType *T) { 1570 return Visit(T->getElementType()); 1571 } 1572 AutoType *VisitDependentSizedExtVectorType( 1573 const DependentSizedExtVectorType *T) { 1574 return Visit(T->getElementType()); 1575 } 1576 AutoType *VisitVectorType(const VectorType *T) { 1577 return Visit(T->getElementType()); 1578 } 1579 AutoType *VisitFunctionType(const FunctionType *T) { 1580 return Visit(T->getReturnType()); 1581 } 1582 AutoType *VisitParenType(const ParenType *T) { 1583 return Visit(T->getInnerType()); 1584 } 1585 AutoType *VisitAttributedType(const AttributedType *T) { 1586 return Visit(T->getModifiedType()); 1587 } 1588 AutoType *VisitAdjustedType(const AdjustedType *T) { 1589 return Visit(T->getOriginalType()); 1590 } 1591 }; 1592 } 1593 1594 AutoType *Type::getContainedAutoType() const { 1595 return GetContainedAutoVisitor().Visit(this); 1596 } 1597 1598 bool Type::hasIntegerRepresentation() const { 1599 if (const VectorType *VT = dyn_cast<VectorType>(CanonicalType)) 1600 return VT->getElementType()->isIntegerType(); 1601 else 1602 return isIntegerType(); 1603 } 1604 1605 /// \brief Determine whether this type is an integral type. 1606 /// 1607 /// This routine determines whether the given type is an integral type per 1608 /// C++ [basic.fundamental]p7. Although the C standard does not define the 1609 /// term "integral type", it has a similar term "integer type", and in C++ 1610 /// the two terms are equivalent. However, C's "integer type" includes 1611 /// enumeration types, while C++'s "integer type" does not. The \c ASTContext 1612 /// parameter is used to determine whether we should be following the C or 1613 /// C++ rules when determining whether this type is an integral/integer type. 1614 /// 1615 /// For cases where C permits "an integer type" and C++ permits "an integral 1616 /// type", use this routine. 1617 /// 1618 /// For cases where C permits "an integer type" and C++ permits "an integral 1619 /// or enumeration type", use \c isIntegralOrEnumerationType() instead. 1620 /// 1621 /// \param Ctx The context in which this type occurs. 1622 /// 1623 /// \returns true if the type is considered an integral type, false otherwise. 1624 bool Type::isIntegralType(const ASTContext &Ctx) const { 1625 if (const BuiltinType *BT = dyn_cast<BuiltinType>(CanonicalType)) 1626 return BT->getKind() >= BuiltinType::Bool && 1627 BT->getKind() <= BuiltinType::Int128; 1628 1629 // Complete enum types are integral in C. 1630 if (!Ctx.getLangOpts().CPlusPlus) 1631 if (const EnumType *ET = dyn_cast<EnumType>(CanonicalType)) 1632 return ET->getDecl()->isComplete(); 1633 1634 return false; 1635 } 1636 1637 1638 bool Type::isIntegralOrUnscopedEnumerationType() const { 1639 if (const BuiltinType *BT = dyn_cast<BuiltinType>(CanonicalType)) 1640 return BT->getKind() >= BuiltinType::Bool && 1641 BT->getKind() <= BuiltinType::Int128; 1642 1643 // Check for a complete enum type; incomplete enum types are not properly an 1644 // enumeration type in the sense required here. 1645 // C++0x: However, if the underlying type of the enum is fixed, it is 1646 // considered complete. 1647 if (const EnumType *ET = dyn_cast<EnumType>(CanonicalType)) 1648 return ET->getDecl()->isComplete() && !ET->getDecl()->isScoped(); 1649 1650 return false; 1651 } 1652 1653 1654 1655 bool Type::isCharType() const { 1656 if (const BuiltinType *BT = dyn_cast<BuiltinType>(CanonicalType)) 1657 return BT->getKind() == BuiltinType::Char_U || 1658 BT->getKind() == BuiltinType::UChar || 1659 BT->getKind() == BuiltinType::Char_S || 1660 BT->getKind() == BuiltinType::SChar; 1661 return false; 1662 } 1663 1664 bool Type::isWideCharType() const { 1665 if (const BuiltinType *BT = dyn_cast<BuiltinType>(CanonicalType)) 1666 return BT->getKind() == BuiltinType::WChar_S || 1667 BT->getKind() == BuiltinType::WChar_U; 1668 return false; 1669 } 1670 1671 bool Type::isChar16Type() const { 1672 if (const BuiltinType *BT = dyn_cast<BuiltinType>(CanonicalType)) 1673 return BT->getKind() == BuiltinType::Char16; 1674 return false; 1675 } 1676 1677 bool Type::isChar32Type() const { 1678 if (const BuiltinType *BT = dyn_cast<BuiltinType>(CanonicalType)) 1679 return BT->getKind() == BuiltinType::Char32; 1680 return false; 1681 } 1682 1683 /// \brief Determine whether this type is any of the built-in character 1684 /// types. 1685 bool Type::isAnyCharacterType() const { 1686 const BuiltinType *BT = dyn_cast<BuiltinType>(CanonicalType); 1687 if (!BT) return false; 1688 switch (BT->getKind()) { 1689 default: return false; 1690 case BuiltinType::Char_U: 1691 case BuiltinType::UChar: 1692 case BuiltinType::WChar_U: 1693 case BuiltinType::Char16: 1694 case BuiltinType::Char32: 1695 case BuiltinType::Char_S: 1696 case BuiltinType::SChar: 1697 case BuiltinType::WChar_S: 1698 return true; 1699 } 1700 } 1701 1702 /// isSignedIntegerType - Return true if this is an integer type that is 1703 /// signed, according to C99 6.2.5p4 [char, signed char, short, int, long..], 1704 /// an enum decl which has a signed representation 1705 bool Type::isSignedIntegerType() const { 1706 if (const BuiltinType *BT = dyn_cast<BuiltinType>(CanonicalType)) { 1707 return BT->getKind() >= BuiltinType::Char_S && 1708 BT->getKind() <= BuiltinType::Int128; 1709 } 1710 1711 if (const EnumType *ET = dyn_cast<EnumType>(CanonicalType)) { 1712 // Incomplete enum types are not treated as integer types. 1713 // FIXME: In C++, enum types are never integer types. 1714 if (ET->getDecl()->isComplete() && !ET->getDecl()->isScoped()) 1715 return ET->getDecl()->getIntegerType()->isSignedIntegerType(); 1716 } 1717 1718 return false; 1719 } 1720 1721 bool Type::isSignedIntegerOrEnumerationType() const { 1722 if (const BuiltinType *BT = dyn_cast<BuiltinType>(CanonicalType)) { 1723 return BT->getKind() >= BuiltinType::Char_S && 1724 BT->getKind() <= BuiltinType::Int128; 1725 } 1726 1727 if (const EnumType *ET = dyn_cast<EnumType>(CanonicalType)) { 1728 if (ET->getDecl()->isComplete()) 1729 return ET->getDecl()->getIntegerType()->isSignedIntegerType(); 1730 } 1731 1732 return false; 1733 } 1734 1735 bool Type::hasSignedIntegerRepresentation() const { 1736 if (const VectorType *VT = dyn_cast<VectorType>(CanonicalType)) 1737 return VT->getElementType()->isSignedIntegerOrEnumerationType(); 1738 else 1739 return isSignedIntegerOrEnumerationType(); 1740 } 1741 1742 /// isUnsignedIntegerType - Return true if this is an integer type that is 1743 /// unsigned, according to C99 6.2.5p6 [which returns true for _Bool], an enum 1744 /// decl which has an unsigned representation 1745 bool Type::isUnsignedIntegerType() const { 1746 if (const BuiltinType *BT = dyn_cast<BuiltinType>(CanonicalType)) { 1747 return BT->getKind() >= BuiltinType::Bool && 1748 BT->getKind() <= BuiltinType::UInt128; 1749 } 1750 1751 if (const EnumType *ET = dyn_cast<EnumType>(CanonicalType)) { 1752 // Incomplete enum types are not treated as integer types. 1753 // FIXME: In C++, enum types are never integer types. 1754 if (ET->getDecl()->isComplete() && !ET->getDecl()->isScoped()) 1755 return ET->getDecl()->getIntegerType()->isUnsignedIntegerType(); 1756 } 1757 1758 return false; 1759 } 1760 1761 bool Type::isUnsignedIntegerOrEnumerationType() const { 1762 if (const BuiltinType *BT = dyn_cast<BuiltinType>(CanonicalType)) { 1763 return BT->getKind() >= BuiltinType::Bool && 1764 BT->getKind() <= BuiltinType::UInt128; 1765 } 1766 1767 if (const EnumType *ET = dyn_cast<EnumType>(CanonicalType)) { 1768 if (ET->getDecl()->isComplete()) 1769 return ET->getDecl()->getIntegerType()->isUnsignedIntegerType(); 1770 } 1771 1772 return false; 1773 } 1774 1775 bool Type::hasUnsignedIntegerRepresentation() const { 1776 if (const VectorType *VT = dyn_cast<VectorType>(CanonicalType)) 1777 return VT->getElementType()->isUnsignedIntegerOrEnumerationType(); 1778 else 1779 return isUnsignedIntegerOrEnumerationType(); 1780 } 1781 1782 bool Type::isFloatingType() const { 1783 if (const BuiltinType *BT = dyn_cast<BuiltinType>(CanonicalType)) 1784 return BT->getKind() >= BuiltinType::Half && 1785 BT->getKind() <= BuiltinType::Float128; 1786 if (const ComplexType *CT = dyn_cast<ComplexType>(CanonicalType)) 1787 return CT->getElementType()->isFloatingType(); 1788 return false; 1789 } 1790 1791 bool Type::hasFloatingRepresentation() const { 1792 if (const VectorType *VT = dyn_cast<VectorType>(CanonicalType)) 1793 return VT->getElementType()->isFloatingType(); 1794 else 1795 return isFloatingType(); 1796 } 1797 1798 bool Type::isRealFloatingType() const { 1799 if (const BuiltinType *BT = dyn_cast<BuiltinType>(CanonicalType)) 1800 return BT->isFloatingPoint(); 1801 return false; 1802 } 1803 1804 bool Type::isRealType() const { 1805 if (const BuiltinType *BT = dyn_cast<BuiltinType>(CanonicalType)) 1806 return BT->getKind() >= BuiltinType::Bool && 1807 BT->getKind() <= BuiltinType::Float128; 1808 if (const EnumType *ET = dyn_cast<EnumType>(CanonicalType)) 1809 return ET->getDecl()->isComplete() && !ET->getDecl()->isScoped(); 1810 return false; 1811 } 1812 1813 bool Type::isArithmeticType() const { 1814 if (const BuiltinType *BT = dyn_cast<BuiltinType>(CanonicalType)) 1815 return BT->getKind() >= BuiltinType::Bool && 1816 BT->getKind() <= BuiltinType::Float128; 1817 if (const EnumType *ET = dyn_cast<EnumType>(CanonicalType)) 1818 // GCC allows forward declaration of enum types (forbid by C99 6.7.2.3p2). 1819 // If a body isn't seen by the time we get here, return false. 1820 // 1821 // C++0x: Enumerations are not arithmetic types. For now, just return 1822 // false for scoped enumerations since that will disable any 1823 // unwanted implicit conversions. 1824 return !ET->getDecl()->isScoped() && ET->getDecl()->isComplete(); 1825 return isa<ComplexType>(CanonicalType); 1826 } 1827 1828 Type::ScalarTypeKind Type::getScalarTypeKind() const { 1829 assert(isScalarType()); 1830 1831 const Type *T = CanonicalType.getTypePtr(); 1832 if (const BuiltinType *BT = dyn_cast<BuiltinType>(T)) { 1833 if (BT->getKind() == BuiltinType::Bool) return STK_Bool; 1834 if (BT->getKind() == BuiltinType::NullPtr) return STK_CPointer; 1835 if (BT->isInteger()) return STK_Integral; 1836 if (BT->isFloatingPoint()) return STK_Floating; 1837 llvm_unreachable("unknown scalar builtin type"); 1838 } else if (isa<PointerType>(T)) { 1839 return STK_CPointer; 1840 } else if (isa<BlockPointerType>(T)) { 1841 return STK_BlockPointer; 1842 } else if (isa<ObjCObjectPointerType>(T)) { 1843 return STK_ObjCObjectPointer; 1844 } else if (isa<MemberPointerType>(T)) { 1845 return STK_MemberPointer; 1846 } else if (isa<EnumType>(T)) { 1847 assert(cast<EnumType>(T)->getDecl()->isComplete()); 1848 return STK_Integral; 1849 } else if (const ComplexType *CT = dyn_cast<ComplexType>(T)) { 1850 if (CT->getElementType()->isRealFloatingType()) 1851 return STK_FloatingComplex; 1852 return STK_IntegralComplex; 1853 } 1854 1855 llvm_unreachable("unknown scalar type"); 1856 } 1857 1858 /// \brief Determines whether the type is a C++ aggregate type or C 1859 /// aggregate or union type. 1860 /// 1861 /// An aggregate type is an array or a class type (struct, union, or 1862 /// class) that has no user-declared constructors, no private or 1863 /// protected non-static data members, no base classes, and no virtual 1864 /// functions (C++ [dcl.init.aggr]p1). The notion of an aggregate type 1865 /// subsumes the notion of C aggregates (C99 6.2.5p21) because it also 1866 /// includes union types. 1867 bool Type::isAggregateType() const { 1868 if (const RecordType *Record = dyn_cast<RecordType>(CanonicalType)) { 1869 if (CXXRecordDecl *ClassDecl = dyn_cast<CXXRecordDecl>(Record->getDecl())) 1870 return ClassDecl->isAggregate(); 1871 1872 return true; 1873 } 1874 1875 return isa<ArrayType>(CanonicalType); 1876 } 1877 1878 /// isConstantSizeType - Return true if this is not a variable sized type, 1879 /// according to the rules of C99 6.7.5p3. It is not legal to call this on 1880 /// incomplete types or dependent types. 1881 bool Type::isConstantSizeType() const { 1882 assert(!isIncompleteType() && "This doesn't make sense for incomplete types"); 1883 assert(!isDependentType() && "This doesn't make sense for dependent types"); 1884 // The VAT must have a size, as it is known to be complete. 1885 return !isa<VariableArrayType>(CanonicalType); 1886 } 1887 1888 /// isIncompleteType - Return true if this is an incomplete type (C99 6.2.5p1) 1889 /// - a type that can describe objects, but which lacks information needed to 1890 /// determine its size. 1891 bool Type::isIncompleteType(NamedDecl **Def) const { 1892 if (Def) 1893 *Def = nullptr; 1894 1895 switch (CanonicalType->getTypeClass()) { 1896 default: return false; 1897 case Builtin: 1898 // Void is the only incomplete builtin type. Per C99 6.2.5p19, it can never 1899 // be completed. 1900 return isVoidType(); 1901 case Enum: { 1902 EnumDecl *EnumD = cast<EnumType>(CanonicalType)->getDecl(); 1903 if (Def) 1904 *Def = EnumD; 1905 1906 // An enumeration with fixed underlying type is complete (C++0x 7.2p3). 1907 if (EnumD->isFixed()) 1908 return false; 1909 1910 return !EnumD->isCompleteDefinition(); 1911 } 1912 case Record: { 1913 // A tagged type (struct/union/enum/class) is incomplete if the decl is a 1914 // forward declaration, but not a full definition (C99 6.2.5p22). 1915 RecordDecl *Rec = cast<RecordType>(CanonicalType)->getDecl(); 1916 if (Def) 1917 *Def = Rec; 1918 return !Rec->isCompleteDefinition(); 1919 } 1920 case ConstantArray: 1921 // An array is incomplete if its element type is incomplete 1922 // (C++ [dcl.array]p1). 1923 // We don't handle variable arrays (they're not allowed in C++) or 1924 // dependent-sized arrays (dependent types are never treated as incomplete). 1925 return cast<ArrayType>(CanonicalType)->getElementType() 1926 ->isIncompleteType(Def); 1927 case IncompleteArray: 1928 // An array of unknown size is an incomplete type (C99 6.2.5p22). 1929 return true; 1930 case MemberPointer: { 1931 // Member pointers in the MS ABI have special behavior in 1932 // RequireCompleteType: they attach a MSInheritanceAttr to the CXXRecordDecl 1933 // to indicate which inheritance model to use. 1934 auto *MPTy = cast<MemberPointerType>(CanonicalType); 1935 const Type *ClassTy = MPTy->getClass(); 1936 // Member pointers with dependent class types don't get special treatment. 1937 if (ClassTy->isDependentType()) 1938 return false; 1939 const CXXRecordDecl *RD = ClassTy->getAsCXXRecordDecl(); 1940 ASTContext &Context = RD->getASTContext(); 1941 // Member pointers not in the MS ABI don't get special treatment. 1942 if (!Context.getTargetInfo().getCXXABI().isMicrosoft()) 1943 return false; 1944 // The inheritance attribute might only be present on the most recent 1945 // CXXRecordDecl, use that one. 1946 RD = RD->getMostRecentDecl(); 1947 // Nothing interesting to do if the inheritance attribute is already set. 1948 if (RD->hasAttr<MSInheritanceAttr>()) 1949 return false; 1950 return true; 1951 } 1952 case ObjCObject: 1953 return cast<ObjCObjectType>(CanonicalType)->getBaseType() 1954 ->isIncompleteType(Def); 1955 case ObjCInterface: { 1956 // ObjC interfaces are incomplete if they are @class, not @interface. 1957 ObjCInterfaceDecl *Interface 1958 = cast<ObjCInterfaceType>(CanonicalType)->getDecl(); 1959 if (Def) 1960 *Def = Interface; 1961 return !Interface->hasDefinition(); 1962 } 1963 } 1964 } 1965 1966 bool QualType::isPODType(const ASTContext &Context) const { 1967 // C++11 has a more relaxed definition of POD. 1968 if (Context.getLangOpts().CPlusPlus11) 1969 return isCXX11PODType(Context); 1970 1971 return isCXX98PODType(Context); 1972 } 1973 1974 bool QualType::isCXX98PODType(const ASTContext &Context) const { 1975 // The compiler shouldn't query this for incomplete types, but the user might. 1976 // We return false for that case. Except for incomplete arrays of PODs, which 1977 // are PODs according to the standard. 1978 if (isNull()) 1979 return 0; 1980 1981 if ((*this)->isIncompleteArrayType()) 1982 return Context.getBaseElementType(*this).isCXX98PODType(Context); 1983 1984 if ((*this)->isIncompleteType()) 1985 return false; 1986 1987 if (Context.getLangOpts().ObjCAutoRefCount) { 1988 switch (getObjCLifetime()) { 1989 case Qualifiers::OCL_ExplicitNone: 1990 return true; 1991 1992 case Qualifiers::OCL_Strong: 1993 case Qualifiers::OCL_Weak: 1994 case Qualifiers::OCL_Autoreleasing: 1995 return false; 1996 1997 case Qualifiers::OCL_None: 1998 break; 1999 } 2000 } 2001 2002 QualType CanonicalType = getTypePtr()->CanonicalType; 2003 switch (CanonicalType->getTypeClass()) { 2004 // Everything not explicitly mentioned is not POD. 2005 default: return false; 2006 case Type::VariableArray: 2007 case Type::ConstantArray: 2008 // IncompleteArray is handled above. 2009 return Context.getBaseElementType(*this).isCXX98PODType(Context); 2010 2011 case Type::ObjCObjectPointer: 2012 case Type::BlockPointer: 2013 case Type::Builtin: 2014 case Type::Complex: 2015 case Type::Pointer: 2016 case Type::MemberPointer: 2017 case Type::Vector: 2018 case Type::ExtVector: 2019 return true; 2020 2021 case Type::Enum: 2022 return true; 2023 2024 case Type::Record: 2025 if (CXXRecordDecl *ClassDecl 2026 = dyn_cast<CXXRecordDecl>(cast<RecordType>(CanonicalType)->getDecl())) 2027 return ClassDecl->isPOD(); 2028 2029 // C struct/union is POD. 2030 return true; 2031 } 2032 } 2033 2034 bool QualType::isTrivialType(const ASTContext &Context) const { 2035 // The compiler shouldn't query this for incomplete types, but the user might. 2036 // We return false for that case. Except for incomplete arrays of PODs, which 2037 // are PODs according to the standard. 2038 if (isNull()) 2039 return 0; 2040 2041 if ((*this)->isArrayType()) 2042 return Context.getBaseElementType(*this).isTrivialType(Context); 2043 2044 // Return false for incomplete types after skipping any incomplete array 2045 // types which are expressly allowed by the standard and thus our API. 2046 if ((*this)->isIncompleteType()) 2047 return false; 2048 2049 if (Context.getLangOpts().ObjCAutoRefCount) { 2050 switch (getObjCLifetime()) { 2051 case Qualifiers::OCL_ExplicitNone: 2052 return true; 2053 2054 case Qualifiers::OCL_Strong: 2055 case Qualifiers::OCL_Weak: 2056 case Qualifiers::OCL_Autoreleasing: 2057 return false; 2058 2059 case Qualifiers::OCL_None: 2060 if ((*this)->isObjCLifetimeType()) 2061 return false; 2062 break; 2063 } 2064 } 2065 2066 QualType CanonicalType = getTypePtr()->CanonicalType; 2067 if (CanonicalType->isDependentType()) 2068 return false; 2069 2070 // C++0x [basic.types]p9: 2071 // Scalar types, trivial class types, arrays of such types, and 2072 // cv-qualified versions of these types are collectively called trivial 2073 // types. 2074 2075 // As an extension, Clang treats vector types as Scalar types. 2076 if (CanonicalType->isScalarType() || CanonicalType->isVectorType()) 2077 return true; 2078 if (const RecordType *RT = CanonicalType->getAs<RecordType>()) { 2079 if (const CXXRecordDecl *ClassDecl = 2080 dyn_cast<CXXRecordDecl>(RT->getDecl())) { 2081 // C++11 [class]p6: 2082 // A trivial class is a class that has a default constructor, 2083 // has no non-trivial default constructors, and is trivially 2084 // copyable. 2085 return ClassDecl->hasDefaultConstructor() && 2086 !ClassDecl->hasNonTrivialDefaultConstructor() && 2087 ClassDecl->isTriviallyCopyable(); 2088 } 2089 2090 return true; 2091 } 2092 2093 // No other types can match. 2094 return false; 2095 } 2096 2097 bool QualType::isTriviallyCopyableType(const ASTContext &Context) const { 2098 if ((*this)->isArrayType()) 2099 return Context.getBaseElementType(*this).isTriviallyCopyableType(Context); 2100 2101 if (Context.getLangOpts().ObjCAutoRefCount) { 2102 switch (getObjCLifetime()) { 2103 case Qualifiers::OCL_ExplicitNone: 2104 return true; 2105 2106 case Qualifiers::OCL_Strong: 2107 case Qualifiers::OCL_Weak: 2108 case Qualifiers::OCL_Autoreleasing: 2109 return false; 2110 2111 case Qualifiers::OCL_None: 2112 if ((*this)->isObjCLifetimeType()) 2113 return false; 2114 break; 2115 } 2116 } 2117 2118 // C++11 [basic.types]p9 2119 // Scalar types, trivially copyable class types, arrays of such types, and 2120 // non-volatile const-qualified versions of these types are collectively 2121 // called trivially copyable types. 2122 2123 QualType CanonicalType = getCanonicalType(); 2124 if (CanonicalType->isDependentType()) 2125 return false; 2126 2127 if (CanonicalType.isVolatileQualified()) 2128 return false; 2129 2130 // Return false for incomplete types after skipping any incomplete array types 2131 // which are expressly allowed by the standard and thus our API. 2132 if (CanonicalType->isIncompleteType()) 2133 return false; 2134 2135 // As an extension, Clang treats vector types as Scalar types. 2136 if (CanonicalType->isScalarType() || CanonicalType->isVectorType()) 2137 return true; 2138 2139 if (const RecordType *RT = CanonicalType->getAs<RecordType>()) { 2140 if (const CXXRecordDecl *ClassDecl = 2141 dyn_cast<CXXRecordDecl>(RT->getDecl())) { 2142 if (!ClassDecl->isTriviallyCopyable()) return false; 2143 } 2144 2145 return true; 2146 } 2147 2148 // No other types can match. 2149 return false; 2150 } 2151 2152 2153 2154 bool Type::isLiteralType(const ASTContext &Ctx) const { 2155 if (isDependentType()) 2156 return false; 2157 2158 // C++1y [basic.types]p10: 2159 // A type is a literal type if it is: 2160 // -- cv void; or 2161 if (Ctx.getLangOpts().CPlusPlus14 && isVoidType()) 2162 return true; 2163 2164 // C++11 [basic.types]p10: 2165 // A type is a literal type if it is: 2166 // [...] 2167 // -- an array of literal type other than an array of runtime bound; or 2168 if (isVariableArrayType()) 2169 return false; 2170 const Type *BaseTy = getBaseElementTypeUnsafe(); 2171 assert(BaseTy && "NULL element type"); 2172 2173 // Return false for incomplete types after skipping any incomplete array 2174 // types; those are expressly allowed by the standard and thus our API. 2175 if (BaseTy->isIncompleteType()) 2176 return false; 2177 2178 // C++11 [basic.types]p10: 2179 // A type is a literal type if it is: 2180 // -- a scalar type; or 2181 // As an extension, Clang treats vector types and complex types as 2182 // literal types. 2183 if (BaseTy->isScalarType() || BaseTy->isVectorType() || 2184 BaseTy->isAnyComplexType()) 2185 return true; 2186 // -- a reference type; or 2187 if (BaseTy->isReferenceType()) 2188 return true; 2189 // -- a class type that has all of the following properties: 2190 if (const RecordType *RT = BaseTy->getAs<RecordType>()) { 2191 // -- a trivial destructor, 2192 // -- every constructor call and full-expression in the 2193 // brace-or-equal-initializers for non-static data members (if any) 2194 // is a constant expression, 2195 // -- it is an aggregate type or has at least one constexpr 2196 // constructor or constructor template that is not a copy or move 2197 // constructor, and 2198 // -- all non-static data members and base classes of literal types 2199 // 2200 // We resolve DR1361 by ignoring the second bullet. 2201 if (const CXXRecordDecl *ClassDecl = 2202 dyn_cast<CXXRecordDecl>(RT->getDecl())) 2203 return ClassDecl->isLiteral(); 2204 2205 return true; 2206 } 2207 2208 // We treat _Atomic T as a literal type if T is a literal type. 2209 if (const AtomicType *AT = BaseTy->getAs<AtomicType>()) 2210 return AT->getValueType()->isLiteralType(Ctx); 2211 2212 // If this type hasn't been deduced yet, then conservatively assume that 2213 // it'll work out to be a literal type. 2214 if (isa<AutoType>(BaseTy->getCanonicalTypeInternal())) 2215 return true; 2216 2217 return false; 2218 } 2219 2220 bool Type::isStandardLayoutType() const { 2221 if (isDependentType()) 2222 return false; 2223 2224 // C++0x [basic.types]p9: 2225 // Scalar types, standard-layout class types, arrays of such types, and 2226 // cv-qualified versions of these types are collectively called 2227 // standard-layout types. 2228 const Type *BaseTy = getBaseElementTypeUnsafe(); 2229 assert(BaseTy && "NULL element type"); 2230 2231 // Return false for incomplete types after skipping any incomplete array 2232 // types which are expressly allowed by the standard and thus our API. 2233 if (BaseTy->isIncompleteType()) 2234 return false; 2235 2236 // As an extension, Clang treats vector types as Scalar types. 2237 if (BaseTy->isScalarType() || BaseTy->isVectorType()) return true; 2238 if (const RecordType *RT = BaseTy->getAs<RecordType>()) { 2239 if (const CXXRecordDecl *ClassDecl = 2240 dyn_cast<CXXRecordDecl>(RT->getDecl())) 2241 if (!ClassDecl->isStandardLayout()) 2242 return false; 2243 2244 // Default to 'true' for non-C++ class types. 2245 // FIXME: This is a bit dubious, but plain C structs should trivially meet 2246 // all the requirements of standard layout classes. 2247 return true; 2248 } 2249 2250 // No other types can match. 2251 return false; 2252 } 2253 2254 // This is effectively the intersection of isTrivialType and 2255 // isStandardLayoutType. We implement it directly to avoid redundant 2256 // conversions from a type to a CXXRecordDecl. 2257 bool QualType::isCXX11PODType(const ASTContext &Context) const { 2258 const Type *ty = getTypePtr(); 2259 if (ty->isDependentType()) 2260 return false; 2261 2262 if (Context.getLangOpts().ObjCAutoRefCount) { 2263 switch (getObjCLifetime()) { 2264 case Qualifiers::OCL_ExplicitNone: 2265 return true; 2266 2267 case Qualifiers::OCL_Strong: 2268 case Qualifiers::OCL_Weak: 2269 case Qualifiers::OCL_Autoreleasing: 2270 return false; 2271 2272 case Qualifiers::OCL_None: 2273 break; 2274 } 2275 } 2276 2277 // C++11 [basic.types]p9: 2278 // Scalar types, POD classes, arrays of such types, and cv-qualified 2279 // versions of these types are collectively called trivial types. 2280 const Type *BaseTy = ty->getBaseElementTypeUnsafe(); 2281 assert(BaseTy && "NULL element type"); 2282 2283 // Return false for incomplete types after skipping any incomplete array 2284 // types which are expressly allowed by the standard and thus our API. 2285 if (BaseTy->isIncompleteType()) 2286 return false; 2287 2288 // As an extension, Clang treats vector types as Scalar types. 2289 if (BaseTy->isScalarType() || BaseTy->isVectorType()) return true; 2290 if (const RecordType *RT = BaseTy->getAs<RecordType>()) { 2291 if (const CXXRecordDecl *ClassDecl = 2292 dyn_cast<CXXRecordDecl>(RT->getDecl())) { 2293 // C++11 [class]p10: 2294 // A POD struct is a non-union class that is both a trivial class [...] 2295 if (!ClassDecl->isTrivial()) return false; 2296 2297 // C++11 [class]p10: 2298 // A POD struct is a non-union class that is both a trivial class and 2299 // a standard-layout class [...] 2300 if (!ClassDecl->isStandardLayout()) return false; 2301 2302 // C++11 [class]p10: 2303 // A POD struct is a non-union class that is both a trivial class and 2304 // a standard-layout class, and has no non-static data members of type 2305 // non-POD struct, non-POD union (or array of such types). [...] 2306 // 2307 // We don't directly query the recursive aspect as the requirements for 2308 // both standard-layout classes and trivial classes apply recursively 2309 // already. 2310 } 2311 2312 return true; 2313 } 2314 2315 // No other types can match. 2316 return false; 2317 } 2318 2319 bool Type::isPromotableIntegerType() const { 2320 if (const BuiltinType *BT = getAs<BuiltinType>()) 2321 switch (BT->getKind()) { 2322 case BuiltinType::Bool: 2323 case BuiltinType::Char_S: 2324 case BuiltinType::Char_U: 2325 case BuiltinType::SChar: 2326 case BuiltinType::UChar: 2327 case BuiltinType::Short: 2328 case BuiltinType::UShort: 2329 case BuiltinType::WChar_S: 2330 case BuiltinType::WChar_U: 2331 case BuiltinType::Char16: 2332 case BuiltinType::Char32: 2333 return true; 2334 default: 2335 return false; 2336 } 2337 2338 // Enumerated types are promotable to their compatible integer types 2339 // (C99 6.3.1.1) a.k.a. its underlying type (C++ [conv.prom]p2). 2340 if (const EnumType *ET = getAs<EnumType>()){ 2341 if (this->isDependentType() || ET->getDecl()->getPromotionType().isNull() 2342 || ET->getDecl()->isScoped()) 2343 return false; 2344 2345 return true; 2346 } 2347 2348 return false; 2349 } 2350 2351 bool Type::isSpecifierType() const { 2352 // Note that this intentionally does not use the canonical type. 2353 switch (getTypeClass()) { 2354 case Builtin: 2355 case Record: 2356 case Enum: 2357 case Typedef: 2358 case Complex: 2359 case TypeOfExpr: 2360 case TypeOf: 2361 case TemplateTypeParm: 2362 case SubstTemplateTypeParm: 2363 case TemplateSpecialization: 2364 case Elaborated: 2365 case DependentName: 2366 case DependentTemplateSpecialization: 2367 case ObjCInterface: 2368 case ObjCObject: 2369 case ObjCObjectPointer: // FIXME: object pointers aren't really specifiers 2370 return true; 2371 default: 2372 return false; 2373 } 2374 } 2375 2376 ElaboratedTypeKeyword 2377 TypeWithKeyword::getKeywordForTypeSpec(unsigned TypeSpec) { 2378 switch (TypeSpec) { 2379 default: return ETK_None; 2380 case TST_typename: return ETK_Typename; 2381 case TST_class: return ETK_Class; 2382 case TST_struct: return ETK_Struct; 2383 case TST_interface: return ETK_Interface; 2384 case TST_union: return ETK_Union; 2385 case TST_enum: return ETK_Enum; 2386 } 2387 } 2388 2389 TagTypeKind 2390 TypeWithKeyword::getTagTypeKindForTypeSpec(unsigned TypeSpec) { 2391 switch(TypeSpec) { 2392 case TST_class: return TTK_Class; 2393 case TST_struct: return TTK_Struct; 2394 case TST_interface: return TTK_Interface; 2395 case TST_union: return TTK_Union; 2396 case TST_enum: return TTK_Enum; 2397 } 2398 2399 llvm_unreachable("Type specifier is not a tag type kind."); 2400 } 2401 2402 ElaboratedTypeKeyword 2403 TypeWithKeyword::getKeywordForTagTypeKind(TagTypeKind Kind) { 2404 switch (Kind) { 2405 case TTK_Class: return ETK_Class; 2406 case TTK_Struct: return ETK_Struct; 2407 case TTK_Interface: return ETK_Interface; 2408 case TTK_Union: return ETK_Union; 2409 case TTK_Enum: return ETK_Enum; 2410 } 2411 llvm_unreachable("Unknown tag type kind."); 2412 } 2413 2414 TagTypeKind 2415 TypeWithKeyword::getTagTypeKindForKeyword(ElaboratedTypeKeyword Keyword) { 2416 switch (Keyword) { 2417 case ETK_Class: return TTK_Class; 2418 case ETK_Struct: return TTK_Struct; 2419 case ETK_Interface: return TTK_Interface; 2420 case ETK_Union: return TTK_Union; 2421 case ETK_Enum: return TTK_Enum; 2422 case ETK_None: // Fall through. 2423 case ETK_Typename: 2424 llvm_unreachable("Elaborated type keyword is not a tag type kind."); 2425 } 2426 llvm_unreachable("Unknown elaborated type keyword."); 2427 } 2428 2429 bool 2430 TypeWithKeyword::KeywordIsTagTypeKind(ElaboratedTypeKeyword Keyword) { 2431 switch (Keyword) { 2432 case ETK_None: 2433 case ETK_Typename: 2434 return false; 2435 case ETK_Class: 2436 case ETK_Struct: 2437 case ETK_Interface: 2438 case ETK_Union: 2439 case ETK_Enum: 2440 return true; 2441 } 2442 llvm_unreachable("Unknown elaborated type keyword."); 2443 } 2444 2445 StringRef TypeWithKeyword::getKeywordName(ElaboratedTypeKeyword Keyword) { 2446 switch (Keyword) { 2447 case ETK_None: return ""; 2448 case ETK_Typename: return "typename"; 2449 case ETK_Class: return "class"; 2450 case ETK_Struct: return "struct"; 2451 case ETK_Interface: return "__interface"; 2452 case ETK_Union: return "union"; 2453 case ETK_Enum: return "enum"; 2454 } 2455 2456 llvm_unreachable("Unknown elaborated type keyword."); 2457 } 2458 2459 DependentTemplateSpecializationType::DependentTemplateSpecializationType( 2460 ElaboratedTypeKeyword Keyword, 2461 NestedNameSpecifier *NNS, const IdentifierInfo *Name, 2462 ArrayRef<TemplateArgument> Args, 2463 QualType Canon) 2464 : TypeWithKeyword(Keyword, DependentTemplateSpecialization, Canon, true, true, 2465 /*VariablyModified=*/false, 2466 NNS && NNS->containsUnexpandedParameterPack()), 2467 NNS(NNS), Name(Name), NumArgs(Args.size()) { 2468 assert((!NNS || NNS->isDependent()) && 2469 "DependentTemplateSpecializatonType requires dependent qualifier"); 2470 TemplateArgument *ArgBuffer = getArgBuffer(); 2471 for (const TemplateArgument &Arg : Args) { 2472 if (Arg.containsUnexpandedParameterPack()) 2473 setContainsUnexpandedParameterPack(); 2474 2475 new (ArgBuffer++) TemplateArgument(Arg); 2476 } 2477 } 2478 2479 void 2480 DependentTemplateSpecializationType::Profile(llvm::FoldingSetNodeID &ID, 2481 const ASTContext &Context, 2482 ElaboratedTypeKeyword Keyword, 2483 NestedNameSpecifier *Qualifier, 2484 const IdentifierInfo *Name, 2485 ArrayRef<TemplateArgument> Args) { 2486 ID.AddInteger(Keyword); 2487 ID.AddPointer(Qualifier); 2488 ID.AddPointer(Name); 2489 for (const TemplateArgument &Arg : Args) 2490 Arg.Profile(ID, Context); 2491 } 2492 2493 bool Type::isElaboratedTypeSpecifier() const { 2494 ElaboratedTypeKeyword Keyword; 2495 if (const ElaboratedType *Elab = dyn_cast<ElaboratedType>(this)) 2496 Keyword = Elab->getKeyword(); 2497 else if (const DependentNameType *DepName = dyn_cast<DependentNameType>(this)) 2498 Keyword = DepName->getKeyword(); 2499 else if (const DependentTemplateSpecializationType *DepTST = 2500 dyn_cast<DependentTemplateSpecializationType>(this)) 2501 Keyword = DepTST->getKeyword(); 2502 else 2503 return false; 2504 2505 return TypeWithKeyword::KeywordIsTagTypeKind(Keyword); 2506 } 2507 2508 const char *Type::getTypeClassName() const { 2509 switch (TypeBits.TC) { 2510 #define ABSTRACT_TYPE(Derived, Base) 2511 #define TYPE(Derived, Base) case Derived: return #Derived; 2512 #include "clang/AST/TypeNodes.def" 2513 } 2514 2515 llvm_unreachable("Invalid type class."); 2516 } 2517 2518 StringRef BuiltinType::getName(const PrintingPolicy &Policy) const { 2519 switch (getKind()) { 2520 case Void: 2521 return "void"; 2522 case Bool: 2523 return Policy.Bool ? "bool" : "_Bool"; 2524 case Char_S: 2525 return "char"; 2526 case Char_U: 2527 return "char"; 2528 case SChar: 2529 return "signed char"; 2530 case Short: 2531 return "short"; 2532 case Int: 2533 return "int"; 2534 case Long: 2535 return "long"; 2536 case LongLong: 2537 return "long long"; 2538 case Int128: 2539 return "__int128"; 2540 case UChar: 2541 return "unsigned char"; 2542 case UShort: 2543 return "unsigned short"; 2544 case UInt: 2545 return "unsigned int"; 2546 case ULong: 2547 return "unsigned long"; 2548 case ULongLong: 2549 return "unsigned long long"; 2550 case UInt128: 2551 return "unsigned __int128"; 2552 case Half: 2553 return Policy.Half ? "half" : "__fp16"; 2554 case Float: 2555 return "float"; 2556 case Double: 2557 return "double"; 2558 case LongDouble: 2559 return "long double"; 2560 case Float128: 2561 return "__float128"; 2562 case WChar_S: 2563 case WChar_U: 2564 return Policy.MSWChar ? "__wchar_t" : "wchar_t"; 2565 case Char16: 2566 return "char16_t"; 2567 case Char32: 2568 return "char32_t"; 2569 case NullPtr: 2570 return "nullptr_t"; 2571 case Overload: 2572 return "<overloaded function type>"; 2573 case BoundMember: 2574 return "<bound member function type>"; 2575 case PseudoObject: 2576 return "<pseudo-object type>"; 2577 case Dependent: 2578 return "<dependent type>"; 2579 case UnknownAny: 2580 return "<unknown type>"; 2581 case ARCUnbridgedCast: 2582 return "<ARC unbridged cast type>"; 2583 case BuiltinFn: 2584 return "<builtin fn type>"; 2585 case ObjCId: 2586 return "id"; 2587 case ObjCClass: 2588 return "Class"; 2589 case ObjCSel: 2590 return "SEL"; 2591 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \ 2592 case Id: \ 2593 return "__" #Access " " #ImgType "_t"; 2594 #include "clang/Basic/OpenCLImageTypes.def" 2595 case OCLSampler: 2596 return "sampler_t"; 2597 case OCLEvent: 2598 return "event_t"; 2599 case OCLClkEvent: 2600 return "clk_event_t"; 2601 case OCLQueue: 2602 return "queue_t"; 2603 case OCLNDRange: 2604 return "ndrange_t"; 2605 case OCLReserveID: 2606 return "reserve_id_t"; 2607 case OMPArraySection: 2608 return "<OpenMP array section type>"; 2609 } 2610 2611 llvm_unreachable("Invalid builtin type."); 2612 } 2613 2614 QualType QualType::getNonLValueExprType(const ASTContext &Context) const { 2615 if (const ReferenceType *RefType = getTypePtr()->getAs<ReferenceType>()) 2616 return RefType->getPointeeType(); 2617 2618 // C++0x [basic.lval]: 2619 // Class prvalues can have cv-qualified types; non-class prvalues always 2620 // have cv-unqualified types. 2621 // 2622 // See also C99 6.3.2.1p2. 2623 if (!Context.getLangOpts().CPlusPlus || 2624 (!getTypePtr()->isDependentType() && !getTypePtr()->isRecordType())) 2625 return getUnqualifiedType(); 2626 2627 return *this; 2628 } 2629 2630 StringRef FunctionType::getNameForCallConv(CallingConv CC) { 2631 switch (CC) { 2632 case CC_C: return "cdecl"; 2633 case CC_X86StdCall: return "stdcall"; 2634 case CC_X86FastCall: return "fastcall"; 2635 case CC_X86ThisCall: return "thiscall"; 2636 case CC_X86Pascal: return "pascal"; 2637 case CC_X86VectorCall: return "vectorcall"; 2638 case CC_X86_64Win64: return "ms_abi"; 2639 case CC_X86_64SysV: return "sysv_abi"; 2640 case CC_AAPCS: return "aapcs"; 2641 case CC_AAPCS_VFP: return "aapcs-vfp"; 2642 case CC_IntelOclBicc: return "intel_ocl_bicc"; 2643 case CC_SpirFunction: return "spir_function"; 2644 case CC_OpenCLKernel: return "opencl_kernel"; 2645 case CC_Swift: return "swiftcall"; 2646 case CC_PreserveMost: return "preserve_most"; 2647 case CC_PreserveAll: return "preserve_all"; 2648 } 2649 2650 llvm_unreachable("Invalid calling convention."); 2651 } 2652 2653 FunctionProtoType::FunctionProtoType(QualType result, ArrayRef<QualType> params, 2654 QualType canonical, 2655 const ExtProtoInfo &epi) 2656 : FunctionType(FunctionProto, result, canonical, 2657 result->isDependentType(), 2658 result->isInstantiationDependentType(), 2659 result->isVariablyModifiedType(), 2660 result->containsUnexpandedParameterPack(), epi.ExtInfo), 2661 NumParams(params.size()), 2662 NumExceptions(epi.ExceptionSpec.Exceptions.size()), 2663 ExceptionSpecType(epi.ExceptionSpec.Type), 2664 HasExtParameterInfos(epi.ExtParameterInfos != nullptr), 2665 Variadic(epi.Variadic), HasTrailingReturn(epi.HasTrailingReturn) { 2666 assert(NumParams == params.size() && "function has too many parameters"); 2667 2668 FunctionTypeBits.TypeQuals = epi.TypeQuals; 2669 FunctionTypeBits.RefQualifier = epi.RefQualifier; 2670 2671 // Fill in the trailing argument array. 2672 QualType *argSlot = reinterpret_cast<QualType*>(this+1); 2673 for (unsigned i = 0; i != NumParams; ++i) { 2674 if (params[i]->isDependentType()) 2675 setDependent(); 2676 else if (params[i]->isInstantiationDependentType()) 2677 setInstantiationDependent(); 2678 2679 if (params[i]->containsUnexpandedParameterPack()) 2680 setContainsUnexpandedParameterPack(); 2681 2682 argSlot[i] = params[i]; 2683 } 2684 2685 if (getExceptionSpecType() == EST_Dynamic) { 2686 // Fill in the exception array. 2687 QualType *exnSlot = argSlot + NumParams; 2688 unsigned I = 0; 2689 for (QualType ExceptionType : epi.ExceptionSpec.Exceptions) { 2690 // Note that a dependent exception specification does *not* make 2691 // a type dependent; it's not even part of the C++ type system. 2692 if (ExceptionType->isInstantiationDependentType()) 2693 setInstantiationDependent(); 2694 2695 if (ExceptionType->containsUnexpandedParameterPack()) 2696 setContainsUnexpandedParameterPack(); 2697 2698 exnSlot[I++] = ExceptionType; 2699 } 2700 } else if (getExceptionSpecType() == EST_ComputedNoexcept) { 2701 // Store the noexcept expression and context. 2702 Expr **noexSlot = reinterpret_cast<Expr **>(argSlot + NumParams); 2703 *noexSlot = epi.ExceptionSpec.NoexceptExpr; 2704 2705 if (epi.ExceptionSpec.NoexceptExpr) { 2706 if (epi.ExceptionSpec.NoexceptExpr->isValueDependent() || 2707 epi.ExceptionSpec.NoexceptExpr->isInstantiationDependent()) 2708 setInstantiationDependent(); 2709 2710 if (epi.ExceptionSpec.NoexceptExpr->containsUnexpandedParameterPack()) 2711 setContainsUnexpandedParameterPack(); 2712 } 2713 } else if (getExceptionSpecType() == EST_Uninstantiated) { 2714 // Store the function decl from which we will resolve our 2715 // exception specification. 2716 FunctionDecl **slot = 2717 reinterpret_cast<FunctionDecl **>(argSlot + NumParams); 2718 slot[0] = epi.ExceptionSpec.SourceDecl; 2719 slot[1] = epi.ExceptionSpec.SourceTemplate; 2720 // This exception specification doesn't make the type dependent, because 2721 // it's not instantiated as part of instantiating the type. 2722 } else if (getExceptionSpecType() == EST_Unevaluated) { 2723 // Store the function decl from which we will resolve our 2724 // exception specification. 2725 FunctionDecl **slot = 2726 reinterpret_cast<FunctionDecl **>(argSlot + NumParams); 2727 slot[0] = epi.ExceptionSpec.SourceDecl; 2728 } 2729 2730 if (epi.ExtParameterInfos) { 2731 ExtParameterInfo *extParamInfos = 2732 const_cast<ExtParameterInfo *>(getExtParameterInfosBuffer()); 2733 for (unsigned i = 0; i != NumParams; ++i) 2734 extParamInfos[i] = epi.ExtParameterInfos[i]; 2735 } 2736 } 2737 2738 bool FunctionProtoType::hasDependentExceptionSpec() const { 2739 if (Expr *NE = getNoexceptExpr()) 2740 return NE->isValueDependent(); 2741 for (QualType ET : exceptions()) 2742 // A pack expansion with a non-dependent pattern is still dependent, 2743 // because we don't know whether the pattern is in the exception spec 2744 // or not (that depends on whether the pack has 0 expansions). 2745 if (ET->isDependentType() || ET->getAs<PackExpansionType>()) 2746 return true; 2747 return false; 2748 } 2749 2750 FunctionProtoType::NoexceptResult 2751 FunctionProtoType::getNoexceptSpec(const ASTContext &ctx) const { 2752 ExceptionSpecificationType est = getExceptionSpecType(); 2753 if (est == EST_BasicNoexcept) 2754 return NR_Nothrow; 2755 2756 if (est != EST_ComputedNoexcept) 2757 return NR_NoNoexcept; 2758 2759 Expr *noexceptExpr = getNoexceptExpr(); 2760 if (!noexceptExpr) 2761 return NR_BadNoexcept; 2762 if (noexceptExpr->isValueDependent()) 2763 return NR_Dependent; 2764 2765 llvm::APSInt value; 2766 bool isICE = noexceptExpr->isIntegerConstantExpr(value, ctx, nullptr, 2767 /*evaluated*/false); 2768 (void)isICE; 2769 assert(isICE && "AST should not contain bad noexcept expressions."); 2770 2771 return value.getBoolValue() ? NR_Nothrow : NR_Throw; 2772 } 2773 2774 bool FunctionProtoType::isNothrow(const ASTContext &Ctx, 2775 bool ResultIfDependent) const { 2776 ExceptionSpecificationType EST = getExceptionSpecType(); 2777 assert(EST != EST_Unevaluated && EST != EST_Uninstantiated); 2778 if (EST == EST_DynamicNone || EST == EST_BasicNoexcept) 2779 return true; 2780 2781 if (EST == EST_Dynamic && ResultIfDependent) { 2782 // A dynamic exception specification is throwing unless every exception 2783 // type is an (unexpanded) pack expansion type. 2784 for (unsigned I = 0, N = NumExceptions; I != N; ++I) 2785 if (!getExceptionType(I)->getAs<PackExpansionType>()) 2786 return false; 2787 return ResultIfDependent; 2788 } 2789 2790 if (EST != EST_ComputedNoexcept) 2791 return false; 2792 2793 NoexceptResult NR = getNoexceptSpec(Ctx); 2794 if (NR == NR_Dependent) 2795 return ResultIfDependent; 2796 return NR == NR_Nothrow; 2797 } 2798 2799 bool FunctionProtoType::isTemplateVariadic() const { 2800 for (unsigned ArgIdx = getNumParams(); ArgIdx; --ArgIdx) 2801 if (isa<PackExpansionType>(getParamType(ArgIdx - 1))) 2802 return true; 2803 2804 return false; 2805 } 2806 2807 void FunctionProtoType::Profile(llvm::FoldingSetNodeID &ID, QualType Result, 2808 const QualType *ArgTys, unsigned NumParams, 2809 const ExtProtoInfo &epi, 2810 const ASTContext &Context) { 2811 2812 // We have to be careful not to get ambiguous profile encodings. 2813 // Note that valid type pointers are never ambiguous with anything else. 2814 // 2815 // The encoding grammar begins: 2816 // type type* bool int bool 2817 // If that final bool is true, then there is a section for the EH spec: 2818 // bool type* 2819 // This is followed by an optional "consumed argument" section of the 2820 // same length as the first type sequence: 2821 // bool* 2822 // Finally, we have the ext info and trailing return type flag: 2823 // int bool 2824 // 2825 // There is no ambiguity between the consumed arguments and an empty EH 2826 // spec because of the leading 'bool' which unambiguously indicates 2827 // whether the following bool is the EH spec or part of the arguments. 2828 2829 ID.AddPointer(Result.getAsOpaquePtr()); 2830 for (unsigned i = 0; i != NumParams; ++i) 2831 ID.AddPointer(ArgTys[i].getAsOpaquePtr()); 2832 // This method is relatively performance sensitive, so as a performance 2833 // shortcut, use one AddInteger call instead of four for the next four 2834 // fields. 2835 assert(!(unsigned(epi.Variadic) & ~1) && 2836 !(unsigned(epi.TypeQuals) & ~255) && 2837 !(unsigned(epi.RefQualifier) & ~3) && 2838 !(unsigned(epi.ExceptionSpec.Type) & ~15) && 2839 "Values larger than expected."); 2840 ID.AddInteger(unsigned(epi.Variadic) + 2841 (epi.TypeQuals << 1) + 2842 (epi.RefQualifier << 9) + 2843 (epi.ExceptionSpec.Type << 11)); 2844 if (epi.ExceptionSpec.Type == EST_Dynamic) { 2845 for (QualType Ex : epi.ExceptionSpec.Exceptions) 2846 ID.AddPointer(Ex.getAsOpaquePtr()); 2847 } else if (epi.ExceptionSpec.Type == EST_ComputedNoexcept && 2848 epi.ExceptionSpec.NoexceptExpr) { 2849 epi.ExceptionSpec.NoexceptExpr->Profile(ID, Context, false); 2850 } else if (epi.ExceptionSpec.Type == EST_Uninstantiated || 2851 epi.ExceptionSpec.Type == EST_Unevaluated) { 2852 ID.AddPointer(epi.ExceptionSpec.SourceDecl->getCanonicalDecl()); 2853 } 2854 if (epi.ExtParameterInfos) { 2855 for (unsigned i = 0; i != NumParams; ++i) 2856 ID.AddInteger(epi.ExtParameterInfos[i].getOpaqueValue()); 2857 } 2858 epi.ExtInfo.Profile(ID); 2859 ID.AddBoolean(epi.HasTrailingReturn); 2860 } 2861 2862 void FunctionProtoType::Profile(llvm::FoldingSetNodeID &ID, 2863 const ASTContext &Ctx) { 2864 Profile(ID, getReturnType(), param_type_begin(), NumParams, getExtProtoInfo(), 2865 Ctx); 2866 } 2867 2868 QualType TypedefType::desugar() const { 2869 return getDecl()->getUnderlyingType(); 2870 } 2871 2872 TypeOfExprType::TypeOfExprType(Expr *E, QualType can) 2873 : Type(TypeOfExpr, can, E->isTypeDependent(), 2874 E->isInstantiationDependent(), 2875 E->getType()->isVariablyModifiedType(), 2876 E->containsUnexpandedParameterPack()), 2877 TOExpr(E) { 2878 } 2879 2880 bool TypeOfExprType::isSugared() const { 2881 return !TOExpr->isTypeDependent(); 2882 } 2883 2884 QualType TypeOfExprType::desugar() const { 2885 if (isSugared()) 2886 return getUnderlyingExpr()->getType(); 2887 2888 return QualType(this, 0); 2889 } 2890 2891 void DependentTypeOfExprType::Profile(llvm::FoldingSetNodeID &ID, 2892 const ASTContext &Context, Expr *E) { 2893 E->Profile(ID, Context, true); 2894 } 2895 2896 DecltypeType::DecltypeType(Expr *E, QualType underlyingType, QualType can) 2897 // C++11 [temp.type]p2: "If an expression e involves a template parameter, 2898 // decltype(e) denotes a unique dependent type." Hence a decltype type is 2899 // type-dependent even if its expression is only instantiation-dependent. 2900 : Type(Decltype, can, E->isInstantiationDependent(), 2901 E->isInstantiationDependent(), 2902 E->getType()->isVariablyModifiedType(), 2903 E->containsUnexpandedParameterPack()), 2904 E(E), 2905 UnderlyingType(underlyingType) { 2906 } 2907 2908 bool DecltypeType::isSugared() const { return !E->isInstantiationDependent(); } 2909 2910 QualType DecltypeType::desugar() const { 2911 if (isSugared()) 2912 return getUnderlyingType(); 2913 2914 return QualType(this, 0); 2915 } 2916 2917 DependentDecltypeType::DependentDecltypeType(const ASTContext &Context, Expr *E) 2918 : DecltypeType(E, Context.DependentTy), Context(Context) { } 2919 2920 void DependentDecltypeType::Profile(llvm::FoldingSetNodeID &ID, 2921 const ASTContext &Context, Expr *E) { 2922 E->Profile(ID, Context, true); 2923 } 2924 2925 UnaryTransformType::UnaryTransformType(QualType BaseType, 2926 QualType UnderlyingType, 2927 UTTKind UKind, 2928 QualType CanonicalType) 2929 : Type(UnaryTransform, CanonicalType, BaseType->isDependentType(), 2930 BaseType->isInstantiationDependentType(), 2931 BaseType->isVariablyModifiedType(), 2932 BaseType->containsUnexpandedParameterPack()) 2933 , BaseType(BaseType), UnderlyingType(UnderlyingType), UKind(UKind) 2934 {} 2935 2936 DependentUnaryTransformType::DependentUnaryTransformType(const ASTContext &C, 2937 QualType BaseType, 2938 UTTKind UKind) 2939 : UnaryTransformType(BaseType, C.DependentTy, UKind, QualType()) 2940 {} 2941 2942 2943 TagType::TagType(TypeClass TC, const TagDecl *D, QualType can) 2944 : Type(TC, can, D->isDependentType(), 2945 /*InstantiationDependent=*/D->isDependentType(), 2946 /*VariablyModified=*/false, 2947 /*ContainsUnexpandedParameterPack=*/false), 2948 decl(const_cast<TagDecl*>(D)) {} 2949 2950 static TagDecl *getInterestingTagDecl(TagDecl *decl) { 2951 for (auto I : decl->redecls()) { 2952 if (I->isCompleteDefinition() || I->isBeingDefined()) 2953 return I; 2954 } 2955 // If there's no definition (not even in progress), return what we have. 2956 return decl; 2957 } 2958 2959 TagDecl *TagType::getDecl() const { 2960 return getInterestingTagDecl(decl); 2961 } 2962 2963 bool TagType::isBeingDefined() const { 2964 return getDecl()->isBeingDefined(); 2965 } 2966 2967 bool AttributedType::isQualifier() const { 2968 switch (getAttrKind()) { 2969 // These are type qualifiers in the traditional C sense: they annotate 2970 // something about a specific value/variable of a type. (They aren't 2971 // always part of the canonical type, though.) 2972 case AttributedType::attr_address_space: 2973 case AttributedType::attr_objc_gc: 2974 case AttributedType::attr_objc_ownership: 2975 case AttributedType::attr_objc_inert_unsafe_unretained: 2976 case AttributedType::attr_nonnull: 2977 case AttributedType::attr_nullable: 2978 case AttributedType::attr_null_unspecified: 2979 return true; 2980 2981 // These aren't qualifiers; they rewrite the modified type to be a 2982 // semantically different type. 2983 case AttributedType::attr_regparm: 2984 case AttributedType::attr_vector_size: 2985 case AttributedType::attr_neon_vector_type: 2986 case AttributedType::attr_neon_polyvector_type: 2987 case AttributedType::attr_pcs: 2988 case AttributedType::attr_pcs_vfp: 2989 case AttributedType::attr_noreturn: 2990 case AttributedType::attr_cdecl: 2991 case AttributedType::attr_fastcall: 2992 case AttributedType::attr_stdcall: 2993 case AttributedType::attr_thiscall: 2994 case AttributedType::attr_pascal: 2995 case AttributedType::attr_swiftcall: 2996 case AttributedType::attr_vectorcall: 2997 case AttributedType::attr_inteloclbicc: 2998 case AttributedType::attr_preserve_most: 2999 case AttributedType::attr_preserve_all: 3000 case AttributedType::attr_ms_abi: 3001 case AttributedType::attr_sysv_abi: 3002 case AttributedType::attr_ptr32: 3003 case AttributedType::attr_ptr64: 3004 case AttributedType::attr_sptr: 3005 case AttributedType::attr_uptr: 3006 case AttributedType::attr_objc_kindof: 3007 return false; 3008 } 3009 llvm_unreachable("bad attributed type kind"); 3010 } 3011 3012 bool AttributedType::isMSTypeSpec() const { 3013 switch (getAttrKind()) { 3014 default: return false; 3015 case attr_ptr32: 3016 case attr_ptr64: 3017 case attr_sptr: 3018 case attr_uptr: 3019 return true; 3020 } 3021 llvm_unreachable("invalid attr kind"); 3022 } 3023 3024 bool AttributedType::isCallingConv() const { 3025 switch (getAttrKind()) { 3026 case attr_ptr32: 3027 case attr_ptr64: 3028 case attr_sptr: 3029 case attr_uptr: 3030 case attr_address_space: 3031 case attr_regparm: 3032 case attr_vector_size: 3033 case attr_neon_vector_type: 3034 case attr_neon_polyvector_type: 3035 case attr_objc_gc: 3036 case attr_objc_ownership: 3037 case attr_objc_inert_unsafe_unretained: 3038 case attr_noreturn: 3039 case attr_nonnull: 3040 case attr_nullable: 3041 case attr_null_unspecified: 3042 case attr_objc_kindof: 3043 return false; 3044 3045 case attr_pcs: 3046 case attr_pcs_vfp: 3047 case attr_cdecl: 3048 case attr_fastcall: 3049 case attr_stdcall: 3050 case attr_thiscall: 3051 case attr_swiftcall: 3052 case attr_vectorcall: 3053 case attr_pascal: 3054 case attr_ms_abi: 3055 case attr_sysv_abi: 3056 case attr_inteloclbicc: 3057 case attr_preserve_most: 3058 case attr_preserve_all: 3059 return true; 3060 } 3061 llvm_unreachable("invalid attr kind"); 3062 } 3063 3064 CXXRecordDecl *InjectedClassNameType::getDecl() const { 3065 return cast<CXXRecordDecl>(getInterestingTagDecl(Decl)); 3066 } 3067 3068 IdentifierInfo *TemplateTypeParmType::getIdentifier() const { 3069 return isCanonicalUnqualified() ? nullptr : getDecl()->getIdentifier(); 3070 } 3071 3072 SubstTemplateTypeParmPackType:: 3073 SubstTemplateTypeParmPackType(const TemplateTypeParmType *Param, 3074 QualType Canon, 3075 const TemplateArgument &ArgPack) 3076 : Type(SubstTemplateTypeParmPack, Canon, true, true, false, true), 3077 Replaced(Param), 3078 Arguments(ArgPack.pack_begin()), NumArguments(ArgPack.pack_size()) 3079 { 3080 } 3081 3082 TemplateArgument SubstTemplateTypeParmPackType::getArgumentPack() const { 3083 return TemplateArgument(llvm::makeArrayRef(Arguments, NumArguments)); 3084 } 3085 3086 void SubstTemplateTypeParmPackType::Profile(llvm::FoldingSetNodeID &ID) { 3087 Profile(ID, getReplacedParameter(), getArgumentPack()); 3088 } 3089 3090 void SubstTemplateTypeParmPackType::Profile(llvm::FoldingSetNodeID &ID, 3091 const TemplateTypeParmType *Replaced, 3092 const TemplateArgument &ArgPack) { 3093 ID.AddPointer(Replaced); 3094 ID.AddInteger(ArgPack.pack_size()); 3095 for (const auto &P : ArgPack.pack_elements()) 3096 ID.AddPointer(P.getAsType().getAsOpaquePtr()); 3097 } 3098 3099 bool TemplateSpecializationType:: 3100 anyDependentTemplateArguments(const TemplateArgumentListInfo &Args, 3101 bool &InstantiationDependent) { 3102 return anyDependentTemplateArguments(Args.arguments(), 3103 InstantiationDependent); 3104 } 3105 3106 bool TemplateSpecializationType:: 3107 anyDependentTemplateArguments(ArrayRef<TemplateArgumentLoc> Args, 3108 bool &InstantiationDependent) { 3109 for (const TemplateArgumentLoc &ArgLoc : Args) { 3110 if (ArgLoc.getArgument().isDependent()) { 3111 InstantiationDependent = true; 3112 return true; 3113 } 3114 3115 if (ArgLoc.getArgument().isInstantiationDependent()) 3116 InstantiationDependent = true; 3117 } 3118 return false; 3119 } 3120 3121 TemplateSpecializationType:: 3122 TemplateSpecializationType(TemplateName T, 3123 ArrayRef<TemplateArgument> Args, 3124 QualType Canon, QualType AliasedType) 3125 : Type(TemplateSpecialization, 3126 Canon.isNull()? QualType(this, 0) : Canon, 3127 Canon.isNull()? true : Canon->isDependentType(), 3128 Canon.isNull()? true : Canon->isInstantiationDependentType(), 3129 false, 3130 T.containsUnexpandedParameterPack()), 3131 Template(T), NumArgs(Args.size()), TypeAlias(!AliasedType.isNull()) { 3132 assert(!T.getAsDependentTemplateName() && 3133 "Use DependentTemplateSpecializationType for dependent template-name"); 3134 assert((T.getKind() == TemplateName::Template || 3135 T.getKind() == TemplateName::SubstTemplateTemplateParm || 3136 T.getKind() == TemplateName::SubstTemplateTemplateParmPack) && 3137 "Unexpected template name for TemplateSpecializationType"); 3138 3139 TemplateArgument *TemplateArgs 3140 = reinterpret_cast<TemplateArgument *>(this + 1); 3141 for (const TemplateArgument &Arg : Args) { 3142 // Update instantiation-dependent and variably-modified bits. 3143 // If the canonical type exists and is non-dependent, the template 3144 // specialization type can be non-dependent even if one of the type 3145 // arguments is. Given: 3146 // template<typename T> using U = int; 3147 // U<T> is always non-dependent, irrespective of the type T. 3148 // However, U<Ts> contains an unexpanded parameter pack, even though 3149 // its expansion (and thus its desugared type) doesn't. 3150 if (Arg.isInstantiationDependent()) 3151 setInstantiationDependent(); 3152 if (Arg.getKind() == TemplateArgument::Type && 3153 Arg.getAsType()->isVariablyModifiedType()) 3154 setVariablyModified(); 3155 if (Arg.containsUnexpandedParameterPack()) 3156 setContainsUnexpandedParameterPack(); 3157 new (TemplateArgs++) TemplateArgument(Arg); 3158 } 3159 3160 // Store the aliased type if this is a type alias template specialization. 3161 if (TypeAlias) { 3162 TemplateArgument *Begin = reinterpret_cast<TemplateArgument *>(this + 1); 3163 *reinterpret_cast<QualType*>(Begin + getNumArgs()) = AliasedType; 3164 } 3165 } 3166 3167 void 3168 TemplateSpecializationType::Profile(llvm::FoldingSetNodeID &ID, 3169 TemplateName T, 3170 ArrayRef<TemplateArgument> Args, 3171 const ASTContext &Context) { 3172 T.Profile(ID); 3173 for (const TemplateArgument &Arg : Args) 3174 Arg.Profile(ID, Context); 3175 } 3176 3177 QualType 3178 QualifierCollector::apply(const ASTContext &Context, QualType QT) const { 3179 if (!hasNonFastQualifiers()) 3180 return QT.withFastQualifiers(getFastQualifiers()); 3181 3182 return Context.getQualifiedType(QT, *this); 3183 } 3184 3185 QualType 3186 QualifierCollector::apply(const ASTContext &Context, const Type *T) const { 3187 if (!hasNonFastQualifiers()) 3188 return QualType(T, getFastQualifiers()); 3189 3190 return Context.getQualifiedType(T, *this); 3191 } 3192 3193 void ObjCObjectTypeImpl::Profile(llvm::FoldingSetNodeID &ID, 3194 QualType BaseType, 3195 ArrayRef<QualType> typeArgs, 3196 ArrayRef<ObjCProtocolDecl *> protocols, 3197 bool isKindOf) { 3198 ID.AddPointer(BaseType.getAsOpaquePtr()); 3199 ID.AddInteger(typeArgs.size()); 3200 for (auto typeArg : typeArgs) 3201 ID.AddPointer(typeArg.getAsOpaquePtr()); 3202 ID.AddInteger(protocols.size()); 3203 for (auto proto : protocols) 3204 ID.AddPointer(proto); 3205 ID.AddBoolean(isKindOf); 3206 } 3207 3208 void ObjCObjectTypeImpl::Profile(llvm::FoldingSetNodeID &ID) { 3209 Profile(ID, getBaseType(), getTypeArgsAsWritten(), 3210 llvm::makeArrayRef(qual_begin(), getNumProtocols()), 3211 isKindOfTypeAsWritten()); 3212 } 3213 3214 namespace { 3215 3216 /// \brief The cached properties of a type. 3217 class CachedProperties { 3218 Linkage L; 3219 bool local; 3220 3221 public: 3222 CachedProperties(Linkage L, bool local) : L(L), local(local) {} 3223 3224 Linkage getLinkage() const { return L; } 3225 bool hasLocalOrUnnamedType() const { return local; } 3226 3227 friend CachedProperties merge(CachedProperties L, CachedProperties R) { 3228 Linkage MergedLinkage = minLinkage(L.L, R.L); 3229 return CachedProperties(MergedLinkage, 3230 L.hasLocalOrUnnamedType() | R.hasLocalOrUnnamedType()); 3231 } 3232 }; 3233 } 3234 3235 static CachedProperties computeCachedProperties(const Type *T); 3236 3237 namespace clang { 3238 /// The type-property cache. This is templated so as to be 3239 /// instantiated at an internal type to prevent unnecessary symbol 3240 /// leakage. 3241 template <class Private> class TypePropertyCache { 3242 public: 3243 static CachedProperties get(QualType T) { 3244 return get(T.getTypePtr()); 3245 } 3246 3247 static CachedProperties get(const Type *T) { 3248 ensure(T); 3249 return CachedProperties(T->TypeBits.getLinkage(), 3250 T->TypeBits.hasLocalOrUnnamedType()); 3251 } 3252 3253 static void ensure(const Type *T) { 3254 // If the cache is valid, we're okay. 3255 if (T->TypeBits.isCacheValid()) return; 3256 3257 // If this type is non-canonical, ask its canonical type for the 3258 // relevant information. 3259 if (!T->isCanonicalUnqualified()) { 3260 const Type *CT = T->getCanonicalTypeInternal().getTypePtr(); 3261 ensure(CT); 3262 T->TypeBits.CacheValid = true; 3263 T->TypeBits.CachedLinkage = CT->TypeBits.CachedLinkage; 3264 T->TypeBits.CachedLocalOrUnnamed = CT->TypeBits.CachedLocalOrUnnamed; 3265 return; 3266 } 3267 3268 // Compute the cached properties and then set the cache. 3269 CachedProperties Result = computeCachedProperties(T); 3270 T->TypeBits.CacheValid = true; 3271 T->TypeBits.CachedLinkage = Result.getLinkage(); 3272 T->TypeBits.CachedLocalOrUnnamed = Result.hasLocalOrUnnamedType(); 3273 } 3274 }; 3275 } 3276 3277 // Instantiate the friend template at a private class. In a 3278 // reasonable implementation, these symbols will be internal. 3279 // It is terrible that this is the best way to accomplish this. 3280 namespace { class Private {}; } 3281 typedef TypePropertyCache<Private> Cache; 3282 3283 static CachedProperties computeCachedProperties(const Type *T) { 3284 switch (T->getTypeClass()) { 3285 #define TYPE(Class,Base) 3286 #define NON_CANONICAL_TYPE(Class,Base) case Type::Class: 3287 #include "clang/AST/TypeNodes.def" 3288 llvm_unreachable("didn't expect a non-canonical type here"); 3289 3290 #define TYPE(Class,Base) 3291 #define DEPENDENT_TYPE(Class,Base) case Type::Class: 3292 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class,Base) case Type::Class: 3293 #include "clang/AST/TypeNodes.def" 3294 // Treat instantiation-dependent types as external. 3295 assert(T->isInstantiationDependentType()); 3296 return CachedProperties(ExternalLinkage, false); 3297 3298 case Type::Auto: 3299 // Give non-deduced 'auto' types external linkage. We should only see them 3300 // here in error recovery. 3301 return CachedProperties(ExternalLinkage, false); 3302 3303 case Type::Builtin: 3304 // C++ [basic.link]p8: 3305 // A type is said to have linkage if and only if: 3306 // - it is a fundamental type (3.9.1); or 3307 return CachedProperties(ExternalLinkage, false); 3308 3309 case Type::Record: 3310 case Type::Enum: { 3311 const TagDecl *Tag = cast<TagType>(T)->getDecl(); 3312 3313 // C++ [basic.link]p8: 3314 // - it is a class or enumeration type that is named (or has a name 3315 // for linkage purposes (7.1.3)) and the name has linkage; or 3316 // - it is a specialization of a class template (14); or 3317 Linkage L = Tag->getLinkageInternal(); 3318 bool IsLocalOrUnnamed = 3319 Tag->getDeclContext()->isFunctionOrMethod() || 3320 !Tag->hasNameForLinkage(); 3321 return CachedProperties(L, IsLocalOrUnnamed); 3322 } 3323 3324 // C++ [basic.link]p8: 3325 // - it is a compound type (3.9.2) other than a class or enumeration, 3326 // compounded exclusively from types that have linkage; or 3327 case Type::Complex: 3328 return Cache::get(cast<ComplexType>(T)->getElementType()); 3329 case Type::Pointer: 3330 return Cache::get(cast<PointerType>(T)->getPointeeType()); 3331 case Type::BlockPointer: 3332 return Cache::get(cast<BlockPointerType>(T)->getPointeeType()); 3333 case Type::LValueReference: 3334 case Type::RValueReference: 3335 return Cache::get(cast<ReferenceType>(T)->getPointeeType()); 3336 case Type::MemberPointer: { 3337 const MemberPointerType *MPT = cast<MemberPointerType>(T); 3338 return merge(Cache::get(MPT->getClass()), 3339 Cache::get(MPT->getPointeeType())); 3340 } 3341 case Type::ConstantArray: 3342 case Type::IncompleteArray: 3343 case Type::VariableArray: 3344 return Cache::get(cast<ArrayType>(T)->getElementType()); 3345 case Type::Vector: 3346 case Type::ExtVector: 3347 return Cache::get(cast<VectorType>(T)->getElementType()); 3348 case Type::FunctionNoProto: 3349 return Cache::get(cast<FunctionType>(T)->getReturnType()); 3350 case Type::FunctionProto: { 3351 const FunctionProtoType *FPT = cast<FunctionProtoType>(T); 3352 CachedProperties result = Cache::get(FPT->getReturnType()); 3353 for (const auto &ai : FPT->param_types()) 3354 result = merge(result, Cache::get(ai)); 3355 return result; 3356 } 3357 case Type::ObjCInterface: { 3358 Linkage L = cast<ObjCInterfaceType>(T)->getDecl()->getLinkageInternal(); 3359 return CachedProperties(L, false); 3360 } 3361 case Type::ObjCObject: 3362 return Cache::get(cast<ObjCObjectType>(T)->getBaseType()); 3363 case Type::ObjCObjectPointer: 3364 return Cache::get(cast<ObjCObjectPointerType>(T)->getPointeeType()); 3365 case Type::Atomic: 3366 return Cache::get(cast<AtomicType>(T)->getValueType()); 3367 case Type::Pipe: 3368 return Cache::get(cast<PipeType>(T)->getElementType()); 3369 } 3370 3371 llvm_unreachable("unhandled type class"); 3372 } 3373 3374 /// \brief Determine the linkage of this type. 3375 Linkage Type::getLinkage() const { 3376 Cache::ensure(this); 3377 return TypeBits.getLinkage(); 3378 } 3379 3380 bool Type::hasUnnamedOrLocalType() const { 3381 Cache::ensure(this); 3382 return TypeBits.hasLocalOrUnnamedType(); 3383 } 3384 3385 static LinkageInfo computeLinkageInfo(QualType T); 3386 3387 static LinkageInfo computeLinkageInfo(const Type *T) { 3388 switch (T->getTypeClass()) { 3389 #define TYPE(Class,Base) 3390 #define NON_CANONICAL_TYPE(Class,Base) case Type::Class: 3391 #include "clang/AST/TypeNodes.def" 3392 llvm_unreachable("didn't expect a non-canonical type here"); 3393 3394 #define TYPE(Class,Base) 3395 #define DEPENDENT_TYPE(Class,Base) case Type::Class: 3396 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class,Base) case Type::Class: 3397 #include "clang/AST/TypeNodes.def" 3398 // Treat instantiation-dependent types as external. 3399 assert(T->isInstantiationDependentType()); 3400 return LinkageInfo::external(); 3401 3402 case Type::Builtin: 3403 return LinkageInfo::external(); 3404 3405 case Type::Auto: 3406 return LinkageInfo::external(); 3407 3408 case Type::Record: 3409 case Type::Enum: 3410 return cast<TagType>(T)->getDecl()->getLinkageAndVisibility(); 3411 3412 case Type::Complex: 3413 return computeLinkageInfo(cast<ComplexType>(T)->getElementType()); 3414 case Type::Pointer: 3415 return computeLinkageInfo(cast<PointerType>(T)->getPointeeType()); 3416 case Type::BlockPointer: 3417 return computeLinkageInfo(cast<BlockPointerType>(T)->getPointeeType()); 3418 case Type::LValueReference: 3419 case Type::RValueReference: 3420 return computeLinkageInfo(cast<ReferenceType>(T)->getPointeeType()); 3421 case Type::MemberPointer: { 3422 const MemberPointerType *MPT = cast<MemberPointerType>(T); 3423 LinkageInfo LV = computeLinkageInfo(MPT->getClass()); 3424 LV.merge(computeLinkageInfo(MPT->getPointeeType())); 3425 return LV; 3426 } 3427 case Type::ConstantArray: 3428 case Type::IncompleteArray: 3429 case Type::VariableArray: 3430 return computeLinkageInfo(cast<ArrayType>(T)->getElementType()); 3431 case Type::Vector: 3432 case Type::ExtVector: 3433 return computeLinkageInfo(cast<VectorType>(T)->getElementType()); 3434 case Type::FunctionNoProto: 3435 return computeLinkageInfo(cast<FunctionType>(T)->getReturnType()); 3436 case Type::FunctionProto: { 3437 const FunctionProtoType *FPT = cast<FunctionProtoType>(T); 3438 LinkageInfo LV = computeLinkageInfo(FPT->getReturnType()); 3439 for (const auto &ai : FPT->param_types()) 3440 LV.merge(computeLinkageInfo(ai)); 3441 return LV; 3442 } 3443 case Type::ObjCInterface: 3444 return cast<ObjCInterfaceType>(T)->getDecl()->getLinkageAndVisibility(); 3445 case Type::ObjCObject: 3446 return computeLinkageInfo(cast<ObjCObjectType>(T)->getBaseType()); 3447 case Type::ObjCObjectPointer: 3448 return computeLinkageInfo(cast<ObjCObjectPointerType>(T)->getPointeeType()); 3449 case Type::Atomic: 3450 return computeLinkageInfo(cast<AtomicType>(T)->getValueType()); 3451 case Type::Pipe: 3452 return computeLinkageInfo(cast<PipeType>(T)->getElementType()); 3453 } 3454 3455 llvm_unreachable("unhandled type class"); 3456 } 3457 3458 static LinkageInfo computeLinkageInfo(QualType T) { 3459 return computeLinkageInfo(T.getTypePtr()); 3460 } 3461 3462 bool Type::isLinkageValid() const { 3463 if (!TypeBits.isCacheValid()) 3464 return true; 3465 3466 return computeLinkageInfo(getCanonicalTypeInternal()).getLinkage() == 3467 TypeBits.getLinkage(); 3468 } 3469 3470 LinkageInfo Type::getLinkageAndVisibility() const { 3471 if (!isCanonicalUnqualified()) 3472 return computeLinkageInfo(getCanonicalTypeInternal()); 3473 3474 LinkageInfo LV = computeLinkageInfo(this); 3475 assert(LV.getLinkage() == getLinkage()); 3476 return LV; 3477 } 3478 3479 Optional<NullabilityKind> Type::getNullability(const ASTContext &context) const { 3480 QualType type(this, 0); 3481 do { 3482 // Check whether this is an attributed type with nullability 3483 // information. 3484 if (auto attributed = dyn_cast<AttributedType>(type.getTypePtr())) { 3485 if (auto nullability = attributed->getImmediateNullability()) 3486 return nullability; 3487 } 3488 3489 // Desugar the type. If desugaring does nothing, we're done. 3490 QualType desugared = type.getSingleStepDesugaredType(context); 3491 if (desugared.getTypePtr() == type.getTypePtr()) 3492 return None; 3493 3494 type = desugared; 3495 } while (true); 3496 } 3497 3498 bool Type::canHaveNullability() const { 3499 QualType type = getCanonicalTypeInternal(); 3500 3501 switch (type->getTypeClass()) { 3502 // We'll only see canonical types here. 3503 #define NON_CANONICAL_TYPE(Class, Parent) \ 3504 case Type::Class: \ 3505 llvm_unreachable("non-canonical type"); 3506 #define TYPE(Class, Parent) 3507 #include "clang/AST/TypeNodes.def" 3508 3509 // Pointer types. 3510 case Type::Pointer: 3511 case Type::BlockPointer: 3512 case Type::MemberPointer: 3513 case Type::ObjCObjectPointer: 3514 return true; 3515 3516 // Dependent types that could instantiate to pointer types. 3517 case Type::UnresolvedUsing: 3518 case Type::TypeOfExpr: 3519 case Type::TypeOf: 3520 case Type::Decltype: 3521 case Type::UnaryTransform: 3522 case Type::TemplateTypeParm: 3523 case Type::SubstTemplateTypeParmPack: 3524 case Type::DependentName: 3525 case Type::DependentTemplateSpecialization: 3526 return true; 3527 3528 // Dependent template specializations can instantiate to pointer 3529 // types unless they're known to be specializations of a class 3530 // template. 3531 case Type::TemplateSpecialization: 3532 if (TemplateDecl *templateDecl 3533 = cast<TemplateSpecializationType>(type.getTypePtr()) 3534 ->getTemplateName().getAsTemplateDecl()) { 3535 if (isa<ClassTemplateDecl>(templateDecl)) 3536 return false; 3537 } 3538 return true; 3539 3540 // auto is considered dependent when it isn't deduced. 3541 case Type::Auto: 3542 return !cast<AutoType>(type.getTypePtr())->isDeduced(); 3543 3544 case Type::Builtin: 3545 switch (cast<BuiltinType>(type.getTypePtr())->getKind()) { 3546 // Signed, unsigned, and floating-point types cannot have nullability. 3547 #define SIGNED_TYPE(Id, SingletonId) case BuiltinType::Id: 3548 #define UNSIGNED_TYPE(Id, SingletonId) case BuiltinType::Id: 3549 #define FLOATING_TYPE(Id, SingletonId) case BuiltinType::Id: 3550 #define BUILTIN_TYPE(Id, SingletonId) 3551 #include "clang/AST/BuiltinTypes.def" 3552 return false; 3553 3554 // Dependent types that could instantiate to a pointer type. 3555 case BuiltinType::Dependent: 3556 case BuiltinType::Overload: 3557 case BuiltinType::BoundMember: 3558 case BuiltinType::PseudoObject: 3559 case BuiltinType::UnknownAny: 3560 case BuiltinType::ARCUnbridgedCast: 3561 return true; 3562 3563 case BuiltinType::Void: 3564 case BuiltinType::ObjCId: 3565 case BuiltinType::ObjCClass: 3566 case BuiltinType::ObjCSel: 3567 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \ 3568 case BuiltinType::Id: 3569 #include "clang/Basic/OpenCLImageTypes.def" 3570 case BuiltinType::OCLSampler: 3571 case BuiltinType::OCLEvent: 3572 case BuiltinType::OCLClkEvent: 3573 case BuiltinType::OCLQueue: 3574 case BuiltinType::OCLNDRange: 3575 case BuiltinType::OCLReserveID: 3576 case BuiltinType::BuiltinFn: 3577 case BuiltinType::NullPtr: 3578 case BuiltinType::OMPArraySection: 3579 return false; 3580 } 3581 3582 // Non-pointer types. 3583 case Type::Complex: 3584 case Type::LValueReference: 3585 case Type::RValueReference: 3586 case Type::ConstantArray: 3587 case Type::IncompleteArray: 3588 case Type::VariableArray: 3589 case Type::DependentSizedArray: 3590 case Type::DependentSizedExtVector: 3591 case Type::Vector: 3592 case Type::ExtVector: 3593 case Type::FunctionProto: 3594 case Type::FunctionNoProto: 3595 case Type::Record: 3596 case Type::Enum: 3597 case Type::InjectedClassName: 3598 case Type::PackExpansion: 3599 case Type::ObjCObject: 3600 case Type::ObjCInterface: 3601 case Type::Atomic: 3602 case Type::Pipe: 3603 return false; 3604 } 3605 llvm_unreachable("bad type kind!"); 3606 } 3607 3608 llvm::Optional<NullabilityKind> AttributedType::getImmediateNullability() const { 3609 if (getAttrKind() == AttributedType::attr_nonnull) 3610 return NullabilityKind::NonNull; 3611 if (getAttrKind() == AttributedType::attr_nullable) 3612 return NullabilityKind::Nullable; 3613 if (getAttrKind() == AttributedType::attr_null_unspecified) 3614 return NullabilityKind::Unspecified; 3615 return None; 3616 } 3617 3618 Optional<NullabilityKind> AttributedType::stripOuterNullability(QualType &T) { 3619 if (auto attributed = dyn_cast<AttributedType>(T.getTypePtr())) { 3620 if (auto nullability = attributed->getImmediateNullability()) { 3621 T = attributed->getModifiedType(); 3622 return nullability; 3623 } 3624 } 3625 3626 return None; 3627 } 3628 3629 bool Type::isBlockCompatibleObjCPointerType(ASTContext &ctx) const { 3630 const ObjCObjectPointerType *objcPtr = getAs<ObjCObjectPointerType>(); 3631 if (!objcPtr) 3632 return false; 3633 3634 if (objcPtr->isObjCIdType()) { 3635 // id is always okay. 3636 return true; 3637 } 3638 3639 // Blocks are NSObjects. 3640 if (ObjCInterfaceDecl *iface = objcPtr->getInterfaceDecl()) { 3641 if (iface->getIdentifier() != ctx.getNSObjectName()) 3642 return false; 3643 3644 // Continue to check qualifiers, below. 3645 } else if (objcPtr->isObjCQualifiedIdType()) { 3646 // Continue to check qualifiers, below. 3647 } else { 3648 return false; 3649 } 3650 3651 // Check protocol qualifiers. 3652 for (ObjCProtocolDecl *proto : objcPtr->quals()) { 3653 // Blocks conform to NSObject and NSCopying. 3654 if (proto->getIdentifier() != ctx.getNSObjectName() && 3655 proto->getIdentifier() != ctx.getNSCopyingName()) 3656 return false; 3657 } 3658 3659 return true; 3660 } 3661 3662 Qualifiers::ObjCLifetime Type::getObjCARCImplicitLifetime() const { 3663 if (isObjCARCImplicitlyUnretainedType()) 3664 return Qualifiers::OCL_ExplicitNone; 3665 return Qualifiers::OCL_Strong; 3666 } 3667 3668 bool Type::isObjCARCImplicitlyUnretainedType() const { 3669 assert(isObjCLifetimeType() && 3670 "cannot query implicit lifetime for non-inferrable type"); 3671 3672 const Type *canon = getCanonicalTypeInternal().getTypePtr(); 3673 3674 // Walk down to the base type. We don't care about qualifiers for this. 3675 while (const ArrayType *array = dyn_cast<ArrayType>(canon)) 3676 canon = array->getElementType().getTypePtr(); 3677 3678 if (const ObjCObjectPointerType *opt 3679 = dyn_cast<ObjCObjectPointerType>(canon)) { 3680 // Class and Class<Protocol> don't require retention. 3681 if (opt->getObjectType()->isObjCClass()) 3682 return true; 3683 } 3684 3685 return false; 3686 } 3687 3688 bool Type::isObjCNSObjectType() const { 3689 const Type *cur = this; 3690 while (true) { 3691 if (const TypedefType *typedefType = dyn_cast<TypedefType>(cur)) 3692 return typedefType->getDecl()->hasAttr<ObjCNSObjectAttr>(); 3693 3694 // Single-step desugar until we run out of sugar. 3695 QualType next = cur->getLocallyUnqualifiedSingleStepDesugaredType(); 3696 if (next.getTypePtr() == cur) return false; 3697 cur = next.getTypePtr(); 3698 } 3699 } 3700 3701 bool Type::isObjCIndependentClassType() const { 3702 if (const TypedefType *typedefType = dyn_cast<TypedefType>(this)) 3703 return typedefType->getDecl()->hasAttr<ObjCIndependentClassAttr>(); 3704 return false; 3705 } 3706 bool Type::isObjCRetainableType() const { 3707 return isObjCObjectPointerType() || 3708 isBlockPointerType() || 3709 isObjCNSObjectType(); 3710 } 3711 bool Type::isObjCIndirectLifetimeType() const { 3712 if (isObjCLifetimeType()) 3713 return true; 3714 if (const PointerType *OPT = getAs<PointerType>()) 3715 return OPT->getPointeeType()->isObjCIndirectLifetimeType(); 3716 if (const ReferenceType *Ref = getAs<ReferenceType>()) 3717 return Ref->getPointeeType()->isObjCIndirectLifetimeType(); 3718 if (const MemberPointerType *MemPtr = getAs<MemberPointerType>()) 3719 return MemPtr->getPointeeType()->isObjCIndirectLifetimeType(); 3720 return false; 3721 } 3722 3723 /// Returns true if objects of this type have lifetime semantics under 3724 /// ARC. 3725 bool Type::isObjCLifetimeType() const { 3726 const Type *type = this; 3727 while (const ArrayType *array = type->getAsArrayTypeUnsafe()) 3728 type = array->getElementType().getTypePtr(); 3729 return type->isObjCRetainableType(); 3730 } 3731 3732 /// \brief Determine whether the given type T is a "bridgable" Objective-C type, 3733 /// which is either an Objective-C object pointer type or an 3734 bool Type::isObjCARCBridgableType() const { 3735 return isObjCObjectPointerType() || isBlockPointerType(); 3736 } 3737 3738 /// \brief Determine whether the given type T is a "bridgeable" C type. 3739 bool Type::isCARCBridgableType() const { 3740 const PointerType *Pointer = getAs<PointerType>(); 3741 if (!Pointer) 3742 return false; 3743 3744 QualType Pointee = Pointer->getPointeeType(); 3745 return Pointee->isVoidType() || Pointee->isRecordType(); 3746 } 3747 3748 bool Type::hasSizedVLAType() const { 3749 if (!isVariablyModifiedType()) return false; 3750 3751 if (const PointerType *ptr = getAs<PointerType>()) 3752 return ptr->getPointeeType()->hasSizedVLAType(); 3753 if (const ReferenceType *ref = getAs<ReferenceType>()) 3754 return ref->getPointeeType()->hasSizedVLAType(); 3755 if (const ArrayType *arr = getAsArrayTypeUnsafe()) { 3756 if (isa<VariableArrayType>(arr) && 3757 cast<VariableArrayType>(arr)->getSizeExpr()) 3758 return true; 3759 3760 return arr->getElementType()->hasSizedVLAType(); 3761 } 3762 3763 return false; 3764 } 3765 3766 QualType::DestructionKind QualType::isDestructedTypeImpl(QualType type) { 3767 switch (type.getObjCLifetime()) { 3768 case Qualifiers::OCL_None: 3769 case Qualifiers::OCL_ExplicitNone: 3770 case Qualifiers::OCL_Autoreleasing: 3771 break; 3772 3773 case Qualifiers::OCL_Strong: 3774 return DK_objc_strong_lifetime; 3775 case Qualifiers::OCL_Weak: 3776 return DK_objc_weak_lifetime; 3777 } 3778 3779 /// Currently, the only destruction kind we recognize is C++ objects 3780 /// with non-trivial destructors. 3781 const CXXRecordDecl *record = 3782 type->getBaseElementTypeUnsafe()->getAsCXXRecordDecl(); 3783 if (record && record->hasDefinition() && !record->hasTrivialDestructor()) 3784 return DK_cxx_destructor; 3785 3786 return DK_none; 3787 } 3788 3789 CXXRecordDecl *MemberPointerType::getMostRecentCXXRecordDecl() const { 3790 return getClass()->getAsCXXRecordDecl()->getMostRecentDecl(); 3791 } 3792