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