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