brintos

brintos / llvm-project-archived public Read only

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