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