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