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