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