1 //===- Type.cpp - Type representation and manipulation --------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file implements type-related functionality.
12 //===----------------------------------------------------------------------===//
14 #include "clang/AST/Type.h"
16 #include "clang/AST/ASTContext.h"
17 #include "clang/AST/Attr.h"
18 #include "clang/AST/CharUnits.h"
19 #include "clang/AST/Decl.h"
20 #include "clang/AST/DeclBase.h"
21 #include "clang/AST/DeclCXX.h"
22 #include "clang/AST/DeclObjC.h"
23 #include "clang/AST/DeclTemplate.h"
24 #include "clang/AST/Expr.h"
25 #include "clang/AST/NestedNameSpecifier.h"
26 #include "clang/AST/PrettyPrinter.h"
27 #include "clang/AST/TemplateBase.h"
28 #include "clang/AST/TemplateName.h"
29 #include "clang/AST/TypeVisitor.h"
30 #include "clang/Basic/AddressSpaces.h"
31 #include "clang/Basic/ExceptionSpecificationType.h"
32 #include "clang/Basic/LLVM.h"
33 #include "clang/Basic/LangOptions.h"
34 #include "clang/Basic/Linkage.h"
35 #include "clang/Basic/Specifiers.h"
36 #include "clang/Basic/TargetCXXABI.h"
37 #include "clang/Basic/TargetInfo.h"
38 #include "clang/Basic/Visibility.h"
39 #include "llvm/ADT/APInt.h"
40 #include "llvm/ADT/APSInt.h"
41 #include "llvm/ADT/ArrayRef.h"
42 #include "llvm/ADT/FoldingSet.h"
43 #include "llvm/ADT/None.h"
44 #include "llvm/ADT/SmallVector.h"
45 #include "llvm/Support/Casting.h"
46 #include "llvm/Support/ErrorHandling.h"
47 #include "llvm/Support/MathExtras.h"
53 using namespace clang;
55 bool Qualifiers::isStrictSupersetOf(Qualifiers Other) const {
56 return (*this != Other) &&
57 // CVR qualifiers superset
58 (((Mask & CVRMask) | (Other.Mask & CVRMask)) == (Mask & CVRMask)) &&
59 // ObjC GC qualifiers superset
60 ((getObjCGCAttr() == Other.getObjCGCAttr()) ||
61 (hasObjCGCAttr() && !Other.hasObjCGCAttr())) &&
62 // Address space superset.
63 ((getAddressSpace() == Other.getAddressSpace()) ||
64 (hasAddressSpace()&& !Other.hasAddressSpace())) &&
65 // Lifetime qualifier superset.
66 ((getObjCLifetime() == Other.getObjCLifetime()) ||
67 (hasObjCLifetime() && !Other.hasObjCLifetime()));
70 const IdentifierInfo* QualType::getBaseTypeIdentifier() const {
71 const Type* ty = getTypePtr();
72 NamedDecl *ND = nullptr;
73 if (ty->isPointerType() || ty->isReferenceType())
74 return ty->getPointeeType().getBaseTypeIdentifier();
75 else if (ty->isRecordType())
76 ND = ty->getAs<RecordType>()->getDecl();
77 else if (ty->isEnumeralType())
78 ND = ty->getAs<EnumType>()->getDecl();
79 else if (ty->getTypeClass() == Type::Typedef)
80 ND = ty->getAs<TypedefType>()->getDecl();
81 else if (ty->isArrayType())
82 return ty->castAsArrayTypeUnsafe()->
83 getElementType().getBaseTypeIdentifier();
86 return ND->getIdentifier();
90 bool QualType::isConstant(QualType T, const ASTContext &Ctx) {
91 if (T.isConstQualified())
94 if (const ArrayType *AT = Ctx.getAsArrayType(T))
95 return AT->getElementType().isConstant(Ctx);
97 return T.getAddressSpace() == LangAS::opencl_constant;
100 unsigned ConstantArrayType::getNumAddressingBits(const ASTContext &Context,
101 QualType ElementType,
102 const llvm::APInt &NumElements) {
103 uint64_t ElementSize = Context.getTypeSizeInChars(ElementType).getQuantity();
105 // Fast path the common cases so we can avoid the conservative computation
106 // below, which in common cases allocates "large" APSInt values, which are
109 // If the element size is a power of 2, we can directly compute the additional
110 // number of addressing bits beyond those required for the element count.
111 if (llvm::isPowerOf2_64(ElementSize)) {
112 return NumElements.getActiveBits() + llvm::Log2_64(ElementSize);
115 // If both the element count and element size fit in 32-bits, we can do the
116 // computation directly in 64-bits.
117 if ((ElementSize >> 32) == 0 && NumElements.getBitWidth() <= 64 &&
118 (NumElements.getZExtValue() >> 32) == 0) {
119 uint64_t TotalSize = NumElements.getZExtValue() * ElementSize;
120 return 64 - llvm::countLeadingZeros(TotalSize);
123 // Otherwise, use APSInt to handle arbitrary sized values.
124 llvm::APSInt SizeExtended(NumElements, true);
125 unsigned SizeTypeBits = Context.getTypeSize(Context.getSizeType());
126 SizeExtended = SizeExtended.extend(std::max(SizeTypeBits,
127 SizeExtended.getBitWidth()) * 2);
129 llvm::APSInt TotalSize(llvm::APInt(SizeExtended.getBitWidth(), ElementSize));
130 TotalSize *= SizeExtended;
132 return TotalSize.getActiveBits();
135 unsigned ConstantArrayType::getMaxSizeBits(const ASTContext &Context) {
136 unsigned Bits = Context.getTypeSize(Context.getSizeType());
138 // Limit the number of bits in size_t so that maximal bit size fits 64 bit
139 // integer (see PR8256). We can do this as currently there is no hardware
140 // that supports full 64-bit virtual space.
147 DependentSizedArrayType::DependentSizedArrayType(const ASTContext &Context,
148 QualType et, QualType can,
149 Expr *e, ArraySizeModifier sm,
151 SourceRange brackets)
152 : ArrayType(DependentSizedArray, et, can, sm, tq,
153 (et->containsUnexpandedParameterPack() ||
154 (e && e->containsUnexpandedParameterPack()))),
155 Context(Context), SizeExpr((Stmt*) e), Brackets(brackets) {}
157 void DependentSizedArrayType::Profile(llvm::FoldingSetNodeID &ID,
158 const ASTContext &Context,
160 ArraySizeModifier SizeMod,
163 ID.AddPointer(ET.getAsOpaquePtr());
164 ID.AddInteger(SizeMod);
165 ID.AddInteger(TypeQuals);
166 E->Profile(ID, Context, true);
169 DependentSizedExtVectorType::DependentSizedExtVectorType(const
171 QualType ElementType,
175 : Type(DependentSizedExtVector, can, /*Dependent=*/true,
176 /*InstantiationDependent=*/true,
177 ElementType->isVariablyModifiedType(),
178 (ElementType->containsUnexpandedParameterPack() ||
179 (SizeExpr && SizeExpr->containsUnexpandedParameterPack()))),
180 Context(Context), SizeExpr(SizeExpr), ElementType(ElementType),
184 DependentSizedExtVectorType::Profile(llvm::FoldingSetNodeID &ID,
185 const ASTContext &Context,
186 QualType ElementType, Expr *SizeExpr) {
187 ID.AddPointer(ElementType.getAsOpaquePtr());
188 SizeExpr->Profile(ID, Context, true);
191 DependentAddressSpaceType::DependentAddressSpaceType(
192 const ASTContext &Context, QualType PointeeType, QualType can,
193 Expr *AddrSpaceExpr, SourceLocation loc)
194 : Type(DependentAddressSpace, can, /*Dependent=*/true,
195 /*InstantiationDependent=*/true,
196 PointeeType->isVariablyModifiedType(),
197 (PointeeType->containsUnexpandedParameterPack() ||
199 AddrSpaceExpr->containsUnexpandedParameterPack()))),
200 Context(Context), AddrSpaceExpr(AddrSpaceExpr), PointeeType(PointeeType),
203 void DependentAddressSpaceType::Profile(llvm::FoldingSetNodeID &ID,
204 const ASTContext &Context,
205 QualType PointeeType,
206 Expr *AddrSpaceExpr) {
207 ID.AddPointer(PointeeType.getAsOpaquePtr());
208 AddrSpaceExpr->Profile(ID, Context, true);
211 VectorType::VectorType(QualType vecType, unsigned nElements, QualType canonType,
213 : VectorType(Vector, vecType, nElements, canonType, vecKind) {}
215 VectorType::VectorType(TypeClass tc, QualType vecType, unsigned nElements,
216 QualType canonType, VectorKind vecKind)
217 : Type(tc, canonType, vecType->isDependentType(),
218 vecType->isInstantiationDependentType(),
219 vecType->isVariablyModifiedType(),
220 vecType->containsUnexpandedParameterPack()),
221 ElementType(vecType) {
222 VectorTypeBits.VecKind = vecKind;
223 VectorTypeBits.NumElements = nElements;
226 /// getArrayElementTypeNoTypeQual - If this is an array type, return the
227 /// element type of the array, potentially with type qualifiers missing.
228 /// This method should never be used when type qualifiers are meaningful.
229 const Type *Type::getArrayElementTypeNoTypeQual() const {
230 // If this is directly an array type, return it.
231 if (const ArrayType *ATy = dyn_cast<ArrayType>(this))
232 return ATy->getElementType().getTypePtr();
234 // If the canonical form of this type isn't the right kind, reject it.
235 if (!isa<ArrayType>(CanonicalType))
238 // If this is a typedef for an array type, strip the typedef off without
239 // losing all typedef information.
240 return cast<ArrayType>(getUnqualifiedDesugaredType())
241 ->getElementType().getTypePtr();
244 /// getDesugaredType - Return the specified type with any "sugar" removed from
245 /// the type. This takes off typedefs, typeof's etc. If the outer level of
246 /// the type is already concrete, it returns it unmodified. This is similar
247 /// to getting the canonical type, but it doesn't remove *all* typedefs. For
248 /// example, it returns "T*" as "T*", (not as "int*"), because the pointer is
250 QualType QualType::getDesugaredType(QualType T, const ASTContext &Context) {
251 SplitQualType split = getSplitDesugaredType(T);
252 return Context.getQualifiedType(split.Ty, split.Quals);
255 QualType QualType::getSingleStepDesugaredTypeImpl(QualType type,
256 const ASTContext &Context) {
257 SplitQualType split = type.split();
258 QualType desugar = split.Ty->getLocallyUnqualifiedSingleStepDesugaredType();
259 return Context.getQualifiedType(desugar, split.Quals);
262 QualType Type::getLocallyUnqualifiedSingleStepDesugaredType() const {
263 switch (getTypeClass()) {
264 #define ABSTRACT_TYPE(Class, Parent)
265 #define TYPE(Class, Parent) \
266 case Type::Class: { \
267 const Class##Type *ty = cast<Class##Type>(this); \
268 if (!ty->isSugared()) return QualType(ty, 0); \
269 return ty->desugar(); \
271 #include "clang/AST/TypeNodes.def"
273 llvm_unreachable("bad type kind!");
276 SplitQualType QualType::getSplitDesugaredType(QualType T) {
277 QualifierCollector Qs;
281 const Type *CurTy = Qs.strip(Cur);
282 switch (CurTy->getTypeClass()) {
283 #define ABSTRACT_TYPE(Class, Parent)
284 #define TYPE(Class, Parent) \
285 case Type::Class: { \
286 const Class##Type *Ty = cast<Class##Type>(CurTy); \
287 if (!Ty->isSugared()) \
288 return SplitQualType(Ty, Qs); \
289 Cur = Ty->desugar(); \
292 #include "clang/AST/TypeNodes.def"
297 SplitQualType QualType::getSplitUnqualifiedTypeImpl(QualType type) {
298 SplitQualType split = type.split();
300 // All the qualifiers we've seen so far.
301 Qualifiers quals = split.Quals;
303 // The last type node we saw with any nodes inside it.
304 const Type *lastTypeWithQuals = split.Ty;
309 // Do a single-step desugar, aborting the loop if the type isn't
311 switch (split.Ty->getTypeClass()) {
312 #define ABSTRACT_TYPE(Class, Parent)
313 #define TYPE(Class, Parent) \
314 case Type::Class: { \
315 const Class##Type *ty = cast<Class##Type>(split.Ty); \
316 if (!ty->isSugared()) goto done; \
317 next = ty->desugar(); \
320 #include "clang/AST/TypeNodes.def"
323 // Otherwise, split the underlying type. If that yields qualifiers,
324 // update the information.
325 split = next.split();
326 if (!split.Quals.empty()) {
327 lastTypeWithQuals = split.Ty;
328 quals.addConsistentQualifiers(split.Quals);
333 return SplitQualType(lastTypeWithQuals, quals);
336 QualType QualType::IgnoreParens(QualType T) {
337 // FIXME: this seems inherently un-qualifiers-safe.
338 while (const ParenType *PT = T->getAs<ParenType>())
339 T = PT->getInnerType();
343 /// \brief This will check for a T (which should be a Type which can act as
344 /// sugar, such as a TypedefType) by removing any existing sugar until it
345 /// reaches a T or a non-sugared type.
346 template<typename T> static const T *getAsSugar(const Type *Cur) {
348 if (const T *Sugar = dyn_cast<T>(Cur))
350 switch (Cur->getTypeClass()) {
351 #define ABSTRACT_TYPE(Class, Parent)
352 #define TYPE(Class, Parent) \
353 case Type::Class: { \
354 const Class##Type *Ty = cast<Class##Type>(Cur); \
355 if (!Ty->isSugared()) return 0; \
356 Cur = Ty->desugar().getTypePtr(); \
359 #include "clang/AST/TypeNodes.def"
364 template <> const TypedefType *Type::getAs() const {
365 return getAsSugar<TypedefType>(this);
368 template <> const TemplateSpecializationType *Type::getAs() const {
369 return getAsSugar<TemplateSpecializationType>(this);
372 template <> const AttributedType *Type::getAs() const {
373 return getAsSugar<AttributedType>(this);
376 /// getUnqualifiedDesugaredType - Pull any qualifiers and syntactic
377 /// sugar off the given type. This should produce an object of the
378 /// same dynamic type as the canonical type.
379 const Type *Type::getUnqualifiedDesugaredType() const {
380 const Type *Cur = this;
383 switch (Cur->getTypeClass()) {
384 #define ABSTRACT_TYPE(Class, Parent)
385 #define TYPE(Class, Parent) \
387 const Class##Type *Ty = cast<Class##Type>(Cur); \
388 if (!Ty->isSugared()) return Cur; \
389 Cur = Ty->desugar().getTypePtr(); \
392 #include "clang/AST/TypeNodes.def"
397 bool Type::isClassType() const {
398 if (const RecordType *RT = getAs<RecordType>())
399 return RT->getDecl()->isClass();
403 bool Type::isStructureType() const {
404 if (const RecordType *RT = getAs<RecordType>())
405 return RT->getDecl()->isStruct();
408 bool Type::isObjCBoxableRecordType() const {
409 if (const RecordType *RT = getAs<RecordType>())
410 return RT->getDecl()->hasAttr<ObjCBoxableAttr>();
413 bool Type::isInterfaceType() const {
414 if (const RecordType *RT = getAs<RecordType>())
415 return RT->getDecl()->isInterface();
418 bool Type::isStructureOrClassType() const {
419 if (const RecordType *RT = getAs<RecordType>()) {
420 RecordDecl *RD = RT->getDecl();
421 return RD->isStruct() || RD->isClass() || RD->isInterface();
426 bool Type::isVoidPointerType() const {
427 if (const PointerType *PT = getAs<PointerType>())
428 return PT->getPointeeType()->isVoidType();
432 bool Type::isUnionType() const {
433 if (const RecordType *RT = getAs<RecordType>())
434 return RT->getDecl()->isUnion();
438 bool Type::isComplexType() const {
439 if (const ComplexType *CT = dyn_cast<ComplexType>(CanonicalType))
440 return CT->getElementType()->isFloatingType();
444 bool Type::isComplexIntegerType() const {
445 // Check for GCC complex integer extension.
446 return getAsComplexIntegerType();
449 const ComplexType *Type::getAsComplexIntegerType() const {
450 if (const ComplexType *Complex = getAs<ComplexType>())
451 if (Complex->getElementType()->isIntegerType())
456 QualType Type::getPointeeType() const {
457 if (const PointerType *PT = getAs<PointerType>())
458 return PT->getPointeeType();
459 if (const ObjCObjectPointerType *OPT = getAs<ObjCObjectPointerType>())
460 return OPT->getPointeeType();
461 if (const BlockPointerType *BPT = getAs<BlockPointerType>())
462 return BPT->getPointeeType();
463 if (const ReferenceType *RT = getAs<ReferenceType>())
464 return RT->getPointeeType();
465 if (const MemberPointerType *MPT = getAs<MemberPointerType>())
466 return MPT->getPointeeType();
467 if (const DecayedType *DT = getAs<DecayedType>())
468 return DT->getPointeeType();
472 const RecordType *Type::getAsStructureType() const {
473 // If this is directly a structure type, return it.
474 if (const RecordType *RT = dyn_cast<RecordType>(this)) {
475 if (RT->getDecl()->isStruct())
479 // If the canonical form of this type isn't the right kind, reject it.
480 if (const RecordType *RT = dyn_cast<RecordType>(CanonicalType)) {
481 if (!RT->getDecl()->isStruct())
484 // If this is a typedef for a structure type, strip the typedef off without
485 // losing all typedef information.
486 return cast<RecordType>(getUnqualifiedDesugaredType());
491 const RecordType *Type::getAsUnionType() const {
492 // If this is directly a union type, return it.
493 if (const RecordType *RT = dyn_cast<RecordType>(this)) {
494 if (RT->getDecl()->isUnion())
498 // If the canonical form of this type isn't the right kind, reject it.
499 if (const RecordType *RT = dyn_cast<RecordType>(CanonicalType)) {
500 if (!RT->getDecl()->isUnion())
503 // If this is a typedef for a union type, strip the typedef off without
504 // losing all typedef information.
505 return cast<RecordType>(getUnqualifiedDesugaredType());
511 bool Type::isObjCIdOrObjectKindOfType(const ASTContext &ctx,
512 const ObjCObjectType *&bound) const {
515 const ObjCObjectPointerType *OPT = getAs<ObjCObjectPointerType>();
520 if (OPT->isObjCIdType())
523 // If it's not a __kindof type, reject it now.
524 if (!OPT->isKindOfType())
527 // If it's Class or qualified Class, it's not an object type.
528 if (OPT->isObjCClassType() || OPT->isObjCQualifiedClassType())
531 // Figure out the type bound for the __kindof type.
532 bound = OPT->getObjectType()->stripObjCKindOfTypeAndQuals(ctx)
533 ->getAs<ObjCObjectType>();
537 bool Type::isObjCClassOrClassKindOfType() const {
538 const ObjCObjectPointerType *OPT = getAs<ObjCObjectPointerType>();
543 if (OPT->isObjCClassType())
546 // If it's not a __kindof type, reject it now.
547 if (!OPT->isKindOfType())
550 // If it's Class or qualified Class, it's a class __kindof type.
551 return OPT->isObjCClassType() || OPT->isObjCQualifiedClassType();
554 /// Was this type written with the special inert-in-MRC __unsafe_unretained
557 /// This approximates the answer to the following question: if this
558 /// translation unit were compiled in ARC, would this type be qualified
559 /// with __unsafe_unretained?
560 bool Type::isObjCInertUnsafeUnretainedType() const {
561 const Type *cur = this;
563 if (auto attributed = dyn_cast<AttributedType>(cur)) {
564 if (attributed->getAttrKind() ==
565 AttributedType::attr_objc_inert_unsafe_unretained)
569 // Single-step desugar until we run out of sugar.
570 QualType next = cur->getLocallyUnqualifiedSingleStepDesugaredType();
571 if (next.getTypePtr() == cur) return false;
572 cur = next.getTypePtr();
576 ObjCTypeParamType::ObjCTypeParamType(const ObjCTypeParamDecl *D,
578 ArrayRef<ObjCProtocolDecl *> protocols)
579 : Type(ObjCTypeParam, can, can->isDependentType(),
580 can->isInstantiationDependentType(),
581 can->isVariablyModifiedType(),
582 /*ContainsUnexpandedParameterPack=*/false),
583 OTPDecl(const_cast<ObjCTypeParamDecl*>(D)) {
584 initialize(protocols);
587 ObjCObjectType::ObjCObjectType(QualType Canonical, QualType Base,
588 ArrayRef<QualType> typeArgs,
589 ArrayRef<ObjCProtocolDecl *> protocols,
591 : Type(ObjCObject, Canonical, Base->isDependentType(),
592 Base->isInstantiationDependentType(),
593 Base->isVariablyModifiedType(),
594 Base->containsUnexpandedParameterPack()),
596 ObjCObjectTypeBits.IsKindOf = isKindOf;
598 ObjCObjectTypeBits.NumTypeArgs = typeArgs.size();
599 assert(getTypeArgsAsWritten().size() == typeArgs.size() &&
600 "bitfield overflow in type argument count");
601 if (!typeArgs.empty())
602 memcpy(getTypeArgStorage(), typeArgs.data(),
603 typeArgs.size() * sizeof(QualType));
605 for (auto typeArg : typeArgs) {
606 if (typeArg->isDependentType())
608 else if (typeArg->isInstantiationDependentType())
609 setInstantiationDependent();
611 if (typeArg->containsUnexpandedParameterPack())
612 setContainsUnexpandedParameterPack();
614 // Initialize the protocol qualifiers. The protocol storage is known
615 // after we set number of type arguments.
616 initialize(protocols);
619 bool ObjCObjectType::isSpecialized() const {
620 // If we have type arguments written here, the type is specialized.
621 if (ObjCObjectTypeBits.NumTypeArgs > 0)
624 // Otherwise, check whether the base type is specialized.
625 if (auto objcObject = getBaseType()->getAs<ObjCObjectType>()) {
626 // Terminate when we reach an interface type.
627 if (isa<ObjCInterfaceType>(objcObject))
630 return objcObject->isSpecialized();
637 ArrayRef<QualType> ObjCObjectType::getTypeArgs() const {
638 // We have type arguments written on this type.
639 if (isSpecializedAsWritten())
640 return getTypeArgsAsWritten();
642 // Look at the base type, which might have type arguments.
643 if (auto objcObject = getBaseType()->getAs<ObjCObjectType>()) {
644 // Terminate when we reach an interface type.
645 if (isa<ObjCInterfaceType>(objcObject))
648 return objcObject->getTypeArgs();
651 // No type arguments.
655 bool ObjCObjectType::isKindOfType() const {
656 if (isKindOfTypeAsWritten())
659 // Look at the base type, which might have type arguments.
660 if (auto objcObject = getBaseType()->getAs<ObjCObjectType>()) {
661 // Terminate when we reach an interface type.
662 if (isa<ObjCInterfaceType>(objcObject))
665 return objcObject->isKindOfType();
668 // Not a "__kindof" type.
672 QualType ObjCObjectType::stripObjCKindOfTypeAndQuals(
673 const ASTContext &ctx) const {
674 if (!isKindOfType() && qual_empty())
675 return QualType(this, 0);
677 // Recursively strip __kindof.
678 SplitQualType splitBaseType = getBaseType().split();
679 QualType baseType(splitBaseType.Ty, 0);
680 if (const ObjCObjectType *baseObj
681 = splitBaseType.Ty->getAs<ObjCObjectType>()) {
682 baseType = baseObj->stripObjCKindOfTypeAndQuals(ctx);
685 return ctx.getObjCObjectType(ctx.getQualifiedType(baseType,
686 splitBaseType.Quals),
687 getTypeArgsAsWritten(),
692 const ObjCObjectPointerType *ObjCObjectPointerType::stripObjCKindOfTypeAndQuals(
693 const ASTContext &ctx) const {
694 if (!isKindOfType() && qual_empty())
697 QualType obj = getObjectType()->stripObjCKindOfTypeAndQuals(ctx);
698 return ctx.getObjCObjectPointerType(obj)->castAs<ObjCObjectPointerType>();
702 static QualType simpleTransform(ASTContext &ctx, QualType type, F &&f);
706 /// Visitor used by simpleTransform() to perform the transformation.
708 struct SimpleTransformVisitor
709 : public TypeVisitor<SimpleTransformVisitor<F>, QualType> {
713 QualType recurse(QualType type) {
714 return simpleTransform(Ctx, type, std::move(TheFunc));
718 SimpleTransformVisitor(ASTContext &ctx, F &&f)
719 : Ctx(ctx), TheFunc(std::move(f)) {}
721 // None of the clients of this transformation can occur where
722 // there are dependent types, so skip dependent types.
723 #define TYPE(Class, Base)
724 #define DEPENDENT_TYPE(Class, Base) \
725 QualType Visit##Class##Type(const Class##Type *T) { return QualType(T, 0); }
726 #include "clang/AST/TypeNodes.def"
728 #define TRIVIAL_TYPE_CLASS(Class) \
729 QualType Visit##Class##Type(const Class##Type *T) { return QualType(T, 0); }
731 TRIVIAL_TYPE_CLASS(Builtin)
733 QualType VisitComplexType(const ComplexType *T) {
734 QualType elementType = recurse(T->getElementType());
735 if (elementType.isNull())
738 if (elementType.getAsOpaquePtr() == T->getElementType().getAsOpaquePtr())
739 return QualType(T, 0);
741 return Ctx.getComplexType(elementType);
744 QualType VisitPointerType(const PointerType *T) {
745 QualType pointeeType = recurse(T->getPointeeType());
746 if (pointeeType.isNull())
749 if (pointeeType.getAsOpaquePtr() == T->getPointeeType().getAsOpaquePtr())
750 return QualType(T, 0);
752 return Ctx.getPointerType(pointeeType);
755 QualType VisitBlockPointerType(const BlockPointerType *T) {
756 QualType pointeeType = recurse(T->getPointeeType());
757 if (pointeeType.isNull())
760 if (pointeeType.getAsOpaquePtr() == T->getPointeeType().getAsOpaquePtr())
761 return QualType(T, 0);
763 return Ctx.getBlockPointerType(pointeeType);
766 QualType VisitLValueReferenceType(const LValueReferenceType *T) {
767 QualType pointeeType = recurse(T->getPointeeTypeAsWritten());
768 if (pointeeType.isNull())
771 if (pointeeType.getAsOpaquePtr()
772 == T->getPointeeTypeAsWritten().getAsOpaquePtr())
773 return QualType(T, 0);
775 return Ctx.getLValueReferenceType(pointeeType, T->isSpelledAsLValue());
778 QualType VisitRValueReferenceType(const RValueReferenceType *T) {
779 QualType pointeeType = recurse(T->getPointeeTypeAsWritten());
780 if (pointeeType.isNull())
783 if (pointeeType.getAsOpaquePtr()
784 == T->getPointeeTypeAsWritten().getAsOpaquePtr())
785 return QualType(T, 0);
787 return Ctx.getRValueReferenceType(pointeeType);
790 QualType VisitMemberPointerType(const MemberPointerType *T) {
791 QualType pointeeType = recurse(T->getPointeeType());
792 if (pointeeType.isNull())
795 if (pointeeType.getAsOpaquePtr() == T->getPointeeType().getAsOpaquePtr())
796 return QualType(T, 0);
798 return Ctx.getMemberPointerType(pointeeType, T->getClass());
801 QualType VisitConstantArrayType(const ConstantArrayType *T) {
802 QualType elementType = recurse(T->getElementType());
803 if (elementType.isNull())
806 if (elementType.getAsOpaquePtr() == T->getElementType().getAsOpaquePtr())
807 return QualType(T, 0);
809 return Ctx.getConstantArrayType(elementType, T->getSize(),
810 T->getSizeModifier(),
811 T->getIndexTypeCVRQualifiers());
814 QualType VisitVariableArrayType(const VariableArrayType *T) {
815 QualType elementType = recurse(T->getElementType());
816 if (elementType.isNull())
819 if (elementType.getAsOpaquePtr() == T->getElementType().getAsOpaquePtr())
820 return QualType(T, 0);
822 return Ctx.getVariableArrayType(elementType, T->getSizeExpr(),
823 T->getSizeModifier(),
824 T->getIndexTypeCVRQualifiers(),
825 T->getBracketsRange());
828 QualType VisitIncompleteArrayType(const IncompleteArrayType *T) {
829 QualType elementType = recurse(T->getElementType());
830 if (elementType.isNull())
833 if (elementType.getAsOpaquePtr() == T->getElementType().getAsOpaquePtr())
834 return QualType(T, 0);
836 return Ctx.getIncompleteArrayType(elementType, T->getSizeModifier(),
837 T->getIndexTypeCVRQualifiers());
840 QualType VisitVectorType(const VectorType *T) {
841 QualType elementType = recurse(T->getElementType());
842 if (elementType.isNull())
845 if (elementType.getAsOpaquePtr() == T->getElementType().getAsOpaquePtr())
846 return QualType(T, 0);
848 return Ctx.getVectorType(elementType, T->getNumElements(),
852 QualType VisitExtVectorType(const ExtVectorType *T) {
853 QualType elementType = recurse(T->getElementType());
854 if (elementType.isNull())
857 if (elementType.getAsOpaquePtr() == T->getElementType().getAsOpaquePtr())
858 return QualType(T, 0);
860 return Ctx.getExtVectorType(elementType, T->getNumElements());
863 QualType VisitFunctionNoProtoType(const FunctionNoProtoType *T) {
864 QualType returnType = recurse(T->getReturnType());
865 if (returnType.isNull())
868 if (returnType.getAsOpaquePtr() == T->getReturnType().getAsOpaquePtr())
869 return QualType(T, 0);
871 return Ctx.getFunctionNoProtoType(returnType, T->getExtInfo());
874 QualType VisitFunctionProtoType(const FunctionProtoType *T) {
875 QualType returnType = recurse(T->getReturnType());
876 if (returnType.isNull())
879 // Transform parameter types.
880 SmallVector<QualType, 4> paramTypes;
881 bool paramChanged = false;
882 for (auto paramType : T->getParamTypes()) {
883 QualType newParamType = recurse(paramType);
884 if (newParamType.isNull())
887 if (newParamType.getAsOpaquePtr() != paramType.getAsOpaquePtr())
890 paramTypes.push_back(newParamType);
893 // Transform extended info.
894 FunctionProtoType::ExtProtoInfo info = T->getExtProtoInfo();
895 bool exceptionChanged = false;
896 if (info.ExceptionSpec.Type == EST_Dynamic) {
897 SmallVector<QualType, 4> exceptionTypes;
898 for (auto exceptionType : info.ExceptionSpec.Exceptions) {
899 QualType newExceptionType = recurse(exceptionType);
900 if (newExceptionType.isNull())
903 if (newExceptionType.getAsOpaquePtr()
904 != exceptionType.getAsOpaquePtr())
905 exceptionChanged = true;
907 exceptionTypes.push_back(newExceptionType);
910 if (exceptionChanged) {
911 info.ExceptionSpec.Exceptions =
912 llvm::makeArrayRef(exceptionTypes).copy(Ctx);
916 if (returnType.getAsOpaquePtr() == T->getReturnType().getAsOpaquePtr() &&
917 !paramChanged && !exceptionChanged)
918 return QualType(T, 0);
920 return Ctx.getFunctionType(returnType, paramTypes, info);
923 QualType VisitParenType(const ParenType *T) {
924 QualType innerType = recurse(T->getInnerType());
925 if (innerType.isNull())
928 if (innerType.getAsOpaquePtr() == T->getInnerType().getAsOpaquePtr())
929 return QualType(T, 0);
931 return Ctx.getParenType(innerType);
934 TRIVIAL_TYPE_CLASS(Typedef)
935 TRIVIAL_TYPE_CLASS(ObjCTypeParam)
937 QualType VisitAdjustedType(const AdjustedType *T) {
938 QualType originalType = recurse(T->getOriginalType());
939 if (originalType.isNull())
942 QualType adjustedType = recurse(T->getAdjustedType());
943 if (adjustedType.isNull())
946 if (originalType.getAsOpaquePtr()
947 == T->getOriginalType().getAsOpaquePtr() &&
948 adjustedType.getAsOpaquePtr() == T->getAdjustedType().getAsOpaquePtr())
949 return QualType(T, 0);
951 return Ctx.getAdjustedType(originalType, adjustedType);
954 QualType VisitDecayedType(const DecayedType *T) {
955 QualType originalType = recurse(T->getOriginalType());
956 if (originalType.isNull())
959 if (originalType.getAsOpaquePtr()
960 == T->getOriginalType().getAsOpaquePtr())
961 return QualType(T, 0);
963 return Ctx.getDecayedType(originalType);
966 TRIVIAL_TYPE_CLASS(TypeOfExpr)
967 TRIVIAL_TYPE_CLASS(TypeOf)
968 TRIVIAL_TYPE_CLASS(Decltype)
969 TRIVIAL_TYPE_CLASS(UnaryTransform)
970 TRIVIAL_TYPE_CLASS(Record)
971 TRIVIAL_TYPE_CLASS(Enum)
973 // FIXME: Non-trivial to implement, but important for C++
974 TRIVIAL_TYPE_CLASS(Elaborated)
976 QualType VisitAttributedType(const AttributedType *T) {
977 QualType modifiedType = recurse(T->getModifiedType());
978 if (modifiedType.isNull())
981 QualType equivalentType = recurse(T->getEquivalentType());
982 if (equivalentType.isNull())
985 if (modifiedType.getAsOpaquePtr()
986 == T->getModifiedType().getAsOpaquePtr() &&
987 equivalentType.getAsOpaquePtr()
988 == T->getEquivalentType().getAsOpaquePtr())
989 return QualType(T, 0);
991 return Ctx.getAttributedType(T->getAttrKind(), modifiedType,
995 QualType VisitSubstTemplateTypeParmType(const SubstTemplateTypeParmType *T) {
996 QualType replacementType = recurse(T->getReplacementType());
997 if (replacementType.isNull())
1000 if (replacementType.getAsOpaquePtr()
1001 == T->getReplacementType().getAsOpaquePtr())
1002 return QualType(T, 0);
1004 return Ctx.getSubstTemplateTypeParmType(T->getReplacedParameter(),
1008 // FIXME: Non-trivial to implement, but important for C++
1009 TRIVIAL_TYPE_CLASS(TemplateSpecialization)
1011 QualType VisitAutoType(const AutoType *T) {
1012 if (!T->isDeduced())
1013 return QualType(T, 0);
1015 QualType deducedType = recurse(T->getDeducedType());
1016 if (deducedType.isNull())
1019 if (deducedType.getAsOpaquePtr()
1020 == T->getDeducedType().getAsOpaquePtr())
1021 return QualType(T, 0);
1023 return Ctx.getAutoType(deducedType, T->getKeyword(),
1024 T->isDependentType());
1027 // FIXME: Non-trivial to implement, but important for C++
1028 TRIVIAL_TYPE_CLASS(PackExpansion)
1030 QualType VisitObjCObjectType(const ObjCObjectType *T) {
1031 QualType baseType = recurse(T->getBaseType());
1032 if (baseType.isNull())
1035 // Transform type arguments.
1036 bool typeArgChanged = false;
1037 SmallVector<QualType, 4> typeArgs;
1038 for (auto typeArg : T->getTypeArgsAsWritten()) {
1039 QualType newTypeArg = recurse(typeArg);
1040 if (newTypeArg.isNull())
1043 if (newTypeArg.getAsOpaquePtr() != typeArg.getAsOpaquePtr())
1044 typeArgChanged = true;
1046 typeArgs.push_back(newTypeArg);
1049 if (baseType.getAsOpaquePtr() == T->getBaseType().getAsOpaquePtr() &&
1051 return QualType(T, 0);
1053 return Ctx.getObjCObjectType(baseType, typeArgs,
1054 llvm::makeArrayRef(T->qual_begin(),
1055 T->getNumProtocols()),
1056 T->isKindOfTypeAsWritten());
1059 TRIVIAL_TYPE_CLASS(ObjCInterface)
1061 QualType VisitObjCObjectPointerType(const ObjCObjectPointerType *T) {
1062 QualType pointeeType = recurse(T->getPointeeType());
1063 if (pointeeType.isNull())
1066 if (pointeeType.getAsOpaquePtr()
1067 == T->getPointeeType().getAsOpaquePtr())
1068 return QualType(T, 0);
1070 return Ctx.getObjCObjectPointerType(pointeeType);
1073 QualType VisitAtomicType(const AtomicType *T) {
1074 QualType valueType = recurse(T->getValueType());
1075 if (valueType.isNull())
1078 if (valueType.getAsOpaquePtr()
1079 == T->getValueType().getAsOpaquePtr())
1080 return QualType(T, 0);
1082 return Ctx.getAtomicType(valueType);
1085 #undef TRIVIAL_TYPE_CLASS
1090 /// Perform a simple type transformation that does not change the
1091 /// semantics of the type.
1092 template<typename F>
1093 static QualType simpleTransform(ASTContext &ctx, QualType type, F &&f) {
1094 // Transform the type. If it changed, return the transformed result.
1095 QualType transformed = f(type);
1096 if (transformed.getAsOpaquePtr() != type.getAsOpaquePtr())
1099 // Split out the qualifiers from the type.
1100 SplitQualType splitType = type.split();
1102 // Visit the type itself.
1103 SimpleTransformVisitor<F> visitor(ctx, std::forward<F>(f));
1104 QualType result = visitor.Visit(splitType.Ty);
1105 if (result.isNull())
1108 // Reconstruct the transformed type by applying the local qualifiers
1109 // from the split type.
1110 return ctx.getQualifiedType(result, splitType.Quals);
1113 /// Substitute the given type arguments for Objective-C type
1114 /// parameters within the given type, recursively.
1115 QualType QualType::substObjCTypeArgs(
1117 ArrayRef<QualType> typeArgs,
1118 ObjCSubstitutionContext context) const {
1119 return simpleTransform(ctx, *this,
1120 [&](QualType type) -> QualType {
1121 SplitQualType splitType = type.split();
1123 // Replace an Objective-C type parameter reference with the corresponding
1125 if (const auto *OTPTy = dyn_cast<ObjCTypeParamType>(splitType.Ty)) {
1126 if (auto *typeParam = dyn_cast<ObjCTypeParamDecl>(OTPTy->getDecl())) {
1127 // If we have type arguments, use them.
1128 if (!typeArgs.empty()) {
1129 QualType argType = typeArgs[typeParam->getIndex()];
1130 if (OTPTy->qual_empty())
1131 return ctx.getQualifiedType(argType, splitType.Quals);
1133 // Apply protocol lists if exists.
1135 SmallVector<ObjCProtocolDecl*, 8> protocolsVec;
1136 protocolsVec.append(OTPTy->qual_begin(),
1138 ArrayRef<ObjCProtocolDecl *> protocolsToApply = protocolsVec;
1139 QualType resultTy = ctx.applyObjCProtocolQualifiers(argType,
1140 protocolsToApply, hasError, true/*allowOnPointerType*/);
1142 return ctx.getQualifiedType(resultTy, splitType.Quals);
1146 case ObjCSubstitutionContext::Ordinary:
1147 case ObjCSubstitutionContext::Parameter:
1148 case ObjCSubstitutionContext::Superclass:
1149 // Substitute the bound.
1150 return ctx.getQualifiedType(typeParam->getUnderlyingType(),
1153 case ObjCSubstitutionContext::Result:
1154 case ObjCSubstitutionContext::Property: {
1155 // Substitute the __kindof form of the underlying type.
1156 const auto *objPtr = typeParam->getUnderlyingType()
1157 ->castAs<ObjCObjectPointerType>();
1159 // __kindof types, id, and Class don't need an additional
1161 if (objPtr->isKindOfType() || objPtr->isObjCIdOrClassType())
1162 return ctx.getQualifiedType(typeParam->getUnderlyingType(),
1166 const auto *obj = objPtr->getObjectType();
1167 QualType resultTy = ctx.getObjCObjectType(obj->getBaseType(),
1168 obj->getTypeArgsAsWritten(),
1169 obj->getProtocols(),
1172 // Rebuild object pointer type.
1173 resultTy = ctx.getObjCObjectPointerType(resultTy);
1174 return ctx.getQualifiedType(resultTy, splitType.Quals);
1180 // If we have a function type, update the context appropriately.
1181 if (const auto *funcType = dyn_cast<FunctionType>(splitType.Ty)) {
1182 // Substitute result type.
1183 QualType returnType = funcType->getReturnType().substObjCTypeArgs(
1186 ObjCSubstitutionContext::Result);
1187 if (returnType.isNull())
1190 // Handle non-prototyped functions, which only substitute into the result
1192 if (isa<FunctionNoProtoType>(funcType)) {
1193 // If the return type was unchanged, do nothing.
1194 if (returnType.getAsOpaquePtr()
1195 == funcType->getReturnType().getAsOpaquePtr())
1198 // Otherwise, build a new type.
1199 return ctx.getFunctionNoProtoType(returnType, funcType->getExtInfo());
1202 const auto *funcProtoType = cast<FunctionProtoType>(funcType);
1204 // Transform parameter types.
1205 SmallVector<QualType, 4> paramTypes;
1206 bool paramChanged = false;
1207 for (auto paramType : funcProtoType->getParamTypes()) {
1208 QualType newParamType = paramType.substObjCTypeArgs(
1211 ObjCSubstitutionContext::Parameter);
1212 if (newParamType.isNull())
1215 if (newParamType.getAsOpaquePtr() != paramType.getAsOpaquePtr())
1216 paramChanged = true;
1218 paramTypes.push_back(newParamType);
1221 // Transform extended info.
1222 FunctionProtoType::ExtProtoInfo info = funcProtoType->getExtProtoInfo();
1223 bool exceptionChanged = false;
1224 if (info.ExceptionSpec.Type == EST_Dynamic) {
1225 SmallVector<QualType, 4> exceptionTypes;
1226 for (auto exceptionType : info.ExceptionSpec.Exceptions) {
1227 QualType newExceptionType = exceptionType.substObjCTypeArgs(
1230 ObjCSubstitutionContext::Ordinary);
1231 if (newExceptionType.isNull())
1234 if (newExceptionType.getAsOpaquePtr()
1235 != exceptionType.getAsOpaquePtr())
1236 exceptionChanged = true;
1238 exceptionTypes.push_back(newExceptionType);
1241 if (exceptionChanged) {
1242 info.ExceptionSpec.Exceptions =
1243 llvm::makeArrayRef(exceptionTypes).copy(ctx);
1247 if (returnType.getAsOpaquePtr()
1248 == funcProtoType->getReturnType().getAsOpaquePtr() &&
1249 !paramChanged && !exceptionChanged)
1252 return ctx.getFunctionType(returnType, paramTypes, info);
1255 // Substitute into the type arguments of a specialized Objective-C object
1257 if (const auto *objcObjectType = dyn_cast<ObjCObjectType>(splitType.Ty)) {
1258 if (objcObjectType->isSpecializedAsWritten()) {
1259 SmallVector<QualType, 4> newTypeArgs;
1260 bool anyChanged = false;
1261 for (auto typeArg : objcObjectType->getTypeArgsAsWritten()) {
1262 QualType newTypeArg = typeArg.substObjCTypeArgs(
1264 ObjCSubstitutionContext::Ordinary);
1265 if (newTypeArg.isNull())
1268 if (newTypeArg.getAsOpaquePtr() != typeArg.getAsOpaquePtr()) {
1269 // If we're substituting based on an unspecialized context type,
1270 // produce an unspecialized type.
1271 ArrayRef<ObjCProtocolDecl *> protocols(
1272 objcObjectType->qual_begin(),
1273 objcObjectType->getNumProtocols());
1274 if (typeArgs.empty() &&
1275 context != ObjCSubstitutionContext::Superclass) {
1276 return ctx.getObjCObjectType(
1277 objcObjectType->getBaseType(), {},
1279 objcObjectType->isKindOfTypeAsWritten());
1285 newTypeArgs.push_back(newTypeArg);
1289 ArrayRef<ObjCProtocolDecl *> protocols(
1290 objcObjectType->qual_begin(),
1291 objcObjectType->getNumProtocols());
1292 return ctx.getObjCObjectType(objcObjectType->getBaseType(),
1293 newTypeArgs, protocols,
1294 objcObjectType->isKindOfTypeAsWritten());
1305 QualType QualType::substObjCMemberType(QualType objectType,
1306 const DeclContext *dc,
1307 ObjCSubstitutionContext context) const {
1308 if (auto subs = objectType->getObjCSubstitutions(dc))
1309 return substObjCTypeArgs(dc->getParentASTContext(), *subs, context);
1314 QualType QualType::stripObjCKindOfType(const ASTContext &constCtx) const {
1315 // FIXME: Because ASTContext::getAttributedType() is non-const.
1316 auto &ctx = const_cast<ASTContext &>(constCtx);
1317 return simpleTransform(ctx, *this,
1318 [&](QualType type) -> QualType {
1319 SplitQualType splitType = type.split();
1320 if (auto *objType = splitType.Ty->getAs<ObjCObjectType>()) {
1321 if (!objType->isKindOfType())
1325 = objType->getBaseType().stripObjCKindOfType(ctx);
1326 return ctx.getQualifiedType(
1327 ctx.getObjCObjectType(baseType,
1328 objType->getTypeArgsAsWritten(),
1329 objType->getProtocols(),
1330 /*isKindOf=*/false),
1338 QualType QualType::getAtomicUnqualifiedType() const {
1339 if (auto AT = getTypePtr()->getAs<AtomicType>())
1340 return AT->getValueType().getUnqualifiedType();
1341 return getUnqualifiedType();
1344 Optional<ArrayRef<QualType>> Type::getObjCSubstitutions(
1345 const DeclContext *dc) const {
1346 // Look through method scopes.
1347 if (auto method = dyn_cast<ObjCMethodDecl>(dc))
1348 dc = method->getDeclContext();
1350 // Find the class or category in which the type we're substituting
1352 const ObjCInterfaceDecl *dcClassDecl = dyn_cast<ObjCInterfaceDecl>(dc);
1353 const ObjCCategoryDecl *dcCategoryDecl = nullptr;
1354 ObjCTypeParamList *dcTypeParams = nullptr;
1356 // If the class does not have any type parameters, there's no
1357 // substitution to do.
1358 dcTypeParams = dcClassDecl->getTypeParamList();
1362 // If we are in neither a class nor a category, there's no
1363 // substitution to perform.
1364 dcCategoryDecl = dyn_cast<ObjCCategoryDecl>(dc);
1365 if (!dcCategoryDecl)
1368 // If the category does not have any type parameters, there's no
1369 // substitution to do.
1370 dcTypeParams = dcCategoryDecl->getTypeParamList();
1374 dcClassDecl = dcCategoryDecl->getClassInterface();
1378 assert(dcTypeParams && "No substitutions to perform");
1379 assert(dcClassDecl && "No class context");
1381 // Find the underlying object type.
1382 const ObjCObjectType *objectType;
1383 if (const auto *objectPointerType = getAs<ObjCObjectPointerType>()) {
1384 objectType = objectPointerType->getObjectType();
1385 } else if (getAs<BlockPointerType>()) {
1386 ASTContext &ctx = dc->getParentASTContext();
1387 objectType = ctx.getObjCObjectType(ctx.ObjCBuiltinIdTy, {}, {})
1388 ->castAs<ObjCObjectType>();
1390 objectType = getAs<ObjCObjectType>();
1393 /// Extract the class from the receiver object type.
1394 ObjCInterfaceDecl *curClassDecl = objectType ? objectType->getInterface()
1396 if (!curClassDecl) {
1397 // If we don't have a context type (e.g., this is "id" or some
1398 // variant thereof), substitute the bounds.
1399 return llvm::ArrayRef<QualType>();
1402 // Follow the superclass chain until we've mapped the receiver type
1403 // to the same class as the context.
1404 while (curClassDecl != dcClassDecl) {
1405 // Map to the superclass type.
1406 QualType superType = objectType->getSuperClassType();
1407 if (superType.isNull()) {
1408 objectType = nullptr;
1412 objectType = superType->castAs<ObjCObjectType>();
1413 curClassDecl = objectType->getInterface();
1416 // If we don't have a receiver type, or the receiver type does not
1417 // have type arguments, substitute in the defaults.
1418 if (!objectType || objectType->isUnspecialized()) {
1419 return llvm::ArrayRef<QualType>();
1422 // The receiver type has the type arguments we want.
1423 return objectType->getTypeArgs();
1426 bool Type::acceptsObjCTypeParams() const {
1427 if (auto *IfaceT = getAsObjCInterfaceType()) {
1428 if (auto *ID = IfaceT->getInterface()) {
1429 if (ID->getTypeParamList())
1437 void ObjCObjectType::computeSuperClassTypeSlow() const {
1438 // Retrieve the class declaration for this type. If there isn't one
1439 // (e.g., this is some variant of "id" or "Class"), then there is no
1441 ObjCInterfaceDecl *classDecl = getInterface();
1443 CachedSuperClassType.setInt(true);
1447 // Extract the superclass type.
1448 const ObjCObjectType *superClassObjTy = classDecl->getSuperClassType();
1449 if (!superClassObjTy) {
1450 CachedSuperClassType.setInt(true);
1454 ObjCInterfaceDecl *superClassDecl = superClassObjTy->getInterface();
1455 if (!superClassDecl) {
1456 CachedSuperClassType.setInt(true);
1460 // If the superclass doesn't have type parameters, then there is no
1461 // substitution to perform.
1462 QualType superClassType(superClassObjTy, 0);
1463 ObjCTypeParamList *superClassTypeParams = superClassDecl->getTypeParamList();
1464 if (!superClassTypeParams) {
1465 CachedSuperClassType.setPointerAndInt(
1466 superClassType->castAs<ObjCObjectType>(), true);
1470 // If the superclass reference is unspecialized, return it.
1471 if (superClassObjTy->isUnspecialized()) {
1472 CachedSuperClassType.setPointerAndInt(superClassObjTy, true);
1476 // If the subclass is not parameterized, there aren't any type
1477 // parameters in the superclass reference to substitute.
1478 ObjCTypeParamList *typeParams = classDecl->getTypeParamList();
1480 CachedSuperClassType.setPointerAndInt(
1481 superClassType->castAs<ObjCObjectType>(), true);
1485 // If the subclass type isn't specialized, return the unspecialized
1487 if (isUnspecialized()) {
1488 QualType unspecializedSuper
1489 = classDecl->getASTContext().getObjCInterfaceType(
1490 superClassObjTy->getInterface());
1491 CachedSuperClassType.setPointerAndInt(
1492 unspecializedSuper->castAs<ObjCObjectType>(),
1497 // Substitute the provided type arguments into the superclass type.
1498 ArrayRef<QualType> typeArgs = getTypeArgs();
1499 assert(typeArgs.size() == typeParams->size());
1500 CachedSuperClassType.setPointerAndInt(
1501 superClassType.substObjCTypeArgs(classDecl->getASTContext(), typeArgs,
1502 ObjCSubstitutionContext::Superclass)
1503 ->castAs<ObjCObjectType>(),
1507 const ObjCInterfaceType *ObjCObjectPointerType::getInterfaceType() const {
1508 if (auto interfaceDecl = getObjectType()->getInterface()) {
1509 return interfaceDecl->getASTContext().getObjCInterfaceType(interfaceDecl)
1510 ->castAs<ObjCInterfaceType>();
1516 QualType ObjCObjectPointerType::getSuperClassType() const {
1517 QualType superObjectType = getObjectType()->getSuperClassType();
1518 if (superObjectType.isNull())
1519 return superObjectType;
1521 ASTContext &ctx = getInterfaceDecl()->getASTContext();
1522 return ctx.getObjCObjectPointerType(superObjectType);
1525 const ObjCObjectType *Type::getAsObjCQualifiedInterfaceType() const {
1526 // There is no sugar for ObjCObjectType's, just return the canonical
1527 // type pointer if it is the right class. There is no typedef information to
1528 // return and these cannot be Address-space qualified.
1529 if (const ObjCObjectType *T = getAs<ObjCObjectType>())
1530 if (T->getNumProtocols() && T->getInterface())
1535 bool Type::isObjCQualifiedInterfaceType() const {
1536 return getAsObjCQualifiedInterfaceType() != nullptr;
1539 const ObjCObjectPointerType *Type::getAsObjCQualifiedIdType() const {
1540 // There is no sugar for ObjCQualifiedIdType's, just return the canonical
1541 // type pointer if it is the right class.
1542 if (const ObjCObjectPointerType *OPT = getAs<ObjCObjectPointerType>()) {
1543 if (OPT->isObjCQualifiedIdType())
1549 const ObjCObjectPointerType *Type::getAsObjCQualifiedClassType() const {
1550 // There is no sugar for ObjCQualifiedClassType's, just return the canonical
1551 // type pointer if it is the right class.
1552 if (const ObjCObjectPointerType *OPT = getAs<ObjCObjectPointerType>()) {
1553 if (OPT->isObjCQualifiedClassType())
1559 const ObjCObjectType *Type::getAsObjCInterfaceType() const {
1560 if (const ObjCObjectType *OT = getAs<ObjCObjectType>()) {
1561 if (OT->getInterface())
1567 const ObjCObjectPointerType *Type::getAsObjCInterfacePointerType() const {
1568 if (const ObjCObjectPointerType *OPT = getAs<ObjCObjectPointerType>()) {
1569 if (OPT->getInterfaceType())
1575 const CXXRecordDecl *Type::getPointeeCXXRecordDecl() const {
1576 QualType PointeeType;
1577 if (const PointerType *PT = getAs<PointerType>())
1578 PointeeType = PT->getPointeeType();
1579 else if (const ReferenceType *RT = getAs<ReferenceType>())
1580 PointeeType = RT->getPointeeType();
1584 if (const RecordType *RT = PointeeType->getAs<RecordType>())
1585 return dyn_cast<CXXRecordDecl>(RT->getDecl());
1590 CXXRecordDecl *Type::getAsCXXRecordDecl() const {
1591 return dyn_cast_or_null<CXXRecordDecl>(getAsTagDecl());
1594 TagDecl *Type::getAsTagDecl() const {
1595 if (const auto *TT = getAs<TagType>())
1596 return cast<TagDecl>(TT->getDecl());
1597 if (const auto *Injected = getAs<InjectedClassNameType>())
1598 return Injected->getDecl();
1605 class GetContainedDeducedTypeVisitor :
1606 public TypeVisitor<GetContainedDeducedTypeVisitor, Type*> {
1610 GetContainedDeducedTypeVisitor(bool Syntactic = false)
1611 : Syntactic(Syntactic) {}
1613 using TypeVisitor<GetContainedDeducedTypeVisitor, Type*>::Visit;
1615 Type *Visit(QualType T) {
1618 return Visit(T.getTypePtr());
1621 // The deduced type itself.
1622 Type *VisitDeducedType(const DeducedType *AT) {
1623 return const_cast<DeducedType*>(AT);
1626 // Only these types can contain the desired 'auto' type.
1628 Type *VisitElaboratedType(const ElaboratedType *T) {
1629 return Visit(T->getNamedType());
1632 Type *VisitPointerType(const PointerType *T) {
1633 return Visit(T->getPointeeType());
1636 Type *VisitBlockPointerType(const BlockPointerType *T) {
1637 return Visit(T->getPointeeType());
1640 Type *VisitReferenceType(const ReferenceType *T) {
1641 return Visit(T->getPointeeTypeAsWritten());
1644 Type *VisitMemberPointerType(const MemberPointerType *T) {
1645 return Visit(T->getPointeeType());
1648 Type *VisitArrayType(const ArrayType *T) {
1649 return Visit(T->getElementType());
1652 Type *VisitDependentSizedExtVectorType(
1653 const DependentSizedExtVectorType *T) {
1654 return Visit(T->getElementType());
1657 Type *VisitVectorType(const VectorType *T) {
1658 return Visit(T->getElementType());
1661 Type *VisitFunctionProtoType(const FunctionProtoType *T) {
1662 if (Syntactic && T->hasTrailingReturn())
1663 return const_cast<FunctionProtoType*>(T);
1664 return VisitFunctionType(T);
1667 Type *VisitFunctionType(const FunctionType *T) {
1668 return Visit(T->getReturnType());
1671 Type *VisitParenType(const ParenType *T) {
1672 return Visit(T->getInnerType());
1675 Type *VisitAttributedType(const AttributedType *T) {
1676 return Visit(T->getModifiedType());
1679 Type *VisitAdjustedType(const AdjustedType *T) {
1680 return Visit(T->getOriginalType());
1686 DeducedType *Type::getContainedDeducedType() const {
1687 return cast_or_null<DeducedType>(
1688 GetContainedDeducedTypeVisitor().Visit(this));
1691 bool Type::hasAutoForTrailingReturnType() const {
1692 return dyn_cast_or_null<FunctionType>(
1693 GetContainedDeducedTypeVisitor(true).Visit(this));
1696 bool Type::hasIntegerRepresentation() const {
1697 if (const VectorType *VT = dyn_cast<VectorType>(CanonicalType))
1698 return VT->getElementType()->isIntegerType();
1700 return isIntegerType();
1703 /// \brief Determine whether this type is an integral type.
1705 /// This routine determines whether the given type is an integral type per
1706 /// C++ [basic.fundamental]p7. Although the C standard does not define the
1707 /// term "integral type", it has a similar term "integer type", and in C++
1708 /// the two terms are equivalent. However, C's "integer type" includes
1709 /// enumeration types, while C++'s "integer type" does not. The \c ASTContext
1710 /// parameter is used to determine whether we should be following the C or
1711 /// C++ rules when determining whether this type is an integral/integer type.
1713 /// For cases where C permits "an integer type" and C++ permits "an integral
1714 /// type", use this routine.
1716 /// For cases where C permits "an integer type" and C++ permits "an integral
1717 /// or enumeration type", use \c isIntegralOrEnumerationType() instead.
1719 /// \param Ctx The context in which this type occurs.
1721 /// \returns true if the type is considered an integral type, false otherwise.
1722 bool Type::isIntegralType(const ASTContext &Ctx) const {
1723 if (const BuiltinType *BT = dyn_cast<BuiltinType>(CanonicalType))
1724 return BT->getKind() >= BuiltinType::Bool &&
1725 BT->getKind() <= BuiltinType::Int128;
1727 // Complete enum types are integral in C.
1728 if (!Ctx.getLangOpts().CPlusPlus)
1729 if (const EnumType *ET = dyn_cast<EnumType>(CanonicalType))
1730 return ET->getDecl()->isComplete();
1735 bool Type::isIntegralOrUnscopedEnumerationType() const {
1736 if (const BuiltinType *BT = dyn_cast<BuiltinType>(CanonicalType))
1737 return BT->getKind() >= BuiltinType::Bool &&
1738 BT->getKind() <= BuiltinType::Int128;
1740 // Check for a complete enum type; incomplete enum types are not properly an
1741 // enumeration type in the sense required here.
1742 // C++0x: However, if the underlying type of the enum is fixed, it is
1743 // considered complete.
1744 if (const EnumType *ET = dyn_cast<EnumType>(CanonicalType))
1745 return ET->getDecl()->isComplete() && !ET->getDecl()->isScoped();
1750 bool Type::isCharType() const {
1751 if (const BuiltinType *BT = dyn_cast<BuiltinType>(CanonicalType))
1752 return BT->getKind() == BuiltinType::Char_U ||
1753 BT->getKind() == BuiltinType::UChar ||
1754 BT->getKind() == BuiltinType::Char_S ||
1755 BT->getKind() == BuiltinType::SChar;
1759 bool Type::isWideCharType() const {
1760 if (const BuiltinType *BT = dyn_cast<BuiltinType>(CanonicalType))
1761 return BT->getKind() == BuiltinType::WChar_S ||
1762 BT->getKind() == BuiltinType::WChar_U;
1766 bool Type::isChar16Type() const {
1767 if (const BuiltinType *BT = dyn_cast<BuiltinType>(CanonicalType))
1768 return BT->getKind() == BuiltinType::Char16;
1772 bool Type::isChar32Type() const {
1773 if (const BuiltinType *BT = dyn_cast<BuiltinType>(CanonicalType))
1774 return BT->getKind() == BuiltinType::Char32;
1778 /// \brief Determine whether this type is any of the built-in character
1780 bool Type::isAnyCharacterType() const {
1781 const BuiltinType *BT = dyn_cast<BuiltinType>(CanonicalType);
1782 if (!BT) return false;
1783 switch (BT->getKind()) {
1784 default: return false;
1785 case BuiltinType::Char_U:
1786 case BuiltinType::UChar:
1787 case BuiltinType::WChar_U:
1788 case BuiltinType::Char16:
1789 case BuiltinType::Char32:
1790 case BuiltinType::Char_S:
1791 case BuiltinType::SChar:
1792 case BuiltinType::WChar_S:
1797 /// isSignedIntegerType - Return true if this is an integer type that is
1798 /// signed, according to C99 6.2.5p4 [char, signed char, short, int, long..],
1799 /// an enum decl which has a signed representation
1800 bool Type::isSignedIntegerType() const {
1801 if (const BuiltinType *BT = dyn_cast<BuiltinType>(CanonicalType)) {
1802 return BT->getKind() >= BuiltinType::Char_S &&
1803 BT->getKind() <= BuiltinType::Int128;
1806 if (const EnumType *ET = dyn_cast<EnumType>(CanonicalType)) {
1807 // Incomplete enum types are not treated as integer types.
1808 // FIXME: In C++, enum types are never integer types.
1809 if (ET->getDecl()->isComplete() && !ET->getDecl()->isScoped())
1810 return ET->getDecl()->getIntegerType()->isSignedIntegerType();
1816 bool Type::isSignedIntegerOrEnumerationType() const {
1817 if (const BuiltinType *BT = dyn_cast<BuiltinType>(CanonicalType)) {
1818 return BT->getKind() >= BuiltinType::Char_S &&
1819 BT->getKind() <= BuiltinType::Int128;
1822 if (const EnumType *ET = dyn_cast<EnumType>(CanonicalType)) {
1823 if (ET->getDecl()->isComplete())
1824 return ET->getDecl()->getIntegerType()->isSignedIntegerType();
1830 bool Type::hasSignedIntegerRepresentation() const {
1831 if (const VectorType *VT = dyn_cast<VectorType>(CanonicalType))
1832 return VT->getElementType()->isSignedIntegerOrEnumerationType();
1834 return isSignedIntegerOrEnumerationType();
1837 /// isUnsignedIntegerType - Return true if this is an integer type that is
1838 /// unsigned, according to C99 6.2.5p6 [which returns true for _Bool], an enum
1839 /// decl which has an unsigned representation
1840 bool Type::isUnsignedIntegerType() const {
1841 if (const BuiltinType *BT = dyn_cast<BuiltinType>(CanonicalType)) {
1842 return BT->getKind() >= BuiltinType::Bool &&
1843 BT->getKind() <= BuiltinType::UInt128;
1846 if (const EnumType *ET = dyn_cast<EnumType>(CanonicalType)) {
1847 // Incomplete enum types are not treated as integer types.
1848 // FIXME: In C++, enum types are never integer types.
1849 if (ET->getDecl()->isComplete() && !ET->getDecl()->isScoped())
1850 return ET->getDecl()->getIntegerType()->isUnsignedIntegerType();
1856 bool Type::isUnsignedIntegerOrEnumerationType() const {
1857 if (const BuiltinType *BT = dyn_cast<BuiltinType>(CanonicalType)) {
1858 return BT->getKind() >= BuiltinType::Bool &&
1859 BT->getKind() <= BuiltinType::UInt128;
1862 if (const EnumType *ET = dyn_cast<EnumType>(CanonicalType)) {
1863 if (ET->getDecl()->isComplete())
1864 return ET->getDecl()->getIntegerType()->isUnsignedIntegerType();
1870 bool Type::hasUnsignedIntegerRepresentation() const {
1871 if (const VectorType *VT = dyn_cast<VectorType>(CanonicalType))
1872 return VT->getElementType()->isUnsignedIntegerOrEnumerationType();
1874 return isUnsignedIntegerOrEnumerationType();
1877 bool Type::isFloatingType() const {
1878 if (const BuiltinType *BT = dyn_cast<BuiltinType>(CanonicalType))
1879 return BT->getKind() >= BuiltinType::Half &&
1880 BT->getKind() <= BuiltinType::Float128;
1881 if (const ComplexType *CT = dyn_cast<ComplexType>(CanonicalType))
1882 return CT->getElementType()->isFloatingType();
1886 bool Type::hasFloatingRepresentation() const {
1887 if (const VectorType *VT = dyn_cast<VectorType>(CanonicalType))
1888 return VT->getElementType()->isFloatingType();
1890 return isFloatingType();
1893 bool Type::isRealFloatingType() const {
1894 if (const BuiltinType *BT = dyn_cast<BuiltinType>(CanonicalType))
1895 return BT->isFloatingPoint();
1899 bool Type::isRealType() const {
1900 if (const BuiltinType *BT = dyn_cast<BuiltinType>(CanonicalType))
1901 return BT->getKind() >= BuiltinType::Bool &&
1902 BT->getKind() <= BuiltinType::Float128;
1903 if (const EnumType *ET = dyn_cast<EnumType>(CanonicalType))
1904 return ET->getDecl()->isComplete() && !ET->getDecl()->isScoped();
1908 bool Type::isArithmeticType() const {
1909 if (const BuiltinType *BT = dyn_cast<BuiltinType>(CanonicalType))
1910 return BT->getKind() >= BuiltinType::Bool &&
1911 BT->getKind() <= BuiltinType::Float128;
1912 if (const EnumType *ET = dyn_cast<EnumType>(CanonicalType))
1913 // GCC allows forward declaration of enum types (forbid by C99 6.7.2.3p2).
1914 // If a body isn't seen by the time we get here, return false.
1916 // C++0x: Enumerations are not arithmetic types. For now, just return
1917 // false for scoped enumerations since that will disable any
1918 // unwanted implicit conversions.
1919 return !ET->getDecl()->isScoped() && ET->getDecl()->isComplete();
1920 return isa<ComplexType>(CanonicalType);
1923 Type::ScalarTypeKind Type::getScalarTypeKind() const {
1924 assert(isScalarType());
1926 const Type *T = CanonicalType.getTypePtr();
1927 if (const BuiltinType *BT = dyn_cast<BuiltinType>(T)) {
1928 if (BT->getKind() == BuiltinType::Bool) return STK_Bool;
1929 if (BT->getKind() == BuiltinType::NullPtr) return STK_CPointer;
1930 if (BT->isInteger()) return STK_Integral;
1931 if (BT->isFloatingPoint()) return STK_Floating;
1932 llvm_unreachable("unknown scalar builtin type");
1933 } else if (isa<PointerType>(T)) {
1934 return STK_CPointer;
1935 } else if (isa<BlockPointerType>(T)) {
1936 return STK_BlockPointer;
1937 } else if (isa<ObjCObjectPointerType>(T)) {
1938 return STK_ObjCObjectPointer;
1939 } else if (isa<MemberPointerType>(T)) {
1940 return STK_MemberPointer;
1941 } else if (isa<EnumType>(T)) {
1942 assert(cast<EnumType>(T)->getDecl()->isComplete());
1943 return STK_Integral;
1944 } else if (const ComplexType *CT = dyn_cast<ComplexType>(T)) {
1945 if (CT->getElementType()->isRealFloatingType())
1946 return STK_FloatingComplex;
1947 return STK_IntegralComplex;
1950 llvm_unreachable("unknown scalar type");
1953 /// \brief Determines whether the type is a C++ aggregate type or C
1954 /// aggregate or union type.
1956 /// An aggregate type is an array or a class type (struct, union, or
1957 /// class) that has no user-declared constructors, no private or
1958 /// protected non-static data members, no base classes, and no virtual
1959 /// functions (C++ [dcl.init.aggr]p1). The notion of an aggregate type
1960 /// subsumes the notion of C aggregates (C99 6.2.5p21) because it also
1961 /// includes union types.
1962 bool Type::isAggregateType() const {
1963 if (const RecordType *Record = dyn_cast<RecordType>(CanonicalType)) {
1964 if (CXXRecordDecl *ClassDecl = dyn_cast<CXXRecordDecl>(Record->getDecl()))
1965 return ClassDecl->isAggregate();
1970 return isa<ArrayType>(CanonicalType);
1973 /// isConstantSizeType - Return true if this is not a variable sized type,
1974 /// according to the rules of C99 6.7.5p3. It is not legal to call this on
1975 /// incomplete types or dependent types.
1976 bool Type::isConstantSizeType() const {
1977 assert(!isIncompleteType() && "This doesn't make sense for incomplete types");
1978 assert(!isDependentType() && "This doesn't make sense for dependent types");
1979 // The VAT must have a size, as it is known to be complete.
1980 return !isa<VariableArrayType>(CanonicalType);
1983 /// isIncompleteType - Return true if this is an incomplete type (C99 6.2.5p1)
1984 /// - a type that can describe objects, but which lacks information needed to
1985 /// determine its size.
1986 bool Type::isIncompleteType(NamedDecl **Def) const {
1990 switch (CanonicalType->getTypeClass()) {
1991 default: return false;
1993 // Void is the only incomplete builtin type. Per C99 6.2.5p19, it can never
1995 return isVoidType();
1997 EnumDecl *EnumD = cast<EnumType>(CanonicalType)->getDecl();
2001 // An enumeration with fixed underlying type is complete (C++0x 7.2p3).
2002 if (EnumD->isFixed())
2005 return !EnumD->isCompleteDefinition();
2008 // A tagged type (struct/union/enum/class) is incomplete if the decl is a
2009 // forward declaration, but not a full definition (C99 6.2.5p22).
2010 RecordDecl *Rec = cast<RecordType>(CanonicalType)->getDecl();
2013 return !Rec->isCompleteDefinition();
2016 // An array is incomplete if its element type is incomplete
2017 // (C++ [dcl.array]p1).
2018 // We don't handle variable arrays (they're not allowed in C++) or
2019 // dependent-sized arrays (dependent types are never treated as incomplete).
2020 return cast<ArrayType>(CanonicalType)->getElementType()
2021 ->isIncompleteType(Def);
2022 case IncompleteArray:
2023 // An array of unknown size is an incomplete type (C99 6.2.5p22).
2025 case MemberPointer: {
2026 // Member pointers in the MS ABI have special behavior in
2027 // RequireCompleteType: they attach a MSInheritanceAttr to the CXXRecordDecl
2028 // to indicate which inheritance model to use.
2029 auto *MPTy = cast<MemberPointerType>(CanonicalType);
2030 const Type *ClassTy = MPTy->getClass();
2031 // Member pointers with dependent class types don't get special treatment.
2032 if (ClassTy->isDependentType())
2034 const CXXRecordDecl *RD = ClassTy->getAsCXXRecordDecl();
2035 ASTContext &Context = RD->getASTContext();
2036 // Member pointers not in the MS ABI don't get special treatment.
2037 if (!Context.getTargetInfo().getCXXABI().isMicrosoft())
2039 // The inheritance attribute might only be present on the most recent
2040 // CXXRecordDecl, use that one.
2041 RD = RD->getMostRecentDecl();
2042 // Nothing interesting to do if the inheritance attribute is already set.
2043 if (RD->hasAttr<MSInheritanceAttr>())
2048 return cast<ObjCObjectType>(CanonicalType)->getBaseType()
2049 ->isIncompleteType(Def);
2050 case ObjCInterface: {
2051 // ObjC interfaces are incomplete if they are @class, not @interface.
2052 ObjCInterfaceDecl *Interface
2053 = cast<ObjCInterfaceType>(CanonicalType)->getDecl();
2056 return !Interface->hasDefinition();
2061 bool QualType::isPODType(const ASTContext &Context) const {
2062 // C++11 has a more relaxed definition of POD.
2063 if (Context.getLangOpts().CPlusPlus11)
2064 return isCXX11PODType(Context);
2066 return isCXX98PODType(Context);
2069 bool QualType::isCXX98PODType(const ASTContext &Context) const {
2070 // The compiler shouldn't query this for incomplete types, but the user might.
2071 // We return false for that case. Except for incomplete arrays of PODs, which
2072 // are PODs according to the standard.
2076 if ((*this)->isIncompleteArrayType())
2077 return Context.getBaseElementType(*this).isCXX98PODType(Context);
2079 if ((*this)->isIncompleteType())
2082 if (hasNonTrivialObjCLifetime())
2085 QualType CanonicalType = getTypePtr()->CanonicalType;
2086 switch (CanonicalType->getTypeClass()) {
2087 // Everything not explicitly mentioned is not POD.
2088 default: return false;
2089 case Type::VariableArray:
2090 case Type::ConstantArray:
2091 // IncompleteArray is handled above.
2092 return Context.getBaseElementType(*this).isCXX98PODType(Context);
2094 case Type::ObjCObjectPointer:
2095 case Type::BlockPointer:
2099 case Type::MemberPointer:
2101 case Type::ExtVector:
2108 if (CXXRecordDecl *ClassDecl
2109 = dyn_cast<CXXRecordDecl>(cast<RecordType>(CanonicalType)->getDecl()))
2110 return ClassDecl->isPOD();
2112 // C struct/union is POD.
2117 bool QualType::isTrivialType(const ASTContext &Context) const {
2118 // The compiler shouldn't query this for incomplete types, but the user might.
2119 // We return false for that case. Except for incomplete arrays of PODs, which
2120 // are PODs according to the standard.
2124 if ((*this)->isArrayType())
2125 return Context.getBaseElementType(*this).isTrivialType(Context);
2127 // Return false for incomplete types after skipping any incomplete array
2128 // types which are expressly allowed by the standard and thus our API.
2129 if ((*this)->isIncompleteType())
2132 if (hasNonTrivialObjCLifetime())
2135 QualType CanonicalType = getTypePtr()->CanonicalType;
2136 if (CanonicalType->isDependentType())
2139 // C++0x [basic.types]p9:
2140 // Scalar types, trivial class types, arrays of such types, and
2141 // cv-qualified versions of these types are collectively called trivial
2144 // As an extension, Clang treats vector types as Scalar types.
2145 if (CanonicalType->isScalarType() || CanonicalType->isVectorType())
2147 if (const RecordType *RT = CanonicalType->getAs<RecordType>()) {
2148 if (const CXXRecordDecl *ClassDecl =
2149 dyn_cast<CXXRecordDecl>(RT->getDecl())) {
2151 // A trivial class is a class that has a default constructor,
2152 // has no non-trivial default constructors, and is trivially
2154 return ClassDecl->hasDefaultConstructor() &&
2155 !ClassDecl->hasNonTrivialDefaultConstructor() &&
2156 ClassDecl->isTriviallyCopyable();
2162 // No other types can match.
2166 bool QualType::isTriviallyCopyableType(const ASTContext &Context) const {
2167 if ((*this)->isArrayType())
2168 return Context.getBaseElementType(*this).isTriviallyCopyableType(Context);
2170 if (hasNonTrivialObjCLifetime())
2173 // C++11 [basic.types]p9 - See Core 2094
2174 // Scalar types, trivially copyable class types, arrays of such types, and
2175 // cv-qualified versions of these types are collectively
2176 // called trivially copyable types.
2178 QualType CanonicalType = getCanonicalType();
2179 if (CanonicalType->isDependentType())
2182 // Return false for incomplete types after skipping any incomplete array types
2183 // which are expressly allowed by the standard and thus our API.
2184 if (CanonicalType->isIncompleteType())
2187 // As an extension, Clang treats vector types as Scalar types.
2188 if (CanonicalType->isScalarType() || CanonicalType->isVectorType())
2191 if (const RecordType *RT = CanonicalType->getAs<RecordType>()) {
2192 if (const CXXRecordDecl *ClassDecl =
2193 dyn_cast<CXXRecordDecl>(RT->getDecl())) {
2194 if (!ClassDecl->isTriviallyCopyable()) return false;
2200 // No other types can match.
2204 bool QualType::isNonWeakInMRRWithObjCWeak(const ASTContext &Context) const {
2205 return !Context.getLangOpts().ObjCAutoRefCount &&
2206 Context.getLangOpts().ObjCWeak &&
2207 getObjCLifetime() != Qualifiers::OCL_Weak;
2210 bool Type::isLiteralType(const ASTContext &Ctx) const {
2211 if (isDependentType())
2214 // C++1y [basic.types]p10:
2215 // A type is a literal type if it is:
2217 if (Ctx.getLangOpts().CPlusPlus14 && isVoidType())
2220 // C++11 [basic.types]p10:
2221 // A type is a literal type if it is:
2223 // -- an array of literal type other than an array of runtime bound; or
2224 if (isVariableArrayType())
2226 const Type *BaseTy = getBaseElementTypeUnsafe();
2227 assert(BaseTy && "NULL element type");
2229 // Return false for incomplete types after skipping any incomplete array
2230 // types; those are expressly allowed by the standard and thus our API.
2231 if (BaseTy->isIncompleteType())
2234 // C++11 [basic.types]p10:
2235 // A type is a literal type if it is:
2236 // -- a scalar type; or
2237 // As an extension, Clang treats vector types and complex types as
2239 if (BaseTy->isScalarType() || BaseTy->isVectorType() ||
2240 BaseTy->isAnyComplexType())
2242 // -- a reference type; or
2243 if (BaseTy->isReferenceType())
2245 // -- a class type that has all of the following properties:
2246 if (const RecordType *RT = BaseTy->getAs<RecordType>()) {
2247 // -- a trivial destructor,
2248 // -- every constructor call and full-expression in the
2249 // brace-or-equal-initializers for non-static data members (if any)
2250 // is a constant expression,
2251 // -- it is an aggregate type or has at least one constexpr
2252 // constructor or constructor template that is not a copy or move
2254 // -- all non-static data members and base classes of literal types
2256 // We resolve DR1361 by ignoring the second bullet.
2257 if (const CXXRecordDecl *ClassDecl =
2258 dyn_cast<CXXRecordDecl>(RT->getDecl()))
2259 return ClassDecl->isLiteral();
2264 // We treat _Atomic T as a literal type if T is a literal type.
2265 if (const AtomicType *AT = BaseTy->getAs<AtomicType>())
2266 return AT->getValueType()->isLiteralType(Ctx);
2268 // If this type hasn't been deduced yet, then conservatively assume that
2269 // it'll work out to be a literal type.
2270 if (isa<AutoType>(BaseTy->getCanonicalTypeInternal()))
2276 bool Type::isStandardLayoutType() const {
2277 if (isDependentType())
2280 // C++0x [basic.types]p9:
2281 // Scalar types, standard-layout class types, arrays of such types, and
2282 // cv-qualified versions of these types are collectively called
2283 // standard-layout types.
2284 const Type *BaseTy = getBaseElementTypeUnsafe();
2285 assert(BaseTy && "NULL element type");
2287 // Return false for incomplete types after skipping any incomplete array
2288 // types which are expressly allowed by the standard and thus our API.
2289 if (BaseTy->isIncompleteType())
2292 // As an extension, Clang treats vector types as Scalar types.
2293 if (BaseTy->isScalarType() || BaseTy->isVectorType()) return true;
2294 if (const RecordType *RT = BaseTy->getAs<RecordType>()) {
2295 if (const CXXRecordDecl *ClassDecl =
2296 dyn_cast<CXXRecordDecl>(RT->getDecl()))
2297 if (!ClassDecl->isStandardLayout())
2300 // Default to 'true' for non-C++ class types.
2301 // FIXME: This is a bit dubious, but plain C structs should trivially meet
2302 // all the requirements of standard layout classes.
2306 // No other types can match.
2310 // This is effectively the intersection of isTrivialType and
2311 // isStandardLayoutType. We implement it directly to avoid redundant
2312 // conversions from a type to a CXXRecordDecl.
2313 bool QualType::isCXX11PODType(const ASTContext &Context) const {
2314 const Type *ty = getTypePtr();
2315 if (ty->isDependentType())
2318 if (hasNonTrivialObjCLifetime())
2321 // C++11 [basic.types]p9:
2322 // Scalar types, POD classes, arrays of such types, and cv-qualified
2323 // versions of these types are collectively called trivial types.
2324 const Type *BaseTy = ty->getBaseElementTypeUnsafe();
2325 assert(BaseTy && "NULL element type");
2327 // Return false for incomplete types after skipping any incomplete array
2328 // types which are expressly allowed by the standard and thus our API.
2329 if (BaseTy->isIncompleteType())
2332 // As an extension, Clang treats vector types as Scalar types.
2333 if (BaseTy->isScalarType() || BaseTy->isVectorType()) return true;
2334 if (const RecordType *RT = BaseTy->getAs<RecordType>()) {
2335 if (const CXXRecordDecl *ClassDecl =
2336 dyn_cast<CXXRecordDecl>(RT->getDecl())) {
2337 // C++11 [class]p10:
2338 // A POD struct is a non-union class that is both a trivial class [...]
2339 if (!ClassDecl->isTrivial()) return false;
2341 // C++11 [class]p10:
2342 // A POD struct is a non-union class that is both a trivial class and
2343 // a standard-layout class [...]
2344 if (!ClassDecl->isStandardLayout()) return false;
2346 // C++11 [class]p10:
2347 // A POD struct is a non-union class that is both a trivial class and
2348 // a standard-layout class, and has no non-static data members of type
2349 // non-POD struct, non-POD union (or array of such types). [...]
2351 // We don't directly query the recursive aspect as the requirements for
2352 // both standard-layout classes and trivial classes apply recursively
2359 // No other types can match.
2363 bool Type::isAlignValT() const {
2364 if (auto *ET = getAs<EnumType>()) {
2365 auto *II = ET->getDecl()->getIdentifier();
2366 if (II && II->isStr("align_val_t") && ET->getDecl()->isInStdNamespace())
2372 bool Type::isStdByteType() const {
2373 if (auto *ET = getAs<EnumType>()) {
2374 auto *II = ET->getDecl()->getIdentifier();
2375 if (II && II->isStr("byte") && ET->getDecl()->isInStdNamespace())
2381 bool Type::isPromotableIntegerType() const {
2382 if (const BuiltinType *BT = getAs<BuiltinType>())
2383 switch (BT->getKind()) {
2384 case BuiltinType::Bool:
2385 case BuiltinType::Char_S:
2386 case BuiltinType::Char_U:
2387 case BuiltinType::SChar:
2388 case BuiltinType::UChar:
2389 case BuiltinType::Short:
2390 case BuiltinType::UShort:
2391 case BuiltinType::WChar_S:
2392 case BuiltinType::WChar_U:
2393 case BuiltinType::Char16:
2394 case BuiltinType::Char32:
2400 // Enumerated types are promotable to their compatible integer types
2401 // (C99 6.3.1.1) a.k.a. its underlying type (C++ [conv.prom]p2).
2402 if (const EnumType *ET = getAs<EnumType>()){
2403 if (this->isDependentType() || ET->getDecl()->getPromotionType().isNull()
2404 || ET->getDecl()->isScoped())
2413 bool Type::isSpecifierType() const {
2414 // Note that this intentionally does not use the canonical type.
2415 switch (getTypeClass()) {
2423 case TemplateTypeParm:
2424 case SubstTemplateTypeParm:
2425 case TemplateSpecialization:
2428 case DependentTemplateSpecialization:
2431 case ObjCObjectPointer: // FIXME: object pointers aren't really specifiers
2438 ElaboratedTypeKeyword
2439 TypeWithKeyword::getKeywordForTypeSpec(unsigned TypeSpec) {
2441 default: return ETK_None;
2442 case TST_typename: return ETK_Typename;
2443 case TST_class: return ETK_Class;
2444 case TST_struct: return ETK_Struct;
2445 case TST_interface: return ETK_Interface;
2446 case TST_union: return ETK_Union;
2447 case TST_enum: return ETK_Enum;
2452 TypeWithKeyword::getTagTypeKindForTypeSpec(unsigned TypeSpec) {
2454 case TST_class: return TTK_Class;
2455 case TST_struct: return TTK_Struct;
2456 case TST_interface: return TTK_Interface;
2457 case TST_union: return TTK_Union;
2458 case TST_enum: return TTK_Enum;
2461 llvm_unreachable("Type specifier is not a tag type kind.");
2464 ElaboratedTypeKeyword
2465 TypeWithKeyword::getKeywordForTagTypeKind(TagTypeKind Kind) {
2467 case TTK_Class: return ETK_Class;
2468 case TTK_Struct: return ETK_Struct;
2469 case TTK_Interface: return ETK_Interface;
2470 case TTK_Union: return ETK_Union;
2471 case TTK_Enum: return ETK_Enum;
2473 llvm_unreachable("Unknown tag type kind.");
2477 TypeWithKeyword::getTagTypeKindForKeyword(ElaboratedTypeKeyword Keyword) {
2479 case ETK_Class: return TTK_Class;
2480 case ETK_Struct: return TTK_Struct;
2481 case ETK_Interface: return TTK_Interface;
2482 case ETK_Union: return TTK_Union;
2483 case ETK_Enum: return TTK_Enum;
2484 case ETK_None: // Fall through.
2486 llvm_unreachable("Elaborated type keyword is not a tag type kind.");
2488 llvm_unreachable("Unknown elaborated type keyword.");
2492 TypeWithKeyword::KeywordIsTagTypeKind(ElaboratedTypeKeyword Keyword) {
2504 llvm_unreachable("Unknown elaborated type keyword.");
2507 StringRef TypeWithKeyword::getKeywordName(ElaboratedTypeKeyword Keyword) {
2509 case ETK_None: return "";
2510 case ETK_Typename: return "typename";
2511 case ETK_Class: return "class";
2512 case ETK_Struct: return "struct";
2513 case ETK_Interface: return "__interface";
2514 case ETK_Union: return "union";
2515 case ETK_Enum: return "enum";
2518 llvm_unreachable("Unknown elaborated type keyword.");
2521 DependentTemplateSpecializationType::DependentTemplateSpecializationType(
2522 ElaboratedTypeKeyword Keyword,
2523 NestedNameSpecifier *NNS, const IdentifierInfo *Name,
2524 ArrayRef<TemplateArgument> Args,
2526 : TypeWithKeyword(Keyword, DependentTemplateSpecialization, Canon, true, true,
2527 /*VariablyModified=*/false,
2528 NNS && NNS->containsUnexpandedParameterPack()),
2529 NNS(NNS), Name(Name), NumArgs(Args.size()) {
2530 assert((!NNS || NNS->isDependent()) &&
2531 "DependentTemplateSpecializatonType requires dependent qualifier");
2532 TemplateArgument *ArgBuffer = getArgBuffer();
2533 for (const TemplateArgument &Arg : Args) {
2534 if (Arg.containsUnexpandedParameterPack())
2535 setContainsUnexpandedParameterPack();
2537 new (ArgBuffer++) TemplateArgument(Arg);
2542 DependentTemplateSpecializationType::Profile(llvm::FoldingSetNodeID &ID,
2543 const ASTContext &Context,
2544 ElaboratedTypeKeyword Keyword,
2545 NestedNameSpecifier *Qualifier,
2546 const IdentifierInfo *Name,
2547 ArrayRef<TemplateArgument> Args) {
2548 ID.AddInteger(Keyword);
2549 ID.AddPointer(Qualifier);
2550 ID.AddPointer(Name);
2551 for (const TemplateArgument &Arg : Args)
2552 Arg.Profile(ID, Context);
2555 bool Type::isElaboratedTypeSpecifier() const {
2556 ElaboratedTypeKeyword Keyword;
2557 if (const ElaboratedType *Elab = dyn_cast<ElaboratedType>(this))
2558 Keyword = Elab->getKeyword();
2559 else if (const DependentNameType *DepName = dyn_cast<DependentNameType>(this))
2560 Keyword = DepName->getKeyword();
2561 else if (const DependentTemplateSpecializationType *DepTST =
2562 dyn_cast<DependentTemplateSpecializationType>(this))
2563 Keyword = DepTST->getKeyword();
2567 return TypeWithKeyword::KeywordIsTagTypeKind(Keyword);
2570 const char *Type::getTypeClassName() const {
2571 switch (TypeBits.TC) {
2572 #define ABSTRACT_TYPE(Derived, Base)
2573 #define TYPE(Derived, Base) case Derived: return #Derived;
2574 #include "clang/AST/TypeNodes.def"
2577 llvm_unreachable("Invalid type class.");
2580 StringRef BuiltinType::getName(const PrintingPolicy &Policy) const {
2581 switch (getKind()) {
2585 return Policy.Bool ? "bool" : "_Bool";
2591 return "signed char";
2603 return "unsigned char";
2605 return "unsigned short";
2607 return "unsigned int";
2609 return "unsigned long";
2611 return "unsigned long long";
2613 return "unsigned __int128";
2615 return Policy.Half ? "half" : "__fp16";
2621 return "long double";
2625 return "__float128";
2628 return Policy.MSWChar ? "__wchar_t" : "wchar_t";
2636 return "<overloaded function type>";
2638 return "<bound member function type>";
2640 return "<pseudo-object type>";
2642 return "<dependent type>";
2644 return "<unknown type>";
2645 case ARCUnbridgedCast:
2646 return "<ARC unbridged cast type>";
2648 return "<builtin fn type>";
2655 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
2657 return "__" #Access " " #ImgType "_t";
2658 #include "clang/Basic/OpenCLImageTypes.def"
2664 return "clk_event_t";
2668 return "reserve_id_t";
2669 case OMPArraySection:
2670 return "<OpenMP array section type>";
2673 llvm_unreachable("Invalid builtin type.");
2676 QualType QualType::getNonLValueExprType(const ASTContext &Context) const {
2677 if (const ReferenceType *RefType = getTypePtr()->getAs<ReferenceType>())
2678 return RefType->getPointeeType();
2680 // C++0x [basic.lval]:
2681 // Class prvalues can have cv-qualified types; non-class prvalues always
2682 // have cv-unqualified types.
2684 // See also C99 6.3.2.1p2.
2685 if (!Context.getLangOpts().CPlusPlus ||
2686 (!getTypePtr()->isDependentType() && !getTypePtr()->isRecordType()))
2687 return getUnqualifiedType();
2692 StringRef FunctionType::getNameForCallConv(CallingConv CC) {
2694 case CC_C: return "cdecl";
2695 case CC_X86StdCall: return "stdcall";
2696 case CC_X86FastCall: return "fastcall";
2697 case CC_X86ThisCall: return "thiscall";
2698 case CC_X86Pascal: return "pascal";
2699 case CC_X86VectorCall: return "vectorcall";
2700 case CC_Win64: return "ms_abi";
2701 case CC_X86_64SysV: return "sysv_abi";
2702 case CC_X86RegCall : return "regcall";
2703 case CC_AAPCS: return "aapcs";
2704 case CC_AAPCS_VFP: return "aapcs-vfp";
2705 case CC_IntelOclBicc: return "intel_ocl_bicc";
2706 case CC_SpirFunction: return "spir_function";
2707 case CC_OpenCLKernel: return "opencl_kernel";
2708 case CC_Swift: return "swiftcall";
2709 case CC_PreserveMost: return "preserve_most";
2710 case CC_PreserveAll: return "preserve_all";
2713 llvm_unreachable("Invalid calling convention.");
2716 FunctionProtoType::FunctionProtoType(QualType result, ArrayRef<QualType> params,
2718 const ExtProtoInfo &epi)
2719 : FunctionType(FunctionProto, result, canonical,
2720 result->isDependentType(),
2721 result->isInstantiationDependentType(),
2722 result->isVariablyModifiedType(),
2723 result->containsUnexpandedParameterPack(), epi.ExtInfo),
2724 NumParams(params.size()),
2725 NumExceptions(epi.ExceptionSpec.Exceptions.size()),
2726 ExceptionSpecType(epi.ExceptionSpec.Type),
2727 HasExtParameterInfos(epi.ExtParameterInfos != nullptr),
2728 Variadic(epi.Variadic), HasTrailingReturn(epi.HasTrailingReturn) {
2729 assert(NumParams == params.size() && "function has too many parameters");
2731 FunctionTypeBits.TypeQuals = epi.TypeQuals;
2732 FunctionTypeBits.RefQualifier = epi.RefQualifier;
2734 // Fill in the trailing argument array.
2735 QualType *argSlot = reinterpret_cast<QualType*>(this+1);
2736 for (unsigned i = 0; i != NumParams; ++i) {
2737 if (params[i]->isDependentType())
2739 else if (params[i]->isInstantiationDependentType())
2740 setInstantiationDependent();
2742 if (params[i]->containsUnexpandedParameterPack())
2743 setContainsUnexpandedParameterPack();
2745 argSlot[i] = params[i];
2748 if (getExceptionSpecType() == EST_Dynamic) {
2749 // Fill in the exception array.
2750 QualType *exnSlot = argSlot + NumParams;
2752 for (QualType ExceptionType : epi.ExceptionSpec.Exceptions) {
2753 // Note that, before C++17, a dependent exception specification does
2754 // *not* make a type dependent; it's not even part of the C++ type
2756 if (ExceptionType->isInstantiationDependentType())
2757 setInstantiationDependent();
2759 if (ExceptionType->containsUnexpandedParameterPack())
2760 setContainsUnexpandedParameterPack();
2762 exnSlot[I++] = ExceptionType;
2764 } else if (getExceptionSpecType() == EST_ComputedNoexcept) {
2765 // Store the noexcept expression and context.
2766 Expr **noexSlot = reinterpret_cast<Expr **>(argSlot + NumParams);
2767 *noexSlot = epi.ExceptionSpec.NoexceptExpr;
2769 if (epi.ExceptionSpec.NoexceptExpr) {
2770 if (epi.ExceptionSpec.NoexceptExpr->isValueDependent() ||
2771 epi.ExceptionSpec.NoexceptExpr->isInstantiationDependent())
2772 setInstantiationDependent();
2774 if (epi.ExceptionSpec.NoexceptExpr->containsUnexpandedParameterPack())
2775 setContainsUnexpandedParameterPack();
2777 } else if (getExceptionSpecType() == EST_Uninstantiated) {
2778 // Store the function decl from which we will resolve our
2779 // exception specification.
2780 FunctionDecl **slot =
2781 reinterpret_cast<FunctionDecl **>(argSlot + NumParams);
2782 slot[0] = epi.ExceptionSpec.SourceDecl;
2783 slot[1] = epi.ExceptionSpec.SourceTemplate;
2784 // This exception specification doesn't make the type dependent, because
2785 // it's not instantiated as part of instantiating the type.
2786 } else if (getExceptionSpecType() == EST_Unevaluated) {
2787 // Store the function decl from which we will resolve our
2788 // exception specification.
2789 FunctionDecl **slot =
2790 reinterpret_cast<FunctionDecl **>(argSlot + NumParams);
2791 slot[0] = epi.ExceptionSpec.SourceDecl;
2794 // If this is a canonical type, and its exception specification is dependent,
2795 // then it's a dependent type. This only happens in C++17 onwards.
2796 if (isCanonicalUnqualified()) {
2797 if (getExceptionSpecType() == EST_Dynamic ||
2798 getExceptionSpecType() == EST_ComputedNoexcept) {
2799 assert(hasDependentExceptionSpec() && "type should not be canonical");
2802 } else if (getCanonicalTypeInternal()->isDependentType()) {
2803 // Ask our canonical type whether our exception specification was dependent.
2807 if (epi.ExtParameterInfos) {
2808 ExtParameterInfo *extParamInfos =
2809 const_cast<ExtParameterInfo *>(getExtParameterInfosBuffer());
2810 for (unsigned i = 0; i != NumParams; ++i)
2811 extParamInfos[i] = epi.ExtParameterInfos[i];
2815 bool FunctionProtoType::hasDependentExceptionSpec() const {
2816 if (Expr *NE = getNoexceptExpr())
2817 return NE->isValueDependent();
2818 for (QualType ET : exceptions())
2819 // A pack expansion with a non-dependent pattern is still dependent,
2820 // because we don't know whether the pattern is in the exception spec
2821 // or not (that depends on whether the pack has 0 expansions).
2822 if (ET->isDependentType() || ET->getAs<PackExpansionType>())
2827 bool FunctionProtoType::hasInstantiationDependentExceptionSpec() const {
2828 if (Expr *NE = getNoexceptExpr())
2829 return NE->isInstantiationDependent();
2830 for (QualType ET : exceptions())
2831 if (ET->isInstantiationDependentType())
2836 FunctionProtoType::NoexceptResult
2837 FunctionProtoType::getNoexceptSpec(const ASTContext &ctx) const {
2838 ExceptionSpecificationType est = getExceptionSpecType();
2839 if (est == EST_BasicNoexcept)
2842 if (est != EST_ComputedNoexcept)
2843 return NR_NoNoexcept;
2845 Expr *noexceptExpr = getNoexceptExpr();
2847 return NR_BadNoexcept;
2848 if (noexceptExpr->isValueDependent())
2849 return NR_Dependent;
2852 bool isICE = noexceptExpr->isIntegerConstantExpr(value, ctx, nullptr,
2853 /*evaluated*/false);
2855 assert(isICE && "AST should not contain bad noexcept expressions.");
2857 return value.getBoolValue() ? NR_Nothrow : NR_Throw;
2860 CanThrowResult FunctionProtoType::canThrow(const ASTContext &Ctx) const {
2861 ExceptionSpecificationType EST = getExceptionSpecType();
2862 assert(EST != EST_Unevaluated && EST != EST_Uninstantiated);
2863 if (EST == EST_DynamicNone || EST == EST_BasicNoexcept)
2866 if (EST == EST_Dynamic) {
2867 // A dynamic exception specification is throwing unless every exception
2868 // type is an (unexpanded) pack expansion type.
2869 for (unsigned I = 0, N = NumExceptions; I != N; ++I)
2870 if (!getExceptionType(I)->getAs<PackExpansionType>())
2872 return CT_Dependent;
2875 if (EST != EST_ComputedNoexcept)
2878 NoexceptResult NR = getNoexceptSpec(Ctx);
2879 if (NR == NR_Dependent)
2880 return CT_Dependent;
2881 return NR == NR_Nothrow ? CT_Cannot : CT_Can;
2884 bool FunctionProtoType::isTemplateVariadic() const {
2885 for (unsigned ArgIdx = getNumParams(); ArgIdx; --ArgIdx)
2886 if (isa<PackExpansionType>(getParamType(ArgIdx - 1)))
2892 void FunctionProtoType::Profile(llvm::FoldingSetNodeID &ID, QualType Result,
2893 const QualType *ArgTys, unsigned NumParams,
2894 const ExtProtoInfo &epi,
2895 const ASTContext &Context, bool Canonical) {
2896 // We have to be careful not to get ambiguous profile encodings.
2897 // Note that valid type pointers are never ambiguous with anything else.
2899 // The encoding grammar begins:
2900 // type type* bool int bool
2901 // If that final bool is true, then there is a section for the EH spec:
2903 // This is followed by an optional "consumed argument" section of the
2904 // same length as the first type sequence:
2906 // Finally, we have the ext info and trailing return type flag:
2909 // There is no ambiguity between the consumed arguments and an empty EH
2910 // spec because of the leading 'bool' which unambiguously indicates
2911 // whether the following bool is the EH spec or part of the arguments.
2913 ID.AddPointer(Result.getAsOpaquePtr());
2914 for (unsigned i = 0; i != NumParams; ++i)
2915 ID.AddPointer(ArgTys[i].getAsOpaquePtr());
2916 // This method is relatively performance sensitive, so as a performance
2917 // shortcut, use one AddInteger call instead of four for the next four
2919 assert(!(unsigned(epi.Variadic) & ~1) &&
2920 !(unsigned(epi.TypeQuals) & ~255) &&
2921 !(unsigned(epi.RefQualifier) & ~3) &&
2922 !(unsigned(epi.ExceptionSpec.Type) & ~15) &&
2923 "Values larger than expected.");
2924 ID.AddInteger(unsigned(epi.Variadic) +
2925 (epi.TypeQuals << 1) +
2926 (epi.RefQualifier << 9) +
2927 (epi.ExceptionSpec.Type << 11));
2928 if (epi.ExceptionSpec.Type == EST_Dynamic) {
2929 for (QualType Ex : epi.ExceptionSpec.Exceptions)
2930 ID.AddPointer(Ex.getAsOpaquePtr());
2931 } else if (epi.ExceptionSpec.Type == EST_ComputedNoexcept &&
2932 epi.ExceptionSpec.NoexceptExpr) {
2933 epi.ExceptionSpec.NoexceptExpr->Profile(ID, Context, Canonical);
2934 } else if (epi.ExceptionSpec.Type == EST_Uninstantiated ||
2935 epi.ExceptionSpec.Type == EST_Unevaluated) {
2936 ID.AddPointer(epi.ExceptionSpec.SourceDecl->getCanonicalDecl());
2938 if (epi.ExtParameterInfos) {
2939 for (unsigned i = 0; i != NumParams; ++i)
2940 ID.AddInteger(epi.ExtParameterInfos[i].getOpaqueValue());
2942 epi.ExtInfo.Profile(ID);
2943 ID.AddBoolean(epi.HasTrailingReturn);
2946 void FunctionProtoType::Profile(llvm::FoldingSetNodeID &ID,
2947 const ASTContext &Ctx) {
2948 Profile(ID, getReturnType(), param_type_begin(), NumParams, getExtProtoInfo(),
2949 Ctx, isCanonicalUnqualified());
2952 QualType TypedefType::desugar() const {
2953 return getDecl()->getUnderlyingType();
2956 TypeOfExprType::TypeOfExprType(Expr *E, QualType can)
2957 : Type(TypeOfExpr, can, E->isTypeDependent(),
2958 E->isInstantiationDependent(),
2959 E->getType()->isVariablyModifiedType(),
2960 E->containsUnexpandedParameterPack()),
2963 bool TypeOfExprType::isSugared() const {
2964 return !TOExpr->isTypeDependent();
2967 QualType TypeOfExprType::desugar() const {
2969 return getUnderlyingExpr()->getType();
2971 return QualType(this, 0);
2974 void DependentTypeOfExprType::Profile(llvm::FoldingSetNodeID &ID,
2975 const ASTContext &Context, Expr *E) {
2976 E->Profile(ID, Context, true);
2979 DecltypeType::DecltypeType(Expr *E, QualType underlyingType, QualType can)
2980 // C++11 [temp.type]p2: "If an expression e involves a template parameter,
2981 // decltype(e) denotes a unique dependent type." Hence a decltype type is
2982 // type-dependent even if its expression is only instantiation-dependent.
2983 : Type(Decltype, can, E->isInstantiationDependent(),
2984 E->isInstantiationDependent(),
2985 E->getType()->isVariablyModifiedType(),
2986 E->containsUnexpandedParameterPack()),
2987 E(E), UnderlyingType(underlyingType) {}
2989 bool DecltypeType::isSugared() const { return !E->isInstantiationDependent(); }
2991 QualType DecltypeType::desugar() const {
2993 return getUnderlyingType();
2995 return QualType(this, 0);
2998 DependentDecltypeType::DependentDecltypeType(const ASTContext &Context, Expr *E)
2999 : DecltypeType(E, Context.DependentTy), Context(Context) {}
3001 void DependentDecltypeType::Profile(llvm::FoldingSetNodeID &ID,
3002 const ASTContext &Context, Expr *E) {
3003 E->Profile(ID, Context, true);
3006 UnaryTransformType::UnaryTransformType(QualType BaseType,
3007 QualType UnderlyingType,
3009 QualType CanonicalType)
3010 : Type(UnaryTransform, CanonicalType, BaseType->isDependentType(),
3011 BaseType->isInstantiationDependentType(),
3012 BaseType->isVariablyModifiedType(),
3013 BaseType->containsUnexpandedParameterPack()),
3014 BaseType(BaseType), UnderlyingType(UnderlyingType), UKind(UKind) {}
3016 DependentUnaryTransformType::DependentUnaryTransformType(const ASTContext &C,
3019 : UnaryTransformType(BaseType, C.DependentTy, UKind, QualType()) {}
3021 TagType::TagType(TypeClass TC, const TagDecl *D, QualType can)
3022 : Type(TC, can, D->isDependentType(),
3023 /*InstantiationDependent=*/D->isDependentType(),
3024 /*VariablyModified=*/false,
3025 /*ContainsUnexpandedParameterPack=*/false),
3026 decl(const_cast<TagDecl*>(D)) {}
3028 static TagDecl *getInterestingTagDecl(TagDecl *decl) {
3029 for (auto I : decl->redecls()) {
3030 if (I->isCompleteDefinition() || I->isBeingDefined())
3033 // If there's no definition (not even in progress), return what we have.
3037 TagDecl *TagType::getDecl() const {
3038 return getInterestingTagDecl(decl);
3041 bool TagType::isBeingDefined() const {
3042 return getDecl()->isBeingDefined();
3045 bool RecordType::hasConstFields() const {
3046 for (FieldDecl *FD : getDecl()->fields()) {
3047 QualType FieldTy = FD->getType();
3048 if (FieldTy.isConstQualified())
3050 FieldTy = FieldTy.getCanonicalType();
3051 if (const RecordType *FieldRecTy = FieldTy->getAs<RecordType>())
3052 if (FieldRecTy->hasConstFields())
3058 bool AttributedType::isQualifier() const {
3059 switch (getAttrKind()) {
3060 // These are type qualifiers in the traditional C sense: they annotate
3061 // something about a specific value/variable of a type. (They aren't
3062 // always part of the canonical type, though.)
3063 case AttributedType::attr_address_space:
3064 case AttributedType::attr_objc_gc:
3065 case AttributedType::attr_objc_ownership:
3066 case AttributedType::attr_objc_inert_unsafe_unretained:
3067 case AttributedType::attr_nonnull:
3068 case AttributedType::attr_nullable:
3069 case AttributedType::attr_null_unspecified:
3072 // These aren't qualifiers; they rewrite the modified type to be a
3073 // semantically different type.
3074 case AttributedType::attr_regparm:
3075 case AttributedType::attr_vector_size:
3076 case AttributedType::attr_neon_vector_type:
3077 case AttributedType::attr_neon_polyvector_type:
3078 case AttributedType::attr_pcs:
3079 case AttributedType::attr_pcs_vfp:
3080 case AttributedType::attr_noreturn:
3081 case AttributedType::attr_cdecl:
3082 case AttributedType::attr_fastcall:
3083 case AttributedType::attr_stdcall:
3084 case AttributedType::attr_thiscall:
3085 case AttributedType::attr_regcall:
3086 case AttributedType::attr_pascal:
3087 case AttributedType::attr_swiftcall:
3088 case AttributedType::attr_vectorcall:
3089 case AttributedType::attr_inteloclbicc:
3090 case AttributedType::attr_preserve_most:
3091 case AttributedType::attr_preserve_all:
3092 case AttributedType::attr_ms_abi:
3093 case AttributedType::attr_sysv_abi:
3094 case AttributedType::attr_ptr32:
3095 case AttributedType::attr_ptr64:
3096 case AttributedType::attr_sptr:
3097 case AttributedType::attr_uptr:
3098 case AttributedType::attr_objc_kindof:
3099 case AttributedType::attr_ns_returns_retained:
3102 llvm_unreachable("bad attributed type kind");
3105 bool AttributedType::isMSTypeSpec() const {
3106 switch (getAttrKind()) {
3107 default: return false;
3114 llvm_unreachable("invalid attr kind");
3117 bool AttributedType::isCallingConv() const {
3118 switch (getAttrKind()) {
3123 case attr_address_space:
3125 case attr_vector_size:
3126 case attr_neon_vector_type:
3127 case attr_neon_polyvector_type:
3129 case attr_objc_ownership:
3130 case attr_objc_inert_unsafe_unretained:
3133 case attr_ns_returns_retained:
3135 case attr_null_unspecified:
3136 case attr_objc_kindof:
3146 case attr_swiftcall:
3147 case attr_vectorcall:
3151 case attr_inteloclbicc:
3152 case attr_preserve_most:
3153 case attr_preserve_all:
3156 llvm_unreachable("invalid attr kind");
3159 CXXRecordDecl *InjectedClassNameType::getDecl() const {
3160 return cast<CXXRecordDecl>(getInterestingTagDecl(Decl));
3163 IdentifierInfo *TemplateTypeParmType::getIdentifier() const {
3164 return isCanonicalUnqualified() ? nullptr : getDecl()->getIdentifier();
3167 SubstTemplateTypeParmPackType::
3168 SubstTemplateTypeParmPackType(const TemplateTypeParmType *Param,
3170 const TemplateArgument &ArgPack)
3171 : Type(SubstTemplateTypeParmPack, Canon, true, true, false, true),
3173 Arguments(ArgPack.pack_begin()), NumArguments(ArgPack.pack_size()) {}
3175 TemplateArgument SubstTemplateTypeParmPackType::getArgumentPack() const {
3176 return TemplateArgument(llvm::makeArrayRef(Arguments, NumArguments));
3179 void SubstTemplateTypeParmPackType::Profile(llvm::FoldingSetNodeID &ID) {
3180 Profile(ID, getReplacedParameter(), getArgumentPack());
3183 void SubstTemplateTypeParmPackType::Profile(llvm::FoldingSetNodeID &ID,
3184 const TemplateTypeParmType *Replaced,
3185 const TemplateArgument &ArgPack) {
3186 ID.AddPointer(Replaced);
3187 ID.AddInteger(ArgPack.pack_size());
3188 for (const auto &P : ArgPack.pack_elements())
3189 ID.AddPointer(P.getAsType().getAsOpaquePtr());
3192 bool TemplateSpecializationType::
3193 anyDependentTemplateArguments(const TemplateArgumentListInfo &Args,
3194 bool &InstantiationDependent) {
3195 return anyDependentTemplateArguments(Args.arguments(),
3196 InstantiationDependent);
3199 bool TemplateSpecializationType::
3200 anyDependentTemplateArguments(ArrayRef<TemplateArgumentLoc> Args,
3201 bool &InstantiationDependent) {
3202 for (const TemplateArgumentLoc &ArgLoc : Args) {
3203 if (ArgLoc.getArgument().isDependent()) {
3204 InstantiationDependent = true;
3208 if (ArgLoc.getArgument().isInstantiationDependent())
3209 InstantiationDependent = true;
3214 TemplateSpecializationType::
3215 TemplateSpecializationType(TemplateName T,
3216 ArrayRef<TemplateArgument> Args,
3217 QualType Canon, QualType AliasedType)
3218 : Type(TemplateSpecialization,
3219 Canon.isNull()? QualType(this, 0) : Canon,
3220 Canon.isNull()? true : Canon->isDependentType(),
3221 Canon.isNull()? true : Canon->isInstantiationDependentType(),
3223 T.containsUnexpandedParameterPack()),
3224 Template(T), NumArgs(Args.size()), TypeAlias(!AliasedType.isNull()) {
3225 assert(!T.getAsDependentTemplateName() &&
3226 "Use DependentTemplateSpecializationType for dependent template-name");
3227 assert((T.getKind() == TemplateName::Template ||
3228 T.getKind() == TemplateName::SubstTemplateTemplateParm ||
3229 T.getKind() == TemplateName::SubstTemplateTemplateParmPack) &&
3230 "Unexpected template name for TemplateSpecializationType");
3232 TemplateArgument *TemplateArgs
3233 = reinterpret_cast<TemplateArgument *>(this + 1);
3234 for (const TemplateArgument &Arg : Args) {
3235 // Update instantiation-dependent and variably-modified bits.
3236 // If the canonical type exists and is non-dependent, the template
3237 // specialization type can be non-dependent even if one of the type
3238 // arguments is. Given:
3239 // template<typename T> using U = int;
3240 // U<T> is always non-dependent, irrespective of the type T.
3241 // However, U<Ts> contains an unexpanded parameter pack, even though
3242 // its expansion (and thus its desugared type) doesn't.
3243 if (Arg.isInstantiationDependent())
3244 setInstantiationDependent();
3245 if (Arg.getKind() == TemplateArgument::Type &&
3246 Arg.getAsType()->isVariablyModifiedType())
3247 setVariablyModified();
3248 if (Arg.containsUnexpandedParameterPack())
3249 setContainsUnexpandedParameterPack();
3250 new (TemplateArgs++) TemplateArgument(Arg);
3253 // Store the aliased type if this is a type alias template specialization.
3255 TemplateArgument *Begin = reinterpret_cast<TemplateArgument *>(this + 1);
3256 *reinterpret_cast<QualType*>(Begin + getNumArgs()) = AliasedType;
3261 TemplateSpecializationType::Profile(llvm::FoldingSetNodeID &ID,
3263 ArrayRef<TemplateArgument> Args,
3264 const ASTContext &Context) {
3266 for (const TemplateArgument &Arg : Args)
3267 Arg.Profile(ID, Context);
3271 QualifierCollector::apply(const ASTContext &Context, QualType QT) const {
3272 if (!hasNonFastQualifiers())
3273 return QT.withFastQualifiers(getFastQualifiers());
3275 return Context.getQualifiedType(QT, *this);
3279 QualifierCollector::apply(const ASTContext &Context, const Type *T) const {
3280 if (!hasNonFastQualifiers())
3281 return QualType(T, getFastQualifiers());
3283 return Context.getQualifiedType(T, *this);
3286 void ObjCObjectTypeImpl::Profile(llvm::FoldingSetNodeID &ID,
3288 ArrayRef<QualType> typeArgs,
3289 ArrayRef<ObjCProtocolDecl *> protocols,
3291 ID.AddPointer(BaseType.getAsOpaquePtr());
3292 ID.AddInteger(typeArgs.size());
3293 for (auto typeArg : typeArgs)
3294 ID.AddPointer(typeArg.getAsOpaquePtr());
3295 ID.AddInteger(protocols.size());
3296 for (auto proto : protocols)
3297 ID.AddPointer(proto);
3298 ID.AddBoolean(isKindOf);
3301 void ObjCObjectTypeImpl::Profile(llvm::FoldingSetNodeID &ID) {
3302 Profile(ID, getBaseType(), getTypeArgsAsWritten(),
3303 llvm::makeArrayRef(qual_begin(), getNumProtocols()),
3304 isKindOfTypeAsWritten());
3307 void ObjCTypeParamType::Profile(llvm::FoldingSetNodeID &ID,
3308 const ObjCTypeParamDecl *OTPDecl,
3309 ArrayRef<ObjCProtocolDecl *> protocols) {
3310 ID.AddPointer(OTPDecl);
3311 ID.AddInteger(protocols.size());
3312 for (auto proto : protocols)
3313 ID.AddPointer(proto);
3316 void ObjCTypeParamType::Profile(llvm::FoldingSetNodeID &ID) {
3317 Profile(ID, getDecl(),
3318 llvm::makeArrayRef(qual_begin(), getNumProtocols()));
3323 /// \brief The cached properties of a type.
3324 class CachedProperties {
3329 CachedProperties(Linkage L, bool local) : L(L), local(local) {}
3331 Linkage getLinkage() const { return L; }
3332 bool hasLocalOrUnnamedType() const { return local; }
3334 friend CachedProperties merge(CachedProperties L, CachedProperties R) {
3335 Linkage MergedLinkage = minLinkage(L.L, R.L);
3336 return CachedProperties(MergedLinkage,
3337 L.hasLocalOrUnnamedType() | R.hasLocalOrUnnamedType());
3343 static CachedProperties computeCachedProperties(const Type *T);
3347 /// The type-property cache. This is templated so as to be
3348 /// instantiated at an internal type to prevent unnecessary symbol
3350 template <class Private> class TypePropertyCache {
3352 static CachedProperties get(QualType T) {
3353 return get(T.getTypePtr());
3356 static CachedProperties get(const Type *T) {
3358 return CachedProperties(T->TypeBits.getLinkage(),
3359 T->TypeBits.hasLocalOrUnnamedType());
3362 static void ensure(const Type *T) {
3363 // If the cache is valid, we're okay.
3364 if (T->TypeBits.isCacheValid()) return;
3366 // If this type is non-canonical, ask its canonical type for the
3367 // relevant information.
3368 if (!T->isCanonicalUnqualified()) {
3369 const Type *CT = T->getCanonicalTypeInternal().getTypePtr();
3371 T->TypeBits.CacheValid = true;
3372 T->TypeBits.CachedLinkage = CT->TypeBits.CachedLinkage;
3373 T->TypeBits.CachedLocalOrUnnamed = CT->TypeBits.CachedLocalOrUnnamed;
3377 // Compute the cached properties and then set the cache.
3378 CachedProperties Result = computeCachedProperties(T);
3379 T->TypeBits.CacheValid = true;
3380 T->TypeBits.CachedLinkage = Result.getLinkage();
3381 T->TypeBits.CachedLocalOrUnnamed = Result.hasLocalOrUnnamedType();
3385 } // namespace clang
3387 // Instantiate the friend template at a private class. In a
3388 // reasonable implementation, these symbols will be internal.
3389 // It is terrible that this is the best way to accomplish this.
3396 using Cache = TypePropertyCache<Private>;
3398 static CachedProperties computeCachedProperties(const Type *T) {
3399 switch (T->getTypeClass()) {
3400 #define TYPE(Class,Base)
3401 #define NON_CANONICAL_TYPE(Class,Base) case Type::Class:
3402 #include "clang/AST/TypeNodes.def"
3403 llvm_unreachable("didn't expect a non-canonical type here");
3405 #define TYPE(Class,Base)
3406 #define DEPENDENT_TYPE(Class,Base) case Type::Class:
3407 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class,Base) case Type::Class:
3408 #include "clang/AST/TypeNodes.def"
3409 // Treat instantiation-dependent types as external.
3410 assert(T->isInstantiationDependentType());
3411 return CachedProperties(ExternalLinkage, false);
3414 case Type::DeducedTemplateSpecialization:
3415 // Give non-deduced 'auto' types external linkage. We should only see them
3416 // here in error recovery.
3417 return CachedProperties(ExternalLinkage, false);
3420 // C++ [basic.link]p8:
3421 // A type is said to have linkage if and only if:
3422 // - it is a fundamental type (3.9.1); or
3423 return CachedProperties(ExternalLinkage, false);
3427 const TagDecl *Tag = cast<TagType>(T)->getDecl();
3429 // C++ [basic.link]p8:
3430 // - it is a class or enumeration type that is named (or has a name
3431 // for linkage purposes (7.1.3)) and the name has linkage; or
3432 // - it is a specialization of a class template (14); or
3433 Linkage L = Tag->getLinkageInternal();
3434 bool IsLocalOrUnnamed =
3435 Tag->getDeclContext()->isFunctionOrMethod() ||
3436 !Tag->hasNameForLinkage();
3437 return CachedProperties(L, IsLocalOrUnnamed);
3440 // C++ [basic.link]p8:
3441 // - it is a compound type (3.9.2) other than a class or enumeration,
3442 // compounded exclusively from types that have linkage; or
3444 return Cache::get(cast<ComplexType>(T)->getElementType());
3446 return Cache::get(cast<PointerType>(T)->getPointeeType());
3447 case Type::BlockPointer:
3448 return Cache::get(cast<BlockPointerType>(T)->getPointeeType());
3449 case Type::LValueReference:
3450 case Type::RValueReference:
3451 return Cache::get(cast<ReferenceType>(T)->getPointeeType());
3452 case Type::MemberPointer: {
3453 const MemberPointerType *MPT = cast<MemberPointerType>(T);
3454 return merge(Cache::get(MPT->getClass()),
3455 Cache::get(MPT->getPointeeType()));
3457 case Type::ConstantArray:
3458 case Type::IncompleteArray:
3459 case Type::VariableArray:
3460 return Cache::get(cast<ArrayType>(T)->getElementType());
3462 case Type::ExtVector:
3463 return Cache::get(cast<VectorType>(T)->getElementType());
3464 case Type::FunctionNoProto:
3465 return Cache::get(cast<FunctionType>(T)->getReturnType());
3466 case Type::FunctionProto: {
3467 const FunctionProtoType *FPT = cast<FunctionProtoType>(T);
3468 CachedProperties result = Cache::get(FPT->getReturnType());
3469 for (const auto &ai : FPT->param_types())
3470 result = merge(result, Cache::get(ai));
3473 case Type::ObjCInterface: {
3474 Linkage L = cast<ObjCInterfaceType>(T)->getDecl()->getLinkageInternal();
3475 return CachedProperties(L, false);
3477 case Type::ObjCObject:
3478 return Cache::get(cast<ObjCObjectType>(T)->getBaseType());
3479 case Type::ObjCObjectPointer:
3480 return Cache::get(cast<ObjCObjectPointerType>(T)->getPointeeType());
3482 return Cache::get(cast<AtomicType>(T)->getValueType());
3484 return Cache::get(cast<PipeType>(T)->getElementType());
3487 llvm_unreachable("unhandled type class");
3490 /// \brief Determine the linkage of this type.
3491 Linkage Type::getLinkage() const {
3492 Cache::ensure(this);
3493 return TypeBits.getLinkage();
3496 bool Type::hasUnnamedOrLocalType() const {
3497 Cache::ensure(this);
3498 return TypeBits.hasLocalOrUnnamedType();
3501 LinkageInfo LinkageComputer::computeTypeLinkageInfo(const Type *T) {
3502 switch (T->getTypeClass()) {
3503 #define TYPE(Class,Base)
3504 #define NON_CANONICAL_TYPE(Class,Base) case Type::Class:
3505 #include "clang/AST/TypeNodes.def"
3506 llvm_unreachable("didn't expect a non-canonical type here");
3508 #define TYPE(Class,Base)
3509 #define DEPENDENT_TYPE(Class,Base) case Type::Class:
3510 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class,Base) case Type::Class:
3511 #include "clang/AST/TypeNodes.def"
3512 // Treat instantiation-dependent types as external.
3513 assert(T->isInstantiationDependentType());
3514 return LinkageInfo::external();
3517 return LinkageInfo::external();
3520 case Type::DeducedTemplateSpecialization:
3521 return LinkageInfo::external();
3525 return getDeclLinkageAndVisibility(cast<TagType>(T)->getDecl());
3528 return computeTypeLinkageInfo(cast<ComplexType>(T)->getElementType());
3530 return computeTypeLinkageInfo(cast<PointerType>(T)->getPointeeType());
3531 case Type::BlockPointer:
3532 return computeTypeLinkageInfo(cast<BlockPointerType>(T)->getPointeeType());
3533 case Type::LValueReference:
3534 case Type::RValueReference:
3535 return computeTypeLinkageInfo(cast<ReferenceType>(T)->getPointeeType());
3536 case Type::MemberPointer: {
3537 const MemberPointerType *MPT = cast<MemberPointerType>(T);
3538 LinkageInfo LV = computeTypeLinkageInfo(MPT->getClass());
3539 LV.merge(computeTypeLinkageInfo(MPT->getPointeeType()));
3542 case Type::ConstantArray:
3543 case Type::IncompleteArray:
3544 case Type::VariableArray:
3545 return computeTypeLinkageInfo(cast<ArrayType>(T)->getElementType());
3547 case Type::ExtVector:
3548 return computeTypeLinkageInfo(cast<VectorType>(T)->getElementType());
3549 case Type::FunctionNoProto:
3550 return computeTypeLinkageInfo(cast<FunctionType>(T)->getReturnType());
3551 case Type::FunctionProto: {
3552 const FunctionProtoType *FPT = cast<FunctionProtoType>(T);
3553 LinkageInfo LV = computeTypeLinkageInfo(FPT->getReturnType());
3554 for (const auto &ai : FPT->param_types())
3555 LV.merge(computeTypeLinkageInfo(ai));
3558 case Type::ObjCInterface:
3559 return getDeclLinkageAndVisibility(cast<ObjCInterfaceType>(T)->getDecl());
3560 case Type::ObjCObject:
3561 return computeTypeLinkageInfo(cast<ObjCObjectType>(T)->getBaseType());
3562 case Type::ObjCObjectPointer:
3563 return computeTypeLinkageInfo(
3564 cast<ObjCObjectPointerType>(T)->getPointeeType());
3566 return computeTypeLinkageInfo(cast<AtomicType>(T)->getValueType());
3568 return computeTypeLinkageInfo(cast<PipeType>(T)->getElementType());
3571 llvm_unreachable("unhandled type class");
3574 bool Type::isLinkageValid() const {
3575 if (!TypeBits.isCacheValid())
3578 Linkage L = LinkageComputer{}
3579 .computeTypeLinkageInfo(getCanonicalTypeInternal())
3581 return L == TypeBits.getLinkage();
3584 LinkageInfo LinkageComputer::getTypeLinkageAndVisibility(const Type *T) {
3585 if (!T->isCanonicalUnqualified())
3586 return computeTypeLinkageInfo(T->getCanonicalTypeInternal());
3588 LinkageInfo LV = computeTypeLinkageInfo(T);
3589 assert(LV.getLinkage() == T->getLinkage());
3593 LinkageInfo Type::getLinkageAndVisibility() const {
3594 return LinkageComputer{}.getTypeLinkageAndVisibility(this);
3597 Optional<NullabilityKind> Type::getNullability(const ASTContext &context) const {
3598 QualType type(this, 0);
3600 // Check whether this is an attributed type with nullability
3602 if (auto attributed = dyn_cast<AttributedType>(type.getTypePtr())) {
3603 if (auto nullability = attributed->getImmediateNullability())
3607 // Desugar the type. If desugaring does nothing, we're done.
3608 QualType desugared = type.getSingleStepDesugaredType(context);
3609 if (desugared.getTypePtr() == type.getTypePtr())
3616 bool Type::canHaveNullability(bool ResultIfUnknown) const {
3617 QualType type = getCanonicalTypeInternal();
3619 switch (type->getTypeClass()) {
3620 // We'll only see canonical types here.
3621 #define NON_CANONICAL_TYPE(Class, Parent) \
3623 llvm_unreachable("non-canonical type");
3624 #define TYPE(Class, Parent)
3625 #include "clang/AST/TypeNodes.def"
3629 case Type::BlockPointer:
3630 case Type::MemberPointer:
3631 case Type::ObjCObjectPointer:
3634 // Dependent types that could instantiate to pointer types.
3635 case Type::UnresolvedUsing:
3636 case Type::TypeOfExpr:
3638 case Type::Decltype:
3639 case Type::UnaryTransform:
3640 case Type::TemplateTypeParm:
3641 case Type::SubstTemplateTypeParmPack:
3642 case Type::DependentName:
3643 case Type::DependentTemplateSpecialization:
3645 return ResultIfUnknown;
3647 // Dependent template specializations can instantiate to pointer
3648 // types unless they're known to be specializations of a class
3650 case Type::TemplateSpecialization:
3651 if (TemplateDecl *templateDecl
3652 = cast<TemplateSpecializationType>(type.getTypePtr())
3653 ->getTemplateName().getAsTemplateDecl()) {
3654 if (isa<ClassTemplateDecl>(templateDecl))
3657 return ResultIfUnknown;
3660 switch (cast<BuiltinType>(type.getTypePtr())->getKind()) {
3661 // Signed, unsigned, and floating-point types cannot have nullability.
3662 #define SIGNED_TYPE(Id, SingletonId) case BuiltinType::Id:
3663 #define UNSIGNED_TYPE(Id, SingletonId) case BuiltinType::Id:
3664 #define FLOATING_TYPE(Id, SingletonId) case BuiltinType::Id:
3665 #define BUILTIN_TYPE(Id, SingletonId)
3666 #include "clang/AST/BuiltinTypes.def"
3669 // Dependent types that could instantiate to a pointer type.
3670 case BuiltinType::Dependent:
3671 case BuiltinType::Overload:
3672 case BuiltinType::BoundMember:
3673 case BuiltinType::PseudoObject:
3674 case BuiltinType::UnknownAny:
3675 case BuiltinType::ARCUnbridgedCast:
3676 return ResultIfUnknown;
3678 case BuiltinType::Void:
3679 case BuiltinType::ObjCId:
3680 case BuiltinType::ObjCClass:
3681 case BuiltinType::ObjCSel:
3682 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
3683 case BuiltinType::Id:
3684 #include "clang/Basic/OpenCLImageTypes.def"
3685 case BuiltinType::OCLSampler:
3686 case BuiltinType::OCLEvent:
3687 case BuiltinType::OCLClkEvent:
3688 case BuiltinType::OCLQueue:
3689 case BuiltinType::OCLReserveID:
3690 case BuiltinType::BuiltinFn:
3691 case BuiltinType::NullPtr:
3692 case BuiltinType::OMPArraySection:
3695 llvm_unreachable("unknown builtin type");
3697 // Non-pointer types.
3699 case Type::LValueReference:
3700 case Type::RValueReference:
3701 case Type::ConstantArray:
3702 case Type::IncompleteArray:
3703 case Type::VariableArray:
3704 case Type::DependentSizedArray:
3705 case Type::DependentSizedExtVector:
3707 case Type::ExtVector:
3708 case Type::DependentAddressSpace:
3709 case Type::FunctionProto:
3710 case Type::FunctionNoProto:
3712 case Type::DeducedTemplateSpecialization:
3714 case Type::InjectedClassName:
3715 case Type::PackExpansion:
3716 case Type::ObjCObject:
3717 case Type::ObjCInterface:
3722 llvm_unreachable("bad type kind!");
3725 llvm::Optional<NullabilityKind> AttributedType::getImmediateNullability() const {
3726 if (getAttrKind() == AttributedType::attr_nonnull)
3727 return NullabilityKind::NonNull;
3728 if (getAttrKind() == AttributedType::attr_nullable)
3729 return NullabilityKind::Nullable;
3730 if (getAttrKind() == AttributedType::attr_null_unspecified)
3731 return NullabilityKind::Unspecified;
3735 Optional<NullabilityKind> AttributedType::stripOuterNullability(QualType &T) {
3736 if (auto attributed = dyn_cast<AttributedType>(T.getTypePtr())) {
3737 if (auto nullability = attributed->getImmediateNullability()) {
3738 T = attributed->getModifiedType();
3746 bool Type::isBlockCompatibleObjCPointerType(ASTContext &ctx) const {
3747 const ObjCObjectPointerType *objcPtr = getAs<ObjCObjectPointerType>();
3751 if (objcPtr->isObjCIdType()) {
3752 // id is always okay.
3756 // Blocks are NSObjects.
3757 if (ObjCInterfaceDecl *iface = objcPtr->getInterfaceDecl()) {
3758 if (iface->getIdentifier() != ctx.getNSObjectName())
3761 // Continue to check qualifiers, below.
3762 } else if (objcPtr->isObjCQualifiedIdType()) {
3763 // Continue to check qualifiers, below.
3768 // Check protocol qualifiers.
3769 for (ObjCProtocolDecl *proto : objcPtr->quals()) {
3770 // Blocks conform to NSObject and NSCopying.
3771 if (proto->getIdentifier() != ctx.getNSObjectName() &&
3772 proto->getIdentifier() != ctx.getNSCopyingName())
3779 Qualifiers::ObjCLifetime Type::getObjCARCImplicitLifetime() const {
3780 if (isObjCARCImplicitlyUnretainedType())
3781 return Qualifiers::OCL_ExplicitNone;
3782 return Qualifiers::OCL_Strong;
3785 bool Type::isObjCARCImplicitlyUnretainedType() const {
3786 assert(isObjCLifetimeType() &&
3787 "cannot query implicit lifetime for non-inferrable type");
3789 const Type *canon = getCanonicalTypeInternal().getTypePtr();
3791 // Walk down to the base type. We don't care about qualifiers for this.
3792 while (const ArrayType *array = dyn_cast<ArrayType>(canon))
3793 canon = array->getElementType().getTypePtr();
3795 if (const ObjCObjectPointerType *opt
3796 = dyn_cast<ObjCObjectPointerType>(canon)) {
3797 // Class and Class<Protocol> don't require retention.
3798 if (opt->getObjectType()->isObjCClass())
3805 bool Type::isObjCNSObjectType() const {
3806 const Type *cur = this;
3808 if (const TypedefType *typedefType = dyn_cast<TypedefType>(cur))
3809 return typedefType->getDecl()->hasAttr<ObjCNSObjectAttr>();
3811 // Single-step desugar until we run out of sugar.
3812 QualType next = cur->getLocallyUnqualifiedSingleStepDesugaredType();
3813 if (next.getTypePtr() == cur) return false;
3814 cur = next.getTypePtr();
3818 bool Type::isObjCIndependentClassType() const {
3819 if (const TypedefType *typedefType = dyn_cast<TypedefType>(this))
3820 return typedefType->getDecl()->hasAttr<ObjCIndependentClassAttr>();
3824 bool Type::isObjCRetainableType() const {
3825 return isObjCObjectPointerType() ||
3826 isBlockPointerType() ||
3827 isObjCNSObjectType();
3830 bool Type::isObjCIndirectLifetimeType() const {
3831 if (isObjCLifetimeType())
3833 if (const PointerType *OPT = getAs<PointerType>())
3834 return OPT->getPointeeType()->isObjCIndirectLifetimeType();
3835 if (const ReferenceType *Ref = getAs<ReferenceType>())
3836 return Ref->getPointeeType()->isObjCIndirectLifetimeType();
3837 if (const MemberPointerType *MemPtr = getAs<MemberPointerType>())
3838 return MemPtr->getPointeeType()->isObjCIndirectLifetimeType();
3842 /// Returns true if objects of this type have lifetime semantics under
3844 bool Type::isObjCLifetimeType() const {
3845 const Type *type = this;
3846 while (const ArrayType *array = type->getAsArrayTypeUnsafe())
3847 type = array->getElementType().getTypePtr();
3848 return type->isObjCRetainableType();
3851 /// \brief Determine whether the given type T is a "bridgable" Objective-C type,
3852 /// which is either an Objective-C object pointer type or an
3853 bool Type::isObjCARCBridgableType() const {
3854 return isObjCObjectPointerType() || isBlockPointerType();
3857 /// \brief Determine whether the given type T is a "bridgeable" C type.
3858 bool Type::isCARCBridgableType() const {
3859 const PointerType *Pointer = getAs<PointerType>();
3863 QualType Pointee = Pointer->getPointeeType();
3864 return Pointee->isVoidType() || Pointee->isRecordType();
3867 bool Type::hasSizedVLAType() const {
3868 if (!isVariablyModifiedType()) return false;
3870 if (const PointerType *ptr = getAs<PointerType>())
3871 return ptr->getPointeeType()->hasSizedVLAType();
3872 if (const ReferenceType *ref = getAs<ReferenceType>())
3873 return ref->getPointeeType()->hasSizedVLAType();
3874 if (const ArrayType *arr = getAsArrayTypeUnsafe()) {
3875 if (isa<VariableArrayType>(arr) &&
3876 cast<VariableArrayType>(arr)->getSizeExpr())
3879 return arr->getElementType()->hasSizedVLAType();
3885 QualType::DestructionKind QualType::isDestructedTypeImpl(QualType type) {
3886 switch (type.getObjCLifetime()) {
3887 case Qualifiers::OCL_None:
3888 case Qualifiers::OCL_ExplicitNone:
3889 case Qualifiers::OCL_Autoreleasing:
3892 case Qualifiers::OCL_Strong:
3893 return DK_objc_strong_lifetime;
3894 case Qualifiers::OCL_Weak:
3895 return DK_objc_weak_lifetime;
3898 /// Currently, the only destruction kind we recognize is C++ objects
3899 /// with non-trivial destructors.
3900 const CXXRecordDecl *record =
3901 type->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
3902 if (record && record->hasDefinition() && !record->hasTrivialDestructor())
3903 return DK_cxx_destructor;
3908 CXXRecordDecl *MemberPointerType::getMostRecentCXXRecordDecl() const {
3909 return getClass()->getAsCXXRecordDecl()->getMostRecentDecl();