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 QualType::canPassInRegisters() const { 2243 if (const auto *RT = 2244 getTypePtr()->getBaseElementTypeUnsafe()->getAs<RecordType>()) 2245 return RT->getDecl()->canPassInRegisters(); 2246 2247 if (getQualifiers().getObjCLifetime() == Qualifiers::OCL_Weak) 2248 return false; 2249 2250 return true; 2251 } 2252 2253 bool Type::isLiteralType(const ASTContext &Ctx) const { 2254 if (isDependentType()) 2255 return false; 2256 2257 // C++1y [basic.types]p10: 2258 // A type is a literal type if it is: 2259 // -- cv void; or 2260 if (Ctx.getLangOpts().CPlusPlus14 && isVoidType()) 2261 return true; 2262 2263 // C++11 [basic.types]p10: 2264 // A type is a literal type if it is: 2265 // [...] 2266 // -- an array of literal type other than an array of runtime bound; or 2267 if (isVariableArrayType()) 2268 return false; 2269 const Type *BaseTy = getBaseElementTypeUnsafe(); 2270 assert(BaseTy && "NULL element type"); 2271 2272 // Return false for incomplete types after skipping any incomplete array 2273 // types; those are expressly allowed by the standard and thus our API. 2274 if (BaseTy->isIncompleteType()) 2275 return false; 2276 2277 // C++11 [basic.types]p10: 2278 // A type is a literal type if it is: 2279 // -- a scalar type; or 2280 // As an extension, Clang treats vector types and complex types as 2281 // literal types. 2282 if (BaseTy->isScalarType() || BaseTy->isVectorType() || 2283 BaseTy->isAnyComplexType()) 2284 return true; 2285 // -- a reference type; or 2286 if (BaseTy->isReferenceType()) 2287 return true; 2288 // -- a class type that has all of the following properties: 2289 if (const auto *RT = BaseTy->getAs<RecordType>()) { 2290 // -- a trivial destructor, 2291 // -- every constructor call and full-expression in the 2292 // brace-or-equal-initializers for non-static data members (if any) 2293 // is a constant expression, 2294 // -- it is an aggregate type or has at least one constexpr 2295 // constructor or constructor template that is not a copy or move 2296 // constructor, and 2297 // -- all non-static data members and base classes of literal types 2298 // 2299 // We resolve DR1361 by ignoring the second bullet. 2300 if (const auto *ClassDecl = dyn_cast<CXXRecordDecl>(RT->getDecl())) 2301 return ClassDecl->isLiteral(); 2302 2303 return true; 2304 } 2305 2306 // We treat _Atomic T as a literal type if T is a literal type. 2307 if (const auto *AT = BaseTy->getAs<AtomicType>()) 2308 return AT->getValueType()->isLiteralType(Ctx); 2309 2310 // If this type hasn't been deduced yet, then conservatively assume that 2311 // it'll work out to be a literal type. 2312 if (isa<AutoType>(BaseTy->getCanonicalTypeInternal())) 2313 return true; 2314 2315 return false; 2316 } 2317 2318 bool Type::isStandardLayoutType() const { 2319 if (isDependentType()) 2320 return false; 2321 2322 // C++0x [basic.types]p9: 2323 // Scalar types, standard-layout class types, arrays of such types, and 2324 // cv-qualified versions of these types are collectively called 2325 // standard-layout types. 2326 const Type *BaseTy = getBaseElementTypeUnsafe(); 2327 assert(BaseTy && "NULL element type"); 2328 2329 // Return false for incomplete types after skipping any incomplete array 2330 // types which are expressly allowed by the standard and thus our API. 2331 if (BaseTy->isIncompleteType()) 2332 return false; 2333 2334 // As an extension, Clang treats vector types as Scalar types. 2335 if (BaseTy->isScalarType() || BaseTy->isVectorType()) return true; 2336 if (const auto *RT = BaseTy->getAs<RecordType>()) { 2337 if (const auto *ClassDecl = dyn_cast<CXXRecordDecl>(RT->getDecl())) 2338 if (!ClassDecl->isStandardLayout()) 2339 return false; 2340 2341 // Default to 'true' for non-C++ class types. 2342 // FIXME: This is a bit dubious, but plain C structs should trivially meet 2343 // all the requirements of standard layout classes. 2344 return true; 2345 } 2346 2347 // No other types can match. 2348 return false; 2349 } 2350 2351 // This is effectively the intersection of isTrivialType and 2352 // isStandardLayoutType. We implement it directly to avoid redundant 2353 // conversions from a type to a CXXRecordDecl. 2354 bool QualType::isCXX11PODType(const ASTContext &Context) const { 2355 const Type *ty = getTypePtr(); 2356 if (ty->isDependentType()) 2357 return false; 2358 2359 if (hasNonTrivialObjCLifetime()) 2360 return false; 2361 2362 // C++11 [basic.types]p9: 2363 // Scalar types, POD classes, arrays of such types, and cv-qualified 2364 // versions of these types are collectively called trivial types. 2365 const Type *BaseTy = ty->getBaseElementTypeUnsafe(); 2366 assert(BaseTy && "NULL element type"); 2367 2368 // Return false for incomplete types after skipping any incomplete array 2369 // types which are expressly allowed by the standard and thus our API. 2370 if (BaseTy->isIncompleteType()) 2371 return false; 2372 2373 // As an extension, Clang treats vector types as Scalar types. 2374 if (BaseTy->isScalarType() || BaseTy->isVectorType()) return true; 2375 if (const auto *RT = BaseTy->getAs<RecordType>()) { 2376 if (const auto *ClassDecl = dyn_cast<CXXRecordDecl>(RT->getDecl())) { 2377 // C++11 [class]p10: 2378 // A POD struct is a non-union class that is both a trivial class [...] 2379 if (!ClassDecl->isTrivial()) return false; 2380 2381 // C++11 [class]p10: 2382 // A POD struct is a non-union class that is both a trivial class and 2383 // a standard-layout class [...] 2384 if (!ClassDecl->isStandardLayout()) return false; 2385 2386 // C++11 [class]p10: 2387 // A POD struct is a non-union class that is both a trivial class and 2388 // a standard-layout class, and has no non-static data members of type 2389 // non-POD struct, non-POD union (or array of such types). [...] 2390 // 2391 // We don't directly query the recursive aspect as the requirements for 2392 // both standard-layout classes and trivial classes apply recursively 2393 // already. 2394 } 2395 2396 return true; 2397 } 2398 2399 // No other types can match. 2400 return false; 2401 } 2402 2403 bool Type::isAlignValT() const { 2404 if (const auto *ET = getAs<EnumType>()) { 2405 IdentifierInfo *II = ET->getDecl()->getIdentifier(); 2406 if (II && II->isStr("align_val_t") && ET->getDecl()->isInStdNamespace()) 2407 return true; 2408 } 2409 return false; 2410 } 2411 2412 bool Type::isStdByteType() const { 2413 if (const auto *ET = getAs<EnumType>()) { 2414 IdentifierInfo *II = ET->getDecl()->getIdentifier(); 2415 if (II && II->isStr("byte") && ET->getDecl()->isInStdNamespace()) 2416 return true; 2417 } 2418 return false; 2419 } 2420 2421 bool Type::isPromotableIntegerType() const { 2422 if (const auto *BT = getAs<BuiltinType>()) 2423 switch (BT->getKind()) { 2424 case BuiltinType::Bool: 2425 case BuiltinType::Char_S: 2426 case BuiltinType::Char_U: 2427 case BuiltinType::SChar: 2428 case BuiltinType::UChar: 2429 case BuiltinType::Short: 2430 case BuiltinType::UShort: 2431 case BuiltinType::WChar_S: 2432 case BuiltinType::WChar_U: 2433 case BuiltinType::Char16: 2434 case BuiltinType::Char32: 2435 return true; 2436 default: 2437 return false; 2438 } 2439 2440 // Enumerated types are promotable to their compatible integer types 2441 // (C99 6.3.1.1) a.k.a. its underlying type (C++ [conv.prom]p2). 2442 if (const auto *ET = getAs<EnumType>()){ 2443 if (this->isDependentType() || ET->getDecl()->getPromotionType().isNull() 2444 || ET->getDecl()->isScoped()) 2445 return false; 2446 2447 return true; 2448 } 2449 2450 return false; 2451 } 2452 2453 bool Type::isSpecifierType() const { 2454 // Note that this intentionally does not use the canonical type. 2455 switch (getTypeClass()) { 2456 case Builtin: 2457 case Record: 2458 case Enum: 2459 case Typedef: 2460 case Complex: 2461 case TypeOfExpr: 2462 case TypeOf: 2463 case TemplateTypeParm: 2464 case SubstTemplateTypeParm: 2465 case TemplateSpecialization: 2466 case Elaborated: 2467 case DependentName: 2468 case DependentTemplateSpecialization: 2469 case ObjCInterface: 2470 case ObjCObject: 2471 case ObjCObjectPointer: // FIXME: object pointers aren't really specifiers 2472 return true; 2473 default: 2474 return false; 2475 } 2476 } 2477 2478 ElaboratedTypeKeyword 2479 TypeWithKeyword::getKeywordForTypeSpec(unsigned TypeSpec) { 2480 switch (TypeSpec) { 2481 default: return ETK_None; 2482 case TST_typename: return ETK_Typename; 2483 case TST_class: return ETK_Class; 2484 case TST_struct: return ETK_Struct; 2485 case TST_interface: return ETK_Interface; 2486 case TST_union: return ETK_Union; 2487 case TST_enum: return ETK_Enum; 2488 } 2489 } 2490 2491 TagTypeKind 2492 TypeWithKeyword::getTagTypeKindForTypeSpec(unsigned TypeSpec) { 2493 switch(TypeSpec) { 2494 case TST_class: return TTK_Class; 2495 case TST_struct: return TTK_Struct; 2496 case TST_interface: return TTK_Interface; 2497 case TST_union: return TTK_Union; 2498 case TST_enum: return TTK_Enum; 2499 } 2500 2501 llvm_unreachable("Type specifier is not a tag type kind."); 2502 } 2503 2504 ElaboratedTypeKeyword 2505 TypeWithKeyword::getKeywordForTagTypeKind(TagTypeKind Kind) { 2506 switch (Kind) { 2507 case TTK_Class: return ETK_Class; 2508 case TTK_Struct: return ETK_Struct; 2509 case TTK_Interface: return ETK_Interface; 2510 case TTK_Union: return ETK_Union; 2511 case TTK_Enum: return ETK_Enum; 2512 } 2513 llvm_unreachable("Unknown tag type kind."); 2514 } 2515 2516 TagTypeKind 2517 TypeWithKeyword::getTagTypeKindForKeyword(ElaboratedTypeKeyword Keyword) { 2518 switch (Keyword) { 2519 case ETK_Class: return TTK_Class; 2520 case ETK_Struct: return TTK_Struct; 2521 case ETK_Interface: return TTK_Interface; 2522 case ETK_Union: return TTK_Union; 2523 case ETK_Enum: return TTK_Enum; 2524 case ETK_None: // Fall through. 2525 case ETK_Typename: 2526 llvm_unreachable("Elaborated type keyword is not a tag type kind."); 2527 } 2528 llvm_unreachable("Unknown elaborated type keyword."); 2529 } 2530 2531 bool 2532 TypeWithKeyword::KeywordIsTagTypeKind(ElaboratedTypeKeyword Keyword) { 2533 switch (Keyword) { 2534 case ETK_None: 2535 case ETK_Typename: 2536 return false; 2537 case ETK_Class: 2538 case ETK_Struct: 2539 case ETK_Interface: 2540 case ETK_Union: 2541 case ETK_Enum: 2542 return true; 2543 } 2544 llvm_unreachable("Unknown elaborated type keyword."); 2545 } 2546 2547 StringRef TypeWithKeyword::getKeywordName(ElaboratedTypeKeyword Keyword) { 2548 switch (Keyword) { 2549 case ETK_None: return {}; 2550 case ETK_Typename: return "typename"; 2551 case ETK_Class: return "class"; 2552 case ETK_Struct: return "struct"; 2553 case ETK_Interface: return "__interface"; 2554 case ETK_Union: return "union"; 2555 case ETK_Enum: return "enum"; 2556 } 2557 2558 llvm_unreachable("Unknown elaborated type keyword."); 2559 } 2560 2561 DependentTemplateSpecializationType::DependentTemplateSpecializationType( 2562 ElaboratedTypeKeyword Keyword, 2563 NestedNameSpecifier *NNS, const IdentifierInfo *Name, 2564 ArrayRef<TemplateArgument> Args, 2565 QualType Canon) 2566 : TypeWithKeyword(Keyword, DependentTemplateSpecialization, Canon, true, true, 2567 /*VariablyModified=*/false, 2568 NNS && NNS->containsUnexpandedParameterPack()), 2569 NNS(NNS), Name(Name), NumArgs(Args.size()) { 2570 assert((!NNS || NNS->isDependent()) && 2571 "DependentTemplateSpecializatonType requires dependent qualifier"); 2572 TemplateArgument *ArgBuffer = getArgBuffer(); 2573 for (const TemplateArgument &Arg : Args) { 2574 if (Arg.containsUnexpandedParameterPack()) 2575 setContainsUnexpandedParameterPack(); 2576 2577 new (ArgBuffer++) TemplateArgument(Arg); 2578 } 2579 } 2580 2581 void 2582 DependentTemplateSpecializationType::Profile(llvm::FoldingSetNodeID &ID, 2583 const ASTContext &Context, 2584 ElaboratedTypeKeyword Keyword, 2585 NestedNameSpecifier *Qualifier, 2586 const IdentifierInfo *Name, 2587 ArrayRef<TemplateArgument> Args) { 2588 ID.AddInteger(Keyword); 2589 ID.AddPointer(Qualifier); 2590 ID.AddPointer(Name); 2591 for (const TemplateArgument &Arg : Args) 2592 Arg.Profile(ID, Context); 2593 } 2594 2595 bool Type::isElaboratedTypeSpecifier() const { 2596 ElaboratedTypeKeyword Keyword; 2597 if (const auto *Elab = dyn_cast<ElaboratedType>(this)) 2598 Keyword = Elab->getKeyword(); 2599 else if (const auto *DepName = dyn_cast<DependentNameType>(this)) 2600 Keyword = DepName->getKeyword(); 2601 else if (const auto *DepTST = 2602 dyn_cast<DependentTemplateSpecializationType>(this)) 2603 Keyword = DepTST->getKeyword(); 2604 else 2605 return false; 2606 2607 return TypeWithKeyword::KeywordIsTagTypeKind(Keyword); 2608 } 2609 2610 const char *Type::getTypeClassName() const { 2611 switch (TypeBits.TC) { 2612 #define ABSTRACT_TYPE(Derived, Base) 2613 #define TYPE(Derived, Base) case Derived: return #Derived; 2614 #include "clang/AST/TypeNodes.def" 2615 } 2616 2617 llvm_unreachable("Invalid type class."); 2618 } 2619 2620 StringRef BuiltinType::getName(const PrintingPolicy &Policy) const { 2621 switch (getKind()) { 2622 case Void: 2623 return "void"; 2624 case Bool: 2625 return Policy.Bool ? "bool" : "_Bool"; 2626 case Char_S: 2627 return "char"; 2628 case Char_U: 2629 return "char"; 2630 case SChar: 2631 return "signed char"; 2632 case Short: 2633 return "short"; 2634 case Int: 2635 return "int"; 2636 case Long: 2637 return "long"; 2638 case LongLong: 2639 return "long long"; 2640 case Int128: 2641 return "__int128"; 2642 case UChar: 2643 return "unsigned char"; 2644 case UShort: 2645 return "unsigned short"; 2646 case UInt: 2647 return "unsigned int"; 2648 case ULong: 2649 return "unsigned long"; 2650 case ULongLong: 2651 return "unsigned long long"; 2652 case UInt128: 2653 return "unsigned __int128"; 2654 case Half: 2655 return Policy.Half ? "half" : "__fp16"; 2656 case Float: 2657 return "float"; 2658 case Double: 2659 return "double"; 2660 case LongDouble: 2661 return "long double"; 2662 case Float16: 2663 return "_Float16"; 2664 case Float128: 2665 return "__float128"; 2666 case WChar_S: 2667 case WChar_U: 2668 return Policy.MSWChar ? "__wchar_t" : "wchar_t"; 2669 case Char16: 2670 return "char16_t"; 2671 case Char32: 2672 return "char32_t"; 2673 case NullPtr: 2674 return "nullptr_t"; 2675 case Overload: 2676 return "<overloaded function type>"; 2677 case BoundMember: 2678 return "<bound member function type>"; 2679 case PseudoObject: 2680 return "<pseudo-object type>"; 2681 case Dependent: 2682 return "<dependent type>"; 2683 case UnknownAny: 2684 return "<unknown type>"; 2685 case ARCUnbridgedCast: 2686 return "<ARC unbridged cast type>"; 2687 case BuiltinFn: 2688 return "<builtin fn type>"; 2689 case ObjCId: 2690 return "id"; 2691 case ObjCClass: 2692 return "Class"; 2693 case ObjCSel: 2694 return "SEL"; 2695 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \ 2696 case Id: \ 2697 return "__" #Access " " #ImgType "_t"; 2698 #include "clang/Basic/OpenCLImageTypes.def" 2699 case OCLSampler: 2700 return "sampler_t"; 2701 case OCLEvent: 2702 return "event_t"; 2703 case OCLClkEvent: 2704 return "clk_event_t"; 2705 case OCLQueue: 2706 return "queue_t"; 2707 case OCLReserveID: 2708 return "reserve_id_t"; 2709 case OMPArraySection: 2710 return "<OpenMP array section type>"; 2711 } 2712 2713 llvm_unreachable("Invalid builtin type."); 2714 } 2715 2716 QualType QualType::getNonLValueExprType(const ASTContext &Context) const { 2717 if (const auto *RefType = getTypePtr()->getAs<ReferenceType>()) 2718 return RefType->getPointeeType(); 2719 2720 // C++0x [basic.lval]: 2721 // Class prvalues can have cv-qualified types; non-class prvalues always 2722 // have cv-unqualified types. 2723 // 2724 // See also C99 6.3.2.1p2. 2725 if (!Context.getLangOpts().CPlusPlus || 2726 (!getTypePtr()->isDependentType() && !getTypePtr()->isRecordType())) 2727 return getUnqualifiedType(); 2728 2729 return *this; 2730 } 2731 2732 StringRef FunctionType::getNameForCallConv(CallingConv CC) { 2733 switch (CC) { 2734 case CC_C: return "cdecl"; 2735 case CC_X86StdCall: return "stdcall"; 2736 case CC_X86FastCall: return "fastcall"; 2737 case CC_X86ThisCall: return "thiscall"; 2738 case CC_X86Pascal: return "pascal"; 2739 case CC_X86VectorCall: return "vectorcall"; 2740 case CC_Win64: return "ms_abi"; 2741 case CC_X86_64SysV: return "sysv_abi"; 2742 case CC_X86RegCall : return "regcall"; 2743 case CC_AAPCS: return "aapcs"; 2744 case CC_AAPCS_VFP: return "aapcs-vfp"; 2745 case CC_IntelOclBicc: return "intel_ocl_bicc"; 2746 case CC_SpirFunction: return "spir_function"; 2747 case CC_OpenCLKernel: return "opencl_kernel"; 2748 case CC_Swift: return "swiftcall"; 2749 case CC_PreserveMost: return "preserve_most"; 2750 case CC_PreserveAll: return "preserve_all"; 2751 } 2752 2753 llvm_unreachable("Invalid calling convention."); 2754 } 2755 2756 FunctionProtoType::FunctionProtoType(QualType result, ArrayRef<QualType> params, 2757 QualType canonical, 2758 const ExtProtoInfo &epi) 2759 : FunctionType(FunctionProto, result, canonical, 2760 result->isDependentType(), 2761 result->isInstantiationDependentType(), 2762 result->isVariablyModifiedType(), 2763 result->containsUnexpandedParameterPack(), epi.ExtInfo), 2764 NumParams(params.size()), 2765 NumExceptions(epi.ExceptionSpec.Exceptions.size()), 2766 ExceptionSpecType(epi.ExceptionSpec.Type), 2767 HasExtParameterInfos(epi.ExtParameterInfos != nullptr), 2768 Variadic(epi.Variadic), HasTrailingReturn(epi.HasTrailingReturn) { 2769 assert(NumParams == params.size() && "function has too many parameters"); 2770 2771 FunctionTypeBits.TypeQuals = epi.TypeQuals; 2772 FunctionTypeBits.RefQualifier = epi.RefQualifier; 2773 2774 // Fill in the trailing argument array. 2775 auto *argSlot = reinterpret_cast<QualType *>(this+1); 2776 for (unsigned i = 0; i != NumParams; ++i) { 2777 if (params[i]->isDependentType()) 2778 setDependent(); 2779 else if (params[i]->isInstantiationDependentType()) 2780 setInstantiationDependent(); 2781 2782 if (params[i]->containsUnexpandedParameterPack()) 2783 setContainsUnexpandedParameterPack(); 2784 2785 argSlot[i] = params[i]; 2786 } 2787 2788 if (getExceptionSpecType() == EST_Dynamic) { 2789 // Fill in the exception array. 2790 QualType *exnSlot = argSlot + NumParams; 2791 unsigned I = 0; 2792 for (QualType ExceptionType : epi.ExceptionSpec.Exceptions) { 2793 // Note that, before C++17, a dependent exception specification does 2794 // *not* make a type dependent; it's not even part of the C++ type 2795 // system. 2796 if (ExceptionType->isInstantiationDependentType()) 2797 setInstantiationDependent(); 2798 2799 if (ExceptionType->containsUnexpandedParameterPack()) 2800 setContainsUnexpandedParameterPack(); 2801 2802 exnSlot[I++] = ExceptionType; 2803 } 2804 } else if (getExceptionSpecType() == EST_ComputedNoexcept) { 2805 // Store the noexcept expression and context. 2806 auto **noexSlot = reinterpret_cast<Expr **>(argSlot + NumParams); 2807 *noexSlot = epi.ExceptionSpec.NoexceptExpr; 2808 2809 if (epi.ExceptionSpec.NoexceptExpr) { 2810 if (epi.ExceptionSpec.NoexceptExpr->isValueDependent() || 2811 epi.ExceptionSpec.NoexceptExpr->isInstantiationDependent()) 2812 setInstantiationDependent(); 2813 2814 if (epi.ExceptionSpec.NoexceptExpr->containsUnexpandedParameterPack()) 2815 setContainsUnexpandedParameterPack(); 2816 } 2817 } else if (getExceptionSpecType() == EST_Uninstantiated) { 2818 // Store the function decl from which we will resolve our 2819 // exception specification. 2820 auto **slot = reinterpret_cast<FunctionDecl **>(argSlot + NumParams); 2821 slot[0] = epi.ExceptionSpec.SourceDecl; 2822 slot[1] = epi.ExceptionSpec.SourceTemplate; 2823 // This exception specification doesn't make the type dependent, because 2824 // it's not instantiated as part of instantiating the type. 2825 } else if (getExceptionSpecType() == EST_Unevaluated) { 2826 // Store the function decl from which we will resolve our 2827 // exception specification. 2828 auto **slot = reinterpret_cast<FunctionDecl **>(argSlot + NumParams); 2829 slot[0] = epi.ExceptionSpec.SourceDecl; 2830 } 2831 2832 // If this is a canonical type, and its exception specification is dependent, 2833 // then it's a dependent type. This only happens in C++17 onwards. 2834 if (isCanonicalUnqualified()) { 2835 if (getExceptionSpecType() == EST_Dynamic || 2836 getExceptionSpecType() == EST_ComputedNoexcept) { 2837 assert(hasDependentExceptionSpec() && "type should not be canonical"); 2838 setDependent(); 2839 } 2840 } else if (getCanonicalTypeInternal()->isDependentType()) { 2841 // Ask our canonical type whether our exception specification was dependent. 2842 setDependent(); 2843 } 2844 2845 if (epi.ExtParameterInfos) { 2846 auto *extParamInfos = 2847 const_cast<ExtParameterInfo *>(getExtParameterInfosBuffer()); 2848 for (unsigned i = 0; i != NumParams; ++i) 2849 extParamInfos[i] = epi.ExtParameterInfos[i]; 2850 } 2851 } 2852 2853 bool FunctionProtoType::hasDependentExceptionSpec() const { 2854 if (Expr *NE = getNoexceptExpr()) 2855 return NE->isValueDependent(); 2856 for (QualType ET : exceptions()) 2857 // A pack expansion with a non-dependent pattern is still dependent, 2858 // because we don't know whether the pattern is in the exception spec 2859 // or not (that depends on whether the pack has 0 expansions). 2860 if (ET->isDependentType() || ET->getAs<PackExpansionType>()) 2861 return true; 2862 return false; 2863 } 2864 2865 bool FunctionProtoType::hasInstantiationDependentExceptionSpec() const { 2866 if (Expr *NE = getNoexceptExpr()) 2867 return NE->isInstantiationDependent(); 2868 for (QualType ET : exceptions()) 2869 if (ET->isInstantiationDependentType()) 2870 return true; 2871 return false; 2872 } 2873 2874 FunctionProtoType::NoexceptResult 2875 FunctionProtoType::getNoexceptSpec(const ASTContext &ctx) const { 2876 ExceptionSpecificationType est = getExceptionSpecType(); 2877 if (est == EST_BasicNoexcept) 2878 return NR_Nothrow; 2879 2880 if (est != EST_ComputedNoexcept) 2881 return NR_NoNoexcept; 2882 2883 Expr *noexceptExpr = getNoexceptExpr(); 2884 if (!noexceptExpr) 2885 return NR_BadNoexcept; 2886 if (noexceptExpr->isValueDependent()) 2887 return NR_Dependent; 2888 2889 llvm::APSInt value; 2890 bool isICE = noexceptExpr->isIntegerConstantExpr(value, ctx, nullptr, 2891 /*evaluated*/false); 2892 (void)isICE; 2893 assert(isICE && "AST should not contain bad noexcept expressions."); 2894 2895 return value.getBoolValue() ? NR_Nothrow : NR_Throw; 2896 } 2897 2898 CanThrowResult FunctionProtoType::canThrow(const ASTContext &Ctx) const { 2899 ExceptionSpecificationType EST = getExceptionSpecType(); 2900 assert(EST != EST_Unevaluated && EST != EST_Uninstantiated); 2901 if (EST == EST_DynamicNone || EST == EST_BasicNoexcept) 2902 return CT_Cannot; 2903 2904 if (EST == EST_Dynamic) { 2905 // A dynamic exception specification is throwing unless every exception 2906 // type is an (unexpanded) pack expansion type. 2907 for (unsigned I = 0, N = NumExceptions; I != N; ++I) 2908 if (!getExceptionType(I)->getAs<PackExpansionType>()) 2909 return CT_Can; 2910 return CT_Dependent; 2911 } 2912 2913 if (EST != EST_ComputedNoexcept) 2914 return CT_Can; 2915 2916 NoexceptResult NR = getNoexceptSpec(Ctx); 2917 if (NR == NR_Dependent) 2918 return CT_Dependent; 2919 return NR == NR_Nothrow ? CT_Cannot : CT_Can; 2920 } 2921 2922 bool FunctionProtoType::isTemplateVariadic() const { 2923 for (unsigned ArgIdx = getNumParams(); ArgIdx; --ArgIdx) 2924 if (isa<PackExpansionType>(getParamType(ArgIdx - 1))) 2925 return true; 2926 2927 return false; 2928 } 2929 2930 void FunctionProtoType::Profile(llvm::FoldingSetNodeID &ID, QualType Result, 2931 const QualType *ArgTys, unsigned NumParams, 2932 const ExtProtoInfo &epi, 2933 const ASTContext &Context, bool Canonical) { 2934 // We have to be careful not to get ambiguous profile encodings. 2935 // Note that valid type pointers are never ambiguous with anything else. 2936 // 2937 // The encoding grammar begins: 2938 // type type* bool int bool 2939 // If that final bool is true, then there is a section for the EH spec: 2940 // bool type* 2941 // This is followed by an optional "consumed argument" section of the 2942 // same length as the first type sequence: 2943 // bool* 2944 // Finally, we have the ext info and trailing return type flag: 2945 // int bool 2946 // 2947 // There is no ambiguity between the consumed arguments and an empty EH 2948 // spec because of the leading 'bool' which unambiguously indicates 2949 // whether the following bool is the EH spec or part of the arguments. 2950 2951 ID.AddPointer(Result.getAsOpaquePtr()); 2952 for (unsigned i = 0; i != NumParams; ++i) 2953 ID.AddPointer(ArgTys[i].getAsOpaquePtr()); 2954 // This method is relatively performance sensitive, so as a performance 2955 // shortcut, use one AddInteger call instead of four for the next four 2956 // fields. 2957 assert(!(unsigned(epi.Variadic) & ~1) && 2958 !(unsigned(epi.TypeQuals) & ~255) && 2959 !(unsigned(epi.RefQualifier) & ~3) && 2960 !(unsigned(epi.ExceptionSpec.Type) & ~15) && 2961 "Values larger than expected."); 2962 ID.AddInteger(unsigned(epi.Variadic) + 2963 (epi.TypeQuals << 1) + 2964 (epi.RefQualifier << 9) + 2965 (epi.ExceptionSpec.Type << 11)); 2966 if (epi.ExceptionSpec.Type == EST_Dynamic) { 2967 for (QualType Ex : epi.ExceptionSpec.Exceptions) 2968 ID.AddPointer(Ex.getAsOpaquePtr()); 2969 } else if (epi.ExceptionSpec.Type == EST_ComputedNoexcept && 2970 epi.ExceptionSpec.NoexceptExpr) { 2971 epi.ExceptionSpec.NoexceptExpr->Profile(ID, Context, Canonical); 2972 } else if (epi.ExceptionSpec.Type == EST_Uninstantiated || 2973 epi.ExceptionSpec.Type == EST_Unevaluated) { 2974 ID.AddPointer(epi.ExceptionSpec.SourceDecl->getCanonicalDecl()); 2975 } 2976 if (epi.ExtParameterInfos) { 2977 for (unsigned i = 0; i != NumParams; ++i) 2978 ID.AddInteger(epi.ExtParameterInfos[i].getOpaqueValue()); 2979 } 2980 epi.ExtInfo.Profile(ID); 2981 ID.AddBoolean(epi.HasTrailingReturn); 2982 } 2983 2984 void FunctionProtoType::Profile(llvm::FoldingSetNodeID &ID, 2985 const ASTContext &Ctx) { 2986 Profile(ID, getReturnType(), param_type_begin(), NumParams, getExtProtoInfo(), 2987 Ctx, isCanonicalUnqualified()); 2988 } 2989 2990 QualType TypedefType::desugar() const { 2991 return getDecl()->getUnderlyingType(); 2992 } 2993 2994 TypeOfExprType::TypeOfExprType(Expr *E, QualType can) 2995 : Type(TypeOfExpr, can, E->isTypeDependent(), 2996 E->isInstantiationDependent(), 2997 E->getType()->isVariablyModifiedType(), 2998 E->containsUnexpandedParameterPack()), 2999 TOExpr(E) {} 3000 3001 bool TypeOfExprType::isSugared() const { 3002 return !TOExpr->isTypeDependent(); 3003 } 3004 3005 QualType TypeOfExprType::desugar() const { 3006 if (isSugared()) 3007 return getUnderlyingExpr()->getType(); 3008 3009 return QualType(this, 0); 3010 } 3011 3012 void DependentTypeOfExprType::Profile(llvm::FoldingSetNodeID &ID, 3013 const ASTContext &Context, Expr *E) { 3014 E->Profile(ID, Context, true); 3015 } 3016 3017 DecltypeType::DecltypeType(Expr *E, QualType underlyingType, QualType can) 3018 // C++11 [temp.type]p2: "If an expression e involves a template parameter, 3019 // decltype(e) denotes a unique dependent type." Hence a decltype type is 3020 // type-dependent even if its expression is only instantiation-dependent. 3021 : Type(Decltype, can, E->isInstantiationDependent(), 3022 E->isInstantiationDependent(), 3023 E->getType()->isVariablyModifiedType(), 3024 E->containsUnexpandedParameterPack()), 3025 E(E), UnderlyingType(underlyingType) {} 3026 3027 bool DecltypeType::isSugared() const { return !E->isInstantiationDependent(); } 3028 3029 QualType DecltypeType::desugar() const { 3030 if (isSugared()) 3031 return getUnderlyingType(); 3032 3033 return QualType(this, 0); 3034 } 3035 3036 DependentDecltypeType::DependentDecltypeType(const ASTContext &Context, Expr *E) 3037 : DecltypeType(E, Context.DependentTy), Context(Context) {} 3038 3039 void DependentDecltypeType::Profile(llvm::FoldingSetNodeID &ID, 3040 const ASTContext &Context, Expr *E) { 3041 E->Profile(ID, Context, true); 3042 } 3043 3044 UnaryTransformType::UnaryTransformType(QualType BaseType, 3045 QualType UnderlyingType, 3046 UTTKind UKind, 3047 QualType CanonicalType) 3048 : Type(UnaryTransform, CanonicalType, BaseType->isDependentType(), 3049 BaseType->isInstantiationDependentType(), 3050 BaseType->isVariablyModifiedType(), 3051 BaseType->containsUnexpandedParameterPack()), 3052 BaseType(BaseType), UnderlyingType(UnderlyingType), UKind(UKind) {} 3053 3054 DependentUnaryTransformType::DependentUnaryTransformType(const ASTContext &C, 3055 QualType BaseType, 3056 UTTKind UKind) 3057 : UnaryTransformType(BaseType, C.DependentTy, UKind, QualType()) {} 3058 3059 TagType::TagType(TypeClass TC, const TagDecl *D, QualType can) 3060 : Type(TC, can, D->isDependentType(), 3061 /*InstantiationDependent=*/D->isDependentType(), 3062 /*VariablyModified=*/false, 3063 /*ContainsUnexpandedParameterPack=*/false), 3064 decl(const_cast<TagDecl*>(D)) {} 3065 3066 static TagDecl *getInterestingTagDecl(TagDecl *decl) { 3067 for (auto I : decl->redecls()) { 3068 if (I->isCompleteDefinition() || I->isBeingDefined()) 3069 return I; 3070 } 3071 // If there's no definition (not even in progress), return what we have. 3072 return decl; 3073 } 3074 3075 TagDecl *TagType::getDecl() const { 3076 return getInterestingTagDecl(decl); 3077 } 3078 3079 bool TagType::isBeingDefined() const { 3080 return getDecl()->isBeingDefined(); 3081 } 3082 3083 bool RecordType::hasConstFields() const { 3084 for (FieldDecl *FD : getDecl()->fields()) { 3085 QualType FieldTy = FD->getType(); 3086 if (FieldTy.isConstQualified()) 3087 return true; 3088 FieldTy = FieldTy.getCanonicalType(); 3089 if (const auto *FieldRecTy = FieldTy->getAs<RecordType>()) 3090 if (FieldRecTy->hasConstFields()) 3091 return true; 3092 } 3093 return false; 3094 } 3095 3096 bool AttributedType::isQualifier() const { 3097 switch (getAttrKind()) { 3098 // These are type qualifiers in the traditional C sense: they annotate 3099 // something about a specific value/variable of a type. (They aren't 3100 // always part of the canonical type, though.) 3101 case AttributedType::attr_address_space: 3102 case AttributedType::attr_objc_gc: 3103 case AttributedType::attr_objc_ownership: 3104 case AttributedType::attr_objc_inert_unsafe_unretained: 3105 case AttributedType::attr_nonnull: 3106 case AttributedType::attr_nullable: 3107 case AttributedType::attr_null_unspecified: 3108 return true; 3109 3110 // These aren't qualifiers; they rewrite the modified type to be a 3111 // semantically different type. 3112 case AttributedType::attr_regparm: 3113 case AttributedType::attr_vector_size: 3114 case AttributedType::attr_neon_vector_type: 3115 case AttributedType::attr_neon_polyvector_type: 3116 case AttributedType::attr_pcs: 3117 case AttributedType::attr_pcs_vfp: 3118 case AttributedType::attr_noreturn: 3119 case AttributedType::attr_cdecl: 3120 case AttributedType::attr_fastcall: 3121 case AttributedType::attr_stdcall: 3122 case AttributedType::attr_thiscall: 3123 case AttributedType::attr_regcall: 3124 case AttributedType::attr_pascal: 3125 case AttributedType::attr_swiftcall: 3126 case AttributedType::attr_vectorcall: 3127 case AttributedType::attr_inteloclbicc: 3128 case AttributedType::attr_preserve_most: 3129 case AttributedType::attr_preserve_all: 3130 case AttributedType::attr_ms_abi: 3131 case AttributedType::attr_sysv_abi: 3132 case AttributedType::attr_ptr32: 3133 case AttributedType::attr_ptr64: 3134 case AttributedType::attr_sptr: 3135 case AttributedType::attr_uptr: 3136 case AttributedType::attr_objc_kindof: 3137 case AttributedType::attr_ns_returns_retained: 3138 case AttributedType::attr_nocf_check: 3139 return false; 3140 } 3141 llvm_unreachable("bad attributed type kind"); 3142 } 3143 3144 bool AttributedType::isMSTypeSpec() const { 3145 switch (getAttrKind()) { 3146 default: return false; 3147 case attr_ptr32: 3148 case attr_ptr64: 3149 case attr_sptr: 3150 case attr_uptr: 3151 return true; 3152 } 3153 llvm_unreachable("invalid attr kind"); 3154 } 3155 3156 bool AttributedType::isCallingConv() const { 3157 switch (getAttrKind()) { 3158 case attr_ptr32: 3159 case attr_ptr64: 3160 case attr_sptr: 3161 case attr_uptr: 3162 case attr_address_space: 3163 case attr_regparm: 3164 case attr_vector_size: 3165 case attr_neon_vector_type: 3166 case attr_neon_polyvector_type: 3167 case attr_objc_gc: 3168 case attr_objc_ownership: 3169 case attr_objc_inert_unsafe_unretained: 3170 case attr_noreturn: 3171 case attr_nonnull: 3172 case attr_ns_returns_retained: 3173 case attr_nullable: 3174 case attr_null_unspecified: 3175 case attr_objc_kindof: 3176 case attr_nocf_check: 3177 return false; 3178 3179 case attr_pcs: 3180 case attr_pcs_vfp: 3181 case attr_cdecl: 3182 case attr_fastcall: 3183 case attr_stdcall: 3184 case attr_thiscall: 3185 case attr_regcall: 3186 case attr_swiftcall: 3187 case attr_vectorcall: 3188 case attr_pascal: 3189 case attr_ms_abi: 3190 case attr_sysv_abi: 3191 case attr_inteloclbicc: 3192 case attr_preserve_most: 3193 case attr_preserve_all: 3194 return true; 3195 } 3196 llvm_unreachable("invalid attr kind"); 3197 } 3198 3199 CXXRecordDecl *InjectedClassNameType::getDecl() const { 3200 return cast<CXXRecordDecl>(getInterestingTagDecl(Decl)); 3201 } 3202 3203 IdentifierInfo *TemplateTypeParmType::getIdentifier() const { 3204 return isCanonicalUnqualified() ? nullptr : getDecl()->getIdentifier(); 3205 } 3206 3207 SubstTemplateTypeParmPackType:: 3208 SubstTemplateTypeParmPackType(const TemplateTypeParmType *Param, 3209 QualType Canon, 3210 const TemplateArgument &ArgPack) 3211 : Type(SubstTemplateTypeParmPack, Canon, true, true, false, true), 3212 Replaced(Param), 3213 Arguments(ArgPack.pack_begin()), NumArguments(ArgPack.pack_size()) {} 3214 3215 TemplateArgument SubstTemplateTypeParmPackType::getArgumentPack() const { 3216 return TemplateArgument(llvm::makeArrayRef(Arguments, NumArguments)); 3217 } 3218 3219 void SubstTemplateTypeParmPackType::Profile(llvm::FoldingSetNodeID &ID) { 3220 Profile(ID, getReplacedParameter(), getArgumentPack()); 3221 } 3222 3223 void SubstTemplateTypeParmPackType::Profile(llvm::FoldingSetNodeID &ID, 3224 const TemplateTypeParmType *Replaced, 3225 const TemplateArgument &ArgPack) { 3226 ID.AddPointer(Replaced); 3227 ID.AddInteger(ArgPack.pack_size()); 3228 for (const auto &P : ArgPack.pack_elements()) 3229 ID.AddPointer(P.getAsType().getAsOpaquePtr()); 3230 } 3231 3232 bool TemplateSpecializationType:: 3233 anyDependentTemplateArguments(const TemplateArgumentListInfo &Args, 3234 bool &InstantiationDependent) { 3235 return anyDependentTemplateArguments(Args.arguments(), 3236 InstantiationDependent); 3237 } 3238 3239 bool TemplateSpecializationType:: 3240 anyDependentTemplateArguments(ArrayRef<TemplateArgumentLoc> Args, 3241 bool &InstantiationDependent) { 3242 for (const TemplateArgumentLoc &ArgLoc : Args) { 3243 if (ArgLoc.getArgument().isDependent()) { 3244 InstantiationDependent = true; 3245 return true; 3246 } 3247 3248 if (ArgLoc.getArgument().isInstantiationDependent()) 3249 InstantiationDependent = true; 3250 } 3251 return false; 3252 } 3253 3254 TemplateSpecializationType:: 3255 TemplateSpecializationType(TemplateName T, 3256 ArrayRef<TemplateArgument> Args, 3257 QualType Canon, QualType AliasedType) 3258 : Type(TemplateSpecialization, 3259 Canon.isNull()? QualType(this, 0) : Canon, 3260 Canon.isNull()? true : Canon->isDependentType(), 3261 Canon.isNull()? true : Canon->isInstantiationDependentType(), 3262 false, 3263 T.containsUnexpandedParameterPack()), 3264 Template(T), NumArgs(Args.size()), TypeAlias(!AliasedType.isNull()) { 3265 assert(!T.getAsDependentTemplateName() && 3266 "Use DependentTemplateSpecializationType for dependent template-name"); 3267 assert((T.getKind() == TemplateName::Template || 3268 T.getKind() == TemplateName::SubstTemplateTemplateParm || 3269 T.getKind() == TemplateName::SubstTemplateTemplateParmPack) && 3270 "Unexpected template name for TemplateSpecializationType"); 3271 3272 auto *TemplateArgs = reinterpret_cast<TemplateArgument *>(this + 1); 3273 for (const TemplateArgument &Arg : Args) { 3274 // Update instantiation-dependent and variably-modified bits. 3275 // If the canonical type exists and is non-dependent, the template 3276 // specialization type can be non-dependent even if one of the type 3277 // arguments is. Given: 3278 // template<typename T> using U = int; 3279 // U<T> is always non-dependent, irrespective of the type T. 3280 // However, U<Ts> contains an unexpanded parameter pack, even though 3281 // its expansion (and thus its desugared type) doesn't. 3282 if (Arg.isInstantiationDependent()) 3283 setInstantiationDependent(); 3284 if (Arg.getKind() == TemplateArgument::Type && 3285 Arg.getAsType()->isVariablyModifiedType()) 3286 setVariablyModified(); 3287 if (Arg.containsUnexpandedParameterPack()) 3288 setContainsUnexpandedParameterPack(); 3289 new (TemplateArgs++) TemplateArgument(Arg); 3290 } 3291 3292 // Store the aliased type if this is a type alias template specialization. 3293 if (TypeAlias) { 3294 auto *Begin = reinterpret_cast<TemplateArgument *>(this + 1); 3295 *reinterpret_cast<QualType*>(Begin + getNumArgs()) = AliasedType; 3296 } 3297 } 3298 3299 void 3300 TemplateSpecializationType::Profile(llvm::FoldingSetNodeID &ID, 3301 TemplateName T, 3302 ArrayRef<TemplateArgument> Args, 3303 const ASTContext &Context) { 3304 T.Profile(ID); 3305 for (const TemplateArgument &Arg : Args) 3306 Arg.Profile(ID, Context); 3307 } 3308 3309 QualType 3310 QualifierCollector::apply(const ASTContext &Context, QualType QT) const { 3311 if (!hasNonFastQualifiers()) 3312 return QT.withFastQualifiers(getFastQualifiers()); 3313 3314 return Context.getQualifiedType(QT, *this); 3315 } 3316 3317 QualType 3318 QualifierCollector::apply(const ASTContext &Context, const Type *T) const { 3319 if (!hasNonFastQualifiers()) 3320 return QualType(T, getFastQualifiers()); 3321 3322 return Context.getQualifiedType(T, *this); 3323 } 3324 3325 void ObjCObjectTypeImpl::Profile(llvm::FoldingSetNodeID &ID, 3326 QualType BaseType, 3327 ArrayRef<QualType> typeArgs, 3328 ArrayRef<ObjCProtocolDecl *> protocols, 3329 bool isKindOf) { 3330 ID.AddPointer(BaseType.getAsOpaquePtr()); 3331 ID.AddInteger(typeArgs.size()); 3332 for (auto typeArg : typeArgs) 3333 ID.AddPointer(typeArg.getAsOpaquePtr()); 3334 ID.AddInteger(protocols.size()); 3335 for (auto proto : protocols) 3336 ID.AddPointer(proto); 3337 ID.AddBoolean(isKindOf); 3338 } 3339 3340 void ObjCObjectTypeImpl::Profile(llvm::FoldingSetNodeID &ID) { 3341 Profile(ID, getBaseType(), getTypeArgsAsWritten(), 3342 llvm::makeArrayRef(qual_begin(), getNumProtocols()), 3343 isKindOfTypeAsWritten()); 3344 } 3345 3346 void ObjCTypeParamType::Profile(llvm::FoldingSetNodeID &ID, 3347 const ObjCTypeParamDecl *OTPDecl, 3348 ArrayRef<ObjCProtocolDecl *> protocols) { 3349 ID.AddPointer(OTPDecl); 3350 ID.AddInteger(protocols.size()); 3351 for (auto proto : protocols) 3352 ID.AddPointer(proto); 3353 } 3354 3355 void ObjCTypeParamType::Profile(llvm::FoldingSetNodeID &ID) { 3356 Profile(ID, getDecl(), 3357 llvm::makeArrayRef(qual_begin(), getNumProtocols())); 3358 } 3359 3360 namespace { 3361 3362 /// \brief The cached properties of a type. 3363 class CachedProperties { 3364 Linkage L; 3365 bool local; 3366 3367 public: 3368 CachedProperties(Linkage L, bool local) : L(L), local(local) {} 3369 3370 Linkage getLinkage() const { return L; } 3371 bool hasLocalOrUnnamedType() const { return local; } 3372 3373 friend CachedProperties merge(CachedProperties L, CachedProperties R) { 3374 Linkage MergedLinkage = minLinkage(L.L, R.L); 3375 return CachedProperties(MergedLinkage, 3376 L.hasLocalOrUnnamedType() | R.hasLocalOrUnnamedType()); 3377 } 3378 }; 3379 3380 } // namespace 3381 3382 static CachedProperties computeCachedProperties(const Type *T); 3383 3384 namespace clang { 3385 3386 /// The type-property cache. This is templated so as to be 3387 /// instantiated at an internal type to prevent unnecessary symbol 3388 /// leakage. 3389 template <class Private> class TypePropertyCache { 3390 public: 3391 static CachedProperties get(QualType T) { 3392 return get(T.getTypePtr()); 3393 } 3394 3395 static CachedProperties get(const Type *T) { 3396 ensure(T); 3397 return CachedProperties(T->TypeBits.getLinkage(), 3398 T->TypeBits.hasLocalOrUnnamedType()); 3399 } 3400 3401 static void ensure(const Type *T) { 3402 // If the cache is valid, we're okay. 3403 if (T->TypeBits.isCacheValid()) return; 3404 3405 // If this type is non-canonical, ask its canonical type for the 3406 // relevant information. 3407 if (!T->isCanonicalUnqualified()) { 3408 const Type *CT = T->getCanonicalTypeInternal().getTypePtr(); 3409 ensure(CT); 3410 T->TypeBits.CacheValid = true; 3411 T->TypeBits.CachedLinkage = CT->TypeBits.CachedLinkage; 3412 T->TypeBits.CachedLocalOrUnnamed = CT->TypeBits.CachedLocalOrUnnamed; 3413 return; 3414 } 3415 3416 // Compute the cached properties and then set the cache. 3417 CachedProperties Result = computeCachedProperties(T); 3418 T->TypeBits.CacheValid = true; 3419 T->TypeBits.CachedLinkage = Result.getLinkage(); 3420 T->TypeBits.CachedLocalOrUnnamed = Result.hasLocalOrUnnamedType(); 3421 } 3422 }; 3423 3424 } // namespace clang 3425 3426 // Instantiate the friend template at a private class. In a 3427 // reasonable implementation, these symbols will be internal. 3428 // It is terrible that this is the best way to accomplish this. 3429 namespace { 3430 3431 class Private {}; 3432 3433 } // namespace 3434 3435 using Cache = TypePropertyCache<Private>; 3436 3437 static CachedProperties computeCachedProperties(const Type *T) { 3438 switch (T->getTypeClass()) { 3439 #define TYPE(Class,Base) 3440 #define NON_CANONICAL_TYPE(Class,Base) case Type::Class: 3441 #include "clang/AST/TypeNodes.def" 3442 llvm_unreachable("didn't expect a non-canonical type here"); 3443 3444 #define TYPE(Class,Base) 3445 #define DEPENDENT_TYPE(Class,Base) case Type::Class: 3446 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class,Base) case Type::Class: 3447 #include "clang/AST/TypeNodes.def" 3448 // Treat instantiation-dependent types as external. 3449 assert(T->isInstantiationDependentType()); 3450 return CachedProperties(ExternalLinkage, false); 3451 3452 case Type::Auto: 3453 case Type::DeducedTemplateSpecialization: 3454 // Give non-deduced 'auto' types external linkage. We should only see them 3455 // here in error recovery. 3456 return CachedProperties(ExternalLinkage, false); 3457 3458 case Type::Builtin: 3459 // C++ [basic.link]p8: 3460 // A type is said to have linkage if and only if: 3461 // - it is a fundamental type (3.9.1); or 3462 return CachedProperties(ExternalLinkage, false); 3463 3464 case Type::Record: 3465 case Type::Enum: { 3466 const TagDecl *Tag = cast<TagType>(T)->getDecl(); 3467 3468 // C++ [basic.link]p8: 3469 // - it is a class or enumeration type that is named (or has a name 3470 // for linkage purposes (7.1.3)) and the name has linkage; or 3471 // - it is a specialization of a class template (14); or 3472 Linkage L = Tag->getLinkageInternal(); 3473 bool IsLocalOrUnnamed = 3474 Tag->getDeclContext()->isFunctionOrMethod() || 3475 !Tag->hasNameForLinkage(); 3476 return CachedProperties(L, IsLocalOrUnnamed); 3477 } 3478 3479 // C++ [basic.link]p8: 3480 // - it is a compound type (3.9.2) other than a class or enumeration, 3481 // compounded exclusively from types that have linkage; or 3482 case Type::Complex: 3483 return Cache::get(cast<ComplexType>(T)->getElementType()); 3484 case Type::Pointer: 3485 return Cache::get(cast<PointerType>(T)->getPointeeType()); 3486 case Type::BlockPointer: 3487 return Cache::get(cast<BlockPointerType>(T)->getPointeeType()); 3488 case Type::LValueReference: 3489 case Type::RValueReference: 3490 return Cache::get(cast<ReferenceType>(T)->getPointeeType()); 3491 case Type::MemberPointer: { 3492 const auto *MPT = cast<MemberPointerType>(T); 3493 return merge(Cache::get(MPT->getClass()), 3494 Cache::get(MPT->getPointeeType())); 3495 } 3496 case Type::ConstantArray: 3497 case Type::IncompleteArray: 3498 case Type::VariableArray: 3499 return Cache::get(cast<ArrayType>(T)->getElementType()); 3500 case Type::Vector: 3501 case Type::ExtVector: 3502 return Cache::get(cast<VectorType>(T)->getElementType()); 3503 case Type::FunctionNoProto: 3504 return Cache::get(cast<FunctionType>(T)->getReturnType()); 3505 case Type::FunctionProto: { 3506 const auto *FPT = cast<FunctionProtoType>(T); 3507 CachedProperties result = Cache::get(FPT->getReturnType()); 3508 for (const auto &ai : FPT->param_types()) 3509 result = merge(result, Cache::get(ai)); 3510 return result; 3511 } 3512 case Type::ObjCInterface: { 3513 Linkage L = cast<ObjCInterfaceType>(T)->getDecl()->getLinkageInternal(); 3514 return CachedProperties(L, false); 3515 } 3516 case Type::ObjCObject: 3517 return Cache::get(cast<ObjCObjectType>(T)->getBaseType()); 3518 case Type::ObjCObjectPointer: 3519 return Cache::get(cast<ObjCObjectPointerType>(T)->getPointeeType()); 3520 case Type::Atomic: 3521 return Cache::get(cast<AtomicType>(T)->getValueType()); 3522 case Type::Pipe: 3523 return Cache::get(cast<PipeType>(T)->getElementType()); 3524 } 3525 3526 llvm_unreachable("unhandled type class"); 3527 } 3528 3529 /// \brief Determine the linkage of this type. 3530 Linkage Type::getLinkage() const { 3531 Cache::ensure(this); 3532 return TypeBits.getLinkage(); 3533 } 3534 3535 bool Type::hasUnnamedOrLocalType() const { 3536 Cache::ensure(this); 3537 return TypeBits.hasLocalOrUnnamedType(); 3538 } 3539 3540 LinkageInfo LinkageComputer::computeTypeLinkageInfo(const Type *T) { 3541 switch (T->getTypeClass()) { 3542 #define TYPE(Class,Base) 3543 #define NON_CANONICAL_TYPE(Class,Base) case Type::Class: 3544 #include "clang/AST/TypeNodes.def" 3545 llvm_unreachable("didn't expect a non-canonical type here"); 3546 3547 #define TYPE(Class,Base) 3548 #define DEPENDENT_TYPE(Class,Base) case Type::Class: 3549 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class,Base) case Type::Class: 3550 #include "clang/AST/TypeNodes.def" 3551 // Treat instantiation-dependent types as external. 3552 assert(T->isInstantiationDependentType()); 3553 return LinkageInfo::external(); 3554 3555 case Type::Builtin: 3556 return LinkageInfo::external(); 3557 3558 case Type::Auto: 3559 case Type::DeducedTemplateSpecialization: 3560 return LinkageInfo::external(); 3561 3562 case Type::Record: 3563 case Type::Enum: 3564 return getDeclLinkageAndVisibility(cast<TagType>(T)->getDecl()); 3565 3566 case Type::Complex: 3567 return computeTypeLinkageInfo(cast<ComplexType>(T)->getElementType()); 3568 case Type::Pointer: 3569 return computeTypeLinkageInfo(cast<PointerType>(T)->getPointeeType()); 3570 case Type::BlockPointer: 3571 return computeTypeLinkageInfo(cast<BlockPointerType>(T)->getPointeeType()); 3572 case Type::LValueReference: 3573 case Type::RValueReference: 3574 return computeTypeLinkageInfo(cast<ReferenceType>(T)->getPointeeType()); 3575 case Type::MemberPointer: { 3576 const auto *MPT = cast<MemberPointerType>(T); 3577 LinkageInfo LV = computeTypeLinkageInfo(MPT->getClass()); 3578 LV.merge(computeTypeLinkageInfo(MPT->getPointeeType())); 3579 return LV; 3580 } 3581 case Type::ConstantArray: 3582 case Type::IncompleteArray: 3583 case Type::VariableArray: 3584 return computeTypeLinkageInfo(cast<ArrayType>(T)->getElementType()); 3585 case Type::Vector: 3586 case Type::ExtVector: 3587 return computeTypeLinkageInfo(cast<VectorType>(T)->getElementType()); 3588 case Type::FunctionNoProto: 3589 return computeTypeLinkageInfo(cast<FunctionType>(T)->getReturnType()); 3590 case Type::FunctionProto: { 3591 const auto *FPT = cast<FunctionProtoType>(T); 3592 LinkageInfo LV = computeTypeLinkageInfo(FPT->getReturnType()); 3593 for (const auto &ai : FPT->param_types()) 3594 LV.merge(computeTypeLinkageInfo(ai)); 3595 return LV; 3596 } 3597 case Type::ObjCInterface: 3598 return getDeclLinkageAndVisibility(cast<ObjCInterfaceType>(T)->getDecl()); 3599 case Type::ObjCObject: 3600 return computeTypeLinkageInfo(cast<ObjCObjectType>(T)->getBaseType()); 3601 case Type::ObjCObjectPointer: 3602 return computeTypeLinkageInfo( 3603 cast<ObjCObjectPointerType>(T)->getPointeeType()); 3604 case Type::Atomic: 3605 return computeTypeLinkageInfo(cast<AtomicType>(T)->getValueType()); 3606 case Type::Pipe: 3607 return computeTypeLinkageInfo(cast<PipeType>(T)->getElementType()); 3608 } 3609 3610 llvm_unreachable("unhandled type class"); 3611 } 3612 3613 bool Type::isLinkageValid() const { 3614 if (!TypeBits.isCacheValid()) 3615 return true; 3616 3617 Linkage L = LinkageComputer{} 3618 .computeTypeLinkageInfo(getCanonicalTypeInternal()) 3619 .getLinkage(); 3620 return L == TypeBits.getLinkage(); 3621 } 3622 3623 LinkageInfo LinkageComputer::getTypeLinkageAndVisibility(const Type *T) { 3624 if (!T->isCanonicalUnqualified()) 3625 return computeTypeLinkageInfo(T->getCanonicalTypeInternal()); 3626 3627 LinkageInfo LV = computeTypeLinkageInfo(T); 3628 assert(LV.getLinkage() == T->getLinkage()); 3629 return LV; 3630 } 3631 3632 LinkageInfo Type::getLinkageAndVisibility() const { 3633 return LinkageComputer{}.getTypeLinkageAndVisibility(this); 3634 } 3635 3636 Optional<NullabilityKind> Type::getNullability(const ASTContext &context) const { 3637 QualType type(this, 0); 3638 do { 3639 // Check whether this is an attributed type with nullability 3640 // information. 3641 if (auto attributed = dyn_cast<AttributedType>(type.getTypePtr())) { 3642 if (auto nullability = attributed->getImmediateNullability()) 3643 return nullability; 3644 } 3645 3646 // Desugar the type. If desugaring does nothing, we're done. 3647 QualType desugared = type.getSingleStepDesugaredType(context); 3648 if (desugared.getTypePtr() == type.getTypePtr()) 3649 return None; 3650 3651 type = desugared; 3652 } while (true); 3653 } 3654 3655 bool Type::canHaveNullability(bool ResultIfUnknown) const { 3656 QualType type = getCanonicalTypeInternal(); 3657 3658 switch (type->getTypeClass()) { 3659 // We'll only see canonical types here. 3660 #define NON_CANONICAL_TYPE(Class, Parent) \ 3661 case Type::Class: \ 3662 llvm_unreachable("non-canonical type"); 3663 #define TYPE(Class, Parent) 3664 #include "clang/AST/TypeNodes.def" 3665 3666 // Pointer types. 3667 case Type::Pointer: 3668 case Type::BlockPointer: 3669 case Type::MemberPointer: 3670 case Type::ObjCObjectPointer: 3671 return true; 3672 3673 // Dependent types that could instantiate to pointer types. 3674 case Type::UnresolvedUsing: 3675 case Type::TypeOfExpr: 3676 case Type::TypeOf: 3677 case Type::Decltype: 3678 case Type::UnaryTransform: 3679 case Type::TemplateTypeParm: 3680 case Type::SubstTemplateTypeParmPack: 3681 case Type::DependentName: 3682 case Type::DependentTemplateSpecialization: 3683 case Type::Auto: 3684 return ResultIfUnknown; 3685 3686 // Dependent template specializations can instantiate to pointer 3687 // types unless they're known to be specializations of a class 3688 // template. 3689 case Type::TemplateSpecialization: 3690 if (TemplateDecl *templateDecl 3691 = cast<TemplateSpecializationType>(type.getTypePtr()) 3692 ->getTemplateName().getAsTemplateDecl()) { 3693 if (isa<ClassTemplateDecl>(templateDecl)) 3694 return false; 3695 } 3696 return ResultIfUnknown; 3697 3698 case Type::Builtin: 3699 switch (cast<BuiltinType>(type.getTypePtr())->getKind()) { 3700 // Signed, unsigned, and floating-point types cannot have nullability. 3701 #define SIGNED_TYPE(Id, SingletonId) case BuiltinType::Id: 3702 #define UNSIGNED_TYPE(Id, SingletonId) case BuiltinType::Id: 3703 #define FLOATING_TYPE(Id, SingletonId) case BuiltinType::Id: 3704 #define BUILTIN_TYPE(Id, SingletonId) 3705 #include "clang/AST/BuiltinTypes.def" 3706 return false; 3707 3708 // Dependent types that could instantiate to a pointer type. 3709 case BuiltinType::Dependent: 3710 case BuiltinType::Overload: 3711 case BuiltinType::BoundMember: 3712 case BuiltinType::PseudoObject: 3713 case BuiltinType::UnknownAny: 3714 case BuiltinType::ARCUnbridgedCast: 3715 return ResultIfUnknown; 3716 3717 case BuiltinType::Void: 3718 case BuiltinType::ObjCId: 3719 case BuiltinType::ObjCClass: 3720 case BuiltinType::ObjCSel: 3721 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \ 3722 case BuiltinType::Id: 3723 #include "clang/Basic/OpenCLImageTypes.def" 3724 case BuiltinType::OCLSampler: 3725 case BuiltinType::OCLEvent: 3726 case BuiltinType::OCLClkEvent: 3727 case BuiltinType::OCLQueue: 3728 case BuiltinType::OCLReserveID: 3729 case BuiltinType::BuiltinFn: 3730 case BuiltinType::NullPtr: 3731 case BuiltinType::OMPArraySection: 3732 return false; 3733 } 3734 llvm_unreachable("unknown builtin type"); 3735 3736 // Non-pointer types. 3737 case Type::Complex: 3738 case Type::LValueReference: 3739 case Type::RValueReference: 3740 case Type::ConstantArray: 3741 case Type::IncompleteArray: 3742 case Type::VariableArray: 3743 case Type::DependentSizedArray: 3744 case Type::DependentSizedExtVector: 3745 case Type::Vector: 3746 case Type::ExtVector: 3747 case Type::DependentAddressSpace: 3748 case Type::FunctionProto: 3749 case Type::FunctionNoProto: 3750 case Type::Record: 3751 case Type::DeducedTemplateSpecialization: 3752 case Type::Enum: 3753 case Type::InjectedClassName: 3754 case Type::PackExpansion: 3755 case Type::ObjCObject: 3756 case Type::ObjCInterface: 3757 case Type::Atomic: 3758 case Type::Pipe: 3759 return false; 3760 } 3761 llvm_unreachable("bad type kind!"); 3762 } 3763 3764 llvm::Optional<NullabilityKind> AttributedType::getImmediateNullability() const { 3765 if (getAttrKind() == AttributedType::attr_nonnull) 3766 return NullabilityKind::NonNull; 3767 if (getAttrKind() == AttributedType::attr_nullable) 3768 return NullabilityKind::Nullable; 3769 if (getAttrKind() == AttributedType::attr_null_unspecified) 3770 return NullabilityKind::Unspecified; 3771 return None; 3772 } 3773 3774 Optional<NullabilityKind> AttributedType::stripOuterNullability(QualType &T) { 3775 if (auto attributed = dyn_cast<AttributedType>(T.getTypePtr())) { 3776 if (auto nullability = attributed->getImmediateNullability()) { 3777 T = attributed->getModifiedType(); 3778 return nullability; 3779 } 3780 } 3781 3782 return None; 3783 } 3784 3785 bool Type::isBlockCompatibleObjCPointerType(ASTContext &ctx) const { 3786 const auto *objcPtr = getAs<ObjCObjectPointerType>(); 3787 if (!objcPtr) 3788 return false; 3789 3790 if (objcPtr->isObjCIdType()) { 3791 // id is always okay. 3792 return true; 3793 } 3794 3795 // Blocks are NSObjects. 3796 if (ObjCInterfaceDecl *iface = objcPtr->getInterfaceDecl()) { 3797 if (iface->getIdentifier() != ctx.getNSObjectName()) 3798 return false; 3799 3800 // Continue to check qualifiers, below. 3801 } else if (objcPtr->isObjCQualifiedIdType()) { 3802 // Continue to check qualifiers, below. 3803 } else { 3804 return false; 3805 } 3806 3807 // Check protocol qualifiers. 3808 for (ObjCProtocolDecl *proto : objcPtr->quals()) { 3809 // Blocks conform to NSObject and NSCopying. 3810 if (proto->getIdentifier() != ctx.getNSObjectName() && 3811 proto->getIdentifier() != ctx.getNSCopyingName()) 3812 return false; 3813 } 3814 3815 return true; 3816 } 3817 3818 Qualifiers::ObjCLifetime Type::getObjCARCImplicitLifetime() const { 3819 if (isObjCARCImplicitlyUnretainedType()) 3820 return Qualifiers::OCL_ExplicitNone; 3821 return Qualifiers::OCL_Strong; 3822 } 3823 3824 bool Type::isObjCARCImplicitlyUnretainedType() const { 3825 assert(isObjCLifetimeType() && 3826 "cannot query implicit lifetime for non-inferrable type"); 3827 3828 const Type *canon = getCanonicalTypeInternal().getTypePtr(); 3829 3830 // Walk down to the base type. We don't care about qualifiers for this. 3831 while (const auto *array = dyn_cast<ArrayType>(canon)) 3832 canon = array->getElementType().getTypePtr(); 3833 3834 if (const auto *opt = dyn_cast<ObjCObjectPointerType>(canon)) { 3835 // Class and Class<Protocol> don't require retention. 3836 if (opt->getObjectType()->isObjCClass()) 3837 return true; 3838 } 3839 3840 return false; 3841 } 3842 3843 bool Type::isObjCNSObjectType() const { 3844 const Type *cur = this; 3845 while (true) { 3846 if (const auto *typedefType = dyn_cast<TypedefType>(cur)) 3847 return typedefType->getDecl()->hasAttr<ObjCNSObjectAttr>(); 3848 3849 // Single-step desugar until we run out of sugar. 3850 QualType next = cur->getLocallyUnqualifiedSingleStepDesugaredType(); 3851 if (next.getTypePtr() == cur) return false; 3852 cur = next.getTypePtr(); 3853 } 3854 } 3855 3856 bool Type::isObjCIndependentClassType() const { 3857 if (const auto *typedefType = dyn_cast<TypedefType>(this)) 3858 return typedefType->getDecl()->hasAttr<ObjCIndependentClassAttr>(); 3859 return false; 3860 } 3861 3862 bool Type::isObjCRetainableType() const { 3863 return isObjCObjectPointerType() || 3864 isBlockPointerType() || 3865 isObjCNSObjectType(); 3866 } 3867 3868 bool Type::isObjCIndirectLifetimeType() const { 3869 if (isObjCLifetimeType()) 3870 return true; 3871 if (const auto *OPT = getAs<PointerType>()) 3872 return OPT->getPointeeType()->isObjCIndirectLifetimeType(); 3873 if (const auto *Ref = getAs<ReferenceType>()) 3874 return Ref->getPointeeType()->isObjCIndirectLifetimeType(); 3875 if (const auto *MemPtr = getAs<MemberPointerType>()) 3876 return MemPtr->getPointeeType()->isObjCIndirectLifetimeType(); 3877 return false; 3878 } 3879 3880 /// Returns true if objects of this type have lifetime semantics under 3881 /// ARC. 3882 bool Type::isObjCLifetimeType() const { 3883 const Type *type = this; 3884 while (const ArrayType *array = type->getAsArrayTypeUnsafe()) 3885 type = array->getElementType().getTypePtr(); 3886 return type->isObjCRetainableType(); 3887 } 3888 3889 /// \brief Determine whether the given type T is a "bridgable" Objective-C type, 3890 /// which is either an Objective-C object pointer type or an 3891 bool Type::isObjCARCBridgableType() const { 3892 return isObjCObjectPointerType() || isBlockPointerType(); 3893 } 3894 3895 /// \brief Determine whether the given type T is a "bridgeable" C type. 3896 bool Type::isCARCBridgableType() const { 3897 const auto *Pointer = getAs<PointerType>(); 3898 if (!Pointer) 3899 return false; 3900 3901 QualType Pointee = Pointer->getPointeeType(); 3902 return Pointee->isVoidType() || Pointee->isRecordType(); 3903 } 3904 3905 bool Type::hasSizedVLAType() const { 3906 if (!isVariablyModifiedType()) return false; 3907 3908 if (const auto *ptr = getAs<PointerType>()) 3909 return ptr->getPointeeType()->hasSizedVLAType(); 3910 if (const auto *ref = getAs<ReferenceType>()) 3911 return ref->getPointeeType()->hasSizedVLAType(); 3912 if (const ArrayType *arr = getAsArrayTypeUnsafe()) { 3913 if (isa<VariableArrayType>(arr) && 3914 cast<VariableArrayType>(arr)->getSizeExpr()) 3915 return true; 3916 3917 return arr->getElementType()->hasSizedVLAType(); 3918 } 3919 3920 return false; 3921 } 3922 3923 QualType::DestructionKind QualType::isDestructedTypeImpl(QualType type) { 3924 switch (type.getObjCLifetime()) { 3925 case Qualifiers::OCL_None: 3926 case Qualifiers::OCL_ExplicitNone: 3927 case Qualifiers::OCL_Autoreleasing: 3928 break; 3929 3930 case Qualifiers::OCL_Strong: 3931 return DK_objc_strong_lifetime; 3932 case Qualifiers::OCL_Weak: 3933 return DK_objc_weak_lifetime; 3934 } 3935 3936 if (const auto *RT = 3937 type->getBaseElementTypeUnsafe()->getAs<RecordType>()) { 3938 const RecordDecl *RD = RT->getDecl(); 3939 if (const auto *CXXRD = dyn_cast<CXXRecordDecl>(RD)) { 3940 /// Check if this is a C++ object with a non-trivial destructor. 3941 if (CXXRD->hasDefinition() && !CXXRD->hasTrivialDestructor()) 3942 return DK_cxx_destructor; 3943 } else { 3944 /// Check if this is a C struct that is non-trivial to destroy or an array 3945 /// that contains such a struct. 3946 if (RD->isNonTrivialToPrimitiveDestroy()) 3947 return DK_nontrivial_c_struct; 3948 } 3949 } 3950 3951 return DK_none; 3952 } 3953 3954 CXXRecordDecl *MemberPointerType::getMostRecentCXXRecordDecl() const { 3955 return getClass()->getAsCXXRecordDecl()->getMostRecentDecl(); 3956 } 3957