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