[clang][modules] Don't prevent translation of FW_Private includes when explicitly...
[llvm-project.git] / clang / lib / AST / Type.cpp
blob98a4f12c4f574fa2186cfac5beaa07b4d13a3ab4
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.
11 //===----------------------------------------------------------------------===//
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>
58 using namespace clang;
60 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()));
75 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();
90 if (ND)
91 return ND->getIdentifier();
92 return nullptr;
95 bool QualType::mayBeDynamicClass() const {
96 const auto *ClassDecl = getTypePtr()->getPointeeCXXRecordDecl();
97 return ClassDecl && ClassDecl->mayBeDynamicClass();
100 bool QualType::mayBeNotDynamicClass() const {
101 const auto *ClassDecl = getTypePtr()->getPointeeCXXRecordDecl();
102 return !ClassDecl || ClassDecl->mayBeNonDynamicClass();
105 bool QualType::isConstant(QualType T, const ASTContext &Ctx) {
106 if (T.isConstQualified())
107 return true;
109 if (const ArrayType *AT = Ctx.getAsArrayType(T))
110 return AT->getElementType().isConstant(Ctx);
112 return T.getAddressSpace() == LangAS::opencl_constant;
115 std::optional<QualType::NonConstantStorageReason>
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;
131 return std::nullopt;
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,
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:
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);
162 unsigned ConstantArrayType::getNumAddressingBits(const ASTContext &Context,
163 QualType ElementType,
164 const llvm::APInt &NumElements) {
165 uint64_t ElementSize = Context.getTypeSizeInChars(ElementType).getQuantity();
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.
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);
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);
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);
191 llvm::APSInt TotalSize(llvm::APInt(SizeExtended.getBitWidth(), ElementSize));
192 TotalSize *= SizeExtended;
194 return TotalSize.getActiveBits();
197 unsigned
198 ConstantArrayType::getNumAddressingBits(const ASTContext &Context) const {
199 return getNumAddressingBits(Context, getElementType(), getSize());
202 unsigned ConstantArrayType::getMaxSizeBits(const ASTContext &Context) {
203 unsigned Bits = Context.getTypeSize(Context.getSizeType());
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;
211 return Bits;
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);
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) {}
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);
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);
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);
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) {}
279 void
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);
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) {}
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);
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) {}
324 ConstantMatrixType::ConstantMatrixType(QualType matrixType, unsigned nRows,
325 unsigned nColumns, QualType canonType)
326 : ConstantMatrixType(ConstantMatrix, matrixType, nRows, nColumns,
327 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) {}
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) {}
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);
353 VectorType::VectorType(QualType vecType, unsigned nElements, QualType canonType,
354 VectorKind vecKind)
355 : VectorType(Vector, vecType, nElements, canonType, 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;
364 BitIntType::BitIntType(bool IsUnsigned, unsigned NumBits)
365 : Type(BitInt, QualType{}, TypeDependence::None), IsUnsigned(IsUnsigned),
366 NumBits(NumBits) {}
368 DependentBitIntType::DependentBitIntType(bool IsUnsigned, Expr *NumBitsExpr)
369 : Type(DependentBitInt, QualType{},
370 toTypeDependence(NumBitsExpr->getDependence())),
371 ExprAndUnsigned(NumBitsExpr, IsUnsigned) {}
373 bool DependentBitIntType::isUnsigned() const {
374 return ExprAndUnsigned.getInt();
377 clang::Expr *DependentBitIntType::getNumBitsExpr() const {
378 return ExprAndUnsigned.getPointer();
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);
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.
391 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();
396 // If the canonical form of this type isn't the right kind, reject it.
397 if (!isa<ArrayType>(CanonicalType))
398 return nullptr;
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();
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.
412 QualType QualType::getDesugaredType(QualType T, const ASTContext &Context) {
413 SplitQualType split = getSplitDesugaredType(T);
414 return Context.getQualifiedType(split.Ty, split.Quals);
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);
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"
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.
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"
444 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(); \
453 #include "clang/AST/TypeNodes.inc"
455 llvm_unreachable("bad type kind!");
458 SplitQualType QualType::getSplitDesugaredType(QualType T) {
459 QualifierCollector Qs;
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; \
474 #include "clang/AST/TypeNodes.inc"
479 SplitQualType QualType::getSplitUnqualifiedTypeImpl(QualType type) {
480 SplitQualType split = type.split();
482 // All the qualifiers we've seen so far.
483 Qualifiers quals = split.Quals;
485 // The last type node we saw with any nodes inside it.
486 const Type *lastTypeWithQuals = split.Ty;
488 while (true) {
489 QualType next;
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; \
502 #include "clang/AST/TypeNodes.inc"
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);
514 done:
515 return SplitQualType(lastTypeWithQuals, quals);
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;
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.
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; \
541 #include "clang/AST/TypeNodes.inc"
546 template <> const TypedefType *Type::getAs() const {
547 return getAsSugar<TypedefType>(this);
550 template <> const UsingType *Type::getAs() const {
551 return getAsSugar<UsingType>(this);
554 template <> const TemplateSpecializationType *Type::getAs() const {
555 return getAsSugar<TemplateSpecializationType>(this);
558 template <> const AttributedType *Type::getAs() const {
559 return getAsSugar<AttributedType>(this);
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.
565 const Type *Type::getUnqualifiedDesugaredType() const {
566 const Type *Cur = this;
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; \
578 #include "clang/AST/TypeNodes.inc"
583 bool Type::isClassType() const {
584 if (const auto *RT = getAs<RecordType>())
585 return RT->getDecl()->isClass();
586 return false;
589 bool Type::isStructureType() const {
590 if (const auto *RT = getAs<RecordType>())
591 return RT->getDecl()->isStruct();
592 return false;
595 bool Type::isObjCBoxableRecordType() const {
596 if (const auto *RT = getAs<RecordType>())
597 return RT->getDecl()->hasAttr<ObjCBoxableAttr>();
598 return false;
601 bool Type::isInterfaceType() const {
602 if (const auto *RT = getAs<RecordType>())
603 return RT->getDecl()->isInterface();
604 return false;
607 bool Type::isStructureOrClassType() const {
608 if (const auto *RT = getAs<RecordType>()) {
609 RecordDecl *RD = RT->getDecl();
610 return RD->isStruct() || RD->isClass() || RD->isInterface();
612 return false;
615 bool Type::isVoidPointerType() const {
616 if (const auto *PT = getAs<PointerType>())
617 return PT->getPointeeType()->isVoidType();
618 return false;
621 bool Type::isUnionType() const {
622 if (const auto *RT = getAs<RecordType>())
623 return RT->getDecl()->isUnion();
624 return false;
627 bool Type::isComplexType() const {
628 if (const auto *CT = dyn_cast<ComplexType>(CanonicalType))
629 return CT->getElementType()->isFloatingType();
630 return false;
633 bool Type::isComplexIntegerType() const {
634 // Check for GCC complex integer extension.
635 return getAsComplexIntegerType();
638 bool Type::isScopedEnumeralType() const {
639 if (const auto *ET = getAs<EnumType>())
640 return ET->getDecl()->isScoped();
641 return false;
644 const ComplexType *Type::getAsComplexIntegerType() const {
645 if (const auto *Complex = getAs<ComplexType>())
646 if (Complex->getElementType()->isIntegerType())
647 return Complex;
648 return nullptr;
651 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 {};
667 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;
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;
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());
683 return nullptr;
686 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;
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;
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());
703 return nullptr;
706 bool Type::isObjCIdOrObjectKindOfType(const ASTContext &ctx,
707 const ObjCObjectType *&bound) const {
708 bound = nullptr;
710 const auto *OPT = getAs<ObjCObjectPointerType>();
711 if (!OPT)
712 return false;
714 // Easy case: id.
715 if (OPT->isObjCIdType())
716 return true;
718 // If it's not a __kindof type, reject it now.
719 if (!OPT->isKindOfType())
720 return false;
722 // If it's Class or qualified Class, it's not an object type.
723 if (OPT->isObjCClassType() || OPT->isObjCQualifiedClassType())
724 return false;
726 // Figure out the type bound for the __kindof type.
727 bound = OPT->getObjectType()->stripObjCKindOfTypeAndQuals(ctx)
728 ->getAs<ObjCObjectType>();
729 return true;
732 bool Type::isObjCClassOrClassKindOfType() const {
733 const auto *OPT = getAs<ObjCObjectPointerType>();
734 if (!OPT)
735 return false;
737 // Easy case: Class.
738 if (OPT->isObjCClassType())
739 return true;
741 // If it's not a __kindof type, reject it now.
742 if (!OPT->isKindOfType())
743 return false;
745 // If it's Class or qualified Class, it's a class __kindof type.
746 return OPT->isObjCClassType() || OPT->isObjCQualifiedClassType();
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);
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;
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));
770 for (auto typeArg : typeArgs) {
771 addDependence(typeArg->getDependence() & ~TypeDependence::VariablyModified);
773 // Initialize the protocol qualifiers. The protocol storage is known
774 // after we set number of type arguments.
775 initialize(protocols);
778 bool ObjCObjectType::isSpecialized() const {
779 // If we have type arguments written here, the type is specialized.
780 if (ObjCObjectTypeBits.NumTypeArgs > 0)
781 return true;
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;
789 return objcObject->isSpecialized();
792 // Not specialized.
793 return false;
796 ArrayRef<QualType> ObjCObjectType::getTypeArgs() const {
797 // We have type arguments written on this type.
798 if (isSpecializedAsWritten())
799 return getTypeArgsAsWritten();
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 {};
807 return objcObject->getTypeArgs();
810 // No type arguments.
811 return {};
814 bool ObjCObjectType::isKindOfType() const {
815 if (isKindOfTypeAsWritten())
816 return true;
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;
824 return objcObject->isKindOfType();
827 // Not a "__kindof" type.
828 return false;
831 QualType ObjCObjectType::stripObjCKindOfTypeAndQuals(
832 const ASTContext &ctx) const {
833 if (!isKindOfType() && qual_empty())
834 return QualType(this, 0);
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);
842 return ctx.getObjCObjectType(ctx.getQualifiedType(baseType,
843 splitBaseType.Quals),
844 getTypeArgsAsWritten(),
845 /*protocols=*/{},
846 /*isKindOf=*/false);
849 ObjCInterfaceDecl *ObjCInterfaceType::getDecl() const {
850 ObjCInterfaceDecl *Canon = Decl->getCanonicalDecl();
851 if (ObjCInterfaceDecl *Def = Canon->getDefinition())
852 return Def;
853 return Canon;
856 const ObjCObjectPointerType *ObjCObjectPointerType::stripObjCKindOfTypeAndQuals(
857 const ASTContext &ctx) const {
858 if (!isKindOfType() && qual_empty())
859 return this;
861 QualType obj = getObjectType()->stripObjCKindOfTypeAndQuals(ctx);
862 return ctx.getObjCObjectPointerType(obj)->castAs<ObjCObjectPointerType>();
865 namespace {
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;
873 QualType recurse(QualType type) {
874 // Split out the qualifiers from the type.
875 SplitQualType splitType = type.split();
877 // Visit the type itself.
878 QualType result = static_cast<Derived *>(this)->Visit(splitType.Ty);
879 if (result.isNull())
880 return result;
882 // Reconstruct the transformed type by applying the local qualifiers
883 // from the split type.
884 return Ctx.getQualifiedType(result, splitType.Quals);
887 public:
888 explicit SimpleTransformVisitor(ASTContext &ctx) : Ctx(ctx) {}
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"
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; \
911 TRIVIAL_TYPE_CLASS(Builtin)
913 QualType VisitComplexType(const ComplexType *T) {
914 QualType elementType = recurse(T->getElementType());
915 if (elementType.isNull())
916 return {};
918 if (elementType.getAsOpaquePtr() == T->getElementType().getAsOpaquePtr())
919 return QualType(T, 0);
921 return Ctx.getComplexType(elementType);
924 QualType VisitPointerType(const PointerType *T) {
925 QualType pointeeType = recurse(T->getPointeeType());
926 if (pointeeType.isNull())
927 return {};
929 if (pointeeType.getAsOpaquePtr() == T->getPointeeType().getAsOpaquePtr())
930 return QualType(T, 0);
932 return Ctx.getPointerType(pointeeType);
935 QualType VisitBlockPointerType(const BlockPointerType *T) {
936 QualType pointeeType = recurse(T->getPointeeType());
937 if (pointeeType.isNull())
938 return {};
940 if (pointeeType.getAsOpaquePtr() == T->getPointeeType().getAsOpaquePtr())
941 return QualType(T, 0);
943 return Ctx.getBlockPointerType(pointeeType);
946 QualType VisitLValueReferenceType(const LValueReferenceType *T) {
947 QualType pointeeType = recurse(T->getPointeeTypeAsWritten());
948 if (pointeeType.isNull())
949 return {};
951 if (pointeeType.getAsOpaquePtr()
952 == T->getPointeeTypeAsWritten().getAsOpaquePtr())
953 return QualType(T, 0);
955 return Ctx.getLValueReferenceType(pointeeType, T->isSpelledAsLValue());
958 QualType VisitRValueReferenceType(const RValueReferenceType *T) {
959 QualType pointeeType = recurse(T->getPointeeTypeAsWritten());
960 if (pointeeType.isNull())
961 return {};
963 if (pointeeType.getAsOpaquePtr()
964 == T->getPointeeTypeAsWritten().getAsOpaquePtr())
965 return QualType(T, 0);
967 return Ctx.getRValueReferenceType(pointeeType);
970 QualType VisitMemberPointerType(const MemberPointerType *T) {
971 QualType pointeeType = recurse(T->getPointeeType());
972 if (pointeeType.isNull())
973 return {};
975 if (pointeeType.getAsOpaquePtr() == T->getPointeeType().getAsOpaquePtr())
976 return QualType(T, 0);
978 return Ctx.getMemberPointerType(pointeeType, T->getClass());
981 QualType VisitConstantArrayType(const ConstantArrayType *T) {
982 QualType elementType = recurse(T->getElementType());
983 if (elementType.isNull())
984 return {};
986 if (elementType.getAsOpaquePtr() == T->getElementType().getAsOpaquePtr())
987 return QualType(T, 0);
989 return Ctx.getConstantArrayType(elementType, T->getSize(), T->getSizeExpr(),
990 T->getSizeModifier(),
991 T->getIndexTypeCVRQualifiers());
994 QualType VisitVariableArrayType(const VariableArrayType *T) {
995 QualType elementType = recurse(T->getElementType());
996 if (elementType.isNull())
997 return {};
999 if (elementType.getAsOpaquePtr() == T->getElementType().getAsOpaquePtr())
1000 return QualType(T, 0);
1002 return Ctx.getVariableArrayType(elementType, T->getSizeExpr(),
1003 T->getSizeModifier(),
1004 T->getIndexTypeCVRQualifiers(),
1005 T->getBracketsRange());
1008 QualType VisitIncompleteArrayType(const IncompleteArrayType *T) {
1009 QualType elementType = recurse(T->getElementType());
1010 if (elementType.isNull())
1011 return {};
1013 if (elementType.getAsOpaquePtr() == T->getElementType().getAsOpaquePtr())
1014 return QualType(T, 0);
1016 return Ctx.getIncompleteArrayType(elementType, T->getSizeModifier(),
1017 T->getIndexTypeCVRQualifiers());
1020 QualType VisitVectorType(const VectorType *T) {
1021 QualType elementType = recurse(T->getElementType());
1022 if (elementType.isNull())
1023 return {};
1025 if (elementType.getAsOpaquePtr() == T->getElementType().getAsOpaquePtr())
1026 return QualType(T, 0);
1028 return Ctx.getVectorType(elementType, T->getNumElements(),
1029 T->getVectorKind());
1032 QualType VisitExtVectorType(const ExtVectorType *T) {
1033 QualType elementType = recurse(T->getElementType());
1034 if (elementType.isNull())
1035 return {};
1037 if (elementType.getAsOpaquePtr() == T->getElementType().getAsOpaquePtr())
1038 return QualType(T, 0);
1040 return Ctx.getExtVectorType(elementType, T->getNumElements());
1043 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);
1050 return Ctx.getConstantMatrixType(elementType, T->getNumRows(),
1051 T->getNumColumns());
1054 QualType VisitFunctionNoProtoType(const FunctionNoProtoType *T) {
1055 QualType returnType = recurse(T->getReturnType());
1056 if (returnType.isNull())
1057 return {};
1059 if (returnType.getAsOpaquePtr() == T->getReturnType().getAsOpaquePtr())
1060 return QualType(T, 0);
1062 return Ctx.getFunctionNoProtoType(returnType, T->getExtInfo());
1065 QualType VisitFunctionProtoType(const FunctionProtoType *T) {
1066 QualType returnType = recurse(T->getReturnType());
1067 if (returnType.isNull())
1068 return {};
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 {};
1078 if (newParamType.getAsOpaquePtr() != paramType.getAsOpaquePtr())
1079 paramChanged = true;
1081 paramTypes.push_back(newParamType);
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 {};
1094 if (newExceptionType.getAsOpaquePtr() != exceptionType.getAsOpaquePtr())
1095 exceptionChanged = true;
1097 exceptionTypes.push_back(newExceptionType);
1100 if (exceptionChanged) {
1101 info.ExceptionSpec.Exceptions =
1102 llvm::ArrayRef(exceptionTypes).copy(Ctx);
1106 if (returnType.getAsOpaquePtr() == T->getReturnType().getAsOpaquePtr() &&
1107 !paramChanged && !exceptionChanged)
1108 return QualType(T, 0);
1110 return Ctx.getFunctionType(returnType, paramTypes, info);
1113 QualType VisitParenType(const ParenType *T) {
1114 QualType innerType = recurse(T->getInnerType());
1115 if (innerType.isNull())
1116 return {};
1118 if (innerType.getAsOpaquePtr() == T->getInnerType().getAsOpaquePtr())
1119 return QualType(T, 0);
1121 return Ctx.getParenType(innerType);
1124 SUGARED_TYPE_CLASS(Typedef)
1125 SUGARED_TYPE_CLASS(ObjCTypeParam)
1126 SUGARED_TYPE_CLASS(MacroQualified)
1128 QualType VisitAdjustedType(const AdjustedType *T) {
1129 QualType originalType = recurse(T->getOriginalType());
1130 if (originalType.isNull())
1131 return {};
1133 QualType adjustedType = recurse(T->getAdjustedType());
1134 if (adjustedType.isNull())
1135 return {};
1137 if (originalType.getAsOpaquePtr()
1138 == T->getOriginalType().getAsOpaquePtr() &&
1139 adjustedType.getAsOpaquePtr() == T->getAdjustedType().getAsOpaquePtr())
1140 return QualType(T, 0);
1142 return Ctx.getAdjustedType(originalType, adjustedType);
1145 QualType VisitDecayedType(const DecayedType *T) {
1146 QualType originalType = recurse(T->getOriginalType());
1147 if (originalType.isNull())
1148 return {};
1150 if (originalType.getAsOpaquePtr()
1151 == T->getOriginalType().getAsOpaquePtr())
1152 return QualType(T, 0);
1154 return Ctx.getDecayedType(originalType);
1157 SUGARED_TYPE_CLASS(TypeOfExpr)
1158 SUGARED_TYPE_CLASS(TypeOf)
1159 SUGARED_TYPE_CLASS(Decltype)
1160 SUGARED_TYPE_CLASS(UnaryTransform)
1161 TRIVIAL_TYPE_CLASS(Record)
1162 TRIVIAL_TYPE_CLASS(Enum)
1164 // FIXME: Non-trivial to implement, but important for C++
1165 SUGARED_TYPE_CLASS(Elaborated)
1167 QualType VisitAttributedType(const AttributedType *T) {
1168 QualType modifiedType = recurse(T->getModifiedType());
1169 if (modifiedType.isNull())
1170 return {};
1172 QualType equivalentType = recurse(T->getEquivalentType());
1173 if (equivalentType.isNull())
1174 return {};
1176 if (modifiedType.getAsOpaquePtr()
1177 == T->getModifiedType().getAsOpaquePtr() &&
1178 equivalentType.getAsOpaquePtr()
1179 == T->getEquivalentType().getAsOpaquePtr())
1180 return QualType(T, 0);
1182 return Ctx.getAttributedType(T->getAttrKind(), modifiedType,
1183 equivalentType);
1186 QualType VisitSubstTemplateTypeParmType(const SubstTemplateTypeParmType *T) {
1187 QualType replacementType = recurse(T->getReplacementType());
1188 if (replacementType.isNull())
1189 return {};
1191 if (replacementType.getAsOpaquePtr()
1192 == T->getReplacementType().getAsOpaquePtr())
1193 return QualType(T, 0);
1195 return Ctx.getSubstTemplateTypeParmType(replacementType,
1196 T->getAssociatedDecl(),
1197 T->getIndex(), T->getPackIndex());
1200 // FIXME: Non-trivial to implement, but important for C++
1201 SUGARED_TYPE_CLASS(TemplateSpecialization)
1203 QualType VisitAutoType(const AutoType *T) {
1204 if (!T->isDeduced())
1205 return QualType(T, 0);
1207 QualType deducedType = recurse(T->getDeducedType());
1208 if (deducedType.isNull())
1209 return {};
1211 if (deducedType.getAsOpaquePtr()
1212 == T->getDeducedType().getAsOpaquePtr())
1213 return QualType(T, 0);
1215 return Ctx.getAutoType(deducedType, T->getKeyword(),
1216 T->isDependentType(), /*IsPack=*/false,
1217 T->getTypeConstraintConcept(),
1218 T->getTypeConstraintArguments());
1221 QualType VisitObjCObjectType(const ObjCObjectType *T) {
1222 QualType baseType = recurse(T->getBaseType());
1223 if (baseType.isNull())
1224 return {};
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 {};
1234 if (newTypeArg.getAsOpaquePtr() != typeArg.getAsOpaquePtr())
1235 typeArgChanged = true;
1237 typeArgs.push_back(newTypeArg);
1240 if (baseType.getAsOpaquePtr() == T->getBaseType().getAsOpaquePtr() &&
1241 !typeArgChanged)
1242 return QualType(T, 0);
1244 return Ctx.getObjCObjectType(
1245 baseType, typeArgs,
1246 llvm::ArrayRef(T->qual_begin(), T->getNumProtocols()),
1247 T->isKindOfTypeAsWritten());
1250 TRIVIAL_TYPE_CLASS(ObjCInterface)
1252 QualType VisitObjCObjectPointerType(const ObjCObjectPointerType *T) {
1253 QualType pointeeType = recurse(T->getPointeeType());
1254 if (pointeeType.isNull())
1255 return {};
1257 if (pointeeType.getAsOpaquePtr()
1258 == T->getPointeeType().getAsOpaquePtr())
1259 return QualType(T, 0);
1261 return Ctx.getObjCObjectPointerType(pointeeType);
1264 QualType VisitAtomicType(const AtomicType *T) {
1265 QualType valueType = recurse(T->getValueType());
1266 if (valueType.isNull())
1267 return {};
1269 if (valueType.getAsOpaquePtr()
1270 == T->getValueType().getAsOpaquePtr())
1271 return QualType(T, 0);
1273 return Ctx.getAtomicType(valueType);
1276 #undef TRIVIAL_TYPE_CLASS
1277 #undef SUGARED_TYPE_CLASS
1280 struct SubstObjCTypeArgsVisitor
1281 : public SimpleTransformVisitor<SubstObjCTypeArgsVisitor> {
1282 using BaseType = SimpleTransformVisitor<SubstObjCTypeArgsVisitor>;
1284 ArrayRef<QualType> TypeArgs;
1285 ObjCSubstitutionContext SubstContext;
1287 SubstObjCTypeArgsVisitor(ASTContext &ctx, ArrayRef<QualType> typeArgs,
1288 ObjCSubstitutionContext context)
1289 : BaseType(ctx), TypeArgs(typeArgs), SubstContext(context) {}
1291 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;
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*/);
1310 switch (SubstContext) {
1311 case ObjCSubstitutionContext::Ordinary:
1312 case ObjCSubstitutionContext::Parameter:
1313 case ObjCSubstitutionContext::Superclass:
1314 // Substitute the bound.
1315 return typeParam->getUnderlyingType();
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>();
1323 // __kindof types, id, and Class don't need an additional
1324 // __kindof.
1325 if (objPtr->isKindOfType() || objPtr->isObjCIdOrClassType())
1326 return typeParam->getUnderlyingType();
1328 // Add __kindof.
1329 const auto *obj = objPtr->getObjectType();
1330 QualType resultTy = Ctx.getObjCObjectType(
1331 obj->getBaseType(), obj->getTypeArgsAsWritten(), obj->getProtocols(),
1332 /*isKindOf=*/true);
1334 // Rebuild object pointer type.
1335 return Ctx.getObjCObjectPointerType(resultTy);
1338 llvm_unreachable("Unexpected ObjCSubstitutionContext!");
1341 QualType VisitFunctionType(const FunctionType *funcType) {
1342 // If we have a function type, update the substitution context
1343 // appropriately.
1345 //Substitute result type.
1346 QualType returnType = funcType->getReturnType().substObjCTypeArgs(
1347 Ctx, TypeArgs, ObjCSubstitutionContext::Result);
1348 if (returnType.isNull())
1349 return {};
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);
1359 // Otherwise, build a new type.
1360 return Ctx.getFunctionNoProtoType(returnType, funcType->getExtInfo());
1363 const auto *funcProtoType = cast<FunctionProtoType>(funcType);
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 {};
1374 if (newParamType.getAsOpaquePtr() != paramType.getAsOpaquePtr())
1375 paramChanged = true;
1377 paramTypes.push_back(newParamType);
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 {};
1391 if (newExceptionType.getAsOpaquePtr() != exceptionType.getAsOpaquePtr())
1392 exceptionChanged = true;
1394 exceptionTypes.push_back(newExceptionType);
1397 if (exceptionChanged) {
1398 info.ExceptionSpec.Exceptions =
1399 llvm::ArrayRef(exceptionTypes).copy(Ctx);
1403 if (returnType.getAsOpaquePtr() ==
1404 funcProtoType->getReturnType().getAsOpaquePtr() &&
1405 !paramChanged && !exceptionChanged)
1406 return BaseType::VisitFunctionType(funcType);
1408 return Ctx.getFunctionType(returnType, paramTypes, info);
1411 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 {};
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());
1435 anyChanged = true;
1438 newTypeArgs.push_back(newTypeArg);
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());
1450 return BaseType::VisitObjCObjectType(objcObjectType);
1453 QualType VisitAttributedType(const AttributedType *attrType) {
1454 QualType newType = BaseType::VisitAttributedType(attrType);
1455 if (newType.isNull())
1456 return {};
1458 const auto *newAttrType = dyn_cast<AttributedType>(newType.getTypePtr());
1459 if (!newAttrType || newAttrType->getAttrKind() != attr::ObjCKindOf)
1460 return newType;
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;
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);
1480 // If we started with an object pointer type, rebuild it.
1481 if (ptrType)
1482 newEquivType = Ctx.getObjCObjectPointerType(newEquivType);
1484 // Rebuild the attributed type.
1485 return Ctx.getAttributedType(newAttrType->getAttrKind(),
1486 newAttrType->getModifiedType(), newEquivType);
1490 struct StripObjCKindOfTypeVisitor
1491 : public SimpleTransformVisitor<StripObjCKindOfTypeVisitor> {
1492 using BaseType = SimpleTransformVisitor<StripObjCKindOfTypeVisitor>;
1494 explicit StripObjCKindOfTypeVisitor(ASTContext &ctx) : BaseType(ctx) {}
1496 QualType VisitObjCObjectType(const ObjCObjectType *objType) {
1497 if (!objType->isKindOfType())
1498 return BaseType::VisitObjCObjectType(objType);
1500 QualType baseType = objType->getBaseType().stripObjCKindOfType(Ctx);
1501 return Ctx.getObjCObjectType(baseType, objType->getTypeArgsAsWritten(),
1502 objType->getProtocols(),
1503 /*isKindOf=*/false);
1507 } // namespace
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);
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;
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;
1535 default:
1536 return false;
1539 return false;
1542 /// Substitute the given type arguments for Objective-C type
1543 /// parameters within the given type, recursively.
1544 QualType QualType::substObjCTypeArgs(ASTContext &ctx,
1545 ArrayRef<QualType> typeArgs,
1546 ObjCSubstitutionContext context) const {
1547 SubstObjCTypeArgsVisitor visitor(ctx, typeArgs, context);
1548 return visitor.recurse(*this);
1551 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);
1557 return *this;
1560 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);
1567 QualType QualType::getAtomicUnqualifiedType() const {
1568 if (const auto AT = getTypePtr()->getAs<AtomicType>())
1569 return AT->getValueType().getUnqualifiedType();
1570 return getUnqualifiedType();
1573 std::optional<ArrayRef<QualType>>
1574 Type::getObjCSubstitutions(const DeclContext *dc) const {
1575 // Look through method scopes.
1576 if (const auto method = dyn_cast<ObjCMethodDecl>(dc))
1577 dc = method->getDeclContext();
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;
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;
1603 dcClassDecl = dcCategoryDecl->getClassInterface();
1604 if (!dcClassDecl)
1605 return std::nullopt;
1607 assert(dcTypeParams && "No substitutions to perform");
1608 assert(dcClassDecl && "No class context");
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>();
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>();
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;
1641 objectType = superType->castAs<ObjCObjectType>();
1642 curClassDecl = objectType->getInterface();
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>();
1651 // The receiver type has the type arguments we want.
1652 return objectType->getTypeArgs();
1655 bool Type::acceptsObjCTypeParams() const {
1656 if (auto *IfaceT = getAsObjCInterfaceType()) {
1657 if (auto *ID = IfaceT->getInterface()) {
1658 if (ID->getTypeParamList())
1659 return true;
1663 return false;
1666 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;
1676 // Extract the superclass type.
1677 const ObjCObjectType *superClassObjTy = classDecl->getSuperClassType();
1678 if (!superClassObjTy) {
1679 CachedSuperClassType.setInt(true);
1680 return;
1683 ObjCInterfaceDecl *superClassDecl = superClassObjTy->getInterface();
1684 if (!superClassDecl) {
1685 CachedSuperClassType.setInt(true);
1686 return;
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;
1699 // If the superclass reference is unspecialized, return it.
1700 if (superClassObjTy->isUnspecialized()) {
1701 CachedSuperClassType.setPointerAndInt(superClassObjTy, true);
1702 return;
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;
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;
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);
1736 const ObjCInterfaceType *ObjCObjectPointerType::getInterfaceType() const {
1737 if (auto interfaceDecl = getObjectType()->getInterface()) {
1738 return interfaceDecl->getASTContext().getObjCInterfaceType(interfaceDecl)
1739 ->castAs<ObjCInterfaceType>();
1742 return nullptr;
1745 QualType ObjCObjectPointerType::getSuperClassType() const {
1746 QualType superObjectType = getObjectType()->getSuperClassType();
1747 if (superObjectType.isNull())
1748 return superObjectType;
1750 ASTContext &ctx = getInterfaceDecl()->getASTContext();
1751 return ctx.getObjCObjectPointerType(superObjectType);
1754 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;
1764 bool Type::isObjCQualifiedInterfaceType() const {
1765 return getAsObjCQualifiedInterfaceType() != nullptr;
1768 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;
1775 return nullptr;
1778 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;
1785 return nullptr;
1788 const ObjCObjectType *Type::getAsObjCInterfaceType() const {
1789 if (const auto *OT = getAs<ObjCObjectType>()) {
1790 if (OT->getInterface())
1791 return OT;
1793 return nullptr;
1796 const ObjCObjectPointerType *Type::getAsObjCInterfacePointerType() const {
1797 if (const auto *OPT = getAs<ObjCObjectPointerType>()) {
1798 if (OPT->getInterfaceType())
1799 return OPT;
1801 return nullptr;
1804 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;
1813 if (const auto *RT = PointeeType->getAs<RecordType>())
1814 return dyn_cast<CXXRecordDecl>(RT->getDecl());
1816 return nullptr;
1819 CXXRecordDecl *Type::getAsCXXRecordDecl() const {
1820 return dyn_cast_or_null<CXXRecordDecl>(getAsTagDecl());
1823 RecordDecl *Type::getAsRecordDecl() const {
1824 return dyn_cast_or_null<RecordDecl>(getAsTagDecl());
1827 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();
1833 return nullptr;
1836 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();
1843 return false;
1846 namespace {
1848 class GetContainedDeducedTypeVisitor :
1849 public TypeVisitor<GetContainedDeducedTypeVisitor, Type*> {
1850 bool Syntactic;
1852 public:
1853 GetContainedDeducedTypeVisitor(bool Syntactic = false)
1854 : Syntactic(Syntactic) {}
1856 using TypeVisitor<GetContainedDeducedTypeVisitor, Type*>::Visit;
1858 Type *Visit(QualType T) {
1859 if (T.isNull())
1860 return nullptr;
1861 return Visit(T.getTypePtr());
1864 // The deduced type itself.
1865 Type *VisitDeducedType(const DeducedType *AT) {
1866 return const_cast<DeducedType*>(AT);
1869 // Only these types can contain the desired 'auto' type.
1870 Type *VisitSubstTemplateTypeParmType(const SubstTemplateTypeParmType *T) {
1871 return Visit(T->getReplacementType());
1874 Type *VisitElaboratedType(const ElaboratedType *T) {
1875 return Visit(T->getNamedType());
1878 Type *VisitPointerType(const PointerType *T) {
1879 return Visit(T->getPointeeType());
1882 Type *VisitBlockPointerType(const BlockPointerType *T) {
1883 return Visit(T->getPointeeType());
1886 Type *VisitReferenceType(const ReferenceType *T) {
1887 return Visit(T->getPointeeTypeAsWritten());
1890 Type *VisitMemberPointerType(const MemberPointerType *T) {
1891 return Visit(T->getPointeeType());
1894 Type *VisitArrayType(const ArrayType *T) {
1895 return Visit(T->getElementType());
1898 Type *VisitDependentSizedExtVectorType(
1899 const DependentSizedExtVectorType *T) {
1900 return Visit(T->getElementType());
1903 Type *VisitVectorType(const VectorType *T) {
1904 return Visit(T->getElementType());
1907 Type *VisitDependentSizedMatrixType(const DependentSizedMatrixType *T) {
1908 return Visit(T->getElementType());
1911 Type *VisitConstantMatrixType(const ConstantMatrixType *T) {
1912 return Visit(T->getElementType());
1915 Type *VisitFunctionProtoType(const FunctionProtoType *T) {
1916 if (Syntactic && T->hasTrailingReturn())
1917 return const_cast<FunctionProtoType*>(T);
1918 return VisitFunctionType(T);
1921 Type *VisitFunctionType(const FunctionType *T) {
1922 return Visit(T->getReturnType());
1925 Type *VisitParenType(const ParenType *T) {
1926 return Visit(T->getInnerType());
1929 Type *VisitAttributedType(const AttributedType *T) {
1930 return Visit(T->getModifiedType());
1933 Type *VisitMacroQualifiedType(const MacroQualifiedType *T) {
1934 return Visit(T->getUnderlyingType());
1937 Type *VisitAdjustedType(const AdjustedType *T) {
1938 return Visit(T->getOriginalType());
1941 Type *VisitPackExpansionType(const PackExpansionType *T) {
1942 return Visit(T->getPattern());
1946 } // namespace
1948 DeducedType *Type::getContainedDeducedType() const {
1949 return cast_or_null<DeducedType>(
1950 GetContainedDeducedTypeVisitor().Visit(this));
1953 bool Type::hasAutoForTrailingReturnType() const {
1954 return isa_and_nonnull<FunctionType>(
1955 GetContainedDeducedTypeVisitor(true).Visit(this));
1958 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);
1967 if (CanonicalType->isRVVVLSBuiltinType()) {
1968 const auto *VT = cast<BuiltinType>(CanonicalType);
1969 return (VT->getKind() >= BuiltinType::RvvInt8mf8 &&
1970 VT->getKind() <= BuiltinType::RvvUint64m8);
1973 return isIntegerType();
1976 /// Determine whether this type is an integral type.
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.
1986 /// For cases where C permits "an integer type" and C++ permits "an integral
1987 /// type", use this routine.
1989 /// For cases where C permits "an integer type" and C++ permits "an integral
1990 /// or enumeration type", use \c isIntegralOrEnumerationType() instead.
1992 /// \param Ctx The context in which this type occurs.
1994 /// \returns true if the type is considered an integral type, false otherwise.
1995 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;
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();
2005 return isBitIntType();
2008 bool Type::isIntegralOrUnscopedEnumerationType() const {
2009 if (const auto *BT = dyn_cast<BuiltinType>(CanonicalType))
2010 return BT->getKind() >= BuiltinType::Bool &&
2011 BT->getKind() <= BuiltinType::Int128;
2013 if (isBitIntType())
2014 return true;
2016 return isUnscopedEnumerationType();
2019 bool Type::isUnscopedEnumerationType() const {
2020 if (const auto *ET = dyn_cast<EnumType>(CanonicalType))
2021 return !ET->getDecl()->isScoped();
2023 return false;
2026 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;
2035 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;
2042 bool Type::isChar8Type() const {
2043 if (const BuiltinType *BT = dyn_cast<BuiltinType>(CanonicalType))
2044 return BT->getKind() == BuiltinType::Char8;
2045 return false;
2048 bool Type::isChar16Type() const {
2049 if (const auto *BT = dyn_cast<BuiltinType>(CanonicalType))
2050 return BT->getKind() == BuiltinType::Char16;
2051 return false;
2054 bool Type::isChar32Type() const {
2055 if (const auto *BT = dyn_cast<BuiltinType>(CanonicalType))
2056 return BT->getKind() == BuiltinType::Char32;
2057 return false;
2060 /// Determine whether this type is any of the built-in character
2061 /// types.
2062 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;
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
2083 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;
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();
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();
2101 return false;
2104 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;
2110 if (const auto *ET = dyn_cast<EnumType>(CanonicalType)) {
2111 if (ET->getDecl()->isComplete())
2112 return ET->getDecl()->getIntegerType()->isSignedIntegerType();
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();
2120 return false;
2123 bool Type::hasSignedIntegerRepresentation() const {
2124 if (const auto *VT = dyn_cast<VectorType>(CanonicalType))
2125 return VT->getElementType()->isSignedIntegerOrEnumerationType();
2126 else
2127 return isSignedIntegerOrEnumerationType();
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
2133 bool Type::isUnsignedIntegerType() const {
2134 if (const auto *BT = dyn_cast<BuiltinType>(CanonicalType)) {
2135 return BT->getKind() >= BuiltinType::Bool &&
2136 BT->getKind() <= BuiltinType::UInt128;
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();
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();
2151 return false;
2154 bool Type::isUnsignedIntegerOrEnumerationType() const {
2155 if (const auto *BT = dyn_cast<BuiltinType>(CanonicalType)) {
2156 return BT->getKind() >= BuiltinType::Bool &&
2157 BT->getKind() <= BuiltinType::UInt128;
2160 if (const auto *ET = dyn_cast<EnumType>(CanonicalType)) {
2161 if (ET->getDecl()->isComplete())
2162 return ET->getDecl()->getIntegerType()->isUnsignedIntegerType();
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();
2170 return false;
2173 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;
2183 return isUnsignedIntegerOrEnumerationType();
2186 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;
2195 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();
2203 bool Type::isRealFloatingType() const {
2204 if (const auto *BT = dyn_cast<BuiltinType>(CanonicalType))
2205 return BT->isFloatingPoint();
2206 return false;
2209 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();
2218 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.
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();
2233 Type::ScalarTypeKind Type::getScalarTypeKind() const {
2234 assert(isScalarType());
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;
2263 llvm_unreachable("unknown scalar type");
2266 /// Determines whether the type is a C++ aggregate type or C
2267 /// aggregate or union type.
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.
2275 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();
2280 return true;
2283 return isa<ArrayType>(CanonicalType);
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.
2289 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);
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.
2299 bool Type::isIncompleteType(NamedDecl **Def) const {
2300 if (Def)
2301 *Def = nullptr;
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();
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();
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;
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();
2370 bool Type::isSizelessBuiltinType() const {
2371 if (isSizelessVectorType())
2372 return true;
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;
2384 return false;
2387 bool Type::isWebAssemblyExternrefType() const {
2388 if (const auto *BT = getAs<BuiltinType>())
2389 return BT->getKind() == BuiltinType::WasmExternRef;
2390 return false;
2393 bool Type::isWebAssemblyTableType() const {
2394 if (const auto *ATy = dyn_cast<ArrayType>(this))
2395 return ATy->getElementType().isWebAssemblyReferenceType();
2397 if (const auto *PTy = dyn_cast<PointerType>(this))
2398 return PTy->getPointeeType().isWebAssemblyReferenceType();
2400 return false;
2403 bool Type::isSizelessType() const { return isSizelessBuiltinType(); }
2405 bool Type::isSizelessVectorType() const {
2406 return isSVESizelessBuiltinType() || isRVVSizelessBuiltinType();
2409 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;
2420 return false;
2423 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;
2433 return false;
2436 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;
2459 return false;
2462 QualType Type::getSveEltType(const ASTContext &Ctx) const {
2463 assert(isSveVLSBuiltinType() && "unsupported type!");
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;
2475 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, IsFP) \
2479 case BuiltinType::Id: \
2480 return NF == 1;
2481 #include "clang/Basic/RISCVVTypes.def"
2482 default:
2483 return false;
2486 return false;
2489 QualType Type::getRVVEltType(const ASTContext &Ctx) const {
2490 assert(isRVVVLSBuiltinType() && "unsupported type!");
2492 const BuiltinType *BTy = castAs<BuiltinType>();
2493 return Ctx.getBuiltinVectorTypeInfo(BTy).ElementType;
2496 bool QualType::isPODType(const ASTContext &Context) const {
2497 // C++11 has a more relaxed definition of POD.
2498 if (Context.getLangOpts().CPlusPlus11)
2499 return isCXX11PODType(Context);
2501 return isCXX98PODType(Context);
2504 bool QualType::isCXX98PODType(const ASTContext &Context) const {
2505 // The compiler shouldn't query this for incomplete types, but the user might.
2506 // We return false for that case. Except for incomplete arrays of PODs, which
2507 // are PODs according to the standard.
2508 if (isNull())
2509 return false;
2511 if ((*this)->isIncompleteArrayType())
2512 return Context.getBaseElementType(*this).isCXX98PODType(Context);
2514 if ((*this)->isIncompleteType())
2515 return false;
2517 if (hasNonTrivialObjCLifetime())
2518 return false;
2520 QualType CanonicalType = getTypePtr()->CanonicalType;
2521 switch (CanonicalType->getTypeClass()) {
2522 // Everything not explicitly mentioned is not POD.
2523 default: return false;
2524 case Type::VariableArray:
2525 case Type::ConstantArray:
2526 // IncompleteArray is handled above.
2527 return Context.getBaseElementType(*this).isCXX98PODType(Context);
2529 case Type::ObjCObjectPointer:
2530 case Type::BlockPointer:
2531 case Type::Builtin:
2532 case Type::Complex:
2533 case Type::Pointer:
2534 case Type::MemberPointer:
2535 case Type::Vector:
2536 case Type::ExtVector:
2537 case Type::BitInt:
2538 return true;
2540 case Type::Enum:
2541 return true;
2543 case Type::Record:
2544 if (const auto *ClassDecl =
2545 dyn_cast<CXXRecordDecl>(cast<RecordType>(CanonicalType)->getDecl()))
2546 return ClassDecl->isPOD();
2548 // C struct/union is POD.
2549 return true;
2553 bool QualType::isTrivialType(const ASTContext &Context) const {
2554 // The compiler shouldn't query this for incomplete types, but the user might.
2555 // We return false for that case. Except for incomplete arrays of PODs, which
2556 // are PODs according to the standard.
2557 if (isNull())
2558 return false;
2560 if ((*this)->isArrayType())
2561 return Context.getBaseElementType(*this).isTrivialType(Context);
2563 if ((*this)->isSizelessBuiltinType())
2564 return true;
2566 // Return false for incomplete types after skipping any incomplete array
2567 // types which are expressly allowed by the standard and thus our API.
2568 if ((*this)->isIncompleteType())
2569 return false;
2571 if (hasNonTrivialObjCLifetime())
2572 return false;
2574 QualType CanonicalType = getTypePtr()->CanonicalType;
2575 if (CanonicalType->isDependentType())
2576 return false;
2578 // C++0x [basic.types]p9:
2579 // Scalar types, trivial class types, arrays of such types, and
2580 // cv-qualified versions of these types are collectively called trivial
2581 // types.
2583 // As an extension, Clang treats vector types as Scalar types.
2584 if (CanonicalType->isScalarType() || CanonicalType->isVectorType())
2585 return true;
2586 if (const auto *RT = CanonicalType->getAs<RecordType>()) {
2587 if (const auto *ClassDecl = dyn_cast<CXXRecordDecl>(RT->getDecl())) {
2588 // C++20 [class]p6:
2589 // A trivial class is a class that is trivially copyable, and
2590 // has one or more eligible default constructors such that each is
2591 // trivial.
2592 // FIXME: We should merge this definition of triviality into
2593 // CXXRecordDecl::isTrivial. Currently it computes the wrong thing.
2594 return ClassDecl->hasTrivialDefaultConstructor() &&
2595 !ClassDecl->hasNonTrivialDefaultConstructor() &&
2596 ClassDecl->isTriviallyCopyable();
2599 return true;
2602 // No other types can match.
2603 return false;
2606 bool QualType::isTriviallyCopyableType(const ASTContext &Context) const {
2607 if ((*this)->isArrayType())
2608 return Context.getBaseElementType(*this).isTriviallyCopyableType(Context);
2610 if (hasNonTrivialObjCLifetime())
2611 return false;
2613 // C++11 [basic.types]p9 - See Core 2094
2614 // Scalar types, trivially copyable class types, arrays of such types, and
2615 // cv-qualified versions of these types are collectively
2616 // called trivially copyable types.
2618 QualType CanonicalType = getCanonicalType();
2619 if (CanonicalType->isDependentType())
2620 return false;
2622 if (CanonicalType->isSizelessBuiltinType())
2623 return true;
2625 // Return false for incomplete types after skipping any incomplete array types
2626 // which are expressly allowed by the standard and thus our API.
2627 if (CanonicalType->isIncompleteType())
2628 return false;
2630 // As an extension, Clang treats vector types as Scalar types.
2631 if (CanonicalType->isScalarType() || CanonicalType->isVectorType())
2632 return true;
2634 if (const auto *RT = CanonicalType->getAs<RecordType>()) {
2635 if (const auto *ClassDecl = dyn_cast<CXXRecordDecl>(RT->getDecl())) {
2636 if (!ClassDecl->isTriviallyCopyable()) return false;
2639 return true;
2642 // No other types can match.
2643 return false;
2646 bool QualType::isTriviallyRelocatableType(const ASTContext &Context) const {
2647 QualType BaseElementType = Context.getBaseElementType(*this);
2649 if (BaseElementType->isIncompleteType()) {
2650 return false;
2651 } else if (const auto *RD = BaseElementType->getAsRecordDecl()) {
2652 return RD->canPassInRegisters();
2653 } else {
2654 switch (isNonTrivialToPrimitiveDestructiveMove()) {
2655 case PCK_Trivial:
2656 return !isDestructedType();
2657 case PCK_ARCStrong:
2658 return true;
2659 default:
2660 return false;
2665 static bool
2666 HasNonDeletedDefaultedEqualityComparison(const CXXRecordDecl *Decl) {
2667 if (Decl->isUnion())
2668 return false;
2669 if (Decl->isLambda())
2670 return Decl->isCapturelessLambda();
2672 auto IsDefaultedOperatorEqualEqual = [&](const FunctionDecl *Function) {
2673 return Function->getOverloadedOperator() ==
2674 OverloadedOperatorKind::OO_EqualEqual &&
2675 Function->isDefaulted() && Function->getNumParams() > 0 &&
2676 (Function->getParamDecl(0)->getType()->isReferenceType() ||
2677 Decl->isTriviallyCopyable());
2680 if (llvm::none_of(Decl->methods(), IsDefaultedOperatorEqualEqual) &&
2681 llvm::none_of(Decl->friends(), [&](const FriendDecl *Friend) {
2682 if (NamedDecl *ND = Friend->getFriendDecl()) {
2683 return ND->isFunctionOrFunctionTemplate() &&
2684 IsDefaultedOperatorEqualEqual(ND->getAsFunction());
2686 return false;
2688 return false;
2690 return llvm::all_of(Decl->bases(),
2691 [](const CXXBaseSpecifier &BS) {
2692 if (const auto *RD = BS.getType()->getAsCXXRecordDecl())
2693 return HasNonDeletedDefaultedEqualityComparison(RD);
2694 return true;
2695 }) &&
2696 llvm::all_of(Decl->fields(), [](const FieldDecl *FD) {
2697 auto Type = FD->getType();
2698 if (Type->isArrayType())
2699 Type = Type->getBaseElementTypeUnsafe()->getCanonicalTypeUnqualified();
2701 if (Type->isReferenceType() || Type->isEnumeralType())
2702 return false;
2703 if (const auto *RD = Type->getAsCXXRecordDecl())
2704 return HasNonDeletedDefaultedEqualityComparison(RD);
2705 return true;
2709 bool QualType::isTriviallyEqualityComparableType(
2710 const ASTContext &Context) const {
2711 QualType CanonicalType = getCanonicalType();
2712 if (CanonicalType->isIncompleteType() || CanonicalType->isDependentType() ||
2713 CanonicalType->isEnumeralType() || CanonicalType->isArrayType())
2714 return false;
2716 if (const auto *RD = CanonicalType->getAsCXXRecordDecl()) {
2717 if (!HasNonDeletedDefaultedEqualityComparison(RD))
2718 return false;
2721 return Context.hasUniqueObjectRepresentations(
2722 CanonicalType, /*CheckIfTriviallyCopyable=*/false);
2725 bool QualType::isNonWeakInMRRWithObjCWeak(const ASTContext &Context) const {
2726 return !Context.getLangOpts().ObjCAutoRefCount &&
2727 Context.getLangOpts().ObjCWeak &&
2728 getObjCLifetime() != Qualifiers::OCL_Weak;
2731 bool QualType::hasNonTrivialToPrimitiveDefaultInitializeCUnion(const RecordDecl *RD) {
2732 return RD->hasNonTrivialToPrimitiveDefaultInitializeCUnion();
2735 bool QualType::hasNonTrivialToPrimitiveDestructCUnion(const RecordDecl *RD) {
2736 return RD->hasNonTrivialToPrimitiveDestructCUnion();
2739 bool QualType::hasNonTrivialToPrimitiveCopyCUnion(const RecordDecl *RD) {
2740 return RD->hasNonTrivialToPrimitiveCopyCUnion();
2743 bool QualType::isWebAssemblyReferenceType() const {
2744 return isWebAssemblyExternrefType() || isWebAssemblyFuncrefType();
2747 bool QualType::isWebAssemblyExternrefType() const {
2748 return getTypePtr()->isWebAssemblyExternrefType();
2751 bool QualType::isWebAssemblyFuncrefType() const {
2752 return getTypePtr()->isFunctionPointerType() &&
2753 getAddressSpace() == LangAS::wasm_funcref;
2756 QualType::PrimitiveDefaultInitializeKind
2757 QualType::isNonTrivialToPrimitiveDefaultInitialize() const {
2758 if (const auto *RT =
2759 getTypePtr()->getBaseElementTypeUnsafe()->getAs<RecordType>())
2760 if (RT->getDecl()->isNonTrivialToPrimitiveDefaultInitialize())
2761 return PDIK_Struct;
2763 switch (getQualifiers().getObjCLifetime()) {
2764 case Qualifiers::OCL_Strong:
2765 return PDIK_ARCStrong;
2766 case Qualifiers::OCL_Weak:
2767 return PDIK_ARCWeak;
2768 default:
2769 return PDIK_Trivial;
2773 QualType::PrimitiveCopyKind QualType::isNonTrivialToPrimitiveCopy() const {
2774 if (const auto *RT =
2775 getTypePtr()->getBaseElementTypeUnsafe()->getAs<RecordType>())
2776 if (RT->getDecl()->isNonTrivialToPrimitiveCopy())
2777 return PCK_Struct;
2779 Qualifiers Qs = getQualifiers();
2780 switch (Qs.getObjCLifetime()) {
2781 case Qualifiers::OCL_Strong:
2782 return PCK_ARCStrong;
2783 case Qualifiers::OCL_Weak:
2784 return PCK_ARCWeak;
2785 default:
2786 return Qs.hasVolatile() ? PCK_VolatileTrivial : PCK_Trivial;
2790 QualType::PrimitiveCopyKind
2791 QualType::isNonTrivialToPrimitiveDestructiveMove() const {
2792 return isNonTrivialToPrimitiveCopy();
2795 bool Type::isLiteralType(const ASTContext &Ctx) const {
2796 if (isDependentType())
2797 return false;
2799 // C++1y [basic.types]p10:
2800 // A type is a literal type if it is:
2801 // -- cv void; or
2802 if (Ctx.getLangOpts().CPlusPlus14 && isVoidType())
2803 return true;
2805 // C++11 [basic.types]p10:
2806 // A type is a literal type if it is:
2807 // [...]
2808 // -- an array of literal type other than an array of runtime bound; or
2809 if (isVariableArrayType())
2810 return false;
2811 const Type *BaseTy = getBaseElementTypeUnsafe();
2812 assert(BaseTy && "NULL element type");
2814 // Return false for incomplete types after skipping any incomplete array
2815 // types; those are expressly allowed by the standard and thus our API.
2816 if (BaseTy->isIncompleteType())
2817 return false;
2819 // C++11 [basic.types]p10:
2820 // A type is a literal type if it is:
2821 // -- a scalar type; or
2822 // As an extension, Clang treats vector types and complex types as
2823 // literal types.
2824 if (BaseTy->isScalarType() || BaseTy->isVectorType() ||
2825 BaseTy->isAnyComplexType())
2826 return true;
2827 // -- a reference type; or
2828 if (BaseTy->isReferenceType())
2829 return true;
2830 // -- a class type that has all of the following properties:
2831 if (const auto *RT = BaseTy->getAs<RecordType>()) {
2832 // -- a trivial destructor,
2833 // -- every constructor call and full-expression in the
2834 // brace-or-equal-initializers for non-static data members (if any)
2835 // is a constant expression,
2836 // -- it is an aggregate type or has at least one constexpr
2837 // constructor or constructor template that is not a copy or move
2838 // constructor, and
2839 // -- all non-static data members and base classes of literal types
2841 // We resolve DR1361 by ignoring the second bullet.
2842 if (const auto *ClassDecl = dyn_cast<CXXRecordDecl>(RT->getDecl()))
2843 return ClassDecl->isLiteral();
2845 return true;
2848 // We treat _Atomic T as a literal type if T is a literal type.
2849 if (const auto *AT = BaseTy->getAs<AtomicType>())
2850 return AT->getValueType()->isLiteralType(Ctx);
2852 // If this type hasn't been deduced yet, then conservatively assume that
2853 // it'll work out to be a literal type.
2854 if (isa<AutoType>(BaseTy->getCanonicalTypeInternal()))
2855 return true;
2857 return false;
2860 bool Type::isStructuralType() const {
2861 // C++20 [temp.param]p6:
2862 // A structural type is one of the following:
2863 // -- a scalar type; or
2864 // -- a vector type [Clang extension]; or
2865 if (isScalarType() || isVectorType())
2866 return true;
2867 // -- an lvalue reference type; or
2868 if (isLValueReferenceType())
2869 return true;
2870 // -- a literal class type [...under some conditions]
2871 if (const CXXRecordDecl *RD = getAsCXXRecordDecl())
2872 return RD->isStructural();
2873 return false;
2876 bool Type::isStandardLayoutType() const {
2877 if (isDependentType())
2878 return false;
2880 // C++0x [basic.types]p9:
2881 // Scalar types, standard-layout class types, arrays of such types, and
2882 // cv-qualified versions of these types are collectively called
2883 // standard-layout types.
2884 const Type *BaseTy = getBaseElementTypeUnsafe();
2885 assert(BaseTy && "NULL element type");
2887 // Return false for incomplete types after skipping any incomplete array
2888 // types which are expressly allowed by the standard and thus our API.
2889 if (BaseTy->isIncompleteType())
2890 return false;
2892 // As an extension, Clang treats vector types as Scalar types.
2893 if (BaseTy->isScalarType() || BaseTy->isVectorType()) return true;
2894 if (const auto *RT = BaseTy->getAs<RecordType>()) {
2895 if (const auto *ClassDecl = dyn_cast<CXXRecordDecl>(RT->getDecl()))
2896 if (!ClassDecl->isStandardLayout())
2897 return false;
2899 // Default to 'true' for non-C++ class types.
2900 // FIXME: This is a bit dubious, but plain C structs should trivially meet
2901 // all the requirements of standard layout classes.
2902 return true;
2905 // No other types can match.
2906 return false;
2909 // This is effectively the intersection of isTrivialType and
2910 // isStandardLayoutType. We implement it directly to avoid redundant
2911 // conversions from a type to a CXXRecordDecl.
2912 bool QualType::isCXX11PODType(const ASTContext &Context) const {
2913 const Type *ty = getTypePtr();
2914 if (ty->isDependentType())
2915 return false;
2917 if (hasNonTrivialObjCLifetime())
2918 return false;
2920 // C++11 [basic.types]p9:
2921 // Scalar types, POD classes, arrays of such types, and cv-qualified
2922 // versions of these types are collectively called trivial types.
2923 const Type *BaseTy = ty->getBaseElementTypeUnsafe();
2924 assert(BaseTy && "NULL element type");
2926 if (BaseTy->isSizelessBuiltinType())
2927 return true;
2929 // Return false for incomplete types after skipping any incomplete array
2930 // types which are expressly allowed by the standard and thus our API.
2931 if (BaseTy->isIncompleteType())
2932 return false;
2934 // As an extension, Clang treats vector types as Scalar types.
2935 if (BaseTy->isScalarType() || BaseTy->isVectorType()) return true;
2936 if (const auto *RT = BaseTy->getAs<RecordType>()) {
2937 if (const auto *ClassDecl = dyn_cast<CXXRecordDecl>(RT->getDecl())) {
2938 // C++11 [class]p10:
2939 // A POD struct is a non-union class that is both a trivial class [...]
2940 if (!ClassDecl->isTrivial()) return false;
2942 // C++11 [class]p10:
2943 // A POD struct is a non-union class that is both a trivial class and
2944 // a standard-layout class [...]
2945 if (!ClassDecl->isStandardLayout()) return false;
2947 // C++11 [class]p10:
2948 // A POD struct is a non-union class that is both a trivial class and
2949 // a standard-layout class, and has no non-static data members of type
2950 // non-POD struct, non-POD union (or array of such types). [...]
2952 // We don't directly query the recursive aspect as the requirements for
2953 // both standard-layout classes and trivial classes apply recursively
2954 // already.
2957 return true;
2960 // No other types can match.
2961 return false;
2964 bool Type::isNothrowT() const {
2965 if (const auto *RD = getAsCXXRecordDecl()) {
2966 IdentifierInfo *II = RD->getIdentifier();
2967 if (II && II->isStr("nothrow_t") && RD->isInStdNamespace())
2968 return true;
2970 return false;
2973 bool Type::isAlignValT() const {
2974 if (const auto *ET = getAs<EnumType>()) {
2975 IdentifierInfo *II = ET->getDecl()->getIdentifier();
2976 if (II && II->isStr("align_val_t") && ET->getDecl()->isInStdNamespace())
2977 return true;
2979 return false;
2982 bool Type::isStdByteType() const {
2983 if (const auto *ET = getAs<EnumType>()) {
2984 IdentifierInfo *II = ET->getDecl()->getIdentifier();
2985 if (II && II->isStr("byte") && ET->getDecl()->isInStdNamespace())
2986 return true;
2988 return false;
2991 bool Type::isSpecifierType() const {
2992 // Note that this intentionally does not use the canonical type.
2993 switch (getTypeClass()) {
2994 case Builtin:
2995 case Record:
2996 case Enum:
2997 case Typedef:
2998 case Complex:
2999 case TypeOfExpr:
3000 case TypeOf:
3001 case TemplateTypeParm:
3002 case SubstTemplateTypeParm:
3003 case TemplateSpecialization:
3004 case Elaborated:
3005 case DependentName:
3006 case DependentTemplateSpecialization:
3007 case ObjCInterface:
3008 case ObjCObject:
3009 return true;
3010 default:
3011 return false;
3015 ElaboratedTypeKeyword
3016 TypeWithKeyword::getKeywordForTypeSpec(unsigned TypeSpec) {
3017 switch (TypeSpec) {
3018 default:
3019 return ElaboratedTypeKeyword::None;
3020 case TST_typename:
3021 return ElaboratedTypeKeyword::Typename;
3022 case TST_class:
3023 return ElaboratedTypeKeyword::Class;
3024 case TST_struct:
3025 return ElaboratedTypeKeyword::Struct;
3026 case TST_interface:
3027 return ElaboratedTypeKeyword::Interface;
3028 case TST_union:
3029 return ElaboratedTypeKeyword::Union;
3030 case TST_enum:
3031 return ElaboratedTypeKeyword::Enum;
3035 TagTypeKind
3036 TypeWithKeyword::getTagTypeKindForTypeSpec(unsigned TypeSpec) {
3037 switch(TypeSpec) {
3038 case TST_class: return TTK_Class;
3039 case TST_struct: return TTK_Struct;
3040 case TST_interface: return TTK_Interface;
3041 case TST_union: return TTK_Union;
3042 case TST_enum: return TTK_Enum;
3045 llvm_unreachable("Type specifier is not a tag type kind.");
3048 ElaboratedTypeKeyword
3049 TypeWithKeyword::getKeywordForTagTypeKind(TagTypeKind Kind) {
3050 switch (Kind) {
3051 case TTK_Class:
3052 return ElaboratedTypeKeyword::Class;
3053 case TTK_Struct:
3054 return ElaboratedTypeKeyword::Struct;
3055 case TTK_Interface:
3056 return ElaboratedTypeKeyword::Interface;
3057 case TTK_Union:
3058 return ElaboratedTypeKeyword::Union;
3059 case TTK_Enum:
3060 return ElaboratedTypeKeyword::Enum;
3062 llvm_unreachable("Unknown tag type kind.");
3065 TagTypeKind
3066 TypeWithKeyword::getTagTypeKindForKeyword(ElaboratedTypeKeyword Keyword) {
3067 switch (Keyword) {
3068 case ElaboratedTypeKeyword::Class:
3069 return TTK_Class;
3070 case ElaboratedTypeKeyword::Struct:
3071 return TTK_Struct;
3072 case ElaboratedTypeKeyword::Interface:
3073 return TTK_Interface;
3074 case ElaboratedTypeKeyword::Union:
3075 return TTK_Union;
3076 case ElaboratedTypeKeyword::Enum:
3077 return TTK_Enum;
3078 case ElaboratedTypeKeyword::None: // Fall through.
3079 case ElaboratedTypeKeyword::Typename:
3080 llvm_unreachable("Elaborated type keyword is not a tag type kind.");
3082 llvm_unreachable("Unknown elaborated type keyword.");
3085 bool
3086 TypeWithKeyword::KeywordIsTagTypeKind(ElaboratedTypeKeyword Keyword) {
3087 switch (Keyword) {
3088 case ElaboratedTypeKeyword::None:
3089 case ElaboratedTypeKeyword::Typename:
3090 return false;
3091 case ElaboratedTypeKeyword::Class:
3092 case ElaboratedTypeKeyword::Struct:
3093 case ElaboratedTypeKeyword::Interface:
3094 case ElaboratedTypeKeyword::Union:
3095 case ElaboratedTypeKeyword::Enum:
3096 return true;
3098 llvm_unreachable("Unknown elaborated type keyword.");
3101 StringRef TypeWithKeyword::getKeywordName(ElaboratedTypeKeyword Keyword) {
3102 switch (Keyword) {
3103 case ElaboratedTypeKeyword::None:
3104 return {};
3105 case ElaboratedTypeKeyword::Typename:
3106 return "typename";
3107 case ElaboratedTypeKeyword::Class:
3108 return "class";
3109 case ElaboratedTypeKeyword::Struct:
3110 return "struct";
3111 case ElaboratedTypeKeyword::Interface:
3112 return "__interface";
3113 case ElaboratedTypeKeyword::Union:
3114 return "union";
3115 case ElaboratedTypeKeyword::Enum:
3116 return "enum";
3119 llvm_unreachable("Unknown elaborated type keyword.");
3122 DependentTemplateSpecializationType::DependentTemplateSpecializationType(
3123 ElaboratedTypeKeyword Keyword, NestedNameSpecifier *NNS,
3124 const IdentifierInfo *Name, ArrayRef<TemplateArgument> Args, QualType Canon)
3125 : TypeWithKeyword(Keyword, DependentTemplateSpecialization, Canon,
3126 TypeDependence::DependentInstantiation |
3127 (NNS ? toTypeDependence(NNS->getDependence())
3128 : TypeDependence::None)),
3129 NNS(NNS), Name(Name) {
3130 DependentTemplateSpecializationTypeBits.NumArgs = Args.size();
3131 assert((!NNS || NNS->isDependent()) &&
3132 "DependentTemplateSpecializatonType requires dependent qualifier");
3133 auto *ArgBuffer = const_cast<TemplateArgument *>(template_arguments().data());
3134 for (const TemplateArgument &Arg : Args) {
3135 addDependence(toTypeDependence(Arg.getDependence() &
3136 TemplateArgumentDependence::UnexpandedPack));
3138 new (ArgBuffer++) TemplateArgument(Arg);
3142 void
3143 DependentTemplateSpecializationType::Profile(llvm::FoldingSetNodeID &ID,
3144 const ASTContext &Context,
3145 ElaboratedTypeKeyword Keyword,
3146 NestedNameSpecifier *Qualifier,
3147 const IdentifierInfo *Name,
3148 ArrayRef<TemplateArgument> Args) {
3149 ID.AddInteger(llvm::to_underlying(Keyword));
3150 ID.AddPointer(Qualifier);
3151 ID.AddPointer(Name);
3152 for (const TemplateArgument &Arg : Args)
3153 Arg.Profile(ID, Context);
3156 bool Type::isElaboratedTypeSpecifier() const {
3157 ElaboratedTypeKeyword Keyword;
3158 if (const auto *Elab = dyn_cast<ElaboratedType>(this))
3159 Keyword = Elab->getKeyword();
3160 else if (const auto *DepName = dyn_cast<DependentNameType>(this))
3161 Keyword = DepName->getKeyword();
3162 else if (const auto *DepTST =
3163 dyn_cast<DependentTemplateSpecializationType>(this))
3164 Keyword = DepTST->getKeyword();
3165 else
3166 return false;
3168 return TypeWithKeyword::KeywordIsTagTypeKind(Keyword);
3171 const char *Type::getTypeClassName() const {
3172 switch (TypeBits.TC) {
3173 #define ABSTRACT_TYPE(Derived, Base)
3174 #define TYPE(Derived, Base) case Derived: return #Derived;
3175 #include "clang/AST/TypeNodes.inc"
3178 llvm_unreachable("Invalid type class.");
3181 StringRef BuiltinType::getName(const PrintingPolicy &Policy) const {
3182 switch (getKind()) {
3183 case Void:
3184 return "void";
3185 case Bool:
3186 return Policy.Bool ? "bool" : "_Bool";
3187 case Char_S:
3188 return "char";
3189 case Char_U:
3190 return "char";
3191 case SChar:
3192 return "signed char";
3193 case Short:
3194 return "short";
3195 case Int:
3196 return "int";
3197 case Long:
3198 return "long";
3199 case LongLong:
3200 return "long long";
3201 case Int128:
3202 return "__int128";
3203 case UChar:
3204 return "unsigned char";
3205 case UShort:
3206 return "unsigned short";
3207 case UInt:
3208 return "unsigned int";
3209 case ULong:
3210 return "unsigned long";
3211 case ULongLong:
3212 return "unsigned long long";
3213 case UInt128:
3214 return "unsigned __int128";
3215 case Half:
3216 return Policy.Half ? "half" : "__fp16";
3217 case BFloat16:
3218 return "__bf16";
3219 case Float:
3220 return "float";
3221 case Double:
3222 return "double";
3223 case LongDouble:
3224 return "long double";
3225 case ShortAccum:
3226 return "short _Accum";
3227 case Accum:
3228 return "_Accum";
3229 case LongAccum:
3230 return "long _Accum";
3231 case UShortAccum:
3232 return "unsigned short _Accum";
3233 case UAccum:
3234 return "unsigned _Accum";
3235 case ULongAccum:
3236 return "unsigned long _Accum";
3237 case BuiltinType::ShortFract:
3238 return "short _Fract";
3239 case BuiltinType::Fract:
3240 return "_Fract";
3241 case BuiltinType::LongFract:
3242 return "long _Fract";
3243 case BuiltinType::UShortFract:
3244 return "unsigned short _Fract";
3245 case BuiltinType::UFract:
3246 return "unsigned _Fract";
3247 case BuiltinType::ULongFract:
3248 return "unsigned long _Fract";
3249 case BuiltinType::SatShortAccum:
3250 return "_Sat short _Accum";
3251 case BuiltinType::SatAccum:
3252 return "_Sat _Accum";
3253 case BuiltinType::SatLongAccum:
3254 return "_Sat long _Accum";
3255 case BuiltinType::SatUShortAccum:
3256 return "_Sat unsigned short _Accum";
3257 case BuiltinType::SatUAccum:
3258 return "_Sat unsigned _Accum";
3259 case BuiltinType::SatULongAccum:
3260 return "_Sat unsigned long _Accum";
3261 case BuiltinType::SatShortFract:
3262 return "_Sat short _Fract";
3263 case BuiltinType::SatFract:
3264 return "_Sat _Fract";
3265 case BuiltinType::SatLongFract:
3266 return "_Sat long _Fract";
3267 case BuiltinType::SatUShortFract:
3268 return "_Sat unsigned short _Fract";
3269 case BuiltinType::SatUFract:
3270 return "_Sat unsigned _Fract";
3271 case BuiltinType::SatULongFract:
3272 return "_Sat unsigned long _Fract";
3273 case Float16:
3274 return "_Float16";
3275 case Float128:
3276 return "__float128";
3277 case Ibm128:
3278 return "__ibm128";
3279 case WChar_S:
3280 case WChar_U:
3281 return Policy.MSWChar ? "__wchar_t" : "wchar_t";
3282 case Char8:
3283 return "char8_t";
3284 case Char16:
3285 return "char16_t";
3286 case Char32:
3287 return "char32_t";
3288 case NullPtr:
3289 return Policy.NullptrTypeInNamespace ? "std::nullptr_t" : "nullptr_t";
3290 case Overload:
3291 return "<overloaded function type>";
3292 case BoundMember:
3293 return "<bound member function type>";
3294 case PseudoObject:
3295 return "<pseudo-object type>";
3296 case Dependent:
3297 return "<dependent type>";
3298 case UnknownAny:
3299 return "<unknown type>";
3300 case ARCUnbridgedCast:
3301 return "<ARC unbridged cast type>";
3302 case BuiltinFn:
3303 return "<builtin fn type>";
3304 case ObjCId:
3305 return "id";
3306 case ObjCClass:
3307 return "Class";
3308 case ObjCSel:
3309 return "SEL";
3310 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
3311 case Id: \
3312 return "__" #Access " " #ImgType "_t";
3313 #include "clang/Basic/OpenCLImageTypes.def"
3314 case OCLSampler:
3315 return "sampler_t";
3316 case OCLEvent:
3317 return "event_t";
3318 case OCLClkEvent:
3319 return "clk_event_t";
3320 case OCLQueue:
3321 return "queue_t";
3322 case OCLReserveID:
3323 return "reserve_id_t";
3324 case IncompleteMatrixIdx:
3325 return "<incomplete matrix index type>";
3326 case OMPArraySection:
3327 return "<OpenMP array section type>";
3328 case OMPArrayShaping:
3329 return "<OpenMP array shaping type>";
3330 case OMPIterator:
3331 return "<OpenMP iterator type>";
3332 #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
3333 case Id: \
3334 return #ExtType;
3335 #include "clang/Basic/OpenCLExtensionTypes.def"
3336 #define SVE_TYPE(Name, Id, SingletonId) \
3337 case Id: \
3338 return Name;
3339 #include "clang/Basic/AArch64SVEACLETypes.def"
3340 #define PPC_VECTOR_TYPE(Name, Id, Size) \
3341 case Id: \
3342 return #Name;
3343 #include "clang/Basic/PPCTypes.def"
3344 #define RVV_TYPE(Name, Id, SingletonId) \
3345 case Id: \
3346 return Name;
3347 #include "clang/Basic/RISCVVTypes.def"
3348 #define WASM_TYPE(Name, Id, SingletonId) \
3349 case Id: \
3350 return Name;
3351 #include "clang/Basic/WebAssemblyReferenceTypes.def"
3354 llvm_unreachable("Invalid builtin type.");
3357 QualType QualType::getNonPackExpansionType() const {
3358 // We never wrap type sugar around a PackExpansionType.
3359 if (auto *PET = dyn_cast<PackExpansionType>(getTypePtr()))
3360 return PET->getPattern();
3361 return *this;
3364 QualType QualType::getNonLValueExprType(const ASTContext &Context) const {
3365 if (const auto *RefType = getTypePtr()->getAs<ReferenceType>())
3366 return RefType->getPointeeType();
3368 // C++0x [basic.lval]:
3369 // Class prvalues can have cv-qualified types; non-class prvalues always
3370 // have cv-unqualified types.
3372 // See also C99 6.3.2.1p2.
3373 if (!Context.getLangOpts().CPlusPlus ||
3374 (!getTypePtr()->isDependentType() && !getTypePtr()->isRecordType()))
3375 return getUnqualifiedType();
3377 return *this;
3380 StringRef FunctionType::getNameForCallConv(CallingConv CC) {
3381 switch (CC) {
3382 case CC_C: return "cdecl";
3383 case CC_X86StdCall: return "stdcall";
3384 case CC_X86FastCall: return "fastcall";
3385 case CC_X86ThisCall: return "thiscall";
3386 case CC_X86Pascal: return "pascal";
3387 case CC_X86VectorCall: return "vectorcall";
3388 case CC_Win64: return "ms_abi";
3389 case CC_X86_64SysV: return "sysv_abi";
3390 case CC_X86RegCall : return "regcall";
3391 case CC_AAPCS: return "aapcs";
3392 case CC_AAPCS_VFP: return "aapcs-vfp";
3393 case CC_AArch64VectorCall: return "aarch64_vector_pcs";
3394 case CC_AArch64SVEPCS: return "aarch64_sve_pcs";
3395 case CC_AMDGPUKernelCall: return "amdgpu_kernel";
3396 case CC_IntelOclBicc: return "intel_ocl_bicc";
3397 case CC_SpirFunction: return "spir_function";
3398 case CC_OpenCLKernel: return "opencl_kernel";
3399 case CC_Swift: return "swiftcall";
3400 case CC_SwiftAsync: return "swiftasynccall";
3401 case CC_PreserveMost: return "preserve_most";
3402 case CC_PreserveAll: return "preserve_all";
3403 case CC_M68kRTD: return "m68k_rtd";
3406 llvm_unreachable("Invalid calling convention.");
3409 FunctionProtoType::FunctionProtoType(QualType result, ArrayRef<QualType> params,
3410 QualType canonical,
3411 const ExtProtoInfo &epi)
3412 : FunctionType(FunctionProto, result, canonical, result->getDependence(),
3413 epi.ExtInfo) {
3414 FunctionTypeBits.FastTypeQuals = epi.TypeQuals.getFastQualifiers();
3415 FunctionTypeBits.RefQualifier = epi.RefQualifier;
3416 FunctionTypeBits.NumParams = params.size();
3417 assert(getNumParams() == params.size() && "NumParams overflow!");
3418 FunctionTypeBits.ExceptionSpecType = epi.ExceptionSpec.Type;
3419 FunctionTypeBits.HasExtParameterInfos = !!epi.ExtParameterInfos;
3420 FunctionTypeBits.Variadic = epi.Variadic;
3421 FunctionTypeBits.HasTrailingReturn = epi.HasTrailingReturn;
3423 if (epi.requiresFunctionProtoTypeExtraBitfields()) {
3424 FunctionTypeBits.HasExtraBitfields = true;
3425 auto &ExtraBits = *getTrailingObjects<FunctionTypeExtraBitfields>();
3426 ExtraBits = FunctionTypeExtraBitfields();
3427 } else {
3428 FunctionTypeBits.HasExtraBitfields = false;
3432 // Fill in the trailing argument array.
3433 auto *argSlot = getTrailingObjects<QualType>();
3434 for (unsigned i = 0; i != getNumParams(); ++i) {
3435 addDependence(params[i]->getDependence() &
3436 ~TypeDependence::VariablyModified);
3437 argSlot[i] = params[i];
3440 // Propagate the SME ACLE attributes.
3441 if (epi.AArch64SMEAttributes != SME_NormalFunction) {
3442 auto &ExtraBits = *getTrailingObjects<FunctionTypeExtraBitfields>();
3443 assert(epi.AArch64SMEAttributes <= SME_AttributeMask &&
3444 "Not enough bits to encode SME attributes");
3445 ExtraBits.AArch64SMEAttributes = epi.AArch64SMEAttributes;
3448 // Fill in the exception type array if present.
3449 if (getExceptionSpecType() == EST_Dynamic) {
3450 auto &ExtraBits = *getTrailingObjects<FunctionTypeExtraBitfields>();
3451 size_t NumExceptions = epi.ExceptionSpec.Exceptions.size();
3452 assert(NumExceptions <= 1023 && "Not enough bits to encode exceptions");
3453 ExtraBits.NumExceptionType = NumExceptions;
3455 assert(hasExtraBitfields() && "missing trailing extra bitfields!");
3456 auto *exnSlot =
3457 reinterpret_cast<QualType *>(getTrailingObjects<ExceptionType>());
3458 unsigned I = 0;
3459 for (QualType ExceptionType : epi.ExceptionSpec.Exceptions) {
3460 // Note that, before C++17, a dependent exception specification does
3461 // *not* make a type dependent; it's not even part of the C++ type
3462 // system.
3463 addDependence(
3464 ExceptionType->getDependence() &
3465 (TypeDependence::Instantiation | TypeDependence::UnexpandedPack));
3467 exnSlot[I++] = ExceptionType;
3470 // Fill in the Expr * in the exception specification if present.
3471 else if (isComputedNoexcept(getExceptionSpecType())) {
3472 assert(epi.ExceptionSpec.NoexceptExpr && "computed noexcept with no expr");
3473 assert((getExceptionSpecType() == EST_DependentNoexcept) ==
3474 epi.ExceptionSpec.NoexceptExpr->isValueDependent());
3476 // Store the noexcept expression and context.
3477 *getTrailingObjects<Expr *>() = epi.ExceptionSpec.NoexceptExpr;
3479 addDependence(
3480 toTypeDependence(epi.ExceptionSpec.NoexceptExpr->getDependence()) &
3481 (TypeDependence::Instantiation | TypeDependence::UnexpandedPack));
3483 // Fill in the FunctionDecl * in the exception specification if present.
3484 else if (getExceptionSpecType() == EST_Uninstantiated) {
3485 // Store the function decl from which we will resolve our
3486 // exception specification.
3487 auto **slot = getTrailingObjects<FunctionDecl *>();
3488 slot[0] = epi.ExceptionSpec.SourceDecl;
3489 slot[1] = epi.ExceptionSpec.SourceTemplate;
3490 // This exception specification doesn't make the type dependent, because
3491 // it's not instantiated as part of instantiating the type.
3492 } else if (getExceptionSpecType() == EST_Unevaluated) {
3493 // Store the function decl from which we will resolve our
3494 // exception specification.
3495 auto **slot = getTrailingObjects<FunctionDecl *>();
3496 slot[0] = epi.ExceptionSpec.SourceDecl;
3499 // If this is a canonical type, and its exception specification is dependent,
3500 // then it's a dependent type. This only happens in C++17 onwards.
3501 if (isCanonicalUnqualified()) {
3502 if (getExceptionSpecType() == EST_Dynamic ||
3503 getExceptionSpecType() == EST_DependentNoexcept) {
3504 assert(hasDependentExceptionSpec() && "type should not be canonical");
3505 addDependence(TypeDependence::DependentInstantiation);
3507 } else if (getCanonicalTypeInternal()->isDependentType()) {
3508 // Ask our canonical type whether our exception specification was dependent.
3509 addDependence(TypeDependence::DependentInstantiation);
3512 // Fill in the extra parameter info if present.
3513 if (epi.ExtParameterInfos) {
3514 auto *extParamInfos = getTrailingObjects<ExtParameterInfo>();
3515 for (unsigned i = 0; i != getNumParams(); ++i)
3516 extParamInfos[i] = epi.ExtParameterInfos[i];
3519 if (epi.TypeQuals.hasNonFastQualifiers()) {
3520 FunctionTypeBits.HasExtQuals = 1;
3521 *getTrailingObjects<Qualifiers>() = epi.TypeQuals;
3522 } else {
3523 FunctionTypeBits.HasExtQuals = 0;
3526 // Fill in the Ellipsis location info if present.
3527 if (epi.Variadic) {
3528 auto &EllipsisLoc = *getTrailingObjects<SourceLocation>();
3529 EllipsisLoc = epi.EllipsisLoc;
3533 bool FunctionProtoType::hasDependentExceptionSpec() const {
3534 if (Expr *NE = getNoexceptExpr())
3535 return NE->isValueDependent();
3536 for (QualType ET : exceptions())
3537 // A pack expansion with a non-dependent pattern is still dependent,
3538 // because we don't know whether the pattern is in the exception spec
3539 // or not (that depends on whether the pack has 0 expansions).
3540 if (ET->isDependentType() || ET->getAs<PackExpansionType>())
3541 return true;
3542 return false;
3545 bool FunctionProtoType::hasInstantiationDependentExceptionSpec() const {
3546 if (Expr *NE = getNoexceptExpr())
3547 return NE->isInstantiationDependent();
3548 for (QualType ET : exceptions())
3549 if (ET->isInstantiationDependentType())
3550 return true;
3551 return false;
3554 CanThrowResult FunctionProtoType::canThrow() const {
3555 switch (getExceptionSpecType()) {
3556 case EST_Unparsed:
3557 case EST_Unevaluated:
3558 llvm_unreachable("should not call this with unresolved exception specs");
3560 case EST_DynamicNone:
3561 case EST_BasicNoexcept:
3562 case EST_NoexceptTrue:
3563 case EST_NoThrow:
3564 return CT_Cannot;
3566 case EST_None:
3567 case EST_MSAny:
3568 case EST_NoexceptFalse:
3569 return CT_Can;
3571 case EST_Dynamic:
3572 // A dynamic exception specification is throwing unless every exception
3573 // type is an (unexpanded) pack expansion type.
3574 for (unsigned I = 0; I != getNumExceptions(); ++I)
3575 if (!getExceptionType(I)->getAs<PackExpansionType>())
3576 return CT_Can;
3577 return CT_Dependent;
3579 case EST_Uninstantiated:
3580 case EST_DependentNoexcept:
3581 return CT_Dependent;
3584 llvm_unreachable("unexpected exception specification kind");
3587 bool FunctionProtoType::isTemplateVariadic() const {
3588 for (unsigned ArgIdx = getNumParams(); ArgIdx; --ArgIdx)
3589 if (isa<PackExpansionType>(getParamType(ArgIdx - 1)))
3590 return true;
3592 return false;
3595 void FunctionProtoType::Profile(llvm::FoldingSetNodeID &ID, QualType Result,
3596 const QualType *ArgTys, unsigned NumParams,
3597 const ExtProtoInfo &epi,
3598 const ASTContext &Context, bool Canonical) {
3599 // We have to be careful not to get ambiguous profile encodings.
3600 // Note that valid type pointers are never ambiguous with anything else.
3602 // The encoding grammar begins:
3603 // type type* bool int bool
3604 // If that final bool is true, then there is a section for the EH spec:
3605 // bool type*
3606 // This is followed by an optional "consumed argument" section of the
3607 // same length as the first type sequence:
3608 // bool*
3609 // This is followed by the ext info:
3610 // int
3611 // Finally we have a trailing return type flag (bool)
3612 // combined with AArch64 SME Attributes, to save space:
3613 // int
3615 // There is no ambiguity between the consumed arguments and an empty EH
3616 // spec because of the leading 'bool' which unambiguously indicates
3617 // whether the following bool is the EH spec or part of the arguments.
3619 ID.AddPointer(Result.getAsOpaquePtr());
3620 for (unsigned i = 0; i != NumParams; ++i)
3621 ID.AddPointer(ArgTys[i].getAsOpaquePtr());
3622 // This method is relatively performance sensitive, so as a performance
3623 // shortcut, use one AddInteger call instead of four for the next four
3624 // fields.
3625 assert(!(unsigned(epi.Variadic) & ~1) &&
3626 !(unsigned(epi.RefQualifier) & ~3) &&
3627 !(unsigned(epi.ExceptionSpec.Type) & ~15) &&
3628 "Values larger than expected.");
3629 ID.AddInteger(unsigned(epi.Variadic) +
3630 (epi.RefQualifier << 1) +
3631 (epi.ExceptionSpec.Type << 3));
3632 ID.Add(epi.TypeQuals);
3633 if (epi.ExceptionSpec.Type == EST_Dynamic) {
3634 for (QualType Ex : epi.ExceptionSpec.Exceptions)
3635 ID.AddPointer(Ex.getAsOpaquePtr());
3636 } else if (isComputedNoexcept(epi.ExceptionSpec.Type)) {
3637 epi.ExceptionSpec.NoexceptExpr->Profile(ID, Context, Canonical);
3638 } else if (epi.ExceptionSpec.Type == EST_Uninstantiated ||
3639 epi.ExceptionSpec.Type == EST_Unevaluated) {
3640 ID.AddPointer(epi.ExceptionSpec.SourceDecl->getCanonicalDecl());
3642 if (epi.ExtParameterInfos) {
3643 for (unsigned i = 0; i != NumParams; ++i)
3644 ID.AddInteger(epi.ExtParameterInfos[i].getOpaqueValue());
3647 epi.ExtInfo.Profile(ID);
3648 ID.AddInteger((epi.AArch64SMEAttributes << 1) | epi.HasTrailingReturn);
3651 void FunctionProtoType::Profile(llvm::FoldingSetNodeID &ID,
3652 const ASTContext &Ctx) {
3653 Profile(ID, getReturnType(), param_type_begin(), getNumParams(),
3654 getExtProtoInfo(), Ctx, isCanonicalUnqualified());
3657 TypedefType::TypedefType(TypeClass tc, const TypedefNameDecl *D,
3658 QualType Underlying, QualType can)
3659 : Type(tc, can, toSemanticDependence(can->getDependence())),
3660 Decl(const_cast<TypedefNameDecl *>(D)) {
3661 assert(!isa<TypedefType>(can) && "Invalid canonical type");
3662 TypedefBits.hasTypeDifferentFromDecl = !Underlying.isNull();
3663 if (!typeMatchesDecl())
3664 *getTrailingObjects<QualType>() = Underlying;
3667 QualType TypedefType::desugar() const {
3668 return typeMatchesDecl() ? Decl->getUnderlyingType()
3669 : *getTrailingObjects<QualType>();
3672 UsingType::UsingType(const UsingShadowDecl *Found, QualType Underlying,
3673 QualType Canon)
3674 : Type(Using, Canon, toSemanticDependence(Canon->getDependence())),
3675 Found(const_cast<UsingShadowDecl *>(Found)) {
3676 UsingBits.hasTypeDifferentFromDecl = !Underlying.isNull();
3677 if (!typeMatchesDecl())
3678 *getTrailingObjects<QualType>() = Underlying;
3681 QualType UsingType::getUnderlyingType() const {
3682 return typeMatchesDecl()
3683 ? QualType(
3684 cast<TypeDecl>(Found->getTargetDecl())->getTypeForDecl(), 0)
3685 : *getTrailingObjects<QualType>();
3688 QualType MacroQualifiedType::desugar() const { return getUnderlyingType(); }
3690 QualType MacroQualifiedType::getModifiedType() const {
3691 // Step over MacroQualifiedTypes from the same macro to find the type
3692 // ultimately qualified by the macro qualifier.
3693 QualType Inner = cast<AttributedType>(getUnderlyingType())->getModifiedType();
3694 while (auto *InnerMQT = dyn_cast<MacroQualifiedType>(Inner)) {
3695 if (InnerMQT->getMacroIdentifier() != getMacroIdentifier())
3696 break;
3697 Inner = InnerMQT->getModifiedType();
3699 return Inner;
3702 TypeOfExprType::TypeOfExprType(Expr *E, TypeOfKind Kind, QualType Can)
3703 : Type(TypeOfExpr,
3704 // We have to protect against 'Can' being invalid through its
3705 // default argument.
3706 Kind == TypeOfKind::Unqualified && !Can.isNull()
3707 ? Can.getAtomicUnqualifiedType()
3708 : Can,
3709 toTypeDependence(E->getDependence()) |
3710 (E->getType()->getDependence() &
3711 TypeDependence::VariablyModified)),
3712 TOExpr(E) {
3713 TypeOfBits.IsUnqual = Kind == TypeOfKind::Unqualified;
3716 bool TypeOfExprType::isSugared() const {
3717 return !TOExpr->isTypeDependent();
3720 QualType TypeOfExprType::desugar() const {
3721 if (isSugared()) {
3722 QualType QT = getUnderlyingExpr()->getType();
3723 return TypeOfBits.IsUnqual ? QT.getAtomicUnqualifiedType() : QT;
3725 return QualType(this, 0);
3728 void DependentTypeOfExprType::Profile(llvm::FoldingSetNodeID &ID,
3729 const ASTContext &Context, Expr *E,
3730 bool IsUnqual) {
3731 E->Profile(ID, Context, true);
3732 ID.AddBoolean(IsUnqual);
3735 DecltypeType::DecltypeType(Expr *E, QualType underlyingType, QualType can)
3736 // C++11 [temp.type]p2: "If an expression e involves a template parameter,
3737 // decltype(e) denotes a unique dependent type." Hence a decltype type is
3738 // type-dependent even if its expression is only instantiation-dependent.
3739 : Type(Decltype, can,
3740 toTypeDependence(E->getDependence()) |
3741 (E->isInstantiationDependent() ? TypeDependence::Dependent
3742 : TypeDependence::None) |
3743 (E->getType()->getDependence() &
3744 TypeDependence::VariablyModified)),
3745 E(E), UnderlyingType(underlyingType) {}
3747 bool DecltypeType::isSugared() const { return !E->isInstantiationDependent(); }
3749 QualType DecltypeType::desugar() const {
3750 if (isSugared())
3751 return getUnderlyingType();
3753 return QualType(this, 0);
3756 DependentDecltypeType::DependentDecltypeType(Expr *E, QualType UnderlyingType)
3757 : DecltypeType(E, UnderlyingType) {}
3759 void DependentDecltypeType::Profile(llvm::FoldingSetNodeID &ID,
3760 const ASTContext &Context, Expr *E) {
3761 E->Profile(ID, Context, true);
3764 UnaryTransformType::UnaryTransformType(QualType BaseType,
3765 QualType UnderlyingType, UTTKind UKind,
3766 QualType CanonicalType)
3767 : Type(UnaryTransform, CanonicalType, BaseType->getDependence()),
3768 BaseType(BaseType), UnderlyingType(UnderlyingType), UKind(UKind) {}
3770 DependentUnaryTransformType::DependentUnaryTransformType(const ASTContext &C,
3771 QualType BaseType,
3772 UTTKind UKind)
3773 : UnaryTransformType(BaseType, C.DependentTy, UKind, QualType()) {}
3775 TagType::TagType(TypeClass TC, const TagDecl *D, QualType can)
3776 : Type(TC, can,
3777 D->isDependentType() ? TypeDependence::DependentInstantiation
3778 : TypeDependence::None),
3779 decl(const_cast<TagDecl *>(D)) {}
3781 static TagDecl *getInterestingTagDecl(TagDecl *decl) {
3782 for (auto *I : decl->redecls()) {
3783 if (I->isCompleteDefinition() || I->isBeingDefined())
3784 return I;
3786 // If there's no definition (not even in progress), return what we have.
3787 return decl;
3790 TagDecl *TagType::getDecl() const {
3791 return getInterestingTagDecl(decl);
3794 bool TagType::isBeingDefined() const {
3795 return getDecl()->isBeingDefined();
3798 bool RecordType::hasConstFields() const {
3799 std::vector<const RecordType*> RecordTypeList;
3800 RecordTypeList.push_back(this);
3801 unsigned NextToCheckIndex = 0;
3803 while (RecordTypeList.size() > NextToCheckIndex) {
3804 for (FieldDecl *FD :
3805 RecordTypeList[NextToCheckIndex]->getDecl()->fields()) {
3806 QualType FieldTy = FD->getType();
3807 if (FieldTy.isConstQualified())
3808 return true;
3809 FieldTy = FieldTy.getCanonicalType();
3810 if (const auto *FieldRecTy = FieldTy->getAs<RecordType>()) {
3811 if (!llvm::is_contained(RecordTypeList, FieldRecTy))
3812 RecordTypeList.push_back(FieldRecTy);
3815 ++NextToCheckIndex;
3817 return false;
3820 bool AttributedType::isQualifier() const {
3821 // FIXME: Generate this with TableGen.
3822 switch (getAttrKind()) {
3823 // These are type qualifiers in the traditional C sense: they annotate
3824 // something about a specific value/variable of a type. (They aren't
3825 // always part of the canonical type, though.)
3826 case attr::ObjCGC:
3827 case attr::ObjCOwnership:
3828 case attr::ObjCInertUnsafeUnretained:
3829 case attr::TypeNonNull:
3830 case attr::TypeNullable:
3831 case attr::TypeNullableResult:
3832 case attr::TypeNullUnspecified:
3833 case attr::LifetimeBound:
3834 case attr::AddressSpace:
3835 return true;
3837 // All other type attributes aren't qualifiers; they rewrite the modified
3838 // type to be a semantically different type.
3839 default:
3840 return false;
3844 bool AttributedType::isMSTypeSpec() const {
3845 // FIXME: Generate this with TableGen?
3846 switch (getAttrKind()) {
3847 default: return false;
3848 case attr::Ptr32:
3849 case attr::Ptr64:
3850 case attr::SPtr:
3851 case attr::UPtr:
3852 return true;
3854 llvm_unreachable("invalid attr kind");
3857 bool AttributedType::isWebAssemblyFuncrefSpec() const {
3858 return getAttrKind() == attr::WebAssemblyFuncref;
3861 bool AttributedType::isCallingConv() const {
3862 // FIXME: Generate this with TableGen.
3863 switch (getAttrKind()) {
3864 default: return false;
3865 case attr::Pcs:
3866 case attr::CDecl:
3867 case attr::FastCall:
3868 case attr::StdCall:
3869 case attr::ThisCall:
3870 case attr::RegCall:
3871 case attr::SwiftCall:
3872 case attr::SwiftAsyncCall:
3873 case attr::VectorCall:
3874 case attr::AArch64VectorPcs:
3875 case attr::AArch64SVEPcs:
3876 case attr::AMDGPUKernelCall:
3877 case attr::Pascal:
3878 case attr::MSABI:
3879 case attr::SysVABI:
3880 case attr::IntelOclBicc:
3881 case attr::PreserveMost:
3882 case attr::PreserveAll:
3883 case attr::M68kRTD:
3884 return true;
3886 llvm_unreachable("invalid attr kind");
3889 CXXRecordDecl *InjectedClassNameType::getDecl() const {
3890 return cast<CXXRecordDecl>(getInterestingTagDecl(Decl));
3893 IdentifierInfo *TemplateTypeParmType::getIdentifier() const {
3894 return isCanonicalUnqualified() ? nullptr : getDecl()->getIdentifier();
3897 static const TemplateTypeParmDecl *getReplacedParameter(Decl *D,
3898 unsigned Index) {
3899 if (const auto *TTP = dyn_cast<TemplateTypeParmDecl>(D))
3900 return TTP;
3901 return cast<TemplateTypeParmDecl>(
3902 getReplacedTemplateParameterList(D)->getParam(Index));
3905 SubstTemplateTypeParmType::SubstTemplateTypeParmType(
3906 QualType Replacement, Decl *AssociatedDecl, unsigned Index,
3907 std::optional<unsigned> PackIndex)
3908 : Type(SubstTemplateTypeParm, Replacement.getCanonicalType(),
3909 Replacement->getDependence()),
3910 AssociatedDecl(AssociatedDecl) {
3911 SubstTemplateTypeParmTypeBits.HasNonCanonicalUnderlyingType =
3912 Replacement != getCanonicalTypeInternal();
3913 if (SubstTemplateTypeParmTypeBits.HasNonCanonicalUnderlyingType)
3914 *getTrailingObjects<QualType>() = Replacement;
3916 SubstTemplateTypeParmTypeBits.Index = Index;
3917 SubstTemplateTypeParmTypeBits.PackIndex = PackIndex ? *PackIndex + 1 : 0;
3918 assert(AssociatedDecl != nullptr);
3921 const TemplateTypeParmDecl *
3922 SubstTemplateTypeParmType::getReplacedParameter() const {
3923 return ::getReplacedParameter(getAssociatedDecl(), getIndex());
3926 SubstTemplateTypeParmPackType::SubstTemplateTypeParmPackType(
3927 QualType Canon, Decl *AssociatedDecl, unsigned Index, bool Final,
3928 const TemplateArgument &ArgPack)
3929 : Type(SubstTemplateTypeParmPack, Canon,
3930 TypeDependence::DependentInstantiation |
3931 TypeDependence::UnexpandedPack),
3932 Arguments(ArgPack.pack_begin()),
3933 AssociatedDeclAndFinal(AssociatedDecl, Final) {
3934 SubstTemplateTypeParmPackTypeBits.Index = Index;
3935 SubstTemplateTypeParmPackTypeBits.NumArgs = ArgPack.pack_size();
3936 assert(AssociatedDecl != nullptr);
3939 Decl *SubstTemplateTypeParmPackType::getAssociatedDecl() const {
3940 return AssociatedDeclAndFinal.getPointer();
3943 bool SubstTemplateTypeParmPackType::getFinal() const {
3944 return AssociatedDeclAndFinal.getInt();
3947 const TemplateTypeParmDecl *
3948 SubstTemplateTypeParmPackType::getReplacedParameter() const {
3949 return ::getReplacedParameter(getAssociatedDecl(), getIndex());
3952 IdentifierInfo *SubstTemplateTypeParmPackType::getIdentifier() const {
3953 return getReplacedParameter()->getIdentifier();
3956 TemplateArgument SubstTemplateTypeParmPackType::getArgumentPack() const {
3957 return TemplateArgument(llvm::ArrayRef(Arguments, getNumArgs()));
3960 void SubstTemplateTypeParmPackType::Profile(llvm::FoldingSetNodeID &ID) {
3961 Profile(ID, getAssociatedDecl(), getIndex(), getFinal(), getArgumentPack());
3964 void SubstTemplateTypeParmPackType::Profile(llvm::FoldingSetNodeID &ID,
3965 const Decl *AssociatedDecl,
3966 unsigned Index, bool Final,
3967 const TemplateArgument &ArgPack) {
3968 ID.AddPointer(AssociatedDecl);
3969 ID.AddInteger(Index);
3970 ID.AddBoolean(Final);
3971 ID.AddInteger(ArgPack.pack_size());
3972 for (const auto &P : ArgPack.pack_elements())
3973 ID.AddPointer(P.getAsType().getAsOpaquePtr());
3976 bool TemplateSpecializationType::anyDependentTemplateArguments(
3977 const TemplateArgumentListInfo &Args, ArrayRef<TemplateArgument> Converted) {
3978 return anyDependentTemplateArguments(Args.arguments(), Converted);
3981 bool TemplateSpecializationType::anyDependentTemplateArguments(
3982 ArrayRef<TemplateArgumentLoc> Args, ArrayRef<TemplateArgument> Converted) {
3983 for (const TemplateArgument &Arg : Converted)
3984 if (Arg.isDependent())
3985 return true;
3986 return false;
3989 bool TemplateSpecializationType::anyInstantiationDependentTemplateArguments(
3990 ArrayRef<TemplateArgumentLoc> Args) {
3991 for (const TemplateArgumentLoc &ArgLoc : Args) {
3992 if (ArgLoc.getArgument().isInstantiationDependent())
3993 return true;
3995 return false;
3998 TemplateSpecializationType::TemplateSpecializationType(
3999 TemplateName T, ArrayRef<TemplateArgument> Args, QualType Canon,
4000 QualType AliasedType)
4001 : Type(TemplateSpecialization, Canon.isNull() ? QualType(this, 0) : Canon,
4002 (Canon.isNull()
4003 ? TypeDependence::DependentInstantiation
4004 : toSemanticDependence(Canon->getDependence())) |
4005 (toTypeDependence(T.getDependence()) &
4006 TypeDependence::UnexpandedPack)),
4007 Template(T) {
4008 TemplateSpecializationTypeBits.NumArgs = Args.size();
4009 TemplateSpecializationTypeBits.TypeAlias = !AliasedType.isNull();
4011 assert(!T.getAsDependentTemplateName() &&
4012 "Use DependentTemplateSpecializationType for dependent template-name");
4013 assert((T.getKind() == TemplateName::Template ||
4014 T.getKind() == TemplateName::SubstTemplateTemplateParm ||
4015 T.getKind() == TemplateName::SubstTemplateTemplateParmPack ||
4016 T.getKind() == TemplateName::UsingTemplate) &&
4017 "Unexpected template name for TemplateSpecializationType");
4019 auto *TemplateArgs = reinterpret_cast<TemplateArgument *>(this + 1);
4020 for (const TemplateArgument &Arg : Args) {
4021 // Update instantiation-dependent, variably-modified, and error bits.
4022 // If the canonical type exists and is non-dependent, the template
4023 // specialization type can be non-dependent even if one of the type
4024 // arguments is. Given:
4025 // template<typename T> using U = int;
4026 // U<T> is always non-dependent, irrespective of the type T.
4027 // However, U<Ts> contains an unexpanded parameter pack, even though
4028 // its expansion (and thus its desugared type) doesn't.
4029 addDependence(toTypeDependence(Arg.getDependence()) &
4030 ~TypeDependence::Dependent);
4031 if (Arg.getKind() == TemplateArgument::Type)
4032 addDependence(Arg.getAsType()->getDependence() &
4033 TypeDependence::VariablyModified);
4034 new (TemplateArgs++) TemplateArgument(Arg);
4037 // Store the aliased type if this is a type alias template specialization.
4038 if (isTypeAlias()) {
4039 auto *Begin = reinterpret_cast<TemplateArgument *>(this + 1);
4040 *reinterpret_cast<QualType *>(Begin + Args.size()) = AliasedType;
4044 QualType TemplateSpecializationType::getAliasedType() const {
4045 assert(isTypeAlias() && "not a type alias template specialization");
4046 return *reinterpret_cast<const QualType *>(template_arguments().end());
4049 void TemplateSpecializationType::Profile(llvm::FoldingSetNodeID &ID,
4050 const ASTContext &Ctx) {
4051 Profile(ID, Template, template_arguments(), Ctx);
4052 if (isTypeAlias())
4053 getAliasedType().Profile(ID);
4056 void
4057 TemplateSpecializationType::Profile(llvm::FoldingSetNodeID &ID,
4058 TemplateName T,
4059 ArrayRef<TemplateArgument> Args,
4060 const ASTContext &Context) {
4061 T.Profile(ID);
4062 for (const TemplateArgument &Arg : Args)
4063 Arg.Profile(ID, Context);
4066 QualType
4067 QualifierCollector::apply(const ASTContext &Context, QualType QT) const {
4068 if (!hasNonFastQualifiers())
4069 return QT.withFastQualifiers(getFastQualifiers());
4071 return Context.getQualifiedType(QT, *this);
4074 QualType
4075 QualifierCollector::apply(const ASTContext &Context, const Type *T) const {
4076 if (!hasNonFastQualifiers())
4077 return QualType(T, getFastQualifiers());
4079 return Context.getQualifiedType(T, *this);
4082 void ObjCObjectTypeImpl::Profile(llvm::FoldingSetNodeID &ID,
4083 QualType BaseType,
4084 ArrayRef<QualType> typeArgs,
4085 ArrayRef<ObjCProtocolDecl *> protocols,
4086 bool isKindOf) {
4087 ID.AddPointer(BaseType.getAsOpaquePtr());
4088 ID.AddInteger(typeArgs.size());
4089 for (auto typeArg : typeArgs)
4090 ID.AddPointer(typeArg.getAsOpaquePtr());
4091 ID.AddInteger(protocols.size());
4092 for (auto *proto : protocols)
4093 ID.AddPointer(proto);
4094 ID.AddBoolean(isKindOf);
4097 void ObjCObjectTypeImpl::Profile(llvm::FoldingSetNodeID &ID) {
4098 Profile(ID, getBaseType(), getTypeArgsAsWritten(),
4099 llvm::ArrayRef(qual_begin(), getNumProtocols()),
4100 isKindOfTypeAsWritten());
4103 void ObjCTypeParamType::Profile(llvm::FoldingSetNodeID &ID,
4104 const ObjCTypeParamDecl *OTPDecl,
4105 QualType CanonicalType,
4106 ArrayRef<ObjCProtocolDecl *> protocols) {
4107 ID.AddPointer(OTPDecl);
4108 ID.AddPointer(CanonicalType.getAsOpaquePtr());
4109 ID.AddInteger(protocols.size());
4110 for (auto *proto : protocols)
4111 ID.AddPointer(proto);
4114 void ObjCTypeParamType::Profile(llvm::FoldingSetNodeID &ID) {
4115 Profile(ID, getDecl(), getCanonicalTypeInternal(),
4116 llvm::ArrayRef(qual_begin(), getNumProtocols()));
4119 namespace {
4121 /// The cached properties of a type.
4122 class CachedProperties {
4123 Linkage L;
4124 bool local;
4126 public:
4127 CachedProperties(Linkage L, bool local) : L(L), local(local) {}
4129 Linkage getLinkage() const { return L; }
4130 bool hasLocalOrUnnamedType() const { return local; }
4132 friend CachedProperties merge(CachedProperties L, CachedProperties R) {
4133 Linkage MergedLinkage = minLinkage(L.L, R.L);
4134 return CachedProperties(MergedLinkage, L.hasLocalOrUnnamedType() ||
4135 R.hasLocalOrUnnamedType());
4139 } // namespace
4141 static CachedProperties computeCachedProperties(const Type *T);
4143 namespace clang {
4145 /// The type-property cache. This is templated so as to be
4146 /// instantiated at an internal type to prevent unnecessary symbol
4147 /// leakage.
4148 template <class Private> class TypePropertyCache {
4149 public:
4150 static CachedProperties get(QualType T) {
4151 return get(T.getTypePtr());
4154 static CachedProperties get(const Type *T) {
4155 ensure(T);
4156 return CachedProperties(T->TypeBits.getLinkage(),
4157 T->TypeBits.hasLocalOrUnnamedType());
4160 static void ensure(const Type *T) {
4161 // If the cache is valid, we're okay.
4162 if (T->TypeBits.isCacheValid()) return;
4164 // If this type is non-canonical, ask its canonical type for the
4165 // relevant information.
4166 if (!T->isCanonicalUnqualified()) {
4167 const Type *CT = T->getCanonicalTypeInternal().getTypePtr();
4168 ensure(CT);
4169 T->TypeBits.CacheValid = true;
4170 T->TypeBits.CachedLinkage = CT->TypeBits.CachedLinkage;
4171 T->TypeBits.CachedLocalOrUnnamed = CT->TypeBits.CachedLocalOrUnnamed;
4172 return;
4175 // Compute the cached properties and then set the cache.
4176 CachedProperties Result = computeCachedProperties(T);
4177 T->TypeBits.CacheValid = true;
4178 T->TypeBits.CachedLinkage = Result.getLinkage();
4179 T->TypeBits.CachedLocalOrUnnamed = Result.hasLocalOrUnnamedType();
4183 } // namespace clang
4185 // Instantiate the friend template at a private class. In a
4186 // reasonable implementation, these symbols will be internal.
4187 // It is terrible that this is the best way to accomplish this.
4188 namespace {
4190 class Private {};
4192 } // namespace
4194 using Cache = TypePropertyCache<Private>;
4196 static CachedProperties computeCachedProperties(const Type *T) {
4197 switch (T->getTypeClass()) {
4198 #define TYPE(Class,Base)
4199 #define NON_CANONICAL_TYPE(Class,Base) case Type::Class:
4200 #include "clang/AST/TypeNodes.inc"
4201 llvm_unreachable("didn't expect a non-canonical type here");
4203 #define TYPE(Class,Base)
4204 #define DEPENDENT_TYPE(Class,Base) case Type::Class:
4205 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class,Base) case Type::Class:
4206 #include "clang/AST/TypeNodes.inc"
4207 // Treat instantiation-dependent types as external.
4208 if (!T->isInstantiationDependentType()) T->dump();
4209 assert(T->isInstantiationDependentType());
4210 return CachedProperties(ExternalLinkage, false);
4212 case Type::Auto:
4213 case Type::DeducedTemplateSpecialization:
4214 // Give non-deduced 'auto' types external linkage. We should only see them
4215 // here in error recovery.
4216 return CachedProperties(ExternalLinkage, false);
4218 case Type::BitInt:
4219 case Type::Builtin:
4220 // C++ [basic.link]p8:
4221 // A type is said to have linkage if and only if:
4222 // - it is a fundamental type (3.9.1); or
4223 return CachedProperties(ExternalLinkage, false);
4225 case Type::Record:
4226 case Type::Enum: {
4227 const TagDecl *Tag = cast<TagType>(T)->getDecl();
4229 // C++ [basic.link]p8:
4230 // - it is a class or enumeration type that is named (or has a name
4231 // for linkage purposes (7.1.3)) and the name has linkage; or
4232 // - it is a specialization of a class template (14); or
4233 Linkage L = Tag->getLinkageInternal();
4234 bool IsLocalOrUnnamed =
4235 Tag->getDeclContext()->isFunctionOrMethod() ||
4236 !Tag->hasNameForLinkage();
4237 return CachedProperties(L, IsLocalOrUnnamed);
4240 // C++ [basic.link]p8:
4241 // - it is a compound type (3.9.2) other than a class or enumeration,
4242 // compounded exclusively from types that have linkage; or
4243 case Type::Complex:
4244 return Cache::get(cast<ComplexType>(T)->getElementType());
4245 case Type::Pointer:
4246 return Cache::get(cast<PointerType>(T)->getPointeeType());
4247 case Type::BlockPointer:
4248 return Cache::get(cast<BlockPointerType>(T)->getPointeeType());
4249 case Type::LValueReference:
4250 case Type::RValueReference:
4251 return Cache::get(cast<ReferenceType>(T)->getPointeeType());
4252 case Type::MemberPointer: {
4253 const auto *MPT = cast<MemberPointerType>(T);
4254 return merge(Cache::get(MPT->getClass()),
4255 Cache::get(MPT->getPointeeType()));
4257 case Type::ConstantArray:
4258 case Type::IncompleteArray:
4259 case Type::VariableArray:
4260 return Cache::get(cast<ArrayType>(T)->getElementType());
4261 case Type::Vector:
4262 case Type::ExtVector:
4263 return Cache::get(cast<VectorType>(T)->getElementType());
4264 case Type::ConstantMatrix:
4265 return Cache::get(cast<ConstantMatrixType>(T)->getElementType());
4266 case Type::FunctionNoProto:
4267 return Cache::get(cast<FunctionType>(T)->getReturnType());
4268 case Type::FunctionProto: {
4269 const auto *FPT = cast<FunctionProtoType>(T);
4270 CachedProperties result = Cache::get(FPT->getReturnType());
4271 for (const auto &ai : FPT->param_types())
4272 result = merge(result, Cache::get(ai));
4273 return result;
4275 case Type::ObjCInterface: {
4276 Linkage L = cast<ObjCInterfaceType>(T)->getDecl()->getLinkageInternal();
4277 return CachedProperties(L, false);
4279 case Type::ObjCObject:
4280 return Cache::get(cast<ObjCObjectType>(T)->getBaseType());
4281 case Type::ObjCObjectPointer:
4282 return Cache::get(cast<ObjCObjectPointerType>(T)->getPointeeType());
4283 case Type::Atomic:
4284 return Cache::get(cast<AtomicType>(T)->getValueType());
4285 case Type::Pipe:
4286 return Cache::get(cast<PipeType>(T)->getElementType());
4289 llvm_unreachable("unhandled type class");
4292 /// Determine the linkage of this type.
4293 Linkage Type::getLinkage() const {
4294 Cache::ensure(this);
4295 return TypeBits.getLinkage();
4298 bool Type::hasUnnamedOrLocalType() const {
4299 Cache::ensure(this);
4300 return TypeBits.hasLocalOrUnnamedType();
4303 LinkageInfo LinkageComputer::computeTypeLinkageInfo(const Type *T) {
4304 switch (T->getTypeClass()) {
4305 #define TYPE(Class,Base)
4306 #define NON_CANONICAL_TYPE(Class,Base) case Type::Class:
4307 #include "clang/AST/TypeNodes.inc"
4308 llvm_unreachable("didn't expect a non-canonical type here");
4310 #define TYPE(Class,Base)
4311 #define DEPENDENT_TYPE(Class,Base) case Type::Class:
4312 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class,Base) case Type::Class:
4313 #include "clang/AST/TypeNodes.inc"
4314 // Treat instantiation-dependent types as external.
4315 assert(T->isInstantiationDependentType());
4316 return LinkageInfo::external();
4318 case Type::BitInt:
4319 case Type::Builtin:
4320 return LinkageInfo::external();
4322 case Type::Auto:
4323 case Type::DeducedTemplateSpecialization:
4324 return LinkageInfo::external();
4326 case Type::Record:
4327 case Type::Enum:
4328 return getDeclLinkageAndVisibility(cast<TagType>(T)->getDecl());
4330 case Type::Complex:
4331 return computeTypeLinkageInfo(cast<ComplexType>(T)->getElementType());
4332 case Type::Pointer:
4333 return computeTypeLinkageInfo(cast<PointerType>(T)->getPointeeType());
4334 case Type::BlockPointer:
4335 return computeTypeLinkageInfo(cast<BlockPointerType>(T)->getPointeeType());
4336 case Type::LValueReference:
4337 case Type::RValueReference:
4338 return computeTypeLinkageInfo(cast<ReferenceType>(T)->getPointeeType());
4339 case Type::MemberPointer: {
4340 const auto *MPT = cast<MemberPointerType>(T);
4341 LinkageInfo LV = computeTypeLinkageInfo(MPT->getClass());
4342 LV.merge(computeTypeLinkageInfo(MPT->getPointeeType()));
4343 return LV;
4345 case Type::ConstantArray:
4346 case Type::IncompleteArray:
4347 case Type::VariableArray:
4348 return computeTypeLinkageInfo(cast<ArrayType>(T)->getElementType());
4349 case Type::Vector:
4350 case Type::ExtVector:
4351 return computeTypeLinkageInfo(cast<VectorType>(T)->getElementType());
4352 case Type::ConstantMatrix:
4353 return computeTypeLinkageInfo(
4354 cast<ConstantMatrixType>(T)->getElementType());
4355 case Type::FunctionNoProto:
4356 return computeTypeLinkageInfo(cast<FunctionType>(T)->getReturnType());
4357 case Type::FunctionProto: {
4358 const auto *FPT = cast<FunctionProtoType>(T);
4359 LinkageInfo LV = computeTypeLinkageInfo(FPT->getReturnType());
4360 for (const auto &ai : FPT->param_types())
4361 LV.merge(computeTypeLinkageInfo(ai));
4362 return LV;
4364 case Type::ObjCInterface:
4365 return getDeclLinkageAndVisibility(cast<ObjCInterfaceType>(T)->getDecl());
4366 case Type::ObjCObject:
4367 return computeTypeLinkageInfo(cast<ObjCObjectType>(T)->getBaseType());
4368 case Type::ObjCObjectPointer:
4369 return computeTypeLinkageInfo(
4370 cast<ObjCObjectPointerType>(T)->getPointeeType());
4371 case Type::Atomic:
4372 return computeTypeLinkageInfo(cast<AtomicType>(T)->getValueType());
4373 case Type::Pipe:
4374 return computeTypeLinkageInfo(cast<PipeType>(T)->getElementType());
4377 llvm_unreachable("unhandled type class");
4380 bool Type::isLinkageValid() const {
4381 if (!TypeBits.isCacheValid())
4382 return true;
4384 Linkage L = LinkageComputer{}
4385 .computeTypeLinkageInfo(getCanonicalTypeInternal())
4386 .getLinkage();
4387 return L == TypeBits.getLinkage();
4390 LinkageInfo LinkageComputer::getTypeLinkageAndVisibility(const Type *T) {
4391 if (!T->isCanonicalUnqualified())
4392 return computeTypeLinkageInfo(T->getCanonicalTypeInternal());
4394 LinkageInfo LV = computeTypeLinkageInfo(T);
4395 assert(LV.getLinkage() == T->getLinkage());
4396 return LV;
4399 LinkageInfo Type::getLinkageAndVisibility() const {
4400 return LinkageComputer{}.getTypeLinkageAndVisibility(this);
4403 std::optional<NullabilityKind> Type::getNullability() const {
4404 QualType Type(this, 0);
4405 while (const auto *AT = Type->getAs<AttributedType>()) {
4406 // Check whether this is an attributed type with nullability
4407 // information.
4408 if (auto Nullability = AT->getImmediateNullability())
4409 return Nullability;
4411 Type = AT->getEquivalentType();
4413 return std::nullopt;
4416 bool Type::canHaveNullability(bool ResultIfUnknown) const {
4417 QualType type = getCanonicalTypeInternal();
4419 switch (type->getTypeClass()) {
4420 // We'll only see canonical types here.
4421 #define NON_CANONICAL_TYPE(Class, Parent) \
4422 case Type::Class: \
4423 llvm_unreachable("non-canonical type");
4424 #define TYPE(Class, Parent)
4425 #include "clang/AST/TypeNodes.inc"
4427 // Pointer types.
4428 case Type::Pointer:
4429 case Type::BlockPointer:
4430 case Type::MemberPointer:
4431 case Type::ObjCObjectPointer:
4432 return true;
4434 // Dependent types that could instantiate to pointer types.
4435 case Type::UnresolvedUsing:
4436 case Type::TypeOfExpr:
4437 case Type::TypeOf:
4438 case Type::Decltype:
4439 case Type::UnaryTransform:
4440 case Type::TemplateTypeParm:
4441 case Type::SubstTemplateTypeParmPack:
4442 case Type::DependentName:
4443 case Type::DependentTemplateSpecialization:
4444 case Type::Auto:
4445 return ResultIfUnknown;
4447 // Dependent template specializations can instantiate to pointer
4448 // types unless they're known to be specializations of a class
4449 // template.
4450 case Type::TemplateSpecialization:
4451 if (TemplateDecl *templateDecl
4452 = cast<TemplateSpecializationType>(type.getTypePtr())
4453 ->getTemplateName().getAsTemplateDecl()) {
4454 if (isa<ClassTemplateDecl>(templateDecl))
4455 return false;
4457 return ResultIfUnknown;
4459 case Type::Builtin:
4460 switch (cast<BuiltinType>(type.getTypePtr())->getKind()) {
4461 // Signed, unsigned, and floating-point types cannot have nullability.
4462 #define SIGNED_TYPE(Id, SingletonId) case BuiltinType::Id:
4463 #define UNSIGNED_TYPE(Id, SingletonId) case BuiltinType::Id:
4464 #define FLOATING_TYPE(Id, SingletonId) case BuiltinType::Id:
4465 #define BUILTIN_TYPE(Id, SingletonId)
4466 #include "clang/AST/BuiltinTypes.def"
4467 return false;
4469 // Dependent types that could instantiate to a pointer type.
4470 case BuiltinType::Dependent:
4471 case BuiltinType::Overload:
4472 case BuiltinType::BoundMember:
4473 case BuiltinType::PseudoObject:
4474 case BuiltinType::UnknownAny:
4475 case BuiltinType::ARCUnbridgedCast:
4476 return ResultIfUnknown;
4478 case BuiltinType::Void:
4479 case BuiltinType::ObjCId:
4480 case BuiltinType::ObjCClass:
4481 case BuiltinType::ObjCSel:
4482 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
4483 case BuiltinType::Id:
4484 #include "clang/Basic/OpenCLImageTypes.def"
4485 #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
4486 case BuiltinType::Id:
4487 #include "clang/Basic/OpenCLExtensionTypes.def"
4488 case BuiltinType::OCLSampler:
4489 case BuiltinType::OCLEvent:
4490 case BuiltinType::OCLClkEvent:
4491 case BuiltinType::OCLQueue:
4492 case BuiltinType::OCLReserveID:
4493 #define SVE_TYPE(Name, Id, SingletonId) \
4494 case BuiltinType::Id:
4495 #include "clang/Basic/AArch64SVEACLETypes.def"
4496 #define PPC_VECTOR_TYPE(Name, Id, Size) \
4497 case BuiltinType::Id:
4498 #include "clang/Basic/PPCTypes.def"
4499 #define RVV_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
4500 #include "clang/Basic/RISCVVTypes.def"
4501 #define WASM_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
4502 #include "clang/Basic/WebAssemblyReferenceTypes.def"
4503 case BuiltinType::BuiltinFn:
4504 case BuiltinType::NullPtr:
4505 case BuiltinType::IncompleteMatrixIdx:
4506 case BuiltinType::OMPArraySection:
4507 case BuiltinType::OMPArrayShaping:
4508 case BuiltinType::OMPIterator:
4509 return false;
4511 llvm_unreachable("unknown builtin type");
4513 // Non-pointer types.
4514 case Type::Complex:
4515 case Type::LValueReference:
4516 case Type::RValueReference:
4517 case Type::ConstantArray:
4518 case Type::IncompleteArray:
4519 case Type::VariableArray:
4520 case Type::DependentSizedArray:
4521 case Type::DependentVector:
4522 case Type::DependentSizedExtVector:
4523 case Type::Vector:
4524 case Type::ExtVector:
4525 case Type::ConstantMatrix:
4526 case Type::DependentSizedMatrix:
4527 case Type::DependentAddressSpace:
4528 case Type::FunctionProto:
4529 case Type::FunctionNoProto:
4530 case Type::Record:
4531 case Type::DeducedTemplateSpecialization:
4532 case Type::Enum:
4533 case Type::InjectedClassName:
4534 case Type::PackExpansion:
4535 case Type::ObjCObject:
4536 case Type::ObjCInterface:
4537 case Type::Atomic:
4538 case Type::Pipe:
4539 case Type::BitInt:
4540 case Type::DependentBitInt:
4541 return false;
4543 llvm_unreachable("bad type kind!");
4546 std::optional<NullabilityKind> AttributedType::getImmediateNullability() const {
4547 if (getAttrKind() == attr::TypeNonNull)
4548 return NullabilityKind::NonNull;
4549 if (getAttrKind() == attr::TypeNullable)
4550 return NullabilityKind::Nullable;
4551 if (getAttrKind() == attr::TypeNullUnspecified)
4552 return NullabilityKind::Unspecified;
4553 if (getAttrKind() == attr::TypeNullableResult)
4554 return NullabilityKind::NullableResult;
4555 return std::nullopt;
4558 std::optional<NullabilityKind>
4559 AttributedType::stripOuterNullability(QualType &T) {
4560 QualType AttrTy = T;
4561 if (auto MacroTy = dyn_cast<MacroQualifiedType>(T))
4562 AttrTy = MacroTy->getUnderlyingType();
4564 if (auto attributed = dyn_cast<AttributedType>(AttrTy)) {
4565 if (auto nullability = attributed->getImmediateNullability()) {
4566 T = attributed->getModifiedType();
4567 return nullability;
4571 return std::nullopt;
4574 bool Type::isBlockCompatibleObjCPointerType(ASTContext &ctx) const {
4575 const auto *objcPtr = getAs<ObjCObjectPointerType>();
4576 if (!objcPtr)
4577 return false;
4579 if (objcPtr->isObjCIdType()) {
4580 // id is always okay.
4581 return true;
4584 // Blocks are NSObjects.
4585 if (ObjCInterfaceDecl *iface = objcPtr->getInterfaceDecl()) {
4586 if (iface->getIdentifier() != ctx.getNSObjectName())
4587 return false;
4589 // Continue to check qualifiers, below.
4590 } else if (objcPtr->isObjCQualifiedIdType()) {
4591 // Continue to check qualifiers, below.
4592 } else {
4593 return false;
4596 // Check protocol qualifiers.
4597 for (ObjCProtocolDecl *proto : objcPtr->quals()) {
4598 // Blocks conform to NSObject and NSCopying.
4599 if (proto->getIdentifier() != ctx.getNSObjectName() &&
4600 proto->getIdentifier() != ctx.getNSCopyingName())
4601 return false;
4604 return true;
4607 Qualifiers::ObjCLifetime Type::getObjCARCImplicitLifetime() const {
4608 if (isObjCARCImplicitlyUnretainedType())
4609 return Qualifiers::OCL_ExplicitNone;
4610 return Qualifiers::OCL_Strong;
4613 bool Type::isObjCARCImplicitlyUnretainedType() const {
4614 assert(isObjCLifetimeType() &&
4615 "cannot query implicit lifetime for non-inferrable type");
4617 const Type *canon = getCanonicalTypeInternal().getTypePtr();
4619 // Walk down to the base type. We don't care about qualifiers for this.
4620 while (const auto *array = dyn_cast<ArrayType>(canon))
4621 canon = array->getElementType().getTypePtr();
4623 if (const auto *opt = dyn_cast<ObjCObjectPointerType>(canon)) {
4624 // Class and Class<Protocol> don't require retention.
4625 if (opt->getObjectType()->isObjCClass())
4626 return true;
4629 return false;
4632 bool Type::isObjCNSObjectType() const {
4633 if (const auto *typedefType = getAs<TypedefType>())
4634 return typedefType->getDecl()->hasAttr<ObjCNSObjectAttr>();
4635 return false;
4638 bool Type::isObjCIndependentClassType() const {
4639 if (const auto *typedefType = getAs<TypedefType>())
4640 return typedefType->getDecl()->hasAttr<ObjCIndependentClassAttr>();
4641 return false;
4644 bool Type::isObjCRetainableType() const {
4645 return isObjCObjectPointerType() ||
4646 isBlockPointerType() ||
4647 isObjCNSObjectType();
4650 bool Type::isObjCIndirectLifetimeType() const {
4651 if (isObjCLifetimeType())
4652 return true;
4653 if (const auto *OPT = getAs<PointerType>())
4654 return OPT->getPointeeType()->isObjCIndirectLifetimeType();
4655 if (const auto *Ref = getAs<ReferenceType>())
4656 return Ref->getPointeeType()->isObjCIndirectLifetimeType();
4657 if (const auto *MemPtr = getAs<MemberPointerType>())
4658 return MemPtr->getPointeeType()->isObjCIndirectLifetimeType();
4659 return false;
4662 /// Returns true if objects of this type have lifetime semantics under
4663 /// ARC.
4664 bool Type::isObjCLifetimeType() const {
4665 const Type *type = this;
4666 while (const ArrayType *array = type->getAsArrayTypeUnsafe())
4667 type = array->getElementType().getTypePtr();
4668 return type->isObjCRetainableType();
4671 /// Determine whether the given type T is a "bridgable" Objective-C type,
4672 /// which is either an Objective-C object pointer type or an
4673 bool Type::isObjCARCBridgableType() const {
4674 return isObjCObjectPointerType() || isBlockPointerType();
4677 /// Determine whether the given type T is a "bridgeable" C type.
4678 bool Type::isCARCBridgableType() const {
4679 const auto *Pointer = getAs<PointerType>();
4680 if (!Pointer)
4681 return false;
4683 QualType Pointee = Pointer->getPointeeType();
4684 return Pointee->isVoidType() || Pointee->isRecordType();
4687 /// Check if the specified type is the CUDA device builtin surface type.
4688 bool Type::isCUDADeviceBuiltinSurfaceType() const {
4689 if (const auto *RT = getAs<RecordType>())
4690 return RT->getDecl()->hasAttr<CUDADeviceBuiltinSurfaceTypeAttr>();
4691 return false;
4694 /// Check if the specified type is the CUDA device builtin texture type.
4695 bool Type::isCUDADeviceBuiltinTextureType() const {
4696 if (const auto *RT = getAs<RecordType>())
4697 return RT->getDecl()->hasAttr<CUDADeviceBuiltinTextureTypeAttr>();
4698 return false;
4701 bool Type::hasSizedVLAType() const {
4702 if (!isVariablyModifiedType()) return false;
4704 if (const auto *ptr = getAs<PointerType>())
4705 return ptr->getPointeeType()->hasSizedVLAType();
4706 if (const auto *ref = getAs<ReferenceType>())
4707 return ref->getPointeeType()->hasSizedVLAType();
4708 if (const ArrayType *arr = getAsArrayTypeUnsafe()) {
4709 if (isa<VariableArrayType>(arr) &&
4710 cast<VariableArrayType>(arr)->getSizeExpr())
4711 return true;
4713 return arr->getElementType()->hasSizedVLAType();
4716 return false;
4719 QualType::DestructionKind QualType::isDestructedTypeImpl(QualType type) {
4720 switch (type.getObjCLifetime()) {
4721 case Qualifiers::OCL_None:
4722 case Qualifiers::OCL_ExplicitNone:
4723 case Qualifiers::OCL_Autoreleasing:
4724 break;
4726 case Qualifiers::OCL_Strong:
4727 return DK_objc_strong_lifetime;
4728 case Qualifiers::OCL_Weak:
4729 return DK_objc_weak_lifetime;
4732 if (const auto *RT =
4733 type->getBaseElementTypeUnsafe()->getAs<RecordType>()) {
4734 const RecordDecl *RD = RT->getDecl();
4735 if (const auto *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
4736 /// Check if this is a C++ object with a non-trivial destructor.
4737 if (CXXRD->hasDefinition() && !CXXRD->hasTrivialDestructor())
4738 return DK_cxx_destructor;
4739 } else {
4740 /// Check if this is a C struct that is non-trivial to destroy or an array
4741 /// that contains such a struct.
4742 if (RD->isNonTrivialToPrimitiveDestroy())
4743 return DK_nontrivial_c_struct;
4747 return DK_none;
4750 CXXRecordDecl *MemberPointerType::getMostRecentCXXRecordDecl() const {
4751 return getClass()->getAsCXXRecordDecl()->getMostRecentNonInjectedDecl();
4754 void clang::FixedPointValueToString(SmallVectorImpl<char> &Str,
4755 llvm::APSInt Val, unsigned Scale) {
4756 llvm::FixedPointSemantics FXSema(Val.getBitWidth(), Scale, Val.isSigned(),
4757 /*IsSaturated=*/false,
4758 /*HasUnsignedPadding=*/false);
4759 llvm::APFixedPoint(Val, FXSema).toString(Str);
4762 AutoType::AutoType(QualType DeducedAsType, AutoTypeKeyword Keyword,
4763 TypeDependence ExtraDependence, QualType Canon,
4764 ConceptDecl *TypeConstraintConcept,
4765 ArrayRef<TemplateArgument> TypeConstraintArgs)
4766 : DeducedType(Auto, DeducedAsType, ExtraDependence, Canon) {
4767 AutoTypeBits.Keyword = llvm::to_underlying(Keyword);
4768 AutoTypeBits.NumArgs = TypeConstraintArgs.size();
4769 this->TypeConstraintConcept = TypeConstraintConcept;
4770 assert(TypeConstraintConcept || AutoTypeBits.NumArgs == 0);
4771 if (TypeConstraintConcept) {
4772 auto *ArgBuffer =
4773 const_cast<TemplateArgument *>(getTypeConstraintArguments().data());
4774 for (const TemplateArgument &Arg : TypeConstraintArgs) {
4775 // We only syntactically depend on the constraint arguments. They don't
4776 // affect the deduced type, only its validity.
4777 addDependence(
4778 toSyntacticDependence(toTypeDependence(Arg.getDependence())));
4780 new (ArgBuffer++) TemplateArgument(Arg);
4785 void AutoType::Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context,
4786 QualType Deduced, AutoTypeKeyword Keyword,
4787 bool IsDependent, ConceptDecl *CD,
4788 ArrayRef<TemplateArgument> Arguments) {
4789 ID.AddPointer(Deduced.getAsOpaquePtr());
4790 ID.AddInteger((unsigned)Keyword);
4791 ID.AddBoolean(IsDependent);
4792 ID.AddPointer(CD);
4793 for (const TemplateArgument &Arg : Arguments)
4794 Arg.Profile(ID, Context);
4797 void AutoType::Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context) {
4798 Profile(ID, Context, getDeducedType(), getKeyword(), isDependentType(),
4799 getTypeConstraintConcept(), getTypeConstraintArguments());