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