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"
15 #include "clang/AST/ASTContext.h"
16 #include "clang/AST/Attr.h"
17 #include "clang/AST/CharUnits.h"
18 #include "clang/AST/DeclCXX.h"
19 #include "clang/AST/DeclObjC.h"
20 #include "clang/AST/DeclTemplate.h"
21 #include "clang/AST/Expr.h"
22 #include "clang/AST/PrettyPrinter.h"
23 #include "clang/AST/TypeVisitor.h"
24 #include "clang/Basic/Specifiers.h"
25 #include "clang/Basic/TargetInfo.h"
26 #include "llvm/ADT/APSInt.h"
27 #include "llvm/ADT/StringExtras.h"
29 using namespace clang;
31 bool Qualifiers::isStrictSupersetOf(Qualifiers Other) const {
32 return (*this != Other) &&
33 // CVR qualifiers superset
34 (((Mask & CVRMask) | (Other.Mask & CVRMask)) == (Mask & CVRMask)) &&
35 // ObjC GC qualifiers superset
36 ((getObjCGCAttr() == Other.getObjCGCAttr()) ||
37 (hasObjCGCAttr() && !Other.hasObjCGCAttr())) &&
38 // Address space superset.
39 ((getAddressSpace() == Other.getAddressSpace()) ||
40 (hasAddressSpace()&& !Other.hasAddressSpace())) &&
41 // Lifetime qualifier superset.
42 ((getObjCLifetime() == Other.getObjCLifetime()) ||
43 (hasObjCLifetime() && !Other.hasObjCLifetime()));
46 const IdentifierInfo* QualType::getBaseTypeIdentifier() const {
47 const Type* ty = getTypePtr();
48 NamedDecl *ND = nullptr;
49 if (ty->isPointerType() || ty->isReferenceType())
50 return ty->getPointeeType().getBaseTypeIdentifier();
51 else if (ty->isRecordType())
52 ND = ty->getAs<RecordType>()->getDecl();
53 else if (ty->isEnumeralType())
54 ND = ty->getAs<EnumType>()->getDecl();
55 else if (ty->getTypeClass() == Type::Typedef)
56 ND = ty->getAs<TypedefType>()->getDecl();
57 else if (ty->isArrayType())
58 return ty->castAsArrayTypeUnsafe()->
59 getElementType().getBaseTypeIdentifier();
62 return ND->getIdentifier();
66 bool QualType::isConstant(QualType T, const ASTContext &Ctx) {
67 if (T.isConstQualified())
70 if (const ArrayType *AT = Ctx.getAsArrayType(T))
71 return AT->getElementType().isConstant(Ctx);
73 return T.getAddressSpace() == LangAS::opencl_constant;
76 unsigned ConstantArrayType::getNumAddressingBits(const ASTContext &Context,
78 const llvm::APInt &NumElements) {
79 uint64_t ElementSize = Context.getTypeSizeInChars(ElementType).getQuantity();
81 // Fast path the common cases so we can avoid the conservative computation
82 // below, which in common cases allocates "large" APSInt values, which are
85 // If the element size is a power of 2, we can directly compute the additional
86 // number of addressing bits beyond those required for the element count.
87 if (llvm::isPowerOf2_64(ElementSize)) {
88 return NumElements.getActiveBits() + llvm::Log2_64(ElementSize);
91 // If both the element count and element size fit in 32-bits, we can do the
92 // computation directly in 64-bits.
93 if ((ElementSize >> 32) == 0 && NumElements.getBitWidth() <= 64 &&
94 (NumElements.getZExtValue() >> 32) == 0) {
95 uint64_t TotalSize = NumElements.getZExtValue() * ElementSize;
96 return 64 - llvm::countLeadingZeros(TotalSize);
99 // Otherwise, use APSInt to handle arbitrary sized values.
100 llvm::APSInt SizeExtended(NumElements, true);
101 unsigned SizeTypeBits = Context.getTypeSize(Context.getSizeType());
102 SizeExtended = SizeExtended.extend(std::max(SizeTypeBits,
103 SizeExtended.getBitWidth()) * 2);
105 llvm::APSInt TotalSize(llvm::APInt(SizeExtended.getBitWidth(), ElementSize));
106 TotalSize *= SizeExtended;
108 return TotalSize.getActiveBits();
111 unsigned ConstantArrayType::getMaxSizeBits(const ASTContext &Context) {
112 unsigned Bits = Context.getTypeSize(Context.getSizeType());
114 // Limit the number of bits in size_t so that maximal bit size fits 64 bit
115 // integer (see PR8256). We can do this as currently there is no hardware
116 // that supports full 64-bit virtual space.
123 DependentSizedArrayType::DependentSizedArrayType(const ASTContext &Context,
124 QualType et, QualType can,
125 Expr *e, ArraySizeModifier sm,
127 SourceRange brackets)
128 : ArrayType(DependentSizedArray, et, can, sm, tq,
129 (et->containsUnexpandedParameterPack() ||
130 (e && e->containsUnexpandedParameterPack()))),
131 Context(Context), SizeExpr((Stmt*) e), Brackets(brackets)
135 void DependentSizedArrayType::Profile(llvm::FoldingSetNodeID &ID,
136 const ASTContext &Context,
138 ArraySizeModifier SizeMod,
141 ID.AddPointer(ET.getAsOpaquePtr());
142 ID.AddInteger(SizeMod);
143 ID.AddInteger(TypeQuals);
144 E->Profile(ID, Context, true);
147 DependentSizedExtVectorType::DependentSizedExtVectorType(const
149 QualType ElementType,
153 : Type(DependentSizedExtVector, can, /*Dependent=*/true,
154 /*InstantiationDependent=*/true,
155 ElementType->isVariablyModifiedType(),
156 (ElementType->containsUnexpandedParameterPack() ||
157 (SizeExpr && SizeExpr->containsUnexpandedParameterPack()))),
158 Context(Context), SizeExpr(SizeExpr), ElementType(ElementType),
164 DependentSizedExtVectorType::Profile(llvm::FoldingSetNodeID &ID,
165 const ASTContext &Context,
166 QualType ElementType, Expr *SizeExpr) {
167 ID.AddPointer(ElementType.getAsOpaquePtr());
168 SizeExpr->Profile(ID, Context, true);
171 VectorType::VectorType(QualType vecType, unsigned nElements, QualType canonType,
173 : VectorType(Vector, vecType, nElements, canonType, vecKind) {}
175 VectorType::VectorType(TypeClass tc, QualType vecType, unsigned nElements,
176 QualType canonType, VectorKind vecKind)
177 : Type(tc, canonType, vecType->isDependentType(),
178 vecType->isInstantiationDependentType(),
179 vecType->isVariablyModifiedType(),
180 vecType->containsUnexpandedParameterPack()),
183 VectorTypeBits.VecKind = vecKind;
184 VectorTypeBits.NumElements = nElements;
187 /// getArrayElementTypeNoTypeQual - If this is an array type, return the
188 /// element type of the array, potentially with type qualifiers missing.
189 /// This method should never be used when type qualifiers are meaningful.
190 const Type *Type::getArrayElementTypeNoTypeQual() const {
191 // If this is directly an array type, return it.
192 if (const ArrayType *ATy = dyn_cast<ArrayType>(this))
193 return ATy->getElementType().getTypePtr();
195 // If the canonical form of this type isn't the right kind, reject it.
196 if (!isa<ArrayType>(CanonicalType))
199 // If this is a typedef for an array type, strip the typedef off without
200 // losing all typedef information.
201 return cast<ArrayType>(getUnqualifiedDesugaredType())
202 ->getElementType().getTypePtr();
205 /// getDesugaredType - Return the specified type with any "sugar" removed from
206 /// the type. This takes off typedefs, typeof's etc. If the outer level of
207 /// the type is already concrete, it returns it unmodified. This is similar
208 /// to getting the canonical type, but it doesn't remove *all* typedefs. For
209 /// example, it returns "T*" as "T*", (not as "int*"), because the pointer is
211 QualType QualType::getDesugaredType(QualType T, const ASTContext &Context) {
212 SplitQualType split = getSplitDesugaredType(T);
213 return Context.getQualifiedType(split.Ty, split.Quals);
216 QualType QualType::getSingleStepDesugaredTypeImpl(QualType type,
217 const ASTContext &Context) {
218 SplitQualType split = type.split();
219 QualType desugar = split.Ty->getLocallyUnqualifiedSingleStepDesugaredType();
220 return Context.getQualifiedType(desugar, split.Quals);
223 QualType Type::getLocallyUnqualifiedSingleStepDesugaredType() const {
224 switch (getTypeClass()) {
225 #define ABSTRACT_TYPE(Class, Parent)
226 #define TYPE(Class, Parent) \
227 case Type::Class: { \
228 const Class##Type *ty = cast<Class##Type>(this); \
229 if (!ty->isSugared()) return QualType(ty, 0); \
230 return ty->desugar(); \
232 #include "clang/AST/TypeNodes.def"
234 llvm_unreachable("bad type kind!");
237 SplitQualType QualType::getSplitDesugaredType(QualType T) {
238 QualifierCollector Qs;
242 const Type *CurTy = Qs.strip(Cur);
243 switch (CurTy->getTypeClass()) {
244 #define ABSTRACT_TYPE(Class, Parent)
245 #define TYPE(Class, Parent) \
246 case Type::Class: { \
247 const Class##Type *Ty = cast<Class##Type>(CurTy); \
248 if (!Ty->isSugared()) \
249 return SplitQualType(Ty, Qs); \
250 Cur = Ty->desugar(); \
253 #include "clang/AST/TypeNodes.def"
258 SplitQualType QualType::getSplitUnqualifiedTypeImpl(QualType type) {
259 SplitQualType split = type.split();
261 // All the qualifiers we've seen so far.
262 Qualifiers quals = split.Quals;
264 // The last type node we saw with any nodes inside it.
265 const Type *lastTypeWithQuals = split.Ty;
270 // Do a single-step desugar, aborting the loop if the type isn't
272 switch (split.Ty->getTypeClass()) {
273 #define ABSTRACT_TYPE(Class, Parent)
274 #define TYPE(Class, Parent) \
275 case Type::Class: { \
276 const Class##Type *ty = cast<Class##Type>(split.Ty); \
277 if (!ty->isSugared()) goto done; \
278 next = ty->desugar(); \
281 #include "clang/AST/TypeNodes.def"
284 // Otherwise, split the underlying type. If that yields qualifiers,
285 // update the information.
286 split = next.split();
287 if (!split.Quals.empty()) {
288 lastTypeWithQuals = split.Ty;
289 quals.addConsistentQualifiers(split.Quals);
294 return SplitQualType(lastTypeWithQuals, quals);
297 QualType QualType::IgnoreParens(QualType T) {
298 // FIXME: this seems inherently un-qualifiers-safe.
299 while (const ParenType *PT = T->getAs<ParenType>())
300 T = PT->getInnerType();
304 /// \brief This will check for a T (which should be a Type which can act as
305 /// sugar, such as a TypedefType) by removing any existing sugar until it
306 /// reaches a T or a non-sugared type.
307 template<typename T> static const T *getAsSugar(const Type *Cur) {
309 if (const T *Sugar = dyn_cast<T>(Cur))
311 switch (Cur->getTypeClass()) {
312 #define ABSTRACT_TYPE(Class, Parent)
313 #define TYPE(Class, Parent) \
314 case Type::Class: { \
315 const Class##Type *Ty = cast<Class##Type>(Cur); \
316 if (!Ty->isSugared()) return 0; \
317 Cur = Ty->desugar().getTypePtr(); \
320 #include "clang/AST/TypeNodes.def"
325 template <> const TypedefType *Type::getAs() const {
326 return getAsSugar<TypedefType>(this);
329 template <> const TemplateSpecializationType *Type::getAs() const {
330 return getAsSugar<TemplateSpecializationType>(this);
333 template <> const AttributedType *Type::getAs() const {
334 return getAsSugar<AttributedType>(this);
337 /// getUnqualifiedDesugaredType - Pull any qualifiers and syntactic
338 /// sugar off the given type. This should produce an object of the
339 /// same dynamic type as the canonical type.
340 const Type *Type::getUnqualifiedDesugaredType() const {
341 const Type *Cur = this;
344 switch (Cur->getTypeClass()) {
345 #define ABSTRACT_TYPE(Class, Parent)
346 #define TYPE(Class, Parent) \
348 const Class##Type *Ty = cast<Class##Type>(Cur); \
349 if (!Ty->isSugared()) return Cur; \
350 Cur = Ty->desugar().getTypePtr(); \
353 #include "clang/AST/TypeNodes.def"
357 bool Type::isClassType() const {
358 if (const RecordType *RT = getAs<RecordType>())
359 return RT->getDecl()->isClass();
362 bool Type::isStructureType() const {
363 if (const RecordType *RT = getAs<RecordType>())
364 return RT->getDecl()->isStruct();
367 bool Type::isObjCBoxableRecordType() const {
368 if (const RecordType *RT = getAs<RecordType>())
369 return RT->getDecl()->hasAttr<ObjCBoxableAttr>();
372 bool Type::isInterfaceType() const {
373 if (const RecordType *RT = getAs<RecordType>())
374 return RT->getDecl()->isInterface();
377 bool Type::isStructureOrClassType() const {
378 if (const RecordType *RT = getAs<RecordType>()) {
379 RecordDecl *RD = RT->getDecl();
380 return RD->isStruct() || RD->isClass() || RD->isInterface();
384 bool Type::isVoidPointerType() const {
385 if (const PointerType *PT = getAs<PointerType>())
386 return PT->getPointeeType()->isVoidType();
390 bool Type::isUnionType() const {
391 if (const RecordType *RT = getAs<RecordType>())
392 return RT->getDecl()->isUnion();
396 bool Type::isComplexType() const {
397 if (const ComplexType *CT = dyn_cast<ComplexType>(CanonicalType))
398 return CT->getElementType()->isFloatingType();
402 bool Type::isComplexIntegerType() const {
403 // Check for GCC complex integer extension.
404 return getAsComplexIntegerType();
407 const ComplexType *Type::getAsComplexIntegerType() const {
408 if (const ComplexType *Complex = getAs<ComplexType>())
409 if (Complex->getElementType()->isIntegerType())
414 QualType Type::getPointeeType() const {
415 if (const PointerType *PT = getAs<PointerType>())
416 return PT->getPointeeType();
417 if (const ObjCObjectPointerType *OPT = getAs<ObjCObjectPointerType>())
418 return OPT->getPointeeType();
419 if (const BlockPointerType *BPT = getAs<BlockPointerType>())
420 return BPT->getPointeeType();
421 if (const ReferenceType *RT = getAs<ReferenceType>())
422 return RT->getPointeeType();
423 if (const MemberPointerType *MPT = getAs<MemberPointerType>())
424 return MPT->getPointeeType();
425 if (const DecayedType *DT = getAs<DecayedType>())
426 return DT->getPointeeType();
430 const RecordType *Type::getAsStructureType() const {
431 // If this is directly a structure type, return it.
432 if (const RecordType *RT = dyn_cast<RecordType>(this)) {
433 if (RT->getDecl()->isStruct())
437 // If the canonical form of this type isn't the right kind, reject it.
438 if (const RecordType *RT = dyn_cast<RecordType>(CanonicalType)) {
439 if (!RT->getDecl()->isStruct())
442 // If this is a typedef for a structure type, strip the typedef off without
443 // losing all typedef information.
444 return cast<RecordType>(getUnqualifiedDesugaredType());
449 const RecordType *Type::getAsUnionType() const {
450 // If this is directly a union type, return it.
451 if (const RecordType *RT = dyn_cast<RecordType>(this)) {
452 if (RT->getDecl()->isUnion())
456 // If the canonical form of this type isn't the right kind, reject it.
457 if (const RecordType *RT = dyn_cast<RecordType>(CanonicalType)) {
458 if (!RT->getDecl()->isUnion())
461 // If this is a typedef for a union type, strip the typedef off without
462 // losing all typedef information.
463 return cast<RecordType>(getUnqualifiedDesugaredType());
469 bool Type::isObjCIdOrObjectKindOfType(const ASTContext &ctx,
470 const ObjCObjectType *&bound) const {
473 const ObjCObjectPointerType *OPT = getAs<ObjCObjectPointerType>();
478 if (OPT->isObjCIdType())
481 // If it's not a __kindof type, reject it now.
482 if (!OPT->isKindOfType())
485 // If it's Class or qualified Class, it's not an object type.
486 if (OPT->isObjCClassType() || OPT->isObjCQualifiedClassType())
489 // Figure out the type bound for the __kindof type.
490 bound = OPT->getObjectType()->stripObjCKindOfTypeAndQuals(ctx)
491 ->getAs<ObjCObjectType>();
495 bool Type::isObjCClassOrClassKindOfType() const {
496 const ObjCObjectPointerType *OPT = getAs<ObjCObjectPointerType>();
501 if (OPT->isObjCClassType())
504 // If it's not a __kindof type, reject it now.
505 if (!OPT->isKindOfType())
508 // If it's Class or qualified Class, it's a class __kindof type.
509 return OPT->isObjCClassType() || OPT->isObjCQualifiedClassType();
512 /// Was this type written with the special inert-in-MRC __unsafe_unretained
515 /// This approximates the answer to the following question: if this
516 /// translation unit were compiled in ARC, would this type be qualified
517 /// with __unsafe_unretained?
518 bool Type::isObjCInertUnsafeUnretainedType() const {
519 const Type *cur = this;
521 if (auto attributed = dyn_cast<AttributedType>(cur)) {
522 if (attributed->getAttrKind() ==
523 AttributedType::attr_objc_inert_unsafe_unretained)
527 // Single-step desugar until we run out of sugar.
528 QualType next = cur->getLocallyUnqualifiedSingleStepDesugaredType();
529 if (next.getTypePtr() == cur) return false;
530 cur = next.getTypePtr();
534 ObjCTypeParamType::ObjCTypeParamType(const ObjCTypeParamDecl *D,
536 ArrayRef<ObjCProtocolDecl *> protocols)
537 : Type(ObjCTypeParam, can, can->isDependentType(),
538 can->isInstantiationDependentType(),
539 can->isVariablyModifiedType(),
540 /*ContainsUnexpandedParameterPack=*/false),
541 OTPDecl(const_cast<ObjCTypeParamDecl*>(D))
543 initialize(protocols);
546 ObjCObjectType::ObjCObjectType(QualType Canonical, QualType Base,
547 ArrayRef<QualType> typeArgs,
548 ArrayRef<ObjCProtocolDecl *> protocols,
550 : Type(ObjCObject, Canonical, Base->isDependentType(),
551 Base->isInstantiationDependentType(),
552 Base->isVariablyModifiedType(),
553 Base->containsUnexpandedParameterPack()),
556 ObjCObjectTypeBits.IsKindOf = isKindOf;
558 ObjCObjectTypeBits.NumTypeArgs = typeArgs.size();
559 assert(getTypeArgsAsWritten().size() == typeArgs.size() &&
560 "bitfield overflow in type argument count");
561 if (!typeArgs.empty())
562 memcpy(getTypeArgStorage(), typeArgs.data(),
563 typeArgs.size() * sizeof(QualType));
565 for (auto typeArg : typeArgs) {
566 if (typeArg->isDependentType())
568 else if (typeArg->isInstantiationDependentType())
569 setInstantiationDependent();
571 if (typeArg->containsUnexpandedParameterPack())
572 setContainsUnexpandedParameterPack();
574 // Initialize the protocol qualifiers. The protocol storage is known
575 // after we set number of type arguments.
576 initialize(protocols);
579 bool ObjCObjectType::isSpecialized() const {
580 // If we have type arguments written here, the type is specialized.
581 if (ObjCObjectTypeBits.NumTypeArgs > 0)
584 // Otherwise, check whether the base type is specialized.
585 if (auto objcObject = getBaseType()->getAs<ObjCObjectType>()) {
586 // Terminate when we reach an interface type.
587 if (isa<ObjCInterfaceType>(objcObject))
590 return objcObject->isSpecialized();
597 ArrayRef<QualType> ObjCObjectType::getTypeArgs() const {
598 // We have type arguments written on this type.
599 if (isSpecializedAsWritten())
600 return getTypeArgsAsWritten();
602 // Look at the base type, which might have type arguments.
603 if (auto objcObject = getBaseType()->getAs<ObjCObjectType>()) {
604 // Terminate when we reach an interface type.
605 if (isa<ObjCInterfaceType>(objcObject))
608 return objcObject->getTypeArgs();
611 // No type arguments.
615 bool ObjCObjectType::isKindOfType() const {
616 if (isKindOfTypeAsWritten())
619 // Look at the base type, which might have type arguments.
620 if (auto objcObject = getBaseType()->getAs<ObjCObjectType>()) {
621 // Terminate when we reach an interface type.
622 if (isa<ObjCInterfaceType>(objcObject))
625 return objcObject->isKindOfType();
628 // Not a "__kindof" type.
632 QualType ObjCObjectType::stripObjCKindOfTypeAndQuals(
633 const ASTContext &ctx) const {
634 if (!isKindOfType() && qual_empty())
635 return QualType(this, 0);
637 // Recursively strip __kindof.
638 SplitQualType splitBaseType = getBaseType().split();
639 QualType baseType(splitBaseType.Ty, 0);
640 if (const ObjCObjectType *baseObj
641 = splitBaseType.Ty->getAs<ObjCObjectType>()) {
642 baseType = baseObj->stripObjCKindOfTypeAndQuals(ctx);
645 return ctx.getObjCObjectType(ctx.getQualifiedType(baseType,
646 splitBaseType.Quals),
647 getTypeArgsAsWritten(),
652 const ObjCObjectPointerType *ObjCObjectPointerType::stripObjCKindOfTypeAndQuals(
653 const ASTContext &ctx) const {
654 if (!isKindOfType() && qual_empty())
657 QualType obj = getObjectType()->stripObjCKindOfTypeAndQuals(ctx);
658 return ctx.getObjCObjectPointerType(obj)->castAs<ObjCObjectPointerType>();
664 QualType simpleTransform(ASTContext &ctx, QualType type, F &&f);
666 /// Visitor used by simpleTransform() to perform the transformation.
668 struct SimpleTransformVisitor
669 : public TypeVisitor<SimpleTransformVisitor<F>, QualType> {
673 QualType recurse(QualType type) {
674 return simpleTransform(Ctx, type, std::move(TheFunc));
678 SimpleTransformVisitor(ASTContext &ctx, F &&f) : Ctx(ctx), TheFunc(std::move(f)) { }
680 // None of the clients of this transformation can occur where
681 // there are dependent types, so skip dependent types.
682 #define TYPE(Class, Base)
683 #define DEPENDENT_TYPE(Class, Base) \
684 QualType Visit##Class##Type(const Class##Type *T) { return QualType(T, 0); }
685 #include "clang/AST/TypeNodes.def"
687 #define TRIVIAL_TYPE_CLASS(Class) \
688 QualType Visit##Class##Type(const Class##Type *T) { return QualType(T, 0); }
690 TRIVIAL_TYPE_CLASS(Builtin)
692 QualType VisitComplexType(const ComplexType *T) {
693 QualType elementType = recurse(T->getElementType());
694 if (elementType.isNull())
697 if (elementType.getAsOpaquePtr() == T->getElementType().getAsOpaquePtr())
698 return QualType(T, 0);
700 return Ctx.getComplexType(elementType);
703 QualType VisitPointerType(const PointerType *T) {
704 QualType pointeeType = recurse(T->getPointeeType());
705 if (pointeeType.isNull())
708 if (pointeeType.getAsOpaquePtr() == T->getPointeeType().getAsOpaquePtr())
709 return QualType(T, 0);
711 return Ctx.getPointerType(pointeeType);
714 QualType VisitBlockPointerType(const BlockPointerType *T) {
715 QualType pointeeType = recurse(T->getPointeeType());
716 if (pointeeType.isNull())
719 if (pointeeType.getAsOpaquePtr() == T->getPointeeType().getAsOpaquePtr())
720 return QualType(T, 0);
722 return Ctx.getBlockPointerType(pointeeType);
725 QualType VisitLValueReferenceType(const LValueReferenceType *T) {
726 QualType pointeeType = recurse(T->getPointeeTypeAsWritten());
727 if (pointeeType.isNull())
730 if (pointeeType.getAsOpaquePtr()
731 == T->getPointeeTypeAsWritten().getAsOpaquePtr())
732 return QualType(T, 0);
734 return Ctx.getLValueReferenceType(pointeeType, T->isSpelledAsLValue());
737 QualType VisitRValueReferenceType(const RValueReferenceType *T) {
738 QualType pointeeType = recurse(T->getPointeeTypeAsWritten());
739 if (pointeeType.isNull())
742 if (pointeeType.getAsOpaquePtr()
743 == T->getPointeeTypeAsWritten().getAsOpaquePtr())
744 return QualType(T, 0);
746 return Ctx.getRValueReferenceType(pointeeType);
749 QualType VisitMemberPointerType(const MemberPointerType *T) {
750 QualType pointeeType = recurse(T->getPointeeType());
751 if (pointeeType.isNull())
754 if (pointeeType.getAsOpaquePtr() == T->getPointeeType().getAsOpaquePtr())
755 return QualType(T, 0);
757 return Ctx.getMemberPointerType(pointeeType, T->getClass());
760 QualType VisitConstantArrayType(const ConstantArrayType *T) {
761 QualType elementType = recurse(T->getElementType());
762 if (elementType.isNull())
765 if (elementType.getAsOpaquePtr() == T->getElementType().getAsOpaquePtr())
766 return QualType(T, 0);
768 return Ctx.getConstantArrayType(elementType, T->getSize(),
769 T->getSizeModifier(),
770 T->getIndexTypeCVRQualifiers());
773 QualType VisitVariableArrayType(const VariableArrayType *T) {
774 QualType elementType = recurse(T->getElementType());
775 if (elementType.isNull())
778 if (elementType.getAsOpaquePtr() == T->getElementType().getAsOpaquePtr())
779 return QualType(T, 0);
781 return Ctx.getVariableArrayType(elementType, T->getSizeExpr(),
782 T->getSizeModifier(),
783 T->getIndexTypeCVRQualifiers(),
784 T->getBracketsRange());
787 QualType VisitIncompleteArrayType(const IncompleteArrayType *T) {
788 QualType elementType = recurse(T->getElementType());
789 if (elementType.isNull())
792 if (elementType.getAsOpaquePtr() == T->getElementType().getAsOpaquePtr())
793 return QualType(T, 0);
795 return Ctx.getIncompleteArrayType(elementType, T->getSizeModifier(),
796 T->getIndexTypeCVRQualifiers());
799 QualType VisitVectorType(const VectorType *T) {
800 QualType elementType = recurse(T->getElementType());
801 if (elementType.isNull())
804 if (elementType.getAsOpaquePtr() == T->getElementType().getAsOpaquePtr())
805 return QualType(T, 0);
807 return Ctx.getVectorType(elementType, T->getNumElements(),
811 QualType VisitExtVectorType(const ExtVectorType *T) {
812 QualType elementType = recurse(T->getElementType());
813 if (elementType.isNull())
816 if (elementType.getAsOpaquePtr() == T->getElementType().getAsOpaquePtr())
817 return QualType(T, 0);
819 return Ctx.getExtVectorType(elementType, T->getNumElements());
822 QualType VisitFunctionNoProtoType(const FunctionNoProtoType *T) {
823 QualType returnType = recurse(T->getReturnType());
824 if (returnType.isNull())
827 if (returnType.getAsOpaquePtr() == T->getReturnType().getAsOpaquePtr())
828 return QualType(T, 0);
830 return Ctx.getFunctionNoProtoType(returnType, T->getExtInfo());
833 QualType VisitFunctionProtoType(const FunctionProtoType *T) {
834 QualType returnType = recurse(T->getReturnType());
835 if (returnType.isNull())
838 // Transform parameter types.
839 SmallVector<QualType, 4> paramTypes;
840 bool paramChanged = false;
841 for (auto paramType : T->getParamTypes()) {
842 QualType newParamType = recurse(paramType);
843 if (newParamType.isNull())
846 if (newParamType.getAsOpaquePtr() != paramType.getAsOpaquePtr())
849 paramTypes.push_back(newParamType);
852 // Transform extended info.
853 FunctionProtoType::ExtProtoInfo info = T->getExtProtoInfo();
854 bool exceptionChanged = false;
855 if (info.ExceptionSpec.Type == EST_Dynamic) {
856 SmallVector<QualType, 4> exceptionTypes;
857 for (auto exceptionType : info.ExceptionSpec.Exceptions) {
858 QualType newExceptionType = recurse(exceptionType);
859 if (newExceptionType.isNull())
862 if (newExceptionType.getAsOpaquePtr()
863 != exceptionType.getAsOpaquePtr())
864 exceptionChanged = true;
866 exceptionTypes.push_back(newExceptionType);
869 if (exceptionChanged) {
870 info.ExceptionSpec.Exceptions =
871 llvm::makeArrayRef(exceptionTypes).copy(Ctx);
875 if (returnType.getAsOpaquePtr() == T->getReturnType().getAsOpaquePtr() &&
876 !paramChanged && !exceptionChanged)
877 return QualType(T, 0);
879 return Ctx.getFunctionType(returnType, paramTypes, info);
882 QualType VisitParenType(const ParenType *T) {
883 QualType innerType = recurse(T->getInnerType());
884 if (innerType.isNull())
887 if (innerType.getAsOpaquePtr() == T->getInnerType().getAsOpaquePtr())
888 return QualType(T, 0);
890 return Ctx.getParenType(innerType);
893 TRIVIAL_TYPE_CLASS(Typedef)
894 TRIVIAL_TYPE_CLASS(ObjCTypeParam)
896 QualType VisitAdjustedType(const AdjustedType *T) {
897 QualType originalType = recurse(T->getOriginalType());
898 if (originalType.isNull())
901 QualType adjustedType = recurse(T->getAdjustedType());
902 if (adjustedType.isNull())
905 if (originalType.getAsOpaquePtr()
906 == T->getOriginalType().getAsOpaquePtr() &&
907 adjustedType.getAsOpaquePtr() == T->getAdjustedType().getAsOpaquePtr())
908 return QualType(T, 0);
910 return Ctx.getAdjustedType(originalType, adjustedType);
913 QualType VisitDecayedType(const DecayedType *T) {
914 QualType originalType = recurse(T->getOriginalType());
915 if (originalType.isNull())
918 if (originalType.getAsOpaquePtr()
919 == T->getOriginalType().getAsOpaquePtr())
920 return QualType(T, 0);
922 return Ctx.getDecayedType(originalType);
925 TRIVIAL_TYPE_CLASS(TypeOfExpr)
926 TRIVIAL_TYPE_CLASS(TypeOf)
927 TRIVIAL_TYPE_CLASS(Decltype)
928 TRIVIAL_TYPE_CLASS(UnaryTransform)
929 TRIVIAL_TYPE_CLASS(Record)
930 TRIVIAL_TYPE_CLASS(Enum)
932 // FIXME: Non-trivial to implement, but important for C++
933 TRIVIAL_TYPE_CLASS(Elaborated)
935 QualType VisitAttributedType(const AttributedType *T) {
936 QualType modifiedType = recurse(T->getModifiedType());
937 if (modifiedType.isNull())
940 QualType equivalentType = recurse(T->getEquivalentType());
941 if (equivalentType.isNull())
944 if (modifiedType.getAsOpaquePtr()
945 == T->getModifiedType().getAsOpaquePtr() &&
946 equivalentType.getAsOpaquePtr()
947 == T->getEquivalentType().getAsOpaquePtr())
948 return QualType(T, 0);
950 return Ctx.getAttributedType(T->getAttrKind(), modifiedType,
954 QualType VisitSubstTemplateTypeParmType(const SubstTemplateTypeParmType *T) {
955 QualType replacementType = recurse(T->getReplacementType());
956 if (replacementType.isNull())
959 if (replacementType.getAsOpaquePtr()
960 == T->getReplacementType().getAsOpaquePtr())
961 return QualType(T, 0);
963 return Ctx.getSubstTemplateTypeParmType(T->getReplacedParameter(),
967 // FIXME: Non-trivial to implement, but important for C++
968 TRIVIAL_TYPE_CLASS(TemplateSpecialization)
970 QualType VisitAutoType(const AutoType *T) {
972 return QualType(T, 0);
974 QualType deducedType = recurse(T->getDeducedType());
975 if (deducedType.isNull())
978 if (deducedType.getAsOpaquePtr()
979 == T->getDeducedType().getAsOpaquePtr())
980 return QualType(T, 0);
982 return Ctx.getAutoType(deducedType, T->getKeyword(),
983 T->isDependentType());
986 // FIXME: Non-trivial to implement, but important for C++
987 TRIVIAL_TYPE_CLASS(PackExpansion)
989 QualType VisitObjCObjectType(const ObjCObjectType *T) {
990 QualType baseType = recurse(T->getBaseType());
991 if (baseType.isNull())
994 // Transform type arguments.
995 bool typeArgChanged = false;
996 SmallVector<QualType, 4> typeArgs;
997 for (auto typeArg : T->getTypeArgsAsWritten()) {
998 QualType newTypeArg = recurse(typeArg);
999 if (newTypeArg.isNull())
1002 if (newTypeArg.getAsOpaquePtr() != typeArg.getAsOpaquePtr())
1003 typeArgChanged = true;
1005 typeArgs.push_back(newTypeArg);
1008 if (baseType.getAsOpaquePtr() == T->getBaseType().getAsOpaquePtr() &&
1010 return QualType(T, 0);
1012 return Ctx.getObjCObjectType(baseType, typeArgs,
1013 llvm::makeArrayRef(T->qual_begin(),
1014 T->getNumProtocols()),
1015 T->isKindOfTypeAsWritten());
1018 TRIVIAL_TYPE_CLASS(ObjCInterface)
1020 QualType VisitObjCObjectPointerType(const ObjCObjectPointerType *T) {
1021 QualType pointeeType = recurse(T->getPointeeType());
1022 if (pointeeType.isNull())
1025 if (pointeeType.getAsOpaquePtr()
1026 == T->getPointeeType().getAsOpaquePtr())
1027 return QualType(T, 0);
1029 return Ctx.getObjCObjectPointerType(pointeeType);
1032 QualType VisitAtomicType(const AtomicType *T) {
1033 QualType valueType = recurse(T->getValueType());
1034 if (valueType.isNull())
1037 if (valueType.getAsOpaquePtr()
1038 == T->getValueType().getAsOpaquePtr())
1039 return QualType(T, 0);
1041 return Ctx.getAtomicType(valueType);
1044 #undef TRIVIAL_TYPE_CLASS
1047 /// Perform a simple type transformation that does not change the
1048 /// semantics of the type.
1049 template<typename F>
1050 QualType simpleTransform(ASTContext &ctx, QualType type, F &&f) {
1051 // Transform the type. If it changed, return the transformed result.
1052 QualType transformed = f(type);
1053 if (transformed.getAsOpaquePtr() != type.getAsOpaquePtr())
1056 // Split out the qualifiers from the type.
1057 SplitQualType splitType = type.split();
1059 // Visit the type itself.
1060 SimpleTransformVisitor<F> visitor(ctx, std::forward<F>(f));
1061 QualType result = visitor.Visit(splitType.Ty);
1062 if (result.isNull())
1065 // Reconstruct the transformed type by applying the local qualifiers
1066 // from the split type.
1067 return ctx.getQualifiedType(result, splitType.Quals);
1070 } // end anonymous namespace
1072 /// Substitute the given type arguments for Objective-C type
1073 /// parameters within the given type, recursively.
1074 QualType QualType::substObjCTypeArgs(
1076 ArrayRef<QualType> typeArgs,
1077 ObjCSubstitutionContext context) const {
1078 return simpleTransform(ctx, *this,
1079 [&](QualType type) -> QualType {
1080 SplitQualType splitType = type.split();
1082 // Replace an Objective-C type parameter reference with the corresponding
1084 if (const auto *OTPTy = dyn_cast<ObjCTypeParamType>(splitType.Ty)) {
1085 if (auto *typeParam = dyn_cast<ObjCTypeParamDecl>(OTPTy->getDecl())) {
1086 // If we have type arguments, use them.
1087 if (!typeArgs.empty()) {
1088 QualType argType = typeArgs[typeParam->getIndex()];
1089 if (OTPTy->qual_empty())
1090 return ctx.getQualifiedType(argType, splitType.Quals);
1092 // Apply protocol lists if exists.
1094 SmallVector<ObjCProtocolDecl*, 8> protocolsVec;
1095 protocolsVec.append(OTPTy->qual_begin(),
1097 ArrayRef<ObjCProtocolDecl *> protocolsToApply = protocolsVec;
1098 QualType resultTy = ctx.applyObjCProtocolQualifiers(argType,
1099 protocolsToApply, hasError, true/*allowOnPointerType*/);
1101 return ctx.getQualifiedType(resultTy, splitType.Quals);
1105 case ObjCSubstitutionContext::Ordinary:
1106 case ObjCSubstitutionContext::Parameter:
1107 case ObjCSubstitutionContext::Superclass:
1108 // Substitute the bound.
1109 return ctx.getQualifiedType(typeParam->getUnderlyingType(),
1112 case ObjCSubstitutionContext::Result:
1113 case ObjCSubstitutionContext::Property: {
1114 // Substitute the __kindof form of the underlying type.
1115 const auto *objPtr = typeParam->getUnderlyingType()
1116 ->castAs<ObjCObjectPointerType>();
1118 // __kindof types, id, and Class don't need an additional
1120 if (objPtr->isKindOfType() || objPtr->isObjCIdOrClassType())
1121 return ctx.getQualifiedType(typeParam->getUnderlyingType(),
1125 const auto *obj = objPtr->getObjectType();
1126 QualType resultTy = ctx.getObjCObjectType(obj->getBaseType(),
1127 obj->getTypeArgsAsWritten(),
1128 obj->getProtocols(),
1131 // Rebuild object pointer type.
1132 resultTy = ctx.getObjCObjectPointerType(resultTy);
1133 return ctx.getQualifiedType(resultTy, splitType.Quals);
1139 // If we have a function type, update the context appropriately.
1140 if (const auto *funcType = dyn_cast<FunctionType>(splitType.Ty)) {
1141 // Substitute result type.
1142 QualType returnType = funcType->getReturnType().substObjCTypeArgs(
1145 ObjCSubstitutionContext::Result);
1146 if (returnType.isNull())
1149 // Handle non-prototyped functions, which only substitute into the result
1151 if (isa<FunctionNoProtoType>(funcType)) {
1152 // If the return type was unchanged, do nothing.
1153 if (returnType.getAsOpaquePtr()
1154 == funcType->getReturnType().getAsOpaquePtr())
1157 // Otherwise, build a new type.
1158 return ctx.getFunctionNoProtoType(returnType, funcType->getExtInfo());
1161 const auto *funcProtoType = cast<FunctionProtoType>(funcType);
1163 // Transform parameter types.
1164 SmallVector<QualType, 4> paramTypes;
1165 bool paramChanged = false;
1166 for (auto paramType : funcProtoType->getParamTypes()) {
1167 QualType newParamType = paramType.substObjCTypeArgs(
1170 ObjCSubstitutionContext::Parameter);
1171 if (newParamType.isNull())
1174 if (newParamType.getAsOpaquePtr() != paramType.getAsOpaquePtr())
1175 paramChanged = true;
1177 paramTypes.push_back(newParamType);
1180 // Transform extended info.
1181 FunctionProtoType::ExtProtoInfo info = funcProtoType->getExtProtoInfo();
1182 bool exceptionChanged = false;
1183 if (info.ExceptionSpec.Type == EST_Dynamic) {
1184 SmallVector<QualType, 4> exceptionTypes;
1185 for (auto exceptionType : info.ExceptionSpec.Exceptions) {
1186 QualType newExceptionType = exceptionType.substObjCTypeArgs(
1189 ObjCSubstitutionContext::Ordinary);
1190 if (newExceptionType.isNull())
1193 if (newExceptionType.getAsOpaquePtr()
1194 != exceptionType.getAsOpaquePtr())
1195 exceptionChanged = true;
1197 exceptionTypes.push_back(newExceptionType);
1200 if (exceptionChanged) {
1201 info.ExceptionSpec.Exceptions =
1202 llvm::makeArrayRef(exceptionTypes).copy(ctx);
1206 if (returnType.getAsOpaquePtr()
1207 == funcProtoType->getReturnType().getAsOpaquePtr() &&
1208 !paramChanged && !exceptionChanged)
1211 return ctx.getFunctionType(returnType, paramTypes, info);
1214 // Substitute into the type arguments of a specialized Objective-C object
1216 if (const auto *objcObjectType = dyn_cast<ObjCObjectType>(splitType.Ty)) {
1217 if (objcObjectType->isSpecializedAsWritten()) {
1218 SmallVector<QualType, 4> newTypeArgs;
1219 bool anyChanged = false;
1220 for (auto typeArg : objcObjectType->getTypeArgsAsWritten()) {
1221 QualType newTypeArg = typeArg.substObjCTypeArgs(
1223 ObjCSubstitutionContext::Ordinary);
1224 if (newTypeArg.isNull())
1227 if (newTypeArg.getAsOpaquePtr() != typeArg.getAsOpaquePtr()) {
1228 // If we're substituting based on an unspecialized context type,
1229 // produce an unspecialized type.
1230 ArrayRef<ObjCProtocolDecl *> protocols(
1231 objcObjectType->qual_begin(),
1232 objcObjectType->getNumProtocols());
1233 if (typeArgs.empty() &&
1234 context != ObjCSubstitutionContext::Superclass) {
1235 return ctx.getObjCObjectType(
1236 objcObjectType->getBaseType(), { },
1238 objcObjectType->isKindOfTypeAsWritten());
1244 newTypeArgs.push_back(newTypeArg);
1248 ArrayRef<ObjCProtocolDecl *> protocols(
1249 objcObjectType->qual_begin(),
1250 objcObjectType->getNumProtocols());
1251 return ctx.getObjCObjectType(objcObjectType->getBaseType(),
1252 newTypeArgs, protocols,
1253 objcObjectType->isKindOfTypeAsWritten());
1264 QualType QualType::substObjCMemberType(QualType objectType,
1265 const DeclContext *dc,
1266 ObjCSubstitutionContext context) const {
1267 if (auto subs = objectType->getObjCSubstitutions(dc))
1268 return substObjCTypeArgs(dc->getParentASTContext(), *subs, context);
1273 QualType QualType::stripObjCKindOfType(const ASTContext &constCtx) const {
1274 // FIXME: Because ASTContext::getAttributedType() is non-const.
1275 auto &ctx = const_cast<ASTContext &>(constCtx);
1276 return simpleTransform(ctx, *this,
1277 [&](QualType type) -> QualType {
1278 SplitQualType splitType = type.split();
1279 if (auto *objType = splitType.Ty->getAs<ObjCObjectType>()) {
1280 if (!objType->isKindOfType())
1284 = objType->getBaseType().stripObjCKindOfType(ctx);
1285 return ctx.getQualifiedType(
1286 ctx.getObjCObjectType(baseType,
1287 objType->getTypeArgsAsWritten(),
1288 objType->getProtocols(),
1289 /*isKindOf=*/false),
1297 QualType QualType::getAtomicUnqualifiedType() const {
1298 if (auto AT = getTypePtr()->getAs<AtomicType>())
1299 return AT->getValueType().getUnqualifiedType();
1300 return getUnqualifiedType();
1303 Optional<ArrayRef<QualType>> Type::getObjCSubstitutions(
1304 const DeclContext *dc) const {
1305 // Look through method scopes.
1306 if (auto method = dyn_cast<ObjCMethodDecl>(dc))
1307 dc = method->getDeclContext();
1309 // Find the class or category in which the type we're substituting
1311 const ObjCInterfaceDecl *dcClassDecl = dyn_cast<ObjCInterfaceDecl>(dc);
1312 const ObjCCategoryDecl *dcCategoryDecl = nullptr;
1313 ObjCTypeParamList *dcTypeParams = nullptr;
1315 // If the class does not have any type parameters, there's no
1316 // substitution to do.
1317 dcTypeParams = dcClassDecl->getTypeParamList();
1321 // If we are in neither a class nor a category, there's no
1322 // substitution to perform.
1323 dcCategoryDecl = dyn_cast<ObjCCategoryDecl>(dc);
1324 if (!dcCategoryDecl)
1327 // If the category does not have any type parameters, there's no
1328 // substitution to do.
1329 dcTypeParams = dcCategoryDecl->getTypeParamList();
1333 dcClassDecl = dcCategoryDecl->getClassInterface();
1337 assert(dcTypeParams && "No substitutions to perform");
1338 assert(dcClassDecl && "No class context");
1340 // Find the underlying object type.
1341 const ObjCObjectType *objectType;
1342 if (const auto *objectPointerType = getAs<ObjCObjectPointerType>()) {
1343 objectType = objectPointerType->getObjectType();
1344 } else if (getAs<BlockPointerType>()) {
1345 ASTContext &ctx = dc->getParentASTContext();
1346 objectType = ctx.getObjCObjectType(ctx.ObjCBuiltinIdTy, { }, { })
1347 ->castAs<ObjCObjectType>();;
1349 objectType = getAs<ObjCObjectType>();
1352 /// Extract the class from the receiver object type.
1353 ObjCInterfaceDecl *curClassDecl = objectType ? objectType->getInterface()
1355 if (!curClassDecl) {
1356 // If we don't have a context type (e.g., this is "id" or some
1357 // variant thereof), substitute the bounds.
1358 return llvm::ArrayRef<QualType>();
1361 // Follow the superclass chain until we've mapped the receiver type
1362 // to the same class as the context.
1363 while (curClassDecl != dcClassDecl) {
1364 // Map to the superclass type.
1365 QualType superType = objectType->getSuperClassType();
1366 if (superType.isNull()) {
1367 objectType = nullptr;
1371 objectType = superType->castAs<ObjCObjectType>();
1372 curClassDecl = objectType->getInterface();
1375 // If we don't have a receiver type, or the receiver type does not
1376 // have type arguments, substitute in the defaults.
1377 if (!objectType || objectType->isUnspecialized()) {
1378 return llvm::ArrayRef<QualType>();
1381 // The receiver type has the type arguments we want.
1382 return objectType->getTypeArgs();
1385 bool Type::acceptsObjCTypeParams() const {
1386 if (auto *IfaceT = getAsObjCInterfaceType()) {
1387 if (auto *ID = IfaceT->getInterface()) {
1388 if (ID->getTypeParamList())
1396 void ObjCObjectType::computeSuperClassTypeSlow() const {
1397 // Retrieve the class declaration for this type. If there isn't one
1398 // (e.g., this is some variant of "id" or "Class"), then there is no
1400 ObjCInterfaceDecl *classDecl = getInterface();
1402 CachedSuperClassType.setInt(true);
1406 // Extract the superclass type.
1407 const ObjCObjectType *superClassObjTy = classDecl->getSuperClassType();
1408 if (!superClassObjTy) {
1409 CachedSuperClassType.setInt(true);
1413 ObjCInterfaceDecl *superClassDecl = superClassObjTy->getInterface();
1414 if (!superClassDecl) {
1415 CachedSuperClassType.setInt(true);
1419 // If the superclass doesn't have type parameters, then there is no
1420 // substitution to perform.
1421 QualType superClassType(superClassObjTy, 0);
1422 ObjCTypeParamList *superClassTypeParams = superClassDecl->getTypeParamList();
1423 if (!superClassTypeParams) {
1424 CachedSuperClassType.setPointerAndInt(
1425 superClassType->castAs<ObjCObjectType>(), true);
1429 // If the superclass reference is unspecialized, return it.
1430 if (superClassObjTy->isUnspecialized()) {
1431 CachedSuperClassType.setPointerAndInt(superClassObjTy, true);
1435 // If the subclass is not parameterized, there aren't any type
1436 // parameters in the superclass reference to substitute.
1437 ObjCTypeParamList *typeParams = classDecl->getTypeParamList();
1439 CachedSuperClassType.setPointerAndInt(
1440 superClassType->castAs<ObjCObjectType>(), true);
1444 // If the subclass type isn't specialized, return the unspecialized
1446 if (isUnspecialized()) {
1447 QualType unspecializedSuper
1448 = classDecl->getASTContext().getObjCInterfaceType(
1449 superClassObjTy->getInterface());
1450 CachedSuperClassType.setPointerAndInt(
1451 unspecializedSuper->castAs<ObjCObjectType>(),
1456 // Substitute the provided type arguments into the superclass type.
1457 ArrayRef<QualType> typeArgs = getTypeArgs();
1458 assert(typeArgs.size() == typeParams->size());
1459 CachedSuperClassType.setPointerAndInt(
1460 superClassType.substObjCTypeArgs(classDecl->getASTContext(), typeArgs,
1461 ObjCSubstitutionContext::Superclass)
1462 ->castAs<ObjCObjectType>(),
1466 const ObjCInterfaceType *ObjCObjectPointerType::getInterfaceType() const {
1467 if (auto interfaceDecl = getObjectType()->getInterface()) {
1468 return interfaceDecl->getASTContext().getObjCInterfaceType(interfaceDecl)
1469 ->castAs<ObjCInterfaceType>();
1475 QualType ObjCObjectPointerType::getSuperClassType() const {
1476 QualType superObjectType = getObjectType()->getSuperClassType();
1477 if (superObjectType.isNull())
1478 return superObjectType;
1480 ASTContext &ctx = getInterfaceDecl()->getASTContext();
1481 return ctx.getObjCObjectPointerType(superObjectType);
1484 const ObjCObjectType *Type::getAsObjCQualifiedInterfaceType() const {
1485 // There is no sugar for ObjCObjectType's, just return the canonical
1486 // type pointer if it is the right class. There is no typedef information to
1487 // return and these cannot be Address-space qualified.
1488 if (const ObjCObjectType *T = getAs<ObjCObjectType>())
1489 if (T->getNumProtocols() && T->getInterface())
1494 bool Type::isObjCQualifiedInterfaceType() const {
1495 return getAsObjCQualifiedInterfaceType() != nullptr;
1498 const ObjCObjectPointerType *Type::getAsObjCQualifiedIdType() const {
1499 // There is no sugar for ObjCQualifiedIdType's, just return the canonical
1500 // type pointer if it is the right class.
1501 if (const ObjCObjectPointerType *OPT = getAs<ObjCObjectPointerType>()) {
1502 if (OPT->isObjCQualifiedIdType())
1508 const ObjCObjectPointerType *Type::getAsObjCQualifiedClassType() const {
1509 // There is no sugar for ObjCQualifiedClassType's, just return the canonical
1510 // type pointer if it is the right class.
1511 if (const ObjCObjectPointerType *OPT = getAs<ObjCObjectPointerType>()) {
1512 if (OPT->isObjCQualifiedClassType())
1518 const ObjCObjectType *Type::getAsObjCInterfaceType() const {
1519 if (const ObjCObjectType *OT = getAs<ObjCObjectType>()) {
1520 if (OT->getInterface())
1525 const ObjCObjectPointerType *Type::getAsObjCInterfacePointerType() const {
1526 if (const ObjCObjectPointerType *OPT = getAs<ObjCObjectPointerType>()) {
1527 if (OPT->getInterfaceType())
1533 const CXXRecordDecl *Type::getPointeeCXXRecordDecl() const {
1534 QualType PointeeType;
1535 if (const PointerType *PT = getAs<PointerType>())
1536 PointeeType = PT->getPointeeType();
1537 else if (const ReferenceType *RT = getAs<ReferenceType>())
1538 PointeeType = RT->getPointeeType();
1542 if (const RecordType *RT = PointeeType->getAs<RecordType>())
1543 return dyn_cast<CXXRecordDecl>(RT->getDecl());
1548 CXXRecordDecl *Type::getAsCXXRecordDecl() const {
1549 return dyn_cast_or_null<CXXRecordDecl>(getAsTagDecl());
1552 TagDecl *Type::getAsTagDecl() const {
1553 if (const auto *TT = getAs<TagType>())
1554 return cast<TagDecl>(TT->getDecl());
1555 if (const auto *Injected = getAs<InjectedClassNameType>())
1556 return Injected->getDecl();
1562 class GetContainedDeducedTypeVisitor :
1563 public TypeVisitor<GetContainedDeducedTypeVisitor, Type*> {
1566 GetContainedDeducedTypeVisitor(bool Syntactic = false)
1567 : Syntactic(Syntactic) {}
1569 using TypeVisitor<GetContainedDeducedTypeVisitor, Type*>::Visit;
1570 Type *Visit(QualType T) {
1573 return Visit(T.getTypePtr());
1576 // The deduced type itself.
1577 Type *VisitDeducedType(const DeducedType *AT) {
1578 return const_cast<DeducedType*>(AT);
1581 // Only these types can contain the desired 'auto' type.
1582 Type *VisitElaboratedType(const ElaboratedType *T) {
1583 return Visit(T->getNamedType());
1585 Type *VisitPointerType(const PointerType *T) {
1586 return Visit(T->getPointeeType());
1588 Type *VisitBlockPointerType(const BlockPointerType *T) {
1589 return Visit(T->getPointeeType());
1591 Type *VisitReferenceType(const ReferenceType *T) {
1592 return Visit(T->getPointeeTypeAsWritten());
1594 Type *VisitMemberPointerType(const MemberPointerType *T) {
1595 return Visit(T->getPointeeType());
1597 Type *VisitArrayType(const ArrayType *T) {
1598 return Visit(T->getElementType());
1600 Type *VisitDependentSizedExtVectorType(
1601 const DependentSizedExtVectorType *T) {
1602 return Visit(T->getElementType());
1604 Type *VisitVectorType(const VectorType *T) {
1605 return Visit(T->getElementType());
1607 Type *VisitFunctionProtoType(const FunctionProtoType *T) {
1608 if (Syntactic && T->hasTrailingReturn())
1609 return const_cast<FunctionProtoType*>(T);
1610 return VisitFunctionType(T);
1612 Type *VisitFunctionType(const FunctionType *T) {
1613 return Visit(T->getReturnType());
1615 Type *VisitParenType(const ParenType *T) {
1616 return Visit(T->getInnerType());
1618 Type *VisitAttributedType(const AttributedType *T) {
1619 return Visit(T->getModifiedType());
1621 Type *VisitAdjustedType(const AdjustedType *T) {
1622 return Visit(T->getOriginalType());
1627 DeducedType *Type::getContainedDeducedType() const {
1628 return cast_or_null<DeducedType>(
1629 GetContainedDeducedTypeVisitor().Visit(this));
1632 bool Type::hasAutoForTrailingReturnType() const {
1633 return dyn_cast_or_null<FunctionType>(
1634 GetContainedDeducedTypeVisitor(true).Visit(this));
1637 bool Type::hasIntegerRepresentation() const {
1638 if (const VectorType *VT = dyn_cast<VectorType>(CanonicalType))
1639 return VT->getElementType()->isIntegerType();
1641 return isIntegerType();
1644 /// \brief Determine whether this type is an integral type.
1646 /// This routine determines whether the given type is an integral type per
1647 /// C++ [basic.fundamental]p7. Although the C standard does not define the
1648 /// term "integral type", it has a similar term "integer type", and in C++
1649 /// the two terms are equivalent. However, C's "integer type" includes
1650 /// enumeration types, while C++'s "integer type" does not. The \c ASTContext
1651 /// parameter is used to determine whether we should be following the C or
1652 /// C++ rules when determining whether this type is an integral/integer type.
1654 /// For cases where C permits "an integer type" and C++ permits "an integral
1655 /// type", use this routine.
1657 /// For cases where C permits "an integer type" and C++ permits "an integral
1658 /// or enumeration type", use \c isIntegralOrEnumerationType() instead.
1660 /// \param Ctx The context in which this type occurs.
1662 /// \returns true if the type is considered an integral type, false otherwise.
1663 bool Type::isIntegralType(const ASTContext &Ctx) const {
1664 if (const BuiltinType *BT = dyn_cast<BuiltinType>(CanonicalType))
1665 return BT->getKind() >= BuiltinType::Bool &&
1666 BT->getKind() <= BuiltinType::Int128;
1668 // Complete enum types are integral in C.
1669 if (!Ctx.getLangOpts().CPlusPlus)
1670 if (const EnumType *ET = dyn_cast<EnumType>(CanonicalType))
1671 return ET->getDecl()->isComplete();
1677 bool Type::isIntegralOrUnscopedEnumerationType() const {
1678 if (const BuiltinType *BT = dyn_cast<BuiltinType>(CanonicalType))
1679 return BT->getKind() >= BuiltinType::Bool &&
1680 BT->getKind() <= BuiltinType::Int128;
1682 // Check for a complete enum type; incomplete enum types are not properly an
1683 // enumeration type in the sense required here.
1684 // C++0x: However, if the underlying type of the enum is fixed, it is
1685 // considered complete.
1686 if (const EnumType *ET = dyn_cast<EnumType>(CanonicalType))
1687 return ET->getDecl()->isComplete() && !ET->getDecl()->isScoped();
1694 bool Type::isCharType() const {
1695 if (const BuiltinType *BT = dyn_cast<BuiltinType>(CanonicalType))
1696 return BT->getKind() == BuiltinType::Char_U ||
1697 BT->getKind() == BuiltinType::UChar ||
1698 BT->getKind() == BuiltinType::Char_S ||
1699 BT->getKind() == BuiltinType::SChar;
1703 bool Type::isWideCharType() const {
1704 if (const BuiltinType *BT = dyn_cast<BuiltinType>(CanonicalType))
1705 return BT->getKind() == BuiltinType::WChar_S ||
1706 BT->getKind() == BuiltinType::WChar_U;
1710 bool Type::isChar16Type() const {
1711 if (const BuiltinType *BT = dyn_cast<BuiltinType>(CanonicalType))
1712 return BT->getKind() == BuiltinType::Char16;
1716 bool Type::isChar32Type() const {
1717 if (const BuiltinType *BT = dyn_cast<BuiltinType>(CanonicalType))
1718 return BT->getKind() == BuiltinType::Char32;
1722 /// \brief Determine whether this type is any of the built-in character
1724 bool Type::isAnyCharacterType() const {
1725 const BuiltinType *BT = dyn_cast<BuiltinType>(CanonicalType);
1726 if (!BT) return false;
1727 switch (BT->getKind()) {
1728 default: return false;
1729 case BuiltinType::Char_U:
1730 case BuiltinType::UChar:
1731 case BuiltinType::WChar_U:
1732 case BuiltinType::Char16:
1733 case BuiltinType::Char32:
1734 case BuiltinType::Char_S:
1735 case BuiltinType::SChar:
1736 case BuiltinType::WChar_S:
1741 /// isSignedIntegerType - Return true if this is an integer type that is
1742 /// signed, according to C99 6.2.5p4 [char, signed char, short, int, long..],
1743 /// an enum decl which has a signed representation
1744 bool Type::isSignedIntegerType() const {
1745 if (const BuiltinType *BT = dyn_cast<BuiltinType>(CanonicalType)) {
1746 return BT->getKind() >= BuiltinType::Char_S &&
1747 BT->getKind() <= BuiltinType::Int128;
1750 if (const EnumType *ET = dyn_cast<EnumType>(CanonicalType)) {
1751 // Incomplete enum types are not treated as integer types.
1752 // FIXME: In C++, enum types are never integer types.
1753 if (ET->getDecl()->isComplete() && !ET->getDecl()->isScoped())
1754 return ET->getDecl()->getIntegerType()->isSignedIntegerType();
1760 bool Type::isSignedIntegerOrEnumerationType() const {
1761 if (const BuiltinType *BT = dyn_cast<BuiltinType>(CanonicalType)) {
1762 return BT->getKind() >= BuiltinType::Char_S &&
1763 BT->getKind() <= BuiltinType::Int128;
1766 if (const EnumType *ET = dyn_cast<EnumType>(CanonicalType)) {
1767 if (ET->getDecl()->isComplete())
1768 return ET->getDecl()->getIntegerType()->isSignedIntegerType();
1774 bool Type::hasSignedIntegerRepresentation() const {
1775 if (const VectorType *VT = dyn_cast<VectorType>(CanonicalType))
1776 return VT->getElementType()->isSignedIntegerOrEnumerationType();
1778 return isSignedIntegerOrEnumerationType();
1781 /// isUnsignedIntegerType - Return true if this is an integer type that is
1782 /// unsigned, according to C99 6.2.5p6 [which returns true for _Bool], an enum
1783 /// decl which has an unsigned representation
1784 bool Type::isUnsignedIntegerType() const {
1785 if (const BuiltinType *BT = dyn_cast<BuiltinType>(CanonicalType)) {
1786 return BT->getKind() >= BuiltinType::Bool &&
1787 BT->getKind() <= BuiltinType::UInt128;
1790 if (const EnumType *ET = dyn_cast<EnumType>(CanonicalType)) {
1791 // Incomplete enum types are not treated as integer types.
1792 // FIXME: In C++, enum types are never integer types.
1793 if (ET->getDecl()->isComplete() && !ET->getDecl()->isScoped())
1794 return ET->getDecl()->getIntegerType()->isUnsignedIntegerType();
1800 bool Type::isUnsignedIntegerOrEnumerationType() const {
1801 if (const BuiltinType *BT = dyn_cast<BuiltinType>(CanonicalType)) {
1802 return BT->getKind() >= BuiltinType::Bool &&
1803 BT->getKind() <= BuiltinType::UInt128;
1806 if (const EnumType *ET = dyn_cast<EnumType>(CanonicalType)) {
1807 if (ET->getDecl()->isComplete())
1808 return ET->getDecl()->getIntegerType()->isUnsignedIntegerType();
1814 bool Type::hasUnsignedIntegerRepresentation() const {
1815 if (const VectorType *VT = dyn_cast<VectorType>(CanonicalType))
1816 return VT->getElementType()->isUnsignedIntegerOrEnumerationType();
1818 return isUnsignedIntegerOrEnumerationType();
1821 bool Type::isFloatingType() const {
1822 if (const BuiltinType *BT = dyn_cast<BuiltinType>(CanonicalType))
1823 return BT->getKind() >= BuiltinType::Half &&
1824 BT->getKind() <= BuiltinType::Float128;
1825 if (const ComplexType *CT = dyn_cast<ComplexType>(CanonicalType))
1826 return CT->getElementType()->isFloatingType();
1830 bool Type::hasFloatingRepresentation() const {
1831 if (const VectorType *VT = dyn_cast<VectorType>(CanonicalType))
1832 return VT->getElementType()->isFloatingType();
1834 return isFloatingType();
1837 bool Type::isRealFloatingType() const {
1838 if (const BuiltinType *BT = dyn_cast<BuiltinType>(CanonicalType))
1839 return BT->isFloatingPoint();
1843 bool Type::isRealType() const {
1844 if (const BuiltinType *BT = dyn_cast<BuiltinType>(CanonicalType))
1845 return BT->getKind() >= BuiltinType::Bool &&
1846 BT->getKind() <= BuiltinType::Float128;
1847 if (const EnumType *ET = dyn_cast<EnumType>(CanonicalType))
1848 return ET->getDecl()->isComplete() && !ET->getDecl()->isScoped();
1852 bool Type::isArithmeticType() const {
1853 if (const BuiltinType *BT = dyn_cast<BuiltinType>(CanonicalType))
1854 return BT->getKind() >= BuiltinType::Bool &&
1855 BT->getKind() <= BuiltinType::Float128;
1856 if (const EnumType *ET = dyn_cast<EnumType>(CanonicalType))
1857 // GCC allows forward declaration of enum types (forbid by C99 6.7.2.3p2).
1858 // If a body isn't seen by the time we get here, return false.
1860 // C++0x: Enumerations are not arithmetic types. For now, just return
1861 // false for scoped enumerations since that will disable any
1862 // unwanted implicit conversions.
1863 return !ET->getDecl()->isScoped() && ET->getDecl()->isComplete();
1864 return isa<ComplexType>(CanonicalType);
1867 Type::ScalarTypeKind Type::getScalarTypeKind() const {
1868 assert(isScalarType());
1870 const Type *T = CanonicalType.getTypePtr();
1871 if (const BuiltinType *BT = dyn_cast<BuiltinType>(T)) {
1872 if (BT->getKind() == BuiltinType::Bool) return STK_Bool;
1873 if (BT->getKind() == BuiltinType::NullPtr) return STK_CPointer;
1874 if (BT->isInteger()) return STK_Integral;
1875 if (BT->isFloatingPoint()) return STK_Floating;
1876 llvm_unreachable("unknown scalar builtin type");
1877 } else if (isa<PointerType>(T)) {
1878 return STK_CPointer;
1879 } else if (isa<BlockPointerType>(T)) {
1880 return STK_BlockPointer;
1881 } else if (isa<ObjCObjectPointerType>(T)) {
1882 return STK_ObjCObjectPointer;
1883 } else if (isa<MemberPointerType>(T)) {
1884 return STK_MemberPointer;
1885 } else if (isa<EnumType>(T)) {
1886 assert(cast<EnumType>(T)->getDecl()->isComplete());
1887 return STK_Integral;
1888 } else if (const ComplexType *CT = dyn_cast<ComplexType>(T)) {
1889 if (CT->getElementType()->isRealFloatingType())
1890 return STK_FloatingComplex;
1891 return STK_IntegralComplex;
1894 llvm_unreachable("unknown scalar type");
1897 /// \brief Determines whether the type is a C++ aggregate type or C
1898 /// aggregate or union type.
1900 /// An aggregate type is an array or a class type (struct, union, or
1901 /// class) that has no user-declared constructors, no private or
1902 /// protected non-static data members, no base classes, and no virtual
1903 /// functions (C++ [dcl.init.aggr]p1). The notion of an aggregate type
1904 /// subsumes the notion of C aggregates (C99 6.2.5p21) because it also
1905 /// includes union types.
1906 bool Type::isAggregateType() const {
1907 if (const RecordType *Record = dyn_cast<RecordType>(CanonicalType)) {
1908 if (CXXRecordDecl *ClassDecl = dyn_cast<CXXRecordDecl>(Record->getDecl()))
1909 return ClassDecl->isAggregate();
1914 return isa<ArrayType>(CanonicalType);
1917 /// isConstantSizeType - Return true if this is not a variable sized type,
1918 /// according to the rules of C99 6.7.5p3. It is not legal to call this on
1919 /// incomplete types or dependent types.
1920 bool Type::isConstantSizeType() const {
1921 assert(!isIncompleteType() && "This doesn't make sense for incomplete types");
1922 assert(!isDependentType() && "This doesn't make sense for dependent types");
1923 // The VAT must have a size, as it is known to be complete.
1924 return !isa<VariableArrayType>(CanonicalType);
1927 /// isIncompleteType - Return true if this is an incomplete type (C99 6.2.5p1)
1928 /// - a type that can describe objects, but which lacks information needed to
1929 /// determine its size.
1930 bool Type::isIncompleteType(NamedDecl **Def) const {
1934 switch (CanonicalType->getTypeClass()) {
1935 default: return false;
1937 // Void is the only incomplete builtin type. Per C99 6.2.5p19, it can never
1939 return isVoidType();
1941 EnumDecl *EnumD = cast<EnumType>(CanonicalType)->getDecl();
1945 // An enumeration with fixed underlying type is complete (C++0x 7.2p3).
1946 if (EnumD->isFixed())
1949 return !EnumD->isCompleteDefinition();
1952 // A tagged type (struct/union/enum/class) is incomplete if the decl is a
1953 // forward declaration, but not a full definition (C99 6.2.5p22).
1954 RecordDecl *Rec = cast<RecordType>(CanonicalType)->getDecl();
1957 return !Rec->isCompleteDefinition();
1960 // An array is incomplete if its element type is incomplete
1961 // (C++ [dcl.array]p1).
1962 // We don't handle variable arrays (they're not allowed in C++) or
1963 // dependent-sized arrays (dependent types are never treated as incomplete).
1964 return cast<ArrayType>(CanonicalType)->getElementType()
1965 ->isIncompleteType(Def);
1966 case IncompleteArray:
1967 // An array of unknown size is an incomplete type (C99 6.2.5p22).
1969 case MemberPointer: {
1970 // Member pointers in the MS ABI have special behavior in
1971 // RequireCompleteType: they attach a MSInheritanceAttr to the CXXRecordDecl
1972 // to indicate which inheritance model to use.
1973 auto *MPTy = cast<MemberPointerType>(CanonicalType);
1974 const Type *ClassTy = MPTy->getClass();
1975 // Member pointers with dependent class types don't get special treatment.
1976 if (ClassTy->isDependentType())
1978 const CXXRecordDecl *RD = ClassTy->getAsCXXRecordDecl();
1979 ASTContext &Context = RD->getASTContext();
1980 // Member pointers not in the MS ABI don't get special treatment.
1981 if (!Context.getTargetInfo().getCXXABI().isMicrosoft())
1983 // The inheritance attribute might only be present on the most recent
1984 // CXXRecordDecl, use that one.
1985 RD = RD->getMostRecentDecl();
1986 // Nothing interesting to do if the inheritance attribute is already set.
1987 if (RD->hasAttr<MSInheritanceAttr>())
1992 return cast<ObjCObjectType>(CanonicalType)->getBaseType()
1993 ->isIncompleteType(Def);
1994 case ObjCInterface: {
1995 // ObjC interfaces are incomplete if they are @class, not @interface.
1996 ObjCInterfaceDecl *Interface
1997 = cast<ObjCInterfaceType>(CanonicalType)->getDecl();
2000 return !Interface->hasDefinition();
2005 bool QualType::isPODType(const ASTContext &Context) const {
2006 // C++11 has a more relaxed definition of POD.
2007 if (Context.getLangOpts().CPlusPlus11)
2008 return isCXX11PODType(Context);
2010 return isCXX98PODType(Context);
2013 bool QualType::isCXX98PODType(const ASTContext &Context) const {
2014 // The compiler shouldn't query this for incomplete types, but the user might.
2015 // We return false for that case. Except for incomplete arrays of PODs, which
2016 // are PODs according to the standard.
2020 if ((*this)->isIncompleteArrayType())
2021 return Context.getBaseElementType(*this).isCXX98PODType(Context);
2023 if ((*this)->isIncompleteType())
2026 if (hasNonTrivialObjCLifetime())
2029 QualType CanonicalType = getTypePtr()->CanonicalType;
2030 switch (CanonicalType->getTypeClass()) {
2031 // Everything not explicitly mentioned is not POD.
2032 default: return false;
2033 case Type::VariableArray:
2034 case Type::ConstantArray:
2035 // IncompleteArray is handled above.
2036 return Context.getBaseElementType(*this).isCXX98PODType(Context);
2038 case Type::ObjCObjectPointer:
2039 case Type::BlockPointer:
2043 case Type::MemberPointer:
2045 case Type::ExtVector:
2052 if (CXXRecordDecl *ClassDecl
2053 = dyn_cast<CXXRecordDecl>(cast<RecordType>(CanonicalType)->getDecl()))
2054 return ClassDecl->isPOD();
2056 // C struct/union is POD.
2061 bool QualType::isTrivialType(const ASTContext &Context) const {
2062 // The compiler shouldn't query this for incomplete types, but the user might.
2063 // We return false for that case. Except for incomplete arrays of PODs, which
2064 // are PODs according to the standard.
2068 if ((*this)->isArrayType())
2069 return Context.getBaseElementType(*this).isTrivialType(Context);
2071 // Return false for incomplete types after skipping any incomplete array
2072 // types which are expressly allowed by the standard and thus our API.
2073 if ((*this)->isIncompleteType())
2076 if (hasNonTrivialObjCLifetime())
2079 QualType CanonicalType = getTypePtr()->CanonicalType;
2080 if (CanonicalType->isDependentType())
2083 // C++0x [basic.types]p9:
2084 // Scalar types, trivial class types, arrays of such types, and
2085 // cv-qualified versions of these types are collectively called trivial
2088 // As an extension, Clang treats vector types as Scalar types.
2089 if (CanonicalType->isScalarType() || CanonicalType->isVectorType())
2091 if (const RecordType *RT = CanonicalType->getAs<RecordType>()) {
2092 if (const CXXRecordDecl *ClassDecl =
2093 dyn_cast<CXXRecordDecl>(RT->getDecl())) {
2095 // A trivial class is a class that has a default constructor,
2096 // has no non-trivial default constructors, and is trivially
2098 return ClassDecl->hasDefaultConstructor() &&
2099 !ClassDecl->hasNonTrivialDefaultConstructor() &&
2100 ClassDecl->isTriviallyCopyable();
2106 // No other types can match.
2110 bool QualType::isTriviallyCopyableType(const ASTContext &Context) const {
2111 if ((*this)->isArrayType())
2112 return Context.getBaseElementType(*this).isTriviallyCopyableType(Context);
2114 if (hasNonTrivialObjCLifetime())
2117 // C++11 [basic.types]p9
2118 // Scalar types, trivially copyable class types, arrays of such types, and
2119 // non-volatile const-qualified versions of these types are collectively
2120 // called trivially copyable types.
2122 QualType CanonicalType = getCanonicalType();
2123 if (CanonicalType->isDependentType())
2126 if (CanonicalType.isVolatileQualified())
2129 // Return false for incomplete types after skipping any incomplete array types
2130 // which are expressly allowed by the standard and thus our API.
2131 if (CanonicalType->isIncompleteType())
2134 // As an extension, Clang treats vector types as Scalar types.
2135 if (CanonicalType->isScalarType() || CanonicalType->isVectorType())
2138 if (const RecordType *RT = CanonicalType->getAs<RecordType>()) {
2139 if (const CXXRecordDecl *ClassDecl =
2140 dyn_cast<CXXRecordDecl>(RT->getDecl())) {
2141 if (!ClassDecl->isTriviallyCopyable()) return false;
2147 // No other types can match.
2151 bool QualType::isNonWeakInMRRWithObjCWeak(const ASTContext &Context) const {
2152 return !Context.getLangOpts().ObjCAutoRefCount &&
2153 Context.getLangOpts().ObjCWeak &&
2154 getObjCLifetime() != Qualifiers::OCL_Weak;
2157 bool Type::isLiteralType(const ASTContext &Ctx) const {
2158 if (isDependentType())
2161 // C++1y [basic.types]p10:
2162 // A type is a literal type if it is:
2164 if (Ctx.getLangOpts().CPlusPlus14 && isVoidType())
2167 // C++11 [basic.types]p10:
2168 // A type is a literal type if it is:
2170 // -- an array of literal type other than an array of runtime bound; or
2171 if (isVariableArrayType())
2173 const Type *BaseTy = getBaseElementTypeUnsafe();
2174 assert(BaseTy && "NULL element type");
2176 // Return false for incomplete types after skipping any incomplete array
2177 // types; those are expressly allowed by the standard and thus our API.
2178 if (BaseTy->isIncompleteType())
2181 // C++11 [basic.types]p10:
2182 // A type is a literal type if it is:
2183 // -- a scalar type; or
2184 // As an extension, Clang treats vector types and complex types as
2186 if (BaseTy->isScalarType() || BaseTy->isVectorType() ||
2187 BaseTy->isAnyComplexType())
2189 // -- a reference type; or
2190 if (BaseTy->isReferenceType())
2192 // -- a class type that has all of the following properties:
2193 if (const RecordType *RT = BaseTy->getAs<RecordType>()) {
2194 // -- a trivial destructor,
2195 // -- every constructor call and full-expression in the
2196 // brace-or-equal-initializers for non-static data members (if any)
2197 // is a constant expression,
2198 // -- it is an aggregate type or has at least one constexpr
2199 // constructor or constructor template that is not a copy or move
2201 // -- all non-static data members and base classes of literal types
2203 // We resolve DR1361 by ignoring the second bullet.
2204 if (const CXXRecordDecl *ClassDecl =
2205 dyn_cast<CXXRecordDecl>(RT->getDecl()))
2206 return ClassDecl->isLiteral();
2211 // We treat _Atomic T as a literal type if T is a literal type.
2212 if (const AtomicType *AT = BaseTy->getAs<AtomicType>())
2213 return AT->getValueType()->isLiteralType(Ctx);
2215 // If this type hasn't been deduced yet, then conservatively assume that
2216 // it'll work out to be a literal type.
2217 if (isa<AutoType>(BaseTy->getCanonicalTypeInternal()))
2223 bool Type::isStandardLayoutType() const {
2224 if (isDependentType())
2227 // C++0x [basic.types]p9:
2228 // Scalar types, standard-layout class types, arrays of such types, and
2229 // cv-qualified versions of these types are collectively called
2230 // standard-layout types.
2231 const Type *BaseTy = getBaseElementTypeUnsafe();
2232 assert(BaseTy && "NULL element type");
2234 // Return false for incomplete types after skipping any incomplete array
2235 // types which are expressly allowed by the standard and thus our API.
2236 if (BaseTy->isIncompleteType())
2239 // As an extension, Clang treats vector types as Scalar types.
2240 if (BaseTy->isScalarType() || BaseTy->isVectorType()) return true;
2241 if (const RecordType *RT = BaseTy->getAs<RecordType>()) {
2242 if (const CXXRecordDecl *ClassDecl =
2243 dyn_cast<CXXRecordDecl>(RT->getDecl()))
2244 if (!ClassDecl->isStandardLayout())
2247 // Default to 'true' for non-C++ class types.
2248 // FIXME: This is a bit dubious, but plain C structs should trivially meet
2249 // all the requirements of standard layout classes.
2253 // No other types can match.
2257 // This is effectively the intersection of isTrivialType and
2258 // isStandardLayoutType. We implement it directly to avoid redundant
2259 // conversions from a type to a CXXRecordDecl.
2260 bool QualType::isCXX11PODType(const ASTContext &Context) const {
2261 const Type *ty = getTypePtr();
2262 if (ty->isDependentType())
2265 if (hasNonTrivialObjCLifetime())
2268 // C++11 [basic.types]p9:
2269 // Scalar types, POD classes, arrays of such types, and cv-qualified
2270 // versions of these types are collectively called trivial types.
2271 const Type *BaseTy = ty->getBaseElementTypeUnsafe();
2272 assert(BaseTy && "NULL element type");
2274 // Return false for incomplete types after skipping any incomplete array
2275 // types which are expressly allowed by the standard and thus our API.
2276 if (BaseTy->isIncompleteType())
2279 // As an extension, Clang treats vector types as Scalar types.
2280 if (BaseTy->isScalarType() || BaseTy->isVectorType()) return true;
2281 if (const RecordType *RT = BaseTy->getAs<RecordType>()) {
2282 if (const CXXRecordDecl *ClassDecl =
2283 dyn_cast<CXXRecordDecl>(RT->getDecl())) {
2284 // C++11 [class]p10:
2285 // A POD struct is a non-union class that is both a trivial class [...]
2286 if (!ClassDecl->isTrivial()) return false;
2288 // C++11 [class]p10:
2289 // A POD struct is a non-union class that is both a trivial class and
2290 // a standard-layout class [...]
2291 if (!ClassDecl->isStandardLayout()) return false;
2293 // C++11 [class]p10:
2294 // A POD struct is a non-union class that is both a trivial class and
2295 // a standard-layout class, and has no non-static data members of type
2296 // non-POD struct, non-POD union (or array of such types). [...]
2298 // We don't directly query the recursive aspect as the requirements for
2299 // both standard-layout classes and trivial classes apply recursively
2306 // No other types can match.
2310 bool Type::isAlignValT() const {
2311 if (auto *ET = getAs<EnumType>()) {
2312 auto *II = ET->getDecl()->getIdentifier();
2313 if (II && II->isStr("align_val_t") && ET->getDecl()->isInStdNamespace())
2319 bool Type::isPromotableIntegerType() const {
2320 if (const BuiltinType *BT = getAs<BuiltinType>())
2321 switch (BT->getKind()) {
2322 case BuiltinType::Bool:
2323 case BuiltinType::Char_S:
2324 case BuiltinType::Char_U:
2325 case BuiltinType::SChar:
2326 case BuiltinType::UChar:
2327 case BuiltinType::Short:
2328 case BuiltinType::UShort:
2329 case BuiltinType::WChar_S:
2330 case BuiltinType::WChar_U:
2331 case BuiltinType::Char16:
2332 case BuiltinType::Char32:
2338 // Enumerated types are promotable to their compatible integer types
2339 // (C99 6.3.1.1) a.k.a. its underlying type (C++ [conv.prom]p2).
2340 if (const EnumType *ET = getAs<EnumType>()){
2341 if (this->isDependentType() || ET->getDecl()->getPromotionType().isNull()
2342 || ET->getDecl()->isScoped())
2351 bool Type::isSpecifierType() const {
2352 // Note that this intentionally does not use the canonical type.
2353 switch (getTypeClass()) {
2361 case TemplateTypeParm:
2362 case SubstTemplateTypeParm:
2363 case TemplateSpecialization:
2366 case DependentTemplateSpecialization:
2369 case ObjCObjectPointer: // FIXME: object pointers aren't really specifiers
2376 ElaboratedTypeKeyword
2377 TypeWithKeyword::getKeywordForTypeSpec(unsigned TypeSpec) {
2379 default: return ETK_None;
2380 case TST_typename: return ETK_Typename;
2381 case TST_class: return ETK_Class;
2382 case TST_struct: return ETK_Struct;
2383 case TST_interface: return ETK_Interface;
2384 case TST_union: return ETK_Union;
2385 case TST_enum: return ETK_Enum;
2390 TypeWithKeyword::getTagTypeKindForTypeSpec(unsigned TypeSpec) {
2392 case TST_class: return TTK_Class;
2393 case TST_struct: return TTK_Struct;
2394 case TST_interface: return TTK_Interface;
2395 case TST_union: return TTK_Union;
2396 case TST_enum: return TTK_Enum;
2399 llvm_unreachable("Type specifier is not a tag type kind.");
2402 ElaboratedTypeKeyword
2403 TypeWithKeyword::getKeywordForTagTypeKind(TagTypeKind Kind) {
2405 case TTK_Class: return ETK_Class;
2406 case TTK_Struct: return ETK_Struct;
2407 case TTK_Interface: return ETK_Interface;
2408 case TTK_Union: return ETK_Union;
2409 case TTK_Enum: return ETK_Enum;
2411 llvm_unreachable("Unknown tag type kind.");
2415 TypeWithKeyword::getTagTypeKindForKeyword(ElaboratedTypeKeyword Keyword) {
2417 case ETK_Class: return TTK_Class;
2418 case ETK_Struct: return TTK_Struct;
2419 case ETK_Interface: return TTK_Interface;
2420 case ETK_Union: return TTK_Union;
2421 case ETK_Enum: return TTK_Enum;
2422 case ETK_None: // Fall through.
2424 llvm_unreachable("Elaborated type keyword is not a tag type kind.");
2426 llvm_unreachable("Unknown elaborated type keyword.");
2430 TypeWithKeyword::KeywordIsTagTypeKind(ElaboratedTypeKeyword Keyword) {
2442 llvm_unreachable("Unknown elaborated type keyword.");
2445 StringRef TypeWithKeyword::getKeywordName(ElaboratedTypeKeyword Keyword) {
2447 case ETK_None: return "";
2448 case ETK_Typename: return "typename";
2449 case ETK_Class: return "class";
2450 case ETK_Struct: return "struct";
2451 case ETK_Interface: return "__interface";
2452 case ETK_Union: return "union";
2453 case ETK_Enum: return "enum";
2456 llvm_unreachable("Unknown elaborated type keyword.");
2459 DependentTemplateSpecializationType::DependentTemplateSpecializationType(
2460 ElaboratedTypeKeyword Keyword,
2461 NestedNameSpecifier *NNS, const IdentifierInfo *Name,
2462 ArrayRef<TemplateArgument> Args,
2464 : TypeWithKeyword(Keyword, DependentTemplateSpecialization, Canon, true, true,
2465 /*VariablyModified=*/false,
2466 NNS && NNS->containsUnexpandedParameterPack()),
2467 NNS(NNS), Name(Name), NumArgs(Args.size()) {
2468 assert((!NNS || NNS->isDependent()) &&
2469 "DependentTemplateSpecializatonType requires dependent qualifier");
2470 TemplateArgument *ArgBuffer = getArgBuffer();
2471 for (const TemplateArgument &Arg : Args) {
2472 if (Arg.containsUnexpandedParameterPack())
2473 setContainsUnexpandedParameterPack();
2475 new (ArgBuffer++) TemplateArgument(Arg);
2480 DependentTemplateSpecializationType::Profile(llvm::FoldingSetNodeID &ID,
2481 const ASTContext &Context,
2482 ElaboratedTypeKeyword Keyword,
2483 NestedNameSpecifier *Qualifier,
2484 const IdentifierInfo *Name,
2485 ArrayRef<TemplateArgument> Args) {
2486 ID.AddInteger(Keyword);
2487 ID.AddPointer(Qualifier);
2488 ID.AddPointer(Name);
2489 for (const TemplateArgument &Arg : Args)
2490 Arg.Profile(ID, Context);
2493 bool Type::isElaboratedTypeSpecifier() const {
2494 ElaboratedTypeKeyword Keyword;
2495 if (const ElaboratedType *Elab = dyn_cast<ElaboratedType>(this))
2496 Keyword = Elab->getKeyword();
2497 else if (const DependentNameType *DepName = dyn_cast<DependentNameType>(this))
2498 Keyword = DepName->getKeyword();
2499 else if (const DependentTemplateSpecializationType *DepTST =
2500 dyn_cast<DependentTemplateSpecializationType>(this))
2501 Keyword = DepTST->getKeyword();
2505 return TypeWithKeyword::KeywordIsTagTypeKind(Keyword);
2508 const char *Type::getTypeClassName() const {
2509 switch (TypeBits.TC) {
2510 #define ABSTRACT_TYPE(Derived, Base)
2511 #define TYPE(Derived, Base) case Derived: return #Derived;
2512 #include "clang/AST/TypeNodes.def"
2515 llvm_unreachable("Invalid type class.");
2518 StringRef BuiltinType::getName(const PrintingPolicy &Policy) const {
2519 switch (getKind()) {
2523 return Policy.Bool ? "bool" : "_Bool";
2529 return "signed char";
2541 return "unsigned char";
2543 return "unsigned short";
2545 return "unsigned int";
2547 return "unsigned long";
2549 return "unsigned long long";
2551 return "unsigned __int128";
2553 return Policy.Half ? "half" : "__fp16";
2559 return "long double";
2561 return "__float128";
2564 return Policy.MSWChar ? "__wchar_t" : "wchar_t";
2572 return "<overloaded function type>";
2574 return "<bound member function type>";
2576 return "<pseudo-object type>";
2578 return "<dependent type>";
2580 return "<unknown type>";
2581 case ARCUnbridgedCast:
2582 return "<ARC unbridged cast type>";
2584 return "<builtin fn type>";
2591 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
2593 return "__" #Access " " #ImgType "_t";
2594 #include "clang/Basic/OpenCLImageTypes.def"
2600 return "clk_event_t";
2604 return "reserve_id_t";
2605 case OMPArraySection:
2606 return "<OpenMP array section type>";
2609 llvm_unreachable("Invalid builtin type.");
2612 QualType QualType::getNonLValueExprType(const ASTContext &Context) const {
2613 if (const ReferenceType *RefType = getTypePtr()->getAs<ReferenceType>())
2614 return RefType->getPointeeType();
2616 // C++0x [basic.lval]:
2617 // Class prvalues can have cv-qualified types; non-class prvalues always
2618 // have cv-unqualified types.
2620 // See also C99 6.3.2.1p2.
2621 if (!Context.getLangOpts().CPlusPlus ||
2622 (!getTypePtr()->isDependentType() && !getTypePtr()->isRecordType()))
2623 return getUnqualifiedType();
2628 StringRef FunctionType::getNameForCallConv(CallingConv CC) {
2630 case CC_C: return "cdecl";
2631 case CC_X86StdCall: return "stdcall";
2632 case CC_X86FastCall: return "fastcall";
2633 case CC_X86ThisCall: return "thiscall";
2634 case CC_X86Pascal: return "pascal";
2635 case CC_X86VectorCall: return "vectorcall";
2636 case CC_X86_64Win64: return "ms_abi";
2637 case CC_X86_64SysV: return "sysv_abi";
2638 case CC_X86RegCall : return "regcall";
2639 case CC_AAPCS: return "aapcs";
2640 case CC_AAPCS_VFP: return "aapcs-vfp";
2641 case CC_IntelOclBicc: return "intel_ocl_bicc";
2642 case CC_SpirFunction: return "spir_function";
2643 case CC_OpenCLKernel: return "opencl_kernel";
2644 case CC_Swift: return "swiftcall";
2645 case CC_PreserveMost: return "preserve_most";
2646 case CC_PreserveAll: return "preserve_all";
2649 llvm_unreachable("Invalid calling convention.");
2652 FunctionProtoType::FunctionProtoType(QualType result, ArrayRef<QualType> params,
2654 const ExtProtoInfo &epi)
2655 : FunctionType(FunctionProto, result, canonical,
2656 result->isDependentType(),
2657 result->isInstantiationDependentType(),
2658 result->isVariablyModifiedType(),
2659 result->containsUnexpandedParameterPack(), epi.ExtInfo),
2660 NumParams(params.size()),
2661 NumExceptions(epi.ExceptionSpec.Exceptions.size()),
2662 ExceptionSpecType(epi.ExceptionSpec.Type),
2663 HasExtParameterInfos(epi.ExtParameterInfos != nullptr),
2664 Variadic(epi.Variadic), HasTrailingReturn(epi.HasTrailingReturn) {
2665 assert(NumParams == params.size() && "function has too many parameters");
2667 FunctionTypeBits.TypeQuals = epi.TypeQuals;
2668 FunctionTypeBits.RefQualifier = epi.RefQualifier;
2670 // Fill in the trailing argument array.
2671 QualType *argSlot = reinterpret_cast<QualType*>(this+1);
2672 for (unsigned i = 0; i != NumParams; ++i) {
2673 if (params[i]->isDependentType())
2675 else if (params[i]->isInstantiationDependentType())
2676 setInstantiationDependent();
2678 if (params[i]->containsUnexpandedParameterPack())
2679 setContainsUnexpandedParameterPack();
2681 argSlot[i] = params[i];
2684 if (getExceptionSpecType() == EST_Dynamic) {
2685 // Fill in the exception array.
2686 QualType *exnSlot = argSlot + NumParams;
2688 for (QualType ExceptionType : epi.ExceptionSpec.Exceptions) {
2689 // Note that, before C++17, a dependent exception specification does
2690 // *not* make a type dependent; it's not even part of the C++ type
2692 if (ExceptionType->isInstantiationDependentType())
2693 setInstantiationDependent();
2695 if (ExceptionType->containsUnexpandedParameterPack())
2696 setContainsUnexpandedParameterPack();
2698 exnSlot[I++] = ExceptionType;
2700 } else if (getExceptionSpecType() == EST_ComputedNoexcept) {
2701 // Store the noexcept expression and context.
2702 Expr **noexSlot = reinterpret_cast<Expr **>(argSlot + NumParams);
2703 *noexSlot = epi.ExceptionSpec.NoexceptExpr;
2705 if (epi.ExceptionSpec.NoexceptExpr) {
2706 if (epi.ExceptionSpec.NoexceptExpr->isValueDependent() ||
2707 epi.ExceptionSpec.NoexceptExpr->isInstantiationDependent())
2708 setInstantiationDependent();
2710 if (epi.ExceptionSpec.NoexceptExpr->containsUnexpandedParameterPack())
2711 setContainsUnexpandedParameterPack();
2713 } else if (getExceptionSpecType() == EST_Uninstantiated) {
2714 // Store the function decl from which we will resolve our
2715 // exception specification.
2716 FunctionDecl **slot =
2717 reinterpret_cast<FunctionDecl **>(argSlot + NumParams);
2718 slot[0] = epi.ExceptionSpec.SourceDecl;
2719 slot[1] = epi.ExceptionSpec.SourceTemplate;
2720 // This exception specification doesn't make the type dependent, because
2721 // it's not instantiated as part of instantiating the type.
2722 } else if (getExceptionSpecType() == EST_Unevaluated) {
2723 // Store the function decl from which we will resolve our
2724 // exception specification.
2725 FunctionDecl **slot =
2726 reinterpret_cast<FunctionDecl **>(argSlot + NumParams);
2727 slot[0] = epi.ExceptionSpec.SourceDecl;
2730 // If this is a canonical type, and its exception specification is dependent,
2731 // then it's a dependent type. This only happens in C++17 onwards.
2732 if (isCanonicalUnqualified()) {
2733 if (getExceptionSpecType() == EST_Dynamic ||
2734 getExceptionSpecType() == EST_ComputedNoexcept) {
2735 assert(hasDependentExceptionSpec() && "type should not be canonical");
2738 } else if (getCanonicalTypeInternal()->isDependentType()) {
2739 // Ask our canonical type whether our exception specification was dependent.
2743 if (epi.ExtParameterInfos) {
2744 ExtParameterInfo *extParamInfos =
2745 const_cast<ExtParameterInfo *>(getExtParameterInfosBuffer());
2746 for (unsigned i = 0; i != NumParams; ++i)
2747 extParamInfos[i] = epi.ExtParameterInfos[i];
2751 bool FunctionProtoType::hasDependentExceptionSpec() const {
2752 if (Expr *NE = getNoexceptExpr())
2753 return NE->isValueDependent();
2754 for (QualType ET : exceptions())
2755 // A pack expansion with a non-dependent pattern is still dependent,
2756 // because we don't know whether the pattern is in the exception spec
2757 // or not (that depends on whether the pack has 0 expansions).
2758 if (ET->isDependentType() || ET->getAs<PackExpansionType>())
2763 bool FunctionProtoType::hasInstantiationDependentExceptionSpec() const {
2764 if (Expr *NE = getNoexceptExpr())
2765 return NE->isInstantiationDependent();
2766 for (QualType ET : exceptions())
2767 if (ET->isInstantiationDependentType())
2772 FunctionProtoType::NoexceptResult
2773 FunctionProtoType::getNoexceptSpec(const ASTContext &ctx) const {
2774 ExceptionSpecificationType est = getExceptionSpecType();
2775 if (est == EST_BasicNoexcept)
2778 if (est != EST_ComputedNoexcept)
2779 return NR_NoNoexcept;
2781 Expr *noexceptExpr = getNoexceptExpr();
2783 return NR_BadNoexcept;
2784 if (noexceptExpr->isValueDependent())
2785 return NR_Dependent;
2788 bool isICE = noexceptExpr->isIntegerConstantExpr(value, ctx, nullptr,
2789 /*evaluated*/false);
2791 assert(isICE && "AST should not contain bad noexcept expressions.");
2793 return value.getBoolValue() ? NR_Nothrow : NR_Throw;
2796 CanThrowResult FunctionProtoType::canThrow(const ASTContext &Ctx) const {
2797 ExceptionSpecificationType EST = getExceptionSpecType();
2798 assert(EST != EST_Unevaluated && EST != EST_Uninstantiated);
2799 if (EST == EST_DynamicNone || EST == EST_BasicNoexcept)
2802 if (EST == EST_Dynamic) {
2803 // A dynamic exception specification is throwing unless every exception
2804 // type is an (unexpanded) pack expansion type.
2805 for (unsigned I = 0, N = NumExceptions; I != N; ++I)
2806 if (!getExceptionType(I)->getAs<PackExpansionType>())
2808 return CT_Dependent;
2811 if (EST != EST_ComputedNoexcept)
2814 NoexceptResult NR = getNoexceptSpec(Ctx);
2815 if (NR == NR_Dependent)
2816 return CT_Dependent;
2817 return NR == NR_Nothrow ? CT_Cannot : CT_Can;
2820 bool FunctionProtoType::isTemplateVariadic() const {
2821 for (unsigned ArgIdx = getNumParams(); ArgIdx; --ArgIdx)
2822 if (isa<PackExpansionType>(getParamType(ArgIdx - 1)))
2828 void FunctionProtoType::Profile(llvm::FoldingSetNodeID &ID, QualType Result,
2829 const QualType *ArgTys, unsigned NumParams,
2830 const ExtProtoInfo &epi,
2831 const ASTContext &Context, bool Canonical) {
2833 // We have to be careful not to get ambiguous profile encodings.
2834 // Note that valid type pointers are never ambiguous with anything else.
2836 // The encoding grammar begins:
2837 // type type* bool int bool
2838 // If that final bool is true, then there is a section for the EH spec:
2840 // This is followed by an optional "consumed argument" section of the
2841 // same length as the first type sequence:
2843 // Finally, we have the ext info and trailing return type flag:
2846 // There is no ambiguity between the consumed arguments and an empty EH
2847 // spec because of the leading 'bool' which unambiguously indicates
2848 // whether the following bool is the EH spec or part of the arguments.
2850 ID.AddPointer(Result.getAsOpaquePtr());
2851 for (unsigned i = 0; i != NumParams; ++i)
2852 ID.AddPointer(ArgTys[i].getAsOpaquePtr());
2853 // This method is relatively performance sensitive, so as a performance
2854 // shortcut, use one AddInteger call instead of four for the next four
2856 assert(!(unsigned(epi.Variadic) & ~1) &&
2857 !(unsigned(epi.TypeQuals) & ~255) &&
2858 !(unsigned(epi.RefQualifier) & ~3) &&
2859 !(unsigned(epi.ExceptionSpec.Type) & ~15) &&
2860 "Values larger than expected.");
2861 ID.AddInteger(unsigned(epi.Variadic) +
2862 (epi.TypeQuals << 1) +
2863 (epi.RefQualifier << 9) +
2864 (epi.ExceptionSpec.Type << 11));
2865 if (epi.ExceptionSpec.Type == EST_Dynamic) {
2866 for (QualType Ex : epi.ExceptionSpec.Exceptions)
2867 ID.AddPointer(Ex.getAsOpaquePtr());
2868 } else if (epi.ExceptionSpec.Type == EST_ComputedNoexcept &&
2869 epi.ExceptionSpec.NoexceptExpr) {
2870 epi.ExceptionSpec.NoexceptExpr->Profile(ID, Context, Canonical);
2871 } else if (epi.ExceptionSpec.Type == EST_Uninstantiated ||
2872 epi.ExceptionSpec.Type == EST_Unevaluated) {
2873 ID.AddPointer(epi.ExceptionSpec.SourceDecl->getCanonicalDecl());
2875 if (epi.ExtParameterInfos) {
2876 for (unsigned i = 0; i != NumParams; ++i)
2877 ID.AddInteger(epi.ExtParameterInfos[i].getOpaqueValue());
2879 epi.ExtInfo.Profile(ID);
2880 ID.AddBoolean(epi.HasTrailingReturn);
2883 void FunctionProtoType::Profile(llvm::FoldingSetNodeID &ID,
2884 const ASTContext &Ctx) {
2885 Profile(ID, getReturnType(), param_type_begin(), NumParams, getExtProtoInfo(),
2886 Ctx, isCanonicalUnqualified());
2889 QualType TypedefType::desugar() const {
2890 return getDecl()->getUnderlyingType();
2893 TypeOfExprType::TypeOfExprType(Expr *E, QualType can)
2894 : Type(TypeOfExpr, can, E->isTypeDependent(),
2895 E->isInstantiationDependent(),
2896 E->getType()->isVariablyModifiedType(),
2897 E->containsUnexpandedParameterPack()),
2901 bool TypeOfExprType::isSugared() const {
2902 return !TOExpr->isTypeDependent();
2905 QualType TypeOfExprType::desugar() const {
2907 return getUnderlyingExpr()->getType();
2909 return QualType(this, 0);
2912 void DependentTypeOfExprType::Profile(llvm::FoldingSetNodeID &ID,
2913 const ASTContext &Context, Expr *E) {
2914 E->Profile(ID, Context, true);
2917 DecltypeType::DecltypeType(Expr *E, QualType underlyingType, QualType can)
2918 // C++11 [temp.type]p2: "If an expression e involves a template parameter,
2919 // decltype(e) denotes a unique dependent type." Hence a decltype type is
2920 // type-dependent even if its expression is only instantiation-dependent.
2921 : Type(Decltype, can, E->isInstantiationDependent(),
2922 E->isInstantiationDependent(),
2923 E->getType()->isVariablyModifiedType(),
2924 E->containsUnexpandedParameterPack()),
2926 UnderlyingType(underlyingType) {
2929 bool DecltypeType::isSugared() const { return !E->isInstantiationDependent(); }
2931 QualType DecltypeType::desugar() const {
2933 return getUnderlyingType();
2935 return QualType(this, 0);
2938 DependentDecltypeType::DependentDecltypeType(const ASTContext &Context, Expr *E)
2939 : DecltypeType(E, Context.DependentTy), Context(Context) { }
2941 void DependentDecltypeType::Profile(llvm::FoldingSetNodeID &ID,
2942 const ASTContext &Context, Expr *E) {
2943 E->Profile(ID, Context, true);
2946 UnaryTransformType::UnaryTransformType(QualType BaseType,
2947 QualType UnderlyingType,
2949 QualType CanonicalType)
2950 : Type(UnaryTransform, CanonicalType, BaseType->isDependentType(),
2951 BaseType->isInstantiationDependentType(),
2952 BaseType->isVariablyModifiedType(),
2953 BaseType->containsUnexpandedParameterPack())
2954 , BaseType(BaseType), UnderlyingType(UnderlyingType), UKind(UKind)
2957 DependentUnaryTransformType::DependentUnaryTransformType(const ASTContext &C,
2960 : UnaryTransformType(BaseType, C.DependentTy, UKind, QualType())
2964 TagType::TagType(TypeClass TC, const TagDecl *D, QualType can)
2965 : Type(TC, can, D->isDependentType(),
2966 /*InstantiationDependent=*/D->isDependentType(),
2967 /*VariablyModified=*/false,
2968 /*ContainsUnexpandedParameterPack=*/false),
2969 decl(const_cast<TagDecl*>(D)) {}
2971 static TagDecl *getInterestingTagDecl(TagDecl *decl) {
2972 for (auto I : decl->redecls()) {
2973 if (I->isCompleteDefinition() || I->isBeingDefined())
2976 // If there's no definition (not even in progress), return what we have.
2980 TagDecl *TagType::getDecl() const {
2981 return getInterestingTagDecl(decl);
2984 bool TagType::isBeingDefined() const {
2985 return getDecl()->isBeingDefined();
2988 bool AttributedType::isQualifier() const {
2989 switch (getAttrKind()) {
2990 // These are type qualifiers in the traditional C sense: they annotate
2991 // something about a specific value/variable of a type. (They aren't
2992 // always part of the canonical type, though.)
2993 case AttributedType::attr_address_space:
2994 case AttributedType::attr_objc_gc:
2995 case AttributedType::attr_objc_ownership:
2996 case AttributedType::attr_objc_inert_unsafe_unretained:
2997 case AttributedType::attr_nonnull:
2998 case AttributedType::attr_nullable:
2999 case AttributedType::attr_null_unspecified:
3002 // These aren't qualifiers; they rewrite the modified type to be a
3003 // semantically different type.
3004 case AttributedType::attr_regparm:
3005 case AttributedType::attr_vector_size:
3006 case AttributedType::attr_neon_vector_type:
3007 case AttributedType::attr_neon_polyvector_type:
3008 case AttributedType::attr_pcs:
3009 case AttributedType::attr_pcs_vfp:
3010 case AttributedType::attr_noreturn:
3011 case AttributedType::attr_cdecl:
3012 case AttributedType::attr_fastcall:
3013 case AttributedType::attr_stdcall:
3014 case AttributedType::attr_thiscall:
3015 case AttributedType::attr_regcall:
3016 case AttributedType::attr_pascal:
3017 case AttributedType::attr_swiftcall:
3018 case AttributedType::attr_vectorcall:
3019 case AttributedType::attr_inteloclbicc:
3020 case AttributedType::attr_preserve_most:
3021 case AttributedType::attr_preserve_all:
3022 case AttributedType::attr_ms_abi:
3023 case AttributedType::attr_sysv_abi:
3024 case AttributedType::attr_ptr32:
3025 case AttributedType::attr_ptr64:
3026 case AttributedType::attr_sptr:
3027 case AttributedType::attr_uptr:
3028 case AttributedType::attr_objc_kindof:
3031 llvm_unreachable("bad attributed type kind");
3034 bool AttributedType::isMSTypeSpec() const {
3035 switch (getAttrKind()) {
3036 default: return false;
3043 llvm_unreachable("invalid attr kind");
3046 bool AttributedType::isCallingConv() const {
3047 switch (getAttrKind()) {
3052 case attr_address_space:
3054 case attr_vector_size:
3055 case attr_neon_vector_type:
3056 case attr_neon_polyvector_type:
3058 case attr_objc_ownership:
3059 case attr_objc_inert_unsafe_unretained:
3063 case attr_null_unspecified:
3064 case attr_objc_kindof:
3074 case attr_swiftcall:
3075 case attr_vectorcall:
3079 case attr_inteloclbicc:
3080 case attr_preserve_most:
3081 case attr_preserve_all:
3084 llvm_unreachable("invalid attr kind");
3087 CXXRecordDecl *InjectedClassNameType::getDecl() const {
3088 return cast<CXXRecordDecl>(getInterestingTagDecl(Decl));
3091 IdentifierInfo *TemplateTypeParmType::getIdentifier() const {
3092 return isCanonicalUnqualified() ? nullptr : getDecl()->getIdentifier();
3095 SubstTemplateTypeParmPackType::
3096 SubstTemplateTypeParmPackType(const TemplateTypeParmType *Param,
3098 const TemplateArgument &ArgPack)
3099 : Type(SubstTemplateTypeParmPack, Canon, true, true, false, true),
3101 Arguments(ArgPack.pack_begin()), NumArguments(ArgPack.pack_size())
3105 TemplateArgument SubstTemplateTypeParmPackType::getArgumentPack() const {
3106 return TemplateArgument(llvm::makeArrayRef(Arguments, NumArguments));
3109 void SubstTemplateTypeParmPackType::Profile(llvm::FoldingSetNodeID &ID) {
3110 Profile(ID, getReplacedParameter(), getArgumentPack());
3113 void SubstTemplateTypeParmPackType::Profile(llvm::FoldingSetNodeID &ID,
3114 const TemplateTypeParmType *Replaced,
3115 const TemplateArgument &ArgPack) {
3116 ID.AddPointer(Replaced);
3117 ID.AddInteger(ArgPack.pack_size());
3118 for (const auto &P : ArgPack.pack_elements())
3119 ID.AddPointer(P.getAsType().getAsOpaquePtr());
3122 bool TemplateSpecializationType::
3123 anyDependentTemplateArguments(const TemplateArgumentListInfo &Args,
3124 bool &InstantiationDependent) {
3125 return anyDependentTemplateArguments(Args.arguments(),
3126 InstantiationDependent);
3129 bool TemplateSpecializationType::
3130 anyDependentTemplateArguments(ArrayRef<TemplateArgumentLoc> Args,
3131 bool &InstantiationDependent) {
3132 for (const TemplateArgumentLoc &ArgLoc : Args) {
3133 if (ArgLoc.getArgument().isDependent()) {
3134 InstantiationDependent = true;
3138 if (ArgLoc.getArgument().isInstantiationDependent())
3139 InstantiationDependent = true;
3144 TemplateSpecializationType::
3145 TemplateSpecializationType(TemplateName T,
3146 ArrayRef<TemplateArgument> Args,
3147 QualType Canon, QualType AliasedType)
3148 : Type(TemplateSpecialization,
3149 Canon.isNull()? QualType(this, 0) : Canon,
3150 Canon.isNull()? true : Canon->isDependentType(),
3151 Canon.isNull()? true : Canon->isInstantiationDependentType(),
3153 T.containsUnexpandedParameterPack()),
3154 Template(T), NumArgs(Args.size()), TypeAlias(!AliasedType.isNull()) {
3155 assert(!T.getAsDependentTemplateName() &&
3156 "Use DependentTemplateSpecializationType for dependent template-name");
3157 assert((T.getKind() == TemplateName::Template ||
3158 T.getKind() == TemplateName::SubstTemplateTemplateParm ||
3159 T.getKind() == TemplateName::SubstTemplateTemplateParmPack) &&
3160 "Unexpected template name for TemplateSpecializationType");
3162 TemplateArgument *TemplateArgs
3163 = reinterpret_cast<TemplateArgument *>(this + 1);
3164 for (const TemplateArgument &Arg : Args) {
3165 // Update instantiation-dependent and variably-modified bits.
3166 // If the canonical type exists and is non-dependent, the template
3167 // specialization type can be non-dependent even if one of the type
3168 // arguments is. Given:
3169 // template<typename T> using U = int;
3170 // U<T> is always non-dependent, irrespective of the type T.
3171 // However, U<Ts> contains an unexpanded parameter pack, even though
3172 // its expansion (and thus its desugared type) doesn't.
3173 if (Arg.isInstantiationDependent())
3174 setInstantiationDependent();
3175 if (Arg.getKind() == TemplateArgument::Type &&
3176 Arg.getAsType()->isVariablyModifiedType())
3177 setVariablyModified();
3178 if (Arg.containsUnexpandedParameterPack())
3179 setContainsUnexpandedParameterPack();
3180 new (TemplateArgs++) TemplateArgument(Arg);
3183 // Store the aliased type if this is a type alias template specialization.
3185 TemplateArgument *Begin = reinterpret_cast<TemplateArgument *>(this + 1);
3186 *reinterpret_cast<QualType*>(Begin + getNumArgs()) = AliasedType;
3191 TemplateSpecializationType::Profile(llvm::FoldingSetNodeID &ID,
3193 ArrayRef<TemplateArgument> Args,
3194 const ASTContext &Context) {
3196 for (const TemplateArgument &Arg : Args)
3197 Arg.Profile(ID, Context);
3201 QualifierCollector::apply(const ASTContext &Context, QualType QT) const {
3202 if (!hasNonFastQualifiers())
3203 return QT.withFastQualifiers(getFastQualifiers());
3205 return Context.getQualifiedType(QT, *this);
3209 QualifierCollector::apply(const ASTContext &Context, const Type *T) const {
3210 if (!hasNonFastQualifiers())
3211 return QualType(T, getFastQualifiers());
3213 return Context.getQualifiedType(T, *this);
3216 void ObjCObjectTypeImpl::Profile(llvm::FoldingSetNodeID &ID,
3218 ArrayRef<QualType> typeArgs,
3219 ArrayRef<ObjCProtocolDecl *> protocols,
3221 ID.AddPointer(BaseType.getAsOpaquePtr());
3222 ID.AddInteger(typeArgs.size());
3223 for (auto typeArg : typeArgs)
3224 ID.AddPointer(typeArg.getAsOpaquePtr());
3225 ID.AddInteger(protocols.size());
3226 for (auto proto : protocols)
3227 ID.AddPointer(proto);
3228 ID.AddBoolean(isKindOf);
3231 void ObjCObjectTypeImpl::Profile(llvm::FoldingSetNodeID &ID) {
3232 Profile(ID, getBaseType(), getTypeArgsAsWritten(),
3233 llvm::makeArrayRef(qual_begin(), getNumProtocols()),
3234 isKindOfTypeAsWritten());
3237 void ObjCTypeParamType::Profile(llvm::FoldingSetNodeID &ID,
3238 const ObjCTypeParamDecl *OTPDecl,
3239 ArrayRef<ObjCProtocolDecl *> protocols) {
3240 ID.AddPointer(OTPDecl);
3241 ID.AddInteger(protocols.size());
3242 for (auto proto : protocols)
3243 ID.AddPointer(proto);
3246 void ObjCTypeParamType::Profile(llvm::FoldingSetNodeID &ID) {
3247 Profile(ID, getDecl(),
3248 llvm::makeArrayRef(qual_begin(), getNumProtocols()));
3253 /// \brief The cached properties of a type.
3254 class CachedProperties {
3259 CachedProperties(Linkage L, bool local) : L(L), local(local) {}
3261 Linkage getLinkage() const { return L; }
3262 bool hasLocalOrUnnamedType() const { return local; }
3264 friend CachedProperties merge(CachedProperties L, CachedProperties R) {
3265 Linkage MergedLinkage = minLinkage(L.L, R.L);
3266 return CachedProperties(MergedLinkage,
3267 L.hasLocalOrUnnamedType() | R.hasLocalOrUnnamedType());
3272 static CachedProperties computeCachedProperties(const Type *T);
3275 /// The type-property cache. This is templated so as to be
3276 /// instantiated at an internal type to prevent unnecessary symbol
3278 template <class Private> class TypePropertyCache {
3280 static CachedProperties get(QualType T) {
3281 return get(T.getTypePtr());
3284 static CachedProperties get(const Type *T) {
3286 return CachedProperties(T->TypeBits.getLinkage(),
3287 T->TypeBits.hasLocalOrUnnamedType());
3290 static void ensure(const Type *T) {
3291 // If the cache is valid, we're okay.
3292 if (T->TypeBits.isCacheValid()) return;
3294 // If this type is non-canonical, ask its canonical type for the
3295 // relevant information.
3296 if (!T->isCanonicalUnqualified()) {
3297 const Type *CT = T->getCanonicalTypeInternal().getTypePtr();
3299 T->TypeBits.CacheValid = true;
3300 T->TypeBits.CachedLinkage = CT->TypeBits.CachedLinkage;
3301 T->TypeBits.CachedLocalOrUnnamed = CT->TypeBits.CachedLocalOrUnnamed;
3305 // Compute the cached properties and then set the cache.
3306 CachedProperties Result = computeCachedProperties(T);
3307 T->TypeBits.CacheValid = true;
3308 T->TypeBits.CachedLinkage = Result.getLinkage();
3309 T->TypeBits.CachedLocalOrUnnamed = Result.hasLocalOrUnnamedType();
3314 // Instantiate the friend template at a private class. In a
3315 // reasonable implementation, these symbols will be internal.
3316 // It is terrible that this is the best way to accomplish this.
3317 namespace { class Private {}; }
3318 typedef TypePropertyCache<Private> Cache;
3320 static CachedProperties computeCachedProperties(const Type *T) {
3321 switch (T->getTypeClass()) {
3322 #define TYPE(Class,Base)
3323 #define NON_CANONICAL_TYPE(Class,Base) case Type::Class:
3324 #include "clang/AST/TypeNodes.def"
3325 llvm_unreachable("didn't expect a non-canonical type here");
3327 #define TYPE(Class,Base)
3328 #define DEPENDENT_TYPE(Class,Base) case Type::Class:
3329 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class,Base) case Type::Class:
3330 #include "clang/AST/TypeNodes.def"
3331 // Treat instantiation-dependent types as external.
3332 assert(T->isInstantiationDependentType());
3333 return CachedProperties(ExternalLinkage, false);
3336 case Type::DeducedTemplateSpecialization:
3337 // Give non-deduced 'auto' types external linkage. We should only see them
3338 // here in error recovery.
3339 return CachedProperties(ExternalLinkage, false);
3342 // C++ [basic.link]p8:
3343 // A type is said to have linkage if and only if:
3344 // - it is a fundamental type (3.9.1); or
3345 return CachedProperties(ExternalLinkage, false);
3349 const TagDecl *Tag = cast<TagType>(T)->getDecl();
3351 // C++ [basic.link]p8:
3352 // - it is a class or enumeration type that is named (or has a name
3353 // for linkage purposes (7.1.3)) and the name has linkage; or
3354 // - it is a specialization of a class template (14); or
3355 Linkage L = Tag->getLinkageInternal();
3356 bool IsLocalOrUnnamed =
3357 Tag->getDeclContext()->isFunctionOrMethod() ||
3358 !Tag->hasNameForLinkage();
3359 return CachedProperties(L, IsLocalOrUnnamed);
3362 // C++ [basic.link]p8:
3363 // - it is a compound type (3.9.2) other than a class or enumeration,
3364 // compounded exclusively from types that have linkage; or
3366 return Cache::get(cast<ComplexType>(T)->getElementType());
3368 return Cache::get(cast<PointerType>(T)->getPointeeType());
3369 case Type::BlockPointer:
3370 return Cache::get(cast<BlockPointerType>(T)->getPointeeType());
3371 case Type::LValueReference:
3372 case Type::RValueReference:
3373 return Cache::get(cast<ReferenceType>(T)->getPointeeType());
3374 case Type::MemberPointer: {
3375 const MemberPointerType *MPT = cast<MemberPointerType>(T);
3376 return merge(Cache::get(MPT->getClass()),
3377 Cache::get(MPT->getPointeeType()));
3379 case Type::ConstantArray:
3380 case Type::IncompleteArray:
3381 case Type::VariableArray:
3382 return Cache::get(cast<ArrayType>(T)->getElementType());
3384 case Type::ExtVector:
3385 return Cache::get(cast<VectorType>(T)->getElementType());
3386 case Type::FunctionNoProto:
3387 return Cache::get(cast<FunctionType>(T)->getReturnType());
3388 case Type::FunctionProto: {
3389 const FunctionProtoType *FPT = cast<FunctionProtoType>(T);
3390 CachedProperties result = Cache::get(FPT->getReturnType());
3391 for (const auto &ai : FPT->param_types())
3392 result = merge(result, Cache::get(ai));
3395 case Type::ObjCInterface: {
3396 Linkage L = cast<ObjCInterfaceType>(T)->getDecl()->getLinkageInternal();
3397 return CachedProperties(L, false);
3399 case Type::ObjCObject:
3400 return Cache::get(cast<ObjCObjectType>(T)->getBaseType());
3401 case Type::ObjCObjectPointer:
3402 return Cache::get(cast<ObjCObjectPointerType>(T)->getPointeeType());
3404 return Cache::get(cast<AtomicType>(T)->getValueType());
3406 return Cache::get(cast<PipeType>(T)->getElementType());
3409 llvm_unreachable("unhandled type class");
3412 /// \brief Determine the linkage of this type.
3413 Linkage Type::getLinkage() const {
3414 Cache::ensure(this);
3415 return TypeBits.getLinkage();
3418 bool Type::hasUnnamedOrLocalType() const {
3419 Cache::ensure(this);
3420 return TypeBits.hasLocalOrUnnamedType();
3423 static LinkageInfo computeLinkageInfo(QualType T);
3425 static LinkageInfo computeLinkageInfo(const Type *T) {
3426 switch (T->getTypeClass()) {
3427 #define TYPE(Class,Base)
3428 #define NON_CANONICAL_TYPE(Class,Base) case Type::Class:
3429 #include "clang/AST/TypeNodes.def"
3430 llvm_unreachable("didn't expect a non-canonical type here");
3432 #define TYPE(Class,Base)
3433 #define DEPENDENT_TYPE(Class,Base) case Type::Class:
3434 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class,Base) case Type::Class:
3435 #include "clang/AST/TypeNodes.def"
3436 // Treat instantiation-dependent types as external.
3437 assert(T->isInstantiationDependentType());
3438 return LinkageInfo::external();
3441 return LinkageInfo::external();
3444 case Type::DeducedTemplateSpecialization:
3445 return LinkageInfo::external();
3449 return cast<TagType>(T)->getDecl()->getLinkageAndVisibility();
3452 return computeLinkageInfo(cast<ComplexType>(T)->getElementType());
3454 return computeLinkageInfo(cast<PointerType>(T)->getPointeeType());
3455 case Type::BlockPointer:
3456 return computeLinkageInfo(cast<BlockPointerType>(T)->getPointeeType());
3457 case Type::LValueReference:
3458 case Type::RValueReference:
3459 return computeLinkageInfo(cast<ReferenceType>(T)->getPointeeType());
3460 case Type::MemberPointer: {
3461 const MemberPointerType *MPT = cast<MemberPointerType>(T);
3462 LinkageInfo LV = computeLinkageInfo(MPT->getClass());
3463 LV.merge(computeLinkageInfo(MPT->getPointeeType()));
3466 case Type::ConstantArray:
3467 case Type::IncompleteArray:
3468 case Type::VariableArray:
3469 return computeLinkageInfo(cast<ArrayType>(T)->getElementType());
3471 case Type::ExtVector:
3472 return computeLinkageInfo(cast<VectorType>(T)->getElementType());
3473 case Type::FunctionNoProto:
3474 return computeLinkageInfo(cast<FunctionType>(T)->getReturnType());
3475 case Type::FunctionProto: {
3476 const FunctionProtoType *FPT = cast<FunctionProtoType>(T);
3477 LinkageInfo LV = computeLinkageInfo(FPT->getReturnType());
3478 for (const auto &ai : FPT->param_types())
3479 LV.merge(computeLinkageInfo(ai));
3482 case Type::ObjCInterface:
3483 return cast<ObjCInterfaceType>(T)->getDecl()->getLinkageAndVisibility();
3484 case Type::ObjCObject:
3485 return computeLinkageInfo(cast<ObjCObjectType>(T)->getBaseType());
3486 case Type::ObjCObjectPointer:
3487 return computeLinkageInfo(cast<ObjCObjectPointerType>(T)->getPointeeType());
3489 return computeLinkageInfo(cast<AtomicType>(T)->getValueType());
3491 return computeLinkageInfo(cast<PipeType>(T)->getElementType());
3494 llvm_unreachable("unhandled type class");
3497 static LinkageInfo computeLinkageInfo(QualType T) {
3498 return computeLinkageInfo(T.getTypePtr());
3501 bool Type::isLinkageValid() const {
3502 if (!TypeBits.isCacheValid())
3505 return computeLinkageInfo(getCanonicalTypeInternal()).getLinkage() ==
3506 TypeBits.getLinkage();
3509 LinkageInfo Type::getLinkageAndVisibility() const {
3510 if (!isCanonicalUnqualified())
3511 return computeLinkageInfo(getCanonicalTypeInternal());
3513 LinkageInfo LV = computeLinkageInfo(this);
3514 assert(LV.getLinkage() == getLinkage());
3518 Optional<NullabilityKind> Type::getNullability(const ASTContext &context) const {
3519 QualType type(this, 0);
3521 // Check whether this is an attributed type with nullability
3523 if (auto attributed = dyn_cast<AttributedType>(type.getTypePtr())) {
3524 if (auto nullability = attributed->getImmediateNullability())
3528 // Desugar the type. If desugaring does nothing, we're done.
3529 QualType desugared = type.getSingleStepDesugaredType(context);
3530 if (desugared.getTypePtr() == type.getTypePtr())
3537 bool Type::canHaveNullability() const {
3538 QualType type = getCanonicalTypeInternal();
3540 switch (type->getTypeClass()) {
3541 // We'll only see canonical types here.
3542 #define NON_CANONICAL_TYPE(Class, Parent) \
3544 llvm_unreachable("non-canonical type");
3545 #define TYPE(Class, Parent)
3546 #include "clang/AST/TypeNodes.def"
3550 case Type::BlockPointer:
3551 case Type::MemberPointer:
3552 case Type::ObjCObjectPointer:
3555 // Dependent types that could instantiate to pointer types.
3556 case Type::UnresolvedUsing:
3557 case Type::TypeOfExpr:
3559 case Type::Decltype:
3560 case Type::UnaryTransform:
3561 case Type::TemplateTypeParm:
3562 case Type::SubstTemplateTypeParmPack:
3563 case Type::DependentName:
3564 case Type::DependentTemplateSpecialization:
3567 // Dependent template specializations can instantiate to pointer
3568 // types unless they're known to be specializations of a class
3570 case Type::TemplateSpecialization:
3571 if (TemplateDecl *templateDecl
3572 = cast<TemplateSpecializationType>(type.getTypePtr())
3573 ->getTemplateName().getAsTemplateDecl()) {
3574 if (isa<ClassTemplateDecl>(templateDecl))
3579 // auto is considered dependent when it isn't deduced.
3581 case Type::DeducedTemplateSpecialization:
3582 return !cast<DeducedType>(type.getTypePtr())->isDeduced();
3585 switch (cast<BuiltinType>(type.getTypePtr())->getKind()) {
3586 // Signed, unsigned, and floating-point types cannot have nullability.
3587 #define SIGNED_TYPE(Id, SingletonId) case BuiltinType::Id:
3588 #define UNSIGNED_TYPE(Id, SingletonId) case BuiltinType::Id:
3589 #define FLOATING_TYPE(Id, SingletonId) case BuiltinType::Id:
3590 #define BUILTIN_TYPE(Id, SingletonId)
3591 #include "clang/AST/BuiltinTypes.def"
3594 // Dependent types that could instantiate to a pointer type.
3595 case BuiltinType::Dependent:
3596 case BuiltinType::Overload:
3597 case BuiltinType::BoundMember:
3598 case BuiltinType::PseudoObject:
3599 case BuiltinType::UnknownAny:
3600 case BuiltinType::ARCUnbridgedCast:
3603 case BuiltinType::Void:
3604 case BuiltinType::ObjCId:
3605 case BuiltinType::ObjCClass:
3606 case BuiltinType::ObjCSel:
3607 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
3608 case BuiltinType::Id:
3609 #include "clang/Basic/OpenCLImageTypes.def"
3610 case BuiltinType::OCLSampler:
3611 case BuiltinType::OCLEvent:
3612 case BuiltinType::OCLClkEvent:
3613 case BuiltinType::OCLQueue:
3614 case BuiltinType::OCLReserveID:
3615 case BuiltinType::BuiltinFn:
3616 case BuiltinType::NullPtr:
3617 case BuiltinType::OMPArraySection:
3621 // Non-pointer types.
3623 case Type::LValueReference:
3624 case Type::RValueReference:
3625 case Type::ConstantArray:
3626 case Type::IncompleteArray:
3627 case Type::VariableArray:
3628 case Type::DependentSizedArray:
3629 case Type::DependentSizedExtVector:
3631 case Type::ExtVector:
3632 case Type::FunctionProto:
3633 case Type::FunctionNoProto:
3636 case Type::InjectedClassName:
3637 case Type::PackExpansion:
3638 case Type::ObjCObject:
3639 case Type::ObjCInterface:
3644 llvm_unreachable("bad type kind!");
3647 llvm::Optional<NullabilityKind> AttributedType::getImmediateNullability() const {
3648 if (getAttrKind() == AttributedType::attr_nonnull)
3649 return NullabilityKind::NonNull;
3650 if (getAttrKind() == AttributedType::attr_nullable)
3651 return NullabilityKind::Nullable;
3652 if (getAttrKind() == AttributedType::attr_null_unspecified)
3653 return NullabilityKind::Unspecified;
3657 Optional<NullabilityKind> AttributedType::stripOuterNullability(QualType &T) {
3658 if (auto attributed = dyn_cast<AttributedType>(T.getTypePtr())) {
3659 if (auto nullability = attributed->getImmediateNullability()) {
3660 T = attributed->getModifiedType();
3668 bool Type::isBlockCompatibleObjCPointerType(ASTContext &ctx) const {
3669 const ObjCObjectPointerType *objcPtr = getAs<ObjCObjectPointerType>();
3673 if (objcPtr->isObjCIdType()) {
3674 // id is always okay.
3678 // Blocks are NSObjects.
3679 if (ObjCInterfaceDecl *iface = objcPtr->getInterfaceDecl()) {
3680 if (iface->getIdentifier() != ctx.getNSObjectName())
3683 // Continue to check qualifiers, below.
3684 } else if (objcPtr->isObjCQualifiedIdType()) {
3685 // Continue to check qualifiers, below.
3690 // Check protocol qualifiers.
3691 for (ObjCProtocolDecl *proto : objcPtr->quals()) {
3692 // Blocks conform to NSObject and NSCopying.
3693 if (proto->getIdentifier() != ctx.getNSObjectName() &&
3694 proto->getIdentifier() != ctx.getNSCopyingName())
3701 Qualifiers::ObjCLifetime Type::getObjCARCImplicitLifetime() const {
3702 if (isObjCARCImplicitlyUnretainedType())
3703 return Qualifiers::OCL_ExplicitNone;
3704 return Qualifiers::OCL_Strong;
3707 bool Type::isObjCARCImplicitlyUnretainedType() const {
3708 assert(isObjCLifetimeType() &&
3709 "cannot query implicit lifetime for non-inferrable type");
3711 const Type *canon = getCanonicalTypeInternal().getTypePtr();
3713 // Walk down to the base type. We don't care about qualifiers for this.
3714 while (const ArrayType *array = dyn_cast<ArrayType>(canon))
3715 canon = array->getElementType().getTypePtr();
3717 if (const ObjCObjectPointerType *opt
3718 = dyn_cast<ObjCObjectPointerType>(canon)) {
3719 // Class and Class<Protocol> don't require retention.
3720 if (opt->getObjectType()->isObjCClass())
3727 bool Type::isObjCNSObjectType() const {
3728 const Type *cur = this;
3730 if (const TypedefType *typedefType = dyn_cast<TypedefType>(cur))
3731 return typedefType->getDecl()->hasAttr<ObjCNSObjectAttr>();
3733 // Single-step desugar until we run out of sugar.
3734 QualType next = cur->getLocallyUnqualifiedSingleStepDesugaredType();
3735 if (next.getTypePtr() == cur) return false;
3736 cur = next.getTypePtr();
3740 bool Type::isObjCIndependentClassType() const {
3741 if (const TypedefType *typedefType = dyn_cast<TypedefType>(this))
3742 return typedefType->getDecl()->hasAttr<ObjCIndependentClassAttr>();
3745 bool Type::isObjCRetainableType() const {
3746 return isObjCObjectPointerType() ||
3747 isBlockPointerType() ||
3748 isObjCNSObjectType();
3750 bool Type::isObjCIndirectLifetimeType() const {
3751 if (isObjCLifetimeType())
3753 if (const PointerType *OPT = getAs<PointerType>())
3754 return OPT->getPointeeType()->isObjCIndirectLifetimeType();
3755 if (const ReferenceType *Ref = getAs<ReferenceType>())
3756 return Ref->getPointeeType()->isObjCIndirectLifetimeType();
3757 if (const MemberPointerType *MemPtr = getAs<MemberPointerType>())
3758 return MemPtr->getPointeeType()->isObjCIndirectLifetimeType();
3762 /// Returns true if objects of this type have lifetime semantics under
3764 bool Type::isObjCLifetimeType() const {
3765 const Type *type = this;
3766 while (const ArrayType *array = type->getAsArrayTypeUnsafe())
3767 type = array->getElementType().getTypePtr();
3768 return type->isObjCRetainableType();
3771 /// \brief Determine whether the given type T is a "bridgable" Objective-C type,
3772 /// which is either an Objective-C object pointer type or an
3773 bool Type::isObjCARCBridgableType() const {
3774 return isObjCObjectPointerType() || isBlockPointerType();
3777 /// \brief Determine whether the given type T is a "bridgeable" C type.
3778 bool Type::isCARCBridgableType() const {
3779 const PointerType *Pointer = getAs<PointerType>();
3783 QualType Pointee = Pointer->getPointeeType();
3784 return Pointee->isVoidType() || Pointee->isRecordType();
3787 bool Type::hasSizedVLAType() const {
3788 if (!isVariablyModifiedType()) return false;
3790 if (const PointerType *ptr = getAs<PointerType>())
3791 return ptr->getPointeeType()->hasSizedVLAType();
3792 if (const ReferenceType *ref = getAs<ReferenceType>())
3793 return ref->getPointeeType()->hasSizedVLAType();
3794 if (const ArrayType *arr = getAsArrayTypeUnsafe()) {
3795 if (isa<VariableArrayType>(arr) &&
3796 cast<VariableArrayType>(arr)->getSizeExpr())
3799 return arr->getElementType()->hasSizedVLAType();
3805 QualType::DestructionKind QualType::isDestructedTypeImpl(QualType type) {
3806 switch (type.getObjCLifetime()) {
3807 case Qualifiers::OCL_None:
3808 case Qualifiers::OCL_ExplicitNone:
3809 case Qualifiers::OCL_Autoreleasing:
3812 case Qualifiers::OCL_Strong:
3813 return DK_objc_strong_lifetime;
3814 case Qualifiers::OCL_Weak:
3815 return DK_objc_weak_lifetime;
3818 /// Currently, the only destruction kind we recognize is C++ objects
3819 /// with non-trivial destructors.
3820 const CXXRecordDecl *record =
3821 type->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
3822 if (record && record->hasDefinition() && !record->hasTrivialDestructor())
3823 return DK_cxx_destructor;
3828 CXXRecordDecl *MemberPointerType::getMostRecentCXXRecordDecl() const {
3829 return getClass()->getAsCXXRecordDecl()->getMostRecentDecl();