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