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