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