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.first, split.second);
203 QualType QualType::getSingleStepDesugaredType(const ASTContext &Context) const {
204 QualifierCollector Qs;
206 const Type *CurTy = Qs.strip(*this);
207 switch (CurTy->getTypeClass()) {
208 #define ABSTRACT_TYPE(Class, Parent)
209 #define TYPE(Class, Parent) \
210 case Type::Class: { \
211 const Class##Type *Ty = cast<Class##Type>(CurTy); \
212 if (!Ty->isSugared()) \
214 return Context.getQualifiedType(Ty->desugar(), Qs); \
217 #include "clang/AST/TypeNodes.def"
223 SplitQualType QualType::getSplitDesugaredType(QualType T) {
224 QualifierCollector Qs;
228 const Type *CurTy = Qs.strip(Cur);
229 switch (CurTy->getTypeClass()) {
230 #define ABSTRACT_TYPE(Class, Parent)
231 #define TYPE(Class, Parent) \
232 case Type::Class: { \
233 const Class##Type *Ty = cast<Class##Type>(CurTy); \
234 if (!Ty->isSugared()) \
235 return SplitQualType(Ty, Qs); \
236 Cur = Ty->desugar(); \
239 #include "clang/AST/TypeNodes.def"
244 SplitQualType QualType::getSplitUnqualifiedTypeImpl(QualType type) {
245 SplitQualType split = type.split();
247 // All the qualifiers we've seen so far.
248 Qualifiers quals = split.second;
250 // The last type node we saw with any nodes inside it.
251 const Type *lastTypeWithQuals = split.first;
256 // Do a single-step desugar, aborting the loop if the type isn't
258 switch (split.first->getTypeClass()) {
259 #define ABSTRACT_TYPE(Class, Parent)
260 #define TYPE(Class, Parent) \
261 case Type::Class: { \
262 const Class##Type *ty = cast<Class##Type>(split.first); \
263 if (!ty->isSugared()) goto done; \
264 next = ty->desugar(); \
267 #include "clang/AST/TypeNodes.def"
270 // Otherwise, split the underlying type. If that yields qualifiers,
271 // update the information.
272 split = next.split();
273 if (!split.second.empty()) {
274 lastTypeWithQuals = split.first;
275 quals.addConsistentQualifiers(split.second);
280 return SplitQualType(lastTypeWithQuals, quals);
283 QualType QualType::IgnoreParens(QualType T) {
284 // FIXME: this seems inherently un-qualifiers-safe.
285 while (const ParenType *PT = T->getAs<ParenType>())
286 T = PT->getInnerType();
290 /// getUnqualifiedDesugaredType - Pull any qualifiers and syntactic
291 /// sugar off the given type. This should produce an object of the
292 /// same dynamic type as the canonical type.
293 const Type *Type::getUnqualifiedDesugaredType() const {
294 const Type *Cur = this;
297 switch (Cur->getTypeClass()) {
298 #define ABSTRACT_TYPE(Class, Parent)
299 #define TYPE(Class, Parent) \
301 const Class##Type *Ty = cast<Class##Type>(Cur); \
302 if (!Ty->isSugared()) return Cur; \
303 Cur = Ty->desugar().getTypePtr(); \
306 #include "clang/AST/TypeNodes.def"
311 /// isVoidType - Helper method to determine if this is the 'void' type.
312 bool Type::isVoidType() const {
313 if (const BuiltinType *BT = dyn_cast<BuiltinType>(CanonicalType))
314 return BT->getKind() == BuiltinType::Void;
318 bool Type::isDerivedType() const {
319 switch (CanonicalType->getTypeClass()) {
323 case IncompleteArray:
325 case FunctionNoProto:
326 case LValueReference:
327 case RValueReference:
334 bool Type::isClassType() const {
335 if (const RecordType *RT = getAs<RecordType>())
336 return RT->getDecl()->isClass();
339 bool Type::isStructureType() const {
340 if (const RecordType *RT = getAs<RecordType>())
341 return RT->getDecl()->isStruct();
344 bool Type::isStructureOrClassType() const {
345 if (const RecordType *RT = getAs<RecordType>())
346 return RT->getDecl()->isStruct() || RT->getDecl()->isClass();
349 bool Type::isVoidPointerType() const {
350 if (const PointerType *PT = getAs<PointerType>())
351 return PT->getPointeeType()->isVoidType();
355 bool Type::isUnionType() const {
356 if (const RecordType *RT = getAs<RecordType>())
357 return RT->getDecl()->isUnion();
361 bool Type::isComplexType() const {
362 if (const ComplexType *CT = dyn_cast<ComplexType>(CanonicalType))
363 return CT->getElementType()->isFloatingType();
367 bool Type::isComplexIntegerType() const {
368 // Check for GCC complex integer extension.
369 return getAsComplexIntegerType();
372 const ComplexType *Type::getAsComplexIntegerType() const {
373 if (const ComplexType *Complex = getAs<ComplexType>())
374 if (Complex->getElementType()->isIntegerType())
379 QualType Type::getPointeeType() const {
380 if (const PointerType *PT = getAs<PointerType>())
381 return PT->getPointeeType();
382 if (const ObjCObjectPointerType *OPT = getAs<ObjCObjectPointerType>())
383 return OPT->getPointeeType();
384 if (const BlockPointerType *BPT = getAs<BlockPointerType>())
385 return BPT->getPointeeType();
386 if (const ReferenceType *RT = getAs<ReferenceType>())
387 return RT->getPointeeType();
391 const RecordType *Type::getAsStructureType() const {
392 // If this is directly a structure type, return it.
393 if (const RecordType *RT = dyn_cast<RecordType>(this)) {
394 if (RT->getDecl()->isStruct())
398 // If the canonical form of this type isn't the right kind, reject it.
399 if (const RecordType *RT = dyn_cast<RecordType>(CanonicalType)) {
400 if (!RT->getDecl()->isStruct())
403 // If this is a typedef for a structure type, strip the typedef off without
404 // losing all typedef information.
405 return cast<RecordType>(getUnqualifiedDesugaredType());
410 const RecordType *Type::getAsUnionType() const {
411 // If this is directly a union type, return it.
412 if (const RecordType *RT = dyn_cast<RecordType>(this)) {
413 if (RT->getDecl()->isUnion())
417 // If the canonical form of this type isn't the right kind, reject it.
418 if (const RecordType *RT = dyn_cast<RecordType>(CanonicalType)) {
419 if (!RT->getDecl()->isUnion())
422 // If this is a typedef for a union type, strip the typedef off without
423 // losing all typedef information.
424 return cast<RecordType>(getUnqualifiedDesugaredType());
430 ObjCObjectType::ObjCObjectType(QualType Canonical, QualType Base,
431 ObjCProtocolDecl * const *Protocols,
432 unsigned NumProtocols)
433 : Type(ObjCObject, Canonical, false, false, false, false),
436 ObjCObjectTypeBits.NumProtocols = NumProtocols;
437 assert(getNumProtocols() == NumProtocols &&
438 "bitfield overflow in protocol count");
440 memcpy(getProtocolStorage(), Protocols,
441 NumProtocols * sizeof(ObjCProtocolDecl*));
444 const ObjCObjectType *Type::getAsObjCQualifiedInterfaceType() const {
445 // There is no sugar for ObjCObjectType's, just return the canonical
446 // type pointer if it is the right class. There is no typedef information to
447 // return and these cannot be Address-space qualified.
448 if (const ObjCObjectType *T = getAs<ObjCObjectType>())
449 if (T->getNumProtocols() && T->getInterface())
454 bool Type::isObjCQualifiedInterfaceType() const {
455 return getAsObjCQualifiedInterfaceType() != 0;
458 const ObjCObjectPointerType *Type::getAsObjCQualifiedIdType() const {
459 // There is no sugar for ObjCQualifiedIdType's, just return the canonical
460 // type pointer if it is the right class.
461 if (const ObjCObjectPointerType *OPT = getAs<ObjCObjectPointerType>()) {
462 if (OPT->isObjCQualifiedIdType())
468 const ObjCObjectPointerType *Type::getAsObjCQualifiedClassType() const {
469 // There is no sugar for ObjCQualifiedClassType's, just return the canonical
470 // type pointer if it is the right class.
471 if (const ObjCObjectPointerType *OPT = getAs<ObjCObjectPointerType>()) {
472 if (OPT->isObjCQualifiedClassType())
478 const ObjCObjectPointerType *Type::getAsObjCInterfacePointerType() const {
479 if (const ObjCObjectPointerType *OPT = getAs<ObjCObjectPointerType>()) {
480 if (OPT->getInterfaceType())
486 const CXXRecordDecl *Type::getCXXRecordDeclForPointerType() const {
487 if (const PointerType *PT = getAs<PointerType>())
488 if (const RecordType *RT = PT->getPointeeType()->getAs<RecordType>())
489 return dyn_cast<CXXRecordDecl>(RT->getDecl());
493 CXXRecordDecl *Type::getAsCXXRecordDecl() const {
494 if (const RecordType *RT = getAs<RecordType>())
495 return dyn_cast<CXXRecordDecl>(RT->getDecl());
496 else if (const InjectedClassNameType *Injected
497 = getAs<InjectedClassNameType>())
498 return Injected->getDecl();
504 class GetContainedAutoVisitor :
505 public TypeVisitor<GetContainedAutoVisitor, AutoType*> {
507 using TypeVisitor<GetContainedAutoVisitor, AutoType*>::Visit;
508 AutoType *Visit(QualType T) {
511 return Visit(T.getTypePtr());
514 // The 'auto' type itself.
515 AutoType *VisitAutoType(const AutoType *AT) {
516 return const_cast<AutoType*>(AT);
519 // Only these types can contain the desired 'auto' type.
520 AutoType *VisitPointerType(const PointerType *T) {
521 return Visit(T->getPointeeType());
523 AutoType *VisitBlockPointerType(const BlockPointerType *T) {
524 return Visit(T->getPointeeType());
526 AutoType *VisitReferenceType(const ReferenceType *T) {
527 return Visit(T->getPointeeTypeAsWritten());
529 AutoType *VisitMemberPointerType(const MemberPointerType *T) {
530 return Visit(T->getPointeeType());
532 AutoType *VisitArrayType(const ArrayType *T) {
533 return Visit(T->getElementType());
535 AutoType *VisitDependentSizedExtVectorType(
536 const DependentSizedExtVectorType *T) {
537 return Visit(T->getElementType());
539 AutoType *VisitVectorType(const VectorType *T) {
540 return Visit(T->getElementType());
542 AutoType *VisitFunctionType(const FunctionType *T) {
543 return Visit(T->getResultType());
545 AutoType *VisitParenType(const ParenType *T) {
546 return Visit(T->getInnerType());
548 AutoType *VisitAttributedType(const AttributedType *T) {
549 return Visit(T->getModifiedType());
554 AutoType *Type::getContainedAutoType() const {
555 return GetContainedAutoVisitor().Visit(this);
558 bool Type::isIntegerType() const {
559 if (const BuiltinType *BT = dyn_cast<BuiltinType>(CanonicalType))
560 return BT->getKind() >= BuiltinType::Bool &&
561 BT->getKind() <= BuiltinType::Int128;
562 if (const EnumType *ET = dyn_cast<EnumType>(CanonicalType))
563 // Incomplete enum types are not treated as integer types.
564 // FIXME: In C++, enum types are never integer types.
565 return ET->getDecl()->isComplete() && !ET->getDecl()->isScoped();
569 bool Type::hasIntegerRepresentation() const {
570 if (const VectorType *VT = dyn_cast<VectorType>(CanonicalType))
571 return VT->getElementType()->isIntegerType();
573 return isIntegerType();
576 /// \brief Determine whether this type is an integral type.
578 /// This routine determines whether the given type is an integral type per
579 /// C++ [basic.fundamental]p7. Although the C standard does not define the
580 /// term "integral type", it has a similar term "integer type", and in C++
581 /// the two terms are equivalent. However, C's "integer type" includes
582 /// enumeration types, while C++'s "integer type" does not. The \c ASTContext
583 /// parameter is used to determine whether we should be following the C or
584 /// C++ rules when determining whether this type is an integral/integer type.
586 /// For cases where C permits "an integer type" and C++ permits "an integral
587 /// type", use this routine.
589 /// For cases where C permits "an integer type" and C++ permits "an integral
590 /// or enumeration type", use \c isIntegralOrEnumerationType() instead.
592 /// \param Ctx The context in which this type occurs.
594 /// \returns true if the type is considered an integral type, false otherwise.
595 bool Type::isIntegralType(ASTContext &Ctx) const {
596 if (const BuiltinType *BT = dyn_cast<BuiltinType>(CanonicalType))
597 return BT->getKind() >= BuiltinType::Bool &&
598 BT->getKind() <= BuiltinType::Int128;
600 if (!Ctx.getLangOptions().CPlusPlus)
601 if (const EnumType *ET = dyn_cast<EnumType>(CanonicalType))
602 return ET->getDecl()->isComplete(); // Complete enum types are integral in C.
607 bool Type::isIntegralOrEnumerationType() const {
608 if (const BuiltinType *BT = dyn_cast<BuiltinType>(CanonicalType))
609 return BT->getKind() >= BuiltinType::Bool &&
610 BT->getKind() <= BuiltinType::Int128;
612 // Check for a complete enum type; incomplete enum types are not properly an
613 // enumeration type in the sense required here.
614 if (const EnumType *ET = dyn_cast<EnumType>(CanonicalType))
615 return ET->getDecl()->isComplete();
620 bool Type::isIntegralOrUnscopedEnumerationType() const {
621 if (const BuiltinType *BT = dyn_cast<BuiltinType>(CanonicalType))
622 return BT->getKind() >= BuiltinType::Bool &&
623 BT->getKind() <= BuiltinType::Int128;
625 // Check for a complete enum type; incomplete enum types are not properly an
626 // enumeration type in the sense required here.
627 // C++0x: However, if the underlying type of the enum is fixed, it is
628 // considered complete.
629 if (const EnumType *ET = dyn_cast<EnumType>(CanonicalType))
630 return ET->getDecl()->isComplete() && !ET->getDecl()->isScoped();
636 bool Type::isBooleanType() const {
637 if (const BuiltinType *BT = dyn_cast<BuiltinType>(CanonicalType))
638 return BT->getKind() == BuiltinType::Bool;
642 bool Type::isCharType() const {
643 if (const BuiltinType *BT = dyn_cast<BuiltinType>(CanonicalType))
644 return BT->getKind() == BuiltinType::Char_U ||
645 BT->getKind() == BuiltinType::UChar ||
646 BT->getKind() == BuiltinType::Char_S ||
647 BT->getKind() == BuiltinType::SChar;
651 bool Type::isWideCharType() const {
652 if (const BuiltinType *BT = dyn_cast<BuiltinType>(CanonicalType))
653 return BT->getKind() == BuiltinType::WChar_S ||
654 BT->getKind() == BuiltinType::WChar_U;
658 bool Type::isChar16Type() const {
659 if (const BuiltinType *BT = dyn_cast<BuiltinType>(CanonicalType))
660 return BT->getKind() == BuiltinType::Char16;
664 bool Type::isChar32Type() const {
665 if (const BuiltinType *BT = dyn_cast<BuiltinType>(CanonicalType))
666 return BT->getKind() == BuiltinType::Char32;
670 /// \brief Determine whether this type is any of the built-in character
672 bool Type::isAnyCharacterType() const {
673 const BuiltinType *BT = dyn_cast<BuiltinType>(CanonicalType);
674 if (BT == 0) return false;
675 switch (BT->getKind()) {
676 default: return false;
677 case BuiltinType::Char_U:
678 case BuiltinType::UChar:
679 case BuiltinType::WChar_U:
680 case BuiltinType::Char16:
681 case BuiltinType::Char32:
682 case BuiltinType::Char_S:
683 case BuiltinType::SChar:
684 case BuiltinType::WChar_S:
689 /// isSignedIntegerType - Return true if this is an integer type that is
690 /// signed, according to C99 6.2.5p4 [char, signed char, short, int, long..],
691 /// an enum decl which has a signed representation
692 bool Type::isSignedIntegerType() const {
693 if (const BuiltinType *BT = dyn_cast<BuiltinType>(CanonicalType)) {
694 return BT->getKind() >= BuiltinType::Char_S &&
695 BT->getKind() <= BuiltinType::Int128;
698 if (const EnumType *ET = dyn_cast<EnumType>(CanonicalType)) {
699 // Incomplete enum types are not treated as integer types.
700 // FIXME: In C++, enum types are never integer types.
701 if (ET->getDecl()->isComplete() && !ET->getDecl()->isScoped())
702 return ET->getDecl()->getIntegerType()->isSignedIntegerType();
708 bool Type::isSignedIntegerOrEnumerationType() const {
709 if (const BuiltinType *BT = dyn_cast<BuiltinType>(CanonicalType)) {
710 return BT->getKind() >= BuiltinType::Char_S &&
711 BT->getKind() <= BuiltinType::Int128;
714 if (const EnumType *ET = dyn_cast<EnumType>(CanonicalType)) {
715 if (ET->getDecl()->isComplete())
716 return ET->getDecl()->getIntegerType()->isSignedIntegerType();
722 bool Type::hasSignedIntegerRepresentation() const {
723 if (const VectorType *VT = dyn_cast<VectorType>(CanonicalType))
724 return VT->getElementType()->isSignedIntegerType();
726 return isSignedIntegerType();
729 /// isUnsignedIntegerType - Return true if this is an integer type that is
730 /// unsigned, according to C99 6.2.5p6 [which returns true for _Bool], an enum
731 /// decl which has an unsigned representation
732 bool Type::isUnsignedIntegerType() const {
733 if (const BuiltinType *BT = dyn_cast<BuiltinType>(CanonicalType)) {
734 return BT->getKind() >= BuiltinType::Bool &&
735 BT->getKind() <= BuiltinType::UInt128;
738 if (const EnumType *ET = dyn_cast<EnumType>(CanonicalType)) {
739 // Incomplete enum types are not treated as integer types.
740 // FIXME: In C++, enum types are never integer types.
741 if (ET->getDecl()->isComplete() && !ET->getDecl()->isScoped())
742 return ET->getDecl()->getIntegerType()->isUnsignedIntegerType();
748 bool Type::isUnsignedIntegerOrEnumerationType() const {
749 if (const BuiltinType *BT = dyn_cast<BuiltinType>(CanonicalType)) {
750 return BT->getKind() >= BuiltinType::Bool &&
751 BT->getKind() <= BuiltinType::UInt128;
754 if (const EnumType *ET = dyn_cast<EnumType>(CanonicalType)) {
755 if (ET->getDecl()->isComplete())
756 return ET->getDecl()->getIntegerType()->isUnsignedIntegerType();
762 bool Type::hasUnsignedIntegerRepresentation() const {
763 if (const VectorType *VT = dyn_cast<VectorType>(CanonicalType))
764 return VT->getElementType()->isUnsignedIntegerType();
766 return isUnsignedIntegerType();
769 bool Type::isHalfType() const {
770 if (const BuiltinType *BT = dyn_cast<BuiltinType>(CanonicalType))
771 return BT->getKind() == BuiltinType::Half;
772 // FIXME: Should we allow complex __fp16? Probably not.
776 bool Type::isFloatingType() const {
777 if (const BuiltinType *BT = dyn_cast<BuiltinType>(CanonicalType))
778 return BT->getKind() >= BuiltinType::Half &&
779 BT->getKind() <= BuiltinType::LongDouble;
780 if (const ComplexType *CT = dyn_cast<ComplexType>(CanonicalType))
781 return CT->getElementType()->isFloatingType();
785 bool Type::hasFloatingRepresentation() const {
786 if (const VectorType *VT = dyn_cast<VectorType>(CanonicalType))
787 return VT->getElementType()->isFloatingType();
789 return isFloatingType();
792 bool Type::isRealFloatingType() const {
793 if (const BuiltinType *BT = dyn_cast<BuiltinType>(CanonicalType))
794 return BT->isFloatingPoint();
798 bool Type::isRealType() const {
799 if (const BuiltinType *BT = dyn_cast<BuiltinType>(CanonicalType))
800 return BT->getKind() >= BuiltinType::Bool &&
801 BT->getKind() <= BuiltinType::LongDouble;
802 if (const EnumType *ET = dyn_cast<EnumType>(CanonicalType))
803 return ET->getDecl()->isComplete() && !ET->getDecl()->isScoped();
807 bool Type::isArithmeticType() const {
808 if (const BuiltinType *BT = dyn_cast<BuiltinType>(CanonicalType))
809 return BT->getKind() >= BuiltinType::Bool &&
810 BT->getKind() <= BuiltinType::LongDouble;
811 if (const EnumType *ET = dyn_cast<EnumType>(CanonicalType))
812 // GCC allows forward declaration of enum types (forbid by C99 6.7.2.3p2).
813 // If a body isn't seen by the time we get here, return false.
815 // C++0x: Enumerations are not arithmetic types. For now, just return
816 // false for scoped enumerations since that will disable any
817 // unwanted implicit conversions.
818 return !ET->getDecl()->isScoped() && ET->getDecl()->isComplete();
819 return isa<ComplexType>(CanonicalType);
822 bool Type::isScalarType() const {
823 if (const BuiltinType *BT = dyn_cast<BuiltinType>(CanonicalType))
824 return BT->getKind() > BuiltinType::Void &&
825 BT->getKind() <= BuiltinType::NullPtr;
826 if (const EnumType *ET = dyn_cast<EnumType>(CanonicalType))
827 // Enums are scalar types, but only if they are defined. Incomplete enums
828 // are not treated as scalar types.
829 return ET->getDecl()->isComplete();
830 return isa<PointerType>(CanonicalType) ||
831 isa<BlockPointerType>(CanonicalType) ||
832 isa<MemberPointerType>(CanonicalType) ||
833 isa<ComplexType>(CanonicalType) ||
834 isa<ObjCObjectPointerType>(CanonicalType);
837 Type::ScalarTypeKind Type::getScalarTypeKind() const {
838 assert(isScalarType());
840 const Type *T = CanonicalType.getTypePtr();
841 if (const BuiltinType *BT = dyn_cast<BuiltinType>(T)) {
842 if (BT->getKind() == BuiltinType::Bool) return STK_Bool;
843 if (BT->getKind() == BuiltinType::NullPtr) return STK_CPointer;
844 if (BT->isInteger()) return STK_Integral;
845 if (BT->isFloatingPoint()) return STK_Floating;
846 llvm_unreachable("unknown scalar builtin type");
847 } else if (isa<PointerType>(T)) {
849 } else if (isa<BlockPointerType>(T)) {
850 return STK_BlockPointer;
851 } else if (isa<ObjCObjectPointerType>(T)) {
852 return STK_ObjCObjectPointer;
853 } else if (isa<MemberPointerType>(T)) {
854 return STK_MemberPointer;
855 } else if (isa<EnumType>(T)) {
856 assert(cast<EnumType>(T)->getDecl()->isComplete());
858 } else if (const ComplexType *CT = dyn_cast<ComplexType>(T)) {
859 if (CT->getElementType()->isRealFloatingType())
860 return STK_FloatingComplex;
861 return STK_IntegralComplex;
864 llvm_unreachable("unknown scalar type");
867 /// \brief Determines whether the type is a C++ aggregate type or C
868 /// aggregate or union type.
870 /// An aggregate type is an array or a class type (struct, union, or
871 /// class) that has no user-declared constructors, no private or
872 /// protected non-static data members, no base classes, and no virtual
873 /// functions (C++ [dcl.init.aggr]p1). The notion of an aggregate type
874 /// subsumes the notion of C aggregates (C99 6.2.5p21) because it also
875 /// includes union types.
876 bool Type::isAggregateType() const {
877 if (const RecordType *Record = dyn_cast<RecordType>(CanonicalType)) {
878 if (CXXRecordDecl *ClassDecl = dyn_cast<CXXRecordDecl>(Record->getDecl()))
879 return ClassDecl->isAggregate();
884 return isa<ArrayType>(CanonicalType);
887 /// isConstantSizeType - Return true if this is not a variable sized type,
888 /// according to the rules of C99 6.7.5p3. It is not legal to call this on
889 /// incomplete types or dependent types.
890 bool Type::isConstantSizeType() const {
891 assert(!isIncompleteType() && "This doesn't make sense for incomplete types");
892 assert(!isDependentType() && "This doesn't make sense for dependent types");
893 // The VAT must have a size, as it is known to be complete.
894 return !isa<VariableArrayType>(CanonicalType);
897 /// isIncompleteType - Return true if this is an incomplete type (C99 6.2.5p1)
898 /// - a type that can describe objects, but which lacks information needed to
899 /// determine its size.
900 bool Type::isIncompleteType() const {
901 switch (CanonicalType->getTypeClass()) {
902 default: return false;
904 // Void is the only incomplete builtin type. Per C99 6.2.5p19, it can never
908 // An enumeration with fixed underlying type is complete (C++0x 7.2p3).
909 if (cast<EnumType>(CanonicalType)->getDecl()->isFixed())
913 // A tagged type (struct/union/enum/class) is incomplete if the decl is a
914 // forward declaration, but not a full definition (C99 6.2.5p22).
915 return !cast<TagType>(CanonicalType)->getDecl()->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()->isIncompleteType();
922 case IncompleteArray:
923 // An array of unknown size is an incomplete type (C99 6.2.5p22).
926 return cast<ObjCObjectType>(CanonicalType)->getBaseType()
927 ->isIncompleteType();
929 // ObjC interfaces are incomplete if they are @class, not @interface.
930 return cast<ObjCInterfaceType>(CanonicalType)->getDecl()->isForwardDecl();
934 bool QualType::isPODType(ASTContext &Context) const {
935 // The compiler shouldn't query this for incomplete types, but the user might.
936 // We return false for that case. Except for incomplete arrays of PODs, which
937 // are PODs according to the standard.
941 if ((*this)->isIncompleteArrayType())
942 return Context.getBaseElementType(*this).isPODType(Context);
944 if ((*this)->isIncompleteType())
947 if (Context.getLangOptions().ObjCAutoRefCount) {
948 switch (getObjCLifetime()) {
949 case Qualifiers::OCL_ExplicitNone:
952 case Qualifiers::OCL_Strong:
953 case Qualifiers::OCL_Weak:
954 case Qualifiers::OCL_Autoreleasing:
957 case Qualifiers::OCL_None:
962 QualType CanonicalType = getTypePtr()->CanonicalType;
963 switch (CanonicalType->getTypeClass()) {
964 // Everything not explicitly mentioned is not POD.
965 default: return false;
966 case Type::VariableArray:
967 case Type::ConstantArray:
968 // IncompleteArray is handled above.
969 return Context.getBaseElementType(*this).isPODType(Context);
971 case Type::ObjCObjectPointer:
972 case Type::BlockPointer:
976 case Type::MemberPointer:
978 case Type::ExtVector:
985 if (CXXRecordDecl *ClassDecl
986 = dyn_cast<CXXRecordDecl>(cast<RecordType>(CanonicalType)->getDecl()))
987 return ClassDecl->isPOD();
989 // C struct/union is POD.
994 bool QualType::isTrivialType(ASTContext &Context) const {
995 // The compiler shouldn't query this for incomplete types, but the user might.
996 // We return false for that case. Except for incomplete arrays of PODs, which
997 // are PODs according to the standard.
1001 if ((*this)->isArrayType())
1002 return Context.getBaseElementType(*this).isTrivialType(Context);
1004 // Return false for incomplete types after skipping any incomplete array
1005 // types which are expressly allowed by the standard and thus our API.
1006 if ((*this)->isIncompleteType())
1009 if (Context.getLangOptions().ObjCAutoRefCount) {
1010 switch (getObjCLifetime()) {
1011 case Qualifiers::OCL_ExplicitNone:
1014 case Qualifiers::OCL_Strong:
1015 case Qualifiers::OCL_Weak:
1016 case Qualifiers::OCL_Autoreleasing:
1019 case Qualifiers::OCL_None:
1020 if ((*this)->isObjCLifetimeType())
1026 QualType CanonicalType = getTypePtr()->CanonicalType;
1027 if (CanonicalType->isDependentType())
1030 // C++0x [basic.types]p9:
1031 // Scalar types, trivial class types, arrays of such types, and
1032 // cv-qualified versions of these types are collectively called trivial
1035 // As an extension, Clang treats vector types as Scalar types.
1036 if (CanonicalType->isScalarType() || CanonicalType->isVectorType())
1038 if (const RecordType *RT = CanonicalType->getAs<RecordType>()) {
1039 if (const CXXRecordDecl *ClassDecl =
1040 dyn_cast<CXXRecordDecl>(RT->getDecl())) {
1042 // A trivial class is a class that has a trivial default constructor
1043 if (!ClassDecl->hasTrivialDefaultConstructor()) return false;
1044 // and is trivially copyable.
1045 if (!ClassDecl->isTriviallyCopyable()) return false;
1051 // No other types can match.
1055 bool QualType::isTriviallyCopyableType(ASTContext &Context) const {
1056 if ((*this)->isArrayType())
1057 return Context.getBaseElementType(*this).isTrivialType(Context);
1059 if (Context.getLangOptions().ObjCAutoRefCount) {
1060 switch (getObjCLifetime()) {
1061 case Qualifiers::OCL_ExplicitNone:
1064 case Qualifiers::OCL_Strong:
1065 case Qualifiers::OCL_Weak:
1066 case Qualifiers::OCL_Autoreleasing:
1069 case Qualifiers::OCL_None:
1070 if ((*this)->isObjCLifetimeType())
1076 // C++0x [basic.types]p9
1077 // Scalar types, trivially copyable class types, arrays of such types, and
1078 // cv-qualified versions of these types are collectively called trivial
1081 QualType CanonicalType = getCanonicalType();
1082 if (CanonicalType->isDependentType())
1085 // Return false for incomplete types after skipping any incomplete array types
1086 // which are expressly allowed by the standard and thus our API.
1087 if (CanonicalType->isIncompleteType())
1090 // As an extension, Clang treats vector types as Scalar types.
1091 if (CanonicalType->isScalarType() || CanonicalType->isVectorType())
1094 if (const RecordType *RT = CanonicalType->getAs<RecordType>()) {
1095 if (const CXXRecordDecl *ClassDecl =
1096 dyn_cast<CXXRecordDecl>(RT->getDecl())) {
1097 if (!ClassDecl->isTriviallyCopyable()) return false;
1103 // No other types can match.
1109 bool Type::isLiteralType() const {
1110 if (isDependentType())
1113 // C++0x [basic.types]p10:
1114 // A type is a literal type if it is:
1116 // -- an array of literal type.
1117 // Extension: variable arrays cannot be literal types, since they're
1119 if (isVariableArrayType())
1121 const Type *BaseTy = getBaseElementTypeUnsafe();
1122 assert(BaseTy && "NULL element type");
1124 // Return false for incomplete types after skipping any incomplete array
1125 // types; those are expressly allowed by the standard and thus our API.
1126 if (BaseTy->isIncompleteType())
1129 // Objective-C lifetime types are not literal types.
1130 if (BaseTy->isObjCRetainableType())
1133 // C++0x [basic.types]p10:
1134 // A type is a literal type if it is:
1135 // -- a scalar type; or
1136 // As an extension, Clang treats vector types as literal types.
1137 if (BaseTy->isScalarType() || BaseTy->isVectorType())
1139 // -- a reference type; or
1140 if (BaseTy->isReferenceType())
1142 // -- a class type that has all of the following properties:
1143 if (const RecordType *RT = BaseTy->getAs<RecordType>()) {
1144 // -- a trivial destructor,
1145 // -- every constructor call and full-expression in the
1146 // brace-or-equal-initializers for non-static data members (if any)
1147 // is a constant expression,
1148 // -- it is an aggregate type or has at least one constexpr
1149 // constructor or constructor template that is not a copy or move
1151 // -- all non-static data members and base classes of literal types
1153 // We resolve DR1361 by ignoring the second bullet.
1154 if (const CXXRecordDecl *ClassDecl =
1155 dyn_cast<CXXRecordDecl>(RT->getDecl()))
1156 return ClassDecl->isLiteral();
1164 bool Type::isStandardLayoutType() const {
1165 if (isDependentType())
1168 // C++0x [basic.types]p9:
1169 // Scalar types, standard-layout class types, arrays of such types, and
1170 // cv-qualified versions of these types are collectively called
1171 // standard-layout types.
1172 const Type *BaseTy = getBaseElementTypeUnsafe();
1173 assert(BaseTy && "NULL element type");
1175 // Return false for incomplete types after skipping any incomplete array
1176 // types which are expressly allowed by the standard and thus our API.
1177 if (BaseTy->isIncompleteType())
1180 // As an extension, Clang treats vector types as Scalar types.
1181 if (BaseTy->isScalarType() || BaseTy->isVectorType()) return true;
1182 if (const RecordType *RT = BaseTy->getAs<RecordType>()) {
1183 if (const CXXRecordDecl *ClassDecl =
1184 dyn_cast<CXXRecordDecl>(RT->getDecl()))
1185 if (!ClassDecl->isStandardLayout())
1188 // Default to 'true' for non-C++ class types.
1189 // FIXME: This is a bit dubious, but plain C structs should trivially meet
1190 // all the requirements of standard layout classes.
1194 // No other types can match.
1198 // This is effectively the intersection of isTrivialType and
1199 // isStandardLayoutType. We implement it directly to avoid redundant
1200 // conversions from a type to a CXXRecordDecl.
1201 bool QualType::isCXX11PODType(ASTContext &Context) const {
1202 const Type *ty = getTypePtr();
1203 if (ty->isDependentType())
1206 if (Context.getLangOptions().ObjCAutoRefCount) {
1207 switch (getObjCLifetime()) {
1208 case Qualifiers::OCL_ExplicitNone:
1211 case Qualifiers::OCL_Strong:
1212 case Qualifiers::OCL_Weak:
1213 case Qualifiers::OCL_Autoreleasing:
1216 case Qualifiers::OCL_None:
1217 if (ty->isObjCLifetimeType())
1223 // C++11 [basic.types]p9:
1224 // Scalar types, POD classes, arrays of such types, and cv-qualified
1225 // versions of these types are collectively called trivial types.
1226 const Type *BaseTy = ty->getBaseElementTypeUnsafe();
1227 assert(BaseTy && "NULL element type");
1229 // Return false for incomplete types after skipping any incomplete array
1230 // types which are expressly allowed by the standard and thus our API.
1231 if (BaseTy->isIncompleteType())
1234 // As an extension, Clang treats vector types as Scalar types.
1235 if (BaseTy->isScalarType() || BaseTy->isVectorType()) return true;
1236 if (const RecordType *RT = BaseTy->getAs<RecordType>()) {
1237 if (const CXXRecordDecl *ClassDecl =
1238 dyn_cast<CXXRecordDecl>(RT->getDecl())) {
1239 // C++11 [class]p10:
1240 // A POD struct is a non-union class that is both a trivial class [...]
1241 if (!ClassDecl->isTrivial()) return false;
1243 // C++11 [class]p10:
1244 // A POD struct is a non-union class that is both a trivial class and
1245 // a standard-layout class [...]
1246 if (!ClassDecl->isStandardLayout()) return false;
1248 // C++11 [class]p10:
1249 // A POD struct is a non-union class that is both a trivial class and
1250 // a standard-layout class, and has no non-static data members of type
1251 // non-POD struct, non-POD union (or array of such types). [...]
1253 // We don't directly query the recursive aspect as the requiremets for
1254 // both standard-layout classes and trivial classes apply recursively
1261 // No other types can match.
1265 bool Type::isPromotableIntegerType() const {
1266 if (const BuiltinType *BT = getAs<BuiltinType>())
1267 switch (BT->getKind()) {
1268 case BuiltinType::Bool:
1269 case BuiltinType::Char_S:
1270 case BuiltinType::Char_U:
1271 case BuiltinType::SChar:
1272 case BuiltinType::UChar:
1273 case BuiltinType::Short:
1274 case BuiltinType::UShort:
1280 // Enumerated types are promotable to their compatible integer types
1281 // (C99 6.3.1.1) a.k.a. its underlying type (C++ [conv.prom]p2).
1282 if (const EnumType *ET = getAs<EnumType>()){
1283 if (this->isDependentType() || ET->getDecl()->getPromotionType().isNull()
1284 || ET->getDecl()->isScoped())
1287 const BuiltinType *BT
1288 = ET->getDecl()->getPromotionType()->getAs<BuiltinType>();
1289 return BT->getKind() == BuiltinType::Int
1290 || BT->getKind() == BuiltinType::UInt;
1296 bool Type::isNullPtrType() const {
1297 if (const BuiltinType *BT = getAs<BuiltinType>())
1298 return BT->getKind() == BuiltinType::NullPtr;
1302 bool Type::isSpecifierType() const {
1303 // Note that this intentionally does not use the canonical type.
1304 switch (getTypeClass()) {
1312 case TemplateTypeParm:
1313 case SubstTemplateTypeParm:
1314 case TemplateSpecialization:
1317 case DependentTemplateSpecialization:
1320 case ObjCObjectPointer: // FIXME: object pointers aren't really specifiers
1327 ElaboratedTypeKeyword
1328 TypeWithKeyword::getKeywordForTypeSpec(unsigned TypeSpec) {
1330 default: return ETK_None;
1331 case TST_typename: return ETK_Typename;
1332 case TST_class: return ETK_Class;
1333 case TST_struct: return ETK_Struct;
1334 case TST_union: return ETK_Union;
1335 case TST_enum: return ETK_Enum;
1340 TypeWithKeyword::getTagTypeKindForTypeSpec(unsigned TypeSpec) {
1342 case TST_class: return TTK_Class;
1343 case TST_struct: return TTK_Struct;
1344 case TST_union: return TTK_Union;
1345 case TST_enum: return TTK_Enum;
1348 llvm_unreachable("Type specifier is not a tag type kind.");
1352 ElaboratedTypeKeyword
1353 TypeWithKeyword::getKeywordForTagTypeKind(TagTypeKind Kind) {
1355 case TTK_Class: return ETK_Class;
1356 case TTK_Struct: return ETK_Struct;
1357 case TTK_Union: return ETK_Union;
1358 case TTK_Enum: return ETK_Enum;
1360 llvm_unreachable("Unknown tag type kind.");
1364 TypeWithKeyword::getTagTypeKindForKeyword(ElaboratedTypeKeyword Keyword) {
1366 case ETK_Class: return TTK_Class;
1367 case ETK_Struct: return TTK_Struct;
1368 case ETK_Union: return TTK_Union;
1369 case ETK_Enum: return TTK_Enum;
1370 case ETK_None: // Fall through.
1372 llvm_unreachable("Elaborated type keyword is not a tag type kind.");
1374 llvm_unreachable("Unknown elaborated type keyword.");
1378 TypeWithKeyword::KeywordIsTagTypeKind(ElaboratedTypeKeyword Keyword) {
1389 llvm_unreachable("Unknown elaborated type keyword.");
1393 TypeWithKeyword::getKeywordName(ElaboratedTypeKeyword Keyword) {
1395 case ETK_None: return "";
1396 case ETK_Typename: return "typename";
1397 case ETK_Class: return "class";
1398 case ETK_Struct: return "struct";
1399 case ETK_Union: return "union";
1400 case ETK_Enum: return "enum";
1403 llvm_unreachable("Unknown elaborated type keyword.");
1407 DependentTemplateSpecializationType::DependentTemplateSpecializationType(
1408 ElaboratedTypeKeyword Keyword,
1409 NestedNameSpecifier *NNS, const IdentifierInfo *Name,
1410 unsigned NumArgs, const TemplateArgument *Args,
1412 : TypeWithKeyword(Keyword, DependentTemplateSpecialization, Canon, true, true,
1413 /*VariablyModified=*/false,
1414 NNS && NNS->containsUnexpandedParameterPack()),
1415 NNS(NNS), Name(Name), NumArgs(NumArgs) {
1416 assert((!NNS || NNS->isDependent()) &&
1417 "DependentTemplateSpecializatonType requires dependent qualifier");
1418 for (unsigned I = 0; I != NumArgs; ++I) {
1419 if (Args[I].containsUnexpandedParameterPack())
1420 setContainsUnexpandedParameterPack();
1422 new (&getArgBuffer()[I]) TemplateArgument(Args[I]);
1427 DependentTemplateSpecializationType::Profile(llvm::FoldingSetNodeID &ID,
1428 const ASTContext &Context,
1429 ElaboratedTypeKeyword Keyword,
1430 NestedNameSpecifier *Qualifier,
1431 const IdentifierInfo *Name,
1433 const TemplateArgument *Args) {
1434 ID.AddInteger(Keyword);
1435 ID.AddPointer(Qualifier);
1436 ID.AddPointer(Name);
1437 for (unsigned Idx = 0; Idx < NumArgs; ++Idx)
1438 Args[Idx].Profile(ID, Context);
1441 bool Type::isElaboratedTypeSpecifier() const {
1442 ElaboratedTypeKeyword Keyword;
1443 if (const ElaboratedType *Elab = dyn_cast<ElaboratedType>(this))
1444 Keyword = Elab->getKeyword();
1445 else if (const DependentNameType *DepName = dyn_cast<DependentNameType>(this))
1446 Keyword = DepName->getKeyword();
1447 else if (const DependentTemplateSpecializationType *DepTST =
1448 dyn_cast<DependentTemplateSpecializationType>(this))
1449 Keyword = DepTST->getKeyword();
1453 return TypeWithKeyword::KeywordIsTagTypeKind(Keyword);
1456 const char *Type::getTypeClassName() const {
1457 switch (TypeBits.TC) {
1458 #define ABSTRACT_TYPE(Derived, Base)
1459 #define TYPE(Derived, Base) case Derived: return #Derived;
1460 #include "clang/AST/TypeNodes.def"
1463 llvm_unreachable("Invalid type class.");
1467 const char *BuiltinType::getName(const PrintingPolicy &Policy) const {
1468 switch (getKind()) {
1469 case Void: return "void";
1470 case Bool: return Policy.Bool ? "bool" : "_Bool";
1471 case Char_S: return "char";
1472 case Char_U: return "char";
1473 case SChar: return "signed char";
1474 case Short: return "short";
1475 case Int: return "int";
1476 case Long: return "long";
1477 case LongLong: return "long long";
1478 case Int128: return "__int128_t";
1479 case UChar: return "unsigned char";
1480 case UShort: return "unsigned short";
1481 case UInt: return "unsigned int";
1482 case ULong: return "unsigned long";
1483 case ULongLong: return "unsigned long long";
1484 case UInt128: return "__uint128_t";
1485 case Half: return "half";
1486 case Float: return "float";
1487 case Double: return "double";
1488 case LongDouble: return "long double";
1490 case WChar_U: return "wchar_t";
1491 case Char16: return "char16_t";
1492 case Char32: return "char32_t";
1493 case NullPtr: return "nullptr_t";
1494 case Overload: return "<overloaded function type>";
1495 case BoundMember: return "<bound member function type>";
1496 case Dependent: return "<dependent type>";
1497 case UnknownAny: return "<unknown type>";
1498 case ObjCId: return "id";
1499 case ObjCClass: return "Class";
1500 case ObjCSel: return "SEL";
1503 llvm_unreachable("Invalid builtin type.");
1507 QualType QualType::getNonLValueExprType(ASTContext &Context) const {
1508 if (const ReferenceType *RefType = getTypePtr()->getAs<ReferenceType>())
1509 return RefType->getPointeeType();
1511 // C++0x [basic.lval]:
1512 // Class prvalues can have cv-qualified types; non-class prvalues always
1513 // have cv-unqualified types.
1515 // See also C99 6.3.2.1p2.
1516 if (!Context.getLangOptions().CPlusPlus ||
1517 (!getTypePtr()->isDependentType() && !getTypePtr()->isRecordType()))
1518 return getUnqualifiedType();
1523 StringRef FunctionType::getNameForCallConv(CallingConv CC) {
1526 llvm_unreachable("no name for default cc");
1529 case CC_C: return "cdecl";
1530 case CC_X86StdCall: return "stdcall";
1531 case CC_X86FastCall: return "fastcall";
1532 case CC_X86ThisCall: return "thiscall";
1533 case CC_X86Pascal: return "pascal";
1534 case CC_AAPCS: return "aapcs";
1535 case CC_AAPCS_VFP: return "aapcs-vfp";
1538 llvm_unreachable("Invalid calling convention.");
1542 FunctionProtoType::FunctionProtoType(QualType result, const QualType *args,
1543 unsigned numArgs, QualType canonical,
1544 const ExtProtoInfo &epi)
1545 : FunctionType(FunctionProto, result, epi.Variadic, epi.TypeQuals,
1546 epi.RefQualifier, canonical,
1547 result->isDependentType(),
1548 result->isInstantiationDependentType(),
1549 result->isVariablyModifiedType(),
1550 result->containsUnexpandedParameterPack(),
1552 NumArgs(numArgs), NumExceptions(epi.NumExceptions),
1553 ExceptionSpecType(epi.ExceptionSpecType),
1554 HasAnyConsumedArgs(epi.ConsumedArguments != 0)
1556 // Fill in the trailing argument array.
1557 QualType *argSlot = reinterpret_cast<QualType*>(this+1);
1558 for (unsigned i = 0; i != numArgs; ++i) {
1559 if (args[i]->isDependentType())
1561 else if (args[i]->isInstantiationDependentType())
1562 setInstantiationDependent();
1564 if (args[i]->containsUnexpandedParameterPack())
1565 setContainsUnexpandedParameterPack();
1567 argSlot[i] = args[i];
1570 if (getExceptionSpecType() == EST_Dynamic) {
1571 // Fill in the exception array.
1572 QualType *exnSlot = argSlot + numArgs;
1573 for (unsigned i = 0, e = epi.NumExceptions; i != e; ++i) {
1574 if (epi.Exceptions[i]->isDependentType())
1576 else if (epi.Exceptions[i]->isInstantiationDependentType())
1577 setInstantiationDependent();
1579 if (epi.Exceptions[i]->containsUnexpandedParameterPack())
1580 setContainsUnexpandedParameterPack();
1582 exnSlot[i] = epi.Exceptions[i];
1584 } else if (getExceptionSpecType() == EST_ComputedNoexcept) {
1585 // Store the noexcept expression and context.
1586 Expr **noexSlot = reinterpret_cast<Expr**>(argSlot + numArgs);
1587 *noexSlot = epi.NoexceptExpr;
1589 if (epi.NoexceptExpr) {
1590 if (epi.NoexceptExpr->isValueDependent()
1591 || epi.NoexceptExpr->isTypeDependent())
1593 else if (epi.NoexceptExpr->isInstantiationDependent())
1594 setInstantiationDependent();
1598 if (epi.ConsumedArguments) {
1599 bool *consumedArgs = const_cast<bool*>(getConsumedArgsBuffer());
1600 for (unsigned i = 0; i != numArgs; ++i)
1601 consumedArgs[i] = epi.ConsumedArguments[i];
1605 FunctionProtoType::NoexceptResult
1606 FunctionProtoType::getNoexceptSpec(ASTContext &ctx) const {
1607 ExceptionSpecificationType est = getExceptionSpecType();
1608 if (est == EST_BasicNoexcept)
1611 if (est != EST_ComputedNoexcept)
1612 return NR_NoNoexcept;
1614 Expr *noexceptExpr = getNoexceptExpr();
1616 return NR_BadNoexcept;
1617 if (noexceptExpr->isValueDependent())
1618 return NR_Dependent;
1621 bool isICE = noexceptExpr->isIntegerConstantExpr(value, ctx, 0,
1622 /*evaluated*/false);
1624 assert(isICE && "AST should not contain bad noexcept expressions.");
1626 return value.getBoolValue() ? NR_Nothrow : NR_Throw;
1629 bool FunctionProtoType::isTemplateVariadic() const {
1630 for (unsigned ArgIdx = getNumArgs(); ArgIdx; --ArgIdx)
1631 if (isa<PackExpansionType>(getArgType(ArgIdx - 1)))
1637 void FunctionProtoType::Profile(llvm::FoldingSetNodeID &ID, QualType Result,
1638 const QualType *ArgTys, unsigned NumArgs,
1639 const ExtProtoInfo &epi,
1640 const ASTContext &Context) {
1642 // We have to be careful not to get ambiguous profile encodings.
1643 // Note that valid type pointers are never ambiguous with anything else.
1645 // The encoding grammar begins:
1646 // type type* bool int bool
1647 // If that final bool is true, then there is a section for the EH spec:
1649 // This is followed by an optional "consumed argument" section of the
1650 // same length as the first type sequence:
1652 // Finally, we have the ext info:
1655 // There is no ambiguity between the consumed arguments and an empty EH
1656 // spec because of the leading 'bool' which unambiguously indicates
1657 // whether the following bool is the EH spec or part of the arguments.
1659 ID.AddPointer(Result.getAsOpaquePtr());
1660 for (unsigned i = 0; i != NumArgs; ++i)
1661 ID.AddPointer(ArgTys[i].getAsOpaquePtr());
1662 // This method is relatively performance sensitive, so as a performance
1663 // shortcut, use one AddInteger call instead of four for the next four
1665 assert(!(unsigned(epi.Variadic) & ~1) &&
1666 !(unsigned(epi.TypeQuals) & ~255) &&
1667 !(unsigned(epi.RefQualifier) & ~3) &&
1668 !(unsigned(epi.ExceptionSpecType) & ~7) &&
1669 "Values larger than expected.");
1670 ID.AddInteger(unsigned(epi.Variadic) +
1671 (epi.TypeQuals << 1) +
1672 (epi.RefQualifier << 9) +
1673 (epi.ExceptionSpecType << 11));
1674 if (epi.ExceptionSpecType == EST_Dynamic) {
1675 for (unsigned i = 0; i != epi.NumExceptions; ++i)
1676 ID.AddPointer(epi.Exceptions[i].getAsOpaquePtr());
1677 } else if (epi.ExceptionSpecType == EST_ComputedNoexcept && epi.NoexceptExpr){
1678 epi.NoexceptExpr->Profile(ID, Context, false);
1680 if (epi.ConsumedArguments) {
1681 for (unsigned i = 0; i != NumArgs; ++i)
1682 ID.AddBoolean(epi.ConsumedArguments[i]);
1684 epi.ExtInfo.Profile(ID);
1687 void FunctionProtoType::Profile(llvm::FoldingSetNodeID &ID,
1688 const ASTContext &Ctx) {
1689 Profile(ID, getResultType(), arg_type_begin(), NumArgs, getExtProtoInfo(),
1693 QualType TypedefType::desugar() const {
1694 return getDecl()->getUnderlyingType();
1697 TypeOfExprType::TypeOfExprType(Expr *E, QualType can)
1698 : Type(TypeOfExpr, can, E->isTypeDependent(),
1699 E->isInstantiationDependent(),
1700 E->getType()->isVariablyModifiedType(),
1701 E->containsUnexpandedParameterPack()),
1705 bool TypeOfExprType::isSugared() const {
1706 return !TOExpr->isTypeDependent();
1709 QualType TypeOfExprType::desugar() const {
1711 return getUnderlyingExpr()->getType();
1713 return QualType(this, 0);
1716 void DependentTypeOfExprType::Profile(llvm::FoldingSetNodeID &ID,
1717 const ASTContext &Context, Expr *E) {
1718 E->Profile(ID, Context, true);
1721 DecltypeType::DecltypeType(Expr *E, QualType underlyingType, QualType can)
1722 : Type(Decltype, can, E->isTypeDependent(),
1723 E->isInstantiationDependent(),
1724 E->getType()->isVariablyModifiedType(),
1725 E->containsUnexpandedParameterPack()),
1727 UnderlyingType(underlyingType) {
1730 bool DecltypeType::isSugared() const { return !E->isInstantiationDependent(); }
1732 QualType DecltypeType::desugar() const {
1734 return getUnderlyingType();
1736 return QualType(this, 0);
1739 DependentDecltypeType::DependentDecltypeType(const ASTContext &Context, Expr *E)
1740 : DecltypeType(E, Context.DependentTy), Context(Context) { }
1742 void DependentDecltypeType::Profile(llvm::FoldingSetNodeID &ID,
1743 const ASTContext &Context, Expr *E) {
1744 E->Profile(ID, Context, true);
1747 TagType::TagType(TypeClass TC, const TagDecl *D, QualType can)
1748 : Type(TC, can, D->isDependentType(),
1749 /*InstantiationDependent=*/D->isDependentType(),
1750 /*VariablyModified=*/false,
1751 /*ContainsUnexpandedParameterPack=*/false),
1752 decl(const_cast<TagDecl*>(D)) {}
1754 static TagDecl *getInterestingTagDecl(TagDecl *decl) {
1755 for (TagDecl::redecl_iterator I = decl->redecls_begin(),
1756 E = decl->redecls_end();
1758 if (I->isCompleteDefinition() || I->isBeingDefined())
1761 // If there's no definition (not even in progress), return what we have.
1765 UnaryTransformType::UnaryTransformType(QualType BaseType,
1766 QualType UnderlyingType,
1768 QualType CanonicalType)
1769 : Type(UnaryTransform, CanonicalType, UnderlyingType->isDependentType(),
1770 UnderlyingType->isInstantiationDependentType(),
1771 UnderlyingType->isVariablyModifiedType(),
1772 BaseType->containsUnexpandedParameterPack())
1773 , BaseType(BaseType), UnderlyingType(UnderlyingType), UKind(UKind)
1776 TagDecl *TagType::getDecl() const {
1777 return getInterestingTagDecl(decl);
1780 bool TagType::isBeingDefined() const {
1781 return getDecl()->isBeingDefined();
1784 CXXRecordDecl *InjectedClassNameType::getDecl() const {
1785 return cast<CXXRecordDecl>(getInterestingTagDecl(Decl));
1788 bool RecordType::classof(const TagType *TT) {
1789 return isa<RecordDecl>(TT->getDecl());
1792 bool EnumType::classof(const TagType *TT) {
1793 return isa<EnumDecl>(TT->getDecl());
1796 IdentifierInfo *TemplateTypeParmType::getIdentifier() const {
1797 return isCanonicalUnqualified() ? 0 : getDecl()->getIdentifier();
1800 SubstTemplateTypeParmPackType::
1801 SubstTemplateTypeParmPackType(const TemplateTypeParmType *Param,
1803 const TemplateArgument &ArgPack)
1804 : Type(SubstTemplateTypeParmPack, Canon, true, true, false, true),
1806 Arguments(ArgPack.pack_begin()), NumArguments(ArgPack.pack_size())
1810 TemplateArgument SubstTemplateTypeParmPackType::getArgumentPack() const {
1811 return TemplateArgument(Arguments, NumArguments);
1814 void SubstTemplateTypeParmPackType::Profile(llvm::FoldingSetNodeID &ID) {
1815 Profile(ID, getReplacedParameter(), getArgumentPack());
1818 void SubstTemplateTypeParmPackType::Profile(llvm::FoldingSetNodeID &ID,
1819 const TemplateTypeParmType *Replaced,
1820 const TemplateArgument &ArgPack) {
1821 ID.AddPointer(Replaced);
1822 ID.AddInteger(ArgPack.pack_size());
1823 for (TemplateArgument::pack_iterator P = ArgPack.pack_begin(),
1824 PEnd = ArgPack.pack_end();
1826 ID.AddPointer(P->getAsType().getAsOpaquePtr());
1829 bool TemplateSpecializationType::
1830 anyDependentTemplateArguments(const TemplateArgumentListInfo &Args,
1831 bool &InstantiationDependent) {
1832 return anyDependentTemplateArguments(Args.getArgumentArray(), Args.size(),
1833 InstantiationDependent);
1836 bool TemplateSpecializationType::
1837 anyDependentTemplateArguments(const TemplateArgumentLoc *Args, unsigned N,
1838 bool &InstantiationDependent) {
1839 for (unsigned i = 0; i != N; ++i) {
1840 if (Args[i].getArgument().isDependent()) {
1841 InstantiationDependent = true;
1845 if (Args[i].getArgument().isInstantiationDependent())
1846 InstantiationDependent = true;
1851 bool TemplateSpecializationType::
1852 anyDependentTemplateArguments(const TemplateArgument *Args, unsigned N,
1853 bool &InstantiationDependent) {
1854 for (unsigned i = 0; i != N; ++i) {
1855 if (Args[i].isDependent()) {
1856 InstantiationDependent = true;
1860 if (Args[i].isInstantiationDependent())
1861 InstantiationDependent = true;
1866 TemplateSpecializationType::
1867 TemplateSpecializationType(TemplateName T,
1868 const TemplateArgument *Args, unsigned NumArgs,
1869 QualType Canon, QualType AliasedType)
1870 : Type(TemplateSpecialization,
1871 Canon.isNull()? QualType(this, 0) : Canon,
1872 Canon.isNull()? T.isDependent() : Canon->isDependentType(),
1873 Canon.isNull()? T.isDependent()
1874 : Canon->isInstantiationDependentType(),
1875 false, T.containsUnexpandedParameterPack()),
1876 Template(T), NumArgs(NumArgs) {
1877 assert(!T.getAsDependentTemplateName() &&
1878 "Use DependentTemplateSpecializationType for dependent template-name");
1879 assert((T.getKind() == TemplateName::Template ||
1880 T.getKind() == TemplateName::SubstTemplateTemplateParm ||
1881 T.getKind() == TemplateName::SubstTemplateTemplateParmPack) &&
1882 "Unexpected template name for TemplateSpecializationType");
1883 bool InstantiationDependent;
1884 (void)InstantiationDependent;
1885 assert((!Canon.isNull() ||
1887 anyDependentTemplateArguments(Args, NumArgs,
1888 InstantiationDependent)) &&
1889 "No canonical type for non-dependent class template specialization");
1891 TemplateArgument *TemplateArgs
1892 = reinterpret_cast<TemplateArgument *>(this + 1);
1893 for (unsigned Arg = 0; Arg < NumArgs; ++Arg) {
1894 // Update dependent and variably-modified bits.
1895 // If the canonical type exists and is non-dependent, the template
1896 // specialization type can be non-dependent even if one of the type
1897 // arguments is. Given:
1898 // template<typename T> using U = int;
1899 // U<T> is always non-dependent, irrespective of the type T.
1900 if (Canon.isNull() && Args[Arg].isDependent())
1902 else if (Args[Arg].isInstantiationDependent())
1903 setInstantiationDependent();
1905 if (Args[Arg].getKind() == TemplateArgument::Type &&
1906 Args[Arg].getAsType()->isVariablyModifiedType())
1907 setVariablyModified();
1908 if (Args[Arg].containsUnexpandedParameterPack())
1909 setContainsUnexpandedParameterPack();
1911 new (&TemplateArgs[Arg]) TemplateArgument(Args[Arg]);
1914 // Store the aliased type if this is a type alias template specialization.
1915 bool IsTypeAlias = !AliasedType.isNull();
1916 assert(IsTypeAlias == isTypeAlias() &&
1917 "allocated wrong size for type alias");
1919 TemplateArgument *Begin = reinterpret_cast<TemplateArgument *>(this + 1);
1920 *reinterpret_cast<QualType*>(Begin + getNumArgs()) = AliasedType;
1925 TemplateSpecializationType::Profile(llvm::FoldingSetNodeID &ID,
1927 const TemplateArgument *Args,
1929 const ASTContext &Context) {
1931 for (unsigned Idx = 0; Idx < NumArgs; ++Idx)
1932 Args[Idx].Profile(ID, Context);
1935 bool TemplateSpecializationType::isTypeAlias() const {
1936 TemplateDecl *D = Template.getAsTemplateDecl();
1937 return D && isa<TypeAliasTemplateDecl>(D);
1941 QualifierCollector::apply(const ASTContext &Context, QualType QT) const {
1942 if (!hasNonFastQualifiers())
1943 return QT.withFastQualifiers(getFastQualifiers());
1945 return Context.getQualifiedType(QT, *this);
1949 QualifierCollector::apply(const ASTContext &Context, const Type *T) const {
1950 if (!hasNonFastQualifiers())
1951 return QualType(T, getFastQualifiers());
1953 return Context.getQualifiedType(T, *this);
1956 void ObjCObjectTypeImpl::Profile(llvm::FoldingSetNodeID &ID,
1958 ObjCProtocolDecl * const *Protocols,
1959 unsigned NumProtocols) {
1960 ID.AddPointer(BaseType.getAsOpaquePtr());
1961 for (unsigned i = 0; i != NumProtocols; i++)
1962 ID.AddPointer(Protocols[i]);
1965 void ObjCObjectTypeImpl::Profile(llvm::FoldingSetNodeID &ID) {
1966 Profile(ID, getBaseType(), qual_begin(), getNumProtocols());
1971 /// \brief The cached properties of a type.
1972 class CachedProperties {
1978 CachedProperties(Linkage linkage, Visibility visibility, bool local)
1979 : linkage(linkage), visibility(visibility), local(local) {}
1981 Linkage getLinkage() const { return (Linkage) linkage; }
1982 Visibility getVisibility() const { return (Visibility) visibility; }
1983 bool hasLocalOrUnnamedType() const { return local; }
1985 friend CachedProperties merge(CachedProperties L, CachedProperties R) {
1986 return CachedProperties(minLinkage(L.getLinkage(), R.getLinkage()),
1987 minVisibility(L.getVisibility(), R.getVisibility()),
1988 L.hasLocalOrUnnamedType() | R.hasLocalOrUnnamedType());
1993 static CachedProperties computeCachedProperties(const Type *T);
1996 /// The type-property cache. This is templated so as to be
1997 /// instantiated at an internal type to prevent unnecessary symbol
1999 template <class Private> class TypePropertyCache {
2001 static CachedProperties get(QualType T) {
2002 return get(T.getTypePtr());
2005 static CachedProperties get(const Type *T) {
2007 return CachedProperties(T->TypeBits.getLinkage(),
2008 T->TypeBits.getVisibility(),
2009 T->TypeBits.hasLocalOrUnnamedType());
2012 static void ensure(const Type *T) {
2013 // If the cache is valid, we're okay.
2014 if (T->TypeBits.isCacheValid()) return;
2016 // If this type is non-canonical, ask its canonical type for the
2017 // relevant information.
2018 if (!T->isCanonicalUnqualified()) {
2019 const Type *CT = T->getCanonicalTypeInternal().getTypePtr();
2021 T->TypeBits.CacheValidAndVisibility =
2022 CT->TypeBits.CacheValidAndVisibility;
2023 T->TypeBits.CachedLinkage = CT->TypeBits.CachedLinkage;
2024 T->TypeBits.CachedLocalOrUnnamed = CT->TypeBits.CachedLocalOrUnnamed;
2028 // Compute the cached properties and then set the cache.
2029 CachedProperties Result = computeCachedProperties(T);
2030 T->TypeBits.CacheValidAndVisibility = Result.getVisibility() + 1U;
2031 assert(T->TypeBits.isCacheValid() &&
2032 T->TypeBits.getVisibility() == Result.getVisibility());
2033 T->TypeBits.CachedLinkage = Result.getLinkage();
2034 T->TypeBits.CachedLocalOrUnnamed = Result.hasLocalOrUnnamedType();
2039 // Instantiate the friend template at a private class. In a
2040 // reasonable implementation, these symbols will be internal.
2041 // It is terrible that this is the best way to accomplish this.
2042 namespace { class Private {}; }
2043 typedef TypePropertyCache<Private> Cache;
2045 static CachedProperties computeCachedProperties(const Type *T) {
2046 switch (T->getTypeClass()) {
2047 #define TYPE(Class,Base)
2048 #define NON_CANONICAL_TYPE(Class,Base) case Type::Class:
2049 #include "clang/AST/TypeNodes.def"
2050 llvm_unreachable("didn't expect a non-canonical type here");
2052 #define TYPE(Class,Base)
2053 #define DEPENDENT_TYPE(Class,Base) case Type::Class:
2054 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class,Base) case Type::Class:
2055 #include "clang/AST/TypeNodes.def"
2056 // Treat instantiation-dependent types as external.
2057 assert(T->isInstantiationDependentType());
2058 return CachedProperties(ExternalLinkage, DefaultVisibility, false);
2061 // C++ [basic.link]p8:
2062 // A type is said to have linkage if and only if:
2063 // - it is a fundamental type (3.9.1); or
2064 return CachedProperties(ExternalLinkage, DefaultVisibility, false);
2068 const TagDecl *Tag = cast<TagType>(T)->getDecl();
2070 // C++ [basic.link]p8:
2071 // - it is a class or enumeration type that is named (or has a name
2072 // for linkage purposes (7.1.3)) and the name has linkage; or
2073 // - it is a specialization of a class template (14); or
2074 NamedDecl::LinkageInfo LV = Tag->getLinkageAndVisibility();
2075 bool IsLocalOrUnnamed =
2076 Tag->getDeclContext()->isFunctionOrMethod() ||
2077 (!Tag->getIdentifier() && !Tag->getTypedefNameForAnonDecl());
2078 return CachedProperties(LV.linkage(), LV.visibility(), IsLocalOrUnnamed);
2081 // C++ [basic.link]p8:
2082 // - it is a compound type (3.9.2) other than a class or enumeration,
2083 // compounded exclusively from types that have linkage; or
2085 return Cache::get(cast<ComplexType>(T)->getElementType());
2087 return Cache::get(cast<PointerType>(T)->getPointeeType());
2088 case Type::BlockPointer:
2089 return Cache::get(cast<BlockPointerType>(T)->getPointeeType());
2090 case Type::LValueReference:
2091 case Type::RValueReference:
2092 return Cache::get(cast<ReferenceType>(T)->getPointeeType());
2093 case Type::MemberPointer: {
2094 const MemberPointerType *MPT = cast<MemberPointerType>(T);
2095 return merge(Cache::get(MPT->getClass()),
2096 Cache::get(MPT->getPointeeType()));
2098 case Type::ConstantArray:
2099 case Type::IncompleteArray:
2100 case Type::VariableArray:
2101 return Cache::get(cast<ArrayType>(T)->getElementType());
2103 case Type::ExtVector:
2104 return Cache::get(cast<VectorType>(T)->getElementType());
2105 case Type::FunctionNoProto:
2106 return Cache::get(cast<FunctionType>(T)->getResultType());
2107 case Type::FunctionProto: {
2108 const FunctionProtoType *FPT = cast<FunctionProtoType>(T);
2109 CachedProperties result = Cache::get(FPT->getResultType());
2110 for (FunctionProtoType::arg_type_iterator ai = FPT->arg_type_begin(),
2111 ae = FPT->arg_type_end(); ai != ae; ++ai)
2112 result = merge(result, Cache::get(*ai));
2115 case Type::ObjCInterface: {
2116 NamedDecl::LinkageInfo LV =
2117 cast<ObjCInterfaceType>(T)->getDecl()->getLinkageAndVisibility();
2118 return CachedProperties(LV.linkage(), LV.visibility(), false);
2120 case Type::ObjCObject:
2121 return Cache::get(cast<ObjCObjectType>(T)->getBaseType());
2122 case Type::ObjCObjectPointer:
2123 return Cache::get(cast<ObjCObjectPointerType>(T)->getPointeeType());
2125 return Cache::get(cast<AtomicType>(T)->getValueType());
2128 llvm_unreachable("unhandled type class");
2130 // C++ [basic.link]p8:
2131 // Names not covered by these rules have no linkage.
2132 return CachedProperties(NoLinkage, DefaultVisibility, false);
2135 /// \brief Determine the linkage of this type.
2136 Linkage Type::getLinkage() const {
2137 Cache::ensure(this);
2138 return TypeBits.getLinkage();
2141 /// \brief Determine the linkage of this type.
2142 Visibility Type::getVisibility() const {
2143 Cache::ensure(this);
2144 return TypeBits.getVisibility();
2147 bool Type::hasUnnamedOrLocalType() const {
2148 Cache::ensure(this);
2149 return TypeBits.hasLocalOrUnnamedType();
2152 std::pair<Linkage,Visibility> Type::getLinkageAndVisibility() const {
2153 Cache::ensure(this);
2154 return std::make_pair(TypeBits.getLinkage(), TypeBits.getVisibility());
2157 void Type::ClearLinkageCache() {
2158 TypeBits.CacheValidAndVisibility = 0;
2159 if (QualType(this, 0) != CanonicalType)
2160 CanonicalType->TypeBits.CacheValidAndVisibility = 0;
2163 Qualifiers::ObjCLifetime Type::getObjCARCImplicitLifetime() const {
2164 if (isObjCARCImplicitlyUnretainedType())
2165 return Qualifiers::OCL_ExplicitNone;
2166 return Qualifiers::OCL_Strong;
2169 bool Type::isObjCARCImplicitlyUnretainedType() const {
2170 assert(isObjCLifetimeType() &&
2171 "cannot query implicit lifetime for non-inferrable type");
2173 const Type *canon = getCanonicalTypeInternal().getTypePtr();
2175 // Walk down to the base type. We don't care about qualifiers for this.
2176 while (const ArrayType *array = dyn_cast<ArrayType>(canon))
2177 canon = array->getElementType().getTypePtr();
2179 if (const ObjCObjectPointerType *opt
2180 = dyn_cast<ObjCObjectPointerType>(canon)) {
2181 // Class and Class<Protocol> don't require retension.
2182 if (opt->getObjectType()->isObjCClass())
2189 bool Type::isObjCNSObjectType() const {
2190 if (const TypedefType *typedefType = dyn_cast<TypedefType>(this))
2191 return typedefType->getDecl()->hasAttr<ObjCNSObjectAttr>();
2194 bool Type::isObjCRetainableType() const {
2195 return isObjCObjectPointerType() ||
2196 isBlockPointerType() ||
2197 isObjCNSObjectType();
2199 bool Type::isObjCIndirectLifetimeType() const {
2200 if (isObjCLifetimeType())
2202 if (const PointerType *OPT = getAs<PointerType>())
2203 return OPT->getPointeeType()->isObjCIndirectLifetimeType();
2204 if (const ReferenceType *Ref = getAs<ReferenceType>())
2205 return Ref->getPointeeType()->isObjCIndirectLifetimeType();
2206 if (const MemberPointerType *MemPtr = getAs<MemberPointerType>())
2207 return MemPtr->getPointeeType()->isObjCIndirectLifetimeType();
2211 /// Returns true if objects of this type have lifetime semantics under
2213 bool Type::isObjCLifetimeType() const {
2214 const Type *type = this;
2215 while (const ArrayType *array = type->getAsArrayTypeUnsafe())
2216 type = array->getElementType().getTypePtr();
2217 return type->isObjCRetainableType();
2220 /// \brief Determine whether the given type T is a "bridgable" Objective-C type,
2221 /// which is either an Objective-C object pointer type or an
2222 bool Type::isObjCARCBridgableType() const {
2223 return isObjCObjectPointerType() || isBlockPointerType();
2226 /// \brief Determine whether the given type T is a "bridgeable" C type.
2227 bool Type::isCARCBridgableType() const {
2228 const PointerType *Pointer = getAs<PointerType>();
2232 QualType Pointee = Pointer->getPointeeType();
2233 return Pointee->isVoidType() || Pointee->isRecordType();
2236 bool Type::hasSizedVLAType() const {
2237 if (!isVariablyModifiedType()) return false;
2239 if (const PointerType *ptr = getAs<PointerType>())
2240 return ptr->getPointeeType()->hasSizedVLAType();
2241 if (const ReferenceType *ref = getAs<ReferenceType>())
2242 return ref->getPointeeType()->hasSizedVLAType();
2243 if (const ArrayType *arr = getAsArrayTypeUnsafe()) {
2244 if (isa<VariableArrayType>(arr) &&
2245 cast<VariableArrayType>(arr)->getSizeExpr())
2248 return arr->getElementType()->hasSizedVLAType();
2254 QualType::DestructionKind QualType::isDestructedTypeImpl(QualType type) {
2255 switch (type.getObjCLifetime()) {
2256 case Qualifiers::OCL_None:
2257 case Qualifiers::OCL_ExplicitNone:
2258 case Qualifiers::OCL_Autoreleasing:
2261 case Qualifiers::OCL_Strong:
2262 return DK_objc_strong_lifetime;
2263 case Qualifiers::OCL_Weak:
2264 return DK_objc_weak_lifetime;
2267 /// Currently, the only destruction kind we recognize is C++ objects
2268 /// with non-trivial destructors.
2269 const CXXRecordDecl *record =
2270 type->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
2271 if (record && record->hasDefinition() && !record->hasTrivialDestructor())
2272 return DK_cxx_destructor;
2277 bool QualType::hasTrivialAssignment(ASTContext &Context, bool Copying) const {
2278 switch (getObjCLifetime()) {
2279 case Qualifiers::OCL_None:
2282 case Qualifiers::OCL_ExplicitNone:
2285 case Qualifiers::OCL_Autoreleasing:
2286 case Qualifiers::OCL_Strong:
2287 case Qualifiers::OCL_Weak:
2288 return !Context.getLangOptions().ObjCAutoRefCount;
2291 if (const CXXRecordDecl *Record
2292 = getTypePtr()->getBaseElementTypeUnsafe()->getAsCXXRecordDecl())
2293 return Copying ? Record->hasTrivialCopyAssignment() :
2294 Record->hasTrivialMoveAssignment();