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