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