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::isTriviallyRelocatableType(const ASTContext &Context) const { 2509 QualType BaseElementType = Context.getBaseElementType(*this); 2510 2511 if (BaseElementType->isIncompleteType()) { 2512 return false; 2513 } else if (const auto *RD = BaseElementType->getAsRecordDecl()) { 2514 return RD->canPassInRegisters(); 2515 } else { 2516 switch (isNonTrivialToPrimitiveDestructiveMove()) { 2517 case PCK_Trivial: 2518 return !isDestructedType(); 2519 case PCK_ARCStrong: 2520 return true; 2521 default: 2522 return false; 2523 } 2524 } 2525 } 2526 2527 bool QualType::isNonWeakInMRRWithObjCWeak(const ASTContext &Context) const { 2528 return !Context.getLangOpts().ObjCAutoRefCount && 2529 Context.getLangOpts().ObjCWeak && 2530 getObjCLifetime() != Qualifiers::OCL_Weak; 2531 } 2532 2533 bool QualType::hasNonTrivialToPrimitiveDefaultInitializeCUnion(const RecordDecl *RD) { 2534 return RD->hasNonTrivialToPrimitiveDefaultInitializeCUnion(); 2535 } 2536 2537 bool QualType::hasNonTrivialToPrimitiveDestructCUnion(const RecordDecl *RD) { 2538 return RD->hasNonTrivialToPrimitiveDestructCUnion(); 2539 } 2540 2541 bool QualType::hasNonTrivialToPrimitiveCopyCUnion(const RecordDecl *RD) { 2542 return RD->hasNonTrivialToPrimitiveCopyCUnion(); 2543 } 2544 2545 QualType::PrimitiveDefaultInitializeKind 2546 QualType::isNonTrivialToPrimitiveDefaultInitialize() const { 2547 if (const auto *RT = 2548 getTypePtr()->getBaseElementTypeUnsafe()->getAs<RecordType>()) 2549 if (RT->getDecl()->isNonTrivialToPrimitiveDefaultInitialize()) 2550 return PDIK_Struct; 2551 2552 switch (getQualifiers().getObjCLifetime()) { 2553 case Qualifiers::OCL_Strong: 2554 return PDIK_ARCStrong; 2555 case Qualifiers::OCL_Weak: 2556 return PDIK_ARCWeak; 2557 default: 2558 return PDIK_Trivial; 2559 } 2560 } 2561 2562 QualType::PrimitiveCopyKind QualType::isNonTrivialToPrimitiveCopy() const { 2563 if (const auto *RT = 2564 getTypePtr()->getBaseElementTypeUnsafe()->getAs<RecordType>()) 2565 if (RT->getDecl()->isNonTrivialToPrimitiveCopy()) 2566 return PCK_Struct; 2567 2568 Qualifiers Qs = getQualifiers(); 2569 switch (Qs.getObjCLifetime()) { 2570 case Qualifiers::OCL_Strong: 2571 return PCK_ARCStrong; 2572 case Qualifiers::OCL_Weak: 2573 return PCK_ARCWeak; 2574 default: 2575 return Qs.hasVolatile() ? PCK_VolatileTrivial : PCK_Trivial; 2576 } 2577 } 2578 2579 QualType::PrimitiveCopyKind 2580 QualType::isNonTrivialToPrimitiveDestructiveMove() const { 2581 return isNonTrivialToPrimitiveCopy(); 2582 } 2583 2584 bool Type::isLiteralType(const ASTContext &Ctx) const { 2585 if (isDependentType()) 2586 return false; 2587 2588 // C++1y [basic.types]p10: 2589 // A type is a literal type if it is: 2590 // -- cv void; or 2591 if (Ctx.getLangOpts().CPlusPlus14 && isVoidType()) 2592 return true; 2593 2594 // C++11 [basic.types]p10: 2595 // A type is a literal type if it is: 2596 // [...] 2597 // -- an array of literal type other than an array of runtime bound; or 2598 if (isVariableArrayType()) 2599 return false; 2600 const Type *BaseTy = getBaseElementTypeUnsafe(); 2601 assert(BaseTy && "NULL element type"); 2602 2603 // Return false for incomplete types after skipping any incomplete array 2604 // types; those are expressly allowed by the standard and thus our API. 2605 if (BaseTy->isIncompleteType()) 2606 return false; 2607 2608 // C++11 [basic.types]p10: 2609 // A type is a literal type if it is: 2610 // -- a scalar type; or 2611 // As an extension, Clang treats vector types and complex types as 2612 // literal types. 2613 if (BaseTy->isScalarType() || BaseTy->isVectorType() || 2614 BaseTy->isAnyComplexType()) 2615 return true; 2616 // -- a reference type; or 2617 if (BaseTy->isReferenceType()) 2618 return true; 2619 // -- a class type that has all of the following properties: 2620 if (const auto *RT = BaseTy->getAs<RecordType>()) { 2621 // -- a trivial destructor, 2622 // -- every constructor call and full-expression in the 2623 // brace-or-equal-initializers for non-static data members (if any) 2624 // is a constant expression, 2625 // -- it is an aggregate type or has at least one constexpr 2626 // constructor or constructor template that is not a copy or move 2627 // constructor, and 2628 // -- all non-static data members and base classes of literal types 2629 // 2630 // We resolve DR1361 by ignoring the second bullet. 2631 if (const auto *ClassDecl = dyn_cast<CXXRecordDecl>(RT->getDecl())) 2632 return ClassDecl->isLiteral(); 2633 2634 return true; 2635 } 2636 2637 // We treat _Atomic T as a literal type if T is a literal type. 2638 if (const auto *AT = BaseTy->getAs<AtomicType>()) 2639 return AT->getValueType()->isLiteralType(Ctx); 2640 2641 // If this type hasn't been deduced yet, then conservatively assume that 2642 // it'll work out to be a literal type. 2643 if (isa<AutoType>(BaseTy->getCanonicalTypeInternal())) 2644 return true; 2645 2646 return false; 2647 } 2648 2649 bool Type::isStructuralType() const { 2650 // C++20 [temp.param]p6: 2651 // A structural type is one of the following: 2652 // -- a scalar type; or 2653 // -- a vector type [Clang extension]; or 2654 if (isScalarType() || isVectorType()) 2655 return true; 2656 // -- an lvalue reference type; or 2657 if (isLValueReferenceType()) 2658 return true; 2659 // -- a literal class type [...under some conditions] 2660 if (const CXXRecordDecl *RD = getAsCXXRecordDecl()) 2661 return RD->isStructural(); 2662 return false; 2663 } 2664 2665 bool Type::isStandardLayoutType() const { 2666 if (isDependentType()) 2667 return false; 2668 2669 // C++0x [basic.types]p9: 2670 // Scalar types, standard-layout class types, arrays of such types, and 2671 // cv-qualified versions of these types are collectively called 2672 // standard-layout types. 2673 const Type *BaseTy = getBaseElementTypeUnsafe(); 2674 assert(BaseTy && "NULL element type"); 2675 2676 // Return false for incomplete types after skipping any incomplete array 2677 // types which are expressly allowed by the standard and thus our API. 2678 if (BaseTy->isIncompleteType()) 2679 return false; 2680 2681 // As an extension, Clang treats vector types as Scalar types. 2682 if (BaseTy->isScalarType() || BaseTy->isVectorType()) return true; 2683 if (const auto *RT = BaseTy->getAs<RecordType>()) { 2684 if (const auto *ClassDecl = dyn_cast<CXXRecordDecl>(RT->getDecl())) 2685 if (!ClassDecl->isStandardLayout()) 2686 return false; 2687 2688 // Default to 'true' for non-C++ class types. 2689 // FIXME: This is a bit dubious, but plain C structs should trivially meet 2690 // all the requirements of standard layout classes. 2691 return true; 2692 } 2693 2694 // No other types can match. 2695 return false; 2696 } 2697 2698 // This is effectively the intersection of isTrivialType and 2699 // isStandardLayoutType. We implement it directly to avoid redundant 2700 // conversions from a type to a CXXRecordDecl. 2701 bool QualType::isCXX11PODType(const ASTContext &Context) const { 2702 const Type *ty = getTypePtr(); 2703 if (ty->isDependentType()) 2704 return false; 2705 2706 if (hasNonTrivialObjCLifetime()) 2707 return false; 2708 2709 // C++11 [basic.types]p9: 2710 // Scalar types, POD classes, arrays of such types, and cv-qualified 2711 // versions of these types are collectively called trivial types. 2712 const Type *BaseTy = ty->getBaseElementTypeUnsafe(); 2713 assert(BaseTy && "NULL element type"); 2714 2715 if (BaseTy->isSizelessBuiltinType()) 2716 return true; 2717 2718 // Return false for incomplete types after skipping any incomplete array 2719 // types which are expressly allowed by the standard and thus our API. 2720 if (BaseTy->isIncompleteType()) 2721 return false; 2722 2723 // As an extension, Clang treats vector types as Scalar types. 2724 if (BaseTy->isScalarType() || BaseTy->isVectorType()) return true; 2725 if (const auto *RT = BaseTy->getAs<RecordType>()) { 2726 if (const auto *ClassDecl = dyn_cast<CXXRecordDecl>(RT->getDecl())) { 2727 // C++11 [class]p10: 2728 // A POD struct is a non-union class that is both a trivial class [...] 2729 if (!ClassDecl->isTrivial()) return false; 2730 2731 // C++11 [class]p10: 2732 // A POD struct is a non-union class that is both a trivial class and 2733 // a standard-layout class [...] 2734 if (!ClassDecl->isStandardLayout()) return false; 2735 2736 // C++11 [class]p10: 2737 // A POD struct is a non-union class that is both a trivial class and 2738 // a standard-layout class, and has no non-static data members of type 2739 // non-POD struct, non-POD union (or array of such types). [...] 2740 // 2741 // We don't directly query the recursive aspect as the requirements for 2742 // both standard-layout classes and trivial classes apply recursively 2743 // already. 2744 } 2745 2746 return true; 2747 } 2748 2749 // No other types can match. 2750 return false; 2751 } 2752 2753 bool Type::isNothrowT() const { 2754 if (const auto *RD = getAsCXXRecordDecl()) { 2755 IdentifierInfo *II = RD->getIdentifier(); 2756 if (II && II->isStr("nothrow_t") && RD->isInStdNamespace()) 2757 return true; 2758 } 2759 return false; 2760 } 2761 2762 bool Type::isAlignValT() const { 2763 if (const auto *ET = getAs<EnumType>()) { 2764 IdentifierInfo *II = ET->getDecl()->getIdentifier(); 2765 if (II && II->isStr("align_val_t") && ET->getDecl()->isInStdNamespace()) 2766 return true; 2767 } 2768 return false; 2769 } 2770 2771 bool Type::isStdByteType() const { 2772 if (const auto *ET = getAs<EnumType>()) { 2773 IdentifierInfo *II = ET->getDecl()->getIdentifier(); 2774 if (II && II->isStr("byte") && ET->getDecl()->isInStdNamespace()) 2775 return true; 2776 } 2777 return false; 2778 } 2779 2780 bool Type::isPromotableIntegerType() const { 2781 if (const auto *BT = getAs<BuiltinType>()) 2782 switch (BT->getKind()) { 2783 case BuiltinType::Bool: 2784 case BuiltinType::Char_S: 2785 case BuiltinType::Char_U: 2786 case BuiltinType::SChar: 2787 case BuiltinType::UChar: 2788 case BuiltinType::Short: 2789 case BuiltinType::UShort: 2790 case BuiltinType::WChar_S: 2791 case BuiltinType::WChar_U: 2792 case BuiltinType::Char8: 2793 case BuiltinType::Char16: 2794 case BuiltinType::Char32: 2795 return true; 2796 default: 2797 return false; 2798 } 2799 2800 // Enumerated types are promotable to their compatible integer types 2801 // (C99 6.3.1.1) a.k.a. its underlying type (C++ [conv.prom]p2). 2802 if (const auto *ET = getAs<EnumType>()){ 2803 if (this->isDependentType() || ET->getDecl()->getPromotionType().isNull() 2804 || ET->getDecl()->isScoped()) 2805 return false; 2806 2807 return true; 2808 } 2809 2810 return false; 2811 } 2812 2813 bool Type::isSpecifierType() const { 2814 // Note that this intentionally does not use the canonical type. 2815 switch (getTypeClass()) { 2816 case Builtin: 2817 case Record: 2818 case Enum: 2819 case Typedef: 2820 case Complex: 2821 case TypeOfExpr: 2822 case TypeOf: 2823 case TemplateTypeParm: 2824 case SubstTemplateTypeParm: 2825 case TemplateSpecialization: 2826 case Elaborated: 2827 case DependentName: 2828 case DependentTemplateSpecialization: 2829 case ObjCInterface: 2830 case ObjCObject: 2831 return true; 2832 default: 2833 return false; 2834 } 2835 } 2836 2837 ElaboratedTypeKeyword 2838 TypeWithKeyword::getKeywordForTypeSpec(unsigned TypeSpec) { 2839 switch (TypeSpec) { 2840 default: return ETK_None; 2841 case TST_typename: return ETK_Typename; 2842 case TST_class: return ETK_Class; 2843 case TST_struct: return ETK_Struct; 2844 case TST_interface: return ETK_Interface; 2845 case TST_union: return ETK_Union; 2846 case TST_enum: return ETK_Enum; 2847 } 2848 } 2849 2850 TagTypeKind 2851 TypeWithKeyword::getTagTypeKindForTypeSpec(unsigned TypeSpec) { 2852 switch(TypeSpec) { 2853 case TST_class: return TTK_Class; 2854 case TST_struct: return TTK_Struct; 2855 case TST_interface: return TTK_Interface; 2856 case TST_union: return TTK_Union; 2857 case TST_enum: return TTK_Enum; 2858 } 2859 2860 llvm_unreachable("Type specifier is not a tag type kind."); 2861 } 2862 2863 ElaboratedTypeKeyword 2864 TypeWithKeyword::getKeywordForTagTypeKind(TagTypeKind Kind) { 2865 switch (Kind) { 2866 case TTK_Class: return ETK_Class; 2867 case TTK_Struct: return ETK_Struct; 2868 case TTK_Interface: return ETK_Interface; 2869 case TTK_Union: return ETK_Union; 2870 case TTK_Enum: return ETK_Enum; 2871 } 2872 llvm_unreachable("Unknown tag type kind."); 2873 } 2874 2875 TagTypeKind 2876 TypeWithKeyword::getTagTypeKindForKeyword(ElaboratedTypeKeyword Keyword) { 2877 switch (Keyword) { 2878 case ETK_Class: return TTK_Class; 2879 case ETK_Struct: return TTK_Struct; 2880 case ETK_Interface: return TTK_Interface; 2881 case ETK_Union: return TTK_Union; 2882 case ETK_Enum: return TTK_Enum; 2883 case ETK_None: // Fall through. 2884 case ETK_Typename: 2885 llvm_unreachable("Elaborated type keyword is not a tag type kind."); 2886 } 2887 llvm_unreachable("Unknown elaborated type keyword."); 2888 } 2889 2890 bool 2891 TypeWithKeyword::KeywordIsTagTypeKind(ElaboratedTypeKeyword Keyword) { 2892 switch (Keyword) { 2893 case ETK_None: 2894 case ETK_Typename: 2895 return false; 2896 case ETK_Class: 2897 case ETK_Struct: 2898 case ETK_Interface: 2899 case ETK_Union: 2900 case ETK_Enum: 2901 return true; 2902 } 2903 llvm_unreachable("Unknown elaborated type keyword."); 2904 } 2905 2906 StringRef TypeWithKeyword::getKeywordName(ElaboratedTypeKeyword Keyword) { 2907 switch (Keyword) { 2908 case ETK_None: return {}; 2909 case ETK_Typename: return "typename"; 2910 case ETK_Class: return "class"; 2911 case ETK_Struct: return "struct"; 2912 case ETK_Interface: return "__interface"; 2913 case ETK_Union: return "union"; 2914 case ETK_Enum: return "enum"; 2915 } 2916 2917 llvm_unreachable("Unknown elaborated type keyword."); 2918 } 2919 2920 DependentTemplateSpecializationType::DependentTemplateSpecializationType( 2921 ElaboratedTypeKeyword Keyword, NestedNameSpecifier *NNS, 2922 const IdentifierInfo *Name, ArrayRef<TemplateArgument> Args, QualType Canon) 2923 : TypeWithKeyword(Keyword, DependentTemplateSpecialization, Canon, 2924 TypeDependence::DependentInstantiation | 2925 (NNS ? toTypeDependence(NNS->getDependence()) 2926 : TypeDependence::None)), 2927 NNS(NNS), Name(Name) { 2928 DependentTemplateSpecializationTypeBits.NumArgs = Args.size(); 2929 assert((!NNS || NNS->isDependent()) && 2930 "DependentTemplateSpecializatonType requires dependent qualifier"); 2931 TemplateArgument *ArgBuffer = getArgBuffer(); 2932 for (const TemplateArgument &Arg : Args) { 2933 addDependence(toTypeDependence(Arg.getDependence() & 2934 TemplateArgumentDependence::UnexpandedPack)); 2935 2936 new (ArgBuffer++) TemplateArgument(Arg); 2937 } 2938 } 2939 2940 void 2941 DependentTemplateSpecializationType::Profile(llvm::FoldingSetNodeID &ID, 2942 const ASTContext &Context, 2943 ElaboratedTypeKeyword Keyword, 2944 NestedNameSpecifier *Qualifier, 2945 const IdentifierInfo *Name, 2946 ArrayRef<TemplateArgument> Args) { 2947 ID.AddInteger(Keyword); 2948 ID.AddPointer(Qualifier); 2949 ID.AddPointer(Name); 2950 for (const TemplateArgument &Arg : Args) 2951 Arg.Profile(ID, Context); 2952 } 2953 2954 bool Type::isElaboratedTypeSpecifier() const { 2955 ElaboratedTypeKeyword Keyword; 2956 if (const auto *Elab = dyn_cast<ElaboratedType>(this)) 2957 Keyword = Elab->getKeyword(); 2958 else if (const auto *DepName = dyn_cast<DependentNameType>(this)) 2959 Keyword = DepName->getKeyword(); 2960 else if (const auto *DepTST = 2961 dyn_cast<DependentTemplateSpecializationType>(this)) 2962 Keyword = DepTST->getKeyword(); 2963 else 2964 return false; 2965 2966 return TypeWithKeyword::KeywordIsTagTypeKind(Keyword); 2967 } 2968 2969 const char *Type::getTypeClassName() const { 2970 switch (TypeBits.TC) { 2971 #define ABSTRACT_TYPE(Derived, Base) 2972 #define TYPE(Derived, Base) case Derived: return #Derived; 2973 #include "clang/AST/TypeNodes.inc" 2974 } 2975 2976 llvm_unreachable("Invalid type class."); 2977 } 2978 2979 StringRef BuiltinType::getName(const PrintingPolicy &Policy) const { 2980 switch (getKind()) { 2981 case Void: 2982 return "void"; 2983 case Bool: 2984 return Policy.Bool ? "bool" : "_Bool"; 2985 case Char_S: 2986 return "char"; 2987 case Char_U: 2988 return "char"; 2989 case SChar: 2990 return "signed char"; 2991 case Short: 2992 return "short"; 2993 case Int: 2994 return "int"; 2995 case Long: 2996 return "long"; 2997 case LongLong: 2998 return "long long"; 2999 case Int128: 3000 return "__int128"; 3001 case UChar: 3002 return "unsigned char"; 3003 case UShort: 3004 return "unsigned short"; 3005 case UInt: 3006 return "unsigned int"; 3007 case ULong: 3008 return "unsigned long"; 3009 case ULongLong: 3010 return "unsigned long long"; 3011 case UInt128: 3012 return "unsigned __int128"; 3013 case Half: 3014 return Policy.Half ? "half" : "__fp16"; 3015 case BFloat16: 3016 return "__bf16"; 3017 case Float: 3018 return "float"; 3019 case Double: 3020 return "double"; 3021 case LongDouble: 3022 return "long double"; 3023 case ShortAccum: 3024 return "short _Accum"; 3025 case Accum: 3026 return "_Accum"; 3027 case LongAccum: 3028 return "long _Accum"; 3029 case UShortAccum: 3030 return "unsigned short _Accum"; 3031 case UAccum: 3032 return "unsigned _Accum"; 3033 case ULongAccum: 3034 return "unsigned long _Accum"; 3035 case BuiltinType::ShortFract: 3036 return "short _Fract"; 3037 case BuiltinType::Fract: 3038 return "_Fract"; 3039 case BuiltinType::LongFract: 3040 return "long _Fract"; 3041 case BuiltinType::UShortFract: 3042 return "unsigned short _Fract"; 3043 case BuiltinType::UFract: 3044 return "unsigned _Fract"; 3045 case BuiltinType::ULongFract: 3046 return "unsigned long _Fract"; 3047 case BuiltinType::SatShortAccum: 3048 return "_Sat short _Accum"; 3049 case BuiltinType::SatAccum: 3050 return "_Sat _Accum"; 3051 case BuiltinType::SatLongAccum: 3052 return "_Sat long _Accum"; 3053 case BuiltinType::SatUShortAccum: 3054 return "_Sat unsigned short _Accum"; 3055 case BuiltinType::SatUAccum: 3056 return "_Sat unsigned _Accum"; 3057 case BuiltinType::SatULongAccum: 3058 return "_Sat unsigned long _Accum"; 3059 case BuiltinType::SatShortFract: 3060 return "_Sat short _Fract"; 3061 case BuiltinType::SatFract: 3062 return "_Sat _Fract"; 3063 case BuiltinType::SatLongFract: 3064 return "_Sat long _Fract"; 3065 case BuiltinType::SatUShortFract: 3066 return "_Sat unsigned short _Fract"; 3067 case BuiltinType::SatUFract: 3068 return "_Sat unsigned _Fract"; 3069 case BuiltinType::SatULongFract: 3070 return "_Sat unsigned long _Fract"; 3071 case Float16: 3072 return "_Float16"; 3073 case Float128: 3074 return "__float128"; 3075 case Ibm128: 3076 return "__ibm128"; 3077 case WChar_S: 3078 case WChar_U: 3079 return Policy.MSWChar ? "__wchar_t" : "wchar_t"; 3080 case Char8: 3081 return "char8_t"; 3082 case Char16: 3083 return "char16_t"; 3084 case Char32: 3085 return "char32_t"; 3086 case NullPtr: 3087 return "std::nullptr_t"; 3088 case Overload: 3089 return "<overloaded function type>"; 3090 case BoundMember: 3091 return "<bound member function type>"; 3092 case PseudoObject: 3093 return "<pseudo-object type>"; 3094 case Dependent: 3095 return "<dependent type>"; 3096 case UnknownAny: 3097 return "<unknown type>"; 3098 case ARCUnbridgedCast: 3099 return "<ARC unbridged cast type>"; 3100 case BuiltinFn: 3101 return "<builtin fn type>"; 3102 case ObjCId: 3103 return "id"; 3104 case ObjCClass: 3105 return "Class"; 3106 case ObjCSel: 3107 return "SEL"; 3108 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \ 3109 case Id: \ 3110 return "__" #Access " " #ImgType "_t"; 3111 #include "clang/Basic/OpenCLImageTypes.def" 3112 case OCLSampler: 3113 return "sampler_t"; 3114 case OCLEvent: 3115 return "event_t"; 3116 case OCLClkEvent: 3117 return "clk_event_t"; 3118 case OCLQueue: 3119 return "queue_t"; 3120 case OCLReserveID: 3121 return "reserve_id_t"; 3122 case IncompleteMatrixIdx: 3123 return "<incomplete matrix index type>"; 3124 case OMPArraySection: 3125 return "<OpenMP array section type>"; 3126 case OMPArrayShaping: 3127 return "<OpenMP array shaping type>"; 3128 case OMPIterator: 3129 return "<OpenMP iterator type>"; 3130 #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \ 3131 case Id: \ 3132 return #ExtType; 3133 #include "clang/Basic/OpenCLExtensionTypes.def" 3134 #define SVE_TYPE(Name, Id, SingletonId) \ 3135 case Id: \ 3136 return Name; 3137 #include "clang/Basic/AArch64SVEACLETypes.def" 3138 #define PPC_VECTOR_TYPE(Name, Id, Size) \ 3139 case Id: \ 3140 return #Name; 3141 #include "clang/Basic/PPCTypes.def" 3142 #define RVV_TYPE(Name, Id, SingletonId) \ 3143 case Id: \ 3144 return Name; 3145 #include "clang/Basic/RISCVVTypes.def" 3146 } 3147 3148 llvm_unreachable("Invalid builtin type."); 3149 } 3150 3151 QualType QualType::getNonPackExpansionType() const { 3152 // We never wrap type sugar around a PackExpansionType. 3153 if (auto *PET = dyn_cast<PackExpansionType>(getTypePtr())) 3154 return PET->getPattern(); 3155 return *this; 3156 } 3157 3158 QualType QualType::getNonLValueExprType(const ASTContext &Context) const { 3159 if (const auto *RefType = getTypePtr()->getAs<ReferenceType>()) 3160 return RefType->getPointeeType(); 3161 3162 // C++0x [basic.lval]: 3163 // Class prvalues can have cv-qualified types; non-class prvalues always 3164 // have cv-unqualified types. 3165 // 3166 // See also C99 6.3.2.1p2. 3167 if (!Context.getLangOpts().CPlusPlus || 3168 (!getTypePtr()->isDependentType() && !getTypePtr()->isRecordType())) 3169 return getUnqualifiedType(); 3170 3171 return *this; 3172 } 3173 3174 StringRef FunctionType::getNameForCallConv(CallingConv CC) { 3175 switch (CC) { 3176 case CC_C: return "cdecl"; 3177 case CC_X86StdCall: return "stdcall"; 3178 case CC_X86FastCall: return "fastcall"; 3179 case CC_X86ThisCall: return "thiscall"; 3180 case CC_X86Pascal: return "pascal"; 3181 case CC_X86VectorCall: return "vectorcall"; 3182 case CC_Win64: return "ms_abi"; 3183 case CC_X86_64SysV: return "sysv_abi"; 3184 case CC_X86RegCall : return "regcall"; 3185 case CC_AAPCS: return "aapcs"; 3186 case CC_AAPCS_VFP: return "aapcs-vfp"; 3187 case CC_AArch64VectorCall: return "aarch64_vector_pcs"; 3188 case CC_AArch64SVEPCS: return "aarch64_sve_pcs"; 3189 case CC_AMDGPUKernelCall: return "amdgpu_kernel"; 3190 case CC_IntelOclBicc: return "intel_ocl_bicc"; 3191 case CC_SpirFunction: return "spir_function"; 3192 case CC_OpenCLKernel: return "opencl_kernel"; 3193 case CC_Swift: return "swiftcall"; 3194 case CC_SwiftAsync: return "swiftasynccall"; 3195 case CC_PreserveMost: return "preserve_most"; 3196 case CC_PreserveAll: return "preserve_all"; 3197 } 3198 3199 llvm_unreachable("Invalid calling convention."); 3200 } 3201 3202 FunctionProtoType::FunctionProtoType(QualType result, ArrayRef<QualType> params, 3203 QualType canonical, 3204 const ExtProtoInfo &epi) 3205 : FunctionType(FunctionProto, result, canonical, result->getDependence(), 3206 epi.ExtInfo) { 3207 FunctionTypeBits.FastTypeQuals = epi.TypeQuals.getFastQualifiers(); 3208 FunctionTypeBits.RefQualifier = epi.RefQualifier; 3209 FunctionTypeBits.NumParams = params.size(); 3210 assert(getNumParams() == params.size() && "NumParams overflow!"); 3211 FunctionTypeBits.ExceptionSpecType = epi.ExceptionSpec.Type; 3212 FunctionTypeBits.HasExtParameterInfos = !!epi.ExtParameterInfos; 3213 FunctionTypeBits.Variadic = epi.Variadic; 3214 FunctionTypeBits.HasTrailingReturn = epi.HasTrailingReturn; 3215 3216 if (epi.requiresFunctionProtoTypeExtraBitfields()) { 3217 FunctionTypeBits.HasExtraBitfields = true; 3218 auto &ExtraBits = *getTrailingObjects<FunctionTypeExtraBitfields>(); 3219 ExtraBits = FunctionTypeExtraBitfields(); 3220 } else { 3221 FunctionTypeBits.HasExtraBitfields = false; 3222 } 3223 3224 3225 // Fill in the trailing argument array. 3226 auto *argSlot = getTrailingObjects<QualType>(); 3227 for (unsigned i = 0; i != getNumParams(); ++i) { 3228 addDependence(params[i]->getDependence() & 3229 ~TypeDependence::VariablyModified); 3230 argSlot[i] = params[i]; 3231 } 3232 3233 // Fill in the exception type array if present. 3234 if (getExceptionSpecType() == EST_Dynamic) { 3235 auto &ExtraBits = *getTrailingObjects<FunctionTypeExtraBitfields>(); 3236 ExtraBits.NumExceptionType = epi.ExceptionSpec.Exceptions.size(); 3237 3238 assert(hasExtraBitfields() && "missing trailing extra bitfields!"); 3239 auto *exnSlot = 3240 reinterpret_cast<QualType *>(getTrailingObjects<ExceptionType>()); 3241 unsigned I = 0; 3242 for (QualType ExceptionType : epi.ExceptionSpec.Exceptions) { 3243 // Note that, before C++17, a dependent exception specification does 3244 // *not* make a type dependent; it's not even part of the C++ type 3245 // system. 3246 addDependence( 3247 ExceptionType->getDependence() & 3248 (TypeDependence::Instantiation | TypeDependence::UnexpandedPack)); 3249 3250 exnSlot[I++] = ExceptionType; 3251 } 3252 } 3253 // Fill in the Expr * in the exception specification if present. 3254 else if (isComputedNoexcept(getExceptionSpecType())) { 3255 assert(epi.ExceptionSpec.NoexceptExpr && "computed noexcept with no expr"); 3256 assert((getExceptionSpecType() == EST_DependentNoexcept) == 3257 epi.ExceptionSpec.NoexceptExpr->isValueDependent()); 3258 3259 // Store the noexcept expression and context. 3260 *getTrailingObjects<Expr *>() = epi.ExceptionSpec.NoexceptExpr; 3261 3262 addDependence( 3263 toTypeDependence(epi.ExceptionSpec.NoexceptExpr->getDependence()) & 3264 (TypeDependence::Instantiation | TypeDependence::UnexpandedPack)); 3265 } 3266 // Fill in the FunctionDecl * in the exception specification if present. 3267 else if (getExceptionSpecType() == EST_Uninstantiated) { 3268 // Store the function decl from which we will resolve our 3269 // exception specification. 3270 auto **slot = getTrailingObjects<FunctionDecl *>(); 3271 slot[0] = epi.ExceptionSpec.SourceDecl; 3272 slot[1] = epi.ExceptionSpec.SourceTemplate; 3273 // This exception specification doesn't make the type dependent, because 3274 // it's not instantiated as part of instantiating the type. 3275 } else if (getExceptionSpecType() == EST_Unevaluated) { 3276 // Store the function decl from which we will resolve our 3277 // exception specification. 3278 auto **slot = getTrailingObjects<FunctionDecl *>(); 3279 slot[0] = epi.ExceptionSpec.SourceDecl; 3280 } 3281 3282 // If this is a canonical type, and its exception specification is dependent, 3283 // then it's a dependent type. This only happens in C++17 onwards. 3284 if (isCanonicalUnqualified()) { 3285 if (getExceptionSpecType() == EST_Dynamic || 3286 getExceptionSpecType() == EST_DependentNoexcept) { 3287 assert(hasDependentExceptionSpec() && "type should not be canonical"); 3288 addDependence(TypeDependence::DependentInstantiation); 3289 } 3290 } else if (getCanonicalTypeInternal()->isDependentType()) { 3291 // Ask our canonical type whether our exception specification was dependent. 3292 addDependence(TypeDependence::DependentInstantiation); 3293 } 3294 3295 // Fill in the extra parameter info if present. 3296 if (epi.ExtParameterInfos) { 3297 auto *extParamInfos = getTrailingObjects<ExtParameterInfo>(); 3298 for (unsigned i = 0; i != getNumParams(); ++i) 3299 extParamInfos[i] = epi.ExtParameterInfos[i]; 3300 } 3301 3302 if (epi.TypeQuals.hasNonFastQualifiers()) { 3303 FunctionTypeBits.HasExtQuals = 1; 3304 *getTrailingObjects<Qualifiers>() = epi.TypeQuals; 3305 } else { 3306 FunctionTypeBits.HasExtQuals = 0; 3307 } 3308 3309 // Fill in the Ellipsis location info if present. 3310 if (epi.Variadic) { 3311 auto &EllipsisLoc = *getTrailingObjects<SourceLocation>(); 3312 EllipsisLoc = epi.EllipsisLoc; 3313 } 3314 } 3315 3316 bool FunctionProtoType::hasDependentExceptionSpec() const { 3317 if (Expr *NE = getNoexceptExpr()) 3318 return NE->isValueDependent(); 3319 for (QualType ET : exceptions()) 3320 // A pack expansion with a non-dependent pattern is still dependent, 3321 // because we don't know whether the pattern is in the exception spec 3322 // or not (that depends on whether the pack has 0 expansions). 3323 if (ET->isDependentType() || ET->getAs<PackExpansionType>()) 3324 return true; 3325 return false; 3326 } 3327 3328 bool FunctionProtoType::hasInstantiationDependentExceptionSpec() const { 3329 if (Expr *NE = getNoexceptExpr()) 3330 return NE->isInstantiationDependent(); 3331 for (QualType ET : exceptions()) 3332 if (ET->isInstantiationDependentType()) 3333 return true; 3334 return false; 3335 } 3336 3337 CanThrowResult FunctionProtoType::canThrow() const { 3338 switch (getExceptionSpecType()) { 3339 case EST_Unparsed: 3340 case EST_Unevaluated: 3341 llvm_unreachable("should not call this with unresolved exception specs"); 3342 3343 case EST_DynamicNone: 3344 case EST_BasicNoexcept: 3345 case EST_NoexceptTrue: 3346 case EST_NoThrow: 3347 return CT_Cannot; 3348 3349 case EST_None: 3350 case EST_MSAny: 3351 case EST_NoexceptFalse: 3352 return CT_Can; 3353 3354 case EST_Dynamic: 3355 // A dynamic exception specification is throwing unless every exception 3356 // type is an (unexpanded) pack expansion type. 3357 for (unsigned I = 0; I != getNumExceptions(); ++I) 3358 if (!getExceptionType(I)->getAs<PackExpansionType>()) 3359 return CT_Can; 3360 return CT_Dependent; 3361 3362 case EST_Uninstantiated: 3363 case EST_DependentNoexcept: 3364 return CT_Dependent; 3365 } 3366 3367 llvm_unreachable("unexpected exception specification kind"); 3368 } 3369 3370 bool FunctionProtoType::isTemplateVariadic() const { 3371 for (unsigned ArgIdx = getNumParams(); ArgIdx; --ArgIdx) 3372 if (isa<PackExpansionType>(getParamType(ArgIdx - 1))) 3373 return true; 3374 3375 return false; 3376 } 3377 3378 void FunctionProtoType::Profile(llvm::FoldingSetNodeID &ID, QualType Result, 3379 const QualType *ArgTys, unsigned NumParams, 3380 const ExtProtoInfo &epi, 3381 const ASTContext &Context, bool Canonical) { 3382 // We have to be careful not to get ambiguous profile encodings. 3383 // Note that valid type pointers are never ambiguous with anything else. 3384 // 3385 // The encoding grammar begins: 3386 // type type* bool int bool 3387 // If that final bool is true, then there is a section for the EH spec: 3388 // bool type* 3389 // This is followed by an optional "consumed argument" section of the 3390 // same length as the first type sequence: 3391 // bool* 3392 // Finally, we have the ext info and trailing return type flag: 3393 // int bool 3394 // 3395 // There is no ambiguity between the consumed arguments and an empty EH 3396 // spec because of the leading 'bool' which unambiguously indicates 3397 // whether the following bool is the EH spec or part of the arguments. 3398 3399 ID.AddPointer(Result.getAsOpaquePtr()); 3400 for (unsigned i = 0; i != NumParams; ++i) 3401 ID.AddPointer(ArgTys[i].getAsOpaquePtr()); 3402 // This method is relatively performance sensitive, so as a performance 3403 // shortcut, use one AddInteger call instead of four for the next four 3404 // fields. 3405 assert(!(unsigned(epi.Variadic) & ~1) && 3406 !(unsigned(epi.RefQualifier) & ~3) && 3407 !(unsigned(epi.ExceptionSpec.Type) & ~15) && 3408 "Values larger than expected."); 3409 ID.AddInteger(unsigned(epi.Variadic) + 3410 (epi.RefQualifier << 1) + 3411 (epi.ExceptionSpec.Type << 3)); 3412 ID.Add(epi.TypeQuals); 3413 if (epi.ExceptionSpec.Type == EST_Dynamic) { 3414 for (QualType Ex : epi.ExceptionSpec.Exceptions) 3415 ID.AddPointer(Ex.getAsOpaquePtr()); 3416 } else if (isComputedNoexcept(epi.ExceptionSpec.Type)) { 3417 epi.ExceptionSpec.NoexceptExpr->Profile(ID, Context, Canonical); 3418 } else if (epi.ExceptionSpec.Type == EST_Uninstantiated || 3419 epi.ExceptionSpec.Type == EST_Unevaluated) { 3420 ID.AddPointer(epi.ExceptionSpec.SourceDecl->getCanonicalDecl()); 3421 } 3422 if (epi.ExtParameterInfos) { 3423 for (unsigned i = 0; i != NumParams; ++i) 3424 ID.AddInteger(epi.ExtParameterInfos[i].getOpaqueValue()); 3425 } 3426 epi.ExtInfo.Profile(ID); 3427 ID.AddBoolean(epi.HasTrailingReturn); 3428 } 3429 3430 void FunctionProtoType::Profile(llvm::FoldingSetNodeID &ID, 3431 const ASTContext &Ctx) { 3432 Profile(ID, getReturnType(), param_type_begin(), getNumParams(), 3433 getExtProtoInfo(), Ctx, isCanonicalUnqualified()); 3434 } 3435 3436 TypedefType::TypedefType(TypeClass tc, const TypedefNameDecl *D, 3437 QualType underlying, QualType can) 3438 : Type(tc, can, toSemanticDependence(underlying->getDependence())), 3439 Decl(const_cast<TypedefNameDecl *>(D)) { 3440 assert(!isa<TypedefType>(can) && "Invalid canonical type"); 3441 } 3442 3443 QualType TypedefType::desugar() const { 3444 return getDecl()->getUnderlyingType(); 3445 } 3446 3447 UsingType::UsingType(const UsingShadowDecl *Found, QualType Underlying, 3448 QualType Canon) 3449 : Type(Using, Canon, toSemanticDependence(Underlying->getDependence())), 3450 Found(const_cast<UsingShadowDecl *>(Found)) { 3451 assert(Underlying == getUnderlyingType()); 3452 } 3453 3454 QualType UsingType::getUnderlyingType() const { 3455 return QualType(cast<TypeDecl>(Found->getTargetDecl())->getTypeForDecl(), 0); 3456 } 3457 3458 QualType MacroQualifiedType::desugar() const { return getUnderlyingType(); } 3459 3460 QualType MacroQualifiedType::getModifiedType() const { 3461 // Step over MacroQualifiedTypes from the same macro to find the type 3462 // ultimately qualified by the macro qualifier. 3463 QualType Inner = cast<AttributedType>(getUnderlyingType())->getModifiedType(); 3464 while (auto *InnerMQT = dyn_cast<MacroQualifiedType>(Inner)) { 3465 if (InnerMQT->getMacroIdentifier() != getMacroIdentifier()) 3466 break; 3467 Inner = InnerMQT->getModifiedType(); 3468 } 3469 return Inner; 3470 } 3471 3472 TypeOfExprType::TypeOfExprType(Expr *E, QualType can) 3473 : Type(TypeOfExpr, can, 3474 toTypeDependence(E->getDependence()) | 3475 (E->getType()->getDependence() & 3476 TypeDependence::VariablyModified)), 3477 TOExpr(E) {} 3478 3479 bool TypeOfExprType::isSugared() const { 3480 return !TOExpr->isTypeDependent(); 3481 } 3482 3483 QualType TypeOfExprType::desugar() const { 3484 if (isSugared()) 3485 return getUnderlyingExpr()->getType(); 3486 3487 return QualType(this, 0); 3488 } 3489 3490 void DependentTypeOfExprType::Profile(llvm::FoldingSetNodeID &ID, 3491 const ASTContext &Context, Expr *E) { 3492 E->Profile(ID, Context, true); 3493 } 3494 3495 DecltypeType::DecltypeType(Expr *E, QualType underlyingType, QualType can) 3496 // C++11 [temp.type]p2: "If an expression e involves a template parameter, 3497 // decltype(e) denotes a unique dependent type." Hence a decltype type is 3498 // type-dependent even if its expression is only instantiation-dependent. 3499 : Type(Decltype, can, 3500 toTypeDependence(E->getDependence()) | 3501 (E->isInstantiationDependent() ? TypeDependence::Dependent 3502 : TypeDependence::None) | 3503 (E->getType()->getDependence() & 3504 TypeDependence::VariablyModified)), 3505 E(E), UnderlyingType(underlyingType) {} 3506 3507 bool DecltypeType::isSugared() const { return !E->isInstantiationDependent(); } 3508 3509 QualType DecltypeType::desugar() const { 3510 if (isSugared()) 3511 return getUnderlyingType(); 3512 3513 return QualType(this, 0); 3514 } 3515 3516 DependentDecltypeType::DependentDecltypeType(const ASTContext &Context, Expr *E) 3517 : DecltypeType(E, Context.DependentTy), Context(Context) {} 3518 3519 void DependentDecltypeType::Profile(llvm::FoldingSetNodeID &ID, 3520 const ASTContext &Context, Expr *E) { 3521 E->Profile(ID, Context, true); 3522 } 3523 3524 UnaryTransformType::UnaryTransformType(QualType BaseType, 3525 QualType UnderlyingType, UTTKind UKind, 3526 QualType CanonicalType) 3527 : Type(UnaryTransform, CanonicalType, BaseType->getDependence()), 3528 BaseType(BaseType), UnderlyingType(UnderlyingType), UKind(UKind) {} 3529 3530 DependentUnaryTransformType::DependentUnaryTransformType(const ASTContext &C, 3531 QualType BaseType, 3532 UTTKind UKind) 3533 : UnaryTransformType(BaseType, C.DependentTy, UKind, QualType()) {} 3534 3535 TagType::TagType(TypeClass TC, const TagDecl *D, QualType can) 3536 : Type(TC, can, 3537 D->isDependentType() ? TypeDependence::DependentInstantiation 3538 : TypeDependence::None), 3539 decl(const_cast<TagDecl *>(D)) {} 3540 3541 static TagDecl *getInterestingTagDecl(TagDecl *decl) { 3542 for (auto I : decl->redecls()) { 3543 if (I->isCompleteDefinition() || I->isBeingDefined()) 3544 return I; 3545 } 3546 // If there's no definition (not even in progress), return what we have. 3547 return decl; 3548 } 3549 3550 TagDecl *TagType::getDecl() const { 3551 return getInterestingTagDecl(decl); 3552 } 3553 3554 bool TagType::isBeingDefined() const { 3555 return getDecl()->isBeingDefined(); 3556 } 3557 3558 bool RecordType::hasConstFields() const { 3559 std::vector<const RecordType*> RecordTypeList; 3560 RecordTypeList.push_back(this); 3561 unsigned NextToCheckIndex = 0; 3562 3563 while (RecordTypeList.size() > NextToCheckIndex) { 3564 for (FieldDecl *FD : 3565 RecordTypeList[NextToCheckIndex]->getDecl()->fields()) { 3566 QualType FieldTy = FD->getType(); 3567 if (FieldTy.isConstQualified()) 3568 return true; 3569 FieldTy = FieldTy.getCanonicalType(); 3570 if (const auto *FieldRecTy = FieldTy->getAs<RecordType>()) { 3571 if (!llvm::is_contained(RecordTypeList, FieldRecTy)) 3572 RecordTypeList.push_back(FieldRecTy); 3573 } 3574 } 3575 ++NextToCheckIndex; 3576 } 3577 return false; 3578 } 3579 3580 bool AttributedType::isQualifier() const { 3581 // FIXME: Generate this with TableGen. 3582 switch (getAttrKind()) { 3583 // These are type qualifiers in the traditional C sense: they annotate 3584 // something about a specific value/variable of a type. (They aren't 3585 // always part of the canonical type, though.) 3586 case attr::ObjCGC: 3587 case attr::ObjCOwnership: 3588 case attr::ObjCInertUnsafeUnretained: 3589 case attr::TypeNonNull: 3590 case attr::TypeNullable: 3591 case attr::TypeNullableResult: 3592 case attr::TypeNullUnspecified: 3593 case attr::LifetimeBound: 3594 case attr::AddressSpace: 3595 return true; 3596 3597 // All other type attributes aren't qualifiers; they rewrite the modified 3598 // type to be a semantically different type. 3599 default: 3600 return false; 3601 } 3602 } 3603 3604 bool AttributedType::isMSTypeSpec() const { 3605 // FIXME: Generate this with TableGen? 3606 switch (getAttrKind()) { 3607 default: return false; 3608 case attr::Ptr32: 3609 case attr::Ptr64: 3610 case attr::SPtr: 3611 case attr::UPtr: 3612 return true; 3613 } 3614 llvm_unreachable("invalid attr kind"); 3615 } 3616 3617 bool AttributedType::isCallingConv() const { 3618 // FIXME: Generate this with TableGen. 3619 switch (getAttrKind()) { 3620 default: return false; 3621 case attr::Pcs: 3622 case attr::CDecl: 3623 case attr::FastCall: 3624 case attr::StdCall: 3625 case attr::ThisCall: 3626 case attr::RegCall: 3627 case attr::SwiftCall: 3628 case attr::SwiftAsyncCall: 3629 case attr::VectorCall: 3630 case attr::AArch64VectorPcs: 3631 case attr::AArch64SVEPcs: 3632 case attr::AMDGPUKernelCall: 3633 case attr::Pascal: 3634 case attr::MSABI: 3635 case attr::SysVABI: 3636 case attr::IntelOclBicc: 3637 case attr::PreserveMost: 3638 case attr::PreserveAll: 3639 return true; 3640 } 3641 llvm_unreachable("invalid attr kind"); 3642 } 3643 3644 CXXRecordDecl *InjectedClassNameType::getDecl() const { 3645 return cast<CXXRecordDecl>(getInterestingTagDecl(Decl)); 3646 } 3647 3648 IdentifierInfo *TemplateTypeParmType::getIdentifier() const { 3649 return isCanonicalUnqualified() ? nullptr : getDecl()->getIdentifier(); 3650 } 3651 3652 SubstTemplateTypeParmPackType::SubstTemplateTypeParmPackType( 3653 const TemplateTypeParmType *Param, QualType Canon, 3654 const TemplateArgument &ArgPack) 3655 : Type(SubstTemplateTypeParmPack, Canon, 3656 TypeDependence::DependentInstantiation | 3657 TypeDependence::UnexpandedPack), 3658 Replaced(Param), Arguments(ArgPack.pack_begin()) { 3659 SubstTemplateTypeParmPackTypeBits.NumArgs = ArgPack.pack_size(); 3660 } 3661 3662 TemplateArgument SubstTemplateTypeParmPackType::getArgumentPack() const { 3663 return TemplateArgument(llvm::makeArrayRef(Arguments, getNumArgs())); 3664 } 3665 3666 void SubstTemplateTypeParmPackType::Profile(llvm::FoldingSetNodeID &ID) { 3667 Profile(ID, getReplacedParameter(), getArgumentPack()); 3668 } 3669 3670 void SubstTemplateTypeParmPackType::Profile(llvm::FoldingSetNodeID &ID, 3671 const TemplateTypeParmType *Replaced, 3672 const TemplateArgument &ArgPack) { 3673 ID.AddPointer(Replaced); 3674 ID.AddInteger(ArgPack.pack_size()); 3675 for (const auto &P : ArgPack.pack_elements()) 3676 ID.AddPointer(P.getAsType().getAsOpaquePtr()); 3677 } 3678 3679 bool TemplateSpecializationType::anyDependentTemplateArguments( 3680 const TemplateArgumentListInfo &Args, ArrayRef<TemplateArgument> Converted) { 3681 return anyDependentTemplateArguments(Args.arguments(), Converted); 3682 } 3683 3684 bool TemplateSpecializationType::anyDependentTemplateArguments( 3685 ArrayRef<TemplateArgumentLoc> Args, ArrayRef<TemplateArgument> Converted) { 3686 for (const TemplateArgument &Arg : Converted) 3687 if (Arg.isDependent()) 3688 return true; 3689 return false; 3690 } 3691 3692 bool TemplateSpecializationType::anyInstantiationDependentTemplateArguments( 3693 ArrayRef<TemplateArgumentLoc> Args) { 3694 for (const TemplateArgumentLoc &ArgLoc : Args) { 3695 if (ArgLoc.getArgument().isInstantiationDependent()) 3696 return true; 3697 } 3698 return false; 3699 } 3700 3701 TemplateSpecializationType::TemplateSpecializationType( 3702 TemplateName T, ArrayRef<TemplateArgument> Args, QualType Canon, 3703 QualType AliasedType) 3704 : Type(TemplateSpecialization, Canon.isNull() ? QualType(this, 0) : Canon, 3705 (Canon.isNull() 3706 ? TypeDependence::DependentInstantiation 3707 : toSemanticDependence(Canon->getDependence())) | 3708 (toTypeDependence(T.getDependence()) & 3709 TypeDependence::UnexpandedPack)), 3710 Template(T) { 3711 TemplateSpecializationTypeBits.NumArgs = Args.size(); 3712 TemplateSpecializationTypeBits.TypeAlias = !AliasedType.isNull(); 3713 3714 assert(!T.getAsDependentTemplateName() && 3715 "Use DependentTemplateSpecializationType for dependent template-name"); 3716 assert((T.getKind() == TemplateName::Template || 3717 T.getKind() == TemplateName::SubstTemplateTemplateParm || 3718 T.getKind() == TemplateName::SubstTemplateTemplateParmPack || 3719 T.getKind() == TemplateName::UsingTemplate) && 3720 "Unexpected template name for TemplateSpecializationType"); 3721 3722 auto *TemplateArgs = reinterpret_cast<TemplateArgument *>(this + 1); 3723 for (const TemplateArgument &Arg : Args) { 3724 // Update instantiation-dependent, variably-modified, and error bits. 3725 // If the canonical type exists and is non-dependent, the template 3726 // specialization type can be non-dependent even if one of the type 3727 // arguments is. Given: 3728 // template<typename T> using U = int; 3729 // U<T> is always non-dependent, irrespective of the type T. 3730 // However, U<Ts> contains an unexpanded parameter pack, even though 3731 // its expansion (and thus its desugared type) doesn't. 3732 addDependence(toTypeDependence(Arg.getDependence()) & 3733 ~TypeDependence::Dependent); 3734 if (Arg.getKind() == TemplateArgument::Type) 3735 addDependence(Arg.getAsType()->getDependence() & 3736 TypeDependence::VariablyModified); 3737 new (TemplateArgs++) TemplateArgument(Arg); 3738 } 3739 3740 // Store the aliased type if this is a type alias template specialization. 3741 if (isTypeAlias()) { 3742 auto *Begin = reinterpret_cast<TemplateArgument *>(this + 1); 3743 *reinterpret_cast<QualType*>(Begin + getNumArgs()) = AliasedType; 3744 } 3745 } 3746 3747 void 3748 TemplateSpecializationType::Profile(llvm::FoldingSetNodeID &ID, 3749 TemplateName T, 3750 ArrayRef<TemplateArgument> Args, 3751 const ASTContext &Context) { 3752 T.Profile(ID); 3753 for (const TemplateArgument &Arg : Args) 3754 Arg.Profile(ID, Context); 3755 } 3756 3757 QualType 3758 QualifierCollector::apply(const ASTContext &Context, QualType QT) const { 3759 if (!hasNonFastQualifiers()) 3760 return QT.withFastQualifiers(getFastQualifiers()); 3761 3762 return Context.getQualifiedType(QT, *this); 3763 } 3764 3765 QualType 3766 QualifierCollector::apply(const ASTContext &Context, const Type *T) const { 3767 if (!hasNonFastQualifiers()) 3768 return QualType(T, getFastQualifiers()); 3769 3770 return Context.getQualifiedType(T, *this); 3771 } 3772 3773 void ObjCObjectTypeImpl::Profile(llvm::FoldingSetNodeID &ID, 3774 QualType BaseType, 3775 ArrayRef<QualType> typeArgs, 3776 ArrayRef<ObjCProtocolDecl *> protocols, 3777 bool isKindOf) { 3778 ID.AddPointer(BaseType.getAsOpaquePtr()); 3779 ID.AddInteger(typeArgs.size()); 3780 for (auto typeArg : typeArgs) 3781 ID.AddPointer(typeArg.getAsOpaquePtr()); 3782 ID.AddInteger(protocols.size()); 3783 for (auto proto : protocols) 3784 ID.AddPointer(proto); 3785 ID.AddBoolean(isKindOf); 3786 } 3787 3788 void ObjCObjectTypeImpl::Profile(llvm::FoldingSetNodeID &ID) { 3789 Profile(ID, getBaseType(), getTypeArgsAsWritten(), 3790 llvm::makeArrayRef(qual_begin(), getNumProtocols()), 3791 isKindOfTypeAsWritten()); 3792 } 3793 3794 void ObjCTypeParamType::Profile(llvm::FoldingSetNodeID &ID, 3795 const ObjCTypeParamDecl *OTPDecl, 3796 QualType CanonicalType, 3797 ArrayRef<ObjCProtocolDecl *> protocols) { 3798 ID.AddPointer(OTPDecl); 3799 ID.AddPointer(CanonicalType.getAsOpaquePtr()); 3800 ID.AddInteger(protocols.size()); 3801 for (auto proto : protocols) 3802 ID.AddPointer(proto); 3803 } 3804 3805 void ObjCTypeParamType::Profile(llvm::FoldingSetNodeID &ID) { 3806 Profile(ID, getDecl(), getCanonicalTypeInternal(), 3807 llvm::makeArrayRef(qual_begin(), getNumProtocols())); 3808 } 3809 3810 namespace { 3811 3812 /// The cached properties of a type. 3813 class CachedProperties { 3814 Linkage L; 3815 bool local; 3816 3817 public: 3818 CachedProperties(Linkage L, bool local) : L(L), local(local) {} 3819 3820 Linkage getLinkage() const { return L; } 3821 bool hasLocalOrUnnamedType() const { return local; } 3822 3823 friend CachedProperties merge(CachedProperties L, CachedProperties R) { 3824 Linkage MergedLinkage = minLinkage(L.L, R.L); 3825 return CachedProperties(MergedLinkage, L.hasLocalOrUnnamedType() || 3826 R.hasLocalOrUnnamedType()); 3827 } 3828 }; 3829 3830 } // namespace 3831 3832 static CachedProperties computeCachedProperties(const Type *T); 3833 3834 namespace clang { 3835 3836 /// The type-property cache. This is templated so as to be 3837 /// instantiated at an internal type to prevent unnecessary symbol 3838 /// leakage. 3839 template <class Private> class TypePropertyCache { 3840 public: 3841 static CachedProperties get(QualType T) { 3842 return get(T.getTypePtr()); 3843 } 3844 3845 static CachedProperties get(const Type *T) { 3846 ensure(T); 3847 return CachedProperties(T->TypeBits.getLinkage(), 3848 T->TypeBits.hasLocalOrUnnamedType()); 3849 } 3850 3851 static void ensure(const Type *T) { 3852 // If the cache is valid, we're okay. 3853 if (T->TypeBits.isCacheValid()) return; 3854 3855 // If this type is non-canonical, ask its canonical type for the 3856 // relevant information. 3857 if (!T->isCanonicalUnqualified()) { 3858 const Type *CT = T->getCanonicalTypeInternal().getTypePtr(); 3859 ensure(CT); 3860 T->TypeBits.CacheValid = true; 3861 T->TypeBits.CachedLinkage = CT->TypeBits.CachedLinkage; 3862 T->TypeBits.CachedLocalOrUnnamed = CT->TypeBits.CachedLocalOrUnnamed; 3863 return; 3864 } 3865 3866 // Compute the cached properties and then set the cache. 3867 CachedProperties Result = computeCachedProperties(T); 3868 T->TypeBits.CacheValid = true; 3869 T->TypeBits.CachedLinkage = Result.getLinkage(); 3870 T->TypeBits.CachedLocalOrUnnamed = Result.hasLocalOrUnnamedType(); 3871 } 3872 }; 3873 3874 } // namespace clang 3875 3876 // Instantiate the friend template at a private class. In a 3877 // reasonable implementation, these symbols will be internal. 3878 // It is terrible that this is the best way to accomplish this. 3879 namespace { 3880 3881 class Private {}; 3882 3883 } // namespace 3884 3885 using Cache = TypePropertyCache<Private>; 3886 3887 static CachedProperties computeCachedProperties(const Type *T) { 3888 switch (T->getTypeClass()) { 3889 #define TYPE(Class,Base) 3890 #define NON_CANONICAL_TYPE(Class,Base) case Type::Class: 3891 #include "clang/AST/TypeNodes.inc" 3892 llvm_unreachable("didn't expect a non-canonical type here"); 3893 3894 #define TYPE(Class,Base) 3895 #define DEPENDENT_TYPE(Class,Base) case Type::Class: 3896 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class,Base) case Type::Class: 3897 #include "clang/AST/TypeNodes.inc" 3898 // Treat instantiation-dependent types as external. 3899 if (!T->isInstantiationDependentType()) T->dump(); 3900 assert(T->isInstantiationDependentType()); 3901 return CachedProperties(ExternalLinkage, false); 3902 3903 case Type::Auto: 3904 case Type::DeducedTemplateSpecialization: 3905 // Give non-deduced 'auto' types external linkage. We should only see them 3906 // here in error recovery. 3907 return CachedProperties(ExternalLinkage, false); 3908 3909 case Type::BitInt: 3910 case Type::Builtin: 3911 // C++ [basic.link]p8: 3912 // A type is said to have linkage if and only if: 3913 // - it is a fundamental type (3.9.1); or 3914 return CachedProperties(ExternalLinkage, false); 3915 3916 case Type::Record: 3917 case Type::Enum: { 3918 const TagDecl *Tag = cast<TagType>(T)->getDecl(); 3919 3920 // C++ [basic.link]p8: 3921 // - it is a class or enumeration type that is named (or has a name 3922 // for linkage purposes (7.1.3)) and the name has linkage; or 3923 // - it is a specialization of a class template (14); or 3924 Linkage L = Tag->getLinkageInternal(); 3925 bool IsLocalOrUnnamed = 3926 Tag->getDeclContext()->isFunctionOrMethod() || 3927 !Tag->hasNameForLinkage(); 3928 return CachedProperties(L, IsLocalOrUnnamed); 3929 } 3930 3931 // C++ [basic.link]p8: 3932 // - it is a compound type (3.9.2) other than a class or enumeration, 3933 // compounded exclusively from types that have linkage; or 3934 case Type::Complex: 3935 return Cache::get(cast<ComplexType>(T)->getElementType()); 3936 case Type::Pointer: 3937 return Cache::get(cast<PointerType>(T)->getPointeeType()); 3938 case Type::BlockPointer: 3939 return Cache::get(cast<BlockPointerType>(T)->getPointeeType()); 3940 case Type::LValueReference: 3941 case Type::RValueReference: 3942 return Cache::get(cast<ReferenceType>(T)->getPointeeType()); 3943 case Type::MemberPointer: { 3944 const auto *MPT = cast<MemberPointerType>(T); 3945 return merge(Cache::get(MPT->getClass()), 3946 Cache::get(MPT->getPointeeType())); 3947 } 3948 case Type::ConstantArray: 3949 case Type::IncompleteArray: 3950 case Type::VariableArray: 3951 return Cache::get(cast<ArrayType>(T)->getElementType()); 3952 case Type::Vector: 3953 case Type::ExtVector: 3954 return Cache::get(cast<VectorType>(T)->getElementType()); 3955 case Type::ConstantMatrix: 3956 return Cache::get(cast<ConstantMatrixType>(T)->getElementType()); 3957 case Type::FunctionNoProto: 3958 return Cache::get(cast<FunctionType>(T)->getReturnType()); 3959 case Type::FunctionProto: { 3960 const auto *FPT = cast<FunctionProtoType>(T); 3961 CachedProperties result = Cache::get(FPT->getReturnType()); 3962 for (const auto &ai : FPT->param_types()) 3963 result = merge(result, Cache::get(ai)); 3964 return result; 3965 } 3966 case Type::ObjCInterface: { 3967 Linkage L = cast<ObjCInterfaceType>(T)->getDecl()->getLinkageInternal(); 3968 return CachedProperties(L, false); 3969 } 3970 case Type::ObjCObject: 3971 return Cache::get(cast<ObjCObjectType>(T)->getBaseType()); 3972 case Type::ObjCObjectPointer: 3973 return Cache::get(cast<ObjCObjectPointerType>(T)->getPointeeType()); 3974 case Type::Atomic: 3975 return Cache::get(cast<AtomicType>(T)->getValueType()); 3976 case Type::Pipe: 3977 return Cache::get(cast<PipeType>(T)->getElementType()); 3978 } 3979 3980 llvm_unreachable("unhandled type class"); 3981 } 3982 3983 /// Determine the linkage of this type. 3984 Linkage Type::getLinkage() const { 3985 Cache::ensure(this); 3986 return TypeBits.getLinkage(); 3987 } 3988 3989 bool Type::hasUnnamedOrLocalType() const { 3990 Cache::ensure(this); 3991 return TypeBits.hasLocalOrUnnamedType(); 3992 } 3993 3994 LinkageInfo LinkageComputer::computeTypeLinkageInfo(const Type *T) { 3995 switch (T->getTypeClass()) { 3996 #define TYPE(Class,Base) 3997 #define NON_CANONICAL_TYPE(Class,Base) case Type::Class: 3998 #include "clang/AST/TypeNodes.inc" 3999 llvm_unreachable("didn't expect a non-canonical type here"); 4000 4001 #define TYPE(Class,Base) 4002 #define DEPENDENT_TYPE(Class,Base) case Type::Class: 4003 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class,Base) case Type::Class: 4004 #include "clang/AST/TypeNodes.inc" 4005 // Treat instantiation-dependent types as external. 4006 assert(T->isInstantiationDependentType()); 4007 return LinkageInfo::external(); 4008 4009 case Type::BitInt: 4010 case Type::Builtin: 4011 return LinkageInfo::external(); 4012 4013 case Type::Auto: 4014 case Type::DeducedTemplateSpecialization: 4015 return LinkageInfo::external(); 4016 4017 case Type::Record: 4018 case Type::Enum: 4019 return getDeclLinkageAndVisibility(cast<TagType>(T)->getDecl()); 4020 4021 case Type::Complex: 4022 return computeTypeLinkageInfo(cast<ComplexType>(T)->getElementType()); 4023 case Type::Pointer: 4024 return computeTypeLinkageInfo(cast<PointerType>(T)->getPointeeType()); 4025 case Type::BlockPointer: 4026 return computeTypeLinkageInfo(cast<BlockPointerType>(T)->getPointeeType()); 4027 case Type::LValueReference: 4028 case Type::RValueReference: 4029 return computeTypeLinkageInfo(cast<ReferenceType>(T)->getPointeeType()); 4030 case Type::MemberPointer: { 4031 const auto *MPT = cast<MemberPointerType>(T); 4032 LinkageInfo LV = computeTypeLinkageInfo(MPT->getClass()); 4033 LV.merge(computeTypeLinkageInfo(MPT->getPointeeType())); 4034 return LV; 4035 } 4036 case Type::ConstantArray: 4037 case Type::IncompleteArray: 4038 case Type::VariableArray: 4039 return computeTypeLinkageInfo(cast<ArrayType>(T)->getElementType()); 4040 case Type::Vector: 4041 case Type::ExtVector: 4042 return computeTypeLinkageInfo(cast<VectorType>(T)->getElementType()); 4043 case Type::ConstantMatrix: 4044 return computeTypeLinkageInfo( 4045 cast<ConstantMatrixType>(T)->getElementType()); 4046 case Type::FunctionNoProto: 4047 return computeTypeLinkageInfo(cast<FunctionType>(T)->getReturnType()); 4048 case Type::FunctionProto: { 4049 const auto *FPT = cast<FunctionProtoType>(T); 4050 LinkageInfo LV = computeTypeLinkageInfo(FPT->getReturnType()); 4051 for (const auto &ai : FPT->param_types()) 4052 LV.merge(computeTypeLinkageInfo(ai)); 4053 return LV; 4054 } 4055 case Type::ObjCInterface: 4056 return getDeclLinkageAndVisibility(cast<ObjCInterfaceType>(T)->getDecl()); 4057 case Type::ObjCObject: 4058 return computeTypeLinkageInfo(cast<ObjCObjectType>(T)->getBaseType()); 4059 case Type::ObjCObjectPointer: 4060 return computeTypeLinkageInfo( 4061 cast<ObjCObjectPointerType>(T)->getPointeeType()); 4062 case Type::Atomic: 4063 return computeTypeLinkageInfo(cast<AtomicType>(T)->getValueType()); 4064 case Type::Pipe: 4065 return computeTypeLinkageInfo(cast<PipeType>(T)->getElementType()); 4066 } 4067 4068 llvm_unreachable("unhandled type class"); 4069 } 4070 4071 bool Type::isLinkageValid() const { 4072 if (!TypeBits.isCacheValid()) 4073 return true; 4074 4075 Linkage L = LinkageComputer{} 4076 .computeTypeLinkageInfo(getCanonicalTypeInternal()) 4077 .getLinkage(); 4078 return L == TypeBits.getLinkage(); 4079 } 4080 4081 LinkageInfo LinkageComputer::getTypeLinkageAndVisibility(const Type *T) { 4082 if (!T->isCanonicalUnqualified()) 4083 return computeTypeLinkageInfo(T->getCanonicalTypeInternal()); 4084 4085 LinkageInfo LV = computeTypeLinkageInfo(T); 4086 assert(LV.getLinkage() == T->getLinkage()); 4087 return LV; 4088 } 4089 4090 LinkageInfo Type::getLinkageAndVisibility() const { 4091 return LinkageComputer{}.getTypeLinkageAndVisibility(this); 4092 } 4093 4094 Optional<NullabilityKind> 4095 Type::getNullability(const ASTContext &Context) const { 4096 QualType Type(this, 0); 4097 while (const auto *AT = Type->getAs<AttributedType>()) { 4098 // Check whether this is an attributed type with nullability 4099 // information. 4100 if (auto Nullability = AT->getImmediateNullability()) 4101 return Nullability; 4102 4103 Type = AT->getEquivalentType(); 4104 } 4105 return None; 4106 } 4107 4108 bool Type::canHaveNullability(bool ResultIfUnknown) const { 4109 QualType type = getCanonicalTypeInternal(); 4110 4111 switch (type->getTypeClass()) { 4112 // We'll only see canonical types here. 4113 #define NON_CANONICAL_TYPE(Class, Parent) \ 4114 case Type::Class: \ 4115 llvm_unreachable("non-canonical type"); 4116 #define TYPE(Class, Parent) 4117 #include "clang/AST/TypeNodes.inc" 4118 4119 // Pointer types. 4120 case Type::Pointer: 4121 case Type::BlockPointer: 4122 case Type::MemberPointer: 4123 case Type::ObjCObjectPointer: 4124 return true; 4125 4126 // Dependent types that could instantiate to pointer types. 4127 case Type::UnresolvedUsing: 4128 case Type::TypeOfExpr: 4129 case Type::TypeOf: 4130 case Type::Decltype: 4131 case Type::UnaryTransform: 4132 case Type::TemplateTypeParm: 4133 case Type::SubstTemplateTypeParmPack: 4134 case Type::DependentName: 4135 case Type::DependentTemplateSpecialization: 4136 case Type::Auto: 4137 return ResultIfUnknown; 4138 4139 // Dependent template specializations can instantiate to pointer 4140 // types unless they're known to be specializations of a class 4141 // template. 4142 case Type::TemplateSpecialization: 4143 if (TemplateDecl *templateDecl 4144 = cast<TemplateSpecializationType>(type.getTypePtr()) 4145 ->getTemplateName().getAsTemplateDecl()) { 4146 if (isa<ClassTemplateDecl>(templateDecl)) 4147 return false; 4148 } 4149 return ResultIfUnknown; 4150 4151 case Type::Builtin: 4152 switch (cast<BuiltinType>(type.getTypePtr())->getKind()) { 4153 // Signed, unsigned, and floating-point types cannot have nullability. 4154 #define SIGNED_TYPE(Id, SingletonId) case BuiltinType::Id: 4155 #define UNSIGNED_TYPE(Id, SingletonId) case BuiltinType::Id: 4156 #define FLOATING_TYPE(Id, SingletonId) case BuiltinType::Id: 4157 #define BUILTIN_TYPE(Id, SingletonId) 4158 #include "clang/AST/BuiltinTypes.def" 4159 return false; 4160 4161 // Dependent types that could instantiate to a pointer type. 4162 case BuiltinType::Dependent: 4163 case BuiltinType::Overload: 4164 case BuiltinType::BoundMember: 4165 case BuiltinType::PseudoObject: 4166 case BuiltinType::UnknownAny: 4167 case BuiltinType::ARCUnbridgedCast: 4168 return ResultIfUnknown; 4169 4170 case BuiltinType::Void: 4171 case BuiltinType::ObjCId: 4172 case BuiltinType::ObjCClass: 4173 case BuiltinType::ObjCSel: 4174 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \ 4175 case BuiltinType::Id: 4176 #include "clang/Basic/OpenCLImageTypes.def" 4177 #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \ 4178 case BuiltinType::Id: 4179 #include "clang/Basic/OpenCLExtensionTypes.def" 4180 case BuiltinType::OCLSampler: 4181 case BuiltinType::OCLEvent: 4182 case BuiltinType::OCLClkEvent: 4183 case BuiltinType::OCLQueue: 4184 case BuiltinType::OCLReserveID: 4185 #define SVE_TYPE(Name, Id, SingletonId) \ 4186 case BuiltinType::Id: 4187 #include "clang/Basic/AArch64SVEACLETypes.def" 4188 #define PPC_VECTOR_TYPE(Name, Id, Size) \ 4189 case BuiltinType::Id: 4190 #include "clang/Basic/PPCTypes.def" 4191 #define RVV_TYPE(Name, Id, SingletonId) case BuiltinType::Id: 4192 #include "clang/Basic/RISCVVTypes.def" 4193 case BuiltinType::BuiltinFn: 4194 case BuiltinType::NullPtr: 4195 case BuiltinType::IncompleteMatrixIdx: 4196 case BuiltinType::OMPArraySection: 4197 case BuiltinType::OMPArrayShaping: 4198 case BuiltinType::OMPIterator: 4199 return false; 4200 } 4201 llvm_unreachable("unknown builtin type"); 4202 4203 // Non-pointer types. 4204 case Type::Complex: 4205 case Type::LValueReference: 4206 case Type::RValueReference: 4207 case Type::ConstantArray: 4208 case Type::IncompleteArray: 4209 case Type::VariableArray: 4210 case Type::DependentSizedArray: 4211 case Type::DependentVector: 4212 case Type::DependentSizedExtVector: 4213 case Type::Vector: 4214 case Type::ExtVector: 4215 case Type::ConstantMatrix: 4216 case Type::DependentSizedMatrix: 4217 case Type::DependentAddressSpace: 4218 case Type::FunctionProto: 4219 case Type::FunctionNoProto: 4220 case Type::Record: 4221 case Type::DeducedTemplateSpecialization: 4222 case Type::Enum: 4223 case Type::InjectedClassName: 4224 case Type::PackExpansion: 4225 case Type::ObjCObject: 4226 case Type::ObjCInterface: 4227 case Type::Atomic: 4228 case Type::Pipe: 4229 case Type::BitInt: 4230 case Type::DependentBitInt: 4231 return false; 4232 } 4233 llvm_unreachable("bad type kind!"); 4234 } 4235 4236 llvm::Optional<NullabilityKind> 4237 AttributedType::getImmediateNullability() const { 4238 if (getAttrKind() == attr::TypeNonNull) 4239 return NullabilityKind::NonNull; 4240 if (getAttrKind() == attr::TypeNullable) 4241 return NullabilityKind::Nullable; 4242 if (getAttrKind() == attr::TypeNullUnspecified) 4243 return NullabilityKind::Unspecified; 4244 if (getAttrKind() == attr::TypeNullableResult) 4245 return NullabilityKind::NullableResult; 4246 return None; 4247 } 4248 4249 Optional<NullabilityKind> AttributedType::stripOuterNullability(QualType &T) { 4250 QualType AttrTy = T; 4251 if (auto MacroTy = dyn_cast<MacroQualifiedType>(T)) 4252 AttrTy = MacroTy->getUnderlyingType(); 4253 4254 if (auto attributed = dyn_cast<AttributedType>(AttrTy)) { 4255 if (auto nullability = attributed->getImmediateNullability()) { 4256 T = attributed->getModifiedType(); 4257 return nullability; 4258 } 4259 } 4260 4261 return None; 4262 } 4263 4264 bool Type::isBlockCompatibleObjCPointerType(ASTContext &ctx) const { 4265 const auto *objcPtr = getAs<ObjCObjectPointerType>(); 4266 if (!objcPtr) 4267 return false; 4268 4269 if (objcPtr->isObjCIdType()) { 4270 // id is always okay. 4271 return true; 4272 } 4273 4274 // Blocks are NSObjects. 4275 if (ObjCInterfaceDecl *iface = objcPtr->getInterfaceDecl()) { 4276 if (iface->getIdentifier() != ctx.getNSObjectName()) 4277 return false; 4278 4279 // Continue to check qualifiers, below. 4280 } else if (objcPtr->isObjCQualifiedIdType()) { 4281 // Continue to check qualifiers, below. 4282 } else { 4283 return false; 4284 } 4285 4286 // Check protocol qualifiers. 4287 for (ObjCProtocolDecl *proto : objcPtr->quals()) { 4288 // Blocks conform to NSObject and NSCopying. 4289 if (proto->getIdentifier() != ctx.getNSObjectName() && 4290 proto->getIdentifier() != ctx.getNSCopyingName()) 4291 return false; 4292 } 4293 4294 return true; 4295 } 4296 4297 Qualifiers::ObjCLifetime Type::getObjCARCImplicitLifetime() const { 4298 if (isObjCARCImplicitlyUnretainedType()) 4299 return Qualifiers::OCL_ExplicitNone; 4300 return Qualifiers::OCL_Strong; 4301 } 4302 4303 bool Type::isObjCARCImplicitlyUnretainedType() const { 4304 assert(isObjCLifetimeType() && 4305 "cannot query implicit lifetime for non-inferrable type"); 4306 4307 const Type *canon = getCanonicalTypeInternal().getTypePtr(); 4308 4309 // Walk down to the base type. We don't care about qualifiers for this. 4310 while (const auto *array = dyn_cast<ArrayType>(canon)) 4311 canon = array->getElementType().getTypePtr(); 4312 4313 if (const auto *opt = dyn_cast<ObjCObjectPointerType>(canon)) { 4314 // Class and Class<Protocol> don't require retention. 4315 if (opt->getObjectType()->isObjCClass()) 4316 return true; 4317 } 4318 4319 return false; 4320 } 4321 4322 bool Type::isObjCNSObjectType() const { 4323 const Type *cur = this; 4324 while (true) { 4325 if (const auto *typedefType = dyn_cast<TypedefType>(cur)) 4326 return typedefType->getDecl()->hasAttr<ObjCNSObjectAttr>(); 4327 4328 // Single-step desugar until we run out of sugar. 4329 QualType next = cur->getLocallyUnqualifiedSingleStepDesugaredType(); 4330 if (next.getTypePtr() == cur) return false; 4331 cur = next.getTypePtr(); 4332 } 4333 } 4334 4335 bool Type::isObjCIndependentClassType() const { 4336 if (const auto *typedefType = dyn_cast<TypedefType>(this)) 4337 return typedefType->getDecl()->hasAttr<ObjCIndependentClassAttr>(); 4338 return false; 4339 } 4340 4341 bool Type::isObjCRetainableType() const { 4342 return isObjCObjectPointerType() || 4343 isBlockPointerType() || 4344 isObjCNSObjectType(); 4345 } 4346 4347 bool Type::isObjCIndirectLifetimeType() const { 4348 if (isObjCLifetimeType()) 4349 return true; 4350 if (const auto *OPT = getAs<PointerType>()) 4351 return OPT->getPointeeType()->isObjCIndirectLifetimeType(); 4352 if (const auto *Ref = getAs<ReferenceType>()) 4353 return Ref->getPointeeType()->isObjCIndirectLifetimeType(); 4354 if (const auto *MemPtr = getAs<MemberPointerType>()) 4355 return MemPtr->getPointeeType()->isObjCIndirectLifetimeType(); 4356 return false; 4357 } 4358 4359 /// Returns true if objects of this type have lifetime semantics under 4360 /// ARC. 4361 bool Type::isObjCLifetimeType() const { 4362 const Type *type = this; 4363 while (const ArrayType *array = type->getAsArrayTypeUnsafe()) 4364 type = array->getElementType().getTypePtr(); 4365 return type->isObjCRetainableType(); 4366 } 4367 4368 /// Determine whether the given type T is a "bridgable" Objective-C type, 4369 /// which is either an Objective-C object pointer type or an 4370 bool Type::isObjCARCBridgableType() const { 4371 return isObjCObjectPointerType() || isBlockPointerType(); 4372 } 4373 4374 /// Determine whether the given type T is a "bridgeable" C type. 4375 bool Type::isCARCBridgableType() const { 4376 const auto *Pointer = getAs<PointerType>(); 4377 if (!Pointer) 4378 return false; 4379 4380 QualType Pointee = Pointer->getPointeeType(); 4381 return Pointee->isVoidType() || Pointee->isRecordType(); 4382 } 4383 4384 /// Check if the specified type is the CUDA device builtin surface type. 4385 bool Type::isCUDADeviceBuiltinSurfaceType() const { 4386 if (const auto *RT = getAs<RecordType>()) 4387 return RT->getDecl()->hasAttr<CUDADeviceBuiltinSurfaceTypeAttr>(); 4388 return false; 4389 } 4390 4391 /// Check if the specified type is the CUDA device builtin texture type. 4392 bool Type::isCUDADeviceBuiltinTextureType() const { 4393 if (const auto *RT = getAs<RecordType>()) 4394 return RT->getDecl()->hasAttr<CUDADeviceBuiltinTextureTypeAttr>(); 4395 return false; 4396 } 4397 4398 bool Type::hasSizedVLAType() const { 4399 if (!isVariablyModifiedType()) return false; 4400 4401 if (const auto *ptr = getAs<PointerType>()) 4402 return ptr->getPointeeType()->hasSizedVLAType(); 4403 if (const auto *ref = getAs<ReferenceType>()) 4404 return ref->getPointeeType()->hasSizedVLAType(); 4405 if (const ArrayType *arr = getAsArrayTypeUnsafe()) { 4406 if (isa<VariableArrayType>(arr) && 4407 cast<VariableArrayType>(arr)->getSizeExpr()) 4408 return true; 4409 4410 return arr->getElementType()->hasSizedVLAType(); 4411 } 4412 4413 return false; 4414 } 4415 4416 QualType::DestructionKind QualType::isDestructedTypeImpl(QualType type) { 4417 switch (type.getObjCLifetime()) { 4418 case Qualifiers::OCL_None: 4419 case Qualifiers::OCL_ExplicitNone: 4420 case Qualifiers::OCL_Autoreleasing: 4421 break; 4422 4423 case Qualifiers::OCL_Strong: 4424 return DK_objc_strong_lifetime; 4425 case Qualifiers::OCL_Weak: 4426 return DK_objc_weak_lifetime; 4427 } 4428 4429 if (const auto *RT = 4430 type->getBaseElementTypeUnsafe()->getAs<RecordType>()) { 4431 const RecordDecl *RD = RT->getDecl(); 4432 if (const auto *CXXRD = dyn_cast<CXXRecordDecl>(RD)) { 4433 /// Check if this is a C++ object with a non-trivial destructor. 4434 if (CXXRD->hasDefinition() && !CXXRD->hasTrivialDestructor()) 4435 return DK_cxx_destructor; 4436 } else { 4437 /// Check if this is a C struct that is non-trivial to destroy or an array 4438 /// that contains such a struct. 4439 if (RD->isNonTrivialToPrimitiveDestroy()) 4440 return DK_nontrivial_c_struct; 4441 } 4442 } 4443 4444 return DK_none; 4445 } 4446 4447 CXXRecordDecl *MemberPointerType::getMostRecentCXXRecordDecl() const { 4448 return getClass()->getAsCXXRecordDecl()->getMostRecentNonInjectedDecl(); 4449 } 4450 4451 void clang::FixedPointValueToString(SmallVectorImpl<char> &Str, 4452 llvm::APSInt Val, unsigned Scale) { 4453 llvm::FixedPointSemantics FXSema(Val.getBitWidth(), Scale, Val.isSigned(), 4454 /*IsSaturated=*/false, 4455 /*HasUnsignedPadding=*/false); 4456 llvm::APFixedPoint(Val, FXSema).toString(Str); 4457 } 4458 4459 AutoType::AutoType(QualType DeducedAsType, AutoTypeKeyword Keyword, 4460 TypeDependence ExtraDependence, QualType Canon, 4461 ConceptDecl *TypeConstraintConcept, 4462 ArrayRef<TemplateArgument> TypeConstraintArgs) 4463 : DeducedType(Auto, DeducedAsType, ExtraDependence, Canon) { 4464 AutoTypeBits.Keyword = (unsigned)Keyword; 4465 AutoTypeBits.NumArgs = TypeConstraintArgs.size(); 4466 this->TypeConstraintConcept = TypeConstraintConcept; 4467 if (TypeConstraintConcept) { 4468 TemplateArgument *ArgBuffer = getArgBuffer(); 4469 for (const TemplateArgument &Arg : TypeConstraintArgs) { 4470 addDependence( 4471 toSyntacticDependence(toTypeDependence(Arg.getDependence()))); 4472 4473 new (ArgBuffer++) TemplateArgument(Arg); 4474 } 4475 } 4476 } 4477 4478 void AutoType::Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context, 4479 QualType Deduced, AutoTypeKeyword Keyword, 4480 bool IsDependent, ConceptDecl *CD, 4481 ArrayRef<TemplateArgument> Arguments) { 4482 ID.AddPointer(Deduced.getAsOpaquePtr()); 4483 ID.AddInteger((unsigned)Keyword); 4484 ID.AddBoolean(IsDependent); 4485 ID.AddPointer(CD); 4486 for (const TemplateArgument &Arg : Arguments) 4487 Arg.Profile(ID, Context); 4488 } 4489