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