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