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
55using namespace clang;
56
57bool 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
72bool Qualifiers::isTargetAddressSpaceSupersetOf(LangAS A, LangAS B,
73 const ASTContext &Ctx) {
74 // In OpenCLC v2.0 s6.5.5: every address space except for __constant can 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(AS: A) || A == LangAS::Default) &&
86 (isPtrSizeAddressSpace(AS: 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
109const 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
130bool QualType::mayBeDynamicClass() const {
131 const auto *ClassDecl = getTypePtr()->getPointeeCXXRecordDecl();
132 return ClassDecl && ClassDecl->mayBeDynamicClass();
133}
134
135bool QualType::mayBeNotDynamicClass() const {
136 const auto *ClassDecl = getTypePtr()->getPointeeCXXRecordDecl();
137 return !ClassDecl || ClassDecl->mayBeNonDynamicClass();
138}
139
140bool QualType::isConstant(QualType T, const ASTContext &Ctx) {
141 if (T.isConstQualified())
142 return true;
143
144 if (const ArrayType *AT = Ctx.getAsArrayType(T))
145 return AT->getElementType().isConstant(Ctx);
146
147 return T.getAddressSpace() == LangAS::opencl_constant;
148}
149
150std::optional<QualType::NonConstantStorageReason>
151QualType::isNonConstantStorage(const ASTContext &Ctx, bool ExcludeCtor,
152 bool ExcludeDtor) {
153 if (!isConstant(Ctx) && !(*this)->isReferenceType())
154 return NonConstantStorageReason::NonConstNonReferenceType;
155 if (!Ctx.getLangOpts().CPlusPlus)
156 return std::nullopt;
157 if (const CXXRecordDecl *Record =
158 Ctx.getBaseElementType(QT: *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,
174ArrayType::ArrayType(TypeClass tc, QualType et, QualType can,
175 ArraySizeModifier sm, unsigned tq, const Expr *sz)
176 // Note, we need to check for DependentSizedArrayType explicitly 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(E: sm);
195}
196
197ConstantArrayType *
198ConstantArrayType::Create(const ASTContext &Ctx, QualType ET, QualType Can,
199 const llvm::APInt &Sz, const Expr *SzExpr,
200 ArraySizeModifier SzMod, unsigned Qual) {
201 bool NeedsExternalSize = SzExpr != nullptr || Sz.ugt(RHS: 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
213unsigned
214ConstantArrayType::getNumAddressingBits(const ASTContext &Context,
215 QualType ElementType,
216 const llvm::APInt &NumElements) {
217 uint64_t ElementSize = Context.getTypeSizeInChars(T: 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(Value: ElementSize)) {
226 return NumElements.getActiveBits() + llvm::Log2_64(Value: 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(Value: TotalSize);
235 }
236
237 // Otherwise, use APSInt to handle arbitrary sized values.
238 llvm::APSInt SizeExtended(NumElements, true);
239 unsigned SizeTypeBits = Context.getTypeSize(T: Context.getSizeType());
240 SizeExtended = SizeExtended.extend(
241 width: std::max(a: SizeTypeBits, b: SizeExtended.getBitWidth()) * 2);
242
243 llvm::APSInt TotalSize(llvm::APInt(SizeExtended.getBitWidth(), ElementSize));
244 TotalSize *= SizeExtended;
245
246 return TotalSize.getActiveBits();
247}
248
249unsigned
250ConstantArrayType::getNumAddressingBits(const ASTContext &Context) const {
251 return getNumAddressingBits(Context, getElementType(), getSize());
252}
253
254unsigned ConstantArrayType::getMaxSizeBits(const ASTContext &Context) {
255 unsigned Bits = Context.getTypeSize(T: 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
266void ConstantArrayType::Profile(llvm::FoldingSetNodeID &ID,
267 const ASTContext &Context, QualType ET,
268 uint64_t ArraySize, const Expr *SizeExpr,
269 ArraySizeModifier SizeMod, unsigned TypeQuals) {
270 ID.AddPointer(Ptr: ET.getAsOpaquePtr());
271 ID.AddInteger(I: ArraySize);
272 ID.AddInteger(I: llvm::to_underlying(E: SizeMod));
273 ID.AddInteger(I: TypeQuals);
274 ID.AddBoolean(B: SizeExpr != nullptr);
275 if (SizeExpr)
276 SizeExpr->Profile(ID, Context, true);
277}
278
279QualType ArrayParameterType::getConstantArrayType(const ASTContext &Ctx) const {
280 return Ctx.getConstantArrayType(EltTy: getElementType(), ArySize: getSize(), SizeExpr: getSizeExpr(),
281 ASM: getSizeModifier(),
282 IndexTypeQuals: getIndexTypeQualifiers().getAsOpaqueValue());
283}
284
285DependentSizedArrayType::DependentSizedArrayType(QualType et, QualType can,
286 Expr *e, ArraySizeModifier sm,
287 unsigned tq)
288 : ArrayType(DependentSizedArray, et, can, sm, tq, e), SizeExpr((Stmt *)e) {}
289
290void DependentSizedArrayType::Profile(llvm::FoldingSetNodeID &ID,
291 const ASTContext &Context, QualType ET,
292 ArraySizeModifier SizeMod,
293 unsigned TypeQuals, Expr *E) {
294 ID.AddPointer(Ptr: ET.getAsOpaquePtr());
295 ID.AddInteger(I: llvm::to_underlying(E: SizeMod));
296 ID.AddInteger(I: TypeQuals);
297 if (E)
298 E->Profile(ID, Context, true);
299}
300
301DependentVectorType::DependentVectorType(QualType ElementType,
302 QualType CanonType, Expr *SizeExpr,
303 SourceLocation Loc, VectorKind VecKind)
304 : Type(DependentVector, CanonType,
305 TypeDependence::DependentInstantiation |
306 ElementType->getDependence() |
307 (SizeExpr ? toTypeDependence(SizeExpr->getDependence())
308 : TypeDependence::None)),
309 ElementType(ElementType), SizeExpr(SizeExpr), Loc(Loc) {
310 VectorTypeBits.VecKind = llvm::to_underlying(E: VecKind);
311}
312
313void DependentVectorType::Profile(llvm::FoldingSetNodeID &ID,
314 const ASTContext &Context,
315 QualType ElementType, const Expr *SizeExpr,
316 VectorKind VecKind) {
317 ID.AddPointer(Ptr: ElementType.getAsOpaquePtr());
318 ID.AddInteger(I: llvm::to_underlying(E: VecKind));
319 SizeExpr->Profile(ID, Context, true);
320}
321
322DependentSizedExtVectorType::DependentSizedExtVectorType(QualType ElementType,
323 QualType can,
324 Expr *SizeExpr,
325 SourceLocation loc)
326 : Type(DependentSizedExtVector, can,
327 TypeDependence::DependentInstantiation |
328 ElementType->getDependence() |
329 (SizeExpr ? toTypeDependence(SizeExpr->getDependence())
330 : TypeDependence::None)),
331 SizeExpr(SizeExpr), ElementType(ElementType), loc(loc) {}
332
333void DependentSizedExtVectorType::Profile(llvm::FoldingSetNodeID &ID,
334 const ASTContext &Context,
335 QualType ElementType,
336 Expr *SizeExpr) {
337 ID.AddPointer(Ptr: ElementType.getAsOpaquePtr());
338 SizeExpr->Profile(ID, Context, true);
339}
340
341DependentAddressSpaceType::DependentAddressSpaceType(QualType PointeeType,
342 QualType can,
343 Expr *AddrSpaceExpr,
344 SourceLocation loc)
345 : Type(DependentAddressSpace, can,
346 TypeDependence::DependentInstantiation |
347 PointeeType->getDependence() |
348 (AddrSpaceExpr ? toTypeDependence(AddrSpaceExpr->getDependence())
349 : TypeDependence::None)),
350 AddrSpaceExpr(AddrSpaceExpr), PointeeType(PointeeType), loc(loc) {}
351
352void DependentAddressSpaceType::Profile(llvm::FoldingSetNodeID &ID,
353 const ASTContext &Context,
354 QualType PointeeType,
355 Expr *AddrSpaceExpr) {
356 ID.AddPointer(Ptr: PointeeType.getAsOpaquePtr());
357 AddrSpaceExpr->Profile(ID, Context, true);
358}
359
360MatrixType::MatrixType(TypeClass tc, QualType matrixType, QualType canonType,
361 const Expr *RowExpr, const Expr *ColumnExpr)
362 : Type(tc, canonType,
363 (RowExpr ? (matrixType->getDependence() | TypeDependence::Dependent |
364 TypeDependence::Instantiation |
365 (matrixType->isVariablyModifiedType()
366 ? TypeDependence::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
378ConstantMatrixType::ConstantMatrixType(QualType matrixType, unsigned nRows,
379 unsigned nColumns, QualType canonType)
380 : ConstantMatrixType(ConstantMatrix, matrixType, nRows, nColumns,
381 canonType) {}
382
383ConstantMatrixType::ConstantMatrixType(TypeClass tc, QualType matrixType,
384 unsigned nRows, unsigned nColumns,
385 QualType canonType)
386 : MatrixType(tc, matrixType, canonType), NumRows(nRows),
387 NumColumns(nColumns) {}
388
389DependentSizedMatrixType::DependentSizedMatrixType(QualType ElementType,
390 QualType CanonicalType,
391 Expr *RowExpr,
392 Expr *ColumnExpr,
393 SourceLocation loc)
394 : MatrixType(DependentSizedMatrix, ElementType, CanonicalType, RowExpr,
395 ColumnExpr),
396 RowExpr(RowExpr), ColumnExpr(ColumnExpr), loc(loc) {}
397
398void DependentSizedMatrixType::Profile(llvm::FoldingSetNodeID &ID,
399 const ASTContext &CTX,
400 QualType ElementType, Expr *RowExpr,
401 Expr *ColumnExpr) {
402 ID.AddPointer(Ptr: ElementType.getAsOpaquePtr());
403 RowExpr->Profile(ID, CTX, true);
404 ColumnExpr->Profile(ID, CTX, true);
405}
406
407VectorType::VectorType(QualType vecType, unsigned nElements, QualType canonType,
408 VectorKind vecKind)
409 : VectorType(Vector, vecType, nElements, canonType, vecKind) {}
410
411VectorType::VectorType(TypeClass tc, QualType vecType, unsigned nElements,
412 QualType canonType, VectorKind vecKind)
413 : Type(tc, canonType, vecType->getDependence()), ElementType(vecType) {
414 VectorTypeBits.VecKind = llvm::to_underlying(E: vecKind);
415 VectorTypeBits.NumElements = nElements;
416}
417
418bool Type::isPackedVectorBoolType(const ASTContext &ctx) const {
419 if (ctx.getLangOpts().HLSL)
420 return false;
421 return isExtVectorBoolType();
422}
423
424BitIntType::BitIntType(bool IsUnsigned, unsigned NumBits)
425 : Type(BitInt, QualType{}, TypeDependence::None), IsUnsigned(IsUnsigned),
426 NumBits(NumBits) {}
427
428DependentBitIntType::DependentBitIntType(bool IsUnsigned, Expr *NumBitsExpr)
429 : Type(DependentBitInt, QualType{},
430 toTypeDependence(NumBitsExpr->getDependence())),
431 ExprAndUnsigned(NumBitsExpr, IsUnsigned) {}
432
433bool DependentBitIntType::isUnsigned() const {
434 return ExprAndUnsigned.getInt();
435}
436
437clang::Expr *DependentBitIntType::getNumBitsExpr() const {
438 return ExprAndUnsigned.getPointer();
439}
440
441void DependentBitIntType::Profile(llvm::FoldingSetNodeID &ID,
442 const ASTContext &Context, bool IsUnsigned,
443 Expr *NumBitsExpr) {
444 ID.AddBoolean(B: IsUnsigned);
445 NumBitsExpr->Profile(ID, Context, true);
446}
447
448bool BoundsAttributedType::referencesFieldDecls() const {
449 return llvm::any_of(Range: dependent_decls(),
450 P: [](const TypeCoupledDeclRefInfo &Info) {
451 return isa<FieldDecl>(Val: Info.getDecl());
452 });
453}
454
455void CountAttributedType::Profile(llvm::FoldingSetNodeID &ID,
456 QualType WrappedTy, Expr *CountExpr,
457 bool CountInBytes, bool OrNull) {
458 ID.AddPointer(Ptr: WrappedTy.getAsOpaquePtr());
459 ID.AddBoolean(B: CountInBytes);
460 ID.AddBoolean(B: 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(Ptr: 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.
471const Type *Type::getArrayElementTypeNoTypeQual() const {
472 // If this is directly an array type, return it.
473 if (const auto *ATy = dyn_cast<ArrayType>(Val: 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>(Val: 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.
493QualType QualType::getDesugaredType(QualType T, const ASTContext &Context) {
494 SplitQualType split = getSplitDesugaredType(T);
495 return Context.getQualifiedType(T: split.Ty, Qs: split.Quals);
496}
497
498QualType QualType::getSingleStepDesugaredTypeImpl(QualType type,
499 const ASTContext &Context) {
500 SplitQualType split = type.split();
501 QualType desugar = split.Ty->getLocallyUnqualifiedSingleStepDesugaredType();
502 return Context.getQualifiedType(T: desugar, Qs: 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
521QualType Type::getLocallyUnqualifiedSingleStepDesugaredType() const {
522 switch (getTypeClass()) {
523#define ABSTRACT_TYPE(Class, Parent)
524#define TYPE(Class, Parent) \
525 case Type::Class: { \
526 const auto *ty = cast<Class##Type>(this); \
527 if (!ty->isSugared()) \
528 return QualType(ty, 0); \
529 return ty->desugar(); \
530 }
531#include "clang/AST/TypeNodes.inc"
532 }
533 llvm_unreachable("bad type kind!");
534}
535
536SplitQualType QualType::getSplitDesugaredType(QualType T) {
537 QualifierCollector Qs;
538
539 QualType Cur = T;
540 while (true) {
541 const Type *CurTy = Qs.strip(type: Cur);
542 switch (CurTy->getTypeClass()) {
543#define ABSTRACT_TYPE(Class, Parent)
544#define TYPE(Class, Parent) \
545 case Type::Class: { \
546 const auto *Ty = cast<Class##Type>(CurTy); \
547 if (!Ty->isSugared()) \
548 return SplitQualType(Ty, Qs); \
549 Cur = Ty->desugar(); \
550 break; \
551 }
552#include "clang/AST/TypeNodes.inc"
553 }
554 }
555}
556
557SplitQualType QualType::getSplitUnqualifiedTypeImpl(QualType type) {
558 SplitQualType split = type.split();
559
560 // All the qualifiers we've seen so far.
561 Qualifiers quals = split.Quals;
562
563 // The last type node we saw with any nodes inside it.
564 const Type *lastTypeWithQuals = split.Ty;
565
566 while (true) {
567 QualType next;
568
569 // Do a single-step desugar, aborting the loop if the type isn'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(qs: split.Quals);
590 }
591 }
592
593done:
594 return SplitQualType(lastTypeWithQuals, quals);
595}
596
597QualType QualType::IgnoreParens(QualType T) {
598 // FIXME: this seems inherently un-qualifiers-safe.
599 while (const auto *PT = T->getAs<ParenType>())
600 T = PT->getInnerType();
601 return T;
602}
603
604/// This will check for a T (which should be a Type which can act as
605/// sugar, such as a TypedefType) by removing any existing sugar until it
606/// reaches a T or a non-sugared type.
607template <typename T> static const T *getAsSugar(const Type *Cur) {
608 while (true) {
609 if (const auto *Sugar = dyn_cast<T>(Cur))
610 return Sugar;
611 switch (Cur->getTypeClass()) {
612#define ABSTRACT_TYPE(Class, Parent)
613#define TYPE(Class, Parent) \
614 case Type::Class: { \
615 const auto *Ty = cast<Class##Type>(Cur); \
616 if (!Ty->isSugared()) \
617 return 0; \
618 Cur = Ty->desugar().getTypePtr(); \
619 break; \
620 }
621#include "clang/AST/TypeNodes.inc"
622 }
623 }
624}
625
626template <> const TypedefType *Type::getAs() const {
627 return getAsSugar<TypedefType>(this);
628}
629
630template <> const UsingType *Type::getAs() const {
631 return getAsSugar<UsingType>(Cur: this);
632}
633
634template <> const TemplateSpecializationType *Type::getAs() const {
635 return getAsSugar<TemplateSpecializationType>(Cur: this);
636}
637
638template <> const AttributedType *Type::getAs() const {
639 return getAsSugar<AttributedType>(Cur: this);
640}
641
642template <> const BoundsAttributedType *Type::getAs() const {
643 return getAsSugar<BoundsAttributedType>(Cur: this);
644}
645
646template <> const CountAttributedType *Type::getAs() const {
647 return getAsSugar<CountAttributedType>(Cur: 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.
653const Type *Type::getUnqualifiedDesugaredType() const {
654 const Type *Cur = this;
655
656 while (true) {
657 switch (Cur->getTypeClass()) {
658#define ABSTRACT_TYPE(Class, Parent)
659#define TYPE(Class, Parent) \
660 case Class: { \
661 const auto *Ty = cast<Class##Type>(Cur); \
662 if (!Ty->isSugared()) \
663 return Cur; \
664 Cur = Ty->desugar().getTypePtr(); \
665 break; \
666 }
667#include "clang/AST/TypeNodes.inc"
668 }
669 }
670}
671
672bool Type::isClassType() const {
673 if (const auto *RT = getAs<RecordType>())
674 return RT->getDecl()->isClass();
675 return false;
676}
677
678bool Type::isStructureType() const {
679 if (const auto *RT = getAs<RecordType>())
680 return RT->getDecl()->isStruct();
681 return false;
682}
683
684bool 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
694bool Type::isObjCBoxableRecordType() const {
695 if (const auto *RT = getAs<RecordType>())
696 return RT->getDecl()->hasAttr<ObjCBoxableAttr>();
697 return false;
698}
699
700bool Type::isInterfaceType() const {
701 if (const auto *RT = getAs<RecordType>())
702 return RT->getDecl()->isInterface();
703 return false;
704}
705
706bool 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
714bool Type::isVoidPointerType() const {
715 if (const auto *PT = getAs<PointerType>())
716 return PT->getPointeeType()->isVoidType();
717 return false;
718}
719
720bool Type::isUnionType() const {
721 if (const auto *RT = getAs<RecordType>())
722 return RT->getDecl()->isUnion();
723 return false;
724}
725
726bool Type::isComplexType() const {
727 if (const auto *CT = dyn_cast<ComplexType>(CanonicalType))
728 return CT->getElementType()->isFloatingType();
729 return false;
730}
731
732bool Type::isComplexIntegerType() const {
733 // Check for GCC complex integer extension.
734 return getAsComplexIntegerType();
735}
736
737bool Type::isScopedEnumeralType() const {
738 if (const auto *ET = getAs<EnumType>())
739 return ET->getDecl()->isScoped();
740 return false;
741}
742
743bool Type::isCountAttributedType() const {
744 return getAs<CountAttributedType>();
745}
746
747const ComplexType *Type::getAsComplexIntegerType() const {
748 if (const auto *Complex = getAs<ComplexType>())
749 if (Complex->getElementType()->isIntegerType())
750 return Complex;
751 return nullptr;
752}
753
754QualType 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
770const RecordType *Type::getAsStructureType() const {
771 // If this is directly a structure type, return it.
772 if (const auto *RT = dyn_cast<RecordType>(Val: 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>(Val: getUnqualifiedDesugaredType());
785 }
786 return nullptr;
787}
788
789const RecordType *Type::getAsUnionType() const {
790 // If this is directly a union type, return it.
791 if (const auto *RT = dyn_cast<RecordType>(Val: 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>(Val: getUnqualifiedDesugaredType());
804 }
805
806 return nullptr;
807}
808
809bool 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
836bool 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
853ObjCTypeParamType::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
860ObjCObjectType::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(dest: getTypeArgStorage(), src: typeArgs.data(),
872 n: 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
882bool 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>(Val: objcObject))
891 return false;
892
893 return objcObject->isSpecialized();
894 }
895
896 // Not specialized.
897 return false;
898}
899
900ArrayRef<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>(Val: objcObject))
909 return {};
910
911 return objcObject->getTypeArgs();
912 }
913
914 // No type arguments.
915 return {};
916}
917
918bool 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>(Val: objcObject))
926 return false;
927
928 return objcObject->isKindOfType();
929 }
930
931 // Not a "__kindof" type.
932 return false;
933}
934
935QualType
936ObjCObjectType::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 Base: ctx.getQualifiedType(T: baseType, Qs: splitBaseType.Quals),
948 typeArgs: getTypeArgsAsWritten(),
949 /*protocols=*/{},
950 /*isKindOf=*/false);
951}
952
953ObjCInterfaceDecl *ObjCInterfaceType::getDecl() const {
954 ObjCInterfaceDecl *Canon = Decl->getCanonicalDecl();
955 if (ObjCInterfaceDecl *Def = Canon->getDefinition())
956 return Def;
957 return Canon;
958}
959
960const 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(OIT: obj)->castAs<ObjCObjectPointerType>();
967}
968
969namespace {
970
971/// Visitor used to perform a simple type transformation that does not change
972/// the semantics of the type.
973template <typename Derived>
974struct SimpleTransformVisitor : public TypeVisitor<Derived, QualType> {
975 ASTContext &Ctx;
976
977 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(T: result, Qs: splitType.Quals);
989 }
990
991public:
992 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
1015 TRIVIAL_TYPE_CLASS(Builtin)
1016
1017 QualType VisitComplexType(const ComplexType *T) {
1018 QualType elementType = recurse(type: 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(T: elementType);
1026 }
1027
1028 QualType VisitPointerType(const PointerType *T) {
1029 QualType pointeeType = recurse(type: 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(T: pointeeType);
1037 }
1038
1039 QualType VisitBlockPointerType(const BlockPointerType *T) {
1040 QualType pointeeType = recurse(type: 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(T: pointeeType);
1048 }
1049
1050 QualType VisitLValueReferenceType(const LValueReferenceType *T) {
1051 QualType pointeeType = recurse(type: 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(T: pointeeType, SpelledAsLValue: T->isSpelledAsLValue());
1060 }
1061
1062 QualType VisitRValueReferenceType(const RValueReferenceType *T) {
1063 QualType pointeeType = recurse(type: 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(T: pointeeType);
1072 }
1073
1074 QualType VisitMemberPointerType(const MemberPointerType *T) {
1075 QualType pointeeType = recurse(type: 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(T: pointeeType, Qualifier: T->getQualifier(),
1083 Cls: T->getMostRecentCXXRecordDecl());
1084 }
1085
1086 QualType VisitConstantArrayType(const ConstantArrayType *T) {
1087 QualType elementType = recurse(type: 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(EltTy: elementType, ArySize: T->getSize(), SizeExpr: T->getSizeExpr(),
1095 ASM: T->getSizeModifier(),
1096 IndexTypeQuals: T->getIndexTypeCVRQualifiers());
1097 }
1098
1099 QualType VisitVariableArrayType(const VariableArrayType *T) {
1100 QualType elementType = recurse(type: 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(EltTy: elementType, NumElts: T->getSizeExpr(),
1108 ASM: T->getSizeModifier(),
1109 IndexTypeQuals: T->getIndexTypeCVRQualifiers());
1110 }
1111
1112 QualType VisitIncompleteArrayType(const IncompleteArrayType *T) {
1113 QualType elementType = recurse(type: 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(EltTy: elementType, ASM: T->getSizeModifier(),
1121 IndexTypeQuals: T->getIndexTypeCVRQualifiers());
1122 }
1123
1124 QualType VisitVectorType(const VectorType *T) {
1125 QualType elementType = recurse(type: 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(VectorType: elementType, NumElts: T->getNumElements(),
1133 VecKind: T->getVectorKind());
1134 }
1135
1136 QualType VisitExtVectorType(const ExtVectorType *T) {
1137 QualType elementType = recurse(type: 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(VectorType: elementType, NumElts: T->getNumElements());
1145 }
1146
1147 QualType VisitConstantMatrixType(const ConstantMatrixType *T) {
1148 QualType elementType = recurse(type: 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: elementType, NumRows: T->getNumRows(),
1155 NumColumns: T->getNumColumns());
1156 }
1157
1158 QualType VisitFunctionNoProtoType(const FunctionNoProtoType *T) {
1159 QualType returnType = recurse(type: 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
1169 QualType VisitFunctionProtoType(const FunctionProtoType *T) {
1170 QualType returnType = recurse(type: 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(type: 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(ResultTy: returnType, Args: paramTypes, EPI: info);
1215 }
1216
1217 QualType VisitParenType(const ParenType *T) {
1218 QualType innerType = recurse(type: 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(NamedType: innerType);
1226 }
1227
1228 SUGARED_TYPE_CLASS(Typedef)
1229 SUGARED_TYPE_CLASS(ObjCTypeParam)
1230 SUGARED_TYPE_CLASS(MacroQualified)
1231
1232 QualType VisitAdjustedType(const AdjustedType *T) {
1233 QualType originalType = recurse(type: T->getOriginalType());
1234 if (originalType.isNull())
1235 return {};
1236
1237 QualType adjustedType = recurse(type: 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(Orig: originalType, New: adjustedType);
1247 }
1248
1249 QualType VisitDecayedType(const DecayedType *T) {
1250 QualType originalType = recurse(type: 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(T: originalType);
1258 }
1259
1260 QualType VisitArrayParameterType(const ArrayParameterType *T) {
1261 QualType ArrTy = VisitConstantArrayType(T);
1262 if (ArrTy.isNull())
1263 return {};
1264
1265 return Ctx.getArrayParameterType(Ty: ArrTy);
1266 }
1267
1268 SUGARED_TYPE_CLASS(TypeOfExpr)
1269 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(type: T->getModifiedType());
1280 if (modifiedType.isNull())
1281 return {};
1282
1283 QualType equivalentType = recurse(type: 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(attrKind: T->getAttrKind(), modifiedType, equivalentType,
1294 attr: T->getAttr());
1295 }
1296
1297 QualType VisitSubstTemplateTypeParmType(const SubstTemplateTypeParmType *T) {
1298 QualType replacementType = recurse(type: 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 Replacement: replacementType, AssociatedDecl: T->getAssociatedDecl(), Index: T->getIndex(),
1308 PackIndex: T->getPackIndex(), Final: T->getFinal());
1309 }
1310
1311 // FIXME: Non-trivial to implement, but important for C++
1312 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(type: 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: deducedType, Keyword: T->getKeyword(), IsDependent: T->isDependentType(),
1326 /*IsPack=*/false, TypeConstraintConcept: T->getTypeConstraintConcept(),
1327 TypeConstraintArgs: T->getTypeConstraintArguments());
1328 }
1329
1330 QualType VisitObjCObjectType(const ObjCObjectType *T) {
1331 QualType baseType = recurse(type: 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(type: 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
1359 TRIVIAL_TYPE_CLASS(ObjCInterface)
1360
1361 QualType VisitObjCObjectPointerType(const ObjCObjectPointerType *T) {
1362 QualType pointeeType = recurse(type: 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(OIT: pointeeType);
1370 }
1371
1372 QualType VisitAtomicType(const AtomicType *T) {
1373 QualType valueType = recurse(type: 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(T: valueType);
1381 }
1382
1383#undef TRIVIAL_TYPE_CLASS
1384#undef SUGARED_TYPE_CLASS
1385};
1386
1387struct SubstObjCTypeArgsVisitor
1388 : public SimpleTransformVisitor<SubstObjCTypeArgsVisitor> {
1389 using BaseType = SimpleTransformVisitor<SubstObjCTypeArgsVisitor>;
1390
1391 ArrayRef<QualType> TypeArgs;
1392 ObjCSubstitutionContext SubstContext;
1393
1394 SubstObjCTypeArgsVisitor(ASTContext &ctx, ArrayRef<QualType> typeArgs,
1395 ObjCSubstitutionContext context)
1396 : BaseType(ctx), TypeArgs(typeArgs), SubstContext(context) {}
1397
1398 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
1448 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
1518 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
1560 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
1598struct StripObjCKindOfTypeVisitor
1599 : public SimpleTransformVisitor<StripObjCKindOfTypeVisitor> {
1600 using BaseType = SimpleTransformVisitor<StripObjCKindOfTypeVisitor>;
1601
1602 explicit StripObjCKindOfTypeVisitor(ASTContext &ctx) : BaseType(ctx) {}
1603
1604 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
1617bool 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.
1652QualType 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
1659QualType QualType::substObjCMemberType(QualType objectType,
1660 const DeclContext *dc,
1661 ObjCSubstitutionContext context) const {
1662 if (auto subs = objectType->getObjCSubstitutions(dc))
1663 return substObjCTypeArgs(ctx&: dc->getParentASTContext(), typeArgs: *subs, context);
1664
1665 return *this;
1666}
1667
1668QualType 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
1675QualType 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
1682std::optional<ArrayRef<QualType>>
1683Type::getObjCSubstitutions(const DeclContext *dc) const {
1684 // Look through method scopes.
1685 if (const auto method = dyn_cast<ObjCMethodDecl>(Val: 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>(Val: 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>(Val: 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
1764bool 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
1775void 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
1845const 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
1855QualType 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(OIT: superObjectType);
1862}
1863
1864const 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
1874bool Type::isObjCQualifiedInterfaceType() const {
1875 return getAsObjCQualifiedInterfaceType() != nullptr;
1876}
1877
1878const 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
1888const 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
1898const ObjCObjectType *Type::getAsObjCInterfaceType() const {
1899 if (const auto *OT = getAs<ObjCObjectType>()) {
1900 if (OT->getInterface())
1901 return OT;
1902 }
1903 return nullptr;
1904}
1905
1906const ObjCObjectPointerType *Type::getAsObjCInterfacePointerType() const {
1907 if (const auto *OPT = getAs<ObjCObjectPointerType>()) {
1908 if (OPT->getInterfaceType())
1909 return OPT;
1910 }
1911 return nullptr;
1912}
1913
1914const 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>(Val: RT->getDecl());
1925
1926 return nullptr;
1927}
1928
1929CXXRecordDecl *Type::getAsCXXRecordDecl() const {
1930 return dyn_cast_or_null<CXXRecordDecl>(Val: getAsTagDecl());
1931}
1932
1933RecordDecl *Type::getAsRecordDecl() const {
1934 return dyn_cast_or_null<RecordDecl>(Val: getAsTagDecl());
1935}
1936
1937TagDecl *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
1946const TemplateSpecializationType *
1947Type::getAsNonAliasTemplateSpecializationType() const {
1948 const auto *TST = getAs<TemplateSpecializationType>();
1949 while (TST && TST->isTypeAlias())
1950 TST = TST->desugar()->getAs<TemplateSpecializationType>();
1951 return TST;
1952}
1953
1954bool 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
1964namespace {
1965
1966class GetContainedDeducedTypeVisitor
1967 : public TypeVisitor<GetContainedDeducedTypeVisitor, Type *> {
1968 bool Syntactic;
1969
1970public:
1971 GetContainedDeducedTypeVisitor(bool Syntactic = false)
1972 : Syntactic(Syntactic) {}
1973
1974 using TypeVisitor<GetContainedDeducedTypeVisitor, Type *>::Visit;
1975
1976 Type *Visit(QualType T) {
1977 if (T.isNull())
1978 return nullptr;
1979 return Visit(T: T.getTypePtr());
1980 }
1981
1982 // The deduced type itself.
1983 Type *VisitDeducedType(const DeducedType *AT) {
1984 return const_cast<DeducedType *>(AT);
1985 }
1986
1987 // Only these types can contain the desired 'auto' type.
1988 Type *VisitSubstTemplateTypeParmType(const SubstTemplateTypeParmType *T) {
1989 return Visit(T: T->getReplacementType());
1990 }
1991
1992 Type *VisitElaboratedType(const ElaboratedType *T) {
1993 return Visit(T: T->getNamedType());
1994 }
1995
1996 Type *VisitPointerType(const PointerType *T) {
1997 return Visit(T: T->getPointeeType());
1998 }
1999
2000 Type *VisitBlockPointerType(const BlockPointerType *T) {
2001 return Visit(T: T->getPointeeType());
2002 }
2003
2004 Type *VisitReferenceType(const ReferenceType *T) {
2005 return Visit(T: T->getPointeeTypeAsWritten());
2006 }
2007
2008 Type *VisitMemberPointerType(const MemberPointerType *T) {
2009 return Visit(T: T->getPointeeType());
2010 }
2011
2012 Type *VisitArrayType(const ArrayType *T) {
2013 return Visit(T: T->getElementType());
2014 }
2015
2016 Type *VisitDependentSizedExtVectorType(const DependentSizedExtVectorType *T) {
2017 return Visit(T: T->getElementType());
2018 }
2019
2020 Type *VisitVectorType(const VectorType *T) {
2021 return Visit(T: T->getElementType());
2022 }
2023
2024 Type *VisitDependentSizedMatrixType(const DependentSizedMatrixType *T) {
2025 return Visit(T->getElementType());
2026 }
2027
2028 Type *VisitConstantMatrixType(const ConstantMatrixType *T) {
2029 return Visit(T->getElementType());
2030 }
2031
2032 Type *VisitFunctionProtoType(const FunctionProtoType *T) {
2033 if (Syntactic && T->hasTrailingReturn())
2034 return const_cast<FunctionProtoType *>(T);
2035 return VisitFunctionType(T);
2036 }
2037
2038 Type *VisitFunctionType(const FunctionType *T) {
2039 return Visit(T: T->getReturnType());
2040 }
2041
2042 Type *VisitParenType(const ParenType *T) { return Visit(T: T->getInnerType()); }
2043
2044 Type *VisitAttributedType(const AttributedType *T) {
2045 return Visit(T: T->getModifiedType());
2046 }
2047
2048 Type *VisitMacroQualifiedType(const MacroQualifiedType *T) {
2049 return Visit(T: T->getUnderlyingType());
2050 }
2051
2052 Type *VisitAdjustedType(const AdjustedType *T) {
2053 return Visit(T: T->getOriginalType());
2054 }
2055
2056 Type *VisitPackExpansionType(const PackExpansionType *T) {
2057 return Visit(T: T->getPattern());
2058 }
2059};
2060
2061} // namespace
2062
2063DeducedType *Type::getContainedDeducedType() const {
2064 return cast_or_null<DeducedType>(
2065 Val: GetContainedDeducedTypeVisitor().Visit(T: this));
2066}
2067
2068bool Type::hasAutoForTrailingReturnType() const {
2069 return isa_and_nonnull<FunctionType>(
2070 Val: GetContainedDeducedTypeVisitor(true).Visit(T: this));
2071}
2072
2073bool 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.
2110bool 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
2122bool 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
2132bool Type::isUnscopedEnumerationType() const {
2133 if (const auto *ET = dyn_cast<EnumType>(CanonicalType))
2134 return !ET->getDecl()->isScoped();
2135
2136 return false;
2137}
2138
2139bool 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
2148bool 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
2155bool Type::isChar8Type() const {
2156 if (const BuiltinType *BT = dyn_cast<BuiltinType>(CanonicalType))
2157 return BT->getKind() == BuiltinType::Char8;
2158 return false;
2159}
2160
2161bool Type::isChar16Type() const {
2162 if (const auto *BT = dyn_cast<BuiltinType>(CanonicalType))
2163 return BT->getKind() == BuiltinType::Char16;
2164 return false;
2165}
2166
2167bool 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.
2175bool 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
2195bool 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
2212bool 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
2231bool 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
2247bool 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
2257bool 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
2276bool 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
2292bool 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
2305bool 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
2313bool 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
2321bool Type::isRealFloatingType() const {
2322 if (const auto *BT = dyn_cast<BuiltinType>(CanonicalType))
2323 return BT->isFloatingPoint();
2324 return false;
2325}
2326
2327bool 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
2336bool 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
2351bool 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
2363Type::ScalarTypeKind Type::getScalarTypeKind() const {
2364 assert(isScalarType());
2365
2366 const Type *T = CanonicalType.getTypePtr();
2367 if (const auto *BT = dyn_cast<BuiltinType>(Val: 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>(Val: T)) {
2380 return STK_CPointer;
2381 } else if (isa<BlockPointerType>(Val: T)) {
2382 return STK_BlockPointer;
2383 } else if (isa<ObjCObjectPointerType>(Val: T)) {
2384 return STK_ObjCObjectPointer;
2385 } else if (isa<MemberPointerType>(Val: T)) {
2386 return STK_MemberPointer;
2387 } else if (isa<EnumType>(Val: T)) {
2388 assert(cast<EnumType>(T)->getDecl()->isComplete());
2389 return STK_Integral;
2390 } else if (const auto *CT = dyn_cast<ComplexType>(Val: 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.
2410bool 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.
2424bool 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.
2434bool 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
2514bool 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
2530bool 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
2550bool Type::isWebAssemblyExternrefType() const {
2551 if (const auto *BT = getAs<BuiltinType>())
2552 return BT->getKind() == BuiltinType::WasmExternRef;
2553 return false;
2554}
2555
2556bool Type::isWebAssemblyTableType() const {
2557 if (const auto *ATy = dyn_cast<ArrayType>(Val: this))
2558 return ATy->getElementType().isWebAssemblyReferenceType();
2559
2560 if (const auto *PTy = dyn_cast<PointerType>(Val: this))
2561 return PTy->getPointeeType().isWebAssemblyReferenceType();
2562
2563 return false;
2564}
2565
2566bool Type::isSizelessType() const { return isSizelessBuiltinType(); }
2567
2568bool Type::isSizelessVectorType() const {
2569 return isSVESizelessBuiltinType() || isRVVSizelessBuiltinType();
2570}
2571
2572bool 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
2593bool 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
2606bool 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
2633QualType 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
2645QualType 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(VecTy: BTy).ElementType;
2656}
2657
2658bool 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
2676QualType 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(VecTy: BTy).ElementType;
2687#include "clang/Basic/RISCVVTypes.def"
2688 }
2689
2690 llvm_unreachable("Unhandled type");
2691}
2692
2693bool 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
2701bool 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(QT: *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 switch (CanonicalType->getTypeClass()) {
2719 // Everything not explicitly mentioned is not POD.
2720 default:
2721 return false;
2722 case Type::VariableArray:
2723 case Type::ConstantArray:
2724 // IncompleteArray is handled above.
2725 return Context.getBaseElementType(QT: *this).isCXX98PODType(Context);
2726
2727 case Type::ObjCObjectPointer:
2728 case Type::BlockPointer:
2729 case Type::Builtin:
2730 case Type::Complex:
2731 case Type::Pointer:
2732 case Type::MemberPointer:
2733 case Type::Vector:
2734 case Type::ExtVector:
2735 case Type::BitInt:
2736 return true;
2737
2738 case Type::Enum:
2739 return true;
2740
2741 case Type::Record:
2742 if (const auto *ClassDecl =
2743 dyn_cast<CXXRecordDecl>(cast<RecordType>(CanonicalType)->getDecl()))
2744 return ClassDecl->isPOD();
2745
2746 // C struct/union is POD.
2747 return true;
2748 }
2749}
2750
2751bool QualType::isTrivialType(const ASTContext &Context) const {
2752 // The compiler shouldn't query this for incomplete types, but the user might.
2753 // We return false for that case. Except for incomplete arrays of PODs, which
2754 // are PODs according to the standard.
2755 if (isNull())
2756 return false;
2757
2758 if ((*this)->isArrayType())
2759 return Context.getBaseElementType(QT: *this).isTrivialType(Context);
2760
2761 if ((*this)->isSizelessBuiltinType())
2762 return true;
2763
2764 // Return false for incomplete types after skipping any incomplete array
2765 // types which are expressly allowed by the standard and thus our API.
2766 if ((*this)->isIncompleteType())
2767 return false;
2768
2769 if (hasNonTrivialObjCLifetime())
2770 return false;
2771
2772 QualType CanonicalType = getTypePtr()->CanonicalType;
2773 if (CanonicalType->isDependentType())
2774 return false;
2775
2776 // C++0x [basic.types]p9:
2777 // Scalar types, trivial class types, arrays of such types, and
2778 // cv-qualified versions of these types are collectively called trivial
2779 // types.
2780
2781 // As an extension, Clang treats vector types as Scalar types.
2782 if (CanonicalType->isScalarType() || CanonicalType->isVectorType())
2783 return true;
2784 if (const auto *RT = CanonicalType->getAs<RecordType>()) {
2785 if (const auto *ClassDecl = dyn_cast<CXXRecordDecl>(RT->getDecl())) {
2786 // C++20 [class]p6:
2787 // A trivial class is a class that is trivially copyable, and
2788 // has one or more eligible default constructors such that each is
2789 // trivial.
2790 // FIXME: We should merge this definition of triviality into
2791 // CXXRecordDecl::isTrivial. Currently it computes the wrong thing.
2792 return ClassDecl->hasTrivialDefaultConstructor() &&
2793 !ClassDecl->hasNonTrivialDefaultConstructor() &&
2794 ClassDecl->isTriviallyCopyable();
2795 }
2796
2797 return true;
2798 }
2799
2800 // No other types can match.
2801 return false;
2802}
2803
2804static bool isTriviallyCopyableTypeImpl(const QualType &type,
2805 const ASTContext &Context,
2806 bool IsCopyConstructible) {
2807 if (type->isArrayType())
2808 return isTriviallyCopyableTypeImpl(type: Context.getBaseElementType(QT: type),
2809 Context, IsCopyConstructible);
2810
2811 if (type.hasNonTrivialObjCLifetime())
2812 return false;
2813
2814 // C++11 [basic.types]p9 - See Core 2094
2815 // Scalar types, trivially copyable class types, arrays of such types, and
2816 // cv-qualified versions of these types are collectively
2817 // called trivially copy constructible types.
2818
2819 QualType CanonicalType = type.getCanonicalType();
2820 if (CanonicalType->isDependentType())
2821 return false;
2822
2823 if (CanonicalType->isSizelessBuiltinType())
2824 return true;
2825
2826 // Return false for incomplete types after skipping any incomplete array types
2827 // which are expressly allowed by the standard and thus our API.
2828 if (CanonicalType->isIncompleteType())
2829 return false;
2830
2831 if (CanonicalType.hasAddressDiscriminatedPointerAuth())
2832 return false;
2833
2834 // As an extension, Clang treats vector types as Scalar types.
2835 if (CanonicalType->isScalarType() || CanonicalType->isVectorType())
2836 return true;
2837
2838 // Mfloat8 type is a special case as it not scalar, but is still trivially
2839 // copyable.
2840 if (CanonicalType->isMFloat8Type())
2841 return true;
2842
2843 if (const auto *RT = CanonicalType->getAs<RecordType>()) {
2844 if (const auto *ClassDecl = dyn_cast<CXXRecordDecl>(Val: RT->getDecl())) {
2845 if (IsCopyConstructible) {
2846 return ClassDecl->isTriviallyCopyConstructible();
2847 } else {
2848 return ClassDecl->isTriviallyCopyable();
2849 }
2850 }
2851 return !RT->getDecl()->isNonTrivialToPrimitiveCopy();
2852 }
2853 // No other types can match.
2854 return false;
2855}
2856
2857bool QualType::isTriviallyCopyableType(const ASTContext &Context) const {
2858 return isTriviallyCopyableTypeImpl(type: *this, Context,
2859 /*IsCopyConstructible=*/false);
2860}
2861
2862// FIXME: each call will trigger a full computation, cache the result.
2863bool QualType::isBitwiseCloneableType(const ASTContext &Context) const {
2864 auto CanonicalType = getCanonicalType();
2865 if (CanonicalType.hasNonTrivialObjCLifetime())
2866 return false;
2867 if (CanonicalType->isArrayType())
2868 return Context.getBaseElementType(QT: CanonicalType)
2869 .isBitwiseCloneableType(Context);
2870
2871 if (CanonicalType->isIncompleteType())
2872 return false;
2873 const auto *RD = CanonicalType->getAsRecordDecl(); // struct/union/class
2874 if (!RD)
2875 return true;
2876
2877 // Never allow memcpy when we're adding poisoned padding bits to the struct.
2878 // Accessing these posioned bits will trigger false alarms on
2879 // SanitizeAddressFieldPadding etc.
2880 if (RD->mayInsertExtraPadding())
2881 return false;
2882
2883 for (auto *const Field : RD->fields()) {
2884 if (!Field->getType().isBitwiseCloneableType(Context))
2885 return false;
2886 }
2887
2888 if (const auto *CXXRD = dyn_cast<CXXRecordDecl>(Val: RD)) {
2889 for (auto Base : CXXRD->bases())
2890 if (!Base.getType().isBitwiseCloneableType(Context))
2891 return false;
2892 for (auto VBase : CXXRD->vbases())
2893 if (!VBase.getType().isBitwiseCloneableType(Context))
2894 return false;
2895 }
2896 return true;
2897}
2898
2899bool QualType::isTriviallyCopyConstructibleType(
2900 const ASTContext &Context) const {
2901 return isTriviallyCopyableTypeImpl(type: *this, Context,
2902 /*IsCopyConstructible=*/true);
2903}
2904
2905bool QualType::isNonWeakInMRRWithObjCWeak(const ASTContext &Context) const {
2906 return !Context.getLangOpts().ObjCAutoRefCount &&
2907 Context.getLangOpts().ObjCWeak &&
2908 getObjCLifetime() != Qualifiers::OCL_Weak;
2909}
2910
2911bool QualType::hasNonTrivialToPrimitiveDefaultInitializeCUnion(
2912 const RecordDecl *RD) {
2913 return RD->hasNonTrivialToPrimitiveDefaultInitializeCUnion();
2914}
2915
2916bool QualType::hasNonTrivialToPrimitiveDestructCUnion(const RecordDecl *RD) {
2917 return RD->hasNonTrivialToPrimitiveDestructCUnion();
2918}
2919
2920bool QualType::hasNonTrivialToPrimitiveCopyCUnion(const RecordDecl *RD) {
2921 return RD->hasNonTrivialToPrimitiveCopyCUnion();
2922}
2923
2924bool QualType::isWebAssemblyReferenceType() const {
2925 return isWebAssemblyExternrefType() || isWebAssemblyFuncrefType();
2926}
2927
2928bool QualType::isWebAssemblyExternrefType() const {
2929 return getTypePtr()->isWebAssemblyExternrefType();
2930}
2931
2932bool QualType::isWebAssemblyFuncrefType() const {
2933 return getTypePtr()->isFunctionPointerType() &&
2934 getAddressSpace() == LangAS::wasm_funcref;
2935}
2936
2937QualType::PrimitiveDefaultInitializeKind
2938QualType::isNonTrivialToPrimitiveDefaultInitialize() const {
2939 if (const auto *RT =
2940 getTypePtr()->getBaseElementTypeUnsafe()->getAs<RecordType>())
2941 if (RT->getDecl()->isNonTrivialToPrimitiveDefaultInitialize())
2942 return PDIK_Struct;
2943
2944 switch (getQualifiers().getObjCLifetime()) {
2945 case Qualifiers::OCL_Strong:
2946 return PDIK_ARCStrong;
2947 case Qualifiers::OCL_Weak:
2948 return PDIK_ARCWeak;
2949 default:
2950 return PDIK_Trivial;
2951 }
2952}
2953
2954QualType::PrimitiveCopyKind QualType::isNonTrivialToPrimitiveCopy() const {
2955 if (const auto *RT =
2956 getTypePtr()->getBaseElementTypeUnsafe()->getAs<RecordType>())
2957 if (RT->getDecl()->isNonTrivialToPrimitiveCopy())
2958 return PCK_Struct;
2959
2960 Qualifiers Qs = getQualifiers();
2961 switch (Qs.getObjCLifetime()) {
2962 case Qualifiers::OCL_Strong:
2963 return PCK_ARCStrong;
2964 case Qualifiers::OCL_Weak:
2965 return PCK_ARCWeak;
2966 default:
2967 if (hasAddressDiscriminatedPointerAuth())
2968 return PCK_PtrAuth;
2969 return Qs.hasVolatile() ? PCK_VolatileTrivial : PCK_Trivial;
2970 }
2971}
2972
2973QualType::PrimitiveCopyKind
2974QualType::isNonTrivialToPrimitiveDestructiveMove() const {
2975 return isNonTrivialToPrimitiveCopy();
2976}
2977
2978bool Type::isLiteralType(const ASTContext &Ctx) const {
2979 if (isDependentType())
2980 return false;
2981
2982 // C++1y [basic.types]p10:
2983 // A type is a literal type if it is:
2984 // -- cv void; or
2985 if (Ctx.getLangOpts().CPlusPlus14 && isVoidType())
2986 return true;
2987
2988 // C++11 [basic.types]p10:
2989 // A type is a literal type if it is:
2990 // [...]
2991 // -- an array of literal type other than an array of runtime bound; or
2992 if (isVariableArrayType())
2993 return false;
2994 const Type *BaseTy = getBaseElementTypeUnsafe();
2995 assert(BaseTy && "NULL element type");
2996
2997 // Return false for incomplete types after skipping any incomplete array
2998 // types; those are expressly allowed by the standard and thus our API.
2999 if (BaseTy->isIncompleteType())
3000 return false;
3001
3002 // C++11 [basic.types]p10:
3003 // A type is a literal type if it is:
3004 // -- a scalar type; or
3005 // As an extension, Clang treats vector types and complex types as
3006 // literal types.
3007 if (BaseTy->isScalarType() || BaseTy->isVectorType() ||
3008 BaseTy->isAnyComplexType())
3009 return true;
3010 // -- a reference type; or
3011 if (BaseTy->isReferenceType())
3012 return true;
3013 // -- a class type that has all of the following properties:
3014 if (const auto *RT = BaseTy->getAs<RecordType>()) {
3015 // -- a trivial destructor,
3016 // -- every constructor call and full-expression in the
3017 // brace-or-equal-initializers for non-static data members (if any)
3018 // is a constant expression,
3019 // -- it is an aggregate type or has at least one constexpr
3020 // constructor or constructor template that is not a copy or move
3021 // constructor, and
3022 // -- all non-static data members and base classes of literal types
3023 //
3024 // We resolve DR1361 by ignoring the second bullet.
3025 if (const auto *ClassDecl = dyn_cast<CXXRecordDecl>(Val: RT->getDecl()))
3026 return ClassDecl->isLiteral();
3027
3028 return true;
3029 }
3030
3031 // We treat _Atomic T as a literal type if T is a literal type.
3032 if (const auto *AT = BaseTy->getAs<AtomicType>())
3033 return AT->getValueType()->isLiteralType(Ctx);
3034
3035 // If this type hasn't been deduced yet, then conservatively assume that
3036 // it'll work out to be a literal type.
3037 if (isa<AutoType>(Val: BaseTy->getCanonicalTypeInternal()))
3038 return true;
3039
3040 return false;
3041}
3042
3043bool Type::isStructuralType() const {
3044 // C++20 [temp.param]p6:
3045 // A structural type is one of the following:
3046 // -- a scalar type; or
3047 // -- a vector type [Clang extension]; or
3048 if (isScalarType() || isVectorType())
3049 return true;
3050 // -- an lvalue reference type; or
3051 if (isLValueReferenceType())
3052 return true;
3053 // -- a literal class type [...under some conditions]
3054 if (const CXXRecordDecl *RD = getAsCXXRecordDecl())
3055 return RD->isStructural();
3056 return false;
3057}
3058
3059bool Type::isStandardLayoutType() const {
3060 if (isDependentType())
3061 return false;
3062
3063 // C++0x [basic.types]p9:
3064 // Scalar types, standard-layout class types, arrays of such types, and
3065 // cv-qualified versions of these types are collectively called
3066 // standard-layout types.
3067 const Type *BaseTy = getBaseElementTypeUnsafe();
3068 assert(BaseTy && "NULL element type");
3069
3070 // Return false for incomplete types after skipping any incomplete array
3071 // types which are expressly allowed by the standard and thus our API.
3072 if (BaseTy->isIncompleteType())
3073 return false;
3074
3075 // As an extension, Clang treats vector types as Scalar types.
3076 if (BaseTy->isScalarType() || BaseTy->isVectorType())
3077 return true;
3078 if (const auto *RT = BaseTy->getAs<RecordType>()) {
3079 if (const auto *ClassDecl = dyn_cast<CXXRecordDecl>(Val: RT->getDecl()))
3080 if (!ClassDecl->isStandardLayout())
3081 return false;
3082
3083 // Default to 'true' for non-C++ class types.
3084 // FIXME: This is a bit dubious, but plain C structs should trivially meet
3085 // all the requirements of standard layout classes.
3086 return true;
3087 }
3088
3089 // No other types can match.
3090 return false;
3091}
3092
3093// This is effectively the intersection of isTrivialType and
3094// isStandardLayoutType. We implement it directly to avoid redundant
3095// conversions from a type to a CXXRecordDecl.
3096bool QualType::isCXX11PODType(const ASTContext &Context) const {
3097 const Type *ty = getTypePtr();
3098 if (ty->isDependentType())
3099 return false;
3100
3101 if (hasNonTrivialObjCLifetime())
3102 return false;
3103
3104 // C++11 [basic.types]p9:
3105 // Scalar types, POD classes, arrays of such types, and cv-qualified
3106 // versions of these types are collectively called trivial types.
3107 const Type *BaseTy = ty->getBaseElementTypeUnsafe();
3108 assert(BaseTy && "NULL element type");
3109
3110 if (BaseTy->isSizelessBuiltinType())
3111 return true;
3112
3113 // Return false for incomplete types after skipping any incomplete array
3114 // types which are expressly allowed by the standard and thus our API.
3115 if (BaseTy->isIncompleteType())
3116 return false;
3117
3118 // As an extension, Clang treats vector types as Scalar types.
3119 if (BaseTy->isScalarType() || BaseTy->isVectorType())
3120 return true;
3121 if (const auto *RT = BaseTy->getAs<RecordType>()) {
3122 if (const auto *ClassDecl = dyn_cast<CXXRecordDecl>(Val: RT->getDecl())) {
3123 // C++11 [class]p10:
3124 // A POD struct is a non-union class that is both a trivial class [...]
3125 if (!ClassDecl->isTrivial())
3126 return false;
3127
3128 // C++11 [class]p10:
3129 // A POD struct is a non-union class that is both a trivial class and
3130 // a standard-layout class [...]
3131 if (!ClassDecl->isStandardLayout())
3132 return false;
3133
3134 // C++11 [class]p10:
3135 // A POD struct is a non-union class that is both a trivial class and
3136 // a standard-layout class, and has no non-static data members of type
3137 // non-POD struct, non-POD union (or array of such types). [...]
3138 //
3139 // We don't directly query the recursive aspect as the requirements for
3140 // both standard-layout classes and trivial classes apply recursively
3141 // already.
3142 }
3143
3144 return true;
3145 }
3146
3147 // No other types can match.
3148 return false;
3149}
3150
3151bool Type::isNothrowT() const {
3152 if (const auto *RD = getAsCXXRecordDecl()) {
3153 IdentifierInfo *II = RD->getIdentifier();
3154 if (II && II->isStr(Str: "nothrow_t") && RD->isInStdNamespace())
3155 return true;
3156 }
3157 return false;
3158}
3159
3160bool Type::isAlignValT() const {
3161 if (const auto *ET = getAs<EnumType>()) {
3162 IdentifierInfo *II = ET->getDecl()->getIdentifier();
3163 if (II && II->isStr(Str: "align_val_t") && ET->getDecl()->isInStdNamespace())
3164 return true;
3165 }
3166 return false;
3167}
3168
3169bool Type::isStdByteType() const {
3170 if (const auto *ET = getAs<EnumType>()) {
3171 IdentifierInfo *II = ET->getDecl()->getIdentifier();
3172 if (II && II->isStr(Str: "byte") && ET->getDecl()->isInStdNamespace())
3173 return true;
3174 }
3175 return false;
3176}
3177
3178bool Type::isSpecifierType() const {
3179 // Note that this intentionally does not use the canonical type.
3180 switch (getTypeClass()) {
3181 case Builtin:
3182 case Record:
3183 case Enum:
3184 case Typedef:
3185 case Complex:
3186 case TypeOfExpr:
3187 case TypeOf:
3188 case TemplateTypeParm:
3189 case SubstTemplateTypeParm:
3190 case TemplateSpecialization:
3191 case Elaborated:
3192 case DependentName:
3193 case DependentTemplateSpecialization:
3194 case ObjCInterface:
3195 case ObjCObject:
3196 return true;
3197 default:
3198 return false;
3199 }
3200}
3201
3202ElaboratedTypeKeyword
3203TypeWithKeyword::getKeywordForTypeSpec(unsigned TypeSpec) {
3204 switch (TypeSpec) {
3205 default:
3206 return ElaboratedTypeKeyword::None;
3207 case TST_typename:
3208 return ElaboratedTypeKeyword::Typename;
3209 case TST_class:
3210 return ElaboratedTypeKeyword::Class;
3211 case TST_struct:
3212 return ElaboratedTypeKeyword::Struct;
3213 case TST_interface:
3214 return ElaboratedTypeKeyword::Interface;
3215 case TST_union:
3216 return ElaboratedTypeKeyword::Union;
3217 case TST_enum:
3218 return ElaboratedTypeKeyword::Enum;
3219 }
3220}
3221
3222TagTypeKind TypeWithKeyword::getTagTypeKindForTypeSpec(unsigned TypeSpec) {
3223 switch (TypeSpec) {
3224 case TST_class:
3225 return TagTypeKind::Class;
3226 case TST_struct:
3227 return TagTypeKind::Struct;
3228 case TST_interface:
3229 return TagTypeKind::Interface;
3230 case TST_union:
3231 return TagTypeKind::Union;
3232 case TST_enum:
3233 return TagTypeKind::Enum;
3234 }
3235
3236 llvm_unreachable("Type specifier is not a tag type kind.");
3237}
3238
3239ElaboratedTypeKeyword
3240TypeWithKeyword::getKeywordForTagTypeKind(TagTypeKind Kind) {
3241 switch (Kind) {
3242 case TagTypeKind::Class:
3243 return ElaboratedTypeKeyword::Class;
3244 case TagTypeKind::Struct:
3245 return ElaboratedTypeKeyword::Struct;
3246 case TagTypeKind::Interface:
3247 return ElaboratedTypeKeyword::Interface;
3248 case TagTypeKind::Union:
3249 return ElaboratedTypeKeyword::Union;
3250 case TagTypeKind::Enum:
3251 return ElaboratedTypeKeyword::Enum;
3252 }
3253 llvm_unreachable("Unknown tag type kind.");
3254}
3255
3256TagTypeKind
3257TypeWithKeyword::getTagTypeKindForKeyword(ElaboratedTypeKeyword Keyword) {
3258 switch (Keyword) {
3259 case ElaboratedTypeKeyword::Class:
3260 return TagTypeKind::Class;
3261 case ElaboratedTypeKeyword::Struct:
3262 return TagTypeKind::Struct;
3263 case ElaboratedTypeKeyword::Interface:
3264 return TagTypeKind::Interface;
3265 case ElaboratedTypeKeyword::Union:
3266 return TagTypeKind::Union;
3267 case ElaboratedTypeKeyword::Enum:
3268 return TagTypeKind::Enum;
3269 case ElaboratedTypeKeyword::None: // Fall through.
3270 case ElaboratedTypeKeyword::Typename:
3271 llvm_unreachable("Elaborated type keyword is not a tag type kind.");
3272 }
3273 llvm_unreachable("Unknown elaborated type keyword.");
3274}
3275
3276bool TypeWithKeyword::KeywordIsTagTypeKind(ElaboratedTypeKeyword Keyword) {
3277 switch (Keyword) {
3278 case ElaboratedTypeKeyword::None:
3279 case ElaboratedTypeKeyword::Typename:
3280 return false;
3281 case ElaboratedTypeKeyword::Class:
3282 case ElaboratedTypeKeyword::Struct:
3283 case ElaboratedTypeKeyword::Interface:
3284 case ElaboratedTypeKeyword::Union:
3285 case ElaboratedTypeKeyword::Enum:
3286 return true;
3287 }
3288 llvm_unreachable("Unknown elaborated type keyword.");
3289}
3290
3291StringRef TypeWithKeyword::getKeywordName(ElaboratedTypeKeyword Keyword) {
3292 switch (Keyword) {
3293 case ElaboratedTypeKeyword::None:
3294 return {};
3295 case ElaboratedTypeKeyword::Typename:
3296 return "typename";
3297 case ElaboratedTypeKeyword::Class:
3298 return "class";
3299 case ElaboratedTypeKeyword::Struct:
3300 return "struct";
3301 case ElaboratedTypeKeyword::Interface:
3302 return "__interface";
3303 case ElaboratedTypeKeyword::Union:
3304 return "union";
3305 case ElaboratedTypeKeyword::Enum:
3306 return "enum";
3307 }
3308
3309 llvm_unreachable("Unknown elaborated type keyword.");
3310}
3311
3312DependentTemplateSpecializationType::DependentTemplateSpecializationType(
3313 ElaboratedTypeKeyword Keyword, const DependentTemplateStorage &Name,
3314 ArrayRef<TemplateArgument> Args, QualType Canon)
3315 : TypeWithKeyword(Keyword, DependentTemplateSpecialization, Canon,
3316
3317 toTypeDependence(Name.getDependence())),
3318 Name(Name) {
3319 DependentTemplateSpecializationTypeBits.NumArgs = Args.size();
3320 auto *ArgBuffer = const_cast<TemplateArgument *>(template_arguments().data());
3321 for (const TemplateArgument &Arg : Args) {
3322 addDependence(toTypeDependence(D: Arg.getDependence() &
3323 TemplateArgumentDependence::UnexpandedPack));
3324
3325 new (ArgBuffer++) TemplateArgument(Arg);
3326 }
3327}
3328
3329void DependentTemplateSpecializationType::Profile(
3330 llvm::FoldingSetNodeID &ID, const ASTContext &Context,
3331 ElaboratedTypeKeyword Keyword, const DependentTemplateStorage &Name,
3332 ArrayRef<TemplateArgument> Args) {
3333 ID.AddInteger(I: llvm::to_underlying(E: Keyword));
3334 Name.Profile(ID);
3335 for (const TemplateArgument &Arg : Args)
3336 Arg.Profile(ID, Context);
3337}
3338
3339bool Type::isElaboratedTypeSpecifier() const {
3340 ElaboratedTypeKeyword Keyword;
3341 if (const auto *Elab = dyn_cast<ElaboratedType>(Val: this))
3342 Keyword = Elab->getKeyword();
3343 else if (const auto *DepName = dyn_cast<DependentNameType>(Val: this))
3344 Keyword = DepName->getKeyword();
3345 else if (const auto *DepTST =
3346 dyn_cast<DependentTemplateSpecializationType>(Val: this))
3347 Keyword = DepTST->getKeyword();
3348 else
3349 return false;
3350
3351 return TypeWithKeyword::KeywordIsTagTypeKind(Keyword);
3352}
3353
3354const char *Type::getTypeClassName() const {
3355 switch (TypeBits.TC) {
3356#define ABSTRACT_TYPE(Derived, Base)
3357#define TYPE(Derived, Base) \
3358 case Derived: \
3359 return #Derived;
3360#include "clang/AST/TypeNodes.inc"
3361 }
3362
3363 llvm_unreachable("Invalid type class.");
3364}
3365
3366StringRef BuiltinType::getName(const PrintingPolicy &Policy) const {
3367 switch (getKind()) {
3368 case Void:
3369 return "void";
3370 case Bool:
3371 return Policy.Bool ? "bool" : "_Bool";
3372 case Char_S:
3373 return "char";
3374 case Char_U:
3375 return "char";
3376 case SChar:
3377 return "signed char";
3378 case Short:
3379 return "short";
3380 case Int:
3381 return "int";
3382 case Long:
3383 return "long";
3384 case LongLong:
3385 return "long long";
3386 case Int128:
3387 return "__int128";
3388 case UChar:
3389 return "unsigned char";
3390 case UShort:
3391 return "unsigned short";
3392 case UInt:
3393 return "unsigned int";
3394 case ULong:
3395 return "unsigned long";
3396 case ULongLong:
3397 return "unsigned long long";
3398 case UInt128:
3399 return "unsigned __int128";
3400 case Half:
3401 return Policy.Half ? "half" : "__fp16";
3402 case BFloat16:
3403 return "__bf16";
3404 case Float:
3405 return "float";
3406 case Double:
3407 return "double";
3408 case LongDouble:
3409 return "long double";
3410 case ShortAccum:
3411 return "short _Accum";
3412 case Accum:
3413 return "_Accum";
3414 case LongAccum:
3415 return "long _Accum";
3416 case UShortAccum:
3417 return "unsigned short _Accum";
3418 case UAccum:
3419 return "unsigned _Accum";
3420 case ULongAccum:
3421 return "unsigned long _Accum";
3422 case BuiltinType::ShortFract:
3423 return "short _Fract";
3424 case BuiltinType::Fract:
3425 return "_Fract";
3426 case BuiltinType::LongFract:
3427 return "long _Fract";
3428 case BuiltinType::UShortFract:
3429 return "unsigned short _Fract";
3430 case BuiltinType::UFract:
3431 return "unsigned _Fract";
3432 case BuiltinType::ULongFract:
3433 return "unsigned long _Fract";
3434 case BuiltinType::SatShortAccum:
3435 return "_Sat short _Accum";
3436 case BuiltinType::SatAccum:
3437 return "_Sat _Accum";
3438 case BuiltinType::SatLongAccum:
3439 return "_Sat long _Accum";
3440 case BuiltinType::SatUShortAccum:
3441 return "_Sat unsigned short _Accum";
3442 case BuiltinType::SatUAccum:
3443 return "_Sat unsigned _Accum";
3444 case BuiltinType::SatULongAccum:
3445 return "_Sat unsigned long _Accum";
3446 case BuiltinType::SatShortFract:
3447 return "_Sat short _Fract";
3448 case BuiltinType::SatFract:
3449 return "_Sat _Fract";
3450 case BuiltinType::SatLongFract:
3451 return "_Sat long _Fract";
3452 case BuiltinType::SatUShortFract:
3453 return "_Sat unsigned short _Fract";
3454 case BuiltinType::SatUFract:
3455 return "_Sat unsigned _Fract";
3456 case BuiltinType::SatULongFract:
3457 return "_Sat unsigned long _Fract";
3458 case Float16:
3459 return "_Float16";
3460 case Float128:
3461 return "__float128";
3462 case Ibm128:
3463 return "__ibm128";
3464 case WChar_S:
3465 case WChar_U:
3466 return Policy.MSWChar ? "__wchar_t" : "wchar_t";
3467 case Char8:
3468 return "char8_t";
3469 case Char16:
3470 return "char16_t";
3471 case Char32:
3472 return "char32_t";
3473 case NullPtr:
3474 return Policy.NullptrTypeInNamespace ? "std::nullptr_t" : "nullptr_t";
3475 case Overload:
3476 return "<overloaded function type>";
3477 case BoundMember:
3478 return "<bound member function type>";
3479 case UnresolvedTemplate:
3480 return "<unresolved template type>";
3481 case PseudoObject:
3482 return "<pseudo-object type>";
3483 case Dependent:
3484 return "<dependent type>";
3485 case UnknownAny:
3486 return "<unknown type>";
3487 case ARCUnbridgedCast:
3488 return "<ARC unbridged cast type>";
3489 case BuiltinFn:
3490 return "<builtin fn type>";
3491 case ObjCId:
3492 return "id";
3493 case ObjCClass:
3494 return "Class";
3495 case ObjCSel:
3496 return "SEL";
3497#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
3498 case Id: \
3499 return "__" #Access " " #ImgType "_t";
3500#include "clang/Basic/OpenCLImageTypes.def"
3501 case OCLSampler:
3502 return "sampler_t";
3503 case OCLEvent:
3504 return "event_t";
3505 case OCLClkEvent:
3506 return "clk_event_t";
3507 case OCLQueue:
3508 return "queue_t";
3509 case OCLReserveID:
3510 return "reserve_id_t";
3511 case IncompleteMatrixIdx:
3512 return "<incomplete matrix index type>";
3513 case ArraySection:
3514 return "<array section type>";
3515 case OMPArrayShaping:
3516 return "<OpenMP array shaping type>";
3517 case OMPIterator:
3518 return "<OpenMP iterator type>";
3519#define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
3520 case Id: \
3521 return #ExtType;
3522#include "clang/Basic/OpenCLExtensionTypes.def"
3523#define SVE_TYPE(Name, Id, SingletonId) \
3524 case Id: \
3525 return #Name;
3526#include "clang/Basic/AArch64ACLETypes.def"
3527#define PPC_VECTOR_TYPE(Name, Id, Size) \
3528 case Id: \
3529 return #Name;
3530#include "clang/Basic/PPCTypes.def"
3531#define RVV_TYPE(Name, Id, SingletonId) \
3532 case Id: \
3533 return Name;
3534#include "clang/Basic/RISCVVTypes.def"
3535#define WASM_TYPE(Name, Id, SingletonId) \
3536 case Id: \
3537 return Name;
3538#include "clang/Basic/WebAssemblyReferenceTypes.def"
3539#define AMDGPU_TYPE(Name, Id, SingletonId, Width, Align) \
3540 case Id: \
3541 return Name;
3542#include "clang/Basic/AMDGPUTypes.def"
3543#define HLSL_INTANGIBLE_TYPE(Name, Id, SingletonId) \
3544 case Id: \
3545 return #Name;
3546#include "clang/Basic/HLSLIntangibleTypes.def"
3547 }
3548
3549 llvm_unreachable("Invalid builtin type.");
3550}
3551
3552QualType QualType::getNonPackExpansionType() const {
3553 // We never wrap type sugar around a PackExpansionType.
3554 if (auto *PET = dyn_cast<PackExpansionType>(Val: getTypePtr()))
3555 return PET->getPattern();
3556 return *this;
3557}
3558
3559QualType QualType::getNonLValueExprType(const ASTContext &Context) const {
3560 if (const auto *RefType = getTypePtr()->getAs<ReferenceType>())
3561 return RefType->getPointeeType();
3562
3563 // C++0x [basic.lval]:
3564 // Class prvalues can have cv-qualified types; non-class prvalues always
3565 // have cv-unqualified types.
3566 //
3567 // See also C99 6.3.2.1p2.
3568 if (!Context.getLangOpts().CPlusPlus ||
3569 (!getTypePtr()->isDependentType() && !getTypePtr()->isRecordType()))
3570 return getUnqualifiedType();
3571
3572 return *this;
3573}
3574
3575bool FunctionType::getCFIUncheckedCalleeAttr() const {
3576 if (const auto *FPT = getAs<FunctionProtoType>())
3577 return FPT->hasCFIUncheckedCallee();
3578 return false;
3579}
3580
3581StringRef FunctionType::getNameForCallConv(CallingConv CC) {
3582 switch (CC) {
3583 case CC_C:
3584 return "cdecl";
3585 case CC_X86StdCall:
3586 return "stdcall";
3587 case CC_X86FastCall:
3588 return "fastcall";
3589 case CC_X86ThisCall:
3590 return "thiscall";
3591 case CC_X86Pascal:
3592 return "pascal";
3593 case CC_X86VectorCall:
3594 return "vectorcall";
3595 case CC_Win64:
3596 return "ms_abi";
3597 case CC_X86_64SysV:
3598 return "sysv_abi";
3599 case CC_X86RegCall:
3600 return "regcall";
3601 case CC_AAPCS:
3602 return "aapcs";
3603 case CC_AAPCS_VFP:
3604 return "aapcs-vfp";
3605 case CC_AArch64VectorCall:
3606 return "aarch64_vector_pcs";
3607 case CC_AArch64SVEPCS:
3608 return "aarch64_sve_pcs";
3609 case CC_IntelOclBicc:
3610 return "intel_ocl_bicc";
3611 case CC_SpirFunction:
3612 return "spir_function";
3613 case CC_DeviceKernel:
3614 return "device_kernel";
3615 case CC_Swift:
3616 return "swiftcall";
3617 case CC_SwiftAsync:
3618 return "swiftasynccall";
3619 case CC_PreserveMost:
3620 return "preserve_most";
3621 case CC_PreserveAll:
3622 return "preserve_all";
3623 case CC_M68kRTD:
3624 return "m68k_rtd";
3625 case CC_PreserveNone:
3626 return "preserve_none";
3627 // clang-format off
3628 case CC_RISCVVectorCall: return "riscv_vector_cc";
3629#define CC_VLS_CASE(ABI_VLEN) \
3630 case CC_RISCVVLSCall_##ABI_VLEN: return "riscv_vls_cc(" #ABI_VLEN ")";
3631 CC_VLS_CASE(32)
3632 CC_VLS_CASE(64)
3633 CC_VLS_CASE(128)
3634 CC_VLS_CASE(256)
3635 CC_VLS_CASE(512)
3636 CC_VLS_CASE(1024)
3637 CC_VLS_CASE(2048)
3638 CC_VLS_CASE(4096)
3639 CC_VLS_CASE(8192)
3640 CC_VLS_CASE(16384)
3641 CC_VLS_CASE(32768)
3642 CC_VLS_CASE(65536)
3643#undef CC_VLS_CASE
3644 // clang-format on
3645 }
3646
3647 llvm_unreachable("Invalid calling convention.");
3648}
3649
3650void FunctionProtoType::ExceptionSpecInfo::instantiate() {
3651 assert(Type == EST_Uninstantiated);
3652 NoexceptExpr =
3653 cast<FunctionProtoType>(SourceTemplate->getType())->getNoexceptExpr();
3654 Type = EST_DependentNoexcept;
3655}
3656
3657FunctionProtoType::FunctionProtoType(QualType result, ArrayRef<QualType> params,
3658 QualType canonical,
3659 const ExtProtoInfo &epi)
3660 : FunctionType(FunctionProto, result, canonical, result->getDependence(),
3661 epi.ExtInfo) {
3662 FunctionTypeBits.FastTypeQuals = epi.TypeQuals.getFastQualifiers();
3663 FunctionTypeBits.RefQualifier = epi.RefQualifier;
3664 FunctionTypeBits.NumParams = params.size();
3665 assert(getNumParams() == params.size() && "NumParams overflow!");
3666 FunctionTypeBits.ExceptionSpecType = epi.ExceptionSpec.Type;
3667 FunctionTypeBits.HasExtParameterInfos = !!epi.ExtParameterInfos;
3668 FunctionTypeBits.Variadic = epi.Variadic;
3669 FunctionTypeBits.HasTrailingReturn = epi.HasTrailingReturn;
3670 FunctionTypeBits.CFIUncheckedCallee = epi.CFIUncheckedCallee;
3671
3672 if (epi.requiresFunctionProtoTypeExtraBitfields()) {
3673 FunctionTypeBits.HasExtraBitfields = true;
3674 auto &ExtraBits = *getTrailingObjects<FunctionTypeExtraBitfields>();
3675 ExtraBits = FunctionTypeExtraBitfields();
3676 } else {
3677 FunctionTypeBits.HasExtraBitfields = false;
3678 }
3679
3680 if (epi.requiresFunctionProtoTypeArmAttributes()) {
3681 auto &ArmTypeAttrs = *getTrailingObjects<FunctionTypeArmAttributes>();
3682 ArmTypeAttrs = FunctionTypeArmAttributes();
3683
3684 // Also set the bit in FunctionTypeExtraBitfields
3685 auto &ExtraBits = *getTrailingObjects<FunctionTypeExtraBitfields>();
3686 ExtraBits.HasArmTypeAttributes = true;
3687 }
3688
3689 // Fill in the trailing argument array.
3690 auto *argSlot = getTrailingObjects<QualType>();
3691 for (unsigned i = 0; i != getNumParams(); ++i) {
3692 addDependence(params[i]->getDependence() &
3693 ~TypeDependence::VariablyModified);
3694 argSlot[i] = params[i];
3695 }
3696
3697 // Propagate the SME ACLE attributes.
3698 if (epi.AArch64SMEAttributes != SME_NormalFunction) {
3699 auto &ArmTypeAttrs = *getTrailingObjects<FunctionTypeArmAttributes>();
3700 assert(epi.AArch64SMEAttributes <= SME_AttributeMask &&
3701 "Not enough bits to encode SME attributes");
3702 ArmTypeAttrs.AArch64SMEAttributes = epi.AArch64SMEAttributes;
3703 }
3704
3705 // Fill in the exception type array if present.
3706 if (getExceptionSpecType() == EST_Dynamic) {
3707 auto &ExtraBits = *getTrailingObjects<FunctionTypeExtraBitfields>();
3708 size_t NumExceptions = epi.ExceptionSpec.Exceptions.size();
3709 assert(NumExceptions <= 1023 && "Not enough bits to encode exceptions");
3710 ExtraBits.NumExceptionType = NumExceptions;
3711
3712 assert(hasExtraBitfields() && "missing trailing extra bitfields!");
3713 auto *exnSlot =
3714 reinterpret_cast<QualType *>(getTrailingObjects<ExceptionType>());
3715 unsigned I = 0;
3716 for (QualType ExceptionType : epi.ExceptionSpec.Exceptions) {
3717 // Note that, before C++17, a dependent exception specification does
3718 // *not* make a type dependent; it's not even part of the C++ type
3719 // system.
3720 addDependence(
3721 ExceptionType->getDependence() &
3722 (TypeDependence::Instantiation | TypeDependence::UnexpandedPack));
3723
3724 exnSlot[I++] = ExceptionType;
3725 }
3726 }
3727 // Fill in the Expr * in the exception specification if present.
3728 else if (isComputedNoexcept(ESpecType: getExceptionSpecType())) {
3729 assert(epi.ExceptionSpec.NoexceptExpr && "computed noexcept with no expr");
3730 assert((getExceptionSpecType() == EST_DependentNoexcept) ==
3731 epi.ExceptionSpec.NoexceptExpr->isValueDependent());
3732
3733 // Store the noexcept expression and context.
3734 *getTrailingObjects<Expr *>() = epi.ExceptionSpec.NoexceptExpr;
3735
3736 addDependence(
3737 D: toTypeDependence(epi.ExceptionSpec.NoexceptExpr->getDependence()) &
3738 (TypeDependence::Instantiation | TypeDependence::UnexpandedPack));
3739 }
3740 // Fill in the FunctionDecl * in the exception specification if present.
3741 else if (getExceptionSpecType() == EST_Uninstantiated) {
3742 // Store the function decl from which we will resolve our
3743 // exception specification.
3744 auto **slot = getTrailingObjects<FunctionDecl *>();
3745 slot[0] = epi.ExceptionSpec.SourceDecl;
3746 slot[1] = epi.ExceptionSpec.SourceTemplate;
3747 // This exception specification doesn't make the type dependent, because
3748 // it's not instantiated as part of instantiating the type.
3749 } else if (getExceptionSpecType() == EST_Unevaluated) {
3750 // Store the function decl from which we will resolve our
3751 // exception specification.
3752 auto **slot = getTrailingObjects<FunctionDecl *>();
3753 slot[0] = epi.ExceptionSpec.SourceDecl;
3754 }
3755
3756 // If this is a canonical type, and its exception specification is dependent,
3757 // then it's a dependent type. This only happens in C++17 onwards.
3758 if (isCanonicalUnqualified()) {
3759 if (getExceptionSpecType() == EST_Dynamic ||
3760 getExceptionSpecType() == EST_DependentNoexcept) {
3761 assert(hasDependentExceptionSpec() && "type should not be canonical");
3762 addDependence(TypeDependence::DependentInstantiation);
3763 }
3764 } else if (getCanonicalTypeInternal()->isDependentType()) {
3765 // Ask our canonical type whether our exception specification was dependent.
3766 addDependence(TypeDependence::DependentInstantiation);
3767 }
3768
3769 // Fill in the extra parameter info if present.
3770 if (epi.ExtParameterInfos) {
3771 auto *extParamInfos = getTrailingObjects<ExtParameterInfo>();
3772 for (unsigned i = 0; i != getNumParams(); ++i)
3773 extParamInfos[i] = epi.ExtParameterInfos[i];
3774 }
3775
3776 if (epi.TypeQuals.hasNonFastQualifiers()) {
3777 FunctionTypeBits.HasExtQuals = 1;
3778 *getTrailingObjects<Qualifiers>() = epi.TypeQuals;
3779 } else {
3780 FunctionTypeBits.HasExtQuals = 0;
3781 }
3782
3783 // Fill in the Ellipsis location info if present.
3784 if (epi.Variadic) {
3785 auto &EllipsisLoc = *getTrailingObjects<SourceLocation>();
3786 EllipsisLoc = epi.EllipsisLoc;
3787 }
3788
3789 if (!epi.FunctionEffects.empty()) {
3790 auto &ExtraBits = *getTrailingObjects<FunctionTypeExtraBitfields>();
3791 size_t EffectsCount = epi.FunctionEffects.size();
3792 ExtraBits.NumFunctionEffects = EffectsCount;
3793 assert(ExtraBits.NumFunctionEffects == EffectsCount &&
3794 "effect bitfield overflow");
3795
3796 ArrayRef<FunctionEffect> SrcFX = epi.FunctionEffects.effects();
3797 auto *DestFX = getTrailingObjects<FunctionEffect>();
3798 llvm::uninitialized_copy(SrcFX, DestFX);
3799
3800 ArrayRef<EffectConditionExpr> SrcConds = epi.FunctionEffects.conditions();
3801 if (!SrcConds.empty()) {
3802 ExtraBits.EffectsHaveConditions = true;
3803 auto *DestConds = getTrailingObjects<EffectConditionExpr>();
3804 llvm::uninitialized_copy(SrcConds, DestConds);
3805 assert(llvm::any_of(SrcConds,
3806 [](const EffectConditionExpr &EC) {
3807 if (const Expr *E = EC.getCondition())
3808 return E->isTypeDependent() ||
3809 E->isValueDependent();
3810 return false;
3811 }) &&
3812 "expected a dependent expression among the conditions");
3813 addDependence(TypeDependence::DependentInstantiation);
3814 }
3815 }
3816}
3817
3818bool FunctionProtoType::hasDependentExceptionSpec() const {
3819 if (Expr *NE = getNoexceptExpr())
3820 return NE->isValueDependent();
3821 for (QualType ET : exceptions())
3822 // A pack expansion with a non-dependent pattern is still dependent,
3823 // because we don't know whether the pattern is in the exception spec
3824 // or not (that depends on whether the pack has 0 expansions).
3825 if (ET->isDependentType() || ET->getAs<PackExpansionType>())
3826 return true;
3827 return false;
3828}
3829
3830bool FunctionProtoType::hasInstantiationDependentExceptionSpec() const {
3831 if (Expr *NE = getNoexceptExpr())
3832 return NE->isInstantiationDependent();
3833 for (QualType ET : exceptions())
3834 if (ET->isInstantiationDependentType())
3835 return true;
3836 return false;
3837}
3838
3839CanThrowResult FunctionProtoType::canThrow() const {
3840 switch (getExceptionSpecType()) {
3841 case EST_Unparsed:
3842 case EST_Unevaluated:
3843 llvm_unreachable("should not call this with unresolved exception specs");
3844
3845 case EST_DynamicNone:
3846 case EST_BasicNoexcept:
3847 case EST_NoexceptTrue:
3848 case EST_NoThrow:
3849 return CT_Cannot;
3850
3851 case EST_None:
3852 case EST_MSAny:
3853 case EST_NoexceptFalse:
3854 return CT_Can;
3855
3856 case EST_Dynamic:
3857 // A dynamic exception specification is throwing unless every exception
3858 // type is an (unexpanded) pack expansion type.
3859 for (unsigned I = 0; I != getNumExceptions(); ++I)
3860 if (!getExceptionType(i: I)->getAs<PackExpansionType>())
3861 return CT_Can;
3862 return CT_Dependent;
3863
3864 case EST_Uninstantiated:
3865 case EST_DependentNoexcept:
3866 return CT_Dependent;
3867 }
3868
3869 llvm_unreachable("unexpected exception specification kind");
3870}
3871
3872bool FunctionProtoType::isTemplateVariadic() const {
3873 for (unsigned ArgIdx = getNumParams(); ArgIdx; --ArgIdx)
3874 if (isa<PackExpansionType>(Val: getParamType(i: ArgIdx - 1)))
3875 return true;
3876
3877 return false;
3878}
3879
3880void FunctionProtoType::Profile(llvm::FoldingSetNodeID &ID, QualType Result,
3881 const QualType *ArgTys, unsigned NumParams,
3882 const ExtProtoInfo &epi,
3883 const ASTContext &Context, bool Canonical) {
3884 // We have to be careful not to get ambiguous profile encodings.
3885 // Note that valid type pointers are never ambiguous with anything else.
3886 //
3887 // The encoding grammar begins:
3888 // type type* bool int bool
3889 // If that final bool is true, then there is a section for the EH spec:
3890 // bool type*
3891 // This is followed by an optional "consumed argument" section of the
3892 // same length as the first type sequence:
3893 // bool*
3894 // This is followed by the ext info:
3895 // int
3896 // Finally we have a trailing return type flag (bool)
3897 // combined with AArch64 SME Attributes, to save space:
3898 // int
3899 // combined with any FunctionEffects
3900 //
3901 // There is no ambiguity between the consumed arguments and an empty EH
3902 // spec because of the leading 'bool' which unambiguously indicates
3903 // whether the following bool is the EH spec or part of the arguments.
3904
3905 ID.AddPointer(Ptr: Result.getAsOpaquePtr());
3906 for (unsigned i = 0; i != NumParams; ++i)
3907 ID.AddPointer(Ptr: ArgTys[i].getAsOpaquePtr());
3908 // This method is relatively performance sensitive, so as a performance
3909 // shortcut, use one AddInteger call instead of four for the next four
3910 // fields.
3911 assert(!(unsigned(epi.Variadic) & ~1) && !(unsigned(epi.RefQualifier) & ~3) &&
3912 !(unsigned(epi.ExceptionSpec.Type) & ~15) &&
3913 "Values larger than expected.");
3914 ID.AddInteger(unsigned(epi.Variadic) + (epi.RefQualifier << 1) +
3915 (epi.ExceptionSpec.Type << 3));
3916 ID.Add(x: epi.TypeQuals);
3917 if (epi.ExceptionSpec.Type == EST_Dynamic) {
3918 for (QualType Ex : epi.ExceptionSpec.Exceptions)
3919 ID.AddPointer(Ex.getAsOpaquePtr());
3920 } else if (isComputedNoexcept(epi.ExceptionSpec.Type)) {
3921 epi.ExceptionSpec.NoexceptExpr->Profile(ID, Context, Canonical);
3922 } else if (epi.ExceptionSpec.Type == EST_Uninstantiated ||
3923 epi.ExceptionSpec.Type == EST_Unevaluated) {
3924 ID.AddPointer(Ptr: epi.ExceptionSpec.SourceDecl->getCanonicalDecl());
3925 }
3926 if (epi.ExtParameterInfos) {
3927 for (unsigned i = 0; i != NumParams; ++i)
3928 ID.AddInteger(I: epi.ExtParameterInfos[i].getOpaqueValue());
3929 }
3930
3931 epi.ExtInfo.Profile(ID);
3932
3933 unsigned EffectCount = epi.FunctionEffects.size();
3934 bool HasConds = !epi.FunctionEffects.Conditions.empty();
3935
3936 ID.AddInteger(I: (EffectCount << 3) | (HasConds << 2) |
3937 (epi.AArch64SMEAttributes << 1) | epi.HasTrailingReturn);
3938 ID.AddInteger(I: epi.CFIUncheckedCallee);
3939
3940 for (unsigned Idx = 0; Idx != EffectCount; ++Idx) {
3941 ID.AddInteger(epi.FunctionEffects.Effects[Idx].toOpaqueInt32());
3942 if (HasConds)
3943 ID.AddPointer(Ptr: epi.FunctionEffects.Conditions[Idx].getCondition());
3944 }
3945}
3946
3947void FunctionProtoType::Profile(llvm::FoldingSetNodeID &ID,
3948 const ASTContext &Ctx) {
3949 Profile(ID, getReturnType(), param_type_begin(), getNumParams(),
3950 getExtProtoInfo(), Ctx, isCanonicalUnqualified());
3951}
3952
3953TypeCoupledDeclRefInfo::TypeCoupledDeclRefInfo(ValueDecl *D, bool Deref)
3954 : Data(D, Deref << DerefShift) {}
3955
3956bool TypeCoupledDeclRefInfo::isDeref() const {
3957 return Data.getInt() & DerefMask;
3958}
3959ValueDecl *TypeCoupledDeclRefInfo::getDecl() const { return Data.getPointer(); }
3960unsigned TypeCoupledDeclRefInfo::getInt() const { return Data.getInt(); }
3961void *TypeCoupledDeclRefInfo::getOpaqueValue() const {
3962 return Data.getOpaqueValue();
3963}
3964bool TypeCoupledDeclRefInfo::operator==(
3965 const TypeCoupledDeclRefInfo &Other) const {
3966 return getOpaqueValue() == Other.getOpaqueValue();
3967}
3968void TypeCoupledDeclRefInfo::setFromOpaqueValue(void *V) {
3969 Data.setFromOpaqueValue(V);
3970}
3971
3972BoundsAttributedType::BoundsAttributedType(TypeClass TC, QualType Wrapped,
3973 QualType Canon)
3974 : Type(TC, Canon, Wrapped->getDependence()), WrappedTy(Wrapped) {}
3975
3976CountAttributedType::CountAttributedType(
3977 QualType Wrapped, QualType Canon, Expr *CountExpr, bool CountInBytes,
3978 bool OrNull, ArrayRef<TypeCoupledDeclRefInfo> CoupledDecls)
3979 : BoundsAttributedType(CountAttributed, Wrapped, Canon),
3980 CountExpr(CountExpr) {
3981 CountAttributedTypeBits.NumCoupledDecls = CoupledDecls.size();
3982 CountAttributedTypeBits.CountInBytes = CountInBytes;
3983 CountAttributedTypeBits.OrNull = OrNull;
3984 auto *DeclSlot = getTrailingObjects<TypeCoupledDeclRefInfo>();
3985 Decls = llvm::ArrayRef(DeclSlot, CoupledDecls.size());
3986 for (unsigned i = 0; i != CoupledDecls.size(); ++i)
3987 DeclSlot[i] = CoupledDecls[i];
3988}
3989
3990StringRef CountAttributedType::getAttributeName(bool WithMacroPrefix) const {
3991// TODO: This method isn't really ideal because it doesn't return the spelling
3992// of the attribute that was used in the user's code. This method is used for
3993// diagnostics so the fact it doesn't use the spelling of the attribute in
3994// the user's code could be confusing (#113585).
3995#define ENUMERATE_ATTRS(PREFIX) \
3996 do { \
3997 if (isCountInBytes()) { \
3998 if (isOrNull()) \
3999 return PREFIX "sized_by_or_null"; \
4000 return PREFIX "sized_by"; \
4001 } \
4002 if (isOrNull()) \
4003 return PREFIX "counted_by_or_null"; \
4004 return PREFIX "counted_by"; \
4005 } while (0)
4006
4007 if (WithMacroPrefix)
4008 ENUMERATE_ATTRS("__");
4009 else
4010 ENUMERATE_ATTRS("");
4011
4012#undef ENUMERATE_ATTRS
4013}
4014
4015TypedefType::TypedefType(TypeClass tc, const TypedefNameDecl *D,
4016 QualType UnderlyingType, bool HasTypeDifferentFromDecl)
4017 : Type(tc, UnderlyingType.getCanonicalType(),
4018 toSemanticDependence(D: UnderlyingType->getDependence())),
4019 Decl(const_cast<TypedefNameDecl *>(D)) {
4020 TypedefBits.hasTypeDifferentFromDecl = HasTypeDifferentFromDecl;
4021 if (!typeMatchesDecl())
4022 *getTrailingObjects() = UnderlyingType;
4023}
4024
4025QualType TypedefType::desugar() const {
4026 return typeMatchesDecl() ? Decl->getUnderlyingType() : *getTrailingObjects();
4027}
4028
4029UsingType::UsingType(const UsingShadowDecl *Found, QualType Underlying,
4030 QualType Canon)
4031 : Type(Using, Canon, toSemanticDependence(Canon->getDependence())),
4032 Found(const_cast<UsingShadowDecl *>(Found)) {
4033 UsingBits.hasTypeDifferentFromDecl = !Underlying.isNull();
4034 if (!typeMatchesDecl())
4035 *getTrailingObjects() = Underlying;
4036}
4037
4038QualType UsingType::getUnderlyingType() const {
4039 return typeMatchesDecl()
4040 ? QualType(
4041 cast<TypeDecl>(Val: Found->getTargetDecl())->getTypeForDecl(), 0)
4042 : *getTrailingObjects();
4043}
4044
4045QualType MacroQualifiedType::desugar() const { return getUnderlyingType(); }
4046
4047QualType MacroQualifiedType::getModifiedType() const {
4048 // Step over MacroQualifiedTypes from the same macro to find the type
4049 // ultimately qualified by the macro qualifier.
4050 QualType Inner = cast<AttributedType>(Val: getUnderlyingType())->getModifiedType();
4051 while (auto *InnerMQT = dyn_cast<MacroQualifiedType>(Val&: Inner)) {
4052 if (InnerMQT->getMacroIdentifier() != getMacroIdentifier())
4053 break;
4054 Inner = InnerMQT->getModifiedType();
4055 }
4056 return Inner;
4057}
4058
4059TypeOfExprType::TypeOfExprType(const ASTContext &Context, Expr *E,
4060 TypeOfKind Kind, QualType Can)
4061 : Type(TypeOfExpr,
4062 // We have to protect against 'Can' being invalid through its
4063 // default argument.
4064 Kind == TypeOfKind::Unqualified && !Can.isNull()
4065 ? Context.getUnqualifiedArrayType(Can).getAtomicUnqualifiedType()
4066 : Can,
4067 toTypeDependence(E->getDependence()) |
4068 (E->getType()->getDependence() &
4069 TypeDependence::VariablyModified)),
4070 TOExpr(E), Context(Context) {
4071 TypeOfBits.Kind = static_cast<unsigned>(Kind);
4072}
4073
4074bool TypeOfExprType::isSugared() const { return !TOExpr->isTypeDependent(); }
4075
4076QualType TypeOfExprType::desugar() const {
4077 if (isSugared()) {
4078 QualType QT = getUnderlyingExpr()->getType();
4079 return getKind() == TypeOfKind::Unqualified
4080 ? Context.getUnqualifiedArrayType(T: QT).getAtomicUnqualifiedType()
4081 : QT;
4082 }
4083 return QualType(this, 0);
4084}
4085
4086void DependentTypeOfExprType::Profile(llvm::FoldingSetNodeID &ID,
4087 const ASTContext &Context, Expr *E,
4088 bool IsUnqual) {
4089 E->Profile(ID, Context, true);
4090 ID.AddBoolean(B: IsUnqual);
4091}
4092
4093TypeOfType::TypeOfType(const ASTContext &Context, QualType T, QualType Can,
4094 TypeOfKind Kind)
4095 : Type(TypeOf,
4096 Kind == TypeOfKind::Unqualified
4097 ? Context.getUnqualifiedArrayType(Can).getAtomicUnqualifiedType()
4098 : Can,
4099 T->getDependence()),
4100 TOType(T), Context(Context) {
4101 TypeOfBits.Kind = static_cast<unsigned>(Kind);
4102}
4103
4104QualType TypeOfType::desugar() const {
4105 QualType QT = getUnmodifiedType();
4106 return getKind() == TypeOfKind::Unqualified
4107 ? Context.getUnqualifiedArrayType(T: QT).getAtomicUnqualifiedType()
4108 : QT;
4109}
4110
4111DecltypeType::DecltypeType(Expr *E, QualType underlyingType, QualType can)
4112 // C++11 [temp.type]p2: "If an expression e involves a template parameter,
4113 // decltype(e) denotes a unique dependent type." Hence a decltype type is
4114 // type-dependent even if its expression is only instantiation-dependent.
4115 : Type(Decltype, can,
4116 toTypeDependence(E->getDependence()) |
4117 (E->isInstantiationDependent() ? TypeDependence::Dependent
4118 : TypeDependence::None) |
4119 (E->getType()->getDependence() &
4120 TypeDependence::VariablyModified)),
4121 E(E), UnderlyingType(underlyingType) {}
4122
4123bool DecltypeType::isSugared() const { return !E->isInstantiationDependent(); }
4124
4125QualType DecltypeType::desugar() const {
4126 if (isSugared())
4127 return getUnderlyingType();
4128
4129 return QualType(this, 0);
4130}
4131
4132DependentDecltypeType::DependentDecltypeType(Expr *E)
4133 : DecltypeType(E, QualType()) {}
4134
4135void DependentDecltypeType::Profile(llvm::FoldingSetNodeID &ID,
4136 const ASTContext &Context, Expr *E) {
4137 E->Profile(ID, Context, true);
4138}
4139
4140PackIndexingType::PackIndexingType(QualType Canonical, QualType Pattern,
4141 Expr *IndexExpr, bool FullySubstituted,
4142 ArrayRef<QualType> Expansions)
4143 : Type(PackIndexing, Canonical,
4144 computeDependence(Pattern, IndexExpr, Expansions)),
4145 Pattern(Pattern), IndexExpr(IndexExpr), Size(Expansions.size()),
4146 FullySubstituted(FullySubstituted) {
4147
4148 llvm::uninitialized_copy(Expansions, getTrailingObjects());
4149}
4150
4151UnsignedOrNone PackIndexingType::getSelectedIndex() const {
4152 if (isInstantiationDependentType())
4153 return std::nullopt;
4154 // Should only be not a constant for error recovery.
4155 ConstantExpr *CE = dyn_cast<ConstantExpr>(Val: getIndexExpr());
4156 if (!CE)
4157 return std::nullopt;
4158 auto Index = CE->getResultAsAPSInt();
4159 assert(Index.isNonNegative() && "Invalid index");
4160 return static_cast<unsigned>(Index.getExtValue());
4161}
4162
4163TypeDependence
4164PackIndexingType::computeDependence(QualType Pattern, Expr *IndexExpr,
4165 ArrayRef<QualType> Expansions) {
4166 TypeDependence IndexD = toTypeDependence(D: IndexExpr->getDependence());
4167
4168 TypeDependence TD = IndexD | (IndexExpr->isInstantiationDependent()
4169 ? TypeDependence::DependentInstantiation
4170 : TypeDependence::None);
4171 if (Expansions.empty())
4172 TD |= Pattern->getDependence() & TypeDependence::DependentInstantiation;
4173 else
4174 for (const QualType &T : Expansions)
4175 TD |= T->getDependence();
4176
4177 if (!(IndexD & TypeDependence::UnexpandedPack))
4178 TD &= ~TypeDependence::UnexpandedPack;
4179
4180 // If the pattern does not contain an unexpended pack,
4181 // the type is still dependent, and invalid
4182 if (!Pattern->containsUnexpandedParameterPack())
4183 TD |= TypeDependence::Error | TypeDependence::DependentInstantiation;
4184
4185 return TD;
4186}
4187
4188void PackIndexingType::Profile(llvm::FoldingSetNodeID &ID,
4189 const ASTContext &Context) {
4190 Profile(ID, Context, Pattern: getPattern(), E: getIndexExpr(), FullySubstituted: isFullySubstituted(),
4191 Expansions: getExpansions());
4192}
4193
4194void PackIndexingType::Profile(llvm::FoldingSetNodeID &ID,
4195 const ASTContext &Context, QualType Pattern,
4196 Expr *E, bool FullySubstituted,
4197 ArrayRef<QualType> Expansions) {
4198
4199 E->Profile(ID, Context, true);
4200 ID.AddBoolean(B: FullySubstituted);
4201 if (!Expansions.empty()) {
4202 ID.AddInteger(I: Expansions.size());
4203 for (QualType T : Expansions)
4204 T.getCanonicalType().Profile(ID);
4205 } else {
4206 Pattern.Profile(ID);
4207 }
4208}
4209
4210UnaryTransformType::UnaryTransformType(QualType BaseType,
4211 QualType UnderlyingType, UTTKind UKind,
4212 QualType CanonicalType)
4213 : Type(UnaryTransform, CanonicalType, BaseType->getDependence()),
4214 BaseType(BaseType), UnderlyingType(UnderlyingType), UKind(UKind) {}
4215
4216TagType::TagType(TypeClass TC, const TagDecl *D, QualType can)
4217 : Type(TC, can,
4218 D->isDependentType() ? TypeDependence::DependentInstantiation
4219 : TypeDependence::None),
4220 decl(const_cast<TagDecl *>(D)) {}
4221
4222static TagDecl *getInterestingTagDecl(TagDecl *decl) {
4223 for (auto *I : decl->redecls()) {
4224 if (I->isCompleteDefinition() || I->isBeingDefined())
4225 return I;
4226 }
4227 // If there's no definition (not even in progress), return what we have.
4228 return decl;
4229}
4230
4231TagDecl *TagType::getDecl() const { return getInterestingTagDecl(decl); }
4232
4233bool TagType::isBeingDefined() const { return getDecl()->isBeingDefined(); }
4234
4235bool RecordType::hasConstFields() const {
4236 std::vector<const RecordType *> RecordTypeList;
4237 RecordTypeList.push_back(x: this);
4238 unsigned NextToCheckIndex = 0;
4239
4240 while (RecordTypeList.size() > NextToCheckIndex) {
4241 for (FieldDecl *FD :
4242 RecordTypeList[NextToCheckIndex]->getDecl()->fields()) {
4243 QualType FieldTy = FD->getType();
4244 if (FieldTy.isConstQualified())
4245 return true;
4246 FieldTy = FieldTy.getCanonicalType();
4247 if (const auto *FieldRecTy = FieldTy->getAs<RecordType>()) {
4248 if (!llvm::is_contained(RecordTypeList, FieldRecTy))
4249 RecordTypeList.push_back(FieldRecTy);
4250 }
4251 }
4252 ++NextToCheckIndex;
4253 }
4254 return false;
4255}
4256
4257AttributedType::AttributedType(QualType canon, const Attr *attr,
4258 QualType modified, QualType equivalent)
4259 : AttributedType(canon, attr->getKind(), attr, modified, equivalent) {}
4260
4261AttributedType::AttributedType(QualType canon, attr::Kind attrKind,
4262 const Attr *attr, QualType modified,
4263 QualType equivalent)
4264 : Type(Attributed, canon, equivalent->getDependence()), Attribute(attr),
4265 ModifiedType(modified), EquivalentType(equivalent) {
4266 AttributedTypeBits.AttrKind = attrKind;
4267 assert(!attr || attr->getKind() == attrKind);
4268}
4269
4270bool AttributedType::isQualifier() const {
4271 // FIXME: Generate this with TableGen.
4272 switch (getAttrKind()) {
4273 // These are type qualifiers in the traditional C sense: they annotate
4274 // something about a specific value/variable of a type. (They aren't
4275 // always part of the canonical type, though.)
4276 case attr::ObjCGC:
4277 case attr::ObjCOwnership:
4278 case attr::ObjCInertUnsafeUnretained:
4279 case attr::TypeNonNull:
4280 case attr::TypeNullable:
4281 case attr::TypeNullableResult:
4282 case attr::TypeNullUnspecified:
4283 case attr::LifetimeBound:
4284 case attr::AddressSpace:
4285 return true;
4286
4287 // All other type attributes aren't qualifiers; they rewrite the modified
4288 // type to be a semantically different type.
4289 default:
4290 return false;
4291 }
4292}
4293
4294bool AttributedType::isMSTypeSpec() const {
4295 // FIXME: Generate this with TableGen?
4296 switch (getAttrKind()) {
4297 default:
4298 return false;
4299 case attr::Ptr32:
4300 case attr::Ptr64:
4301 case attr::SPtr:
4302 case attr::UPtr:
4303 return true;
4304 }
4305 llvm_unreachable("invalid attr kind");
4306}
4307
4308bool AttributedType::isWebAssemblyFuncrefSpec() const {
4309 return getAttrKind() == attr::WebAssemblyFuncref;
4310}
4311
4312bool AttributedType::isCallingConv() const {
4313 // FIXME: Generate this with TableGen.
4314 switch (getAttrKind()) {
4315 default:
4316 return false;
4317 case attr::Pcs:
4318 case attr::CDecl:
4319 case attr::FastCall:
4320 case attr::StdCall:
4321 case attr::ThisCall:
4322 case attr::RegCall:
4323 case attr::SwiftCall:
4324 case attr::SwiftAsyncCall:
4325 case attr::VectorCall:
4326 case attr::AArch64VectorPcs:
4327 case attr::AArch64SVEPcs:
4328 case attr::DeviceKernel:
4329 case attr::Pascal:
4330 case attr::MSABI:
4331 case attr::SysVABI:
4332 case attr::IntelOclBicc:
4333 case attr::PreserveMost:
4334 case attr::PreserveAll:
4335 case attr::M68kRTD:
4336 case attr::PreserveNone:
4337 case attr::RISCVVectorCC:
4338 case attr::RISCVVLSCC:
4339 return true;
4340 }
4341 llvm_unreachable("invalid attr kind");
4342}
4343
4344CXXRecordDecl *InjectedClassNameType::getDecl() const {
4345 return cast<CXXRecordDecl>(Val: getInterestingTagDecl(Decl));
4346}
4347
4348IdentifierInfo *TemplateTypeParmType::getIdentifier() const {
4349 return isCanonicalUnqualified() ? nullptr : getDecl()->getIdentifier();
4350}
4351
4352static const TemplateTypeParmDecl *getReplacedParameter(Decl *D,
4353 unsigned Index) {
4354 if (const auto *TTP = dyn_cast<TemplateTypeParmDecl>(Val: D))
4355 return TTP;
4356 return cast<TemplateTypeParmDecl>(
4357 Val: getReplacedTemplateParameterList(D)->getParam(Idx: Index));
4358}
4359
4360SubstTemplateTypeParmType::SubstTemplateTypeParmType(QualType Replacement,
4361 Decl *AssociatedDecl,
4362 unsigned Index,
4363 UnsignedOrNone PackIndex,
4364 bool Final)
4365 : Type(SubstTemplateTypeParm, Replacement.getCanonicalType(),
4366 Replacement->getDependence()),
4367 AssociatedDecl(AssociatedDecl) {
4368 SubstTemplateTypeParmTypeBits.HasNonCanonicalUnderlyingType =
4369 Replacement != getCanonicalTypeInternal();
4370 if (SubstTemplateTypeParmTypeBits.HasNonCanonicalUnderlyingType)
4371 *getTrailingObjects() = Replacement;
4372
4373 SubstTemplateTypeParmTypeBits.Index = Index;
4374 SubstTemplateTypeParmTypeBits.Final = Final;
4375 SubstTemplateTypeParmTypeBits.PackIndex =
4376 PackIndex.toInternalRepresentation();
4377 assert(AssociatedDecl != nullptr);
4378}
4379
4380const TemplateTypeParmDecl *
4381SubstTemplateTypeParmType::getReplacedParameter() const {
4382 return ::getReplacedParameter(D: getAssociatedDecl(), Index: getIndex());
4383}
4384
4385void SubstTemplateTypeParmType::Profile(llvm::FoldingSetNodeID &ID,
4386 QualType Replacement,
4387 const Decl *AssociatedDecl,
4388 unsigned Index,
4389 UnsignedOrNone PackIndex, bool Final) {
4390 Replacement.Profile(ID);
4391 ID.AddPointer(Ptr: AssociatedDecl);
4392 ID.AddInteger(I: Index);
4393 ID.AddInteger(I: PackIndex.toInternalRepresentation());
4394 ID.AddBoolean(B: Final);
4395}
4396
4397SubstTemplateTypeParmPackType::SubstTemplateTypeParmPackType(
4398 QualType Canon, Decl *AssociatedDecl, unsigned Index, bool Final,
4399 const TemplateArgument &ArgPack)
4400 : Type(SubstTemplateTypeParmPack, Canon,
4401 TypeDependence::DependentInstantiation |
4402 TypeDependence::UnexpandedPack),
4403 Arguments(ArgPack.pack_begin()),
4404 AssociatedDeclAndFinal(AssociatedDecl, Final) {
4405 SubstTemplateTypeParmPackTypeBits.Index = Index;
4406 SubstTemplateTypeParmPackTypeBits.NumArgs = ArgPack.pack_size();
4407 assert(AssociatedDecl != nullptr);
4408}
4409
4410Decl *SubstTemplateTypeParmPackType::getAssociatedDecl() const {
4411 return AssociatedDeclAndFinal.getPointer();
4412}
4413
4414bool SubstTemplateTypeParmPackType::getFinal() const {
4415 return AssociatedDeclAndFinal.getInt();
4416}
4417
4418const TemplateTypeParmDecl *
4419SubstTemplateTypeParmPackType::getReplacedParameter() const {
4420 return ::getReplacedParameter(D: getAssociatedDecl(), Index: getIndex());
4421}
4422
4423IdentifierInfo *SubstTemplateTypeParmPackType::getIdentifier() const {
4424 return getReplacedParameter()->getIdentifier();
4425}
4426
4427TemplateArgument SubstTemplateTypeParmPackType::getArgumentPack() const {
4428 return TemplateArgument(llvm::ArrayRef(Arguments, getNumArgs()));
4429}
4430
4431void SubstTemplateTypeParmPackType::Profile(llvm::FoldingSetNodeID &ID) {
4432 Profile(ID, AssociatedDecl: getAssociatedDecl(), Index: getIndex(), Final: getFinal(), ArgPack: getArgumentPack());
4433}
4434
4435void SubstTemplateTypeParmPackType::Profile(llvm::FoldingSetNodeID &ID,
4436 const Decl *AssociatedDecl,
4437 unsigned Index, bool Final,
4438 const TemplateArgument &ArgPack) {
4439 ID.AddPointer(Ptr: AssociatedDecl);
4440 ID.AddInteger(I: Index);
4441 ID.AddBoolean(B: Final);
4442 ID.AddInteger(I: ArgPack.pack_size());
4443 for (const auto &P : ArgPack.pack_elements())
4444 ID.AddPointer(Ptr: P.getAsType().getAsOpaquePtr());
4445}
4446
4447bool TemplateSpecializationType::anyDependentTemplateArguments(
4448 const TemplateArgumentListInfo &Args,
4449 ArrayRef<TemplateArgument> Converted) {
4450 return anyDependentTemplateArguments(Args: Args.arguments(), Converted);
4451}
4452
4453bool TemplateSpecializationType::anyDependentTemplateArguments(
4454 ArrayRef<TemplateArgumentLoc> Args, ArrayRef<TemplateArgument> Converted) {
4455 for (const TemplateArgument &Arg : Converted)
4456 if (Arg.isDependent())
4457 return true;
4458 return false;
4459}
4460
4461bool TemplateSpecializationType::anyInstantiationDependentTemplateArguments(
4462 ArrayRef<TemplateArgumentLoc> Args) {
4463 for (const TemplateArgumentLoc &ArgLoc : Args) {
4464 if (ArgLoc.getArgument().isInstantiationDependent())
4465 return true;
4466 }
4467 return false;
4468}
4469
4470TemplateSpecializationType::TemplateSpecializationType(
4471 TemplateName T, bool IsAlias, ArrayRef<TemplateArgument> Args,
4472 QualType Underlying)
4473 : Type(TemplateSpecialization,
4474 Underlying.isNull() ? QualType(this, 0)
4475 : Underlying.getCanonicalType(),
4476 (Underlying.isNull()
4477 ? TypeDependence::DependentInstantiation
4478 : toSemanticDependence(Underlying->getDependence())) |
4479 (toTypeDependence(T.getDependence()) &
4480 TypeDependence::UnexpandedPack)),
4481 Template(T) {
4482 TemplateSpecializationTypeBits.NumArgs = Args.size();
4483 TemplateSpecializationTypeBits.TypeAlias = IsAlias;
4484
4485 assert(!T.getAsDependentTemplateName() &&
4486 "Use DependentTemplateSpecializationType for dependent template-name");
4487 assert((T.getKind() == TemplateName::Template ||
4488 T.getKind() == TemplateName::SubstTemplateTemplateParm ||
4489 T.getKind() == TemplateName::SubstTemplateTemplateParmPack ||
4490 T.getKind() == TemplateName::UsingTemplate ||
4491 T.getKind() == TemplateName::QualifiedTemplate ||
4492 T.getKind() == TemplateName::DeducedTemplate ||
4493 T.getKind() == TemplateName::AssumedTemplate) &&
4494 "Unexpected template name for TemplateSpecializationType");
4495
4496 auto *TemplateArgs =
4497 const_cast<TemplateArgument *>(template_arguments().data());
4498 for (const TemplateArgument &Arg : Args) {
4499 // Update instantiation-dependent, variably-modified, and error bits.
4500 // If the canonical type exists and is non-dependent, the template
4501 // specialization type can be non-dependent even if one of the type
4502 // arguments is. Given:
4503 // template<typename T> using U = int;
4504 // U<T> is always non-dependent, irrespective of the type T.
4505 // However, U<Ts> contains an unexpanded parameter pack, even though
4506 // its expansion (and thus its desugared type) doesn't.
4507 addDependence(toTypeDependence(D: Arg.getDependence()) &
4508 ~TypeDependence::Dependent);
4509 if (Arg.getKind() == TemplateArgument::Type)
4510 addDependence(Arg.getAsType()->getDependence() &
4511 TypeDependence::VariablyModified);
4512 new (TemplateArgs++) TemplateArgument(Arg);
4513 }
4514
4515 // Store the aliased type after the template arguments, if this is a type
4516 // alias template specialization.
4517 if (IsAlias)
4518 *reinterpret_cast<QualType *>(TemplateArgs) = Underlying;
4519}
4520
4521QualType TemplateSpecializationType::getAliasedType() const {
4522 assert(isTypeAlias() && "not a type alias template specialization");
4523 return *reinterpret_cast<const QualType *>(template_arguments().end());
4524}
4525
4526void TemplateSpecializationType::Profile(llvm::FoldingSetNodeID &ID,
4527 const ASTContext &Ctx) {
4528 Profile(ID, T: Template, Args: template_arguments(),
4529 Underlying: isSugared() ? desugar() : QualType(), Context: Ctx);
4530}
4531
4532void TemplateSpecializationType::Profile(llvm::FoldingSetNodeID &ID,
4533 TemplateName T,
4534 ArrayRef<TemplateArgument> Args,
4535 QualType Underlying,
4536 const ASTContext &Context) {
4537 T.Profile(ID);
4538 Underlying.Profile(ID);
4539
4540 ID.AddInteger(I: Args.size());
4541 for (const TemplateArgument &Arg : Args)
4542 Arg.Profile(ID, Context);
4543}
4544
4545QualType QualifierCollector::apply(const ASTContext &Context,
4546 QualType QT) const {
4547 if (!hasNonFastQualifiers())
4548 return QT.withFastQualifiers(TQs: getFastQualifiers());
4549
4550 return Context.getQualifiedType(T: QT, Qs: *this);
4551}
4552
4553QualType QualifierCollector::apply(const ASTContext &Context,
4554 const Type *T) const {
4555 if (!hasNonFastQualifiers())
4556 return QualType(T, getFastQualifiers());
4557
4558 return Context.getQualifiedType(T, Qs: *this);
4559}
4560
4561void ObjCObjectTypeImpl::Profile(llvm::FoldingSetNodeID &ID, QualType BaseType,
4562 ArrayRef<QualType> typeArgs,
4563 ArrayRef<ObjCProtocolDecl *> protocols,
4564 bool isKindOf) {
4565 ID.AddPointer(Ptr: BaseType.getAsOpaquePtr());
4566 ID.AddInteger(I: typeArgs.size());
4567 for (auto typeArg : typeArgs)
4568 ID.AddPointer(Ptr: typeArg.getAsOpaquePtr());
4569 ID.AddInteger(I: protocols.size());
4570 for (auto *proto : protocols)
4571 ID.AddPointer(Ptr: proto);
4572 ID.AddBoolean(B: isKindOf);
4573}
4574
4575void ObjCObjectTypeImpl::Profile(llvm::FoldingSetNodeID &ID) {
4576 Profile(ID, getBaseType(), getTypeArgsAsWritten(),
4577 llvm::ArrayRef(qual_begin(), getNumProtocols()),
4578 isKindOfTypeAsWritten());
4579}
4580
4581void ObjCTypeParamType::Profile(llvm::FoldingSetNodeID &ID,
4582 const ObjCTypeParamDecl *OTPDecl,
4583 QualType CanonicalType,
4584 ArrayRef<ObjCProtocolDecl *> protocols) {
4585 ID.AddPointer(Ptr: OTPDecl);
4586 ID.AddPointer(Ptr: CanonicalType.getAsOpaquePtr());
4587 ID.AddInteger(I: protocols.size());
4588 for (auto *proto : protocols)
4589 ID.AddPointer(Ptr: proto);
4590}
4591
4592void ObjCTypeParamType::Profile(llvm::FoldingSetNodeID &ID) {
4593 Profile(ID, getDecl(), getCanonicalTypeInternal(),
4594 llvm::ArrayRef(qual_begin(), getNumProtocols()));
4595}
4596
4597namespace {
4598
4599/// The cached properties of a type.
4600class CachedProperties {
4601 Linkage L;
4602 bool local;
4603
4604public:
4605 CachedProperties(Linkage L, bool local) : L(L), local(local) {}
4606
4607 Linkage getLinkage() const { return L; }
4608 bool hasLocalOrUnnamedType() const { return local; }
4609
4610 friend CachedProperties merge(CachedProperties L, CachedProperties R) {
4611 Linkage MergedLinkage = minLinkage(L1: L.L, L2: R.L);
4612 return CachedProperties(MergedLinkage, L.hasLocalOrUnnamedType() ||
4613 R.hasLocalOrUnnamedType());
4614 }
4615};
4616
4617} // namespace
4618
4619static CachedProperties computeCachedProperties(const Type *T);
4620
4621namespace clang {
4622
4623/// The type-property cache. This is templated so as to be
4624/// instantiated at an internal type to prevent unnecessary symbol
4625/// leakage.
4626template <class Private> class TypePropertyCache {
4627public:
4628 static CachedProperties get(QualType T) { return get(T.getTypePtr()); }
4629
4630 static CachedProperties get(const Type *T) {
4631 ensure(T);
4632 return CachedProperties(T->TypeBits.getLinkage(),
4633 T->TypeBits.hasLocalOrUnnamedType());
4634 }
4635
4636 static void ensure(const Type *T) {
4637 // If the cache is valid, we're okay.
4638 if (T->TypeBits.isCacheValid())
4639 return;
4640
4641 // If this type is non-canonical, ask its canonical type for the
4642 // relevant information.
4643 if (!T->isCanonicalUnqualified()) {
4644 const Type *CT = T->getCanonicalTypeInternal().getTypePtr();
4645 ensure(T: CT);
4646 T->TypeBits.CacheValid = true;
4647 T->TypeBits.CachedLinkage = CT->TypeBits.CachedLinkage;
4648 T->TypeBits.CachedLocalOrUnnamed = CT->TypeBits.CachedLocalOrUnnamed;
4649 return;
4650 }
4651
4652 // Compute the cached properties and then set the cache.
4653 CachedProperties Result = computeCachedProperties(T);
4654 T->TypeBits.CacheValid = true;
4655 T->TypeBits.CachedLinkage = llvm::to_underlying(E: Result.getLinkage());
4656 T->TypeBits.CachedLocalOrUnnamed = Result.hasLocalOrUnnamedType();
4657 }
4658};
4659
4660} // namespace clang
4661
4662// Instantiate the friend template at a private class. In a
4663// reasonable implementation, these symbols will be internal.
4664// It is terrible that this is the best way to accomplish this.
4665namespace {
4666
4667class Private {};
4668
4669} // namespace
4670
4671using Cache = TypePropertyCache<Private>;
4672
4673static CachedProperties computeCachedProperties(const Type *T) {
4674 switch (T->getTypeClass()) {
4675#define TYPE(Class, Base)
4676#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
4677#include "clang/AST/TypeNodes.inc"
4678 llvm_unreachable("didn't expect a non-canonical type here");
4679
4680#define TYPE(Class, Base)
4681#define DEPENDENT_TYPE(Class, Base) case Type::Class:
4682#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class:
4683#include "clang/AST/TypeNodes.inc"
4684 // Treat instantiation-dependent types as external.
4685 assert(T->isInstantiationDependentType());
4686 return CachedProperties(Linkage::External, false);
4687
4688 case Type::Auto:
4689 case Type::DeducedTemplateSpecialization:
4690 // Give non-deduced 'auto' types external linkage. We should only see them
4691 // here in error recovery.
4692 return CachedProperties(Linkage::External, false);
4693
4694 case Type::BitInt:
4695 case Type::Builtin:
4696 // C++ [basic.link]p8:
4697 // A type is said to have linkage if and only if:
4698 // - it is a fundamental type (3.9.1); or
4699 return CachedProperties(Linkage::External, false);
4700
4701 case Type::Record:
4702 case Type::Enum: {
4703 const TagDecl *Tag = cast<TagType>(T)->getDecl();
4704
4705 // C++ [basic.link]p8:
4706 // - it is a class or enumeration type that is named (or has a name
4707 // for linkage purposes (7.1.3)) and the name has linkage; or
4708 // - it is a specialization of a class template (14); or
4709 Linkage L = Tag->getLinkageInternal();
4710 bool IsLocalOrUnnamed = Tag->getDeclContext()->isFunctionOrMethod() ||
4711 !Tag->hasNameForLinkage();
4712 return CachedProperties(L, IsLocalOrUnnamed);
4713 }
4714
4715 // C++ [basic.link]p8:
4716 // - it is a compound type (3.9.2) other than a class or enumeration,
4717 // compounded exclusively from types that have linkage; or
4718 case Type::Complex:
4719 return Cache::get(cast<ComplexType>(T)->getElementType());
4720 case Type::Pointer:
4721 return Cache::get(cast<PointerType>(T)->getPointeeType());
4722 case Type::BlockPointer:
4723 return Cache::get(cast<BlockPointerType>(T)->getPointeeType());
4724 case Type::LValueReference:
4725 case Type::RValueReference:
4726 return Cache::get(cast<ReferenceType>(T)->getPointeeType());
4727 case Type::MemberPointer: {
4728 const auto *MPT = cast<MemberPointerType>(T);
4729 CachedProperties Cls = [&] {
4730 if (auto *RD = MPT->getMostRecentCXXRecordDecl())
4731 return Cache::get(QualType(RD->getTypeForDecl(), 0));
4732 if (const Type *T = MPT->getQualifier()->getAsType())
4733 return Cache::get(T);
4734 // Treat as a dependent type.
4735 return CachedProperties(Linkage::External, false);
4736 }();
4737 return merge(Cls, Cache::get(MPT->getPointeeType()));
4738 }
4739 case Type::ConstantArray:
4740 case Type::IncompleteArray:
4741 case Type::VariableArray:
4742 case Type::ArrayParameter:
4743 return Cache::get(cast<ArrayType>(T)->getElementType());
4744 case Type::Vector:
4745 case Type::ExtVector:
4746 return Cache::get(cast<VectorType>(T)->getElementType());
4747 case Type::ConstantMatrix:
4748 return Cache::get(cast<ConstantMatrixType>(T)->getElementType());
4749 case Type::FunctionNoProto:
4750 return Cache::get(cast<FunctionType>(T)->getReturnType());
4751 case Type::FunctionProto: {
4752 const auto *FPT = cast<FunctionProtoType>(T);
4753 CachedProperties result = Cache::get(FPT->getReturnType());
4754 for (const auto &ai : FPT->param_types())
4755 result = merge(result, Cache::get(ai));
4756 return result;
4757 }
4758 case Type::ObjCInterface: {
4759 Linkage L = cast<ObjCInterfaceType>(T)->getDecl()->getLinkageInternal();
4760 return CachedProperties(L, false);
4761 }
4762 case Type::ObjCObject:
4763 return Cache::get(cast<ObjCObjectType>(T)->getBaseType());
4764 case Type::ObjCObjectPointer:
4765 return Cache::get(cast<ObjCObjectPointerType>(T)->getPointeeType());
4766 case Type::Atomic:
4767 return Cache::get(cast<AtomicType>(T)->getValueType());
4768 case Type::Pipe:
4769 return Cache::get(cast<PipeType>(T)->getElementType());
4770 case Type::HLSLAttributedResource:
4771 return Cache::get(cast<HLSLAttributedResourceType>(T)->getWrappedType());
4772 case Type::HLSLInlineSpirv:
4773 return CachedProperties(Linkage::External, false);
4774 }
4775
4776 llvm_unreachable("unhandled type class");
4777}
4778
4779/// Determine the linkage of this type.
4780Linkage Type::getLinkage() const {
4781 Cache::ensure(T: this);
4782 return TypeBits.getLinkage();
4783}
4784
4785bool Type::hasUnnamedOrLocalType() const {
4786 Cache::ensure(T: this);
4787 return TypeBits.hasLocalOrUnnamedType();
4788}
4789
4790LinkageInfo LinkageComputer::computeTypeLinkageInfo(const Type *T) {
4791 switch (T->getTypeClass()) {
4792#define TYPE(Class, Base)
4793#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
4794#include "clang/AST/TypeNodes.inc"
4795 llvm_unreachable("didn't expect a non-canonical type here");
4796
4797#define TYPE(Class, Base)
4798#define DEPENDENT_TYPE(Class, Base) case Type::Class:
4799#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class:
4800#include "clang/AST/TypeNodes.inc"
4801 // Treat instantiation-dependent types as external.
4802 assert(T->isInstantiationDependentType());
4803 return LinkageInfo::external();
4804
4805 case Type::BitInt:
4806 case Type::Builtin:
4807 return LinkageInfo::external();
4808
4809 case Type::Auto:
4810 case Type::DeducedTemplateSpecialization:
4811 return LinkageInfo::external();
4812
4813 case Type::Record:
4814 case Type::Enum:
4815 return getDeclLinkageAndVisibility(D: cast<TagType>(T)->getDecl());
4816
4817 case Type::Complex:
4818 return computeTypeLinkageInfo(cast<ComplexType>(T)->getElementType());
4819 case Type::Pointer:
4820 return computeTypeLinkageInfo(cast<PointerType>(T)->getPointeeType());
4821 case Type::BlockPointer:
4822 return computeTypeLinkageInfo(cast<BlockPointerType>(T)->getPointeeType());
4823 case Type::LValueReference:
4824 case Type::RValueReference:
4825 return computeTypeLinkageInfo(cast<ReferenceType>(T)->getPointeeType());
4826 case Type::MemberPointer: {
4827 const auto *MPT = cast<MemberPointerType>(T);
4828 LinkageInfo LV;
4829 if (auto *D = MPT->getMostRecentCXXRecordDecl()) {
4830 LV.merge(other: getDeclLinkageAndVisibility(D: D));
4831 } else if (auto *Ty = MPT->getQualifier()->getAsType()) {
4832 LV.merge(other: computeTypeLinkageInfo(Ty));
4833 }
4834 LV.merge(other: computeTypeLinkageInfo(MPT->getPointeeType()));
4835 return LV;
4836 }
4837 case Type::ConstantArray:
4838 case Type::IncompleteArray:
4839 case Type::VariableArray:
4840 case Type::ArrayParameter:
4841 return computeTypeLinkageInfo(cast<ArrayType>(T)->getElementType());
4842 case Type::Vector:
4843 case Type::ExtVector:
4844 return computeTypeLinkageInfo(cast<VectorType>(T)->getElementType());
4845 case Type::ConstantMatrix:
4846 return computeTypeLinkageInfo(
4847 cast<ConstantMatrixType>(T)->getElementType());
4848 case Type::FunctionNoProto:
4849 return computeTypeLinkageInfo(cast<FunctionType>(T)->getReturnType());
4850 case Type::FunctionProto: {
4851 const auto *FPT = cast<FunctionProtoType>(T);
4852 LinkageInfo LV = computeTypeLinkageInfo(FPT->getReturnType());
4853 for (const auto &ai : FPT->param_types())
4854 LV.merge(computeTypeLinkageInfo(ai));
4855 return LV;
4856 }
4857 case Type::ObjCInterface:
4858 return getDeclLinkageAndVisibility(D: cast<ObjCInterfaceType>(T)->getDecl());
4859 case Type::ObjCObject:
4860 return computeTypeLinkageInfo(cast<ObjCObjectType>(T)->getBaseType());
4861 case Type::ObjCObjectPointer:
4862 return computeTypeLinkageInfo(
4863 cast<ObjCObjectPointerType>(T)->getPointeeType());
4864 case Type::Atomic:
4865 return computeTypeLinkageInfo(cast<AtomicType>(T)->getValueType());
4866 case Type::Pipe:
4867 return computeTypeLinkageInfo(cast<PipeType>(T)->getElementType());
4868 case Type::HLSLAttributedResource:
4869 return computeTypeLinkageInfo(cast<HLSLAttributedResourceType>(T)
4870 ->getContainedType()
4871 ->getCanonicalTypeInternal());
4872 case Type::HLSLInlineSpirv:
4873 return LinkageInfo::external();
4874 {
4875 const auto *ST = cast<HLSLInlineSpirvType>(T);
4876 LinkageInfo LV = LinkageInfo::external();
4877 for (auto &Operand : ST->getOperands()) {
4878 if (Operand.isConstant() || Operand.isType())
4879 LV.merge(computeTypeLinkageInfo(Operand.getResultType()));
4880 }
4881 return LV;
4882 }
4883 }
4884
4885 llvm_unreachable("unhandled type class");
4886}
4887
4888bool Type::isLinkageValid() const {
4889 if (!TypeBits.isCacheValid())
4890 return true;
4891
4892 Linkage L = LinkageComputer{}
4893 .computeTypeLinkageInfo(T: getCanonicalTypeInternal())
4894 .getLinkage();
4895 return L == TypeBits.getLinkage();
4896}
4897
4898LinkageInfo LinkageComputer::getTypeLinkageAndVisibility(const Type *T) {
4899 if (!T->isCanonicalUnqualified())
4900 return computeTypeLinkageInfo(T: T->getCanonicalTypeInternal());
4901
4902 LinkageInfo LV = computeTypeLinkageInfo(T);
4903 assert(LV.getLinkage() == T->getLinkage());
4904 return LV;
4905}
4906
4907LinkageInfo Type::getLinkageAndVisibility() const {
4908 return LinkageComputer{}.getTypeLinkageAndVisibility(T: this);
4909}
4910
4911std::optional<NullabilityKind> Type::getNullability() const {
4912 QualType Type(this, 0);
4913 while (const auto *AT = Type->getAs<AttributedType>()) {
4914 // Check whether this is an attributed type with nullability
4915 // information.
4916 if (auto Nullability = AT->getImmediateNullability())
4917 return Nullability;
4918
4919 Type = AT->getEquivalentType();
4920 }
4921 return std::nullopt;
4922}
4923
4924bool Type::canHaveNullability(bool ResultIfUnknown) const {
4925 QualType type = getCanonicalTypeInternal();
4926
4927 switch (type->getTypeClass()) {
4928#define NON_CANONICAL_TYPE(Class, Parent) \
4929 /* We'll only see canonical types here. */ \
4930 case Type::Class: \
4931 llvm_unreachable("non-canonical type");
4932#define TYPE(Class, Parent)
4933#include "clang/AST/TypeNodes.inc"
4934
4935 // Pointer types.
4936 case Type::Pointer:
4937 case Type::BlockPointer:
4938 case Type::MemberPointer:
4939 case Type::ObjCObjectPointer:
4940 return true;
4941
4942 // Dependent types that could instantiate to pointer types.
4943 case Type::UnresolvedUsing:
4944 case Type::TypeOfExpr:
4945 case Type::TypeOf:
4946 case Type::Decltype:
4947 case Type::PackIndexing:
4948 case Type::UnaryTransform:
4949 case Type::TemplateTypeParm:
4950 case Type::SubstTemplateTypeParmPack:
4951 case Type::DependentName:
4952 case Type::DependentTemplateSpecialization:
4953 case Type::Auto:
4954 return ResultIfUnknown;
4955
4956 // Dependent template specializations could instantiate to pointer types.
4957 case Type::TemplateSpecialization:
4958 // If it's a known class template, we can already check if it's nullable.
4959 if (TemplateDecl *templateDecl =
4960 cast<TemplateSpecializationType>(type.getTypePtr())
4961 ->getTemplateName()
4962 .getAsTemplateDecl())
4963 if (auto *CTD = dyn_cast<ClassTemplateDecl>(templateDecl))
4964 return llvm::any_of(
4965 CTD->redecls(), [](const RedeclarableTemplateDecl *RTD) {
4966 return RTD->getTemplatedDecl()->hasAttr<TypeNullableAttr>();
4967 });
4968 return ResultIfUnknown;
4969
4970 case Type::Builtin:
4971 switch (cast<BuiltinType>(type.getTypePtr())->getKind()) {
4972 // Signed, unsigned, and floating-point types cannot have nullability.
4973#define SIGNED_TYPE(Id, SingletonId) case BuiltinType::Id:
4974#define UNSIGNED_TYPE(Id, SingletonId) case BuiltinType::Id:
4975#define FLOATING_TYPE(Id, SingletonId) case BuiltinType::Id:
4976#define BUILTIN_TYPE(Id, SingletonId)
4977#include "clang/AST/BuiltinTypes.def"
4978 return false;
4979
4980 case BuiltinType::UnresolvedTemplate:
4981 // Dependent types that could instantiate to a pointer type.
4982 case BuiltinType::Dependent:
4983 case BuiltinType::Overload:
4984 case BuiltinType::BoundMember:
4985 case BuiltinType::PseudoObject:
4986 case BuiltinType::UnknownAny:
4987 case BuiltinType::ARCUnbridgedCast:
4988 return ResultIfUnknown;
4989
4990 case BuiltinType::Void:
4991 case BuiltinType::ObjCId:
4992 case BuiltinType::ObjCClass:
4993 case BuiltinType::ObjCSel:
4994#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
4995 case BuiltinType::Id:
4996#include "clang/Basic/OpenCLImageTypes.def"
4997#define EXT_OPAQUE_TYPE(ExtType, Id, Ext) case BuiltinType::Id:
4998#include "clang/Basic/OpenCLExtensionTypes.def"
4999 case BuiltinType::OCLSampler:
5000 case BuiltinType::OCLEvent:
5001 case BuiltinType::OCLClkEvent:
5002 case BuiltinType::OCLQueue:
5003 case BuiltinType::OCLReserveID:
5004#define SVE_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
5005#include "clang/Basic/AArch64ACLETypes.def"
5006#define PPC_VECTOR_TYPE(Name, Id, Size) case BuiltinType::Id:
5007#include "clang/Basic/PPCTypes.def"
5008#define RVV_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
5009#include "clang/Basic/RISCVVTypes.def"
5010#define WASM_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
5011#include "clang/Basic/WebAssemblyReferenceTypes.def"
5012#define AMDGPU_TYPE(Name, Id, SingletonId, Width, Align) case BuiltinType::Id:
5013#include "clang/Basic/AMDGPUTypes.def"
5014#define HLSL_INTANGIBLE_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
5015#include "clang/Basic/HLSLIntangibleTypes.def"
5016 case BuiltinType::BuiltinFn:
5017 case BuiltinType::NullPtr:
5018 case BuiltinType::IncompleteMatrixIdx:
5019 case BuiltinType::ArraySection:
5020 case BuiltinType::OMPArrayShaping:
5021 case BuiltinType::OMPIterator:
5022 return false;
5023 }
5024 llvm_unreachable("unknown builtin type");
5025
5026 case Type::Record: {
5027 const RecordDecl *RD = cast<RecordType>(type)->getDecl();
5028 // For template specializations, look only at primary template attributes.
5029 // This is a consistent regardless of whether the instantiation is known.
5030 if (const auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(RD))
5031 return llvm::any_of(
5032 CTSD->getSpecializedTemplate()->redecls(),
5033 [](const RedeclarableTemplateDecl *RTD) {
5034 return RTD->getTemplatedDecl()->hasAttr<TypeNullableAttr>();
5035 });
5036 return llvm::any_of(RD->redecls(), [](const TagDecl *RD) {
5037 return RD->hasAttr<TypeNullableAttr>();
5038 });
5039 }
5040
5041 // Non-pointer types.
5042 case Type::Complex:
5043 case Type::LValueReference:
5044 case Type::RValueReference:
5045 case Type::ConstantArray:
5046 case Type::IncompleteArray:
5047 case Type::VariableArray:
5048 case Type::DependentSizedArray:
5049 case Type::DependentVector:
5050 case Type::DependentSizedExtVector:
5051 case Type::Vector:
5052 case Type::ExtVector:
5053 case Type::ConstantMatrix:
5054 case Type::DependentSizedMatrix:
5055 case Type::DependentAddressSpace:
5056 case Type::FunctionProto:
5057 case Type::FunctionNoProto:
5058 case Type::DeducedTemplateSpecialization:
5059 case Type::Enum:
5060 case Type::InjectedClassName:
5061 case Type::PackExpansion:
5062 case Type::ObjCObject:
5063 case Type::ObjCInterface:
5064 case Type::Atomic:
5065 case Type::Pipe:
5066 case Type::BitInt:
5067 case Type::DependentBitInt:
5068 case Type::ArrayParameter:
5069 case Type::HLSLAttributedResource:
5070 case Type::HLSLInlineSpirv:
5071 return false;
5072 }
5073 llvm_unreachable("bad type kind!");
5074}
5075
5076std::optional<NullabilityKind> AttributedType::getImmediateNullability() const {
5077 if (getAttrKind() == attr::TypeNonNull)
5078 return NullabilityKind::NonNull;
5079 if (getAttrKind() == attr::TypeNullable)
5080 return NullabilityKind::Nullable;
5081 if (getAttrKind() == attr::TypeNullUnspecified)
5082 return NullabilityKind::Unspecified;
5083 if (getAttrKind() == attr::TypeNullableResult)
5084 return NullabilityKind::NullableResult;
5085 return std::nullopt;
5086}
5087
5088std::optional<NullabilityKind>
5089AttributedType::stripOuterNullability(QualType &T) {
5090 QualType AttrTy = T;
5091 if (auto MacroTy = dyn_cast<MacroQualifiedType>(Val&: T))
5092 AttrTy = MacroTy->getUnderlyingType();
5093
5094 if (auto attributed = dyn_cast<AttributedType>(Val&: AttrTy)) {
5095 if (auto nullability = attributed->getImmediateNullability()) {
5096 T = attributed->getModifiedType();
5097 return nullability;
5098 }
5099 }
5100
5101 return std::nullopt;
5102}
5103
5104bool Type::isSignableIntegerType(const ASTContext &Ctx) const {
5105 if (!isIntegralType(Ctx) || isEnumeralType())
5106 return false;
5107 return Ctx.getTypeSize(T: this) == Ctx.getTypeSize(Ctx.VoidPtrTy);
5108}
5109
5110bool Type::isBlockCompatibleObjCPointerType(ASTContext &ctx) const {
5111 const auto *objcPtr = getAs<ObjCObjectPointerType>();
5112 if (!objcPtr)
5113 return false;
5114
5115 if (objcPtr->isObjCIdType()) {
5116 // id is always okay.
5117 return true;
5118 }
5119
5120 // Blocks are NSObjects.
5121 if (ObjCInterfaceDecl *iface = objcPtr->getInterfaceDecl()) {
5122 if (iface->getIdentifier() != ctx.getNSObjectName())
5123 return false;
5124
5125 // Continue to check qualifiers, below.
5126 } else if (objcPtr->isObjCQualifiedIdType()) {
5127 // Continue to check qualifiers, below.
5128 } else {
5129 return false;
5130 }
5131
5132 // Check protocol qualifiers.
5133 for (ObjCProtocolDecl *proto : objcPtr->quals()) {
5134 // Blocks conform to NSObject and NSCopying.
5135 if (proto->getIdentifier() != ctx.getNSObjectName() &&
5136 proto->getIdentifier() != ctx.getNSCopyingName())
5137 return false;
5138 }
5139
5140 return true;
5141}
5142
5143Qualifiers::ObjCLifetime Type::getObjCARCImplicitLifetime() const {
5144 if (isObjCARCImplicitlyUnretainedType())
5145 return Qualifiers::OCL_ExplicitNone;
5146 return Qualifiers::OCL_Strong;
5147}
5148
5149bool Type::isObjCARCImplicitlyUnretainedType() const {
5150 assert(isObjCLifetimeType() &&
5151 "cannot query implicit lifetime for non-inferrable type");
5152
5153 const Type *canon = getCanonicalTypeInternal().getTypePtr();
5154
5155 // Walk down to the base type. We don't care about qualifiers for this.
5156 while (const auto *array = dyn_cast<ArrayType>(Val: canon))
5157 canon = array->getElementType().getTypePtr();
5158
5159 if (const auto *opt = dyn_cast<ObjCObjectPointerType>(Val: canon)) {
5160 // Class and Class<Protocol> don't require retention.
5161 if (opt->getObjectType()->isObjCClass())
5162 return true;
5163 }
5164
5165 return false;
5166}
5167
5168bool Type::isObjCNSObjectType() const {
5169 if (const auto *typedefType = getAs<TypedefType>())
5170 return typedefType->getDecl()->hasAttr<ObjCNSObjectAttr>();
5171 return false;
5172}
5173
5174bool Type::isObjCIndependentClassType() const {
5175 if (const auto *typedefType = getAs<TypedefType>())
5176 return typedefType->getDecl()->hasAttr<ObjCIndependentClassAttr>();
5177 return false;
5178}
5179
5180bool Type::isObjCRetainableType() const {
5181 return isObjCObjectPointerType() || isBlockPointerType() ||
5182 isObjCNSObjectType();
5183}
5184
5185bool Type::isObjCIndirectLifetimeType() const {
5186 if (isObjCLifetimeType())
5187 return true;
5188 if (const auto *OPT = getAs<PointerType>())
5189 return OPT->getPointeeType()->isObjCIndirectLifetimeType();
5190 if (const auto *Ref = getAs<ReferenceType>())
5191 return Ref->getPointeeType()->isObjCIndirectLifetimeType();
5192 if (const auto *MemPtr = getAs<MemberPointerType>())
5193 return MemPtr->getPointeeType()->isObjCIndirectLifetimeType();
5194 return false;
5195}
5196
5197/// Returns true if objects of this type have lifetime semantics under
5198/// ARC.
5199bool Type::isObjCLifetimeType() const {
5200 const Type *type = this;
5201 while (const ArrayType *array = type->getAsArrayTypeUnsafe())
5202 type = array->getElementType().getTypePtr();
5203 return type->isObjCRetainableType();
5204}
5205
5206/// Determine whether the given type T is a "bridgable" Objective-C type,
5207/// which is either an Objective-C object pointer type or an
5208bool Type::isObjCARCBridgableType() const {
5209 return isObjCObjectPointerType() || isBlockPointerType();
5210}
5211
5212/// Determine whether the given type T is a "bridgeable" C type.
5213bool Type::isCARCBridgableType() const {
5214 const auto *Pointer = getAs<PointerType>();
5215 if (!Pointer)
5216 return false;
5217
5218 QualType Pointee = Pointer->getPointeeType();
5219 return Pointee->isVoidType() || Pointee->isRecordType();
5220}
5221
5222/// Check if the specified type is the CUDA device builtin surface type.
5223bool Type::isCUDADeviceBuiltinSurfaceType() const {
5224 if (const auto *RT = getAs<RecordType>())
5225 return RT->getDecl()->hasAttr<CUDADeviceBuiltinSurfaceTypeAttr>();
5226 return false;
5227}
5228
5229/// Check if the specified type is the CUDA device builtin texture type.
5230bool Type::isCUDADeviceBuiltinTextureType() const {
5231 if (const auto *RT = getAs<RecordType>())
5232 return RT->getDecl()->hasAttr<CUDADeviceBuiltinTextureTypeAttr>();
5233 return false;
5234}
5235
5236bool Type::hasSizedVLAType() const {
5237 if (!isVariablyModifiedType())
5238 return false;
5239
5240 if (const auto *ptr = getAs<PointerType>())
5241 return ptr->getPointeeType()->hasSizedVLAType();
5242 if (const auto *ref = getAs<ReferenceType>())
5243 return ref->getPointeeType()->hasSizedVLAType();
5244 if (const ArrayType *arr = getAsArrayTypeUnsafe()) {
5245 if (isa<VariableArrayType>(Val: arr) &&
5246 cast<VariableArrayType>(Val: arr)->getSizeExpr())
5247 return true;
5248
5249 return arr->getElementType()->hasSizedVLAType();
5250 }
5251
5252 return false;
5253}
5254
5255bool Type::isHLSLResourceRecord() const {
5256 return HLSLAttributedResourceType::findHandleTypeOnResource(RT: this) != nullptr;
5257}
5258
5259bool Type::isHLSLIntangibleType() const {
5260 const Type *Ty = getUnqualifiedDesugaredType();
5261
5262 // check if it's a builtin type first
5263 if (Ty->isBuiltinType())
5264 return Ty->isHLSLBuiltinIntangibleType();
5265
5266 // unwrap arrays
5267 while (isa<ConstantArrayType>(Val: Ty))
5268 Ty = Ty->getArrayElementTypeNoTypeQual();
5269
5270 const RecordType *RT =
5271 dyn_cast<RecordType>(Val: Ty->getUnqualifiedDesugaredType());
5272 if (!RT)
5273 return false;
5274
5275 CXXRecordDecl *RD = RT->getAsCXXRecordDecl();
5276 assert(RD != nullptr &&
5277 "all HLSL structs and classes should be CXXRecordDecl");
5278 assert(RD->isCompleteDefinition() && "expecting complete type");
5279 return RD->isHLSLIntangible();
5280}
5281
5282QualType::DestructionKind QualType::isDestructedTypeImpl(QualType type) {
5283 switch (type.getObjCLifetime()) {
5284 case Qualifiers::OCL_None:
5285 case Qualifiers::OCL_ExplicitNone:
5286 case Qualifiers::OCL_Autoreleasing:
5287 break;
5288
5289 case Qualifiers::OCL_Strong:
5290 return DK_objc_strong_lifetime;
5291 case Qualifiers::OCL_Weak:
5292 return DK_objc_weak_lifetime;
5293 }
5294
5295 if (const auto *RT = type->getBaseElementTypeUnsafe()->getAs<RecordType>()) {
5296 const RecordDecl *RD = RT->getDecl();
5297 if (const auto *CXXRD = dyn_cast<CXXRecordDecl>(Val: RD)) {
5298 /// Check if this is a C++ object with a non-trivial destructor.
5299 if (CXXRD->hasDefinition() && !CXXRD->hasTrivialDestructor())
5300 return DK_cxx_destructor;
5301 } else {
5302 /// Check if this is a C struct that is non-trivial to destroy or an array
5303 /// that contains such a struct.
5304 if (RD->isNonTrivialToPrimitiveDestroy())
5305 return DK_nontrivial_c_struct;
5306 }
5307 }
5308
5309 return DK_none;
5310}
5311
5312bool MemberPointerType::isSugared() const {
5313 CXXRecordDecl *D1 = getMostRecentCXXRecordDecl(),
5314 *D2 = getQualifier()->getAsRecordDecl();
5315 assert(!D1 == !D2);
5316 return D1 != D2 && D1->getCanonicalDecl() != D2->getCanonicalDecl();
5317}
5318
5319void MemberPointerType::Profile(llvm::FoldingSetNodeID &ID, QualType Pointee,
5320 const NestedNameSpecifier *Qualifier,
5321 const CXXRecordDecl *Cls) {
5322 ID.AddPointer(Ptr: Pointee.getAsOpaquePtr());
5323 ID.AddPointer(Ptr: Qualifier);
5324 if (Cls)
5325 ID.AddPointer(Ptr: Cls->getCanonicalDecl());
5326}
5327
5328CXXRecordDecl *MemberPointerType::getCXXRecordDecl() const {
5329 return dyn_cast<MemberPointerType>(getCanonicalTypeInternal())
5330 ->getQualifier()
5331 ->getAsRecordDecl();
5332}
5333
5334CXXRecordDecl *MemberPointerType::getMostRecentCXXRecordDecl() const {
5335 auto *RD = getCXXRecordDecl();
5336 if (!RD)
5337 return nullptr;
5338 return RD->getMostRecentNonInjectedDecl();
5339}
5340
5341void clang::FixedPointValueToString(SmallVectorImpl<char> &Str,
5342 llvm::APSInt Val, unsigned Scale) {
5343 llvm::FixedPointSemantics FXSema(Val.getBitWidth(), Scale, Val.isSigned(),
5344 /*IsSaturated=*/false,
5345 /*HasUnsignedPadding=*/false);
5346 llvm::APFixedPoint(Val, FXSema).toString(Str);
5347}
5348
5349AutoType::AutoType(QualType DeducedAsType, AutoTypeKeyword Keyword,
5350 TypeDependence ExtraDependence, QualType Canon,
5351 ConceptDecl *TypeConstraintConcept,
5352 ArrayRef<TemplateArgument> TypeConstraintArgs)
5353 : DeducedType(Auto, DeducedAsType, ExtraDependence, Canon) {
5354 AutoTypeBits.Keyword = llvm::to_underlying(E: Keyword);
5355 AutoTypeBits.NumArgs = TypeConstraintArgs.size();
5356 this->TypeConstraintConcept = TypeConstraintConcept;
5357 assert(TypeConstraintConcept || AutoTypeBits.NumArgs == 0);
5358 if (TypeConstraintConcept) {
5359 auto *ArgBuffer =
5360 const_cast<TemplateArgument *>(getTypeConstraintArguments().data());
5361 for (const TemplateArgument &Arg : TypeConstraintArgs) {
5362 // We only syntactically depend on the constraint arguments. They don't
5363 // affect the deduced type, only its validity.
5364 addDependence(
5365 toSyntacticDependence(D: toTypeDependence(D: Arg.getDependence())));
5366
5367 new (ArgBuffer++) TemplateArgument(Arg);
5368 }
5369 }
5370}
5371
5372void AutoType::Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context,
5373 QualType Deduced, AutoTypeKeyword Keyword,
5374 bool IsDependent, ConceptDecl *CD,
5375 ArrayRef<TemplateArgument> Arguments) {
5376 ID.AddPointer(Ptr: Deduced.getAsOpaquePtr());
5377 ID.AddInteger(I: (unsigned)Keyword);
5378 ID.AddBoolean(B: IsDependent);
5379 ID.AddPointer(Ptr: CD);
5380 for (const TemplateArgument &Arg : Arguments)
5381 Arg.Profile(ID, Context);
5382}
5383
5384void AutoType::Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context) {
5385 Profile(ID, Context, getDeducedType(), getKeyword(), isDependentType(),
5386 getTypeConstraintConcept(), getTypeConstraintArguments());
5387}
5388
5389FunctionEffect::Kind FunctionEffect::oppositeKind() const {
5390 switch (kind()) {
5391 case Kind::NonBlocking:
5392 return Kind::Blocking;
5393 case Kind::Blocking:
5394 return Kind::NonBlocking;
5395 case Kind::NonAllocating:
5396 return Kind::Allocating;
5397 case Kind::Allocating:
5398 return Kind::NonAllocating;
5399 }
5400 llvm_unreachable("unknown effect kind");
5401}
5402
5403StringRef FunctionEffect::name() const {
5404 switch (kind()) {
5405 case Kind::NonBlocking:
5406 return "nonblocking";
5407 case Kind::NonAllocating:
5408 return "nonallocating";
5409 case Kind::Blocking:
5410 return "blocking";
5411 case Kind::Allocating:
5412 return "allocating";
5413 }
5414 llvm_unreachable("unknown effect kind");
5415}
5416
5417std::optional<FunctionEffect> FunctionEffect::effectProhibitingInference(
5418 const Decl &Callee, FunctionEffectKindSet CalleeFX) const {
5419 switch (kind()) {
5420 case Kind::NonAllocating:
5421 case Kind::NonBlocking: {
5422 for (FunctionEffect Effect : CalleeFX) {
5423 // nonblocking/nonallocating cannot call allocating.
5424 if (Effect.kind() == Kind::Allocating)
5425 return Effect;
5426 // nonblocking cannot call blocking.
5427 if (kind() == Kind::NonBlocking && Effect.kind() == Kind::Blocking)
5428 return Effect;
5429 }
5430 return std::nullopt;
5431 }
5432
5433 case Kind::Allocating:
5434 case Kind::Blocking:
5435 assert(0 && "effectProhibitingInference with non-inferable effect kind");
5436 break;
5437 }
5438 llvm_unreachable("unknown effect kind");
5439}
5440
5441bool FunctionEffect::shouldDiagnoseFunctionCall(
5442 bool Direct, FunctionEffectKindSet CalleeFX) const {
5443 switch (kind()) {
5444 case Kind::NonAllocating:
5445 case Kind::NonBlocking: {
5446 const Kind CallerKind = kind();
5447 for (FunctionEffect Effect : CalleeFX) {
5448 const Kind EK = Effect.kind();
5449 // Does callee have same or stronger constraint?
5450 if (EK == CallerKind ||
5451 (CallerKind == Kind::NonAllocating && EK == Kind::NonBlocking)) {
5452 return false; // no diagnostic
5453 }
5454 }
5455 return true; // warning
5456 }
5457 case Kind::Allocating:
5458 case Kind::Blocking:
5459 return false;
5460 }
5461 llvm_unreachable("unknown effect kind");
5462}
5463
5464// =====
5465
5466bool FunctionEffectSet::insert(const FunctionEffectWithCondition &NewEC,
5467 Conflicts &Errs) {
5468 FunctionEffect::Kind NewOppositeKind = NewEC.Effect.oppositeKind();
5469 Expr *NewCondition = NewEC.Cond.getCondition();
5470
5471 // The index at which insertion will take place; default is at end
5472 // but we might find an earlier insertion point.
5473 unsigned InsertIdx = Effects.size();
5474 unsigned Idx = 0;
5475 for (const FunctionEffectWithCondition &EC : *this) {
5476 // Note about effects with conditions: They are considered distinct from
5477 // those without conditions; they are potentially unique, redundant, or
5478 // in conflict, but we can't tell which until the condition is evaluated.
5479 if (EC.Cond.getCondition() == nullptr && NewCondition == nullptr) {
5480 if (EC.Effect.kind() == NewEC.Effect.kind()) {
5481 // There is no condition, and the effect kind is already present,
5482 // so just fail to insert the new one (creating a duplicate),
5483 // and return success.
5484 return true;
5485 }
5486
5487 if (EC.Effect.kind() == NewOppositeKind) {
5488 Errs.push_back({EC, NewEC});
5489 return false;
5490 }
5491 }
5492
5493 if (NewEC.Effect.kind() < EC.Effect.kind() && InsertIdx > Idx)
5494 InsertIdx = Idx;
5495
5496 ++Idx;
5497 }
5498
5499 if (NewCondition || !Conditions.empty()) {
5500 if (Conditions.empty() && !Effects.empty())
5501 Conditions.resize(Effects.size());
5502 Conditions.insert(Conditions.begin() + InsertIdx,
5503 NewEC.Cond.getCondition());
5504 }
5505 Effects.insert(Effects.begin() + InsertIdx, NewEC.Effect);
5506 return true;
5507}
5508
5509bool FunctionEffectSet::insert(const FunctionEffectsRef &Set, Conflicts &Errs) {
5510 for (const auto &Item : Set)
5511 insert(Item, Errs);
5512 return Errs.empty();
5513}
5514
5515FunctionEffectSet FunctionEffectSet::getIntersection(FunctionEffectsRef LHS,
5516 FunctionEffectsRef RHS) {
5517 FunctionEffectSet Result;
5518 FunctionEffectSet::Conflicts Errs;
5519
5520 // We could use std::set_intersection but that would require expanding the
5521 // container interface to include push_back, making it available to clients
5522 // who might fail to maintain invariants.
5523 auto IterA = LHS.begin(), EndA = LHS.end();
5524 auto IterB = RHS.begin(), EndB = RHS.end();
5525
5526 auto FEWCLess = [](const FunctionEffectWithCondition &LHS,
5527 const FunctionEffectWithCondition &RHS) {
5528 return std::tuple(LHS.Effect, uintptr_t(LHS.Cond.getCondition())) <
5529 std::tuple(RHS.Effect, uintptr_t(RHS.Cond.getCondition()));
5530 };
5531
5532 while (IterA != EndA && IterB != EndB) {
5533 FunctionEffectWithCondition A = *IterA;
5534 FunctionEffectWithCondition B = *IterB;
5535 if (FEWCLess(A, B))
5536 ++IterA;
5537 else if (FEWCLess(B, A))
5538 ++IterB;
5539 else {
5540 Result.insert(A, Errs);
5541 ++IterA;
5542 ++IterB;
5543 }
5544 }
5545
5546 // Insertion shouldn't be able to fail; that would mean both input
5547 // sets contained conflicts.
5548 assert(Errs.empty() && "conflict shouldn't be possible in getIntersection");
5549
5550 return Result;
5551}
5552
5553FunctionEffectSet FunctionEffectSet::getUnion(FunctionEffectsRef LHS,
5554 FunctionEffectsRef RHS,
5555 Conflicts &Errs) {
5556 // Optimize for either of the two sets being empty (very common).
5557 if (LHS.empty())
5558 return FunctionEffectSet(RHS);
5559
5560 FunctionEffectSet Combined(LHS);
5561 Combined.insert(RHS, Errs);
5562 return Combined;
5563}
5564
5565namespace clang {
5566
5567raw_ostream &operator<<(raw_ostream &OS,
5568 const FunctionEffectWithCondition &CFE) {
5569 OS << CFE.Effect.name();
5570 if (Expr *E = CFE.Cond.getCondition()) {
5571 OS << '(';
5572 E->dump();
5573 OS << ')';
5574 }
5575 return OS;
5576}
5577
5578} // namespace clang
5579
5580LLVM_DUMP_METHOD void FunctionEffectsRef::dump(llvm::raw_ostream &OS) const {
5581 OS << "Effects{";
5582 llvm::interleaveComma(c: *this, os&: OS);
5583 OS << "}";
5584}
5585
5586LLVM_DUMP_METHOD void FunctionEffectSet::dump(llvm::raw_ostream &OS) const {
5587 FunctionEffectsRef(*this).dump(OS);
5588}
5589
5590LLVM_DUMP_METHOD void FunctionEffectKindSet::dump(llvm::raw_ostream &OS) const {
5591 OS << "Effects{";
5592 llvm::interleaveComma(c: *this, os&: OS);
5593 OS << "}";
5594}
5595
5596FunctionEffectsRef
5597FunctionEffectsRef::create(ArrayRef<FunctionEffect> FX,
5598 ArrayRef<EffectConditionExpr> Conds) {
5599 assert(llvm::is_sorted(FX) && "effects should be sorted");
5600 assert((Conds.empty() || Conds.size() == FX.size()) &&
5601 "effects size should match conditions size");
5602 return FunctionEffectsRef(FX, Conds);
5603}
5604
5605std::string FunctionEffectWithCondition::description() const {
5606 std::string Result(Effect.name().str());
5607 if (Cond.getCondition() != nullptr)
5608 Result += "(expr)";
5609 return Result;
5610}
5611
5612const HLSLAttributedResourceType *
5613HLSLAttributedResourceType::findHandleTypeOnResource(const Type *RT) {
5614 // If the type RT is an HLSL resource class, the first field must
5615 // be the resource handle of type HLSLAttributedResourceType
5616 const clang::Type *Ty = RT->getUnqualifiedDesugaredType();
5617 if (const RecordDecl *RD = Ty->getAsCXXRecordDecl()) {
5618 if (!RD->fields().empty()) {
5619 const auto &FirstFD = RD->fields().begin();
5620 return dyn_cast<HLSLAttributedResourceType>(
5621 FirstFD->getType().getTypePtr());
5622 }
5623 }
5624 return nullptr;
5625}
5626

Provided by KDAB

Privacy Policy
Update your C++ knowledge – Modern C++11/14/17 Training
Find out more

source code of clang/lib/AST/Type.cpp