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()));
42 bool QualType::isConstant(QualType T, ASTContext &Ctx) {
43 if (T.isConstQualified())
46 if (const ArrayType *AT = Ctx.getAsArrayType(T))
47 return AT->getElementType().isConstant(Ctx);
52 unsigned ConstantArrayType::getNumAddressingBits(ASTContext &Context,
54 const llvm::APInt &NumElements) {
55 llvm::APSInt SizeExtended(NumElements, true);
56 unsigned SizeTypeBits = Context.getTypeSize(Context.getSizeType());
57 SizeExtended = SizeExtended.extend(std::max(SizeTypeBits,
58 SizeExtended.getBitWidth()) * 2);
61 = Context.getTypeSizeInChars(ElementType).getQuantity();
62 llvm::APSInt TotalSize(llvm::APInt(SizeExtended.getBitWidth(), ElementSize));
63 TotalSize *= SizeExtended;
65 return TotalSize.getActiveBits();
68 unsigned ConstantArrayType::getMaxSizeBits(ASTContext &Context) {
69 unsigned Bits = Context.getTypeSize(Context.getSizeType());
71 // GCC appears to only allow 63 bits worth of address space when compiling
72 // for 64-bit, so we do the same.
79 DependentSizedArrayType::DependentSizedArrayType(const ASTContext &Context,
80 QualType et, QualType can,
81 Expr *e, ArraySizeModifier sm,
84 : ArrayType(DependentSizedArray, et, can, sm, tq,
85 (et->containsUnexpandedParameterPack() ||
86 (e && e->containsUnexpandedParameterPack()))),
87 Context(Context), SizeExpr((Stmt*) e), Brackets(brackets)
91 void DependentSizedArrayType::Profile(llvm::FoldingSetNodeID &ID,
92 const ASTContext &Context,
94 ArraySizeModifier SizeMod,
97 ID.AddPointer(ET.getAsOpaquePtr());
98 ID.AddInteger(SizeMod);
99 ID.AddInteger(TypeQuals);
100 E->Profile(ID, Context, true);
103 DependentSizedExtVectorType::DependentSizedExtVectorType(const
105 QualType ElementType,
109 : Type(DependentSizedExtVector, can, /*Dependent=*/true,
110 ElementType->isVariablyModifiedType(),
111 (ElementType->containsUnexpandedParameterPack() ||
112 (SizeExpr && SizeExpr->containsUnexpandedParameterPack()))),
113 Context(Context), SizeExpr(SizeExpr), ElementType(ElementType),
119 DependentSizedExtVectorType::Profile(llvm::FoldingSetNodeID &ID,
120 const ASTContext &Context,
121 QualType ElementType, Expr *SizeExpr) {
122 ID.AddPointer(ElementType.getAsOpaquePtr());
123 SizeExpr->Profile(ID, Context, true);
126 VectorType::VectorType(QualType vecType, unsigned nElements, QualType canonType,
128 : Type(Vector, canonType, vecType->isDependentType(),
129 vecType->isVariablyModifiedType(),
130 vecType->containsUnexpandedParameterPack()),
133 VectorTypeBits.VecKind = vecKind;
134 VectorTypeBits.NumElements = nElements;
137 VectorType::VectorType(TypeClass tc, QualType vecType, unsigned nElements,
138 QualType canonType, VectorKind vecKind)
139 : Type(tc, canonType, vecType->isDependentType(),
140 vecType->isVariablyModifiedType(),
141 vecType->containsUnexpandedParameterPack()),
144 VectorTypeBits.VecKind = vecKind;
145 VectorTypeBits.NumElements = nElements;
148 /// getArrayElementTypeNoTypeQual - If this is an array type, return the
149 /// element type of the array, potentially with type qualifiers missing.
150 /// This method should never be used when type qualifiers are meaningful.
151 const Type *Type::getArrayElementTypeNoTypeQual() const {
152 // If this is directly an array type, return it.
153 if (const ArrayType *ATy = dyn_cast<ArrayType>(this))
154 return ATy->getElementType().getTypePtr();
156 // If the canonical form of this type isn't the right kind, reject it.
157 if (!isa<ArrayType>(CanonicalType))
160 // If this is a typedef for an array type, strip the typedef off without
161 // losing all typedef information.
162 return cast<ArrayType>(getUnqualifiedDesugaredType())
163 ->getElementType().getTypePtr();
166 /// getDesugaredType - Return the specified type with any "sugar" removed from
167 /// the type. This takes off typedefs, typeof's etc. If the outer level of
168 /// the type is already concrete, it returns it unmodified. This is similar
169 /// to getting the canonical type, but it doesn't remove *all* typedefs. For
170 /// example, it returns "T*" as "T*", (not as "int*"), because the pointer is
172 QualType QualType::getDesugaredType(QualType T, const ASTContext &Context) {
173 SplitQualType split = getSplitDesugaredType(T);
174 return Context.getQualifiedType(split.first, split.second);
177 SplitQualType QualType::getSplitDesugaredType(QualType T) {
178 QualifierCollector Qs;
182 const Type *CurTy = Qs.strip(Cur);
183 switch (CurTy->getTypeClass()) {
184 #define ABSTRACT_TYPE(Class, Parent)
185 #define TYPE(Class, Parent) \
186 case Type::Class: { \
187 const Class##Type *Ty = cast<Class##Type>(CurTy); \
188 if (!Ty->isSugared()) \
189 return SplitQualType(Ty, Qs); \
190 Cur = Ty->desugar(); \
193 #include "clang/AST/TypeNodes.def"
198 SplitQualType QualType::getSplitUnqualifiedTypeImpl(QualType type) {
199 SplitQualType split = type.split();
201 // All the qualifiers we've seen so far.
202 Qualifiers quals = split.second;
204 // The last type node we saw with any nodes inside it.
205 const Type *lastTypeWithQuals = split.first;
210 // Do a single-step desugar, aborting the loop if the type isn't
212 switch (split.first->getTypeClass()) {
213 #define ABSTRACT_TYPE(Class, Parent)
214 #define TYPE(Class, Parent) \
215 case Type::Class: { \
216 const Class##Type *ty = cast<Class##Type>(split.first); \
217 if (!ty->isSugared()) goto done; \
218 next = ty->desugar(); \
221 #include "clang/AST/TypeNodes.def"
224 // Otherwise, split the underlying type. If that yields qualifiers,
225 // update the information.
226 split = next.split();
227 if (!split.second.empty()) {
228 lastTypeWithQuals = split.first;
229 quals.addConsistentQualifiers(split.second);
234 return SplitQualType(lastTypeWithQuals, quals);
237 QualType QualType::IgnoreParens(QualType T) {
238 // FIXME: this seems inherently un-qualifiers-safe.
239 while (const ParenType *PT = T->getAs<ParenType>())
240 T = PT->getInnerType();
244 /// getUnqualifiedDesugaredType - Pull any qualifiers and syntactic
245 /// sugar off the given type. This should produce an object of the
246 /// same dynamic type as the canonical type.
247 const Type *Type::getUnqualifiedDesugaredType() const {
248 const Type *Cur = this;
251 switch (Cur->getTypeClass()) {
252 #define ABSTRACT_TYPE(Class, Parent)
253 #define TYPE(Class, Parent) \
255 const Class##Type *Ty = cast<Class##Type>(Cur); \
256 if (!Ty->isSugared()) return Cur; \
257 Cur = Ty->desugar().getTypePtr(); \
260 #include "clang/AST/TypeNodes.def"
265 /// isVoidType - Helper method to determine if this is the 'void' type.
266 bool Type::isVoidType() const {
267 if (const BuiltinType *BT = dyn_cast<BuiltinType>(CanonicalType))
268 return BT->getKind() == BuiltinType::Void;
272 bool Type::isDerivedType() const {
273 switch (CanonicalType->getTypeClass()) {
277 case IncompleteArray:
279 case FunctionNoProto:
280 case LValueReference:
281 case RValueReference:
289 bool Type::isClassType() const {
290 if (const RecordType *RT = getAs<RecordType>())
291 return RT->getDecl()->isClass();
294 bool Type::isStructureType() const {
295 if (const RecordType *RT = getAs<RecordType>())
296 return RT->getDecl()->isStruct();
299 bool Type::isStructureOrClassType() const {
300 if (const RecordType *RT = getAs<RecordType>())
301 return RT->getDecl()->isStruct() || RT->getDecl()->isClass();
304 bool Type::isVoidPointerType() const {
305 if (const PointerType *PT = getAs<PointerType>())
306 return PT->getPointeeType()->isVoidType();
310 bool Type::isUnionType() const {
311 if (const RecordType *RT = getAs<RecordType>())
312 return RT->getDecl()->isUnion();
316 bool Type::isComplexType() const {
317 if (const ComplexType *CT = dyn_cast<ComplexType>(CanonicalType))
318 return CT->getElementType()->isFloatingType();
322 bool Type::isComplexIntegerType() const {
323 // Check for GCC complex integer extension.
324 return getAsComplexIntegerType();
327 const ComplexType *Type::getAsComplexIntegerType() const {
328 if (const ComplexType *Complex = getAs<ComplexType>())
329 if (Complex->getElementType()->isIntegerType())
334 QualType Type::getPointeeType() const {
335 if (const PointerType *PT = getAs<PointerType>())
336 return PT->getPointeeType();
337 if (const ObjCObjectPointerType *OPT = getAs<ObjCObjectPointerType>())
338 return OPT->getPointeeType();
339 if (const BlockPointerType *BPT = getAs<BlockPointerType>())
340 return BPT->getPointeeType();
341 if (const ReferenceType *RT = getAs<ReferenceType>())
342 return RT->getPointeeType();
346 const RecordType *Type::getAsStructureType() const {
347 // If this is directly a structure type, return it.
348 if (const RecordType *RT = dyn_cast<RecordType>(this)) {
349 if (RT->getDecl()->isStruct())
353 // If the canonical form of this type isn't the right kind, reject it.
354 if (const RecordType *RT = dyn_cast<RecordType>(CanonicalType)) {
355 if (!RT->getDecl()->isStruct())
358 // If this is a typedef for a structure type, strip the typedef off without
359 // losing all typedef information.
360 return cast<RecordType>(getUnqualifiedDesugaredType());
365 const RecordType *Type::getAsUnionType() const {
366 // If this is directly a union type, return it.
367 if (const RecordType *RT = dyn_cast<RecordType>(this)) {
368 if (RT->getDecl()->isUnion())
372 // If the canonical form of this type isn't the right kind, reject it.
373 if (const RecordType *RT = dyn_cast<RecordType>(CanonicalType)) {
374 if (!RT->getDecl()->isUnion())
377 // If this is a typedef for a union type, strip the typedef off without
378 // losing all typedef information.
379 return cast<RecordType>(getUnqualifiedDesugaredType());
385 ObjCObjectType::ObjCObjectType(QualType Canonical, QualType Base,
386 ObjCProtocolDecl * const *Protocols,
387 unsigned NumProtocols)
388 : Type(ObjCObject, Canonical, false, false, false),
391 ObjCObjectTypeBits.NumProtocols = NumProtocols;
392 assert(getNumProtocols() == NumProtocols &&
393 "bitfield overflow in protocol count");
395 memcpy(getProtocolStorage(), Protocols,
396 NumProtocols * sizeof(ObjCProtocolDecl*));
399 const ObjCObjectType *Type::getAsObjCQualifiedInterfaceType() const {
400 // There is no sugar for ObjCObjectType's, just return the canonical
401 // type pointer if it is the right class. There is no typedef information to
402 // return and these cannot be Address-space qualified.
403 if (const ObjCObjectType *T = getAs<ObjCObjectType>())
404 if (T->getNumProtocols() && T->getInterface())
409 bool Type::isObjCQualifiedInterfaceType() const {
410 return getAsObjCQualifiedInterfaceType() != 0;
413 const ObjCObjectPointerType *Type::getAsObjCQualifiedIdType() const {
414 // There is no sugar for ObjCQualifiedIdType's, just return the canonical
415 // type pointer if it is the right class.
416 if (const ObjCObjectPointerType *OPT = getAs<ObjCObjectPointerType>()) {
417 if (OPT->isObjCQualifiedIdType())
423 const ObjCObjectPointerType *Type::getAsObjCQualifiedClassType() const {
424 // There is no sugar for ObjCQualifiedClassType's, just return the canonical
425 // type pointer if it is the right class.
426 if (const ObjCObjectPointerType *OPT = getAs<ObjCObjectPointerType>()) {
427 if (OPT->isObjCQualifiedClassType())
433 const ObjCObjectPointerType *Type::getAsObjCInterfacePointerType() const {
434 if (const ObjCObjectPointerType *OPT = getAs<ObjCObjectPointerType>()) {
435 if (OPT->getInterfaceType())
441 const CXXRecordDecl *Type::getCXXRecordDeclForPointerType() const {
442 if (const PointerType *PT = getAs<PointerType>())
443 if (const RecordType *RT = PT->getPointeeType()->getAs<RecordType>())
444 return dyn_cast<CXXRecordDecl>(RT->getDecl());
448 CXXRecordDecl *Type::getAsCXXRecordDecl() const {
449 if (const RecordType *RT = getAs<RecordType>())
450 return dyn_cast<CXXRecordDecl>(RT->getDecl());
451 else if (const InjectedClassNameType *Injected
452 = getAs<InjectedClassNameType>())
453 return Injected->getDecl();
459 class GetContainedAutoVisitor :
460 public TypeVisitor<GetContainedAutoVisitor, AutoType*> {
462 using TypeVisitor<GetContainedAutoVisitor, AutoType*>::Visit;
463 AutoType *Visit(QualType T) {
466 return Visit(T.getTypePtr());
469 // The 'auto' type itself.
470 AutoType *VisitAutoType(const AutoType *AT) {
471 return const_cast<AutoType*>(AT);
474 // Only these types can contain the desired 'auto' type.
475 AutoType *VisitPointerType(const PointerType *T) {
476 return Visit(T->getPointeeType());
478 AutoType *VisitBlockPointerType(const BlockPointerType *T) {
479 return Visit(T->getPointeeType());
481 AutoType *VisitReferenceType(const ReferenceType *T) {
482 return Visit(T->getPointeeTypeAsWritten());
484 AutoType *VisitMemberPointerType(const MemberPointerType *T) {
485 return Visit(T->getPointeeType());
487 AutoType *VisitArrayType(const ArrayType *T) {
488 return Visit(T->getElementType());
490 AutoType *VisitDependentSizedExtVectorType(
491 const DependentSizedExtVectorType *T) {
492 return Visit(T->getElementType());
494 AutoType *VisitVectorType(const VectorType *T) {
495 return Visit(T->getElementType());
497 AutoType *VisitFunctionType(const FunctionType *T) {
498 return Visit(T->getResultType());
500 AutoType *VisitParenType(const ParenType *T) {
501 return Visit(T->getInnerType());
503 AutoType *VisitAttributedType(const AttributedType *T) {
504 return Visit(T->getModifiedType());
509 AutoType *Type::getContainedAutoType() const {
510 return GetContainedAutoVisitor().Visit(this);
513 bool Type::isIntegerType() const {
514 if (const BuiltinType *BT = dyn_cast<BuiltinType>(CanonicalType))
515 return BT->getKind() >= BuiltinType::Bool &&
516 BT->getKind() <= BuiltinType::Int128;
517 if (const EnumType *ET = dyn_cast<EnumType>(CanonicalType))
518 // Incomplete enum types are not treated as integer types.
519 // FIXME: In C++, enum types are never integer types.
520 return ET->getDecl()->isComplete();
524 bool Type::hasIntegerRepresentation() const {
525 if (const VectorType *VT = dyn_cast<VectorType>(CanonicalType))
526 return VT->getElementType()->isIntegerType();
528 return isIntegerType();
531 /// \brief Determine whether this type is an integral type.
533 /// This routine determines whether the given type is an integral type per
534 /// C++ [basic.fundamental]p7. Although the C standard does not define the
535 /// term "integral type", it has a similar term "integer type", and in C++
536 /// the two terms are equivalent. However, C's "integer type" includes
537 /// enumeration types, while C++'s "integer type" does not. The \c ASTContext
538 /// parameter is used to determine whether we should be following the C or
539 /// C++ rules when determining whether this type is an integral/integer type.
541 /// For cases where C permits "an integer type" and C++ permits "an integral
542 /// type", use this routine.
544 /// For cases where C permits "an integer type" and C++ permits "an integral
545 /// or enumeration type", use \c isIntegralOrEnumerationType() instead.
547 /// \param Ctx The context in which this type occurs.
549 /// \returns true if the type is considered an integral type, false otherwise.
550 bool Type::isIntegralType(ASTContext &Ctx) const {
551 if (const BuiltinType *BT = dyn_cast<BuiltinType>(CanonicalType))
552 return BT->getKind() >= BuiltinType::Bool &&
553 BT->getKind() <= BuiltinType::Int128;
555 if (!Ctx.getLangOptions().CPlusPlus)
556 if (const EnumType *ET = dyn_cast<EnumType>(CanonicalType))
557 return ET->getDecl()->isComplete(); // Complete enum types are integral in C.
562 bool Type::isIntegralOrEnumerationType() const {
563 if (const BuiltinType *BT = dyn_cast<BuiltinType>(CanonicalType))
564 return BT->getKind() >= BuiltinType::Bool &&
565 BT->getKind() <= BuiltinType::Int128;
567 // Check for a complete enum type; incomplete enum types are not properly an
568 // enumeration type in the sense required here.
569 if (const EnumType *ET = dyn_cast<EnumType>(CanonicalType))
570 return ET->getDecl()->isComplete();
575 bool Type::isIntegralOrUnscopedEnumerationType() const {
576 if (const BuiltinType *BT = dyn_cast<BuiltinType>(CanonicalType))
577 return BT->getKind() >= BuiltinType::Bool &&
578 BT->getKind() <= BuiltinType::Int128;
580 // Check for a complete enum type; incomplete enum types are not properly an
581 // enumeration type in the sense required here.
582 // C++0x: However, if the underlying type of the enum is fixed, it is
583 // considered complete.
584 if (const EnumType *ET = dyn_cast<EnumType>(CanonicalType))
585 return ET->getDecl()->isComplete() && !ET->getDecl()->isScoped();
591 bool Type::isBooleanType() const {
592 if (const BuiltinType *BT = dyn_cast<BuiltinType>(CanonicalType))
593 return BT->getKind() == BuiltinType::Bool;
597 bool Type::isCharType() const {
598 if (const BuiltinType *BT = dyn_cast<BuiltinType>(CanonicalType))
599 return BT->getKind() == BuiltinType::Char_U ||
600 BT->getKind() == BuiltinType::UChar ||
601 BT->getKind() == BuiltinType::Char_S ||
602 BT->getKind() == BuiltinType::SChar;
606 bool Type::isWideCharType() const {
607 if (const BuiltinType *BT = dyn_cast<BuiltinType>(CanonicalType))
608 return BT->getKind() == BuiltinType::WChar_S ||
609 BT->getKind() == BuiltinType::WChar_U;
613 /// \brief Determine whether this type is any of the built-in character
615 bool Type::isAnyCharacterType() const {
616 const BuiltinType *BT = dyn_cast<BuiltinType>(CanonicalType);
617 if (BT == 0) return false;
618 switch (BT->getKind()) {
619 default: return false;
620 case BuiltinType::Char_U:
621 case BuiltinType::UChar:
622 case BuiltinType::WChar_U:
623 case BuiltinType::Char16:
624 case BuiltinType::Char32:
625 case BuiltinType::Char_S:
626 case BuiltinType::SChar:
627 case BuiltinType::WChar_S:
632 /// isSignedIntegerType - Return true if this is an integer type that is
633 /// signed, according to C99 6.2.5p4 [char, signed char, short, int, long..],
634 /// an enum decl which has a signed representation
635 bool Type::isSignedIntegerType() const {
636 if (const BuiltinType *BT = dyn_cast<BuiltinType>(CanonicalType)) {
637 return BT->getKind() >= BuiltinType::Char_S &&
638 BT->getKind() <= BuiltinType::Int128;
641 if (const EnumType *ET = dyn_cast<EnumType>(CanonicalType)) {
642 // Incomplete enum types are not treated as integer types.
643 // FIXME: In C++, enum types are never integer types.
644 if (ET->getDecl()->isComplete())
645 return ET->getDecl()->getIntegerType()->isSignedIntegerType();
651 bool Type::hasSignedIntegerRepresentation() const {
652 if (const VectorType *VT = dyn_cast<VectorType>(CanonicalType))
653 return VT->getElementType()->isSignedIntegerType();
655 return isSignedIntegerType();
658 /// isUnsignedIntegerType - Return true if this is an integer type that is
659 /// unsigned, according to C99 6.2.5p6 [which returns true for _Bool], an enum
660 /// decl which has an unsigned representation
661 bool Type::isUnsignedIntegerType() const {
662 if (const BuiltinType *BT = dyn_cast<BuiltinType>(CanonicalType)) {
663 return BT->getKind() >= BuiltinType::Bool &&
664 BT->getKind() <= BuiltinType::UInt128;
667 if (const EnumType *ET = dyn_cast<EnumType>(CanonicalType)) {
668 // Incomplete enum types are not treated as integer types.
669 // FIXME: In C++, enum types are never integer types.
670 if (ET->getDecl()->isComplete())
671 return ET->getDecl()->getIntegerType()->isUnsignedIntegerType();
677 bool Type::hasUnsignedIntegerRepresentation() const {
678 if (const VectorType *VT = dyn_cast<VectorType>(CanonicalType))
679 return VT->getElementType()->isUnsignedIntegerType();
681 return isUnsignedIntegerType();
684 bool Type::isFloatingType() const {
685 if (const BuiltinType *BT = dyn_cast<BuiltinType>(CanonicalType))
686 return BT->getKind() >= BuiltinType::Float &&
687 BT->getKind() <= BuiltinType::LongDouble;
688 if (const ComplexType *CT = dyn_cast<ComplexType>(CanonicalType))
689 return CT->getElementType()->isFloatingType();
693 bool Type::hasFloatingRepresentation() const {
694 if (const VectorType *VT = dyn_cast<VectorType>(CanonicalType))
695 return VT->getElementType()->isFloatingType();
697 return isFloatingType();
700 bool Type::isRealFloatingType() const {
701 if (const BuiltinType *BT = dyn_cast<BuiltinType>(CanonicalType))
702 return BT->isFloatingPoint();
706 bool Type::isRealType() const {
707 if (const BuiltinType *BT = dyn_cast<BuiltinType>(CanonicalType))
708 return BT->getKind() >= BuiltinType::Bool &&
709 BT->getKind() <= BuiltinType::LongDouble;
710 if (const EnumType *ET = dyn_cast<EnumType>(CanonicalType))
711 return ET->getDecl()->isComplete() && !ET->getDecl()->isScoped();
715 bool Type::isArithmeticType() const {
716 if (const BuiltinType *BT = dyn_cast<BuiltinType>(CanonicalType))
717 return BT->getKind() >= BuiltinType::Bool &&
718 BT->getKind() <= BuiltinType::LongDouble;
719 if (const EnumType *ET = dyn_cast<EnumType>(CanonicalType))
720 // GCC allows forward declaration of enum types (forbid by C99 6.7.2.3p2).
721 // If a body isn't seen by the time we get here, return false.
723 // C++0x: Enumerations are not arithmetic types. For now, just return
724 // false for scoped enumerations since that will disable any
725 // unwanted implicit conversions.
726 return !ET->getDecl()->isScoped() && ET->getDecl()->isComplete();
727 return isa<ComplexType>(CanonicalType);
730 bool Type::isScalarType() const {
731 if (const BuiltinType *BT = dyn_cast<BuiltinType>(CanonicalType))
732 return BT->getKind() > BuiltinType::Void &&
733 BT->getKind() <= BuiltinType::NullPtr;
734 if (const EnumType *ET = dyn_cast<EnumType>(CanonicalType))
735 // Enums are scalar types, but only if they are defined. Incomplete enums
736 // are not treated as scalar types.
737 return ET->getDecl()->isComplete();
738 return isa<PointerType>(CanonicalType) ||
739 isa<BlockPointerType>(CanonicalType) ||
740 isa<MemberPointerType>(CanonicalType) ||
741 isa<ComplexType>(CanonicalType) ||
742 isa<ObjCObjectPointerType>(CanonicalType);
745 Type::ScalarTypeKind Type::getScalarTypeKind() const {
746 assert(isScalarType());
748 const Type *T = CanonicalType.getTypePtr();
749 if (const BuiltinType *BT = dyn_cast<BuiltinType>(T)) {
750 if (BT->getKind() == BuiltinType::Bool) return STK_Bool;
751 if (BT->getKind() == BuiltinType::NullPtr) return STK_Pointer;
752 if (BT->isInteger()) return STK_Integral;
753 if (BT->isFloatingPoint()) return STK_Floating;
754 llvm_unreachable("unknown scalar builtin type");
755 } else if (isa<PointerType>(T) ||
756 isa<BlockPointerType>(T) ||
757 isa<ObjCObjectPointerType>(T)) {
759 } else if (isa<MemberPointerType>(T)) {
760 return STK_MemberPointer;
761 } else if (isa<EnumType>(T)) {
762 assert(cast<EnumType>(T)->getDecl()->isComplete());
764 } else if (const ComplexType *CT = dyn_cast<ComplexType>(T)) {
765 if (CT->getElementType()->isRealFloatingType())
766 return STK_FloatingComplex;
767 return STK_IntegralComplex;
770 llvm_unreachable("unknown scalar type");
774 /// \brief Determines whether the type is a C++ aggregate type or C
775 /// aggregate or union type.
777 /// An aggregate type is an array or a class type (struct, union, or
778 /// class) that has no user-declared constructors, no private or
779 /// protected non-static data members, no base classes, and no virtual
780 /// functions (C++ [dcl.init.aggr]p1). The notion of an aggregate type
781 /// subsumes the notion of C aggregates (C99 6.2.5p21) because it also
782 /// includes union types.
783 bool Type::isAggregateType() const {
784 if (const RecordType *Record = dyn_cast<RecordType>(CanonicalType)) {
785 if (CXXRecordDecl *ClassDecl = dyn_cast<CXXRecordDecl>(Record->getDecl()))
786 return ClassDecl->isAggregate();
791 return isa<ArrayType>(CanonicalType);
794 /// isConstantSizeType - Return true if this is not a variable sized type,
795 /// according to the rules of C99 6.7.5p3. It is not legal to call this on
796 /// incomplete types or dependent types.
797 bool Type::isConstantSizeType() const {
798 assert(!isIncompleteType() && "This doesn't make sense for incomplete types");
799 assert(!isDependentType() && "This doesn't make sense for dependent types");
800 // The VAT must have a size, as it is known to be complete.
801 return !isa<VariableArrayType>(CanonicalType);
804 /// isIncompleteType - Return true if this is an incomplete type (C99 6.2.5p1)
805 /// - a type that can describe objects, but which lacks information needed to
806 /// determine its size.
807 bool Type::isIncompleteType() const {
808 switch (CanonicalType->getTypeClass()) {
809 default: return false;
811 // Void is the only incomplete builtin type. Per C99 6.2.5p19, it can never
815 // An enumeration with fixed underlying type is complete (C++0x 7.2p3).
816 if (cast<EnumType>(CanonicalType)->getDecl()->isFixed())
820 // A tagged type (struct/union/enum/class) is incomplete if the decl is a
821 // forward declaration, but not a full definition (C99 6.2.5p22).
822 return !cast<TagType>(CanonicalType)->getDecl()->isDefinition();
824 // An array is incomplete if its element type is incomplete
825 // (C++ [dcl.array]p1).
826 // We don't handle variable arrays (they're not allowed in C++) or
827 // dependent-sized arrays (dependent types are never treated as incomplete).
828 return cast<ArrayType>(CanonicalType)->getElementType()->isIncompleteType();
829 case IncompleteArray:
830 // An array of unknown size is an incomplete type (C99 6.2.5p22).
833 return cast<ObjCObjectType>(CanonicalType)->getBaseType()
834 ->isIncompleteType();
836 // ObjC interfaces are incomplete if they are @class, not @interface.
837 return cast<ObjCInterfaceType>(CanonicalType)->getDecl()->isForwardDecl();
841 /// isPODType - Return true if this is a plain-old-data type (C++ 3.9p10)
842 bool Type::isPODType() const {
843 // The compiler shouldn't query this for incomplete types, but the user might.
844 // We return false for that case. Except for incomplete arrays of PODs, which
845 // are PODs according to the standard.
846 if (isIncompleteArrayType() &&
847 cast<ArrayType>(CanonicalType)->getElementType()->isPODType())
849 if (isIncompleteType())
852 switch (CanonicalType->getTypeClass()) {
853 // Everything not explicitly mentioned is not POD.
854 default: return false;
857 // IncompleteArray is handled above.
858 return cast<ArrayType>(CanonicalType)->getElementType()->isPODType();
866 case ObjCObjectPointer:
874 if (CXXRecordDecl *ClassDecl
875 = dyn_cast<CXXRecordDecl>(cast<RecordType>(CanonicalType)->getDecl()))
876 return ClassDecl->isPOD();
878 // C struct/union is POD.
883 bool Type::isLiteralType() const {
884 if (isDependentType())
887 // C++0x [basic.types]p10:
888 // A type is a literal type if it is:
890 // -- an array of literal type
891 // Extension: variable arrays cannot be literal types, since they're
893 if (isVariableArrayType())
895 const Type *BaseTy = getBaseElementTypeUnsafe();
896 assert(BaseTy && "NULL element type");
898 // Return false for incomplete types after skipping any incomplete array
899 // types; those are expressly allowed by the standard and thus our API.
900 if (BaseTy->isIncompleteType())
903 // C++0x [basic.types]p10:
904 // A type is a literal type if it is:
905 // -- a scalar type; or
906 // As an extension, Clang treats vector types as Scalar types.
907 if (BaseTy->isScalarType() || BaseTy->isVectorType()) return true;
908 // -- a reference type; or
909 if (BaseTy->isReferenceType()) return true;
910 // -- a class type that has all of the following properties:
911 if (const RecordType *RT = BaseTy->getAs<RecordType>()) {
912 if (const CXXRecordDecl *ClassDecl =
913 dyn_cast<CXXRecordDecl>(RT->getDecl())) {
914 // -- a trivial destructor,
915 if (!ClassDecl->hasTrivialDestructor()) return false;
916 // -- every constructor call and full-expression in the
917 // brace-or-equal-initializers for non-static data members (if any)
918 // is a constant expression,
919 // FIXME: C++0x: Clang doesn't yet support non-static data member
920 // declarations with initializers, or constexprs.
921 // -- it is an aggregate type or has at least one constexpr
922 // constructor or constructor template that is not a copy or move
924 if (!ClassDecl->isAggregate() &&
925 !ClassDecl->hasConstExprNonCopyMoveConstructor())
927 // -- all non-static data members and base classes of literal types
928 if (ClassDecl->hasNonLiteralTypeFieldsOrBases()) return false;
936 bool Type::isTrivialType() const {
937 if (isDependentType())
940 // C++0x [basic.types]p9:
941 // Scalar types, trivial class types, arrays of such types, and
942 // cv-qualified versions of these types are collectively called trivial
944 const Type *BaseTy = getBaseElementTypeUnsafe();
945 assert(BaseTy && "NULL element type");
947 // Return false for incomplete types after skipping any incomplete array
948 // types which are expressly allowed by the standard and thus our API.
949 if (BaseTy->isIncompleteType())
952 // As an extension, Clang treats vector types as Scalar types.
953 if (BaseTy->isScalarType() || BaseTy->isVectorType()) return true;
954 if (const RecordType *RT = BaseTy->getAs<RecordType>()) {
955 if (const CXXRecordDecl *ClassDecl =
956 dyn_cast<CXXRecordDecl>(RT->getDecl())) {
958 // A trivial class is a class that has a trivial default constructor
959 if (!ClassDecl->hasTrivialConstructor()) return false;
960 // and is trivially copyable.
961 if (!ClassDecl->isTriviallyCopyable()) return false;
967 // No other types can match.
971 bool Type::isStandardLayoutType() const {
972 if (isDependentType())
975 // C++0x [basic.types]p9:
976 // Scalar types, standard-layout class types, arrays of such types, and
977 // cv-qualified versions of these types are collectively called
978 // standard-layout types.
979 const Type *BaseTy = getBaseElementTypeUnsafe();
980 assert(BaseTy && "NULL element type");
982 // Return false for incomplete types after skipping any incomplete array
983 // types which are expressly allowed by the standard and thus our API.
984 if (BaseTy->isIncompleteType())
987 // As an extension, Clang treats vector types as Scalar types.
988 if (BaseTy->isScalarType() || BaseTy->isVectorType()) return true;
989 if (const RecordType *RT = BaseTy->getAs<RecordType>()) {
990 if (const CXXRecordDecl *ClassDecl =
991 dyn_cast<CXXRecordDecl>(RT->getDecl()))
992 if (!ClassDecl->isStandardLayout())
995 // Default to 'true' for non-C++ class types.
996 // FIXME: This is a bit dubious, but plain C structs should trivially meet
997 // all the requirements of standard layout classes.
1001 // No other types can match.
1005 // This is effectively the intersection of isTrivialType and
1006 // isStandardLayoutType. We implement it dircetly to avoid redundant
1007 // conversions from a type to a CXXRecordDecl.
1008 bool Type::isCXX11PODType() const {
1009 if (isDependentType())
1012 // C++11 [basic.types]p9:
1013 // Scalar types, POD classes, arrays of such types, and cv-qualified
1014 // versions of these types are collectively called trivial types.
1015 const Type *BaseTy = getBaseElementTypeUnsafe();
1016 assert(BaseTy && "NULL element type");
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 (BaseTy->isIncompleteType())
1023 // As an extension, Clang treats vector types as Scalar types.
1024 if (BaseTy->isScalarType() || BaseTy->isVectorType()) return true;
1025 if (const RecordType *RT = BaseTy->getAs<RecordType>()) {
1026 if (const CXXRecordDecl *ClassDecl =
1027 dyn_cast<CXXRecordDecl>(RT->getDecl())) {
1028 // C++11 [class]p10:
1029 // A POD struct is a non-union class that is both a trivial class [...]
1031 // A trivial class is a class that has a trivial default constructor
1032 if (!ClassDecl->hasTrivialConstructor()) return false;
1033 // and is trivially copyable.
1034 if (!ClassDecl->isTriviallyCopyable()) return false;
1036 // C++11 [class]p10:
1037 // A POD struct is a non-union class that is both a trivial class and
1038 // a standard-layout class [...]
1039 if (!ClassDecl->isStandardLayout()) return false;
1041 // C++11 [class]p10:
1042 // A POD struct is a non-union class that is both a trivial class and
1043 // a standard-layout class, and has no non-static data members of type
1044 // non-POD struct, non-POD union (or array of such types). [...]
1046 // We don't directly query the recursive aspect as the requiremets for
1047 // both standard-layout classes and trivial classes apply recursively
1054 // No other types can match.
1058 bool Type::isPromotableIntegerType() const {
1059 if (const BuiltinType *BT = getAs<BuiltinType>())
1060 switch (BT->getKind()) {
1061 case BuiltinType::Bool:
1062 case BuiltinType::Char_S:
1063 case BuiltinType::Char_U:
1064 case BuiltinType::SChar:
1065 case BuiltinType::UChar:
1066 case BuiltinType::Short:
1067 case BuiltinType::UShort:
1073 // Enumerated types are promotable to their compatible integer types
1074 // (C99 6.3.1.1) a.k.a. its underlying type (C++ [conv.prom]p2).
1075 if (const EnumType *ET = getAs<EnumType>()){
1076 if (this->isDependentType() || ET->getDecl()->getPromotionType().isNull()
1077 || ET->getDecl()->isScoped())
1080 const BuiltinType *BT
1081 = ET->getDecl()->getPromotionType()->getAs<BuiltinType>();
1082 return BT->getKind() == BuiltinType::Int
1083 || BT->getKind() == BuiltinType::UInt;
1089 bool Type::isNullPtrType() const {
1090 if (const BuiltinType *BT = getAs<BuiltinType>())
1091 return BT->getKind() == BuiltinType::NullPtr;
1095 bool Type::isSpecifierType() const {
1096 // Note that this intentionally does not use the canonical type.
1097 switch (getTypeClass()) {
1105 case TemplateTypeParm:
1106 case SubstTemplateTypeParm:
1107 case TemplateSpecialization:
1110 case DependentTemplateSpecialization:
1113 case ObjCObjectPointer: // FIXME: object pointers aren't really specifiers
1120 ElaboratedTypeKeyword
1121 TypeWithKeyword::getKeywordForTypeSpec(unsigned TypeSpec) {
1123 default: return ETK_None;
1124 case TST_typename: return ETK_Typename;
1125 case TST_class: return ETK_Class;
1126 case TST_struct: return ETK_Struct;
1127 case TST_union: return ETK_Union;
1128 case TST_enum: return ETK_Enum;
1133 TypeWithKeyword::getTagTypeKindForTypeSpec(unsigned TypeSpec) {
1135 case TST_class: return TTK_Class;
1136 case TST_struct: return TTK_Struct;
1137 case TST_union: return TTK_Union;
1138 case TST_enum: return TTK_Enum;
1141 llvm_unreachable("Type specifier is not a tag type kind.");
1145 ElaboratedTypeKeyword
1146 TypeWithKeyword::getKeywordForTagTypeKind(TagTypeKind Kind) {
1148 case TTK_Class: return ETK_Class;
1149 case TTK_Struct: return ETK_Struct;
1150 case TTK_Union: return ETK_Union;
1151 case TTK_Enum: return ETK_Enum;
1153 llvm_unreachable("Unknown tag type kind.");
1157 TypeWithKeyword::getTagTypeKindForKeyword(ElaboratedTypeKeyword Keyword) {
1159 case ETK_Class: return TTK_Class;
1160 case ETK_Struct: return TTK_Struct;
1161 case ETK_Union: return TTK_Union;
1162 case ETK_Enum: return TTK_Enum;
1163 case ETK_None: // Fall through.
1165 llvm_unreachable("Elaborated type keyword is not a tag type kind.");
1167 llvm_unreachable("Unknown elaborated type keyword.");
1171 TypeWithKeyword::KeywordIsTagTypeKind(ElaboratedTypeKeyword Keyword) {
1182 llvm_unreachable("Unknown elaborated type keyword.");
1186 TypeWithKeyword::getKeywordName(ElaboratedTypeKeyword Keyword) {
1188 case ETK_None: return "";
1189 case ETK_Typename: return "typename";
1190 case ETK_Class: return "class";
1191 case ETK_Struct: return "struct";
1192 case ETK_Union: return "union";
1193 case ETK_Enum: return "enum";
1196 llvm_unreachable("Unknown elaborated type keyword.");
1200 DependentTemplateSpecializationType::DependentTemplateSpecializationType(
1201 ElaboratedTypeKeyword Keyword,
1202 NestedNameSpecifier *NNS, const IdentifierInfo *Name,
1203 unsigned NumArgs, const TemplateArgument *Args,
1205 : TypeWithKeyword(Keyword, DependentTemplateSpecialization, Canon, true,
1206 /*VariablyModified=*/false,
1207 NNS && NNS->containsUnexpandedParameterPack()),
1208 NNS(NNS), Name(Name), NumArgs(NumArgs) {
1209 assert((!NNS || NNS->isDependent()) &&
1210 "DependentTemplateSpecializatonType requires dependent qualifier");
1211 for (unsigned I = 0; I != NumArgs; ++I) {
1212 if (Args[I].containsUnexpandedParameterPack())
1213 setContainsUnexpandedParameterPack();
1215 new (&getArgBuffer()[I]) TemplateArgument(Args[I]);
1220 DependentTemplateSpecializationType::Profile(llvm::FoldingSetNodeID &ID,
1221 const ASTContext &Context,
1222 ElaboratedTypeKeyword Keyword,
1223 NestedNameSpecifier *Qualifier,
1224 const IdentifierInfo *Name,
1226 const TemplateArgument *Args) {
1227 ID.AddInteger(Keyword);
1228 ID.AddPointer(Qualifier);
1229 ID.AddPointer(Name);
1230 for (unsigned Idx = 0; Idx < NumArgs; ++Idx)
1231 Args[Idx].Profile(ID, Context);
1234 bool Type::isElaboratedTypeSpecifier() const {
1235 ElaboratedTypeKeyword Keyword;
1236 if (const ElaboratedType *Elab = dyn_cast<ElaboratedType>(this))
1237 Keyword = Elab->getKeyword();
1238 else if (const DependentNameType *DepName = dyn_cast<DependentNameType>(this))
1239 Keyword = DepName->getKeyword();
1240 else if (const DependentTemplateSpecializationType *DepTST =
1241 dyn_cast<DependentTemplateSpecializationType>(this))
1242 Keyword = DepTST->getKeyword();
1246 return TypeWithKeyword::KeywordIsTagTypeKind(Keyword);
1249 const char *Type::getTypeClassName() const {
1250 switch (TypeBits.TC) {
1251 #define ABSTRACT_TYPE(Derived, Base)
1252 #define TYPE(Derived, Base) case Derived: return #Derived;
1253 #include "clang/AST/TypeNodes.def"
1256 llvm_unreachable("Invalid type class.");
1260 const char *BuiltinType::getName(const LangOptions &LO) const {
1261 switch (getKind()) {
1262 case Void: return "void";
1263 case Bool: return LO.Bool ? "bool" : "_Bool";
1264 case Char_S: return "char";
1265 case Char_U: return "char";
1266 case SChar: return "signed char";
1267 case Short: return "short";
1268 case Int: return "int";
1269 case Long: return "long";
1270 case LongLong: return "long long";
1271 case Int128: return "__int128_t";
1272 case UChar: return "unsigned char";
1273 case UShort: return "unsigned short";
1274 case UInt: return "unsigned int";
1275 case ULong: return "unsigned long";
1276 case ULongLong: return "unsigned long long";
1277 case UInt128: return "__uint128_t";
1278 case Float: return "float";
1279 case Double: return "double";
1280 case LongDouble: return "long double";
1282 case WChar_U: return "wchar_t";
1283 case Char16: return "char16_t";
1284 case Char32: return "char32_t";
1285 case NullPtr: return "nullptr_t";
1286 case Overload: return "<overloaded function type>";
1287 case BoundMember: return "<bound member function type>";
1288 case Dependent: return "<dependent type>";
1289 case UnknownAny: return "<unknown type>";
1290 case ObjCId: return "id";
1291 case ObjCClass: return "Class";
1292 case ObjCSel: return "SEL";
1295 llvm_unreachable("Invalid builtin type.");
1299 QualType QualType::getNonLValueExprType(ASTContext &Context) const {
1300 if (const ReferenceType *RefType = getTypePtr()->getAs<ReferenceType>())
1301 return RefType->getPointeeType();
1303 // C++0x [basic.lval]:
1304 // Class prvalues can have cv-qualified types; non-class prvalues always
1305 // have cv-unqualified types.
1307 // See also C99 6.3.2.1p2.
1308 if (!Context.getLangOptions().CPlusPlus ||
1309 (!getTypePtr()->isDependentType() && !getTypePtr()->isRecordType()))
1310 return getUnqualifiedType();
1315 llvm::StringRef FunctionType::getNameForCallConv(CallingConv CC) {
1318 llvm_unreachable("no name for default cc");
1321 case CC_C: return "cdecl";
1322 case CC_X86StdCall: return "stdcall";
1323 case CC_X86FastCall: return "fastcall";
1324 case CC_X86ThisCall: return "thiscall";
1325 case CC_X86Pascal: return "pascal";
1326 case CC_AAPCS: return "aapcs";
1327 case CC_AAPCS_VFP: return "aapcs-vfp";
1330 llvm_unreachable("Invalid calling convention.");
1334 FunctionProtoType::FunctionProtoType(QualType result, const QualType *args,
1335 unsigned numArgs, QualType canonical,
1336 const ExtProtoInfo &epi)
1337 : FunctionType(FunctionProto, result, epi.Variadic, epi.TypeQuals,
1338 epi.RefQualifier, canonical,
1339 result->isDependentType(),
1340 result->isVariablyModifiedType(),
1341 result->containsUnexpandedParameterPack(),
1343 NumArgs(numArgs), NumExceptions(epi.NumExceptions),
1344 ExceptionSpecType(epi.ExceptionSpecType)
1346 // Fill in the trailing argument array.
1347 QualType *argSlot = reinterpret_cast<QualType*>(this+1);
1348 for (unsigned i = 0; i != numArgs; ++i) {
1349 if (args[i]->isDependentType())
1352 if (args[i]->containsUnexpandedParameterPack())
1353 setContainsUnexpandedParameterPack();
1355 argSlot[i] = args[i];
1358 if (getExceptionSpecType() == EST_Dynamic) {
1359 // Fill in the exception array.
1360 QualType *exnSlot = argSlot + numArgs;
1361 for (unsigned i = 0, e = epi.NumExceptions; i != e; ++i) {
1362 if (epi.Exceptions[i]->isDependentType())
1365 if (epi.Exceptions[i]->containsUnexpandedParameterPack())
1366 setContainsUnexpandedParameterPack();
1368 exnSlot[i] = epi.Exceptions[i];
1370 } else if (getExceptionSpecType() == EST_ComputedNoexcept) {
1371 // Store the noexcept expression and context.
1372 Expr **noexSlot = reinterpret_cast<Expr**>(argSlot + numArgs);
1373 *noexSlot = epi.NoexceptExpr;
1377 FunctionProtoType::NoexceptResult
1378 FunctionProtoType::getNoexceptSpec(ASTContext &ctx) const {
1379 ExceptionSpecificationType est = getExceptionSpecType();
1380 if (est == EST_BasicNoexcept)
1383 if (est != EST_ComputedNoexcept)
1384 return NR_NoNoexcept;
1386 Expr *noexceptExpr = getNoexceptExpr();
1388 return NR_BadNoexcept;
1389 if (noexceptExpr->isValueDependent())
1390 return NR_Dependent;
1393 bool isICE = noexceptExpr->isIntegerConstantExpr(value, ctx, 0,
1394 /*evaluated*/false);
1396 assert(isICE && "AST should not contain bad noexcept expressions.");
1398 return value.getBoolValue() ? NR_Nothrow : NR_Throw;
1401 bool FunctionProtoType::isTemplateVariadic() const {
1402 for (unsigned ArgIdx = getNumArgs(); ArgIdx; --ArgIdx)
1403 if (isa<PackExpansionType>(getArgType(ArgIdx - 1)))
1409 void FunctionProtoType::Profile(llvm::FoldingSetNodeID &ID, QualType Result,
1410 const QualType *ArgTys, unsigned NumArgs,
1411 const ExtProtoInfo &epi,
1412 const ASTContext &Context) {
1413 ID.AddPointer(Result.getAsOpaquePtr());
1414 for (unsigned i = 0; i != NumArgs; ++i)
1415 ID.AddPointer(ArgTys[i].getAsOpaquePtr());
1416 ID.AddBoolean(epi.Variadic);
1417 ID.AddInteger(epi.TypeQuals);
1418 ID.AddInteger(epi.RefQualifier);
1419 ID.AddInteger(epi.ExceptionSpecType);
1420 if (epi.ExceptionSpecType == EST_Dynamic) {
1421 for (unsigned i = 0; i != epi.NumExceptions; ++i)
1422 ID.AddPointer(epi.Exceptions[i].getAsOpaquePtr());
1423 } else if (epi.ExceptionSpecType == EST_ComputedNoexcept && epi.NoexceptExpr){
1424 epi.NoexceptExpr->Profile(ID, Context, true);
1426 epi.ExtInfo.Profile(ID);
1429 void FunctionProtoType::Profile(llvm::FoldingSetNodeID &ID,
1430 const ASTContext &Ctx) {
1431 Profile(ID, getResultType(), arg_type_begin(), NumArgs, getExtProtoInfo(),
1435 QualType TypedefType::desugar() const {
1436 return getDecl()->getUnderlyingType();
1439 TypeOfExprType::TypeOfExprType(Expr *E, QualType can)
1440 : Type(TypeOfExpr, can, E->isTypeDependent(),
1441 E->getType()->isVariablyModifiedType(),
1442 E->containsUnexpandedParameterPack()),
1446 QualType TypeOfExprType::desugar() const {
1447 return getUnderlyingExpr()->getType();
1450 void DependentTypeOfExprType::Profile(llvm::FoldingSetNodeID &ID,
1451 const ASTContext &Context, Expr *E) {
1452 E->Profile(ID, Context, true);
1455 DecltypeType::DecltypeType(Expr *E, QualType underlyingType, QualType can)
1456 : Type(Decltype, can, E->isTypeDependent(),
1457 E->getType()->isVariablyModifiedType(),
1458 E->containsUnexpandedParameterPack()),
1460 UnderlyingType(underlyingType) {
1463 DependentDecltypeType::DependentDecltypeType(const ASTContext &Context, Expr *E)
1464 : DecltypeType(E, Context.DependentTy), Context(Context) { }
1466 void DependentDecltypeType::Profile(llvm::FoldingSetNodeID &ID,
1467 const ASTContext &Context, Expr *E) {
1468 E->Profile(ID, Context, true);
1471 TagType::TagType(TypeClass TC, const TagDecl *D, QualType can)
1472 : Type(TC, can, D->isDependentType(), /*VariablyModified=*/false,
1473 /*ContainsUnexpandedParameterPack=*/false),
1474 decl(const_cast<TagDecl*>(D)) {}
1476 static TagDecl *getInterestingTagDecl(TagDecl *decl) {
1477 for (TagDecl::redecl_iterator I = decl->redecls_begin(),
1478 E = decl->redecls_end();
1480 if (I->isDefinition() || I->isBeingDefined())
1483 // If there's no definition (not even in progress), return what we have.
1487 TagDecl *TagType::getDecl() const {
1488 return getInterestingTagDecl(decl);
1491 bool TagType::isBeingDefined() const {
1492 return getDecl()->isBeingDefined();
1495 CXXRecordDecl *InjectedClassNameType::getDecl() const {
1496 return cast<CXXRecordDecl>(getInterestingTagDecl(Decl));
1499 bool RecordType::classof(const TagType *TT) {
1500 return isa<RecordDecl>(TT->getDecl());
1503 bool EnumType::classof(const TagType *TT) {
1504 return isa<EnumDecl>(TT->getDecl());
1507 IdentifierInfo *TemplateTypeParmType::getIdentifier() const {
1508 return isCanonicalUnqualified() ? 0 : getDecl()->getIdentifier();
1511 SubstTemplateTypeParmPackType::
1512 SubstTemplateTypeParmPackType(const TemplateTypeParmType *Param,
1514 const TemplateArgument &ArgPack)
1515 : Type(SubstTemplateTypeParmPack, Canon, true, false, true), Replaced(Param),
1516 Arguments(ArgPack.pack_begin()), NumArguments(ArgPack.pack_size())
1520 TemplateArgument SubstTemplateTypeParmPackType::getArgumentPack() const {
1521 return TemplateArgument(Arguments, NumArguments);
1524 void SubstTemplateTypeParmPackType::Profile(llvm::FoldingSetNodeID &ID) {
1525 Profile(ID, getReplacedParameter(), getArgumentPack());
1528 void SubstTemplateTypeParmPackType::Profile(llvm::FoldingSetNodeID &ID,
1529 const TemplateTypeParmType *Replaced,
1530 const TemplateArgument &ArgPack) {
1531 ID.AddPointer(Replaced);
1532 ID.AddInteger(ArgPack.pack_size());
1533 for (TemplateArgument::pack_iterator P = ArgPack.pack_begin(),
1534 PEnd = ArgPack.pack_end();
1536 ID.AddPointer(P->getAsType().getAsOpaquePtr());
1539 bool TemplateSpecializationType::
1540 anyDependentTemplateArguments(const TemplateArgumentListInfo &Args) {
1541 return anyDependentTemplateArguments(Args.getArgumentArray(), Args.size());
1544 bool TemplateSpecializationType::
1545 anyDependentTemplateArguments(const TemplateArgumentLoc *Args, unsigned N) {
1546 for (unsigned i = 0; i != N; ++i)
1547 if (Args[i].getArgument().isDependent())
1552 bool TemplateSpecializationType::
1553 anyDependentTemplateArguments(const TemplateArgument *Args, unsigned N) {
1554 for (unsigned i = 0; i != N; ++i)
1555 if (Args[i].isDependent())
1560 TemplateSpecializationType::
1561 TemplateSpecializationType(TemplateName T,
1562 const TemplateArgument *Args,
1563 unsigned NumArgs, QualType Canon)
1564 : Type(TemplateSpecialization,
1565 Canon.isNull()? QualType(this, 0) : Canon,
1566 T.isDependent(), false, T.containsUnexpandedParameterPack()),
1567 Template(T), NumArgs(NumArgs)
1569 assert(!T.getAsDependentTemplateName() &&
1570 "Use DependentTemplateSpecializationType for dependent template-name");
1571 assert((!Canon.isNull() ||
1572 T.isDependent() || anyDependentTemplateArguments(Args, NumArgs)) &&
1573 "No canonical type for non-dependent class template specialization");
1575 TemplateArgument *TemplateArgs
1576 = reinterpret_cast<TemplateArgument *>(this + 1);
1577 for (unsigned Arg = 0; Arg < NumArgs; ++Arg) {
1578 // Update dependent and variably-modified bits.
1579 if (Args[Arg].isDependent())
1581 if (Args[Arg].getKind() == TemplateArgument::Type &&
1582 Args[Arg].getAsType()->isVariablyModifiedType())
1583 setVariablyModified();
1584 if (Args[Arg].containsUnexpandedParameterPack())
1585 setContainsUnexpandedParameterPack();
1587 new (&TemplateArgs[Arg]) TemplateArgument(Args[Arg]);
1592 TemplateSpecializationType::Profile(llvm::FoldingSetNodeID &ID,
1594 const TemplateArgument *Args,
1596 const ASTContext &Context) {
1598 for (unsigned Idx = 0; Idx < NumArgs; ++Idx)
1599 Args[Idx].Profile(ID, Context);
1603 QualifierCollector::apply(const ASTContext &Context, QualType QT) const {
1604 if (!hasNonFastQualifiers())
1605 return QT.withFastQualifiers(getFastQualifiers());
1607 return Context.getQualifiedType(QT, *this);
1611 QualifierCollector::apply(const ASTContext &Context, const Type *T) const {
1612 if (!hasNonFastQualifiers())
1613 return QualType(T, getFastQualifiers());
1615 return Context.getQualifiedType(T, *this);
1618 void ObjCObjectTypeImpl::Profile(llvm::FoldingSetNodeID &ID,
1620 ObjCProtocolDecl * const *Protocols,
1621 unsigned NumProtocols) {
1622 ID.AddPointer(BaseType.getAsOpaquePtr());
1623 for (unsigned i = 0; i != NumProtocols; i++)
1624 ID.AddPointer(Protocols[i]);
1627 void ObjCObjectTypeImpl::Profile(llvm::FoldingSetNodeID &ID) {
1628 Profile(ID, getBaseType(), qual_begin(), getNumProtocols());
1633 /// \brief The cached properties of a type.
1634 class CachedProperties {
1640 CachedProperties(Linkage linkage, Visibility visibility, bool local)
1641 : linkage(linkage), visibility(visibility), local(local) {}
1643 Linkage getLinkage() const { return (Linkage) linkage; }
1644 Visibility getVisibility() const { return (Visibility) visibility; }
1645 bool hasLocalOrUnnamedType() const { return local; }
1647 friend CachedProperties merge(CachedProperties L, CachedProperties R) {
1648 return CachedProperties(minLinkage(L.getLinkage(), R.getLinkage()),
1649 minVisibility(L.getVisibility(), R.getVisibility()),
1650 L.hasLocalOrUnnamedType() | R.hasLocalOrUnnamedType());
1655 static CachedProperties computeCachedProperties(const Type *T);
1658 /// The type-property cache. This is templated so as to be
1659 /// instantiated at an internal type to prevent unnecessary symbol
1661 template <class Private> class TypePropertyCache {
1663 static CachedProperties get(QualType T) {
1664 return get(T.getTypePtr());
1667 static CachedProperties get(const Type *T) {
1669 return CachedProperties(T->TypeBits.getLinkage(),
1670 T->TypeBits.getVisibility(),
1671 T->TypeBits.hasLocalOrUnnamedType());
1674 static void ensure(const Type *T) {
1675 // If the cache is valid, we're okay.
1676 if (T->TypeBits.isCacheValid()) return;
1678 // If this type is non-canonical, ask its canonical type for the
1679 // relevant information.
1680 if (!T->isCanonicalUnqualified()) {
1681 const Type *CT = T->getCanonicalTypeInternal().getTypePtr();
1683 T->TypeBits.CacheValidAndVisibility =
1684 CT->TypeBits.CacheValidAndVisibility;
1685 T->TypeBits.CachedLinkage = CT->TypeBits.CachedLinkage;
1686 T->TypeBits.CachedLocalOrUnnamed = CT->TypeBits.CachedLocalOrUnnamed;
1690 // Compute the cached properties and then set the cache.
1691 CachedProperties Result = computeCachedProperties(T);
1692 T->TypeBits.CacheValidAndVisibility = Result.getVisibility() + 1U;
1693 assert(T->TypeBits.isCacheValid() &&
1694 T->TypeBits.getVisibility() == Result.getVisibility());
1695 T->TypeBits.CachedLinkage = Result.getLinkage();
1696 T->TypeBits.CachedLocalOrUnnamed = Result.hasLocalOrUnnamedType();
1701 // Instantiate the friend template at a private class. In a
1702 // reasonable implementation, these symbols will be internal.
1703 // It is terrible that this is the best way to accomplish this.
1704 namespace { class Private {}; }
1705 typedef TypePropertyCache<Private> Cache;
1707 static CachedProperties computeCachedProperties(const Type *T) {
1708 switch (T->getTypeClass()) {
1709 #define TYPE(Class,Base)
1710 #define NON_CANONICAL_TYPE(Class,Base) case Type::Class:
1711 #include "clang/AST/TypeNodes.def"
1712 llvm_unreachable("didn't expect a non-canonical type here");
1714 #define TYPE(Class,Base)
1715 #define DEPENDENT_TYPE(Class,Base) case Type::Class:
1716 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class,Base) case Type::Class:
1717 #include "clang/AST/TypeNodes.def"
1718 // Treat dependent types as external.
1719 assert(T->isDependentType());
1720 return CachedProperties(ExternalLinkage, DefaultVisibility, false);
1723 // C++ [basic.link]p8:
1724 // A type is said to have linkage if and only if:
1725 // - it is a fundamental type (3.9.1); or
1726 return CachedProperties(ExternalLinkage, DefaultVisibility, false);
1730 const TagDecl *Tag = cast<TagType>(T)->getDecl();
1732 // C++ [basic.link]p8:
1733 // - it is a class or enumeration type that is named (or has a name
1734 // for linkage purposes (7.1.3)) and the name has linkage; or
1735 // - it is a specialization of a class template (14); or
1736 NamedDecl::LinkageInfo LV = Tag->getLinkageAndVisibility();
1737 bool IsLocalOrUnnamed =
1738 Tag->getDeclContext()->isFunctionOrMethod() ||
1739 (!Tag->getIdentifier() && !Tag->getTypedefNameForAnonDecl());
1740 return CachedProperties(LV.linkage(), LV.visibility(), IsLocalOrUnnamed);
1743 // C++ [basic.link]p8:
1744 // - it is a compound type (3.9.2) other than a class or enumeration,
1745 // compounded exclusively from types that have linkage; or
1747 return Cache::get(cast<ComplexType>(T)->getElementType());
1749 return Cache::get(cast<PointerType>(T)->getPointeeType());
1750 case Type::BlockPointer:
1751 return Cache::get(cast<BlockPointerType>(T)->getPointeeType());
1752 case Type::LValueReference:
1753 case Type::RValueReference:
1754 return Cache::get(cast<ReferenceType>(T)->getPointeeType());
1755 case Type::MemberPointer: {
1756 const MemberPointerType *MPT = cast<MemberPointerType>(T);
1757 return merge(Cache::get(MPT->getClass()),
1758 Cache::get(MPT->getPointeeType()));
1760 case Type::ConstantArray:
1761 case Type::IncompleteArray:
1762 case Type::VariableArray:
1763 return Cache::get(cast<ArrayType>(T)->getElementType());
1765 case Type::ExtVector:
1766 return Cache::get(cast<VectorType>(T)->getElementType());
1767 case Type::FunctionNoProto:
1768 return Cache::get(cast<FunctionType>(T)->getResultType());
1769 case Type::FunctionProto: {
1770 const FunctionProtoType *FPT = cast<FunctionProtoType>(T);
1771 CachedProperties result = Cache::get(FPT->getResultType());
1772 for (FunctionProtoType::arg_type_iterator ai = FPT->arg_type_begin(),
1773 ae = FPT->arg_type_end(); ai != ae; ++ai)
1774 result = merge(result, Cache::get(*ai));
1777 case Type::ObjCInterface: {
1778 NamedDecl::LinkageInfo LV =
1779 cast<ObjCInterfaceType>(T)->getDecl()->getLinkageAndVisibility();
1780 return CachedProperties(LV.linkage(), LV.visibility(), false);
1782 case Type::ObjCObject:
1783 return Cache::get(cast<ObjCObjectType>(T)->getBaseType());
1784 case Type::ObjCObjectPointer:
1785 return Cache::get(cast<ObjCObjectPointerType>(T)->getPointeeType());
1788 llvm_unreachable("unhandled type class");
1790 // C++ [basic.link]p8:
1791 // Names not covered by these rules have no linkage.
1792 return CachedProperties(NoLinkage, DefaultVisibility, false);
1795 /// \brief Determine the linkage of this type.
1796 Linkage Type::getLinkage() const {
1797 Cache::ensure(this);
1798 return TypeBits.getLinkage();
1801 /// \brief Determine the linkage of this type.
1802 Visibility Type::getVisibility() const {
1803 Cache::ensure(this);
1804 return TypeBits.getVisibility();
1807 bool Type::hasUnnamedOrLocalType() const {
1808 Cache::ensure(this);
1809 return TypeBits.hasLocalOrUnnamedType();
1812 std::pair<Linkage,Visibility> Type::getLinkageAndVisibility() const {
1813 Cache::ensure(this);
1814 return std::make_pair(TypeBits.getLinkage(), TypeBits.getVisibility());
1817 void Type::ClearLinkageCache() {
1818 TypeBits.CacheValidAndVisibility = 0;
1819 if (QualType(this, 0) != CanonicalType)
1820 CanonicalType->TypeBits.CacheValidAndVisibility = 0;
1823 bool Type::hasSizedVLAType() const {
1824 if (!isVariablyModifiedType()) return false;
1826 if (const PointerType *ptr = getAs<PointerType>())
1827 return ptr->getPointeeType()->hasSizedVLAType();
1828 if (const ReferenceType *ref = getAs<ReferenceType>())
1829 return ref->getPointeeType()->hasSizedVLAType();
1830 if (const ArrayType *arr = getAsArrayTypeUnsafe()) {
1831 if (isa<VariableArrayType>(arr) &&
1832 cast<VariableArrayType>(arr)->getSizeExpr())
1835 return arr->getElementType()->hasSizedVLAType();
1841 QualType::DestructionKind QualType::isDestructedTypeImpl(QualType type) {
1842 /// Currently, the only destruction kind we recognize is C++ objects
1843 /// with non-trivial destructors.
1844 const CXXRecordDecl *record =
1845 type->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
1846 if (record && !record->hasTrivialDestructor())
1847 return DK_cxx_destructor;