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() && !ET->getDecl()->isScoped();
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() && !ET->getDecl()->isScoped())
645 return ET->getDecl()->getIntegerType()->isSignedIntegerType();
651 bool Type::isSignedIntegerOrEnumerationType() const {
652 if (const BuiltinType *BT = dyn_cast<BuiltinType>(CanonicalType)) {
653 return BT->getKind() >= BuiltinType::Char_S &&
654 BT->getKind() <= BuiltinType::Int128;
657 if (const EnumType *ET = dyn_cast<EnumType>(CanonicalType)) {
658 if (ET->getDecl()->isComplete())
659 return ET->getDecl()->getIntegerType()->isSignedIntegerType();
665 bool Type::hasSignedIntegerRepresentation() const {
666 if (const VectorType *VT = dyn_cast<VectorType>(CanonicalType))
667 return VT->getElementType()->isSignedIntegerType();
669 return isSignedIntegerType();
672 /// isUnsignedIntegerType - Return true if this is an integer type that is
673 /// unsigned, according to C99 6.2.5p6 [which returns true for _Bool], an enum
674 /// decl which has an unsigned representation
675 bool Type::isUnsignedIntegerType() const {
676 if (const BuiltinType *BT = dyn_cast<BuiltinType>(CanonicalType)) {
677 return BT->getKind() >= BuiltinType::Bool &&
678 BT->getKind() <= BuiltinType::UInt128;
681 if (const EnumType *ET = dyn_cast<EnumType>(CanonicalType)) {
682 // Incomplete enum types are not treated as integer types.
683 // FIXME: In C++, enum types are never integer types.
684 if (ET->getDecl()->isComplete() && !ET->getDecl()->isScoped())
685 return ET->getDecl()->getIntegerType()->isUnsignedIntegerType();
691 bool Type::isUnsignedIntegerOrEnumerationType() const {
692 if (const BuiltinType *BT = dyn_cast<BuiltinType>(CanonicalType)) {
693 return BT->getKind() >= BuiltinType::Bool &&
694 BT->getKind() <= BuiltinType::UInt128;
697 if (const EnumType *ET = dyn_cast<EnumType>(CanonicalType)) {
698 if (ET->getDecl()->isComplete())
699 return ET->getDecl()->getIntegerType()->isUnsignedIntegerType();
705 bool Type::hasUnsignedIntegerRepresentation() const {
706 if (const VectorType *VT = dyn_cast<VectorType>(CanonicalType))
707 return VT->getElementType()->isUnsignedIntegerType();
709 return isUnsignedIntegerType();
712 bool Type::isFloatingType() const {
713 if (const BuiltinType *BT = dyn_cast<BuiltinType>(CanonicalType))
714 return BT->getKind() >= BuiltinType::Float &&
715 BT->getKind() <= BuiltinType::LongDouble;
716 if (const ComplexType *CT = dyn_cast<ComplexType>(CanonicalType))
717 return CT->getElementType()->isFloatingType();
721 bool Type::hasFloatingRepresentation() const {
722 if (const VectorType *VT = dyn_cast<VectorType>(CanonicalType))
723 return VT->getElementType()->isFloatingType();
725 return isFloatingType();
728 bool Type::isRealFloatingType() const {
729 if (const BuiltinType *BT = dyn_cast<BuiltinType>(CanonicalType))
730 return BT->isFloatingPoint();
734 bool Type::isRealType() const {
735 if (const BuiltinType *BT = dyn_cast<BuiltinType>(CanonicalType))
736 return BT->getKind() >= BuiltinType::Bool &&
737 BT->getKind() <= BuiltinType::LongDouble;
738 if (const EnumType *ET = dyn_cast<EnumType>(CanonicalType))
739 return ET->getDecl()->isComplete() && !ET->getDecl()->isScoped();
743 bool Type::isArithmeticType() const {
744 if (const BuiltinType *BT = dyn_cast<BuiltinType>(CanonicalType))
745 return BT->getKind() >= BuiltinType::Bool &&
746 BT->getKind() <= BuiltinType::LongDouble;
747 if (const EnumType *ET = dyn_cast<EnumType>(CanonicalType))
748 // GCC allows forward declaration of enum types (forbid by C99 6.7.2.3p2).
749 // If a body isn't seen by the time we get here, return false.
751 // C++0x: Enumerations are not arithmetic types. For now, just return
752 // false for scoped enumerations since that will disable any
753 // unwanted implicit conversions.
754 return !ET->getDecl()->isScoped() && ET->getDecl()->isComplete();
755 return isa<ComplexType>(CanonicalType);
758 bool Type::isScalarType() const {
759 if (const BuiltinType *BT = dyn_cast<BuiltinType>(CanonicalType))
760 return BT->getKind() > BuiltinType::Void &&
761 BT->getKind() <= BuiltinType::NullPtr;
762 if (const EnumType *ET = dyn_cast<EnumType>(CanonicalType))
763 // Enums are scalar types, but only if they are defined. Incomplete enums
764 // are not treated as scalar types.
765 return ET->getDecl()->isComplete();
766 return isa<PointerType>(CanonicalType) ||
767 isa<BlockPointerType>(CanonicalType) ||
768 isa<MemberPointerType>(CanonicalType) ||
769 isa<ComplexType>(CanonicalType) ||
770 isa<ObjCObjectPointerType>(CanonicalType);
773 Type::ScalarTypeKind Type::getScalarTypeKind() const {
774 assert(isScalarType());
776 const Type *T = CanonicalType.getTypePtr();
777 if (const BuiltinType *BT = dyn_cast<BuiltinType>(T)) {
778 if (BT->getKind() == BuiltinType::Bool) return STK_Bool;
779 if (BT->getKind() == BuiltinType::NullPtr) return STK_Pointer;
780 if (BT->isInteger()) return STK_Integral;
781 if (BT->isFloatingPoint()) return STK_Floating;
782 llvm_unreachable("unknown scalar builtin type");
783 } else if (isa<PointerType>(T) ||
784 isa<BlockPointerType>(T) ||
785 isa<ObjCObjectPointerType>(T)) {
787 } else if (isa<MemberPointerType>(T)) {
788 return STK_MemberPointer;
789 } else if (isa<EnumType>(T)) {
790 assert(cast<EnumType>(T)->getDecl()->isComplete());
792 } else if (const ComplexType *CT = dyn_cast<ComplexType>(T)) {
793 if (CT->getElementType()->isRealFloatingType())
794 return STK_FloatingComplex;
795 return STK_IntegralComplex;
798 llvm_unreachable("unknown scalar type");
802 /// \brief Determines whether the type is a C++ aggregate type or C
803 /// aggregate or union type.
805 /// An aggregate type is an array or a class type (struct, union, or
806 /// class) that has no user-declared constructors, no private or
807 /// protected non-static data members, no base classes, and no virtual
808 /// functions (C++ [dcl.init.aggr]p1). The notion of an aggregate type
809 /// subsumes the notion of C aggregates (C99 6.2.5p21) because it also
810 /// includes union types.
811 bool Type::isAggregateType() const {
812 if (const RecordType *Record = dyn_cast<RecordType>(CanonicalType)) {
813 if (CXXRecordDecl *ClassDecl = dyn_cast<CXXRecordDecl>(Record->getDecl()))
814 return ClassDecl->isAggregate();
819 return isa<ArrayType>(CanonicalType);
822 /// isConstantSizeType - Return true if this is not a variable sized type,
823 /// according to the rules of C99 6.7.5p3. It is not legal to call this on
824 /// incomplete types or dependent types.
825 bool Type::isConstantSizeType() const {
826 assert(!isIncompleteType() && "This doesn't make sense for incomplete types");
827 assert(!isDependentType() && "This doesn't make sense for dependent types");
828 // The VAT must have a size, as it is known to be complete.
829 return !isa<VariableArrayType>(CanonicalType);
832 /// isIncompleteType - Return true if this is an incomplete type (C99 6.2.5p1)
833 /// - a type that can describe objects, but which lacks information needed to
834 /// determine its size.
835 bool Type::isIncompleteType() const {
836 switch (CanonicalType->getTypeClass()) {
837 default: return false;
839 // Void is the only incomplete builtin type. Per C99 6.2.5p19, it can never
843 // An enumeration with fixed underlying type is complete (C++0x 7.2p3).
844 if (cast<EnumType>(CanonicalType)->getDecl()->isFixed())
848 // A tagged type (struct/union/enum/class) is incomplete if the decl is a
849 // forward declaration, but not a full definition (C99 6.2.5p22).
850 return !cast<TagType>(CanonicalType)->getDecl()->isDefinition();
852 // An array is incomplete if its element type is incomplete
853 // (C++ [dcl.array]p1).
854 // We don't handle variable arrays (they're not allowed in C++) or
855 // dependent-sized arrays (dependent types are never treated as incomplete).
856 return cast<ArrayType>(CanonicalType)->getElementType()->isIncompleteType();
857 case IncompleteArray:
858 // An array of unknown size is an incomplete type (C99 6.2.5p22).
861 return cast<ObjCObjectType>(CanonicalType)->getBaseType()
862 ->isIncompleteType();
864 // ObjC interfaces are incomplete if they are @class, not @interface.
865 return cast<ObjCInterfaceType>(CanonicalType)->getDecl()->isForwardDecl();
869 /// isPODType - Return true if this is a plain-old-data type (C++ 3.9p10)
870 bool Type::isPODType() const {
871 // The compiler shouldn't query this for incomplete types, but the user might.
872 // We return false for that case. Except for incomplete arrays of PODs, which
873 // are PODs according to the standard.
874 if (isIncompleteArrayType() &&
875 cast<ArrayType>(CanonicalType)->getElementType()->isPODType())
877 if (isIncompleteType())
880 switch (CanonicalType->getTypeClass()) {
881 // Everything not explicitly mentioned is not POD.
882 default: return false;
885 // IncompleteArray is handled above.
886 return cast<ArrayType>(CanonicalType)->getElementType()->isPODType();
894 case ObjCObjectPointer:
902 if (CXXRecordDecl *ClassDecl
903 = dyn_cast<CXXRecordDecl>(cast<RecordType>(CanonicalType)->getDecl()))
904 return ClassDecl->isPOD();
906 // C struct/union is POD.
911 bool Type::isLiteralType() const {
912 if (isDependentType())
915 // C++0x [basic.types]p10:
916 // A type is a literal type if it is:
918 // -- an array of literal type
919 // Extension: variable arrays cannot be literal types, since they're
921 if (isVariableArrayType())
923 const Type *BaseTy = getBaseElementTypeUnsafe();
924 assert(BaseTy && "NULL element type");
926 // Return false for incomplete types after skipping any incomplete array
927 // types; those are expressly allowed by the standard and thus our API.
928 if (BaseTy->isIncompleteType())
931 // C++0x [basic.types]p10:
932 // A type is a literal type if it is:
933 // -- a scalar type; or
934 // As an extension, Clang treats vector types as Scalar types.
935 if (BaseTy->isScalarType() || BaseTy->isVectorType()) return true;
936 // -- a reference type; or
937 if (BaseTy->isReferenceType()) return true;
938 // -- a class type that has all of the following properties:
939 if (const RecordType *RT = BaseTy->getAs<RecordType>()) {
940 if (const CXXRecordDecl *ClassDecl =
941 dyn_cast<CXXRecordDecl>(RT->getDecl())) {
942 // -- a trivial destructor,
943 if (!ClassDecl->hasTrivialDestructor()) return false;
944 // -- every constructor call and full-expression in the
945 // brace-or-equal-initializers for non-static data members (if any)
946 // is a constant expression,
947 // FIXME: C++0x: Clang doesn't yet support non-static data member
948 // declarations with initializers, or constexprs.
949 // -- it is an aggregate type or has at least one constexpr
950 // constructor or constructor template that is not a copy or move
952 if (!ClassDecl->isAggregate() &&
953 !ClassDecl->hasConstExprNonCopyMoveConstructor())
955 // -- all non-static data members and base classes of literal types
956 if (ClassDecl->hasNonLiteralTypeFieldsOrBases()) return false;
964 bool Type::isTrivialType() const {
965 if (isDependentType())
968 // C++0x [basic.types]p9:
969 // Scalar types, trivial class types, arrays of such types, and
970 // cv-qualified versions of these types are collectively called trivial
972 const Type *BaseTy = getBaseElementTypeUnsafe();
973 assert(BaseTy && "NULL element type");
975 // Return false for incomplete types after skipping any incomplete array
976 // types which are expressly allowed by the standard and thus our API.
977 if (BaseTy->isIncompleteType())
980 // As an extension, Clang treats vector types as Scalar types.
981 if (BaseTy->isScalarType() || BaseTy->isVectorType()) return true;
982 if (const RecordType *RT = BaseTy->getAs<RecordType>()) {
983 if (const CXXRecordDecl *ClassDecl =
984 dyn_cast<CXXRecordDecl>(RT->getDecl())) {
985 if (!ClassDecl->isTrivial()) return false;
991 // No other types can match.
995 bool Type::isTriviallyCopyableType() const {
996 if (isDependentType())
999 // C++0x [basic.types]p9
1000 // Scalar types, trivially copyable class types, arrays of such types, and
1001 // cv-qualified versions of these types are collectively called trivial
1003 const Type *BaseTy = getBaseElementTypeUnsafe();
1004 assert(BaseTy && "NULL element type");
1006 // Return false for incomplete types after skipping any incomplete array types
1007 // which are expressly allowed by the standard and thus our API.
1008 if (BaseTy->isIncompleteType())
1011 // As an extension, Clang treats vector types as Scalar types.
1012 if (BaseTy->isScalarType() || BaseTy->isVectorType()) return true;
1013 if (const RecordType *RT = BaseTy->getAs<RecordType>()) {
1014 if (const CXXRecordDecl *ClassDecl =
1015 dyn_cast<CXXRecordDecl>(RT->getDecl())) {
1016 if (!ClassDecl->isTriviallyCopyable()) return false;
1022 // No other types can match.
1026 bool Type::isStandardLayoutType() const {
1027 if (isDependentType())
1030 // C++0x [basic.types]p9:
1031 // Scalar types, standard-layout class types, arrays of such types, and
1032 // cv-qualified versions of these types are collectively called
1033 // standard-layout types.
1034 const Type *BaseTy = getBaseElementTypeUnsafe();
1035 assert(BaseTy && "NULL element type");
1037 // Return false for incomplete types after skipping any incomplete array
1038 // types which are expressly allowed by the standard and thus our API.
1039 if (BaseTy->isIncompleteType())
1042 // As an extension, Clang treats vector types as Scalar types.
1043 if (BaseTy->isScalarType() || BaseTy->isVectorType()) return true;
1044 if (const RecordType *RT = BaseTy->getAs<RecordType>()) {
1045 if (const CXXRecordDecl *ClassDecl =
1046 dyn_cast<CXXRecordDecl>(RT->getDecl()))
1047 if (!ClassDecl->isStandardLayout())
1050 // Default to 'true' for non-C++ class types.
1051 // FIXME: This is a bit dubious, but plain C structs should trivially meet
1052 // all the requirements of standard layout classes.
1056 // No other types can match.
1060 // This is effectively the intersection of isTrivialType and
1061 // isStandardLayoutType. We implement it dircetly to avoid redundant
1062 // conversions from a type to a CXXRecordDecl.
1063 bool Type::isCXX11PODType() const {
1064 if (isDependentType())
1067 // C++11 [basic.types]p9:
1068 // Scalar types, POD classes, arrays of such types, and cv-qualified
1069 // versions of these types are collectively called trivial types.
1070 const Type *BaseTy = getBaseElementTypeUnsafe();
1071 assert(BaseTy && "NULL element type");
1073 // Return false for incomplete types after skipping any incomplete array
1074 // types which are expressly allowed by the standard and thus our API.
1075 if (BaseTy->isIncompleteType())
1078 // As an extension, Clang treats vector types as Scalar types.
1079 if (BaseTy->isScalarType() || BaseTy->isVectorType()) return true;
1080 if (const RecordType *RT = BaseTy->getAs<RecordType>()) {
1081 if (const CXXRecordDecl *ClassDecl =
1082 dyn_cast<CXXRecordDecl>(RT->getDecl())) {
1083 // C++11 [class]p10:
1084 // A POD struct is a non-union class that is both a trivial class [...]
1085 if (!ClassDecl->isTrivial()) return false;
1087 // C++11 [class]p10:
1088 // A POD struct is a non-union class that is both a trivial class and
1089 // a standard-layout class [...]
1090 if (!ClassDecl->isStandardLayout()) return false;
1092 // C++11 [class]p10:
1093 // A POD struct is a non-union class that is both a trivial class and
1094 // a standard-layout class, and has no non-static data members of type
1095 // non-POD struct, non-POD union (or array of such types). [...]
1097 // We don't directly query the recursive aspect as the requiremets for
1098 // both standard-layout classes and trivial classes apply recursively
1105 // No other types can match.
1109 bool Type::isPromotableIntegerType() const {
1110 if (const BuiltinType *BT = getAs<BuiltinType>())
1111 switch (BT->getKind()) {
1112 case BuiltinType::Bool:
1113 case BuiltinType::Char_S:
1114 case BuiltinType::Char_U:
1115 case BuiltinType::SChar:
1116 case BuiltinType::UChar:
1117 case BuiltinType::Short:
1118 case BuiltinType::UShort:
1124 // Enumerated types are promotable to their compatible integer types
1125 // (C99 6.3.1.1) a.k.a. its underlying type (C++ [conv.prom]p2).
1126 if (const EnumType *ET = getAs<EnumType>()){
1127 if (this->isDependentType() || ET->getDecl()->getPromotionType().isNull()
1128 || ET->getDecl()->isScoped())
1131 const BuiltinType *BT
1132 = ET->getDecl()->getPromotionType()->getAs<BuiltinType>();
1133 return BT->getKind() == BuiltinType::Int
1134 || BT->getKind() == BuiltinType::UInt;
1140 bool Type::isNullPtrType() const {
1141 if (const BuiltinType *BT = getAs<BuiltinType>())
1142 return BT->getKind() == BuiltinType::NullPtr;
1146 bool Type::isSpecifierType() const {
1147 // Note that this intentionally does not use the canonical type.
1148 switch (getTypeClass()) {
1156 case TemplateTypeParm:
1157 case SubstTemplateTypeParm:
1158 case TemplateSpecialization:
1161 case DependentTemplateSpecialization:
1164 case ObjCObjectPointer: // FIXME: object pointers aren't really specifiers
1171 ElaboratedTypeKeyword
1172 TypeWithKeyword::getKeywordForTypeSpec(unsigned TypeSpec) {
1174 default: return ETK_None;
1175 case TST_typename: return ETK_Typename;
1176 case TST_class: return ETK_Class;
1177 case TST_struct: return ETK_Struct;
1178 case TST_union: return ETK_Union;
1179 case TST_enum: return ETK_Enum;
1184 TypeWithKeyword::getTagTypeKindForTypeSpec(unsigned TypeSpec) {
1186 case TST_class: return TTK_Class;
1187 case TST_struct: return TTK_Struct;
1188 case TST_union: return TTK_Union;
1189 case TST_enum: return TTK_Enum;
1192 llvm_unreachable("Type specifier is not a tag type kind.");
1196 ElaboratedTypeKeyword
1197 TypeWithKeyword::getKeywordForTagTypeKind(TagTypeKind Kind) {
1199 case TTK_Class: return ETK_Class;
1200 case TTK_Struct: return ETK_Struct;
1201 case TTK_Union: return ETK_Union;
1202 case TTK_Enum: return ETK_Enum;
1204 llvm_unreachable("Unknown tag type kind.");
1208 TypeWithKeyword::getTagTypeKindForKeyword(ElaboratedTypeKeyword Keyword) {
1210 case ETK_Class: return TTK_Class;
1211 case ETK_Struct: return TTK_Struct;
1212 case ETK_Union: return TTK_Union;
1213 case ETK_Enum: return TTK_Enum;
1214 case ETK_None: // Fall through.
1216 llvm_unreachable("Elaborated type keyword is not a tag type kind.");
1218 llvm_unreachable("Unknown elaborated type keyword.");
1222 TypeWithKeyword::KeywordIsTagTypeKind(ElaboratedTypeKeyword Keyword) {
1233 llvm_unreachable("Unknown elaborated type keyword.");
1237 TypeWithKeyword::getKeywordName(ElaboratedTypeKeyword Keyword) {
1239 case ETK_None: return "";
1240 case ETK_Typename: return "typename";
1241 case ETK_Class: return "class";
1242 case ETK_Struct: return "struct";
1243 case ETK_Union: return "union";
1244 case ETK_Enum: return "enum";
1247 llvm_unreachable("Unknown elaborated type keyword.");
1251 DependentTemplateSpecializationType::DependentTemplateSpecializationType(
1252 ElaboratedTypeKeyword Keyword,
1253 NestedNameSpecifier *NNS, const IdentifierInfo *Name,
1254 unsigned NumArgs, const TemplateArgument *Args,
1256 : TypeWithKeyword(Keyword, DependentTemplateSpecialization, Canon, true,
1257 /*VariablyModified=*/false,
1258 NNS && NNS->containsUnexpandedParameterPack()),
1259 NNS(NNS), Name(Name), NumArgs(NumArgs) {
1260 assert((!NNS || NNS->isDependent()) &&
1261 "DependentTemplateSpecializatonType requires dependent qualifier");
1262 for (unsigned I = 0; I != NumArgs; ++I) {
1263 if (Args[I].containsUnexpandedParameterPack())
1264 setContainsUnexpandedParameterPack();
1266 new (&getArgBuffer()[I]) TemplateArgument(Args[I]);
1271 DependentTemplateSpecializationType::Profile(llvm::FoldingSetNodeID &ID,
1272 const ASTContext &Context,
1273 ElaboratedTypeKeyword Keyword,
1274 NestedNameSpecifier *Qualifier,
1275 const IdentifierInfo *Name,
1277 const TemplateArgument *Args) {
1278 ID.AddInteger(Keyword);
1279 ID.AddPointer(Qualifier);
1280 ID.AddPointer(Name);
1281 for (unsigned Idx = 0; Idx < NumArgs; ++Idx)
1282 Args[Idx].Profile(ID, Context);
1285 bool Type::isElaboratedTypeSpecifier() const {
1286 ElaboratedTypeKeyword Keyword;
1287 if (const ElaboratedType *Elab = dyn_cast<ElaboratedType>(this))
1288 Keyword = Elab->getKeyword();
1289 else if (const DependentNameType *DepName = dyn_cast<DependentNameType>(this))
1290 Keyword = DepName->getKeyword();
1291 else if (const DependentTemplateSpecializationType *DepTST =
1292 dyn_cast<DependentTemplateSpecializationType>(this))
1293 Keyword = DepTST->getKeyword();
1297 return TypeWithKeyword::KeywordIsTagTypeKind(Keyword);
1300 const char *Type::getTypeClassName() const {
1301 switch (TypeBits.TC) {
1302 #define ABSTRACT_TYPE(Derived, Base)
1303 #define TYPE(Derived, Base) case Derived: return #Derived;
1304 #include "clang/AST/TypeNodes.def"
1307 llvm_unreachable("Invalid type class.");
1311 const char *BuiltinType::getName(const LangOptions &LO) const {
1312 switch (getKind()) {
1313 case Void: return "void";
1314 case Bool: return LO.Bool ? "bool" : "_Bool";
1315 case Char_S: return "char";
1316 case Char_U: return "char";
1317 case SChar: return "signed char";
1318 case Short: return "short";
1319 case Int: return "int";
1320 case Long: return "long";
1321 case LongLong: return "long long";
1322 case Int128: return "__int128_t";
1323 case UChar: return "unsigned char";
1324 case UShort: return "unsigned short";
1325 case UInt: return "unsigned int";
1326 case ULong: return "unsigned long";
1327 case ULongLong: return "unsigned long long";
1328 case UInt128: return "__uint128_t";
1329 case Float: return "float";
1330 case Double: return "double";
1331 case LongDouble: return "long double";
1333 case WChar_U: return "wchar_t";
1334 case Char16: return "char16_t";
1335 case Char32: return "char32_t";
1336 case NullPtr: return "nullptr_t";
1337 case Overload: return "<overloaded function type>";
1338 case BoundMember: return "<bound member function type>";
1339 case Dependent: return "<dependent type>";
1340 case UnknownAny: return "<unknown type>";
1341 case ObjCId: return "id";
1342 case ObjCClass: return "Class";
1343 case ObjCSel: return "SEL";
1346 llvm_unreachable("Invalid builtin type.");
1350 QualType QualType::getNonLValueExprType(ASTContext &Context) const {
1351 if (const ReferenceType *RefType = getTypePtr()->getAs<ReferenceType>())
1352 return RefType->getPointeeType();
1354 // C++0x [basic.lval]:
1355 // Class prvalues can have cv-qualified types; non-class prvalues always
1356 // have cv-unqualified types.
1358 // See also C99 6.3.2.1p2.
1359 if (!Context.getLangOptions().CPlusPlus ||
1360 (!getTypePtr()->isDependentType() && !getTypePtr()->isRecordType()))
1361 return getUnqualifiedType();
1366 llvm::StringRef FunctionType::getNameForCallConv(CallingConv CC) {
1369 llvm_unreachable("no name for default cc");
1372 case CC_C: return "cdecl";
1373 case CC_X86StdCall: return "stdcall";
1374 case CC_X86FastCall: return "fastcall";
1375 case CC_X86ThisCall: return "thiscall";
1376 case CC_X86Pascal: return "pascal";
1377 case CC_AAPCS: return "aapcs";
1378 case CC_AAPCS_VFP: return "aapcs-vfp";
1381 llvm_unreachable("Invalid calling convention.");
1385 FunctionProtoType::FunctionProtoType(QualType result, const QualType *args,
1386 unsigned numArgs, QualType canonical,
1387 const ExtProtoInfo &epi)
1388 : FunctionType(FunctionProto, result, epi.Variadic, epi.TypeQuals,
1389 epi.RefQualifier, canonical,
1390 result->isDependentType(),
1391 result->isVariablyModifiedType(),
1392 result->containsUnexpandedParameterPack(),
1394 NumArgs(numArgs), NumExceptions(epi.NumExceptions),
1395 ExceptionSpecType(epi.ExceptionSpecType)
1397 // Fill in the trailing argument array.
1398 QualType *argSlot = reinterpret_cast<QualType*>(this+1);
1399 for (unsigned i = 0; i != numArgs; ++i) {
1400 if (args[i]->isDependentType())
1403 if (args[i]->containsUnexpandedParameterPack())
1404 setContainsUnexpandedParameterPack();
1406 argSlot[i] = args[i];
1409 if (getExceptionSpecType() == EST_Dynamic) {
1410 // Fill in the exception array.
1411 QualType *exnSlot = argSlot + numArgs;
1412 for (unsigned i = 0, e = epi.NumExceptions; i != e; ++i) {
1413 if (epi.Exceptions[i]->isDependentType())
1416 if (epi.Exceptions[i]->containsUnexpandedParameterPack())
1417 setContainsUnexpandedParameterPack();
1419 exnSlot[i] = epi.Exceptions[i];
1421 } else if (getExceptionSpecType() == EST_ComputedNoexcept) {
1422 // Store the noexcept expression and context.
1423 Expr **noexSlot = reinterpret_cast<Expr**>(argSlot + numArgs);
1424 *noexSlot = epi.NoexceptExpr;
1428 FunctionProtoType::NoexceptResult
1429 FunctionProtoType::getNoexceptSpec(ASTContext &ctx) const {
1430 ExceptionSpecificationType est = getExceptionSpecType();
1431 if (est == EST_BasicNoexcept)
1434 if (est != EST_ComputedNoexcept)
1435 return NR_NoNoexcept;
1437 Expr *noexceptExpr = getNoexceptExpr();
1439 return NR_BadNoexcept;
1440 if (noexceptExpr->isValueDependent())
1441 return NR_Dependent;
1444 bool isICE = noexceptExpr->isIntegerConstantExpr(value, ctx, 0,
1445 /*evaluated*/false);
1447 assert(isICE && "AST should not contain bad noexcept expressions.");
1449 return value.getBoolValue() ? NR_Nothrow : NR_Throw;
1452 bool FunctionProtoType::isTemplateVariadic() const {
1453 for (unsigned ArgIdx = getNumArgs(); ArgIdx; --ArgIdx)
1454 if (isa<PackExpansionType>(getArgType(ArgIdx - 1)))
1460 void FunctionProtoType::Profile(llvm::FoldingSetNodeID &ID, QualType Result,
1461 const QualType *ArgTys, unsigned NumArgs,
1462 const ExtProtoInfo &epi,
1463 const ASTContext &Context) {
1464 ID.AddPointer(Result.getAsOpaquePtr());
1465 for (unsigned i = 0; i != NumArgs; ++i)
1466 ID.AddPointer(ArgTys[i].getAsOpaquePtr());
1467 ID.AddBoolean(epi.Variadic);
1468 ID.AddInteger(epi.TypeQuals);
1469 ID.AddInteger(epi.RefQualifier);
1470 ID.AddInteger(epi.ExceptionSpecType);
1471 if (epi.ExceptionSpecType == EST_Dynamic) {
1472 for (unsigned i = 0; i != epi.NumExceptions; ++i)
1473 ID.AddPointer(epi.Exceptions[i].getAsOpaquePtr());
1474 } else if (epi.ExceptionSpecType == EST_ComputedNoexcept && epi.NoexceptExpr){
1475 epi.NoexceptExpr->Profile(ID, Context, true);
1477 epi.ExtInfo.Profile(ID);
1480 void FunctionProtoType::Profile(llvm::FoldingSetNodeID &ID,
1481 const ASTContext &Ctx) {
1482 Profile(ID, getResultType(), arg_type_begin(), NumArgs, getExtProtoInfo(),
1486 QualType TypedefType::desugar() const {
1487 return getDecl()->getUnderlyingType();
1490 TypeOfExprType::TypeOfExprType(Expr *E, QualType can)
1491 : Type(TypeOfExpr, can, E->isTypeDependent(),
1492 E->getType()->isVariablyModifiedType(),
1493 E->containsUnexpandedParameterPack()),
1497 QualType TypeOfExprType::desugar() const {
1498 return getUnderlyingExpr()->getType();
1501 void DependentTypeOfExprType::Profile(llvm::FoldingSetNodeID &ID,
1502 const ASTContext &Context, Expr *E) {
1503 E->Profile(ID, Context, true);
1506 DecltypeType::DecltypeType(Expr *E, QualType underlyingType, QualType can)
1507 : Type(Decltype, can, E->isTypeDependent(),
1508 E->getType()->isVariablyModifiedType(),
1509 E->containsUnexpandedParameterPack()),
1511 UnderlyingType(underlyingType) {
1514 DependentDecltypeType::DependentDecltypeType(const ASTContext &Context, Expr *E)
1515 : DecltypeType(E, Context.DependentTy), Context(Context) { }
1517 void DependentDecltypeType::Profile(llvm::FoldingSetNodeID &ID,
1518 const ASTContext &Context, Expr *E) {
1519 E->Profile(ID, Context, true);
1522 TagType::TagType(TypeClass TC, const TagDecl *D, QualType can)
1523 : Type(TC, can, D->isDependentType(), /*VariablyModified=*/false,
1524 /*ContainsUnexpandedParameterPack=*/false),
1525 decl(const_cast<TagDecl*>(D)) {}
1527 static TagDecl *getInterestingTagDecl(TagDecl *decl) {
1528 for (TagDecl::redecl_iterator I = decl->redecls_begin(),
1529 E = decl->redecls_end();
1531 if (I->isDefinition() || I->isBeingDefined())
1534 // If there's no definition (not even in progress), return what we have.
1538 UnaryTransformType::UnaryTransformType(QualType BaseType,
1539 QualType UnderlyingType,
1541 QualType CanonicalType)
1542 : Type(UnaryTransform, CanonicalType, UnderlyingType->isDependentType(),
1543 UnderlyingType->isVariablyModifiedType(),
1544 BaseType->containsUnexpandedParameterPack())
1545 , BaseType(BaseType), UnderlyingType(UnderlyingType), UKind(UKind)
1548 TagDecl *TagType::getDecl() const {
1549 return getInterestingTagDecl(decl);
1552 bool TagType::isBeingDefined() const {
1553 return getDecl()->isBeingDefined();
1556 CXXRecordDecl *InjectedClassNameType::getDecl() const {
1557 return cast<CXXRecordDecl>(getInterestingTagDecl(Decl));
1560 bool RecordType::classof(const TagType *TT) {
1561 return isa<RecordDecl>(TT->getDecl());
1564 bool EnumType::classof(const TagType *TT) {
1565 return isa<EnumDecl>(TT->getDecl());
1568 IdentifierInfo *TemplateTypeParmType::getIdentifier() const {
1569 return isCanonicalUnqualified() ? 0 : getDecl()->getIdentifier();
1572 SubstTemplateTypeParmPackType::
1573 SubstTemplateTypeParmPackType(const TemplateTypeParmType *Param,
1575 const TemplateArgument &ArgPack)
1576 : Type(SubstTemplateTypeParmPack, Canon, true, false, true), Replaced(Param),
1577 Arguments(ArgPack.pack_begin()), NumArguments(ArgPack.pack_size())
1581 TemplateArgument SubstTemplateTypeParmPackType::getArgumentPack() const {
1582 return TemplateArgument(Arguments, NumArguments);
1585 void SubstTemplateTypeParmPackType::Profile(llvm::FoldingSetNodeID &ID) {
1586 Profile(ID, getReplacedParameter(), getArgumentPack());
1589 void SubstTemplateTypeParmPackType::Profile(llvm::FoldingSetNodeID &ID,
1590 const TemplateTypeParmType *Replaced,
1591 const TemplateArgument &ArgPack) {
1592 ID.AddPointer(Replaced);
1593 ID.AddInteger(ArgPack.pack_size());
1594 for (TemplateArgument::pack_iterator P = ArgPack.pack_begin(),
1595 PEnd = ArgPack.pack_end();
1597 ID.AddPointer(P->getAsType().getAsOpaquePtr());
1600 bool TemplateSpecializationType::
1601 anyDependentTemplateArguments(const TemplateArgumentListInfo &Args) {
1602 return anyDependentTemplateArguments(Args.getArgumentArray(), Args.size());
1605 bool TemplateSpecializationType::
1606 anyDependentTemplateArguments(const TemplateArgumentLoc *Args, unsigned N) {
1607 for (unsigned i = 0; i != N; ++i)
1608 if (Args[i].getArgument().isDependent())
1613 bool TemplateSpecializationType::
1614 anyDependentTemplateArguments(const TemplateArgument *Args, unsigned N) {
1615 for (unsigned i = 0; i != N; ++i)
1616 if (Args[i].isDependent())
1621 TemplateSpecializationType::
1622 TemplateSpecializationType(TemplateName T,
1623 const TemplateArgument *Args, unsigned NumArgs,
1624 QualType Canon, QualType AliasedType)
1625 : Type(TemplateSpecialization,
1626 Canon.isNull()? QualType(this, 0) : Canon,
1627 Canon.isNull()? T.isDependent() : Canon->isDependentType(),
1628 false, T.containsUnexpandedParameterPack()),
1629 Template(T), NumArgs(NumArgs) {
1630 assert(!T.getAsDependentTemplateName() &&
1631 "Use DependentTemplateSpecializationType for dependent template-name");
1632 assert((!Canon.isNull() ||
1633 T.isDependent() || anyDependentTemplateArguments(Args, NumArgs)) &&
1634 "No canonical type for non-dependent class template specialization");
1636 TemplateArgument *TemplateArgs
1637 = reinterpret_cast<TemplateArgument *>(this + 1);
1638 for (unsigned Arg = 0; Arg < NumArgs; ++Arg) {
1639 // Update dependent and variably-modified bits.
1640 // If the canonical type exists and is non-dependent, the template
1641 // specialization type can be non-dependent even if one of the type
1642 // arguments is. Given:
1643 // template<typename T> using U = int;
1644 // U<T> is always non-dependent, irrespective of the type T.
1645 if (Canon.isNull() && Args[Arg].isDependent())
1647 if (Args[Arg].getKind() == TemplateArgument::Type &&
1648 Args[Arg].getAsType()->isVariablyModifiedType())
1649 setVariablyModified();
1650 if (Args[Arg].containsUnexpandedParameterPack())
1651 setContainsUnexpandedParameterPack();
1653 new (&TemplateArgs[Arg]) TemplateArgument(Args[Arg]);
1656 // Store the aliased type if this is a type alias template specialization.
1657 bool IsTypeAlias = !AliasedType.isNull();
1658 assert(IsTypeAlias == isTypeAlias() &&
1659 "allocated wrong size for type alias");
1661 TemplateArgument *Begin = reinterpret_cast<TemplateArgument *>(this + 1);
1662 *reinterpret_cast<QualType*>(Begin + getNumArgs()) = AliasedType;
1667 TemplateSpecializationType::Profile(llvm::FoldingSetNodeID &ID,
1669 const TemplateArgument *Args,
1671 const ASTContext &Context) {
1673 for (unsigned Idx = 0; Idx < NumArgs; ++Idx)
1674 Args[Idx].Profile(ID, Context);
1677 bool TemplateSpecializationType::isTypeAlias() const {
1678 TemplateDecl *D = Template.getAsTemplateDecl();
1679 return D && isa<TypeAliasTemplateDecl>(D);
1683 QualifierCollector::apply(const ASTContext &Context, QualType QT) const {
1684 if (!hasNonFastQualifiers())
1685 return QT.withFastQualifiers(getFastQualifiers());
1687 return Context.getQualifiedType(QT, *this);
1691 QualifierCollector::apply(const ASTContext &Context, const Type *T) const {
1692 if (!hasNonFastQualifiers())
1693 return QualType(T, getFastQualifiers());
1695 return Context.getQualifiedType(T, *this);
1698 void ObjCObjectTypeImpl::Profile(llvm::FoldingSetNodeID &ID,
1700 ObjCProtocolDecl * const *Protocols,
1701 unsigned NumProtocols) {
1702 ID.AddPointer(BaseType.getAsOpaquePtr());
1703 for (unsigned i = 0; i != NumProtocols; i++)
1704 ID.AddPointer(Protocols[i]);
1707 void ObjCObjectTypeImpl::Profile(llvm::FoldingSetNodeID &ID) {
1708 Profile(ID, getBaseType(), qual_begin(), getNumProtocols());
1713 /// \brief The cached properties of a type.
1714 class CachedProperties {
1720 CachedProperties(Linkage linkage, Visibility visibility, bool local)
1721 : linkage(linkage), visibility(visibility), local(local) {}
1723 Linkage getLinkage() const { return (Linkage) linkage; }
1724 Visibility getVisibility() const { return (Visibility) visibility; }
1725 bool hasLocalOrUnnamedType() const { return local; }
1727 friend CachedProperties merge(CachedProperties L, CachedProperties R) {
1728 return CachedProperties(minLinkage(L.getLinkage(), R.getLinkage()),
1729 minVisibility(L.getVisibility(), R.getVisibility()),
1730 L.hasLocalOrUnnamedType() | R.hasLocalOrUnnamedType());
1735 static CachedProperties computeCachedProperties(const Type *T);
1738 /// The type-property cache. This is templated so as to be
1739 /// instantiated at an internal type to prevent unnecessary symbol
1741 template <class Private> class TypePropertyCache {
1743 static CachedProperties get(QualType T) {
1744 return get(T.getTypePtr());
1747 static CachedProperties get(const Type *T) {
1749 return CachedProperties(T->TypeBits.getLinkage(),
1750 T->TypeBits.getVisibility(),
1751 T->TypeBits.hasLocalOrUnnamedType());
1754 static void ensure(const Type *T) {
1755 // If the cache is valid, we're okay.
1756 if (T->TypeBits.isCacheValid()) return;
1758 // If this type is non-canonical, ask its canonical type for the
1759 // relevant information.
1760 if (!T->isCanonicalUnqualified()) {
1761 const Type *CT = T->getCanonicalTypeInternal().getTypePtr();
1763 T->TypeBits.CacheValidAndVisibility =
1764 CT->TypeBits.CacheValidAndVisibility;
1765 T->TypeBits.CachedLinkage = CT->TypeBits.CachedLinkage;
1766 T->TypeBits.CachedLocalOrUnnamed = CT->TypeBits.CachedLocalOrUnnamed;
1770 // Compute the cached properties and then set the cache.
1771 CachedProperties Result = computeCachedProperties(T);
1772 T->TypeBits.CacheValidAndVisibility = Result.getVisibility() + 1U;
1773 assert(T->TypeBits.isCacheValid() &&
1774 T->TypeBits.getVisibility() == Result.getVisibility());
1775 T->TypeBits.CachedLinkage = Result.getLinkage();
1776 T->TypeBits.CachedLocalOrUnnamed = Result.hasLocalOrUnnamedType();
1781 // Instantiate the friend template at a private class. In a
1782 // reasonable implementation, these symbols will be internal.
1783 // It is terrible that this is the best way to accomplish this.
1784 namespace { class Private {}; }
1785 typedef TypePropertyCache<Private> Cache;
1787 static CachedProperties computeCachedProperties(const Type *T) {
1788 switch (T->getTypeClass()) {
1789 #define TYPE(Class,Base)
1790 #define NON_CANONICAL_TYPE(Class,Base) case Type::Class:
1791 #include "clang/AST/TypeNodes.def"
1792 llvm_unreachable("didn't expect a non-canonical type here");
1794 #define TYPE(Class,Base)
1795 #define DEPENDENT_TYPE(Class,Base) case Type::Class:
1796 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class,Base) case Type::Class:
1797 #include "clang/AST/TypeNodes.def"
1798 // Treat dependent types as external.
1799 assert(T->isDependentType());
1800 return CachedProperties(ExternalLinkage, DefaultVisibility, false);
1803 // C++ [basic.link]p8:
1804 // A type is said to have linkage if and only if:
1805 // - it is a fundamental type (3.9.1); or
1806 return CachedProperties(ExternalLinkage, DefaultVisibility, false);
1810 const TagDecl *Tag = cast<TagType>(T)->getDecl();
1812 // C++ [basic.link]p8:
1813 // - it is a class or enumeration type that is named (or has a name
1814 // for linkage purposes (7.1.3)) and the name has linkage; or
1815 // - it is a specialization of a class template (14); or
1816 NamedDecl::LinkageInfo LV = Tag->getLinkageAndVisibility();
1817 bool IsLocalOrUnnamed =
1818 Tag->getDeclContext()->isFunctionOrMethod() ||
1819 (!Tag->getIdentifier() && !Tag->getTypedefNameForAnonDecl());
1820 return CachedProperties(LV.linkage(), LV.visibility(), IsLocalOrUnnamed);
1823 // C++ [basic.link]p8:
1824 // - it is a compound type (3.9.2) other than a class or enumeration,
1825 // compounded exclusively from types that have linkage; or
1827 return Cache::get(cast<ComplexType>(T)->getElementType());
1829 return Cache::get(cast<PointerType>(T)->getPointeeType());
1830 case Type::BlockPointer:
1831 return Cache::get(cast<BlockPointerType>(T)->getPointeeType());
1832 case Type::LValueReference:
1833 case Type::RValueReference:
1834 return Cache::get(cast<ReferenceType>(T)->getPointeeType());
1835 case Type::MemberPointer: {
1836 const MemberPointerType *MPT = cast<MemberPointerType>(T);
1837 return merge(Cache::get(MPT->getClass()),
1838 Cache::get(MPT->getPointeeType()));
1840 case Type::ConstantArray:
1841 case Type::IncompleteArray:
1842 case Type::VariableArray:
1843 return Cache::get(cast<ArrayType>(T)->getElementType());
1845 case Type::ExtVector:
1846 return Cache::get(cast<VectorType>(T)->getElementType());
1847 case Type::FunctionNoProto:
1848 return Cache::get(cast<FunctionType>(T)->getResultType());
1849 case Type::FunctionProto: {
1850 const FunctionProtoType *FPT = cast<FunctionProtoType>(T);
1851 CachedProperties result = Cache::get(FPT->getResultType());
1852 for (FunctionProtoType::arg_type_iterator ai = FPT->arg_type_begin(),
1853 ae = FPT->arg_type_end(); ai != ae; ++ai)
1854 result = merge(result, Cache::get(*ai));
1857 case Type::ObjCInterface: {
1858 NamedDecl::LinkageInfo LV =
1859 cast<ObjCInterfaceType>(T)->getDecl()->getLinkageAndVisibility();
1860 return CachedProperties(LV.linkage(), LV.visibility(), false);
1862 case Type::ObjCObject:
1863 return Cache::get(cast<ObjCObjectType>(T)->getBaseType());
1864 case Type::ObjCObjectPointer:
1865 return Cache::get(cast<ObjCObjectPointerType>(T)->getPointeeType());
1868 llvm_unreachable("unhandled type class");
1870 // C++ [basic.link]p8:
1871 // Names not covered by these rules have no linkage.
1872 return CachedProperties(NoLinkage, DefaultVisibility, false);
1875 /// \brief Determine the linkage of this type.
1876 Linkage Type::getLinkage() const {
1877 Cache::ensure(this);
1878 return TypeBits.getLinkage();
1881 /// \brief Determine the linkage of this type.
1882 Visibility Type::getVisibility() const {
1883 Cache::ensure(this);
1884 return TypeBits.getVisibility();
1887 bool Type::hasUnnamedOrLocalType() const {
1888 Cache::ensure(this);
1889 return TypeBits.hasLocalOrUnnamedType();
1892 std::pair<Linkage,Visibility> Type::getLinkageAndVisibility() const {
1893 Cache::ensure(this);
1894 return std::make_pair(TypeBits.getLinkage(), TypeBits.getVisibility());
1897 void Type::ClearLinkageCache() {
1898 TypeBits.CacheValidAndVisibility = 0;
1899 if (QualType(this, 0) != CanonicalType)
1900 CanonicalType->TypeBits.CacheValidAndVisibility = 0;
1903 bool Type::hasSizedVLAType() const {
1904 if (!isVariablyModifiedType()) return false;
1906 if (const PointerType *ptr = getAs<PointerType>())
1907 return ptr->getPointeeType()->hasSizedVLAType();
1908 if (const ReferenceType *ref = getAs<ReferenceType>())
1909 return ref->getPointeeType()->hasSizedVLAType();
1910 if (const ArrayType *arr = getAsArrayTypeUnsafe()) {
1911 if (isa<VariableArrayType>(arr) &&
1912 cast<VariableArrayType>(arr)->getSizeExpr())
1915 return arr->getElementType()->hasSizedVLAType();
1921 QualType::DestructionKind QualType::isDestructedTypeImpl(QualType type) {
1922 /// Currently, the only destruction kind we recognize is C++ objects
1923 /// with non-trivial destructors.
1924 const CXXRecordDecl *record =
1925 type->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
1926 if (record && !record->hasTrivialDestructor())
1927 return DK_cxx_destructor;