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