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/ASTContext.h"
15 #include "clang/AST/CharUnits.h"
16 #include "clang/AST/Type.h"
17 #include "clang/AST/DeclCXX.h"
18 #include "clang/AST/DeclObjC.h"
19 #include "clang/AST/DeclTemplate.h"
20 #include "clang/AST/Expr.h"
21 #include "clang/AST/PrettyPrinter.h"
22 #include "clang/AST/TypeVisitor.h"
23 #include "clang/Basic/Specifiers.h"
24 #include "llvm/ADT/APSInt.h"
25 #include "llvm/ADT/StringExtras.h"
26 #include "llvm/Support/raw_ostream.h"
28 using namespace clang;
30 bool Qualifiers::isStrictSupersetOf(Qualifiers Other) const {
31 return (*this != Other) &&
32 // CVR qualifiers superset
33 (((Mask & CVRMask) | (Other.Mask & CVRMask)) == (Mask & CVRMask)) &&
34 // ObjC GC qualifiers superset
35 ((getObjCGCAttr() == Other.getObjCGCAttr()) ||
36 (hasObjCGCAttr() && !Other.hasObjCGCAttr())) &&
37 // Address space superset.
38 ((getAddressSpace() == Other.getAddressSpace()) ||
39 (hasAddressSpace()&& !Other.hasAddressSpace())) &&
40 // Lifetime qualifier superset.
41 ((getObjCLifetime() == Other.getObjCLifetime()) ||
42 (hasObjCLifetime() && !Other.hasObjCLifetime()));
45 bool QualType::isConstant(QualType T, ASTContext &Ctx) {
46 if (T.isConstQualified())
49 if (const ArrayType *AT = Ctx.getAsArrayType(T))
50 return AT->getElementType().isConstant(Ctx);
55 unsigned ConstantArrayType::getNumAddressingBits(ASTContext &Context,
57 const llvm::APInt &NumElements) {
58 llvm::APSInt SizeExtended(NumElements, true);
59 unsigned SizeTypeBits = Context.getTypeSize(Context.getSizeType());
60 SizeExtended = SizeExtended.extend(std::max(SizeTypeBits,
61 SizeExtended.getBitWidth()) * 2);
64 = Context.getTypeSizeInChars(ElementType).getQuantity();
65 llvm::APSInt TotalSize(llvm::APInt(SizeExtended.getBitWidth(), ElementSize));
66 TotalSize *= SizeExtended;
68 return TotalSize.getActiveBits();
71 unsigned ConstantArrayType::getMaxSizeBits(ASTContext &Context) {
72 unsigned Bits = Context.getTypeSize(Context.getSizeType());
74 // GCC appears to only allow 63 bits worth of address space when compiling
75 // for 64-bit, so we do the same.
82 DependentSizedArrayType::DependentSizedArrayType(const ASTContext &Context,
83 QualType et, QualType can,
84 Expr *e, ArraySizeModifier sm,
87 : ArrayType(DependentSizedArray, et, can, sm, tq,
88 (et->containsUnexpandedParameterPack() ||
89 (e && e->containsUnexpandedParameterPack()))),
90 Context(Context), SizeExpr((Stmt*) e), Brackets(brackets)
94 void DependentSizedArrayType::Profile(llvm::FoldingSetNodeID &ID,
95 const ASTContext &Context,
97 ArraySizeModifier SizeMod,
100 ID.AddPointer(ET.getAsOpaquePtr());
101 ID.AddInteger(SizeMod);
102 ID.AddInteger(TypeQuals);
103 E->Profile(ID, Context, true);
106 DependentSizedExtVectorType::DependentSizedExtVectorType(const
108 QualType ElementType,
112 : Type(DependentSizedExtVector, can, /*Dependent=*/true,
113 /*InstantiationDependent=*/true,
114 ElementType->isVariablyModifiedType(),
115 (ElementType->containsUnexpandedParameterPack() ||
116 (SizeExpr && SizeExpr->containsUnexpandedParameterPack()))),
117 Context(Context), SizeExpr(SizeExpr), ElementType(ElementType),
123 DependentSizedExtVectorType::Profile(llvm::FoldingSetNodeID &ID,
124 const ASTContext &Context,
125 QualType ElementType, Expr *SizeExpr) {
126 ID.AddPointer(ElementType.getAsOpaquePtr());
127 SizeExpr->Profile(ID, Context, true);
130 VectorType::VectorType(QualType vecType, unsigned nElements, QualType canonType,
132 : Type(Vector, canonType, vecType->isDependentType(),
133 vecType->isInstantiationDependentType(),
134 vecType->isVariablyModifiedType(),
135 vecType->containsUnexpandedParameterPack()),
138 VectorTypeBits.VecKind = vecKind;
139 VectorTypeBits.NumElements = nElements;
142 VectorType::VectorType(TypeClass tc, QualType vecType, unsigned nElements,
143 QualType canonType, VectorKind vecKind)
144 : Type(tc, canonType, vecType->isDependentType(),
145 vecType->isInstantiationDependentType(),
146 vecType->isVariablyModifiedType(),
147 vecType->containsUnexpandedParameterPack()),
150 VectorTypeBits.VecKind = vecKind;
151 VectorTypeBits.NumElements = nElements;
154 /// getArrayElementTypeNoTypeQual - If this is an array type, return the
155 /// element type of the array, potentially with type qualifiers missing.
156 /// This method should never be used when type qualifiers are meaningful.
157 const Type *Type::getArrayElementTypeNoTypeQual() const {
158 // If this is directly an array type, return it.
159 if (const ArrayType *ATy = dyn_cast<ArrayType>(this))
160 return ATy->getElementType().getTypePtr();
162 // If the canonical form of this type isn't the right kind, reject it.
163 if (!isa<ArrayType>(CanonicalType))
166 // If this is a typedef for an array type, strip the typedef off without
167 // losing all typedef information.
168 return cast<ArrayType>(getUnqualifiedDesugaredType())
169 ->getElementType().getTypePtr();
172 /// getDesugaredType - Return the specified type with any "sugar" removed from
173 /// the type. This takes off typedefs, typeof's etc. If the outer level of
174 /// the type is already concrete, it returns it unmodified. This is similar
175 /// to getting the canonical type, but it doesn't remove *all* typedefs. For
176 /// example, it returns "T*" as "T*", (not as "int*"), because the pointer is
178 QualType QualType::getDesugaredType(QualType T, const ASTContext &Context) {
179 SplitQualType split = getSplitDesugaredType(T);
180 return Context.getQualifiedType(split.first, split.second);
183 QualType QualType::getSingleStepDesugaredType(const ASTContext &Context) const {
184 QualifierCollector Qs;
186 const Type *CurTy = Qs.strip(*this);
187 switch (CurTy->getTypeClass()) {
188 #define ABSTRACT_TYPE(Class, Parent)
189 #define TYPE(Class, Parent) \
190 case Type::Class: { \
191 const Class##Type *Ty = cast<Class##Type>(CurTy); \
192 if (!Ty->isSugared()) \
194 return Context.getQualifiedType(Ty->desugar(), Qs); \
197 #include "clang/AST/TypeNodes.def"
203 SplitQualType QualType::getSplitDesugaredType(QualType T) {
204 QualifierCollector Qs;
208 const Type *CurTy = Qs.strip(Cur);
209 switch (CurTy->getTypeClass()) {
210 #define ABSTRACT_TYPE(Class, Parent)
211 #define TYPE(Class, Parent) \
212 case Type::Class: { \
213 const Class##Type *Ty = cast<Class##Type>(CurTy); \
214 if (!Ty->isSugared()) \
215 return SplitQualType(Ty, Qs); \
216 Cur = Ty->desugar(); \
219 #include "clang/AST/TypeNodes.def"
224 SplitQualType QualType::getSplitUnqualifiedTypeImpl(QualType type) {
225 SplitQualType split = type.split();
227 // All the qualifiers we've seen so far.
228 Qualifiers quals = split.second;
230 // The last type node we saw with any nodes inside it.
231 const Type *lastTypeWithQuals = split.first;
236 // Do a single-step desugar, aborting the loop if the type isn't
238 switch (split.first->getTypeClass()) {
239 #define ABSTRACT_TYPE(Class, Parent)
240 #define TYPE(Class, Parent) \
241 case Type::Class: { \
242 const Class##Type *ty = cast<Class##Type>(split.first); \
243 if (!ty->isSugared()) goto done; \
244 next = ty->desugar(); \
247 #include "clang/AST/TypeNodes.def"
250 // Otherwise, split the underlying type. If that yields qualifiers,
251 // update the information.
252 split = next.split();
253 if (!split.second.empty()) {
254 lastTypeWithQuals = split.first;
255 quals.addConsistentQualifiers(split.second);
260 return SplitQualType(lastTypeWithQuals, quals);
263 QualType QualType::IgnoreParens(QualType T) {
264 // FIXME: this seems inherently un-qualifiers-safe.
265 while (const ParenType *PT = T->getAs<ParenType>())
266 T = PT->getInnerType();
270 /// getUnqualifiedDesugaredType - Pull any qualifiers and syntactic
271 /// sugar off the given type. This should produce an object of the
272 /// same dynamic type as the canonical type.
273 const Type *Type::getUnqualifiedDesugaredType() const {
274 const Type *Cur = this;
277 switch (Cur->getTypeClass()) {
278 #define ABSTRACT_TYPE(Class, Parent)
279 #define TYPE(Class, Parent) \
281 const Class##Type *Ty = cast<Class##Type>(Cur); \
282 if (!Ty->isSugared()) return Cur; \
283 Cur = Ty->desugar().getTypePtr(); \
286 #include "clang/AST/TypeNodes.def"
291 /// isVoidType - Helper method to determine if this is the 'void' type.
292 bool Type::isVoidType() const {
293 if (const BuiltinType *BT = dyn_cast<BuiltinType>(CanonicalType))
294 return BT->getKind() == BuiltinType::Void;
298 bool Type::isDerivedType() const {
299 switch (CanonicalType->getTypeClass()) {
303 case IncompleteArray:
305 case FunctionNoProto:
306 case LValueReference:
307 case RValueReference:
314 bool Type::isClassType() const {
315 if (const RecordType *RT = getAs<RecordType>())
316 return RT->getDecl()->isClass();
319 bool Type::isStructureType() const {
320 if (const RecordType *RT = getAs<RecordType>())
321 return RT->getDecl()->isStruct();
324 bool Type::isStructureOrClassType() const {
325 if (const RecordType *RT = getAs<RecordType>())
326 return RT->getDecl()->isStruct() || RT->getDecl()->isClass();
329 bool Type::isVoidPointerType() const {
330 if (const PointerType *PT = getAs<PointerType>())
331 return PT->getPointeeType()->isVoidType();
335 bool Type::isUnionType() const {
336 if (const RecordType *RT = getAs<RecordType>())
337 return RT->getDecl()->isUnion();
341 bool Type::isComplexType() const {
342 if (const ComplexType *CT = dyn_cast<ComplexType>(CanonicalType))
343 return CT->getElementType()->isFloatingType();
347 bool Type::isComplexIntegerType() const {
348 // Check for GCC complex integer extension.
349 return getAsComplexIntegerType();
352 const ComplexType *Type::getAsComplexIntegerType() const {
353 if (const ComplexType *Complex = getAs<ComplexType>())
354 if (Complex->getElementType()->isIntegerType())
359 QualType Type::getPointeeType() const {
360 if (const PointerType *PT = getAs<PointerType>())
361 return PT->getPointeeType();
362 if (const ObjCObjectPointerType *OPT = getAs<ObjCObjectPointerType>())
363 return OPT->getPointeeType();
364 if (const BlockPointerType *BPT = getAs<BlockPointerType>())
365 return BPT->getPointeeType();
366 if (const ReferenceType *RT = getAs<ReferenceType>())
367 return RT->getPointeeType();
371 const RecordType *Type::getAsStructureType() const {
372 // If this is directly a structure type, return it.
373 if (const RecordType *RT = dyn_cast<RecordType>(this)) {
374 if (RT->getDecl()->isStruct())
378 // If the canonical form of this type isn't the right kind, reject it.
379 if (const RecordType *RT = dyn_cast<RecordType>(CanonicalType)) {
380 if (!RT->getDecl()->isStruct())
383 // If this is a typedef for a structure type, strip the typedef off without
384 // losing all typedef information.
385 return cast<RecordType>(getUnqualifiedDesugaredType());
390 const RecordType *Type::getAsUnionType() const {
391 // If this is directly a union type, return it.
392 if (const RecordType *RT = dyn_cast<RecordType>(this)) {
393 if (RT->getDecl()->isUnion())
397 // If the canonical form of this type isn't the right kind, reject it.
398 if (const RecordType *RT = dyn_cast<RecordType>(CanonicalType)) {
399 if (!RT->getDecl()->isUnion())
402 // If this is a typedef for a union type, strip the typedef off without
403 // losing all typedef information.
404 return cast<RecordType>(getUnqualifiedDesugaredType());
410 ObjCObjectType::ObjCObjectType(QualType Canonical, QualType Base,
411 ObjCProtocolDecl * const *Protocols,
412 unsigned NumProtocols)
413 : Type(ObjCObject, Canonical, false, false, false, false),
416 ObjCObjectTypeBits.NumProtocols = NumProtocols;
417 assert(getNumProtocols() == NumProtocols &&
418 "bitfield overflow in protocol count");
420 memcpy(getProtocolStorage(), Protocols,
421 NumProtocols * sizeof(ObjCProtocolDecl*));
424 const ObjCObjectType *Type::getAsObjCQualifiedInterfaceType() const {
425 // There is no sugar for ObjCObjectType's, just return the canonical
426 // type pointer if it is the right class. There is no typedef information to
427 // return and these cannot be Address-space qualified.
428 if (const ObjCObjectType *T = getAs<ObjCObjectType>())
429 if (T->getNumProtocols() && T->getInterface())
434 bool Type::isObjCQualifiedInterfaceType() const {
435 return getAsObjCQualifiedInterfaceType() != 0;
438 const ObjCObjectPointerType *Type::getAsObjCQualifiedIdType() const {
439 // There is no sugar for ObjCQualifiedIdType's, just return the canonical
440 // type pointer if it is the right class.
441 if (const ObjCObjectPointerType *OPT = getAs<ObjCObjectPointerType>()) {
442 if (OPT->isObjCQualifiedIdType())
448 const ObjCObjectPointerType *Type::getAsObjCQualifiedClassType() const {
449 // There is no sugar for ObjCQualifiedClassType's, just return the canonical
450 // type pointer if it is the right class.
451 if (const ObjCObjectPointerType *OPT = getAs<ObjCObjectPointerType>()) {
452 if (OPT->isObjCQualifiedClassType())
458 const ObjCObjectPointerType *Type::getAsObjCInterfacePointerType() const {
459 if (const ObjCObjectPointerType *OPT = getAs<ObjCObjectPointerType>()) {
460 if (OPT->getInterfaceType())
466 const CXXRecordDecl *Type::getCXXRecordDeclForPointerType() const {
467 if (const PointerType *PT = getAs<PointerType>())
468 if (const RecordType *RT = PT->getPointeeType()->getAs<RecordType>())
469 return dyn_cast<CXXRecordDecl>(RT->getDecl());
473 CXXRecordDecl *Type::getAsCXXRecordDecl() const {
474 if (const RecordType *RT = getAs<RecordType>())
475 return dyn_cast<CXXRecordDecl>(RT->getDecl());
476 else if (const InjectedClassNameType *Injected
477 = getAs<InjectedClassNameType>())
478 return Injected->getDecl();
484 class GetContainedAutoVisitor :
485 public TypeVisitor<GetContainedAutoVisitor, AutoType*> {
487 using TypeVisitor<GetContainedAutoVisitor, AutoType*>::Visit;
488 AutoType *Visit(QualType T) {
491 return Visit(T.getTypePtr());
494 // The 'auto' type itself.
495 AutoType *VisitAutoType(const AutoType *AT) {
496 return const_cast<AutoType*>(AT);
499 // Only these types can contain the desired 'auto' type.
500 AutoType *VisitPointerType(const PointerType *T) {
501 return Visit(T->getPointeeType());
503 AutoType *VisitBlockPointerType(const BlockPointerType *T) {
504 return Visit(T->getPointeeType());
506 AutoType *VisitReferenceType(const ReferenceType *T) {
507 return Visit(T->getPointeeTypeAsWritten());
509 AutoType *VisitMemberPointerType(const MemberPointerType *T) {
510 return Visit(T->getPointeeType());
512 AutoType *VisitArrayType(const ArrayType *T) {
513 return Visit(T->getElementType());
515 AutoType *VisitDependentSizedExtVectorType(
516 const DependentSizedExtVectorType *T) {
517 return Visit(T->getElementType());
519 AutoType *VisitVectorType(const VectorType *T) {
520 return Visit(T->getElementType());
522 AutoType *VisitFunctionType(const FunctionType *T) {
523 return Visit(T->getResultType());
525 AutoType *VisitParenType(const ParenType *T) {
526 return Visit(T->getInnerType());
528 AutoType *VisitAttributedType(const AttributedType *T) {
529 return Visit(T->getModifiedType());
534 AutoType *Type::getContainedAutoType() const {
535 return GetContainedAutoVisitor().Visit(this);
538 bool Type::isIntegerType() const {
539 if (const BuiltinType *BT = dyn_cast<BuiltinType>(CanonicalType))
540 return BT->getKind() >= BuiltinType::Bool &&
541 BT->getKind() <= BuiltinType::Int128;
542 if (const EnumType *ET = dyn_cast<EnumType>(CanonicalType))
543 // Incomplete enum types are not treated as integer types.
544 // FIXME: In C++, enum types are never integer types.
545 return ET->getDecl()->isComplete() && !ET->getDecl()->isScoped();
549 bool Type::hasIntegerRepresentation() const {
550 if (const VectorType *VT = dyn_cast<VectorType>(CanonicalType))
551 return VT->getElementType()->isIntegerType();
553 return isIntegerType();
556 /// \brief Determine whether this type is an integral type.
558 /// This routine determines whether the given type is an integral type per
559 /// C++ [basic.fundamental]p7. Although the C standard does not define the
560 /// term "integral type", it has a similar term "integer type", and in C++
561 /// the two terms are equivalent. However, C's "integer type" includes
562 /// enumeration types, while C++'s "integer type" does not. The \c ASTContext
563 /// parameter is used to determine whether we should be following the C or
564 /// C++ rules when determining whether this type is an integral/integer type.
566 /// For cases where C permits "an integer type" and C++ permits "an integral
567 /// type", use this routine.
569 /// For cases where C permits "an integer type" and C++ permits "an integral
570 /// or enumeration type", use \c isIntegralOrEnumerationType() instead.
572 /// \param Ctx The context in which this type occurs.
574 /// \returns true if the type is considered an integral type, false otherwise.
575 bool Type::isIntegralType(ASTContext &Ctx) const {
576 if (const BuiltinType *BT = dyn_cast<BuiltinType>(CanonicalType))
577 return BT->getKind() >= BuiltinType::Bool &&
578 BT->getKind() <= BuiltinType::Int128;
580 if (!Ctx.getLangOptions().CPlusPlus)
581 if (const EnumType *ET = dyn_cast<EnumType>(CanonicalType))
582 return ET->getDecl()->isComplete(); // Complete enum types are integral in C.
587 bool Type::isIntegralOrEnumerationType() const {
588 if (const BuiltinType *BT = dyn_cast<BuiltinType>(CanonicalType))
589 return BT->getKind() >= BuiltinType::Bool &&
590 BT->getKind() <= BuiltinType::Int128;
592 // Check for a complete enum type; incomplete enum types are not properly an
593 // enumeration type in the sense required here.
594 if (const EnumType *ET = dyn_cast<EnumType>(CanonicalType))
595 return ET->getDecl()->isComplete();
600 bool Type::isIntegralOrUnscopedEnumerationType() const {
601 if (const BuiltinType *BT = dyn_cast<BuiltinType>(CanonicalType))
602 return BT->getKind() >= BuiltinType::Bool &&
603 BT->getKind() <= BuiltinType::Int128;
605 // Check for a complete enum type; incomplete enum types are not properly an
606 // enumeration type in the sense required here.
607 // C++0x: However, if the underlying type of the enum is fixed, it is
608 // considered complete.
609 if (const EnumType *ET = dyn_cast<EnumType>(CanonicalType))
610 return ET->getDecl()->isComplete() && !ET->getDecl()->isScoped();
616 bool Type::isBooleanType() const {
617 if (const BuiltinType *BT = dyn_cast<BuiltinType>(CanonicalType))
618 return BT->getKind() == BuiltinType::Bool;
622 bool Type::isCharType() const {
623 if (const BuiltinType *BT = dyn_cast<BuiltinType>(CanonicalType))
624 return BT->getKind() == BuiltinType::Char_U ||
625 BT->getKind() == BuiltinType::UChar ||
626 BT->getKind() == BuiltinType::Char_S ||
627 BT->getKind() == BuiltinType::SChar;
631 bool Type::isWideCharType() const {
632 if (const BuiltinType *BT = dyn_cast<BuiltinType>(CanonicalType))
633 return BT->getKind() == BuiltinType::WChar_S ||
634 BT->getKind() == BuiltinType::WChar_U;
638 /// \brief Determine whether this type is any of the built-in character
640 bool Type::isAnyCharacterType() const {
641 const BuiltinType *BT = dyn_cast<BuiltinType>(CanonicalType);
642 if (BT == 0) return false;
643 switch (BT->getKind()) {
644 default: return false;
645 case BuiltinType::Char_U:
646 case BuiltinType::UChar:
647 case BuiltinType::WChar_U:
648 case BuiltinType::Char16:
649 case BuiltinType::Char32:
650 case BuiltinType::Char_S:
651 case BuiltinType::SChar:
652 case BuiltinType::WChar_S:
657 /// isSignedIntegerType - Return true if this is an integer type that is
658 /// signed, according to C99 6.2.5p4 [char, signed char, short, int, long..],
659 /// an enum decl which has a signed representation
660 bool Type::isSignedIntegerType() const {
661 if (const BuiltinType *BT = dyn_cast<BuiltinType>(CanonicalType)) {
662 return BT->getKind() >= BuiltinType::Char_S &&
663 BT->getKind() <= BuiltinType::Int128;
666 if (const EnumType *ET = dyn_cast<EnumType>(CanonicalType)) {
667 // Incomplete enum types are not treated as integer types.
668 // FIXME: In C++, enum types are never integer types.
669 if (ET->getDecl()->isComplete() && !ET->getDecl()->isScoped())
670 return ET->getDecl()->getIntegerType()->isSignedIntegerType();
676 bool Type::isSignedIntegerOrEnumerationType() const {
677 if (const BuiltinType *BT = dyn_cast<BuiltinType>(CanonicalType)) {
678 return BT->getKind() >= BuiltinType::Char_S &&
679 BT->getKind() <= BuiltinType::Int128;
682 if (const EnumType *ET = dyn_cast<EnumType>(CanonicalType)) {
683 if (ET->getDecl()->isComplete())
684 return ET->getDecl()->getIntegerType()->isSignedIntegerType();
690 bool Type::hasSignedIntegerRepresentation() const {
691 if (const VectorType *VT = dyn_cast<VectorType>(CanonicalType))
692 return VT->getElementType()->isSignedIntegerType();
694 return isSignedIntegerType();
697 /// isUnsignedIntegerType - Return true if this is an integer type that is
698 /// unsigned, according to C99 6.2.5p6 [which returns true for _Bool], an enum
699 /// decl which has an unsigned representation
700 bool Type::isUnsignedIntegerType() const {
701 if (const BuiltinType *BT = dyn_cast<BuiltinType>(CanonicalType)) {
702 return BT->getKind() >= BuiltinType::Bool &&
703 BT->getKind() <= BuiltinType::UInt128;
706 if (const EnumType *ET = dyn_cast<EnumType>(CanonicalType)) {
707 // Incomplete enum types are not treated as integer types.
708 // FIXME: In C++, enum types are never integer types.
709 if (ET->getDecl()->isComplete() && !ET->getDecl()->isScoped())
710 return ET->getDecl()->getIntegerType()->isUnsignedIntegerType();
716 bool Type::isUnsignedIntegerOrEnumerationType() const {
717 if (const BuiltinType *BT = dyn_cast<BuiltinType>(CanonicalType)) {
718 return BT->getKind() >= BuiltinType::Bool &&
719 BT->getKind() <= BuiltinType::UInt128;
722 if (const EnumType *ET = dyn_cast<EnumType>(CanonicalType)) {
723 if (ET->getDecl()->isComplete())
724 return ET->getDecl()->getIntegerType()->isUnsignedIntegerType();
730 bool Type::hasUnsignedIntegerRepresentation() const {
731 if (const VectorType *VT = dyn_cast<VectorType>(CanonicalType))
732 return VT->getElementType()->isUnsignedIntegerType();
734 return isUnsignedIntegerType();
737 bool Type::isFloatingType() const {
738 if (const BuiltinType *BT = dyn_cast<BuiltinType>(CanonicalType))
739 return BT->getKind() >= BuiltinType::Float &&
740 BT->getKind() <= BuiltinType::LongDouble;
741 if (const ComplexType *CT = dyn_cast<ComplexType>(CanonicalType))
742 return CT->getElementType()->isFloatingType();
746 bool Type::hasFloatingRepresentation() const {
747 if (const VectorType *VT = dyn_cast<VectorType>(CanonicalType))
748 return VT->getElementType()->isFloatingType();
750 return isFloatingType();
753 bool Type::isRealFloatingType() const {
754 if (const BuiltinType *BT = dyn_cast<BuiltinType>(CanonicalType))
755 return BT->isFloatingPoint();
759 bool Type::isRealType() const {
760 if (const BuiltinType *BT = dyn_cast<BuiltinType>(CanonicalType))
761 return BT->getKind() >= BuiltinType::Bool &&
762 BT->getKind() <= BuiltinType::LongDouble;
763 if (const EnumType *ET = dyn_cast<EnumType>(CanonicalType))
764 return ET->getDecl()->isComplete() && !ET->getDecl()->isScoped();
768 bool Type::isArithmeticType() const {
769 if (const BuiltinType *BT = dyn_cast<BuiltinType>(CanonicalType))
770 return BT->getKind() >= BuiltinType::Bool &&
771 BT->getKind() <= BuiltinType::LongDouble;
772 if (const EnumType *ET = dyn_cast<EnumType>(CanonicalType))
773 // GCC allows forward declaration of enum types (forbid by C99 6.7.2.3p2).
774 // If a body isn't seen by the time we get here, return false.
776 // C++0x: Enumerations are not arithmetic types. For now, just return
777 // false for scoped enumerations since that will disable any
778 // unwanted implicit conversions.
779 return !ET->getDecl()->isScoped() && ET->getDecl()->isComplete();
780 return isa<ComplexType>(CanonicalType);
783 bool Type::isScalarType() const {
784 if (const BuiltinType *BT = dyn_cast<BuiltinType>(CanonicalType))
785 return BT->getKind() > BuiltinType::Void &&
786 BT->getKind() <= BuiltinType::NullPtr;
787 if (const EnumType *ET = dyn_cast<EnumType>(CanonicalType))
788 // Enums are scalar types, but only if they are defined. Incomplete enums
789 // are not treated as scalar types.
790 return ET->getDecl()->isComplete();
791 return isa<PointerType>(CanonicalType) ||
792 isa<BlockPointerType>(CanonicalType) ||
793 isa<MemberPointerType>(CanonicalType) ||
794 isa<ComplexType>(CanonicalType) ||
795 isa<ObjCObjectPointerType>(CanonicalType);
798 Type::ScalarTypeKind Type::getScalarTypeKind() const {
799 assert(isScalarType());
801 const Type *T = CanonicalType.getTypePtr();
802 if (const BuiltinType *BT = dyn_cast<BuiltinType>(T)) {
803 if (BT->getKind() == BuiltinType::Bool) return STK_Bool;
804 if (BT->getKind() == BuiltinType::NullPtr) return STK_Pointer;
805 if (BT->isInteger()) return STK_Integral;
806 if (BT->isFloatingPoint()) return STK_Floating;
807 llvm_unreachable("unknown scalar builtin type");
808 } else if (isa<PointerType>(T) ||
809 isa<BlockPointerType>(T) ||
810 isa<ObjCObjectPointerType>(T)) {
812 } else if (isa<MemberPointerType>(T)) {
813 return STK_MemberPointer;
814 } else if (isa<EnumType>(T)) {
815 assert(cast<EnumType>(T)->getDecl()->isComplete());
817 } else if (const ComplexType *CT = dyn_cast<ComplexType>(T)) {
818 if (CT->getElementType()->isRealFloatingType())
819 return STK_FloatingComplex;
820 return STK_IntegralComplex;
823 llvm_unreachable("unknown scalar type");
827 /// \brief Determines whether the type is a C++ aggregate type or C
828 /// aggregate or union type.
830 /// An aggregate type is an array or a class type (struct, union, or
831 /// class) that has no user-declared constructors, no private or
832 /// protected non-static data members, no base classes, and no virtual
833 /// functions (C++ [dcl.init.aggr]p1). The notion of an aggregate type
834 /// subsumes the notion of C aggregates (C99 6.2.5p21) because it also
835 /// includes union types.
836 bool Type::isAggregateType() const {
837 if (const RecordType *Record = dyn_cast<RecordType>(CanonicalType)) {
838 if (CXXRecordDecl *ClassDecl = dyn_cast<CXXRecordDecl>(Record->getDecl()))
839 return ClassDecl->isAggregate();
844 return isa<ArrayType>(CanonicalType);
847 /// isConstantSizeType - Return true if this is not a variable sized type,
848 /// according to the rules of C99 6.7.5p3. It is not legal to call this on
849 /// incomplete types or dependent types.
850 bool Type::isConstantSizeType() const {
851 assert(!isIncompleteType() && "This doesn't make sense for incomplete types");
852 assert(!isDependentType() && "This doesn't make sense for dependent types");
853 // The VAT must have a size, as it is known to be complete.
854 return !isa<VariableArrayType>(CanonicalType);
857 /// isIncompleteType - Return true if this is an incomplete type (C99 6.2.5p1)
858 /// - a type that can describe objects, but which lacks information needed to
859 /// determine its size.
860 bool Type::isIncompleteType() const {
861 switch (CanonicalType->getTypeClass()) {
862 default: return false;
864 // Void is the only incomplete builtin type. Per C99 6.2.5p19, it can never
868 // An enumeration with fixed underlying type is complete (C++0x 7.2p3).
869 if (cast<EnumType>(CanonicalType)->getDecl()->isFixed())
873 // A tagged type (struct/union/enum/class) is incomplete if the decl is a
874 // forward declaration, but not a full definition (C99 6.2.5p22).
875 return !cast<TagType>(CanonicalType)->getDecl()->isDefinition();
877 // An array is incomplete if its element type is incomplete
878 // (C++ [dcl.array]p1).
879 // We don't handle variable arrays (they're not allowed in C++) or
880 // dependent-sized arrays (dependent types are never treated as incomplete).
881 return cast<ArrayType>(CanonicalType)->getElementType()->isIncompleteType();
882 case IncompleteArray:
883 // An array of unknown size is an incomplete type (C99 6.2.5p22).
886 return cast<ObjCObjectType>(CanonicalType)->getBaseType()
887 ->isIncompleteType();
889 // ObjC interfaces are incomplete if they are @class, not @interface.
890 return cast<ObjCInterfaceType>(CanonicalType)->getDecl()->isForwardDecl();
894 bool QualType::isPODType(ASTContext &Context) const {
895 // The compiler shouldn't query this for incomplete types, but the user might.
896 // We return false for that case. Except for incomplete arrays of PODs, which
897 // are PODs according to the standard.
901 if ((*this)->isIncompleteArrayType())
902 return Context.getBaseElementType(*this).isPODType(Context);
904 if ((*this)->isIncompleteType())
907 if (Context.getLangOptions().ObjCAutoRefCount) {
908 switch (getObjCLifetime()) {
909 case Qualifiers::OCL_ExplicitNone:
912 case Qualifiers::OCL_Strong:
913 case Qualifiers::OCL_Weak:
914 case Qualifiers::OCL_Autoreleasing:
917 case Qualifiers::OCL_None:
922 QualType CanonicalType = getTypePtr()->CanonicalType;
923 switch (CanonicalType->getTypeClass()) {
924 // Everything not explicitly mentioned is not POD.
925 default: return false;
926 case Type::VariableArray:
927 case Type::ConstantArray:
928 // IncompleteArray is handled above.
929 return Context.getBaseElementType(*this).isPODType(Context);
931 case Type::ObjCObjectPointer:
932 case Type::BlockPointer:
936 case Type::MemberPointer:
938 case Type::ExtVector:
945 if (CXXRecordDecl *ClassDecl
946 = dyn_cast<CXXRecordDecl>(cast<RecordType>(CanonicalType)->getDecl()))
947 return ClassDecl->isPOD();
949 // C struct/union is POD.
954 bool QualType::isTrivialType(ASTContext &Context) const {
955 // The compiler shouldn't query this for incomplete types, but the user might.
956 // We return false for that case. Except for incomplete arrays of PODs, which
957 // are PODs according to the standard.
961 if ((*this)->isArrayType())
962 return Context.getBaseElementType(*this).isTrivialType(Context);
964 // Return false for incomplete types after skipping any incomplete array
965 // types which are expressly allowed by the standard and thus our API.
966 if ((*this)->isIncompleteType())
969 if (Context.getLangOptions().ObjCAutoRefCount) {
970 switch (getObjCLifetime()) {
971 case Qualifiers::OCL_ExplicitNone:
974 case Qualifiers::OCL_Strong:
975 case Qualifiers::OCL_Weak:
976 case Qualifiers::OCL_Autoreleasing:
979 case Qualifiers::OCL_None:
980 if ((*this)->isObjCLifetimeType())
986 QualType CanonicalType = getTypePtr()->CanonicalType;
987 if (CanonicalType->isDependentType())
990 // C++0x [basic.types]p9:
991 // Scalar types, trivial class types, arrays of such types, and
992 // cv-qualified versions of these types are collectively called trivial
995 // As an extension, Clang treats vector types as Scalar types.
996 if (CanonicalType->isScalarType() || CanonicalType->isVectorType())
998 if (const RecordType *RT = CanonicalType->getAs<RecordType>()) {
999 if (const CXXRecordDecl *ClassDecl =
1000 dyn_cast<CXXRecordDecl>(RT->getDecl())) {
1002 // A trivial class is a class that has a trivial default constructor
1003 if (!ClassDecl->hasTrivialDefaultConstructor()) return false;
1004 // and is trivially copyable.
1005 if (!ClassDecl->isTriviallyCopyable()) return false;
1011 // No other types can match.
1015 bool QualType::isTriviallyCopyableType(ASTContext &Context) const {
1016 if ((*this)->isArrayType())
1017 return Context.getBaseElementType(*this).isTrivialType(Context);
1019 if (Context.getLangOptions().ObjCAutoRefCount) {
1020 switch (getObjCLifetime()) {
1021 case Qualifiers::OCL_ExplicitNone:
1024 case Qualifiers::OCL_Strong:
1025 case Qualifiers::OCL_Weak:
1026 case Qualifiers::OCL_Autoreleasing:
1029 case Qualifiers::OCL_None:
1030 if ((*this)->isObjCLifetimeType())
1036 // C++0x [basic.types]p9
1037 // Scalar types, trivially copyable class types, arrays of such types, and
1038 // cv-qualified versions of these types are collectively called trivial
1041 QualType CanonicalType = getCanonicalType();
1042 if (CanonicalType->isDependentType())
1045 // Return false for incomplete types after skipping any incomplete array types
1046 // which are expressly allowed by the standard and thus our API.
1047 if (CanonicalType->isIncompleteType())
1050 // As an extension, Clang treats vector types as Scalar types.
1051 if (CanonicalType->isScalarType() || CanonicalType->isVectorType())
1054 if (const RecordType *RT = CanonicalType->getAs<RecordType>()) {
1055 if (const CXXRecordDecl *ClassDecl =
1056 dyn_cast<CXXRecordDecl>(RT->getDecl())) {
1057 if (!ClassDecl->isTriviallyCopyable()) return false;
1063 // No other types can match.
1069 bool Type::isLiteralType() const {
1070 if (isDependentType())
1073 // C++0x [basic.types]p10:
1074 // A type is a literal type if it is:
1076 // -- an array of literal type
1077 // Extension: variable arrays cannot be literal types, since they're
1079 if (isVariableArrayType())
1081 const Type *BaseTy = getBaseElementTypeUnsafe();
1082 assert(BaseTy && "NULL element type");
1084 // Return false for incomplete types after skipping any incomplete array
1085 // types; those are expressly allowed by the standard and thus our API.
1086 if (BaseTy->isIncompleteType())
1089 // Objective-C lifetime types are not literal types.
1090 if (BaseTy->isObjCRetainableType())
1093 // C++0x [basic.types]p10:
1094 // A type is a literal type if it is:
1095 // -- a scalar type; or
1096 // As an extension, Clang treats vector types as Scalar types.
1097 if (BaseTy->isScalarType() || BaseTy->isVectorType()) return true;
1098 // -- a reference type; or
1099 if (BaseTy->isReferenceType()) return true;
1100 // -- a class type that has all of the following properties:
1101 if (const RecordType *RT = BaseTy->getAs<RecordType>()) {
1102 if (const CXXRecordDecl *ClassDecl =
1103 dyn_cast<CXXRecordDecl>(RT->getDecl())) {
1104 // -- a trivial destructor,
1105 if (!ClassDecl->hasTrivialDestructor()) return false;
1106 // -- every constructor call and full-expression in the
1107 // brace-or-equal-initializers for non-static data members (if any)
1108 // is a constant expression,
1109 // FIXME: C++0x: Clang doesn't yet support non-static data member
1110 // declarations with initializers, or constexprs.
1111 // -- it is an aggregate type or has at least one constexpr
1112 // constructor or constructor template that is not a copy or move
1114 if (!ClassDecl->isAggregate() &&
1115 !ClassDecl->hasConstExprNonCopyMoveConstructor())
1117 // -- all non-static data members and base classes of literal types
1118 if (ClassDecl->hasNonLiteralTypeFieldsOrBases()) return false;
1126 bool Type::isStandardLayoutType() const {
1127 if (isDependentType())
1130 // C++0x [basic.types]p9:
1131 // Scalar types, standard-layout class types, arrays of such types, and
1132 // cv-qualified versions of these types are collectively called
1133 // standard-layout types.
1134 const Type *BaseTy = getBaseElementTypeUnsafe();
1135 assert(BaseTy && "NULL element type");
1137 // Return false for incomplete types after skipping any incomplete array
1138 // types which are expressly allowed by the standard and thus our API.
1139 if (BaseTy->isIncompleteType())
1142 // As an extension, Clang treats vector types as Scalar types.
1143 if (BaseTy->isScalarType() || BaseTy->isVectorType()) return true;
1144 if (const RecordType *RT = BaseTy->getAs<RecordType>()) {
1145 if (const CXXRecordDecl *ClassDecl =
1146 dyn_cast<CXXRecordDecl>(RT->getDecl()))
1147 if (!ClassDecl->isStandardLayout())
1150 // Default to 'true' for non-C++ class types.
1151 // FIXME: This is a bit dubious, but plain C structs should trivially meet
1152 // all the requirements of standard layout classes.
1156 // No other types can match.
1160 // This is effectively the intersection of isTrivialType and
1161 // isStandardLayoutType. We implement it dircetly to avoid redundant
1162 // conversions from a type to a CXXRecordDecl.
1163 bool QualType::isCXX11PODType(ASTContext &Context) const {
1164 const Type *ty = getTypePtr();
1165 if (ty->isDependentType())
1168 if (Context.getLangOptions().ObjCAutoRefCount) {
1169 switch (getObjCLifetime()) {
1170 case Qualifiers::OCL_ExplicitNone:
1173 case Qualifiers::OCL_Strong:
1174 case Qualifiers::OCL_Weak:
1175 case Qualifiers::OCL_Autoreleasing:
1178 case Qualifiers::OCL_None:
1179 if (ty->isObjCLifetimeType())
1185 // C++11 [basic.types]p9:
1186 // Scalar types, POD classes, arrays of such types, and cv-qualified
1187 // versions of these types are collectively called trivial types.
1188 const Type *BaseTy = ty->getBaseElementTypeUnsafe();
1189 assert(BaseTy && "NULL element type");
1191 // Return false for incomplete types after skipping any incomplete array
1192 // types which are expressly allowed by the standard and thus our API.
1193 if (BaseTy->isIncompleteType())
1196 // As an extension, Clang treats vector types as Scalar types.
1197 if (BaseTy->isScalarType() || BaseTy->isVectorType()) return true;
1198 if (const RecordType *RT = BaseTy->getAs<RecordType>()) {
1199 if (const CXXRecordDecl *ClassDecl =
1200 dyn_cast<CXXRecordDecl>(RT->getDecl())) {
1201 // C++11 [class]p10:
1202 // A POD struct is a non-union class that is both a trivial class [...]
1203 if (!ClassDecl->isTrivial()) return false;
1205 // C++11 [class]p10:
1206 // A POD struct is a non-union class that is both a trivial class and
1207 // a standard-layout class [...]
1208 if (!ClassDecl->isStandardLayout()) return false;
1210 // C++11 [class]p10:
1211 // A POD struct is a non-union class that is both a trivial class and
1212 // a standard-layout class, and has no non-static data members of type
1213 // non-POD struct, non-POD union (or array of such types). [...]
1215 // We don't directly query the recursive aspect as the requiremets for
1216 // both standard-layout classes and trivial classes apply recursively
1223 // No other types can match.
1227 bool Type::isPromotableIntegerType() const {
1228 if (const BuiltinType *BT = getAs<BuiltinType>())
1229 switch (BT->getKind()) {
1230 case BuiltinType::Bool:
1231 case BuiltinType::Char_S:
1232 case BuiltinType::Char_U:
1233 case BuiltinType::SChar:
1234 case BuiltinType::UChar:
1235 case BuiltinType::Short:
1236 case BuiltinType::UShort:
1242 // Enumerated types are promotable to their compatible integer types
1243 // (C99 6.3.1.1) a.k.a. its underlying type (C++ [conv.prom]p2).
1244 if (const EnumType *ET = getAs<EnumType>()){
1245 if (this->isDependentType() || ET->getDecl()->getPromotionType().isNull()
1246 || ET->getDecl()->isScoped())
1249 const BuiltinType *BT
1250 = ET->getDecl()->getPromotionType()->getAs<BuiltinType>();
1251 return BT->getKind() == BuiltinType::Int
1252 || BT->getKind() == BuiltinType::UInt;
1258 bool Type::isNullPtrType() const {
1259 if (const BuiltinType *BT = getAs<BuiltinType>())
1260 return BT->getKind() == BuiltinType::NullPtr;
1264 bool Type::isSpecifierType() const {
1265 // Note that this intentionally does not use the canonical type.
1266 switch (getTypeClass()) {
1274 case TemplateTypeParm:
1275 case SubstTemplateTypeParm:
1276 case TemplateSpecialization:
1279 case DependentTemplateSpecialization:
1282 case ObjCObjectPointer: // FIXME: object pointers aren't really specifiers
1289 ElaboratedTypeKeyword
1290 TypeWithKeyword::getKeywordForTypeSpec(unsigned TypeSpec) {
1292 default: return ETK_None;
1293 case TST_typename: return ETK_Typename;
1294 case TST_class: return ETK_Class;
1295 case TST_struct: return ETK_Struct;
1296 case TST_union: return ETK_Union;
1297 case TST_enum: return ETK_Enum;
1302 TypeWithKeyword::getTagTypeKindForTypeSpec(unsigned TypeSpec) {
1304 case TST_class: return TTK_Class;
1305 case TST_struct: return TTK_Struct;
1306 case TST_union: return TTK_Union;
1307 case TST_enum: return TTK_Enum;
1310 llvm_unreachable("Type specifier is not a tag type kind.");
1314 ElaboratedTypeKeyword
1315 TypeWithKeyword::getKeywordForTagTypeKind(TagTypeKind Kind) {
1317 case TTK_Class: return ETK_Class;
1318 case TTK_Struct: return ETK_Struct;
1319 case TTK_Union: return ETK_Union;
1320 case TTK_Enum: return ETK_Enum;
1322 llvm_unreachable("Unknown tag type kind.");
1326 TypeWithKeyword::getTagTypeKindForKeyword(ElaboratedTypeKeyword Keyword) {
1328 case ETK_Class: return TTK_Class;
1329 case ETK_Struct: return TTK_Struct;
1330 case ETK_Union: return TTK_Union;
1331 case ETK_Enum: return TTK_Enum;
1332 case ETK_None: // Fall through.
1334 llvm_unreachable("Elaborated type keyword is not a tag type kind.");
1336 llvm_unreachable("Unknown elaborated type keyword.");
1340 TypeWithKeyword::KeywordIsTagTypeKind(ElaboratedTypeKeyword Keyword) {
1351 llvm_unreachable("Unknown elaborated type keyword.");
1355 TypeWithKeyword::getKeywordName(ElaboratedTypeKeyword Keyword) {
1357 case ETK_None: return "";
1358 case ETK_Typename: return "typename";
1359 case ETK_Class: return "class";
1360 case ETK_Struct: return "struct";
1361 case ETK_Union: return "union";
1362 case ETK_Enum: return "enum";
1365 llvm_unreachable("Unknown elaborated type keyword.");
1369 DependentTemplateSpecializationType::DependentTemplateSpecializationType(
1370 ElaboratedTypeKeyword Keyword,
1371 NestedNameSpecifier *NNS, const IdentifierInfo *Name,
1372 unsigned NumArgs, const TemplateArgument *Args,
1374 : TypeWithKeyword(Keyword, DependentTemplateSpecialization, Canon, true, true,
1375 /*VariablyModified=*/false,
1376 NNS && NNS->containsUnexpandedParameterPack()),
1377 NNS(NNS), Name(Name), NumArgs(NumArgs) {
1378 assert((!NNS || NNS->isDependent()) &&
1379 "DependentTemplateSpecializatonType requires dependent qualifier");
1380 for (unsigned I = 0; I != NumArgs; ++I) {
1381 if (Args[I].containsUnexpandedParameterPack())
1382 setContainsUnexpandedParameterPack();
1384 new (&getArgBuffer()[I]) TemplateArgument(Args[I]);
1389 DependentTemplateSpecializationType::Profile(llvm::FoldingSetNodeID &ID,
1390 const ASTContext &Context,
1391 ElaboratedTypeKeyword Keyword,
1392 NestedNameSpecifier *Qualifier,
1393 const IdentifierInfo *Name,
1395 const TemplateArgument *Args) {
1396 ID.AddInteger(Keyword);
1397 ID.AddPointer(Qualifier);
1398 ID.AddPointer(Name);
1399 for (unsigned Idx = 0; Idx < NumArgs; ++Idx)
1400 Args[Idx].Profile(ID, Context);
1403 bool Type::isElaboratedTypeSpecifier() const {
1404 ElaboratedTypeKeyword Keyword;
1405 if (const ElaboratedType *Elab = dyn_cast<ElaboratedType>(this))
1406 Keyword = Elab->getKeyword();
1407 else if (const DependentNameType *DepName = dyn_cast<DependentNameType>(this))
1408 Keyword = DepName->getKeyword();
1409 else if (const DependentTemplateSpecializationType *DepTST =
1410 dyn_cast<DependentTemplateSpecializationType>(this))
1411 Keyword = DepTST->getKeyword();
1415 return TypeWithKeyword::KeywordIsTagTypeKind(Keyword);
1418 const char *Type::getTypeClassName() const {
1419 switch (TypeBits.TC) {
1420 #define ABSTRACT_TYPE(Derived, Base)
1421 #define TYPE(Derived, Base) case Derived: return #Derived;
1422 #include "clang/AST/TypeNodes.def"
1425 llvm_unreachable("Invalid type class.");
1429 const char *BuiltinType::getName(const LangOptions &LO) const {
1430 switch (getKind()) {
1431 case Void: return "void";
1432 case Bool: return LO.Bool ? "bool" : "_Bool";
1433 case Char_S: return "char";
1434 case Char_U: return "char";
1435 case SChar: return "signed char";
1436 case Short: return "short";
1437 case Int: return "int";
1438 case Long: return "long";
1439 case LongLong: return "long long";
1440 case Int128: return "__int128_t";
1441 case UChar: return "unsigned char";
1442 case UShort: return "unsigned short";
1443 case UInt: return "unsigned int";
1444 case ULong: return "unsigned long";
1445 case ULongLong: return "unsigned long long";
1446 case UInt128: return "__uint128_t";
1447 case Float: return "float";
1448 case Double: return "double";
1449 case LongDouble: return "long double";
1451 case WChar_U: return "wchar_t";
1452 case Char16: return "char16_t";
1453 case Char32: return "char32_t";
1454 case NullPtr: return "nullptr_t";
1455 case Overload: return "<overloaded function type>";
1456 case BoundMember: return "<bound member function type>";
1457 case Dependent: return "<dependent type>";
1458 case UnknownAny: return "<unknown type>";
1459 case ObjCId: return "id";
1460 case ObjCClass: return "Class";
1461 case ObjCSel: return "SEL";
1464 llvm_unreachable("Invalid builtin type.");
1468 QualType QualType::getNonLValueExprType(ASTContext &Context) const {
1469 if (const ReferenceType *RefType = getTypePtr()->getAs<ReferenceType>())
1470 return RefType->getPointeeType();
1472 // C++0x [basic.lval]:
1473 // Class prvalues can have cv-qualified types; non-class prvalues always
1474 // have cv-unqualified types.
1476 // See also C99 6.3.2.1p2.
1477 if (!Context.getLangOptions().CPlusPlus ||
1478 (!getTypePtr()->isDependentType() && !getTypePtr()->isRecordType()))
1479 return getUnqualifiedType();
1484 llvm::StringRef FunctionType::getNameForCallConv(CallingConv CC) {
1487 llvm_unreachable("no name for default cc");
1490 case CC_C: return "cdecl";
1491 case CC_X86StdCall: return "stdcall";
1492 case CC_X86FastCall: return "fastcall";
1493 case CC_X86ThisCall: return "thiscall";
1494 case CC_X86Pascal: return "pascal";
1495 case CC_AAPCS: return "aapcs";
1496 case CC_AAPCS_VFP: return "aapcs-vfp";
1499 llvm_unreachable("Invalid calling convention.");
1503 FunctionProtoType::FunctionProtoType(QualType result, const QualType *args,
1504 unsigned numArgs, QualType canonical,
1505 const ExtProtoInfo &epi)
1506 : FunctionType(FunctionProto, result, epi.Variadic, epi.TypeQuals,
1507 epi.RefQualifier, canonical,
1508 result->isDependentType(),
1509 result->isInstantiationDependentType(),
1510 result->isVariablyModifiedType(),
1511 result->containsUnexpandedParameterPack(),
1513 NumArgs(numArgs), NumExceptions(epi.NumExceptions),
1514 ExceptionSpecType(epi.ExceptionSpecType),
1515 HasAnyConsumedArgs(epi.ConsumedArguments != 0)
1517 // Fill in the trailing argument array.
1518 QualType *argSlot = reinterpret_cast<QualType*>(this+1);
1519 for (unsigned i = 0; i != numArgs; ++i) {
1520 if (args[i]->isDependentType())
1522 else if (args[i]->isInstantiationDependentType())
1523 setInstantiationDependent();
1525 if (args[i]->containsUnexpandedParameterPack())
1526 setContainsUnexpandedParameterPack();
1528 argSlot[i] = args[i];
1531 if (getExceptionSpecType() == EST_Dynamic) {
1532 // Fill in the exception array.
1533 QualType *exnSlot = argSlot + numArgs;
1534 for (unsigned i = 0, e = epi.NumExceptions; i != e; ++i) {
1535 if (epi.Exceptions[i]->isDependentType())
1537 else if (epi.Exceptions[i]->isInstantiationDependentType())
1538 setInstantiationDependent();
1540 if (epi.Exceptions[i]->containsUnexpandedParameterPack())
1541 setContainsUnexpandedParameterPack();
1543 exnSlot[i] = epi.Exceptions[i];
1545 } else if (getExceptionSpecType() == EST_ComputedNoexcept) {
1546 // Store the noexcept expression and context.
1547 Expr **noexSlot = reinterpret_cast<Expr**>(argSlot + numArgs);
1548 *noexSlot = epi.NoexceptExpr;
1550 if (epi.NoexceptExpr) {
1551 if (epi.NoexceptExpr->isValueDependent()
1552 || epi.NoexceptExpr->isTypeDependent())
1554 else if (epi.NoexceptExpr->isInstantiationDependent())
1555 setInstantiationDependent();
1559 if (epi.ConsumedArguments) {
1560 bool *consumedArgs = const_cast<bool*>(getConsumedArgsBuffer());
1561 for (unsigned i = 0; i != numArgs; ++i)
1562 consumedArgs[i] = epi.ConsumedArguments[i];
1566 FunctionProtoType::NoexceptResult
1567 FunctionProtoType::getNoexceptSpec(ASTContext &ctx) const {
1568 ExceptionSpecificationType est = getExceptionSpecType();
1569 if (est == EST_BasicNoexcept)
1572 if (est != EST_ComputedNoexcept)
1573 return NR_NoNoexcept;
1575 Expr *noexceptExpr = getNoexceptExpr();
1577 return NR_BadNoexcept;
1578 if (noexceptExpr->isValueDependent())
1579 return NR_Dependent;
1582 bool isICE = noexceptExpr->isIntegerConstantExpr(value, ctx, 0,
1583 /*evaluated*/false);
1585 assert(isICE && "AST should not contain bad noexcept expressions.");
1587 return value.getBoolValue() ? NR_Nothrow : NR_Throw;
1590 bool FunctionProtoType::isTemplateVariadic() const {
1591 for (unsigned ArgIdx = getNumArgs(); ArgIdx; --ArgIdx)
1592 if (isa<PackExpansionType>(getArgType(ArgIdx - 1)))
1598 void FunctionProtoType::Profile(llvm::FoldingSetNodeID &ID, QualType Result,
1599 const QualType *ArgTys, unsigned NumArgs,
1600 const ExtProtoInfo &epi,
1601 const ASTContext &Context) {
1603 // We have to be careful not to get ambiguous profile encodings.
1604 // Note that valid type pointers are never ambiguous with anything else.
1606 // The encoding grammar begins:
1607 // type type* bool int bool
1608 // If that final bool is true, then there is a section for the EH spec:
1610 // This is followed by an optional "consumed argument" section of the
1611 // same length as the first type sequence:
1613 // Finally, we have the ext info:
1616 // There is no ambiguity between the consumed arguments and an empty EH
1617 // spec because of the leading 'bool' which unambiguously indicates
1618 // whether the following bool is the EH spec or part of the arguments.
1620 ID.AddPointer(Result.getAsOpaquePtr());
1621 for (unsigned i = 0; i != NumArgs; ++i)
1622 ID.AddPointer(ArgTys[i].getAsOpaquePtr());
1623 // This method is relatively performance sensitive, so as a performance
1624 // shortcut, use one AddInteger call instead of four for the next four
1626 assert(!(unsigned(epi.Variadic) & ~1) &&
1627 !(unsigned(epi.TypeQuals) & ~255) &&
1628 !(unsigned(epi.RefQualifier) & ~3) &&
1629 !(unsigned(epi.ExceptionSpecType) & ~7) &&
1630 "Values larger than expected.");
1631 ID.AddInteger(unsigned(epi.Variadic) +
1632 (epi.TypeQuals << 1) +
1633 (epi.RefQualifier << 9) +
1634 (epi.ExceptionSpecType << 11));
1635 if (epi.ExceptionSpecType == EST_Dynamic) {
1636 for (unsigned i = 0; i != epi.NumExceptions; ++i)
1637 ID.AddPointer(epi.Exceptions[i].getAsOpaquePtr());
1638 } else if (epi.ExceptionSpecType == EST_ComputedNoexcept && epi.NoexceptExpr){
1639 epi.NoexceptExpr->Profile(ID, Context, false);
1641 if (epi.ConsumedArguments) {
1642 for (unsigned i = 0; i != NumArgs; ++i)
1643 ID.AddBoolean(epi.ConsumedArguments[i]);
1645 epi.ExtInfo.Profile(ID);
1648 void FunctionProtoType::Profile(llvm::FoldingSetNodeID &ID,
1649 const ASTContext &Ctx) {
1650 Profile(ID, getResultType(), arg_type_begin(), NumArgs, getExtProtoInfo(),
1654 QualType TypedefType::desugar() const {
1655 return getDecl()->getUnderlyingType();
1658 TypeOfExprType::TypeOfExprType(Expr *E, QualType can)
1659 : Type(TypeOfExpr, can, E->isTypeDependent(),
1660 E->isInstantiationDependent(),
1661 E->getType()->isVariablyModifiedType(),
1662 E->containsUnexpandedParameterPack()),
1666 bool TypeOfExprType::isSugared() const {
1667 return !TOExpr->isTypeDependent();
1670 QualType TypeOfExprType::desugar() const {
1672 return getUnderlyingExpr()->getType();
1674 return QualType(this, 0);
1677 void DependentTypeOfExprType::Profile(llvm::FoldingSetNodeID &ID,
1678 const ASTContext &Context, Expr *E) {
1679 E->Profile(ID, Context, true);
1682 DecltypeType::DecltypeType(Expr *E, QualType underlyingType, QualType can)
1683 : Type(Decltype, can, E->isTypeDependent(),
1684 E->isInstantiationDependent(),
1685 E->getType()->isVariablyModifiedType(),
1686 E->containsUnexpandedParameterPack()),
1688 UnderlyingType(underlyingType) {
1691 bool DecltypeType::isSugared() const { return !E->isInstantiationDependent(); }
1693 QualType DecltypeType::desugar() const {
1695 return getUnderlyingType();
1697 return QualType(this, 0);
1700 DependentDecltypeType::DependentDecltypeType(const ASTContext &Context, Expr *E)
1701 : DecltypeType(E, Context.DependentTy), Context(Context) { }
1703 void DependentDecltypeType::Profile(llvm::FoldingSetNodeID &ID,
1704 const ASTContext &Context, Expr *E) {
1705 E->Profile(ID, Context, true);
1708 TagType::TagType(TypeClass TC, const TagDecl *D, QualType can)
1709 : Type(TC, can, D->isDependentType(),
1710 /*InstantiationDependent=*/D->isDependentType(),
1711 /*VariablyModified=*/false,
1712 /*ContainsUnexpandedParameterPack=*/false),
1713 decl(const_cast<TagDecl*>(D)) {}
1715 static TagDecl *getInterestingTagDecl(TagDecl *decl) {
1716 for (TagDecl::redecl_iterator I = decl->redecls_begin(),
1717 E = decl->redecls_end();
1719 if (I->isDefinition() || I->isBeingDefined())
1722 // If there's no definition (not even in progress), return what we have.
1726 UnaryTransformType::UnaryTransformType(QualType BaseType,
1727 QualType UnderlyingType,
1729 QualType CanonicalType)
1730 : Type(UnaryTransform, CanonicalType, UnderlyingType->isDependentType(),
1731 UnderlyingType->isInstantiationDependentType(),
1732 UnderlyingType->isVariablyModifiedType(),
1733 BaseType->containsUnexpandedParameterPack())
1734 , BaseType(BaseType), UnderlyingType(UnderlyingType), UKind(UKind)
1737 TagDecl *TagType::getDecl() const {
1738 return getInterestingTagDecl(decl);
1741 bool TagType::isBeingDefined() const {
1742 return getDecl()->isBeingDefined();
1745 CXXRecordDecl *InjectedClassNameType::getDecl() const {
1746 return cast<CXXRecordDecl>(getInterestingTagDecl(Decl));
1749 bool RecordType::classof(const TagType *TT) {
1750 return isa<RecordDecl>(TT->getDecl());
1753 bool EnumType::classof(const TagType *TT) {
1754 return isa<EnumDecl>(TT->getDecl());
1757 IdentifierInfo *TemplateTypeParmType::getIdentifier() const {
1758 return isCanonicalUnqualified() ? 0 : getDecl()->getIdentifier();
1761 SubstTemplateTypeParmPackType::
1762 SubstTemplateTypeParmPackType(const TemplateTypeParmType *Param,
1764 const TemplateArgument &ArgPack)
1765 : Type(SubstTemplateTypeParmPack, Canon, true, true, false, true),
1767 Arguments(ArgPack.pack_begin()), NumArguments(ArgPack.pack_size())
1771 TemplateArgument SubstTemplateTypeParmPackType::getArgumentPack() const {
1772 return TemplateArgument(Arguments, NumArguments);
1775 void SubstTemplateTypeParmPackType::Profile(llvm::FoldingSetNodeID &ID) {
1776 Profile(ID, getReplacedParameter(), getArgumentPack());
1779 void SubstTemplateTypeParmPackType::Profile(llvm::FoldingSetNodeID &ID,
1780 const TemplateTypeParmType *Replaced,
1781 const TemplateArgument &ArgPack) {
1782 ID.AddPointer(Replaced);
1783 ID.AddInteger(ArgPack.pack_size());
1784 for (TemplateArgument::pack_iterator P = ArgPack.pack_begin(),
1785 PEnd = ArgPack.pack_end();
1787 ID.AddPointer(P->getAsType().getAsOpaquePtr());
1790 bool TemplateSpecializationType::
1791 anyDependentTemplateArguments(const TemplateArgumentListInfo &Args,
1792 bool &InstantiationDependent) {
1793 return anyDependentTemplateArguments(Args.getArgumentArray(), Args.size(),
1794 InstantiationDependent);
1797 bool TemplateSpecializationType::
1798 anyDependentTemplateArguments(const TemplateArgumentLoc *Args, unsigned N,
1799 bool &InstantiationDependent) {
1800 for (unsigned i = 0; i != N; ++i) {
1801 if (Args[i].getArgument().isDependent()) {
1802 InstantiationDependent = true;
1806 if (Args[i].getArgument().isInstantiationDependent())
1807 InstantiationDependent = true;
1812 bool TemplateSpecializationType::
1813 anyDependentTemplateArguments(const TemplateArgument *Args, unsigned N,
1814 bool &InstantiationDependent) {
1815 for (unsigned i = 0; i != N; ++i) {
1816 if (Args[i].isDependent()) {
1817 InstantiationDependent = true;
1821 if (Args[i].isInstantiationDependent())
1822 InstantiationDependent = true;
1827 TemplateSpecializationType::
1828 TemplateSpecializationType(TemplateName T,
1829 const TemplateArgument *Args, unsigned NumArgs,
1830 QualType Canon, QualType AliasedType)
1831 : Type(TemplateSpecialization,
1832 Canon.isNull()? QualType(this, 0) : Canon,
1833 Canon.isNull()? T.isDependent() : Canon->isDependentType(),
1834 Canon.isNull()? T.isDependent()
1835 : Canon->isInstantiationDependentType(),
1836 false, T.containsUnexpandedParameterPack()),
1837 Template(T), NumArgs(NumArgs) {
1838 assert(!T.getAsDependentTemplateName() &&
1839 "Use DependentTemplateSpecializationType for dependent template-name");
1840 assert((T.getKind() == TemplateName::Template ||
1841 T.getKind() == TemplateName::SubstTemplateTemplateParm ||
1842 T.getKind() == TemplateName::SubstTemplateTemplateParmPack) &&
1843 "Unexpected template name for TemplateSpecializationType");
1844 bool InstantiationDependent;
1845 (void)InstantiationDependent;
1846 assert((!Canon.isNull() ||
1848 anyDependentTemplateArguments(Args, NumArgs,
1849 InstantiationDependent)) &&
1850 "No canonical type for non-dependent class template specialization");
1852 TemplateArgument *TemplateArgs
1853 = reinterpret_cast<TemplateArgument *>(this + 1);
1854 for (unsigned Arg = 0; Arg < NumArgs; ++Arg) {
1855 // Update dependent and variably-modified bits.
1856 // If the canonical type exists and is non-dependent, the template
1857 // specialization type can be non-dependent even if one of the type
1858 // arguments is. Given:
1859 // template<typename T> using U = int;
1860 // U<T> is always non-dependent, irrespective of the type T.
1861 if (Canon.isNull() && Args[Arg].isDependent())
1863 else if (Args[Arg].isInstantiationDependent())
1864 setInstantiationDependent();
1866 if (Args[Arg].getKind() == TemplateArgument::Type &&
1867 Args[Arg].getAsType()->isVariablyModifiedType())
1868 setVariablyModified();
1869 if (Args[Arg].containsUnexpandedParameterPack())
1870 setContainsUnexpandedParameterPack();
1872 new (&TemplateArgs[Arg]) TemplateArgument(Args[Arg]);
1875 // Store the aliased type if this is a type alias template specialization.
1876 bool IsTypeAlias = !AliasedType.isNull();
1877 assert(IsTypeAlias == isTypeAlias() &&
1878 "allocated wrong size for type alias");
1880 TemplateArgument *Begin = reinterpret_cast<TemplateArgument *>(this + 1);
1881 *reinterpret_cast<QualType*>(Begin + getNumArgs()) = AliasedType;
1886 TemplateSpecializationType::Profile(llvm::FoldingSetNodeID &ID,
1888 const TemplateArgument *Args,
1890 const ASTContext &Context) {
1892 for (unsigned Idx = 0; Idx < NumArgs; ++Idx)
1893 Args[Idx].Profile(ID, Context);
1896 bool TemplateSpecializationType::isTypeAlias() const {
1897 TemplateDecl *D = Template.getAsTemplateDecl();
1898 return D && isa<TypeAliasTemplateDecl>(D);
1902 QualifierCollector::apply(const ASTContext &Context, QualType QT) const {
1903 if (!hasNonFastQualifiers())
1904 return QT.withFastQualifiers(getFastQualifiers());
1906 return Context.getQualifiedType(QT, *this);
1910 QualifierCollector::apply(const ASTContext &Context, const Type *T) const {
1911 if (!hasNonFastQualifiers())
1912 return QualType(T, getFastQualifiers());
1914 return Context.getQualifiedType(T, *this);
1917 void ObjCObjectTypeImpl::Profile(llvm::FoldingSetNodeID &ID,
1919 ObjCProtocolDecl * const *Protocols,
1920 unsigned NumProtocols) {
1921 ID.AddPointer(BaseType.getAsOpaquePtr());
1922 for (unsigned i = 0; i != NumProtocols; i++)
1923 ID.AddPointer(Protocols[i]);
1926 void ObjCObjectTypeImpl::Profile(llvm::FoldingSetNodeID &ID) {
1927 Profile(ID, getBaseType(), qual_begin(), getNumProtocols());
1932 /// \brief The cached properties of a type.
1933 class CachedProperties {
1939 CachedProperties(Linkage linkage, Visibility visibility, bool local)
1940 : linkage(linkage), visibility(visibility), local(local) {}
1942 Linkage getLinkage() const { return (Linkage) linkage; }
1943 Visibility getVisibility() const { return (Visibility) visibility; }
1944 bool hasLocalOrUnnamedType() const { return local; }
1946 friend CachedProperties merge(CachedProperties L, CachedProperties R) {
1947 return CachedProperties(minLinkage(L.getLinkage(), R.getLinkage()),
1948 minVisibility(L.getVisibility(), R.getVisibility()),
1949 L.hasLocalOrUnnamedType() | R.hasLocalOrUnnamedType());
1954 static CachedProperties computeCachedProperties(const Type *T);
1957 /// The type-property cache. This is templated so as to be
1958 /// instantiated at an internal type to prevent unnecessary symbol
1960 template <class Private> class TypePropertyCache {
1962 static CachedProperties get(QualType T) {
1963 return get(T.getTypePtr());
1966 static CachedProperties get(const Type *T) {
1968 return CachedProperties(T->TypeBits.getLinkage(),
1969 T->TypeBits.getVisibility(),
1970 T->TypeBits.hasLocalOrUnnamedType());
1973 static void ensure(const Type *T) {
1974 // If the cache is valid, we're okay.
1975 if (T->TypeBits.isCacheValid()) return;
1977 // If this type is non-canonical, ask its canonical type for the
1978 // relevant information.
1979 if (!T->isCanonicalUnqualified()) {
1980 const Type *CT = T->getCanonicalTypeInternal().getTypePtr();
1982 T->TypeBits.CacheValidAndVisibility =
1983 CT->TypeBits.CacheValidAndVisibility;
1984 T->TypeBits.CachedLinkage = CT->TypeBits.CachedLinkage;
1985 T->TypeBits.CachedLocalOrUnnamed = CT->TypeBits.CachedLocalOrUnnamed;
1989 // Compute the cached properties and then set the cache.
1990 CachedProperties Result = computeCachedProperties(T);
1991 T->TypeBits.CacheValidAndVisibility = Result.getVisibility() + 1U;
1992 assert(T->TypeBits.isCacheValid() &&
1993 T->TypeBits.getVisibility() == Result.getVisibility());
1994 T->TypeBits.CachedLinkage = Result.getLinkage();
1995 T->TypeBits.CachedLocalOrUnnamed = Result.hasLocalOrUnnamedType();
2000 // Instantiate the friend template at a private class. In a
2001 // reasonable implementation, these symbols will be internal.
2002 // It is terrible that this is the best way to accomplish this.
2003 namespace { class Private {}; }
2004 typedef TypePropertyCache<Private> Cache;
2006 static CachedProperties computeCachedProperties(const Type *T) {
2007 switch (T->getTypeClass()) {
2008 #define TYPE(Class,Base)
2009 #define NON_CANONICAL_TYPE(Class,Base) case Type::Class:
2010 #include "clang/AST/TypeNodes.def"
2011 llvm_unreachable("didn't expect a non-canonical type here");
2013 #define TYPE(Class,Base)
2014 #define DEPENDENT_TYPE(Class,Base) case Type::Class:
2015 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class,Base) case Type::Class:
2016 #include "clang/AST/TypeNodes.def"
2017 // Treat instantiation-dependent types as external.
2018 assert(T->isInstantiationDependentType());
2019 return CachedProperties(ExternalLinkage, DefaultVisibility, false);
2022 // C++ [basic.link]p8:
2023 // A type is said to have linkage if and only if:
2024 // - it is a fundamental type (3.9.1); or
2025 return CachedProperties(ExternalLinkage, DefaultVisibility, false);
2029 const TagDecl *Tag = cast<TagType>(T)->getDecl();
2031 // C++ [basic.link]p8:
2032 // - it is a class or enumeration type that is named (or has a name
2033 // for linkage purposes (7.1.3)) and the name has linkage; or
2034 // - it is a specialization of a class template (14); or
2035 NamedDecl::LinkageInfo LV = Tag->getLinkageAndVisibility();
2036 bool IsLocalOrUnnamed =
2037 Tag->getDeclContext()->isFunctionOrMethod() ||
2038 (!Tag->getIdentifier() && !Tag->getTypedefNameForAnonDecl());
2039 return CachedProperties(LV.linkage(), LV.visibility(), IsLocalOrUnnamed);
2042 // C++ [basic.link]p8:
2043 // - it is a compound type (3.9.2) other than a class or enumeration,
2044 // compounded exclusively from types that have linkage; or
2046 return Cache::get(cast<ComplexType>(T)->getElementType());
2048 return Cache::get(cast<PointerType>(T)->getPointeeType());
2049 case Type::BlockPointer:
2050 return Cache::get(cast<BlockPointerType>(T)->getPointeeType());
2051 case Type::LValueReference:
2052 case Type::RValueReference:
2053 return Cache::get(cast<ReferenceType>(T)->getPointeeType());
2054 case Type::MemberPointer: {
2055 const MemberPointerType *MPT = cast<MemberPointerType>(T);
2056 return merge(Cache::get(MPT->getClass()),
2057 Cache::get(MPT->getPointeeType()));
2059 case Type::ConstantArray:
2060 case Type::IncompleteArray:
2061 case Type::VariableArray:
2062 return Cache::get(cast<ArrayType>(T)->getElementType());
2064 case Type::ExtVector:
2065 return Cache::get(cast<VectorType>(T)->getElementType());
2066 case Type::FunctionNoProto:
2067 return Cache::get(cast<FunctionType>(T)->getResultType());
2068 case Type::FunctionProto: {
2069 const FunctionProtoType *FPT = cast<FunctionProtoType>(T);
2070 CachedProperties result = Cache::get(FPT->getResultType());
2071 for (FunctionProtoType::arg_type_iterator ai = FPT->arg_type_begin(),
2072 ae = FPT->arg_type_end(); ai != ae; ++ai)
2073 result = merge(result, Cache::get(*ai));
2076 case Type::ObjCInterface: {
2077 NamedDecl::LinkageInfo LV =
2078 cast<ObjCInterfaceType>(T)->getDecl()->getLinkageAndVisibility();
2079 return CachedProperties(LV.linkage(), LV.visibility(), false);
2081 case Type::ObjCObject:
2082 return Cache::get(cast<ObjCObjectType>(T)->getBaseType());
2083 case Type::ObjCObjectPointer:
2084 return Cache::get(cast<ObjCObjectPointerType>(T)->getPointeeType());
2087 llvm_unreachable("unhandled type class");
2089 // C++ [basic.link]p8:
2090 // Names not covered by these rules have no linkage.
2091 return CachedProperties(NoLinkage, DefaultVisibility, false);
2094 /// \brief Determine the linkage of this type.
2095 Linkage Type::getLinkage() const {
2096 Cache::ensure(this);
2097 return TypeBits.getLinkage();
2100 /// \brief Determine the linkage of this type.
2101 Visibility Type::getVisibility() const {
2102 Cache::ensure(this);
2103 return TypeBits.getVisibility();
2106 bool Type::hasUnnamedOrLocalType() const {
2107 Cache::ensure(this);
2108 return TypeBits.hasLocalOrUnnamedType();
2111 std::pair<Linkage,Visibility> Type::getLinkageAndVisibility() const {
2112 Cache::ensure(this);
2113 return std::make_pair(TypeBits.getLinkage(), TypeBits.getVisibility());
2116 void Type::ClearLinkageCache() {
2117 TypeBits.CacheValidAndVisibility = 0;
2118 if (QualType(this, 0) != CanonicalType)
2119 CanonicalType->TypeBits.CacheValidAndVisibility = 0;
2122 Qualifiers::ObjCLifetime Type::getObjCARCImplicitLifetime() const {
2123 if (isObjCARCImplicitlyUnretainedType())
2124 return Qualifiers::OCL_ExplicitNone;
2125 return Qualifiers::OCL_Strong;
2128 bool Type::isObjCARCImplicitlyUnretainedType() const {
2129 assert(isObjCLifetimeType() &&
2130 "cannot query implicit lifetime for non-inferrable type");
2132 const Type *canon = getCanonicalTypeInternal().getTypePtr();
2134 // Walk down to the base type. We don't care about qualifiers for this.
2135 while (const ArrayType *array = dyn_cast<ArrayType>(canon))
2136 canon = array->getElementType().getTypePtr();
2138 if (const ObjCObjectPointerType *opt
2139 = dyn_cast<ObjCObjectPointerType>(canon)) {
2140 // Class and Class<Protocol> don't require retension.
2141 if (opt->getObjectType()->isObjCClass())
2148 bool Type::isObjCNSObjectType() const {
2149 if (const TypedefType *typedefType = dyn_cast<TypedefType>(this))
2150 return typedefType->getDecl()->hasAttr<ObjCNSObjectAttr>();
2153 bool Type::isObjCRetainableType() const {
2154 return isObjCObjectPointerType() ||
2155 isBlockPointerType() ||
2156 isObjCNSObjectType();
2158 bool Type::isObjCIndirectLifetimeType() const {
2159 if (isObjCLifetimeType())
2161 if (const PointerType *OPT = getAs<PointerType>())
2162 return OPT->getPointeeType()->isObjCIndirectLifetimeType();
2163 if (const ReferenceType *Ref = getAs<ReferenceType>())
2164 return Ref->getPointeeType()->isObjCIndirectLifetimeType();
2165 if (const MemberPointerType *MemPtr = getAs<MemberPointerType>())
2166 return MemPtr->getPointeeType()->isObjCIndirectLifetimeType();
2170 /// Returns true if objects of this type have lifetime semantics under
2172 bool Type::isObjCLifetimeType() const {
2173 const Type *type = this;
2174 while (const ArrayType *array = type->getAsArrayTypeUnsafe())
2175 type = array->getElementType().getTypePtr();
2176 return type->isObjCRetainableType();
2179 /// \brief Determine whether the given type T is a "bridgable" Objective-C type,
2180 /// which is either an Objective-C object pointer type or an
2181 bool Type::isObjCARCBridgableType() const {
2182 return isObjCObjectPointerType() || isBlockPointerType();
2185 /// \brief Determine whether the given type T is a "bridgeable" C type.
2186 bool Type::isCARCBridgableType() const {
2187 const PointerType *Pointer = getAs<PointerType>();
2191 QualType Pointee = Pointer->getPointeeType();
2192 return Pointee->isVoidType() || Pointee->isRecordType();
2195 bool Type::hasSizedVLAType() const {
2196 if (!isVariablyModifiedType()) return false;
2198 if (const PointerType *ptr = getAs<PointerType>())
2199 return ptr->getPointeeType()->hasSizedVLAType();
2200 if (const ReferenceType *ref = getAs<ReferenceType>())
2201 return ref->getPointeeType()->hasSizedVLAType();
2202 if (const ArrayType *arr = getAsArrayTypeUnsafe()) {
2203 if (isa<VariableArrayType>(arr) &&
2204 cast<VariableArrayType>(arr)->getSizeExpr())
2207 return arr->getElementType()->hasSizedVLAType();
2213 QualType::DestructionKind QualType::isDestructedTypeImpl(QualType type) {
2214 switch (type.getObjCLifetime()) {
2215 case Qualifiers::OCL_None:
2216 case Qualifiers::OCL_ExplicitNone:
2217 case Qualifiers::OCL_Autoreleasing:
2220 case Qualifiers::OCL_Strong:
2221 return DK_objc_strong_lifetime;
2222 case Qualifiers::OCL_Weak:
2223 return DK_objc_weak_lifetime;
2226 /// Currently, the only destruction kind we recognize is C++ objects
2227 /// with non-trivial destructors.
2228 const CXXRecordDecl *record =
2229 type->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
2230 if (record && !record->hasTrivialDestructor())
2231 return DK_cxx_destructor;
2236 bool QualType::hasTrivialCopyAssignment(ASTContext &Context) const {
2237 switch (getObjCLifetime()) {
2238 case Qualifiers::OCL_None:
2241 case Qualifiers::OCL_ExplicitNone:
2244 case Qualifiers::OCL_Autoreleasing:
2245 case Qualifiers::OCL_Strong:
2246 case Qualifiers::OCL_Weak:
2247 return !Context.getLangOptions().ObjCAutoRefCount;
2250 if (const CXXRecordDecl *Record
2251 = getTypePtr()->getBaseElementTypeUnsafe()->getAsCXXRecordDecl())
2252 return Record->hasTrivialCopyAssignment();