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