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 const IdentifierInfo* QualType::getBaseTypeIdentifier() const {
46 const Type* ty = getTypePtr();
48 if (ty->isPointerType() || ty->isReferenceType())
49 return ty->getPointeeType().getBaseTypeIdentifier();
50 else if (ty->isRecordType())
51 ND = ty->getAs<RecordType>()->getDecl();
52 else if (ty->isEnumeralType())
53 ND = ty->getAs<EnumType>()->getDecl();
54 else if (ty->getTypeClass() == Type::Typedef)
55 ND = ty->getAs<TypedefType>()->getDecl();
56 else if (ty->isArrayType())
57 return ty->castAsArrayTypeUnsafe()->
58 getElementType().getBaseTypeIdentifier();
61 return ND->getIdentifier();
65 bool QualType::isConstant(QualType T, ASTContext &Ctx) {
66 if (T.isConstQualified())
69 if (const ArrayType *AT = Ctx.getAsArrayType(T))
70 return AT->getElementType().isConstant(Ctx);
75 unsigned ConstantArrayType::getNumAddressingBits(ASTContext &Context,
77 const llvm::APInt &NumElements) {
78 llvm::APSInt SizeExtended(NumElements, true);
79 unsigned SizeTypeBits = Context.getTypeSize(Context.getSizeType());
80 SizeExtended = SizeExtended.extend(std::max(SizeTypeBits,
81 SizeExtended.getBitWidth()) * 2);
84 = Context.getTypeSizeInChars(ElementType).getQuantity();
85 llvm::APSInt TotalSize(llvm::APInt(SizeExtended.getBitWidth(), ElementSize));
86 TotalSize *= SizeExtended;
88 return TotalSize.getActiveBits();
91 unsigned ConstantArrayType::getMaxSizeBits(ASTContext &Context) {
92 unsigned Bits = Context.getTypeSize(Context.getSizeType());
94 // GCC appears to only allow 63 bits worth of address space when compiling
95 // for 64-bit, so we do the same.
102 DependentSizedArrayType::DependentSizedArrayType(const ASTContext &Context,
103 QualType et, QualType can,
104 Expr *e, ArraySizeModifier sm,
106 SourceRange brackets)
107 : ArrayType(DependentSizedArray, et, can, sm, tq,
108 (et->containsUnexpandedParameterPack() ||
109 (e && e->containsUnexpandedParameterPack()))),
110 Context(Context), SizeExpr((Stmt*) e), Brackets(brackets)
114 void DependentSizedArrayType::Profile(llvm::FoldingSetNodeID &ID,
115 const ASTContext &Context,
117 ArraySizeModifier SizeMod,
120 ID.AddPointer(ET.getAsOpaquePtr());
121 ID.AddInteger(SizeMod);
122 ID.AddInteger(TypeQuals);
123 E->Profile(ID, Context, true);
126 DependentSizedExtVectorType::DependentSizedExtVectorType(const
128 QualType ElementType,
132 : Type(DependentSizedExtVector, can, /*Dependent=*/true,
133 /*InstantiationDependent=*/true,
134 ElementType->isVariablyModifiedType(),
135 (ElementType->containsUnexpandedParameterPack() ||
136 (SizeExpr && SizeExpr->containsUnexpandedParameterPack()))),
137 Context(Context), SizeExpr(SizeExpr), ElementType(ElementType),
143 DependentSizedExtVectorType::Profile(llvm::FoldingSetNodeID &ID,
144 const ASTContext &Context,
145 QualType ElementType, Expr *SizeExpr) {
146 ID.AddPointer(ElementType.getAsOpaquePtr());
147 SizeExpr->Profile(ID, Context, true);
150 VectorType::VectorType(QualType vecType, unsigned nElements, QualType canonType,
152 : Type(Vector, canonType, vecType->isDependentType(),
153 vecType->isInstantiationDependentType(),
154 vecType->isVariablyModifiedType(),
155 vecType->containsUnexpandedParameterPack()),
158 VectorTypeBits.VecKind = vecKind;
159 VectorTypeBits.NumElements = nElements;
162 VectorType::VectorType(TypeClass tc, QualType vecType, unsigned nElements,
163 QualType canonType, VectorKind vecKind)
164 : Type(tc, canonType, vecType->isDependentType(),
165 vecType->isInstantiationDependentType(),
166 vecType->isVariablyModifiedType(),
167 vecType->containsUnexpandedParameterPack()),
170 VectorTypeBits.VecKind = vecKind;
171 VectorTypeBits.NumElements = nElements;
174 /// getArrayElementTypeNoTypeQual - If this is an array type, return the
175 /// element type of the array, potentially with type qualifiers missing.
176 /// This method should never be used when type qualifiers are meaningful.
177 const Type *Type::getArrayElementTypeNoTypeQual() const {
178 // If this is directly an array type, return it.
179 if (const ArrayType *ATy = dyn_cast<ArrayType>(this))
180 return ATy->getElementType().getTypePtr();
182 // If the canonical form of this type isn't the right kind, reject it.
183 if (!isa<ArrayType>(CanonicalType))
186 // If this is a typedef for an array type, strip the typedef off without
187 // losing all typedef information.
188 return cast<ArrayType>(getUnqualifiedDesugaredType())
189 ->getElementType().getTypePtr();
192 /// getDesugaredType - Return the specified type with any "sugar" removed from
193 /// the type. This takes off typedefs, typeof's etc. If the outer level of
194 /// the type is already concrete, it returns it unmodified. This is similar
195 /// to getting the canonical type, but it doesn't remove *all* typedefs. For
196 /// example, it returns "T*" as "T*", (not as "int*"), because the pointer is
198 QualType QualType::getDesugaredType(QualType T, const ASTContext &Context) {
199 SplitQualType split = getSplitDesugaredType(T);
200 return Context.getQualifiedType(split.Ty, split.Quals);
203 QualType QualType::getSingleStepDesugaredTypeImpl(QualType type,
204 const ASTContext &Context) {
205 SplitQualType split = type.split();
206 QualType desugar = split.Ty->getLocallyUnqualifiedSingleStepDesugaredType();
207 return Context.getQualifiedType(desugar, split.Quals);
210 QualType Type::getLocallyUnqualifiedSingleStepDesugaredType() const {
211 switch (getTypeClass()) {
212 #define ABSTRACT_TYPE(Class, Parent)
213 #define TYPE(Class, Parent) \
214 case Type::Class: { \
215 const Class##Type *ty = cast<Class##Type>(this); \
216 if (!ty->isSugared()) return QualType(ty, 0); \
217 return ty->desugar(); \
219 #include "clang/AST/TypeNodes.def"
221 llvm_unreachable("bad type kind!");
224 SplitQualType QualType::getSplitDesugaredType(QualType T) {
225 QualifierCollector Qs;
229 const Type *CurTy = Qs.strip(Cur);
230 switch (CurTy->getTypeClass()) {
231 #define ABSTRACT_TYPE(Class, Parent)
232 #define TYPE(Class, Parent) \
233 case Type::Class: { \
234 const Class##Type *Ty = cast<Class##Type>(CurTy); \
235 if (!Ty->isSugared()) \
236 return SplitQualType(Ty, Qs); \
237 Cur = Ty->desugar(); \
240 #include "clang/AST/TypeNodes.def"
245 SplitQualType QualType::getSplitUnqualifiedTypeImpl(QualType type) {
246 SplitQualType split = type.split();
248 // All the qualifiers we've seen so far.
249 Qualifiers quals = split.Quals;
251 // The last type node we saw with any nodes inside it.
252 const Type *lastTypeWithQuals = split.Ty;
257 // Do a single-step desugar, aborting the loop if the type isn't
259 switch (split.Ty->getTypeClass()) {
260 #define ABSTRACT_TYPE(Class, Parent)
261 #define TYPE(Class, Parent) \
262 case Type::Class: { \
263 const Class##Type *ty = cast<Class##Type>(split.Ty); \
264 if (!ty->isSugared()) goto done; \
265 next = ty->desugar(); \
268 #include "clang/AST/TypeNodes.def"
271 // Otherwise, split the underlying type. If that yields qualifiers,
272 // update the information.
273 split = next.split();
274 if (!split.Quals.empty()) {
275 lastTypeWithQuals = split.Ty;
276 quals.addConsistentQualifiers(split.Quals);
281 return SplitQualType(lastTypeWithQuals, quals);
284 QualType QualType::IgnoreParens(QualType T) {
285 // FIXME: this seems inherently un-qualifiers-safe.
286 while (const ParenType *PT = T->getAs<ParenType>())
287 T = PT->getInnerType();
291 /// \brief This will check for a T (which should be a Type which can act as
292 /// sugar, such as a TypedefType) by removing any existing sugar until it
293 /// reaches a T or a non-sugared type.
294 template<typename T> static const T *getAsSugar(const Type *Cur) {
296 if (const T *Sugar = dyn_cast<T>(Cur))
298 switch (Cur->getTypeClass()) {
299 #define ABSTRACT_TYPE(Class, Parent)
300 #define TYPE(Class, Parent) \
301 case Type::Class: { \
302 const Class##Type *Ty = cast<Class##Type>(Cur); \
303 if (!Ty->isSugared()) return 0; \
304 Cur = Ty->desugar().getTypePtr(); \
307 #include "clang/AST/TypeNodes.def"
312 template <> const TypedefType *Type::getAs() const {
313 return getAsSugar<TypedefType>(this);
316 template <> const TemplateSpecializationType *Type::getAs() const {
317 return getAsSugar<TemplateSpecializationType>(this);
320 /// getUnqualifiedDesugaredType - Pull any qualifiers and syntactic
321 /// sugar off the given type. This should produce an object of the
322 /// same dynamic type as the canonical type.
323 const Type *Type::getUnqualifiedDesugaredType() const {
324 const Type *Cur = this;
327 switch (Cur->getTypeClass()) {
328 #define ABSTRACT_TYPE(Class, Parent)
329 #define TYPE(Class, Parent) \
331 const Class##Type *Ty = cast<Class##Type>(Cur); \
332 if (!Ty->isSugared()) return Cur; \
333 Cur = Ty->desugar().getTypePtr(); \
336 #include "clang/AST/TypeNodes.def"
341 bool Type::isDerivedType() const {
342 switch (CanonicalType->getTypeClass()) {
346 case IncompleteArray:
348 case FunctionNoProto:
349 case LValueReference:
350 case RValueReference:
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::isInterfaceType() const {
368 if (const RecordType *RT = getAs<RecordType>())
369 return RT->getDecl()->isInterface();
372 bool Type::isStructureOrClassType() const {
373 if (const RecordType *RT = getAs<RecordType>())
374 return RT->getDecl()->isStruct() || RT->getDecl()->isClass() ||
375 RT->getDecl()->isInterface();
378 bool Type::isVoidPointerType() const {
379 if (const PointerType *PT = getAs<PointerType>())
380 return PT->getPointeeType()->isVoidType();
384 bool Type::isUnionType() const {
385 if (const RecordType *RT = getAs<RecordType>())
386 return RT->getDecl()->isUnion();
390 bool Type::isComplexType() const {
391 if (const ComplexType *CT = dyn_cast<ComplexType>(CanonicalType))
392 return CT->getElementType()->isFloatingType();
396 bool Type::isComplexIntegerType() const {
397 // Check for GCC complex integer extension.
398 return getAsComplexIntegerType();
401 const ComplexType *Type::getAsComplexIntegerType() const {
402 if (const ComplexType *Complex = getAs<ComplexType>())
403 if (Complex->getElementType()->isIntegerType())
408 QualType Type::getPointeeType() const {
409 if (const PointerType *PT = getAs<PointerType>())
410 return PT->getPointeeType();
411 if (const ObjCObjectPointerType *OPT = getAs<ObjCObjectPointerType>())
412 return OPT->getPointeeType();
413 if (const BlockPointerType *BPT = getAs<BlockPointerType>())
414 return BPT->getPointeeType();
415 if (const ReferenceType *RT = getAs<ReferenceType>())
416 return RT->getPointeeType();
420 const RecordType *Type::getAsStructureType() const {
421 // If this is directly a structure type, return it.
422 if (const RecordType *RT = dyn_cast<RecordType>(this)) {
423 if (RT->getDecl()->isStruct())
427 // If the canonical form of this type isn't the right kind, reject it.
428 if (const RecordType *RT = dyn_cast<RecordType>(CanonicalType)) {
429 if (!RT->getDecl()->isStruct())
432 // If this is a typedef for a structure type, strip the typedef off without
433 // losing all typedef information.
434 return cast<RecordType>(getUnqualifiedDesugaredType());
439 const RecordType *Type::getAsUnionType() const {
440 // If this is directly a union type, return it.
441 if (const RecordType *RT = dyn_cast<RecordType>(this)) {
442 if (RT->getDecl()->isUnion())
446 // If the canonical form of this type isn't the right kind, reject it.
447 if (const RecordType *RT = dyn_cast<RecordType>(CanonicalType)) {
448 if (!RT->getDecl()->isUnion())
451 // If this is a typedef for a union type, strip the typedef off without
452 // losing all typedef information.
453 return cast<RecordType>(getUnqualifiedDesugaredType());
459 ObjCObjectType::ObjCObjectType(QualType Canonical, QualType Base,
460 ObjCProtocolDecl * const *Protocols,
461 unsigned NumProtocols)
462 : Type(ObjCObject, Canonical, false, false, false, false),
465 ObjCObjectTypeBits.NumProtocols = NumProtocols;
466 assert(getNumProtocols() == NumProtocols &&
467 "bitfield overflow in protocol count");
469 memcpy(getProtocolStorage(), Protocols,
470 NumProtocols * sizeof(ObjCProtocolDecl*));
473 const ObjCObjectType *Type::getAsObjCQualifiedInterfaceType() const {
474 // There is no sugar for ObjCObjectType's, just return the canonical
475 // type pointer if it is the right class. There is no typedef information to
476 // return and these cannot be Address-space qualified.
477 if (const ObjCObjectType *T = getAs<ObjCObjectType>())
478 if (T->getNumProtocols() && T->getInterface())
483 bool Type::isObjCQualifiedInterfaceType() const {
484 return getAsObjCQualifiedInterfaceType() != 0;
487 const ObjCObjectPointerType *Type::getAsObjCQualifiedIdType() const {
488 // There is no sugar for ObjCQualifiedIdType's, just return the canonical
489 // type pointer if it is the right class.
490 if (const ObjCObjectPointerType *OPT = getAs<ObjCObjectPointerType>()) {
491 if (OPT->isObjCQualifiedIdType())
497 const ObjCObjectPointerType *Type::getAsObjCQualifiedClassType() const {
498 // There is no sugar for ObjCQualifiedClassType's, just return the canonical
499 // type pointer if it is the right class.
500 if (const ObjCObjectPointerType *OPT = getAs<ObjCObjectPointerType>()) {
501 if (OPT->isObjCQualifiedClassType())
507 const ObjCObjectPointerType *Type::getAsObjCInterfacePointerType() const {
508 if (const ObjCObjectPointerType *OPT = getAs<ObjCObjectPointerType>()) {
509 if (OPT->getInterfaceType())
515 const CXXRecordDecl *Type::getPointeeCXXRecordDecl() const {
516 QualType PointeeType;
517 if (const PointerType *PT = getAs<PointerType>())
518 PointeeType = PT->getPointeeType();
519 else if (const ReferenceType *RT = getAs<ReferenceType>())
520 PointeeType = RT->getPointeeType();
524 if (const RecordType *RT = PointeeType->getAs<RecordType>())
525 return dyn_cast<CXXRecordDecl>(RT->getDecl());
530 CXXRecordDecl *Type::getAsCXXRecordDecl() const {
531 if (const RecordType *RT = getAs<RecordType>())
532 return dyn_cast<CXXRecordDecl>(RT->getDecl());
533 else if (const InjectedClassNameType *Injected
534 = getAs<InjectedClassNameType>())
535 return Injected->getDecl();
541 class GetContainedAutoVisitor :
542 public TypeVisitor<GetContainedAutoVisitor, AutoType*> {
544 using TypeVisitor<GetContainedAutoVisitor, AutoType*>::Visit;
545 AutoType *Visit(QualType T) {
548 return Visit(T.getTypePtr());
551 // The 'auto' type itself.
552 AutoType *VisitAutoType(const AutoType *AT) {
553 return const_cast<AutoType*>(AT);
556 // Only these types can contain the desired 'auto' type.
557 AutoType *VisitPointerType(const PointerType *T) {
558 return Visit(T->getPointeeType());
560 AutoType *VisitBlockPointerType(const BlockPointerType *T) {
561 return Visit(T->getPointeeType());
563 AutoType *VisitReferenceType(const ReferenceType *T) {
564 return Visit(T->getPointeeTypeAsWritten());
566 AutoType *VisitMemberPointerType(const MemberPointerType *T) {
567 return Visit(T->getPointeeType());
569 AutoType *VisitArrayType(const ArrayType *T) {
570 return Visit(T->getElementType());
572 AutoType *VisitDependentSizedExtVectorType(
573 const DependentSizedExtVectorType *T) {
574 return Visit(T->getElementType());
576 AutoType *VisitVectorType(const VectorType *T) {
577 return Visit(T->getElementType());
579 AutoType *VisitFunctionType(const FunctionType *T) {
580 return Visit(T->getResultType());
582 AutoType *VisitParenType(const ParenType *T) {
583 return Visit(T->getInnerType());
585 AutoType *VisitAttributedType(const AttributedType *T) {
586 return Visit(T->getModifiedType());
591 AutoType *Type::getContainedAutoType() const {
592 return GetContainedAutoVisitor().Visit(this);
595 bool Type::hasIntegerRepresentation() const {
596 if (const VectorType *VT = dyn_cast<VectorType>(CanonicalType))
597 return VT->getElementType()->isIntegerType();
599 return isIntegerType();
602 /// \brief Determine whether this type is an integral type.
604 /// This routine determines whether the given type is an integral type per
605 /// C++ [basic.fundamental]p7. Although the C standard does not define the
606 /// term "integral type", it has a similar term "integer type", and in C++
607 /// the two terms are equivalent. However, C's "integer type" includes
608 /// enumeration types, while C++'s "integer type" does not. The \c ASTContext
609 /// parameter is used to determine whether we should be following the C or
610 /// C++ rules when determining whether this type is an integral/integer type.
612 /// For cases where C permits "an integer type" and C++ permits "an integral
613 /// type", use this routine.
615 /// For cases where C permits "an integer type" and C++ permits "an integral
616 /// or enumeration type", use \c isIntegralOrEnumerationType() instead.
618 /// \param Ctx The context in which this type occurs.
620 /// \returns true if the type is considered an integral type, false otherwise.
621 bool Type::isIntegralType(ASTContext &Ctx) const {
622 if (const BuiltinType *BT = dyn_cast<BuiltinType>(CanonicalType))
623 return BT->getKind() >= BuiltinType::Bool &&
624 BT->getKind() <= BuiltinType::Int128;
626 if (!Ctx.getLangOpts().CPlusPlus)
627 if (const EnumType *ET = dyn_cast<EnumType>(CanonicalType))
628 return ET->getDecl()->isComplete(); // Complete enum types are integral in C.
634 bool Type::isIntegralOrUnscopedEnumerationType() const {
635 if (const BuiltinType *BT = dyn_cast<BuiltinType>(CanonicalType))
636 return BT->getKind() >= BuiltinType::Bool &&
637 BT->getKind() <= BuiltinType::Int128;
639 // Check for a complete enum type; incomplete enum types are not properly an
640 // enumeration type in the sense required here.
641 // C++0x: However, if the underlying type of the enum is fixed, it is
642 // considered complete.
643 if (const EnumType *ET = dyn_cast<EnumType>(CanonicalType))
644 return ET->getDecl()->isComplete() && !ET->getDecl()->isScoped();
651 bool Type::isCharType() const {
652 if (const BuiltinType *BT = dyn_cast<BuiltinType>(CanonicalType))
653 return BT->getKind() == BuiltinType::Char_U ||
654 BT->getKind() == BuiltinType::UChar ||
655 BT->getKind() == BuiltinType::Char_S ||
656 BT->getKind() == BuiltinType::SChar;
660 bool Type::isWideCharType() const {
661 if (const BuiltinType *BT = dyn_cast<BuiltinType>(CanonicalType))
662 return BT->getKind() == BuiltinType::WChar_S ||
663 BT->getKind() == BuiltinType::WChar_U;
667 bool Type::isChar16Type() const {
668 if (const BuiltinType *BT = dyn_cast<BuiltinType>(CanonicalType))
669 return BT->getKind() == BuiltinType::Char16;
673 bool Type::isChar32Type() const {
674 if (const BuiltinType *BT = dyn_cast<BuiltinType>(CanonicalType))
675 return BT->getKind() == BuiltinType::Char32;
679 /// \brief Determine whether this type is any of the built-in character
681 bool Type::isAnyCharacterType() const {
682 const BuiltinType *BT = dyn_cast<BuiltinType>(CanonicalType);
683 if (BT == 0) return false;
684 switch (BT->getKind()) {
685 default: return false;
686 case BuiltinType::Char_U:
687 case BuiltinType::UChar:
688 case BuiltinType::WChar_U:
689 case BuiltinType::Char16:
690 case BuiltinType::Char32:
691 case BuiltinType::Char_S:
692 case BuiltinType::SChar:
693 case BuiltinType::WChar_S:
698 /// isSignedIntegerType - Return true if this is an integer type that is
699 /// signed, according to C99 6.2.5p4 [char, signed char, short, int, long..],
700 /// an enum decl which has a signed representation
701 bool Type::isSignedIntegerType() const {
702 if (const BuiltinType *BT = dyn_cast<BuiltinType>(CanonicalType)) {
703 return BT->getKind() >= BuiltinType::Char_S &&
704 BT->getKind() <= BuiltinType::Int128;
707 if (const EnumType *ET = dyn_cast<EnumType>(CanonicalType)) {
708 // Incomplete enum types are not treated as integer types.
709 // FIXME: In C++, enum types are never integer types.
710 if (ET->getDecl()->isComplete() && !ET->getDecl()->isScoped())
711 return ET->getDecl()->getIntegerType()->isSignedIntegerType();
717 bool Type::isSignedIntegerOrEnumerationType() const {
718 if (const BuiltinType *BT = dyn_cast<BuiltinType>(CanonicalType)) {
719 return BT->getKind() >= BuiltinType::Char_S &&
720 BT->getKind() <= BuiltinType::Int128;
723 if (const EnumType *ET = dyn_cast<EnumType>(CanonicalType)) {
724 if (ET->getDecl()->isComplete())
725 return ET->getDecl()->getIntegerType()->isSignedIntegerType();
731 bool Type::hasSignedIntegerRepresentation() const {
732 if (const VectorType *VT = dyn_cast<VectorType>(CanonicalType))
733 return VT->getElementType()->isSignedIntegerType();
735 return isSignedIntegerType();
738 /// isUnsignedIntegerType - Return true if this is an integer type that is
739 /// unsigned, according to C99 6.2.5p6 [which returns true for _Bool], an enum
740 /// decl which has an unsigned representation
741 bool Type::isUnsignedIntegerType() const {
742 if (const BuiltinType *BT = dyn_cast<BuiltinType>(CanonicalType)) {
743 return BT->getKind() >= BuiltinType::Bool &&
744 BT->getKind() <= BuiltinType::UInt128;
747 if (const EnumType *ET = dyn_cast<EnumType>(CanonicalType)) {
748 // Incomplete enum types are not treated as integer types.
749 // FIXME: In C++, enum types are never integer types.
750 if (ET->getDecl()->isComplete() && !ET->getDecl()->isScoped())
751 return ET->getDecl()->getIntegerType()->isUnsignedIntegerType();
757 bool Type::isUnsignedIntegerOrEnumerationType() const {
758 if (const BuiltinType *BT = dyn_cast<BuiltinType>(CanonicalType)) {
759 return BT->getKind() >= BuiltinType::Bool &&
760 BT->getKind() <= BuiltinType::UInt128;
763 if (const EnumType *ET = dyn_cast<EnumType>(CanonicalType)) {
764 if (ET->getDecl()->isComplete())
765 return ET->getDecl()->getIntegerType()->isUnsignedIntegerType();
771 bool Type::hasUnsignedIntegerRepresentation() const {
772 if (const VectorType *VT = dyn_cast<VectorType>(CanonicalType))
773 return VT->getElementType()->isUnsignedIntegerType();
775 return isUnsignedIntegerType();
778 bool Type::isFloatingType() const {
779 if (const BuiltinType *BT = dyn_cast<BuiltinType>(CanonicalType))
780 return BT->getKind() >= BuiltinType::Half &&
781 BT->getKind() <= BuiltinType::LongDouble;
782 if (const ComplexType *CT = dyn_cast<ComplexType>(CanonicalType))
783 return CT->getElementType()->isFloatingType();
787 bool Type::hasFloatingRepresentation() const {
788 if (const VectorType *VT = dyn_cast<VectorType>(CanonicalType))
789 return VT->getElementType()->isFloatingType();
791 return isFloatingType();
794 bool Type::isRealFloatingType() const {
795 if (const BuiltinType *BT = dyn_cast<BuiltinType>(CanonicalType))
796 return BT->isFloatingPoint();
800 bool Type::isRealType() const {
801 if (const BuiltinType *BT = dyn_cast<BuiltinType>(CanonicalType))
802 return BT->getKind() >= BuiltinType::Bool &&
803 BT->getKind() <= BuiltinType::LongDouble;
804 if (const EnumType *ET = dyn_cast<EnumType>(CanonicalType))
805 return ET->getDecl()->isComplete() && !ET->getDecl()->isScoped();
809 bool Type::isArithmeticType() const {
810 if (const BuiltinType *BT = dyn_cast<BuiltinType>(CanonicalType))
811 return BT->getKind() >= BuiltinType::Bool &&
812 BT->getKind() <= BuiltinType::LongDouble;
813 if (const EnumType *ET = dyn_cast<EnumType>(CanonicalType))
814 // GCC allows forward declaration of enum types (forbid by C99 6.7.2.3p2).
815 // If a body isn't seen by the time we get here, return false.
817 // C++0x: Enumerations are not arithmetic types. For now, just return
818 // false for scoped enumerations since that will disable any
819 // unwanted implicit conversions.
820 return !ET->getDecl()->isScoped() && ET->getDecl()->isComplete();
821 return isa<ComplexType>(CanonicalType);
824 Type::ScalarTypeKind Type::getScalarTypeKind() const {
825 assert(isScalarType());
827 const Type *T = CanonicalType.getTypePtr();
828 if (const BuiltinType *BT = dyn_cast<BuiltinType>(T)) {
829 if (BT->getKind() == BuiltinType::Bool) return STK_Bool;
830 if (BT->getKind() == BuiltinType::NullPtr) return STK_CPointer;
831 if (BT->isInteger()) return STK_Integral;
832 if (BT->isFloatingPoint()) return STK_Floating;
833 llvm_unreachable("unknown scalar builtin type");
834 } else if (isa<PointerType>(T)) {
836 } else if (isa<BlockPointerType>(T)) {
837 return STK_BlockPointer;
838 } else if (isa<ObjCObjectPointerType>(T)) {
839 return STK_ObjCObjectPointer;
840 } else if (isa<MemberPointerType>(T)) {
841 return STK_MemberPointer;
842 } else if (isa<EnumType>(T)) {
843 assert(cast<EnumType>(T)->getDecl()->isComplete());
845 } else if (const ComplexType *CT = dyn_cast<ComplexType>(T)) {
846 if (CT->getElementType()->isRealFloatingType())
847 return STK_FloatingComplex;
848 return STK_IntegralComplex;
851 llvm_unreachable("unknown scalar type");
854 /// \brief Determines whether the type is a C++ aggregate type or C
855 /// aggregate or union type.
857 /// An aggregate type is an array or a class type (struct, union, or
858 /// class) that has no user-declared constructors, no private or
859 /// protected non-static data members, no base classes, and no virtual
860 /// functions (C++ [dcl.init.aggr]p1). The notion of an aggregate type
861 /// subsumes the notion of C aggregates (C99 6.2.5p21) because it also
862 /// includes union types.
863 bool Type::isAggregateType() const {
864 if (const RecordType *Record = dyn_cast<RecordType>(CanonicalType)) {
865 if (CXXRecordDecl *ClassDecl = dyn_cast<CXXRecordDecl>(Record->getDecl()))
866 return ClassDecl->isAggregate();
871 return isa<ArrayType>(CanonicalType);
874 /// isConstantSizeType - Return true if this is not a variable sized type,
875 /// according to the rules of C99 6.7.5p3. It is not legal to call this on
876 /// incomplete types or dependent types.
877 bool Type::isConstantSizeType() const {
878 assert(!isIncompleteType() && "This doesn't make sense for incomplete types");
879 assert(!isDependentType() && "This doesn't make sense for dependent types");
880 // The VAT must have a size, as it is known to be complete.
881 return !isa<VariableArrayType>(CanonicalType);
884 /// isIncompleteType - Return true if this is an incomplete type (C99 6.2.5p1)
885 /// - a type that can describe objects, but which lacks information needed to
886 /// determine its size.
887 bool Type::isIncompleteType(NamedDecl **Def) const {
891 switch (CanonicalType->getTypeClass()) {
892 default: return false;
894 // Void is the only incomplete builtin type. Per C99 6.2.5p19, it can never
898 EnumDecl *EnumD = cast<EnumType>(CanonicalType)->getDecl();
902 // An enumeration with fixed underlying type is complete (C++0x 7.2p3).
903 if (EnumD->isFixed())
906 return !EnumD->isCompleteDefinition();
909 // A tagged type (struct/union/enum/class) is incomplete if the decl is a
910 // forward declaration, but not a full definition (C99 6.2.5p22).
911 RecordDecl *Rec = cast<RecordType>(CanonicalType)->getDecl();
914 return !Rec->isCompleteDefinition();
917 // An array is incomplete if its element type is incomplete
918 // (C++ [dcl.array]p1).
919 // We don't handle variable arrays (they're not allowed in C++) or
920 // dependent-sized arrays (dependent types are never treated as incomplete).
921 return cast<ArrayType>(CanonicalType)->getElementType()
922 ->isIncompleteType(Def);
923 case IncompleteArray:
924 // An array of unknown size is an incomplete type (C99 6.2.5p22).
927 return cast<ObjCObjectType>(CanonicalType)->getBaseType()
928 ->isIncompleteType(Def);
929 case ObjCInterface: {
930 // ObjC interfaces are incomplete if they are @class, not @interface.
931 ObjCInterfaceDecl *Interface
932 = cast<ObjCInterfaceType>(CanonicalType)->getDecl();
935 return !Interface->hasDefinition();
940 bool QualType::isPODType(ASTContext &Context) const {
941 // C++11 has a more relaxed definition of POD.
942 if (Context.getLangOpts().CPlusPlus0x)
943 return isCXX11PODType(Context);
945 return isCXX98PODType(Context);
948 bool QualType::isCXX98PODType(ASTContext &Context) const {
949 // The compiler shouldn't query this for incomplete types, but the user might.
950 // We return false for that case. Except for incomplete arrays of PODs, which
951 // are PODs according to the standard.
955 if ((*this)->isIncompleteArrayType())
956 return Context.getBaseElementType(*this).isCXX98PODType(Context);
958 if ((*this)->isIncompleteType())
961 if (Context.getLangOpts().ObjCAutoRefCount) {
962 switch (getObjCLifetime()) {
963 case Qualifiers::OCL_ExplicitNone:
966 case Qualifiers::OCL_Strong:
967 case Qualifiers::OCL_Weak:
968 case Qualifiers::OCL_Autoreleasing:
971 case Qualifiers::OCL_None:
976 QualType CanonicalType = getTypePtr()->CanonicalType;
977 switch (CanonicalType->getTypeClass()) {
978 // Everything not explicitly mentioned is not POD.
979 default: return false;
980 case Type::VariableArray:
981 case Type::ConstantArray:
982 // IncompleteArray is handled above.
983 return Context.getBaseElementType(*this).isCXX98PODType(Context);
985 case Type::ObjCObjectPointer:
986 case Type::BlockPointer:
990 case Type::MemberPointer:
992 case Type::ExtVector:
999 if (CXXRecordDecl *ClassDecl
1000 = dyn_cast<CXXRecordDecl>(cast<RecordType>(CanonicalType)->getDecl()))
1001 return ClassDecl->isPOD();
1003 // C struct/union is POD.
1008 bool QualType::isTrivialType(ASTContext &Context) const {
1009 // The compiler shouldn't query this for incomplete types, but the user might.
1010 // We return false for that case. Except for incomplete arrays of PODs, which
1011 // are PODs according to the standard.
1015 if ((*this)->isArrayType())
1016 return Context.getBaseElementType(*this).isTrivialType(Context);
1018 // Return false for incomplete types after skipping any incomplete array
1019 // types which are expressly allowed by the standard and thus our API.
1020 if ((*this)->isIncompleteType())
1023 if (Context.getLangOpts().ObjCAutoRefCount) {
1024 switch (getObjCLifetime()) {
1025 case Qualifiers::OCL_ExplicitNone:
1028 case Qualifiers::OCL_Strong:
1029 case Qualifiers::OCL_Weak:
1030 case Qualifiers::OCL_Autoreleasing:
1033 case Qualifiers::OCL_None:
1034 if ((*this)->isObjCLifetimeType())
1040 QualType CanonicalType = getTypePtr()->CanonicalType;
1041 if (CanonicalType->isDependentType())
1044 // C++0x [basic.types]p9:
1045 // Scalar types, trivial class types, arrays of such types, and
1046 // cv-qualified versions of these types are collectively called trivial
1049 // As an extension, Clang treats vector types as Scalar types.
1050 if (CanonicalType->isScalarType() || CanonicalType->isVectorType())
1052 if (const RecordType *RT = CanonicalType->getAs<RecordType>()) {
1053 if (const CXXRecordDecl *ClassDecl =
1054 dyn_cast<CXXRecordDecl>(RT->getDecl())) {
1056 // A trivial class is a class that has a trivial default constructor
1057 if (!ClassDecl->hasTrivialDefaultConstructor()) return false;
1058 // and is trivially copyable.
1059 if (!ClassDecl->isTriviallyCopyable()) return false;
1065 // No other types can match.
1069 bool QualType::isTriviallyCopyableType(ASTContext &Context) const {
1070 if ((*this)->isArrayType())
1071 return Context.getBaseElementType(*this).isTrivialType(Context);
1073 if (Context.getLangOpts().ObjCAutoRefCount) {
1074 switch (getObjCLifetime()) {
1075 case Qualifiers::OCL_ExplicitNone:
1078 case Qualifiers::OCL_Strong:
1079 case Qualifiers::OCL_Weak:
1080 case Qualifiers::OCL_Autoreleasing:
1083 case Qualifiers::OCL_None:
1084 if ((*this)->isObjCLifetimeType())
1090 // C++0x [basic.types]p9
1091 // Scalar types, trivially copyable class types, arrays of such types, and
1092 // cv-qualified versions of these types are collectively called trivial
1095 QualType CanonicalType = getCanonicalType();
1096 if (CanonicalType->isDependentType())
1099 // Return false for incomplete types after skipping any incomplete array types
1100 // which are expressly allowed by the standard and thus our API.
1101 if (CanonicalType->isIncompleteType())
1104 // As an extension, Clang treats vector types as Scalar types.
1105 if (CanonicalType->isScalarType() || CanonicalType->isVectorType())
1108 if (const RecordType *RT = CanonicalType->getAs<RecordType>()) {
1109 if (const CXXRecordDecl *ClassDecl =
1110 dyn_cast<CXXRecordDecl>(RT->getDecl())) {
1111 if (!ClassDecl->isTriviallyCopyable()) return false;
1117 // No other types can match.
1123 bool Type::isLiteralType() const {
1124 if (isDependentType())
1127 // C++0x [basic.types]p10:
1128 // A type is a literal type if it is:
1130 // -- an array of literal type.
1131 // Extension: variable arrays cannot be literal types, since they're
1133 if (isVariableArrayType())
1135 const Type *BaseTy = getBaseElementTypeUnsafe();
1136 assert(BaseTy && "NULL element type");
1138 // Return false for incomplete types after skipping any incomplete array
1139 // types; those are expressly allowed by the standard and thus our API.
1140 if (BaseTy->isIncompleteType())
1143 // C++0x [basic.types]p10:
1144 // A type is a literal type if it is:
1145 // -- a scalar type; or
1146 // As an extension, Clang treats vector types and complex types as
1148 if (BaseTy->isScalarType() || BaseTy->isVectorType() ||
1149 BaseTy->isAnyComplexType())
1151 // -- a reference type; or
1152 if (BaseTy->isReferenceType())
1154 // -- a class type that has all of the following properties:
1155 if (const RecordType *RT = BaseTy->getAs<RecordType>()) {
1156 // -- a trivial destructor,
1157 // -- every constructor call and full-expression in the
1158 // brace-or-equal-initializers for non-static data members (if any)
1159 // is a constant expression,
1160 // -- it is an aggregate type or has at least one constexpr
1161 // constructor or constructor template that is not a copy or move
1163 // -- all non-static data members and base classes of literal types
1165 // We resolve DR1361 by ignoring the second bullet.
1166 if (const CXXRecordDecl *ClassDecl =
1167 dyn_cast<CXXRecordDecl>(RT->getDecl()))
1168 return ClassDecl->isLiteral();
1176 bool Type::isStandardLayoutType() const {
1177 if (isDependentType())
1180 // C++0x [basic.types]p9:
1181 // Scalar types, standard-layout class types, arrays of such types, and
1182 // cv-qualified versions of these types are collectively called
1183 // standard-layout types.
1184 const Type *BaseTy = getBaseElementTypeUnsafe();
1185 assert(BaseTy && "NULL element type");
1187 // Return false for incomplete types after skipping any incomplete array
1188 // types which are expressly allowed by the standard and thus our API.
1189 if (BaseTy->isIncompleteType())
1192 // As an extension, Clang treats vector types as Scalar types.
1193 if (BaseTy->isScalarType() || BaseTy->isVectorType()) return true;
1194 if (const RecordType *RT = BaseTy->getAs<RecordType>()) {
1195 if (const CXXRecordDecl *ClassDecl =
1196 dyn_cast<CXXRecordDecl>(RT->getDecl()))
1197 if (!ClassDecl->isStandardLayout())
1200 // Default to 'true' for non-C++ class types.
1201 // FIXME: This is a bit dubious, but plain C structs should trivially meet
1202 // all the requirements of standard layout classes.
1206 // No other types can match.
1210 // This is effectively the intersection of isTrivialType and
1211 // isStandardLayoutType. We implement it directly to avoid redundant
1212 // conversions from a type to a CXXRecordDecl.
1213 bool QualType::isCXX11PODType(ASTContext &Context) const {
1214 const Type *ty = getTypePtr();
1215 if (ty->isDependentType())
1218 if (Context.getLangOpts().ObjCAutoRefCount) {
1219 switch (getObjCLifetime()) {
1220 case Qualifiers::OCL_ExplicitNone:
1223 case Qualifiers::OCL_Strong:
1224 case Qualifiers::OCL_Weak:
1225 case Qualifiers::OCL_Autoreleasing:
1228 case Qualifiers::OCL_None:
1233 // C++11 [basic.types]p9:
1234 // Scalar types, POD classes, arrays of such types, and cv-qualified
1235 // versions of these types are collectively called trivial types.
1236 const Type *BaseTy = ty->getBaseElementTypeUnsafe();
1237 assert(BaseTy && "NULL element type");
1239 // Return false for incomplete types after skipping any incomplete array
1240 // types which are expressly allowed by the standard and thus our API.
1241 if (BaseTy->isIncompleteType())
1244 // As an extension, Clang treats vector types as Scalar types.
1245 if (BaseTy->isScalarType() || BaseTy->isVectorType()) return true;
1246 if (const RecordType *RT = BaseTy->getAs<RecordType>()) {
1247 if (const CXXRecordDecl *ClassDecl =
1248 dyn_cast<CXXRecordDecl>(RT->getDecl())) {
1249 // C++11 [class]p10:
1250 // A POD struct is a non-union class that is both a trivial class [...]
1251 if (!ClassDecl->isTrivial()) return false;
1253 // C++11 [class]p10:
1254 // A POD struct is a non-union class that is both a trivial class and
1255 // a standard-layout class [...]
1256 if (!ClassDecl->isStandardLayout()) return false;
1258 // C++11 [class]p10:
1259 // A POD struct is a non-union class that is both a trivial class and
1260 // a standard-layout class, and has no non-static data members of type
1261 // non-POD struct, non-POD union (or array of such types). [...]
1263 // We don't directly query the recursive aspect as the requiremets for
1264 // both standard-layout classes and trivial classes apply recursively
1271 // No other types can match.
1275 bool Type::isPromotableIntegerType() const {
1276 if (const BuiltinType *BT = getAs<BuiltinType>())
1277 switch (BT->getKind()) {
1278 case BuiltinType::Bool:
1279 case BuiltinType::Char_S:
1280 case BuiltinType::Char_U:
1281 case BuiltinType::SChar:
1282 case BuiltinType::UChar:
1283 case BuiltinType::Short:
1284 case BuiltinType::UShort:
1285 case BuiltinType::WChar_S:
1286 case BuiltinType::WChar_U:
1287 case BuiltinType::Char16:
1288 case BuiltinType::Char32:
1294 // Enumerated types are promotable to their compatible integer types
1295 // (C99 6.3.1.1) a.k.a. its underlying type (C++ [conv.prom]p2).
1296 if (const EnumType *ET = getAs<EnumType>()){
1297 if (this->isDependentType() || ET->getDecl()->getPromotionType().isNull()
1298 || ET->getDecl()->isScoped())
1307 bool Type::isSpecifierType() const {
1308 // Note that this intentionally does not use the canonical type.
1309 switch (getTypeClass()) {
1317 case TemplateTypeParm:
1318 case SubstTemplateTypeParm:
1319 case TemplateSpecialization:
1322 case DependentTemplateSpecialization:
1325 case ObjCObjectPointer: // FIXME: object pointers aren't really specifiers
1332 ElaboratedTypeKeyword
1333 TypeWithKeyword::getKeywordForTypeSpec(unsigned TypeSpec) {
1335 default: return ETK_None;
1336 case TST_typename: return ETK_Typename;
1337 case TST_class: return ETK_Class;
1338 case TST_struct: return ETK_Struct;
1339 case TST_interface: return ETK_Interface;
1340 case TST_union: return ETK_Union;
1341 case TST_enum: return ETK_Enum;
1346 TypeWithKeyword::getTagTypeKindForTypeSpec(unsigned TypeSpec) {
1348 case TST_class: return TTK_Class;
1349 case TST_struct: return TTK_Struct;
1350 case TST_interface: return TTK_Interface;
1351 case TST_union: return TTK_Union;
1352 case TST_enum: return TTK_Enum;
1355 llvm_unreachable("Type specifier is not a tag type kind.");
1358 ElaboratedTypeKeyword
1359 TypeWithKeyword::getKeywordForTagTypeKind(TagTypeKind Kind) {
1361 case TTK_Class: return ETK_Class;
1362 case TTK_Struct: return ETK_Struct;
1363 case TTK_Interface: return ETK_Interface;
1364 case TTK_Union: return ETK_Union;
1365 case TTK_Enum: return ETK_Enum;
1367 llvm_unreachable("Unknown tag type kind.");
1371 TypeWithKeyword::getTagTypeKindForKeyword(ElaboratedTypeKeyword Keyword) {
1373 case ETK_Class: return TTK_Class;
1374 case ETK_Struct: return TTK_Struct;
1375 case ETK_Interface: return TTK_Interface;
1376 case ETK_Union: return TTK_Union;
1377 case ETK_Enum: return TTK_Enum;
1378 case ETK_None: // Fall through.
1380 llvm_unreachable("Elaborated type keyword is not a tag type kind.");
1382 llvm_unreachable("Unknown elaborated type keyword.");
1386 TypeWithKeyword::KeywordIsTagTypeKind(ElaboratedTypeKeyword Keyword) {
1398 llvm_unreachable("Unknown elaborated type keyword.");
1402 TypeWithKeyword::getKeywordName(ElaboratedTypeKeyword Keyword) {
1404 case ETK_None: return "";
1405 case ETK_Typename: return "typename";
1406 case ETK_Class: return "class";
1407 case ETK_Struct: return "struct";
1408 case ETK_Interface: return "__interface";
1409 case ETK_Union: return "union";
1410 case ETK_Enum: return "enum";
1413 llvm_unreachable("Unknown elaborated type keyword.");
1416 DependentTemplateSpecializationType::DependentTemplateSpecializationType(
1417 ElaboratedTypeKeyword Keyword,
1418 NestedNameSpecifier *NNS, const IdentifierInfo *Name,
1419 unsigned NumArgs, const TemplateArgument *Args,
1421 : TypeWithKeyword(Keyword, DependentTemplateSpecialization, Canon, true, true,
1422 /*VariablyModified=*/false,
1423 NNS && NNS->containsUnexpandedParameterPack()),
1424 NNS(NNS), Name(Name), NumArgs(NumArgs) {
1425 assert((!NNS || NNS->isDependent()) &&
1426 "DependentTemplateSpecializatonType requires dependent qualifier");
1427 for (unsigned I = 0; I != NumArgs; ++I) {
1428 if (Args[I].containsUnexpandedParameterPack())
1429 setContainsUnexpandedParameterPack();
1431 new (&getArgBuffer()[I]) TemplateArgument(Args[I]);
1436 DependentTemplateSpecializationType::Profile(llvm::FoldingSetNodeID &ID,
1437 const ASTContext &Context,
1438 ElaboratedTypeKeyword Keyword,
1439 NestedNameSpecifier *Qualifier,
1440 const IdentifierInfo *Name,
1442 const TemplateArgument *Args) {
1443 ID.AddInteger(Keyword);
1444 ID.AddPointer(Qualifier);
1445 ID.AddPointer(Name);
1446 for (unsigned Idx = 0; Idx < NumArgs; ++Idx)
1447 Args[Idx].Profile(ID, Context);
1450 bool Type::isElaboratedTypeSpecifier() const {
1451 ElaboratedTypeKeyword Keyword;
1452 if (const ElaboratedType *Elab = dyn_cast<ElaboratedType>(this))
1453 Keyword = Elab->getKeyword();
1454 else if (const DependentNameType *DepName = dyn_cast<DependentNameType>(this))
1455 Keyword = DepName->getKeyword();
1456 else if (const DependentTemplateSpecializationType *DepTST =
1457 dyn_cast<DependentTemplateSpecializationType>(this))
1458 Keyword = DepTST->getKeyword();
1462 return TypeWithKeyword::KeywordIsTagTypeKind(Keyword);
1465 const char *Type::getTypeClassName() const {
1466 switch (TypeBits.TC) {
1467 #define ABSTRACT_TYPE(Derived, Base)
1468 #define TYPE(Derived, Base) case Derived: return #Derived;
1469 #include "clang/AST/TypeNodes.def"
1472 llvm_unreachable("Invalid type class.");
1475 StringRef BuiltinType::getName(const PrintingPolicy &Policy) const {
1476 switch (getKind()) {
1477 case Void: return "void";
1478 case Bool: return Policy.Bool ? "bool" : "_Bool";
1479 case Char_S: return "char";
1480 case Char_U: return "char";
1481 case SChar: return "signed char";
1482 case Short: return "short";
1483 case Int: return "int";
1484 case Long: return "long";
1485 case LongLong: return "long long";
1486 case Int128: return "__int128";
1487 case UChar: return "unsigned char";
1488 case UShort: return "unsigned short";
1489 case UInt: return "unsigned int";
1490 case ULong: return "unsigned long";
1491 case ULongLong: return "unsigned long long";
1492 case UInt128: return "unsigned __int128";
1493 case Half: return "half";
1494 case Float: return "float";
1495 case Double: return "double";
1496 case LongDouble: return "long double";
1498 case WChar_U: return "wchar_t";
1499 case Char16: return "char16_t";
1500 case Char32: return "char32_t";
1501 case NullPtr: return "nullptr_t";
1502 case Overload: return "<overloaded function type>";
1503 case BoundMember: return "<bound member function type>";
1504 case PseudoObject: return "<pseudo-object type>";
1505 case Dependent: return "<dependent type>";
1506 case UnknownAny: return "<unknown type>";
1507 case ARCUnbridgedCast: return "<ARC unbridged cast type>";
1508 case BuiltinFn: return "<builtin fn type>";
1509 case ObjCId: return "id";
1510 case ObjCClass: return "Class";
1511 case ObjCSel: return "SEL";
1514 llvm_unreachable("Invalid builtin type.");
1517 QualType QualType::getNonLValueExprType(ASTContext &Context) const {
1518 if (const ReferenceType *RefType = getTypePtr()->getAs<ReferenceType>())
1519 return RefType->getPointeeType();
1521 // C++0x [basic.lval]:
1522 // Class prvalues can have cv-qualified types; non-class prvalues always
1523 // have cv-unqualified types.
1525 // See also C99 6.3.2.1p2.
1526 if (!Context.getLangOpts().CPlusPlus ||
1527 (!getTypePtr()->isDependentType() && !getTypePtr()->isRecordType()))
1528 return getUnqualifiedType();
1533 StringRef FunctionType::getNameForCallConv(CallingConv CC) {
1536 llvm_unreachable("no name for default cc");
1538 case CC_C: return "cdecl";
1539 case CC_X86StdCall: return "stdcall";
1540 case CC_X86FastCall: return "fastcall";
1541 case CC_X86ThisCall: return "thiscall";
1542 case CC_X86Pascal: return "pascal";
1543 case CC_AAPCS: return "aapcs";
1544 case CC_AAPCS_VFP: return "aapcs-vfp";
1545 case CC_PnaclCall: return "pnaclcall";
1548 llvm_unreachable("Invalid calling convention.");
1551 FunctionProtoType::FunctionProtoType(QualType result, const QualType *args,
1552 unsigned numArgs, QualType canonical,
1553 const ExtProtoInfo &epi)
1554 : FunctionType(FunctionProto, result, epi.TypeQuals, epi.RefQualifier,
1556 result->isDependentType(),
1557 result->isInstantiationDependentType(),
1558 result->isVariablyModifiedType(),
1559 result->containsUnexpandedParameterPack(),
1561 NumArgs(numArgs), NumExceptions(epi.NumExceptions),
1562 ExceptionSpecType(epi.ExceptionSpecType),
1563 HasAnyConsumedArgs(epi.ConsumedArguments != 0),
1564 Variadic(epi.Variadic), HasTrailingReturn(epi.HasTrailingReturn)
1566 // Fill in the trailing argument array.
1567 QualType *argSlot = reinterpret_cast<QualType*>(this+1);
1568 for (unsigned i = 0; i != numArgs; ++i) {
1569 if (args[i]->isDependentType())
1571 else if (args[i]->isInstantiationDependentType())
1572 setInstantiationDependent();
1574 if (args[i]->containsUnexpandedParameterPack())
1575 setContainsUnexpandedParameterPack();
1577 argSlot[i] = args[i];
1580 if (getExceptionSpecType() == EST_Dynamic) {
1581 // Fill in the exception array.
1582 QualType *exnSlot = argSlot + numArgs;
1583 for (unsigned i = 0, e = epi.NumExceptions; i != e; ++i) {
1584 if (epi.Exceptions[i]->isDependentType())
1586 else if (epi.Exceptions[i]->isInstantiationDependentType())
1587 setInstantiationDependent();
1589 if (epi.Exceptions[i]->containsUnexpandedParameterPack())
1590 setContainsUnexpandedParameterPack();
1592 exnSlot[i] = epi.Exceptions[i];
1594 } else if (getExceptionSpecType() == EST_ComputedNoexcept) {
1595 // Store the noexcept expression and context.
1596 Expr **noexSlot = reinterpret_cast<Expr**>(argSlot + numArgs);
1597 *noexSlot = epi.NoexceptExpr;
1599 if (epi.NoexceptExpr) {
1600 if (epi.NoexceptExpr->isValueDependent()
1601 || epi.NoexceptExpr->isTypeDependent())
1603 else if (epi.NoexceptExpr->isInstantiationDependent())
1604 setInstantiationDependent();
1606 } else if (getExceptionSpecType() == EST_Uninstantiated) {
1607 // Store the function decl from which we will resolve our
1608 // exception specification.
1609 FunctionDecl **slot = reinterpret_cast<FunctionDecl**>(argSlot + numArgs);
1610 slot[0] = epi.ExceptionSpecDecl;
1611 slot[1] = epi.ExceptionSpecTemplate;
1612 // This exception specification doesn't make the type dependent, because
1613 // it's not instantiated as part of instantiating the type.
1614 } else if (getExceptionSpecType() == EST_Unevaluated) {
1615 // Store the function decl from which we will resolve our
1616 // exception specification.
1617 FunctionDecl **slot = reinterpret_cast<FunctionDecl**>(argSlot + numArgs);
1618 slot[0] = epi.ExceptionSpecDecl;
1621 if (epi.ConsumedArguments) {
1622 bool *consumedArgs = const_cast<bool*>(getConsumedArgsBuffer());
1623 for (unsigned i = 0; i != numArgs; ++i)
1624 consumedArgs[i] = epi.ConsumedArguments[i];
1628 FunctionProtoType::NoexceptResult
1629 FunctionProtoType::getNoexceptSpec(ASTContext &ctx) const {
1630 ExceptionSpecificationType est = getExceptionSpecType();
1631 if (est == EST_BasicNoexcept)
1634 if (est != EST_ComputedNoexcept)
1635 return NR_NoNoexcept;
1637 Expr *noexceptExpr = getNoexceptExpr();
1639 return NR_BadNoexcept;
1640 if (noexceptExpr->isValueDependent())
1641 return NR_Dependent;
1644 bool isICE = noexceptExpr->isIntegerConstantExpr(value, ctx, 0,
1645 /*evaluated*/false);
1647 assert(isICE && "AST should not contain bad noexcept expressions.");
1649 return value.getBoolValue() ? NR_Nothrow : NR_Throw;
1652 bool FunctionProtoType::isTemplateVariadic() const {
1653 for (unsigned ArgIdx = getNumArgs(); ArgIdx; --ArgIdx)
1654 if (isa<PackExpansionType>(getArgType(ArgIdx - 1)))
1660 void FunctionProtoType::Profile(llvm::FoldingSetNodeID &ID, QualType Result,
1661 const QualType *ArgTys, unsigned NumArgs,
1662 const ExtProtoInfo &epi,
1663 const ASTContext &Context) {
1665 // We have to be careful not to get ambiguous profile encodings.
1666 // Note that valid type pointers are never ambiguous with anything else.
1668 // The encoding grammar begins:
1669 // type type* bool int bool
1670 // If that final bool is true, then there is a section for the EH spec:
1672 // This is followed by an optional "consumed argument" section of the
1673 // same length as the first type sequence:
1675 // Finally, we have the ext info and trailing return type flag:
1678 // There is no ambiguity between the consumed arguments and an empty EH
1679 // spec because of the leading 'bool' which unambiguously indicates
1680 // whether the following bool is the EH spec or part of the arguments.
1682 ID.AddPointer(Result.getAsOpaquePtr());
1683 for (unsigned i = 0; i != NumArgs; ++i)
1684 ID.AddPointer(ArgTys[i].getAsOpaquePtr());
1685 // This method is relatively performance sensitive, so as a performance
1686 // shortcut, use one AddInteger call instead of four for the next four
1688 assert(!(unsigned(epi.Variadic) & ~1) &&
1689 !(unsigned(epi.TypeQuals) & ~255) &&
1690 !(unsigned(epi.RefQualifier) & ~3) &&
1691 !(unsigned(epi.ExceptionSpecType) & ~7) &&
1692 "Values larger than expected.");
1693 ID.AddInteger(unsigned(epi.Variadic) +
1694 (epi.TypeQuals << 1) +
1695 (epi.RefQualifier << 9) +
1696 (epi.ExceptionSpecType << 11));
1697 if (epi.ExceptionSpecType == EST_Dynamic) {
1698 for (unsigned i = 0; i != epi.NumExceptions; ++i)
1699 ID.AddPointer(epi.Exceptions[i].getAsOpaquePtr());
1700 } else if (epi.ExceptionSpecType == EST_ComputedNoexcept && epi.NoexceptExpr){
1701 epi.NoexceptExpr->Profile(ID, Context, false);
1702 } else if (epi.ExceptionSpecType == EST_Uninstantiated ||
1703 epi.ExceptionSpecType == EST_Unevaluated) {
1704 ID.AddPointer(epi.ExceptionSpecDecl->getCanonicalDecl());
1706 if (epi.ConsumedArguments) {
1707 for (unsigned i = 0; i != NumArgs; ++i)
1708 ID.AddBoolean(epi.ConsumedArguments[i]);
1710 epi.ExtInfo.Profile(ID);
1711 ID.AddBoolean(epi.HasTrailingReturn);
1714 void FunctionProtoType::Profile(llvm::FoldingSetNodeID &ID,
1715 const ASTContext &Ctx) {
1716 Profile(ID, getResultType(), arg_type_begin(), NumArgs, getExtProtoInfo(),
1720 QualType TypedefType::desugar() const {
1721 return getDecl()->getUnderlyingType();
1724 TypeOfExprType::TypeOfExprType(Expr *E, QualType can)
1725 : Type(TypeOfExpr, can, E->isTypeDependent(),
1726 E->isInstantiationDependent(),
1727 E->getType()->isVariablyModifiedType(),
1728 E->containsUnexpandedParameterPack()),
1732 bool TypeOfExprType::isSugared() const {
1733 return !TOExpr->isTypeDependent();
1736 QualType TypeOfExprType::desugar() const {
1738 return getUnderlyingExpr()->getType();
1740 return QualType(this, 0);
1743 void DependentTypeOfExprType::Profile(llvm::FoldingSetNodeID &ID,
1744 const ASTContext &Context, Expr *E) {
1745 E->Profile(ID, Context, true);
1748 DecltypeType::DecltypeType(Expr *E, QualType underlyingType, QualType can)
1749 // C++11 [temp.type]p2: "If an expression e involves a template parameter,
1750 // decltype(e) denotes a unique dependent type." Hence a decltype type is
1751 // type-dependent even if its expression is only instantiation-dependent.
1752 : Type(Decltype, can, E->isInstantiationDependent(),
1753 E->isInstantiationDependent(),
1754 E->getType()->isVariablyModifiedType(),
1755 E->containsUnexpandedParameterPack()),
1757 UnderlyingType(underlyingType) {
1760 bool DecltypeType::isSugared() const { return !E->isInstantiationDependent(); }
1762 QualType DecltypeType::desugar() const {
1764 return getUnderlyingType();
1766 return QualType(this, 0);
1769 DependentDecltypeType::DependentDecltypeType(const ASTContext &Context, Expr *E)
1770 : DecltypeType(E, Context.DependentTy), Context(Context) { }
1772 void DependentDecltypeType::Profile(llvm::FoldingSetNodeID &ID,
1773 const ASTContext &Context, Expr *E) {
1774 E->Profile(ID, Context, true);
1777 TagType::TagType(TypeClass TC, const TagDecl *D, QualType can)
1778 : Type(TC, can, D->isDependentType(),
1779 /*InstantiationDependent=*/D->isDependentType(),
1780 /*VariablyModified=*/false,
1781 /*ContainsUnexpandedParameterPack=*/false),
1782 decl(const_cast<TagDecl*>(D)) {}
1784 static TagDecl *getInterestingTagDecl(TagDecl *decl) {
1785 for (TagDecl::redecl_iterator I = decl->redecls_begin(),
1786 E = decl->redecls_end();
1788 if (I->isCompleteDefinition() || I->isBeingDefined())
1791 // If there's no definition (not even in progress), return what we have.
1795 UnaryTransformType::UnaryTransformType(QualType BaseType,
1796 QualType UnderlyingType,
1798 QualType CanonicalType)
1799 : Type(UnaryTransform, CanonicalType, UnderlyingType->isDependentType(),
1800 UnderlyingType->isInstantiationDependentType(),
1801 UnderlyingType->isVariablyModifiedType(),
1802 BaseType->containsUnexpandedParameterPack())
1803 , BaseType(BaseType), UnderlyingType(UnderlyingType), UKind(UKind)
1806 TagDecl *TagType::getDecl() const {
1807 return getInterestingTagDecl(decl);
1810 bool TagType::isBeingDefined() const {
1811 return getDecl()->isBeingDefined();
1814 CXXRecordDecl *InjectedClassNameType::getDecl() const {
1815 return cast<CXXRecordDecl>(getInterestingTagDecl(Decl));
1818 IdentifierInfo *TemplateTypeParmType::getIdentifier() const {
1819 return isCanonicalUnqualified() ? 0 : getDecl()->getIdentifier();
1822 SubstTemplateTypeParmPackType::
1823 SubstTemplateTypeParmPackType(const TemplateTypeParmType *Param,
1825 const TemplateArgument &ArgPack)
1826 : Type(SubstTemplateTypeParmPack, Canon, true, true, false, true),
1828 Arguments(ArgPack.pack_begin()), NumArguments(ArgPack.pack_size())
1832 TemplateArgument SubstTemplateTypeParmPackType::getArgumentPack() const {
1833 return TemplateArgument(Arguments, NumArguments);
1836 void SubstTemplateTypeParmPackType::Profile(llvm::FoldingSetNodeID &ID) {
1837 Profile(ID, getReplacedParameter(), getArgumentPack());
1840 void SubstTemplateTypeParmPackType::Profile(llvm::FoldingSetNodeID &ID,
1841 const TemplateTypeParmType *Replaced,
1842 const TemplateArgument &ArgPack) {
1843 ID.AddPointer(Replaced);
1844 ID.AddInteger(ArgPack.pack_size());
1845 for (TemplateArgument::pack_iterator P = ArgPack.pack_begin(),
1846 PEnd = ArgPack.pack_end();
1848 ID.AddPointer(P->getAsType().getAsOpaquePtr());
1851 bool TemplateSpecializationType::
1852 anyDependentTemplateArguments(const TemplateArgumentListInfo &Args,
1853 bool &InstantiationDependent) {
1854 return anyDependentTemplateArguments(Args.getArgumentArray(), Args.size(),
1855 InstantiationDependent);
1858 bool TemplateSpecializationType::
1859 anyDependentTemplateArguments(const TemplateArgumentLoc *Args, unsigned N,
1860 bool &InstantiationDependent) {
1861 for (unsigned i = 0; i != N; ++i) {
1862 if (Args[i].getArgument().isDependent()) {
1863 InstantiationDependent = true;
1867 if (Args[i].getArgument().isInstantiationDependent())
1868 InstantiationDependent = true;
1873 bool TemplateSpecializationType::
1874 anyDependentTemplateArguments(const TemplateArgument *Args, unsigned N,
1875 bool &InstantiationDependent) {
1876 for (unsigned i = 0; i != N; ++i) {
1877 if (Args[i].isDependent()) {
1878 InstantiationDependent = true;
1882 if (Args[i].isInstantiationDependent())
1883 InstantiationDependent = true;
1888 TemplateSpecializationType::
1889 TemplateSpecializationType(TemplateName T,
1890 const TemplateArgument *Args, unsigned NumArgs,
1891 QualType Canon, QualType AliasedType)
1892 : Type(TemplateSpecialization,
1893 Canon.isNull()? QualType(this, 0) : Canon,
1894 Canon.isNull()? T.isDependent() : Canon->isDependentType(),
1895 Canon.isNull()? T.isDependent()
1896 : Canon->isInstantiationDependentType(),
1898 T.containsUnexpandedParameterPack()),
1899 Template(T), NumArgs(NumArgs), TypeAlias(!AliasedType.isNull()) {
1900 assert(!T.getAsDependentTemplateName() &&
1901 "Use DependentTemplateSpecializationType for dependent template-name");
1902 assert((T.getKind() == TemplateName::Template ||
1903 T.getKind() == TemplateName::SubstTemplateTemplateParm ||
1904 T.getKind() == TemplateName::SubstTemplateTemplateParmPack) &&
1905 "Unexpected template name for TemplateSpecializationType");
1906 bool InstantiationDependent;
1907 (void)InstantiationDependent;
1908 assert((!Canon.isNull() ||
1910 anyDependentTemplateArguments(Args, NumArgs,
1911 InstantiationDependent)) &&
1912 "No canonical type for non-dependent class template specialization");
1914 TemplateArgument *TemplateArgs
1915 = reinterpret_cast<TemplateArgument *>(this + 1);
1916 for (unsigned Arg = 0; Arg < NumArgs; ++Arg) {
1917 // Update dependent and variably-modified bits.
1918 // If the canonical type exists and is non-dependent, the template
1919 // specialization type can be non-dependent even if one of the type
1920 // arguments is. Given:
1921 // template<typename T> using U = int;
1922 // U<T> is always non-dependent, irrespective of the type T.
1923 // However, U<Ts> contains an unexpanded parameter pack, even though
1924 // its expansion (and thus its desugared type) doesn't.
1925 if (Canon.isNull() && Args[Arg].isDependent())
1927 else if (Args[Arg].isInstantiationDependent())
1928 setInstantiationDependent();
1930 if (Args[Arg].getKind() == TemplateArgument::Type &&
1931 Args[Arg].getAsType()->isVariablyModifiedType())
1932 setVariablyModified();
1933 if (Args[Arg].containsUnexpandedParameterPack())
1934 setContainsUnexpandedParameterPack();
1936 new (&TemplateArgs[Arg]) TemplateArgument(Args[Arg]);
1939 // Store the aliased type if this is a type alias template specialization.
1941 TemplateArgument *Begin = reinterpret_cast<TemplateArgument *>(this + 1);
1942 *reinterpret_cast<QualType*>(Begin + getNumArgs()) = AliasedType;
1947 TemplateSpecializationType::Profile(llvm::FoldingSetNodeID &ID,
1949 const TemplateArgument *Args,
1951 const ASTContext &Context) {
1953 for (unsigned Idx = 0; Idx < NumArgs; ++Idx)
1954 Args[Idx].Profile(ID, Context);
1958 QualifierCollector::apply(const ASTContext &Context, QualType QT) const {
1959 if (!hasNonFastQualifiers())
1960 return QT.withFastQualifiers(getFastQualifiers());
1962 return Context.getQualifiedType(QT, *this);
1966 QualifierCollector::apply(const ASTContext &Context, const Type *T) const {
1967 if (!hasNonFastQualifiers())
1968 return QualType(T, getFastQualifiers());
1970 return Context.getQualifiedType(T, *this);
1973 void ObjCObjectTypeImpl::Profile(llvm::FoldingSetNodeID &ID,
1975 ObjCProtocolDecl * const *Protocols,
1976 unsigned NumProtocols) {
1977 ID.AddPointer(BaseType.getAsOpaquePtr());
1978 for (unsigned i = 0; i != NumProtocols; i++)
1979 ID.AddPointer(Protocols[i]);
1982 void ObjCObjectTypeImpl::Profile(llvm::FoldingSetNodeID &ID) {
1983 Profile(ID, getBaseType(), qual_begin(), getNumProtocols());
1988 /// \brief The cached properties of a type.
1989 class CachedProperties {
1990 NamedDecl::LinkageInfo LV;
1994 CachedProperties(NamedDecl::LinkageInfo LV, bool local)
1995 : LV(LV), local(local) {}
1997 Linkage getLinkage() const { return LV.linkage(); }
1998 Visibility getVisibility() const { return LV.visibility(); }
1999 bool isVisibilityExplicit() const { return LV.visibilityExplicit(); }
2000 bool hasLocalOrUnnamedType() const { return local; }
2002 friend CachedProperties merge(CachedProperties L, CachedProperties R) {
2003 NamedDecl::LinkageInfo MergedLV = L.LV;
2004 MergedLV.merge(R.LV);
2005 return CachedProperties(MergedLV,
2006 L.hasLocalOrUnnamedType() | R.hasLocalOrUnnamedType());
2011 static CachedProperties computeCachedProperties(const Type *T);
2014 /// The type-property cache. This is templated so as to be
2015 /// instantiated at an internal type to prevent unnecessary symbol
2017 template <class Private> class TypePropertyCache {
2019 static CachedProperties get(QualType T) {
2020 return get(T.getTypePtr());
2023 static CachedProperties get(const Type *T) {
2025 NamedDecl::LinkageInfo LV(T->TypeBits.getLinkage(),
2026 T->TypeBits.getVisibility(),
2027 T->TypeBits.isVisibilityExplicit());
2028 return CachedProperties(LV, T->TypeBits.hasLocalOrUnnamedType());
2031 static void ensure(const Type *T) {
2032 // If the cache is valid, we're okay.
2033 if (T->TypeBits.isCacheValid()) return;
2035 // If this type is non-canonical, ask its canonical type for the
2036 // relevant information.
2037 if (!T->isCanonicalUnqualified()) {
2038 const Type *CT = T->getCanonicalTypeInternal().getTypePtr();
2040 T->TypeBits.CacheValidAndVisibility =
2041 CT->TypeBits.CacheValidAndVisibility;
2042 T->TypeBits.CachedExplicitVisibility =
2043 CT->TypeBits.CachedExplicitVisibility;
2044 T->TypeBits.CachedLinkage = CT->TypeBits.CachedLinkage;
2045 T->TypeBits.CachedLocalOrUnnamed = CT->TypeBits.CachedLocalOrUnnamed;
2049 // Compute the cached properties and then set the cache.
2050 CachedProperties Result = computeCachedProperties(T);
2051 T->TypeBits.CacheValidAndVisibility = Result.getVisibility() + 1U;
2052 T->TypeBits.CachedExplicitVisibility = Result.isVisibilityExplicit();
2053 assert(T->TypeBits.isCacheValid() &&
2054 T->TypeBits.getVisibility() == Result.getVisibility());
2055 T->TypeBits.CachedLinkage = Result.getLinkage();
2056 T->TypeBits.CachedLocalOrUnnamed = Result.hasLocalOrUnnamedType();
2061 // Instantiate the friend template at a private class. In a
2062 // reasonable implementation, these symbols will be internal.
2063 // It is terrible that this is the best way to accomplish this.
2064 namespace { class Private {}; }
2065 typedef TypePropertyCache<Private> Cache;
2067 static CachedProperties computeCachedProperties(const Type *T) {
2068 switch (T->getTypeClass()) {
2069 #define TYPE(Class,Base)
2070 #define NON_CANONICAL_TYPE(Class,Base) case Type::Class:
2071 #include "clang/AST/TypeNodes.def"
2072 llvm_unreachable("didn't expect a non-canonical type here");
2074 #define TYPE(Class,Base)
2075 #define DEPENDENT_TYPE(Class,Base) case Type::Class:
2076 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class,Base) case Type::Class:
2077 #include "clang/AST/TypeNodes.def"
2078 // Treat instantiation-dependent types as external.
2079 assert(T->isInstantiationDependentType());
2080 return CachedProperties(NamedDecl::LinkageInfo(), false);
2083 // C++ [basic.link]p8:
2084 // A type is said to have linkage if and only if:
2085 // - it is a fundamental type (3.9.1); or
2086 return CachedProperties(NamedDecl::LinkageInfo(), false);
2090 const TagDecl *Tag = cast<TagType>(T)->getDecl();
2092 // C++ [basic.link]p8:
2093 // - it is a class or enumeration type that is named (or has a name
2094 // for linkage purposes (7.1.3)) and the name has linkage; or
2095 // - it is a specialization of a class template (14); or
2096 NamedDecl::LinkageInfo LV = Tag->getLinkageAndVisibility();
2097 bool IsLocalOrUnnamed =
2098 Tag->getDeclContext()->isFunctionOrMethod() ||
2099 (!Tag->getIdentifier() && !Tag->getTypedefNameForAnonDecl());
2100 return CachedProperties(LV, IsLocalOrUnnamed);
2103 // C++ [basic.link]p8:
2104 // - it is a compound type (3.9.2) other than a class or enumeration,
2105 // compounded exclusively from types that have linkage; or
2107 return Cache::get(cast<ComplexType>(T)->getElementType());
2109 return Cache::get(cast<PointerType>(T)->getPointeeType());
2110 case Type::BlockPointer:
2111 return Cache::get(cast<BlockPointerType>(T)->getPointeeType());
2112 case Type::LValueReference:
2113 case Type::RValueReference:
2114 return Cache::get(cast<ReferenceType>(T)->getPointeeType());
2115 case Type::MemberPointer: {
2116 const MemberPointerType *MPT = cast<MemberPointerType>(T);
2117 return merge(Cache::get(MPT->getClass()),
2118 Cache::get(MPT->getPointeeType()));
2120 case Type::ConstantArray:
2121 case Type::IncompleteArray:
2122 case Type::VariableArray:
2123 return Cache::get(cast<ArrayType>(T)->getElementType());
2125 case Type::ExtVector:
2126 return Cache::get(cast<VectorType>(T)->getElementType());
2127 case Type::FunctionNoProto:
2128 return Cache::get(cast<FunctionType>(T)->getResultType());
2129 case Type::FunctionProto: {
2130 const FunctionProtoType *FPT = cast<FunctionProtoType>(T);
2131 CachedProperties result = Cache::get(FPT->getResultType());
2132 for (FunctionProtoType::arg_type_iterator ai = FPT->arg_type_begin(),
2133 ae = FPT->arg_type_end(); ai != ae; ++ai)
2134 result = merge(result, Cache::get(*ai));
2137 case Type::ObjCInterface: {
2138 NamedDecl::LinkageInfo LV =
2139 cast<ObjCInterfaceType>(T)->getDecl()->getLinkageAndVisibility();
2140 return CachedProperties(LV, false);
2142 case Type::ObjCObject:
2143 return Cache::get(cast<ObjCObjectType>(T)->getBaseType());
2144 case Type::ObjCObjectPointer:
2145 return Cache::get(cast<ObjCObjectPointerType>(T)->getPointeeType());
2147 return Cache::get(cast<AtomicType>(T)->getValueType());
2150 llvm_unreachable("unhandled type class");
2153 /// \brief Determine the linkage of this type.
2154 Linkage Type::getLinkage() const {
2155 Cache::ensure(this);
2156 return TypeBits.getLinkage();
2159 /// \brief Determine the linkage of this type.
2160 Visibility Type::getVisibility() const {
2161 Cache::ensure(this);
2162 return TypeBits.getVisibility();
2165 bool Type::isVisibilityExplicit() const {
2166 Cache::ensure(this);
2167 return TypeBits.isVisibilityExplicit();
2170 bool Type::hasUnnamedOrLocalType() const {
2171 Cache::ensure(this);
2172 return TypeBits.hasLocalOrUnnamedType();
2175 std::pair<Linkage,Visibility> Type::getLinkageAndVisibility() const {
2176 Cache::ensure(this);
2177 return std::make_pair(TypeBits.getLinkage(), TypeBits.getVisibility());
2180 void Type::ClearLinkageCache() {
2181 TypeBits.CacheValidAndVisibility = 0;
2182 if (QualType(this, 0) != CanonicalType)
2183 CanonicalType->TypeBits.CacheValidAndVisibility = 0;
2186 Qualifiers::ObjCLifetime Type::getObjCARCImplicitLifetime() const {
2187 if (isObjCARCImplicitlyUnretainedType())
2188 return Qualifiers::OCL_ExplicitNone;
2189 return Qualifiers::OCL_Strong;
2192 bool Type::isObjCARCImplicitlyUnretainedType() const {
2193 assert(isObjCLifetimeType() &&
2194 "cannot query implicit lifetime for non-inferrable type");
2196 const Type *canon = getCanonicalTypeInternal().getTypePtr();
2198 // Walk down to the base type. We don't care about qualifiers for this.
2199 while (const ArrayType *array = dyn_cast<ArrayType>(canon))
2200 canon = array->getElementType().getTypePtr();
2202 if (const ObjCObjectPointerType *opt
2203 = dyn_cast<ObjCObjectPointerType>(canon)) {
2204 // Class and Class<Protocol> don't require retension.
2205 if (opt->getObjectType()->isObjCClass())
2212 bool Type::isObjCNSObjectType() const {
2213 if (const TypedefType *typedefType = dyn_cast<TypedefType>(this))
2214 return typedefType->getDecl()->hasAttr<ObjCNSObjectAttr>();
2217 bool Type::isObjCRetainableType() const {
2218 return isObjCObjectPointerType() ||
2219 isBlockPointerType() ||
2220 isObjCNSObjectType();
2222 bool Type::isObjCIndirectLifetimeType() const {
2223 if (isObjCLifetimeType())
2225 if (const PointerType *OPT = getAs<PointerType>())
2226 return OPT->getPointeeType()->isObjCIndirectLifetimeType();
2227 if (const ReferenceType *Ref = getAs<ReferenceType>())
2228 return Ref->getPointeeType()->isObjCIndirectLifetimeType();
2229 if (const MemberPointerType *MemPtr = getAs<MemberPointerType>())
2230 return MemPtr->getPointeeType()->isObjCIndirectLifetimeType();
2234 /// Returns true if objects of this type have lifetime semantics under
2236 bool Type::isObjCLifetimeType() const {
2237 const Type *type = this;
2238 while (const ArrayType *array = type->getAsArrayTypeUnsafe())
2239 type = array->getElementType().getTypePtr();
2240 return type->isObjCRetainableType();
2243 /// \brief Determine whether the given type T is a "bridgable" Objective-C type,
2244 /// which is either an Objective-C object pointer type or an
2245 bool Type::isObjCARCBridgableType() const {
2246 return isObjCObjectPointerType() || isBlockPointerType();
2249 /// \brief Determine whether the given type T is a "bridgeable" C type.
2250 bool Type::isCARCBridgableType() const {
2251 const PointerType *Pointer = getAs<PointerType>();
2255 QualType Pointee = Pointer->getPointeeType();
2256 return Pointee->isVoidType() || Pointee->isRecordType();
2259 bool Type::hasSizedVLAType() const {
2260 if (!isVariablyModifiedType()) return false;
2262 if (const PointerType *ptr = getAs<PointerType>())
2263 return ptr->getPointeeType()->hasSizedVLAType();
2264 if (const ReferenceType *ref = getAs<ReferenceType>())
2265 return ref->getPointeeType()->hasSizedVLAType();
2266 if (const ArrayType *arr = getAsArrayTypeUnsafe()) {
2267 if (isa<VariableArrayType>(arr) &&
2268 cast<VariableArrayType>(arr)->getSizeExpr())
2271 return arr->getElementType()->hasSizedVLAType();
2277 QualType::DestructionKind QualType::isDestructedTypeImpl(QualType type) {
2278 switch (type.getObjCLifetime()) {
2279 case Qualifiers::OCL_None:
2280 case Qualifiers::OCL_ExplicitNone:
2281 case Qualifiers::OCL_Autoreleasing:
2284 case Qualifiers::OCL_Strong:
2285 return DK_objc_strong_lifetime;
2286 case Qualifiers::OCL_Weak:
2287 return DK_objc_weak_lifetime;
2290 /// Currently, the only destruction kind we recognize is C++ objects
2291 /// with non-trivial destructors.
2292 const CXXRecordDecl *record =
2293 type->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
2294 if (record && record->hasDefinition() && !record->hasTrivialDestructor())
2295 return DK_cxx_destructor;
2300 bool QualType::hasTrivialAssignment(ASTContext &Context, bool Copying) const {
2301 switch (getObjCLifetime()) {
2302 case Qualifiers::OCL_None:
2305 case Qualifiers::OCL_ExplicitNone:
2308 case Qualifiers::OCL_Autoreleasing:
2309 case Qualifiers::OCL_Strong:
2310 case Qualifiers::OCL_Weak:
2311 return !Context.getLangOpts().ObjCAutoRefCount;
2314 if (const CXXRecordDecl *Record
2315 = getTypePtr()->getBaseElementTypeUnsafe()->getAsCXXRecordDecl())
2316 return Copying ? Record->hasTrivialCopyAssignment() :
2317 Record->hasTrivialMoveAssignment();