1 //===--- Type.h - C Language Family Type Representation ---------*- C++ -*-===//
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 defines the Type interface and subclasses.
12 //===----------------------------------------------------------------------===//
14 #ifndef LLVM_CLANG_AST_TYPE_H
15 #define LLVM_CLANG_AST_TYPE_H
17 #include "clang/AST/NestedNameSpecifier.h"
18 #include "clang/AST/TemplateName.h"
19 #include "clang/Basic/Diagnostic.h"
20 #include "clang/Basic/ExceptionSpecificationType.h"
21 #include "clang/Basic/IdentifierTable.h"
22 #include "clang/Basic/LLVM.h"
23 #include "clang/Basic/Linkage.h"
24 #include "clang/Basic/PartialDiagnostic.h"
25 #include "clang/Basic/Specifiers.h"
26 #include "clang/Basic/Visibility.h"
27 #include "llvm/ADT/APSInt.h"
28 #include "llvm/ADT/FoldingSet.h"
29 #include "llvm/ADT/Optional.h"
30 #include "llvm/ADT/PointerIntPair.h"
31 #include "llvm/ADT/PointerUnion.h"
32 #include "llvm/ADT/Twine.h"
33 #include "llvm/Support/ErrorHandling.h"
34 #include "llvm/Support/type_traits.h"
38 TypeAlignmentInBits = 4,
39 TypeAlignment = 1 << TypeAlignmentInBits
48 class PointerLikeTypeTraits;
50 class PointerLikeTypeTraits< ::clang::Type*> {
52 static inline void *getAsVoidPointer(::clang::Type *P) { return P; }
53 static inline ::clang::Type *getFromVoidPointer(void *P) {
54 return static_cast< ::clang::Type*>(P);
56 enum { NumLowBitsAvailable = clang::TypeAlignmentInBits };
59 class PointerLikeTypeTraits< ::clang::ExtQuals*> {
61 static inline void *getAsVoidPointer(::clang::ExtQuals *P) { return P; }
62 static inline ::clang::ExtQuals *getFromVoidPointer(void *P) {
63 return static_cast< ::clang::ExtQuals*>(P);
65 enum { NumLowBitsAvailable = clang::TypeAlignmentInBits };
69 struct isPodLike<clang::QualType> { static const bool value = true; };
74 class TypedefNameDecl;
76 class TemplateTypeParmDecl;
77 class NonTypeTemplateParmDecl;
78 class TemplateTemplateParmDecl;
85 class ObjCInterfaceDecl;
86 class ObjCProtocolDecl;
88 class UnresolvedUsingTypenameDecl;
92 class StmtIteratorBase;
93 class TemplateArgument;
94 class TemplateArgumentLoc;
95 class TemplateArgumentListInfo;
98 class ExtQualsTypeCommonBase;
99 struct PrintingPolicy;
101 template <typename> class CanQual;
102 typedef CanQual<Type> CanQualType;
104 // Provide forward declarations for all of the *Type classes
105 #define TYPE(Class, Base) class Class##Type;
106 #include "clang/AST/TypeNodes.def"
108 /// Qualifiers - The collection of all-type qualifiers we support.
109 /// Clang supports five independent qualifiers:
110 /// * C99: const, volatile, and restrict
111 /// * Embedded C (TR18037): address spaces
112 /// * Objective C: the GC attributes (none, weak, or strong)
115 enum TQ { // NOTE: These flags must be kept in sync with DeclSpec::TQ.
119 CVRMask = Const | Volatile | Restrict
129 /// There is no lifetime qualification on this type.
132 /// This object can be modified without requiring retains or
136 /// Assigning into this object requires the old value to be
137 /// released and the new value to be retained. The timing of the
138 /// release of the old value is inexact: it may be moved to
139 /// immediately after the last known point where the value is
143 /// Reading or writing from this object requires a barrier call.
146 /// Assigning into this object requires a lifetime extension.
151 /// The maximum supported address space number.
152 /// 24 bits should be enough for anyone.
153 MaxAddressSpace = 0xffffffu,
155 /// The width of the "fast" qualifier mask.
158 /// The fast qualifier mask.
159 FastMask = (1 << FastWidth) - 1
162 Qualifiers() : Mask(0) {}
164 /// \brief Returns the common set of qualifiers while removing them from
166 static Qualifiers removeCommonQualifiers(Qualifiers &L, Qualifiers &R) {
167 // If both are only CVR-qualified, bit operations are sufficient.
168 if (!(L.Mask & ~CVRMask) && !(R.Mask & ~CVRMask)) {
170 Q.Mask = L.Mask & R.Mask;
177 unsigned CommonCRV = L.getCVRQualifiers() & R.getCVRQualifiers();
178 Q.addCVRQualifiers(CommonCRV);
179 L.removeCVRQualifiers(CommonCRV);
180 R.removeCVRQualifiers(CommonCRV);
182 if (L.getObjCGCAttr() == R.getObjCGCAttr()) {
183 Q.setObjCGCAttr(L.getObjCGCAttr());
184 L.removeObjCGCAttr();
185 R.removeObjCGCAttr();
188 if (L.getObjCLifetime() == R.getObjCLifetime()) {
189 Q.setObjCLifetime(L.getObjCLifetime());
190 L.removeObjCLifetime();
191 R.removeObjCLifetime();
194 if (L.getAddressSpace() == R.getAddressSpace()) {
195 Q.setAddressSpace(L.getAddressSpace());
196 L.removeAddressSpace();
197 R.removeAddressSpace();
202 static Qualifiers fromFastMask(unsigned Mask) {
204 Qs.addFastQualifiers(Mask);
208 static Qualifiers fromCVRMask(unsigned CVR) {
210 Qs.addCVRQualifiers(CVR);
214 // Deserialize qualifiers from an opaque representation.
215 static Qualifiers fromOpaqueValue(unsigned opaque) {
221 // Serialize these qualifiers into an opaque representation.
222 unsigned getAsOpaqueValue() const {
226 bool hasConst() const { return Mask & Const; }
227 void setConst(bool flag) {
228 Mask = (Mask & ~Const) | (flag ? Const : 0);
230 void removeConst() { Mask &= ~Const; }
231 void addConst() { Mask |= Const; }
233 bool hasVolatile() const { return Mask & Volatile; }
234 void setVolatile(bool flag) {
235 Mask = (Mask & ~Volatile) | (flag ? Volatile : 0);
237 void removeVolatile() { Mask &= ~Volatile; }
238 void addVolatile() { Mask |= Volatile; }
240 bool hasRestrict() const { return Mask & Restrict; }
241 void setRestrict(bool flag) {
242 Mask = (Mask & ~Restrict) | (flag ? Restrict : 0);
244 void removeRestrict() { Mask &= ~Restrict; }
245 void addRestrict() { Mask |= Restrict; }
247 bool hasCVRQualifiers() const { return getCVRQualifiers(); }
248 unsigned getCVRQualifiers() const { return Mask & CVRMask; }
249 void setCVRQualifiers(unsigned mask) {
250 assert(!(mask & ~CVRMask) && "bitmask contains non-CVR bits");
251 Mask = (Mask & ~CVRMask) | mask;
253 void removeCVRQualifiers(unsigned mask) {
254 assert(!(mask & ~CVRMask) && "bitmask contains non-CVR bits");
257 void removeCVRQualifiers() {
258 removeCVRQualifiers(CVRMask);
260 void addCVRQualifiers(unsigned mask) {
261 assert(!(mask & ~CVRMask) && "bitmask contains non-CVR bits");
265 bool hasObjCGCAttr() const { return Mask & GCAttrMask; }
266 GC getObjCGCAttr() const { return GC((Mask & GCAttrMask) >> GCAttrShift); }
267 void setObjCGCAttr(GC type) {
268 Mask = (Mask & ~GCAttrMask) | (type << GCAttrShift);
270 void removeObjCGCAttr() { setObjCGCAttr(GCNone); }
271 void addObjCGCAttr(GC type) {
275 Qualifiers withoutObjCGCAttr() const {
276 Qualifiers qs = *this;
277 qs.removeObjCGCAttr();
280 Qualifiers withoutObjCLifetime() const {
281 Qualifiers qs = *this;
282 qs.removeObjCLifetime();
286 bool hasObjCLifetime() const { return Mask & LifetimeMask; }
287 ObjCLifetime getObjCLifetime() const {
288 return ObjCLifetime((Mask & LifetimeMask) >> LifetimeShift);
290 void setObjCLifetime(ObjCLifetime type) {
291 Mask = (Mask & ~LifetimeMask) | (type << LifetimeShift);
293 void removeObjCLifetime() { setObjCLifetime(OCL_None); }
294 void addObjCLifetime(ObjCLifetime type) {
296 assert(!hasObjCLifetime());
297 Mask |= (type << LifetimeShift);
300 /// True if the lifetime is neither None or ExplicitNone.
301 bool hasNonTrivialObjCLifetime() const {
302 ObjCLifetime lifetime = getObjCLifetime();
303 return (lifetime > OCL_ExplicitNone);
306 /// True if the lifetime is either strong or weak.
307 bool hasStrongOrWeakObjCLifetime() const {
308 ObjCLifetime lifetime = getObjCLifetime();
309 return (lifetime == OCL_Strong || lifetime == OCL_Weak);
312 bool hasAddressSpace() const { return Mask & AddressSpaceMask; }
313 unsigned getAddressSpace() const { return Mask >> AddressSpaceShift; }
314 void setAddressSpace(unsigned space) {
315 assert(space <= MaxAddressSpace);
316 Mask = (Mask & ~AddressSpaceMask)
317 | (((uint32_t) space) << AddressSpaceShift);
319 void removeAddressSpace() { setAddressSpace(0); }
320 void addAddressSpace(unsigned space) {
322 setAddressSpace(space);
325 // Fast qualifiers are those that can be allocated directly
326 // on a QualType object.
327 bool hasFastQualifiers() const { return getFastQualifiers(); }
328 unsigned getFastQualifiers() const { return Mask & FastMask; }
329 void setFastQualifiers(unsigned mask) {
330 assert(!(mask & ~FastMask) && "bitmask contains non-fast qualifier bits");
331 Mask = (Mask & ~FastMask) | mask;
333 void removeFastQualifiers(unsigned mask) {
334 assert(!(mask & ~FastMask) && "bitmask contains non-fast qualifier bits");
337 void removeFastQualifiers() {
338 removeFastQualifiers(FastMask);
340 void addFastQualifiers(unsigned mask) {
341 assert(!(mask & ~FastMask) && "bitmask contains non-fast qualifier bits");
345 /// hasNonFastQualifiers - Return true if the set contains any
346 /// qualifiers which require an ExtQuals node to be allocated.
347 bool hasNonFastQualifiers() const { return Mask & ~FastMask; }
348 Qualifiers getNonFastQualifiers() const {
349 Qualifiers Quals = *this;
350 Quals.setFastQualifiers(0);
354 /// hasQualifiers - Return true if the set contains any qualifiers.
355 bool hasQualifiers() const { return Mask; }
356 bool empty() const { return !Mask; }
358 /// \brief Add the qualifiers from the given set to this set.
359 void addQualifiers(Qualifiers Q) {
360 // If the other set doesn't have any non-boolean qualifiers, just
362 if (!(Q.Mask & ~CVRMask))
365 Mask |= (Q.Mask & CVRMask);
366 if (Q.hasAddressSpace())
367 addAddressSpace(Q.getAddressSpace());
368 if (Q.hasObjCGCAttr())
369 addObjCGCAttr(Q.getObjCGCAttr());
370 if (Q.hasObjCLifetime())
371 addObjCLifetime(Q.getObjCLifetime());
375 /// \brief Remove the qualifiers from the given set from this set.
376 void removeQualifiers(Qualifiers Q) {
377 // If the other set doesn't have any non-boolean qualifiers, just
378 // bit-and the inverse in.
379 if (!(Q.Mask & ~CVRMask))
382 Mask &= ~(Q.Mask & CVRMask);
383 if (getObjCGCAttr() == Q.getObjCGCAttr())
385 if (getObjCLifetime() == Q.getObjCLifetime())
386 removeObjCLifetime();
387 if (getAddressSpace() == Q.getAddressSpace())
388 removeAddressSpace();
392 /// \brief Add the qualifiers from the given set to this set, given that
393 /// they don't conflict.
394 void addConsistentQualifiers(Qualifiers qs) {
395 assert(getAddressSpace() == qs.getAddressSpace() ||
396 !hasAddressSpace() || !qs.hasAddressSpace());
397 assert(getObjCGCAttr() == qs.getObjCGCAttr() ||
398 !hasObjCGCAttr() || !qs.hasObjCGCAttr());
399 assert(getObjCLifetime() == qs.getObjCLifetime() ||
400 !hasObjCLifetime() || !qs.hasObjCLifetime());
404 /// \brief Determines if these qualifiers compatibly include another set.
405 /// Generally this answers the question of whether an object with the other
406 /// qualifiers can be safely used as an object with these qualifiers.
407 bool compatiblyIncludes(Qualifiers other) const {
409 // Address spaces must match exactly.
410 getAddressSpace() == other.getAddressSpace() &&
411 // ObjC GC qualifiers can match, be added, or be removed, but can't be
413 (getObjCGCAttr() == other.getObjCGCAttr() ||
414 !hasObjCGCAttr() || !other.hasObjCGCAttr()) &&
415 // ObjC lifetime qualifiers must match exactly.
416 getObjCLifetime() == other.getObjCLifetime() &&
417 // CVR qualifiers may subset.
418 (((Mask & CVRMask) | (other.Mask & CVRMask)) == (Mask & CVRMask));
421 /// \brief Determines if these qualifiers compatibly include another set of
422 /// qualifiers from the narrow perspective of Objective-C ARC lifetime.
424 /// One set of Objective-C lifetime qualifiers compatibly includes the other
425 /// if the lifetime qualifiers match, or if both are non-__weak and the
426 /// including set also contains the 'const' qualifier.
427 bool compatiblyIncludesObjCLifetime(Qualifiers other) const {
428 if (getObjCLifetime() == other.getObjCLifetime())
431 if (getObjCLifetime() == OCL_Weak || other.getObjCLifetime() == OCL_Weak)
437 /// \brief Determine whether this set of qualifiers is a strict superset of
438 /// another set of qualifiers, not considering qualifier compatibility.
439 bool isStrictSupersetOf(Qualifiers Other) const;
441 bool operator==(Qualifiers Other) const { return Mask == Other.Mask; }
442 bool operator!=(Qualifiers Other) const { return Mask != Other.Mask; }
444 operator bool() const { return hasQualifiers(); }
446 Qualifiers &operator+=(Qualifiers R) {
451 // Union two qualifier sets. If an enumerated qualifier appears
452 // in both sets, use the one from the right.
453 friend Qualifiers operator+(Qualifiers L, Qualifiers R) {
458 Qualifiers &operator-=(Qualifiers R) {
463 /// \brief Compute the difference between two qualifier sets.
464 friend Qualifiers operator-(Qualifiers L, Qualifiers R) {
469 std::string getAsString() const;
470 std::string getAsString(const PrintingPolicy &Policy) const;
472 bool isEmptyWhenPrinted(const PrintingPolicy &Policy) const;
473 void print(raw_ostream &OS, const PrintingPolicy &Policy,
474 bool appendSpaceIfNonEmpty = false) const;
476 void Profile(llvm::FoldingSetNodeID &ID) const {
482 // bits: |0 1 2|3 .. 4|5 .. 7|8 ... 31|
483 // |C R V|GCAttr|Lifetime|AddressSpace|
486 static const uint32_t GCAttrMask = 0x18;
487 static const uint32_t GCAttrShift = 3;
488 static const uint32_t LifetimeMask = 0xE0;
489 static const uint32_t LifetimeShift = 5;
490 static const uint32_t AddressSpaceMask = ~(CVRMask|GCAttrMask|LifetimeMask);
491 static const uint32_t AddressSpaceShift = 8;
494 /// A std::pair-like structure for storing a qualified type split
495 /// into its local qualifiers and its locally-unqualified type.
496 struct SplitQualType {
497 /// The locally-unqualified type.
500 /// The local qualifiers.
503 SplitQualType() : Ty(0), Quals() {}
504 SplitQualType(const Type *ty, Qualifiers qs) : Ty(ty), Quals(qs) {}
506 SplitQualType getSingleStepDesugaredType() const; // end of this file
508 // Make llvm::tie work.
509 operator std::pair<const Type *,Qualifiers>() const {
510 return std::pair<const Type *,Qualifiers>(Ty, Quals);
513 friend bool operator==(SplitQualType a, SplitQualType b) {
514 return a.Ty == b.Ty && a.Quals == b.Quals;
516 friend bool operator!=(SplitQualType a, SplitQualType b) {
517 return a.Ty != b.Ty || a.Quals != b.Quals;
521 /// QualType - For efficiency, we don't store CV-qualified types as nodes on
522 /// their own: instead each reference to a type stores the qualifiers. This
523 /// greatly reduces the number of nodes we need to allocate for types (for
524 /// example we only need one for 'int', 'const int', 'volatile int',
525 /// 'const volatile int', etc).
527 /// As an added efficiency bonus, instead of making this a pair, we
528 /// just store the two bits we care about in the low bits of the
529 /// pointer. To handle the packing/unpacking, we make QualType be a
530 /// simple wrapper class that acts like a smart pointer. A third bit
531 /// indicates whether there are extended qualifiers present, in which
532 /// case the pointer points to a special structure.
534 // Thankfully, these are efficiently composable.
535 llvm::PointerIntPair<llvm::PointerUnion<const Type*,const ExtQuals*>,
536 Qualifiers::FastWidth> Value;
538 const ExtQuals *getExtQualsUnsafe() const {
539 return Value.getPointer().get<const ExtQuals*>();
542 const Type *getTypePtrUnsafe() const {
543 return Value.getPointer().get<const Type*>();
546 const ExtQualsTypeCommonBase *getCommonPtr() const {
547 assert(!isNull() && "Cannot retrieve a NULL type pointer");
548 uintptr_t CommonPtrVal
549 = reinterpret_cast<uintptr_t>(Value.getOpaqueValue());
550 CommonPtrVal &= ~(uintptr_t)((1 << TypeAlignmentInBits) - 1);
551 return reinterpret_cast<ExtQualsTypeCommonBase*>(CommonPtrVal);
554 friend class QualifierCollector;
558 QualType(const Type *Ptr, unsigned Quals)
559 : Value(Ptr, Quals) {}
560 QualType(const ExtQuals *Ptr, unsigned Quals)
561 : Value(Ptr, Quals) {}
563 unsigned getLocalFastQualifiers() const { return Value.getInt(); }
564 void setLocalFastQualifiers(unsigned Quals) { Value.setInt(Quals); }
566 /// Retrieves a pointer to the underlying (unqualified) type.
568 /// This function requires that the type not be NULL. If the type might be
569 /// NULL, use the (slightly less efficient) \c getTypePtrOrNull().
570 const Type *getTypePtr() const;
572 const Type *getTypePtrOrNull() const;
574 /// Retrieves a pointer to the name of the base type.
575 const IdentifierInfo *getBaseTypeIdentifier() const;
577 /// Divides a QualType into its unqualified type and a set of local
579 SplitQualType split() const;
581 void *getAsOpaquePtr() const { return Value.getOpaqueValue(); }
582 static QualType getFromOpaquePtr(const void *Ptr) {
584 T.Value.setFromOpaqueValue(const_cast<void*>(Ptr));
588 const Type &operator*() const {
589 return *getTypePtr();
592 const Type *operator->() const {
596 bool isCanonical() const;
597 bool isCanonicalAsParam() const;
599 /// isNull - Return true if this QualType doesn't point to a type yet.
600 bool isNull() const {
601 return Value.getPointer().isNull();
604 /// \brief Determine whether this particular QualType instance has the
605 /// "const" qualifier set, without looking through typedefs that may have
606 /// added "const" at a different level.
607 bool isLocalConstQualified() const {
608 return (getLocalFastQualifiers() & Qualifiers::Const);
611 /// \brief Determine whether this type is const-qualified.
612 bool isConstQualified() const;
614 /// \brief Determine whether this particular QualType instance has the
615 /// "restrict" qualifier set, without looking through typedefs that may have
616 /// added "restrict" at a different level.
617 bool isLocalRestrictQualified() const {
618 return (getLocalFastQualifiers() & Qualifiers::Restrict);
621 /// \brief Determine whether this type is restrict-qualified.
622 bool isRestrictQualified() const;
624 /// \brief Determine whether this particular QualType instance has the
625 /// "volatile" qualifier set, without looking through typedefs that may have
626 /// added "volatile" at a different level.
627 bool isLocalVolatileQualified() const {
628 return (getLocalFastQualifiers() & Qualifiers::Volatile);
631 /// \brief Determine whether this type is volatile-qualified.
632 bool isVolatileQualified() const;
634 /// \brief Determine whether this particular QualType instance has any
635 /// qualifiers, without looking through any typedefs that might add
636 /// qualifiers at a different level.
637 bool hasLocalQualifiers() const {
638 return getLocalFastQualifiers() || hasLocalNonFastQualifiers();
641 /// \brief Determine whether this type has any qualifiers.
642 bool hasQualifiers() const;
644 /// \brief Determine whether this particular QualType instance has any
645 /// "non-fast" qualifiers, e.g., those that are stored in an ExtQualType
647 bool hasLocalNonFastQualifiers() const {
648 return Value.getPointer().is<const ExtQuals*>();
651 /// \brief Retrieve the set of qualifiers local to this particular QualType
652 /// instance, not including any qualifiers acquired through typedefs or
654 Qualifiers getLocalQualifiers() const;
656 /// \brief Retrieve the set of qualifiers applied to this type.
657 Qualifiers getQualifiers() const;
659 /// \brief Retrieve the set of CVR (const-volatile-restrict) qualifiers
660 /// local to this particular QualType instance, not including any qualifiers
661 /// acquired through typedefs or other sugar.
662 unsigned getLocalCVRQualifiers() const {
663 return getLocalFastQualifiers();
666 /// \brief Retrieve the set of CVR (const-volatile-restrict) qualifiers
667 /// applied to this type.
668 unsigned getCVRQualifiers() const;
670 bool isConstant(ASTContext& Ctx) const {
671 return QualType::isConstant(*this, Ctx);
674 /// \brief Determine whether this is a Plain Old Data (POD) type (C++ 3.9p10).
675 bool isPODType(ASTContext &Context) const;
677 /// isCXX98PODType() - Return true if this is a POD type according to the
678 /// rules of the C++98 standard, regardless of the current compilation's
680 bool isCXX98PODType(ASTContext &Context) const;
682 /// isCXX11PODType() - Return true if this is a POD type according to the
683 /// more relaxed rules of the C++11 standard, regardless of the current
684 /// compilation's language.
685 /// (C++0x [basic.types]p9)
686 bool isCXX11PODType(ASTContext &Context) const;
688 /// isTrivialType - Return true if this is a trivial type
689 /// (C++0x [basic.types]p9)
690 bool isTrivialType(ASTContext &Context) const;
692 /// isTriviallyCopyableType - Return true if this is a trivially
693 /// copyable type (C++0x [basic.types]p9)
694 bool isTriviallyCopyableType(ASTContext &Context) const;
696 // Don't promise in the API that anything besides 'const' can be
699 /// addConst - add the specified type qualifier to this QualType.
701 addFastQualifiers(Qualifiers::Const);
703 QualType withConst() const {
704 return withFastQualifiers(Qualifiers::Const);
707 /// addVolatile - add the specified type qualifier to this QualType.
709 addFastQualifiers(Qualifiers::Volatile);
711 QualType withVolatile() const {
712 return withFastQualifiers(Qualifiers::Volatile);
715 /// Add the restrict qualifier to this QualType.
717 addFastQualifiers(Qualifiers::Restrict);
719 QualType withRestrict() const {
720 return withFastQualifiers(Qualifiers::Restrict);
723 QualType withCVRQualifiers(unsigned CVR) const {
724 return withFastQualifiers(CVR);
727 void addFastQualifiers(unsigned TQs) {
728 assert(!(TQs & ~Qualifiers::FastMask)
729 && "non-fast qualifier bits set in mask!");
730 Value.setInt(Value.getInt() | TQs);
733 void removeLocalConst();
734 void removeLocalVolatile();
735 void removeLocalRestrict();
736 void removeLocalCVRQualifiers(unsigned Mask);
738 void removeLocalFastQualifiers() { Value.setInt(0); }
739 void removeLocalFastQualifiers(unsigned Mask) {
740 assert(!(Mask & ~Qualifiers::FastMask) && "mask has non-fast qualifiers");
741 Value.setInt(Value.getInt() & ~Mask);
744 // Creates a type with the given qualifiers in addition to any
745 // qualifiers already on this type.
746 QualType withFastQualifiers(unsigned TQs) const {
748 T.addFastQualifiers(TQs);
752 // Creates a type with exactly the given fast qualifiers, removing
753 // any existing fast qualifiers.
754 QualType withExactLocalFastQualifiers(unsigned TQs) const {
755 return withoutLocalFastQualifiers().withFastQualifiers(TQs);
758 // Removes fast qualifiers, but leaves any extended qualifiers in place.
759 QualType withoutLocalFastQualifiers() const {
761 T.removeLocalFastQualifiers();
765 QualType getCanonicalType() const;
767 /// \brief Return this type with all of the instance-specific qualifiers
768 /// removed, but without removing any qualifiers that may have been applied
769 /// through typedefs.
770 QualType getLocalUnqualifiedType() const { return QualType(getTypePtr(), 0); }
772 /// \brief Retrieve the unqualified variant of the given type,
773 /// removing as little sugar as possible.
775 /// This routine looks through various kinds of sugar to find the
776 /// least-desugared type that is unqualified. For example, given:
779 /// typedef int Integer;
780 /// typedef const Integer CInteger;
781 /// typedef CInteger DifferenceType;
784 /// Executing \c getUnqualifiedType() on the type \c DifferenceType will
785 /// desugar until we hit the type \c Integer, which has no qualifiers on it.
787 /// The resulting type might still be qualified if it's sugar for an array
788 /// type. To strip qualifiers even from within a sugared array type, use
789 /// ASTContext::getUnqualifiedArrayType.
790 inline QualType getUnqualifiedType() const;
792 /// getSplitUnqualifiedType - Retrieve the unqualified variant of the
793 /// given type, removing as little sugar as possible.
795 /// Like getUnqualifiedType(), but also returns the set of
796 /// qualifiers that were built up.
798 /// The resulting type might still be qualified if it's sugar for an array
799 /// type. To strip qualifiers even from within a sugared array type, use
800 /// ASTContext::getUnqualifiedArrayType.
801 inline SplitQualType getSplitUnqualifiedType() const;
803 /// \brief Determine whether this type is more qualified than the other
804 /// given type, requiring exact equality for non-CVR qualifiers.
805 bool isMoreQualifiedThan(QualType Other) const;
807 /// \brief Determine whether this type is at least as qualified as the other
808 /// given type, requiring exact equality for non-CVR qualifiers.
809 bool isAtLeastAsQualifiedAs(QualType Other) const;
811 QualType getNonReferenceType() const;
813 /// \brief Determine the type of a (typically non-lvalue) expression with the
814 /// specified result type.
816 /// This routine should be used for expressions for which the return type is
817 /// explicitly specified (e.g., in a cast or call) and isn't necessarily
818 /// an lvalue. It removes a top-level reference (since there are no
819 /// expressions of reference type) and deletes top-level cvr-qualifiers
820 /// from non-class types (in C++) or all types (in C).
821 QualType getNonLValueExprType(ASTContext &Context) const;
823 /// getDesugaredType - Return the specified type with any "sugar" removed from
824 /// the type. This takes off typedefs, typeof's etc. If the outer level of
825 /// the type is already concrete, it returns it unmodified. This is similar
826 /// to getting the canonical type, but it doesn't remove *all* typedefs. For
827 /// example, it returns "T*" as "T*", (not as "int*"), because the pointer is
830 /// Qualifiers are left in place.
831 QualType getDesugaredType(const ASTContext &Context) const {
832 return getDesugaredType(*this, Context);
835 SplitQualType getSplitDesugaredType() const {
836 return getSplitDesugaredType(*this);
839 /// \brief Return the specified type with one level of "sugar" removed from
842 /// This routine takes off the first typedef, typeof, etc. If the outer level
843 /// of the type is already concrete, it returns it unmodified.
844 QualType getSingleStepDesugaredType(const ASTContext &Context) const {
845 return getSingleStepDesugaredTypeImpl(*this, Context);
848 /// IgnoreParens - Returns the specified type after dropping any
849 /// outer-level parentheses.
850 QualType IgnoreParens() const {
851 if (isa<ParenType>(*this))
852 return QualType::IgnoreParens(*this);
856 /// operator==/!= - Indicate whether the specified types and qualifiers are
858 friend bool operator==(const QualType &LHS, const QualType &RHS) {
859 return LHS.Value == RHS.Value;
861 friend bool operator!=(const QualType &LHS, const QualType &RHS) {
862 return LHS.Value != RHS.Value;
864 std::string getAsString() const {
865 return getAsString(split());
867 static std::string getAsString(SplitQualType split) {
868 return getAsString(split.Ty, split.Quals);
870 static std::string getAsString(const Type *ty, Qualifiers qs);
872 std::string getAsString(const PrintingPolicy &Policy) const;
874 void print(raw_ostream &OS, const PrintingPolicy &Policy,
875 const Twine &PlaceHolder = Twine()) const {
876 print(split(), OS, Policy, PlaceHolder);
878 static void print(SplitQualType split, raw_ostream &OS,
879 const PrintingPolicy &policy, const Twine &PlaceHolder) {
880 return print(split.Ty, split.Quals, OS, policy, PlaceHolder);
882 static void print(const Type *ty, Qualifiers qs,
883 raw_ostream &OS, const PrintingPolicy &policy,
884 const Twine &PlaceHolder);
886 void getAsStringInternal(std::string &Str,
887 const PrintingPolicy &Policy) const {
888 return getAsStringInternal(split(), Str, Policy);
890 static void getAsStringInternal(SplitQualType split, std::string &out,
891 const PrintingPolicy &policy) {
892 return getAsStringInternal(split.Ty, split.Quals, out, policy);
894 static void getAsStringInternal(const Type *ty, Qualifiers qs,
896 const PrintingPolicy &policy);
898 class StreamedQualTypeHelper {
900 const PrintingPolicy &Policy;
901 const Twine &PlaceHolder;
903 StreamedQualTypeHelper(const QualType &T, const PrintingPolicy &Policy,
904 const Twine &PlaceHolder)
905 : T(T), Policy(Policy), PlaceHolder(PlaceHolder) { }
907 friend raw_ostream &operator<<(raw_ostream &OS,
908 const StreamedQualTypeHelper &SQT) {
909 SQT.T.print(OS, SQT.Policy, SQT.PlaceHolder);
914 StreamedQualTypeHelper stream(const PrintingPolicy &Policy,
915 const Twine &PlaceHolder = Twine()) const {
916 return StreamedQualTypeHelper(*this, Policy, PlaceHolder);
919 void dump(const char *s) const;
922 void Profile(llvm::FoldingSetNodeID &ID) const {
923 ID.AddPointer(getAsOpaquePtr());
926 /// getAddressSpace - Return the address space of this type.
927 inline unsigned getAddressSpace() const;
929 /// getObjCGCAttr - Returns gc attribute of this type.
930 inline Qualifiers::GC getObjCGCAttr() const;
932 /// isObjCGCWeak true when Type is objc's weak.
933 bool isObjCGCWeak() const {
934 return getObjCGCAttr() == Qualifiers::Weak;
937 /// isObjCGCStrong true when Type is objc's strong.
938 bool isObjCGCStrong() const {
939 return getObjCGCAttr() == Qualifiers::Strong;
942 /// getObjCLifetime - Returns lifetime attribute of this type.
943 Qualifiers::ObjCLifetime getObjCLifetime() const {
944 return getQualifiers().getObjCLifetime();
947 bool hasNonTrivialObjCLifetime() const {
948 return getQualifiers().hasNonTrivialObjCLifetime();
951 bool hasStrongOrWeakObjCLifetime() const {
952 return getQualifiers().hasStrongOrWeakObjCLifetime();
955 enum DestructionKind {
958 DK_objc_strong_lifetime,
959 DK_objc_weak_lifetime
962 /// isDestructedType - nonzero if objects of this type require
963 /// non-trivial work to clean up after. Non-zero because it's
964 /// conceivable that qualifiers (objc_gc(weak)?) could make
965 /// something require destruction.
966 DestructionKind isDestructedType() const {
967 return isDestructedTypeImpl(*this);
970 /// \brief Determine whether expressions of the given type are forbidden
971 /// from being lvalues in C.
973 /// The expression types that are forbidden to be lvalues are:
974 /// - 'void', but not qualified void
977 /// The exact rule here is C99 6.3.2.1:
978 /// An lvalue is an expression with an object type or an incomplete
979 /// type other than void.
980 bool isCForbiddenLValueType() const;
983 // These methods are implemented in a separate translation unit;
984 // "static"-ize them to avoid creating temporary QualTypes in the
986 static bool isConstant(QualType T, ASTContext& Ctx);
987 static QualType getDesugaredType(QualType T, const ASTContext &Context);
988 static SplitQualType getSplitDesugaredType(QualType T);
989 static SplitQualType getSplitUnqualifiedTypeImpl(QualType type);
990 static QualType getSingleStepDesugaredTypeImpl(QualType type,
991 const ASTContext &C);
992 static QualType IgnoreParens(QualType T);
993 static DestructionKind isDestructedTypeImpl(QualType type);
999 /// Implement simplify_type for QualType, so that we can dyn_cast from QualType
1000 /// to a specific Type class.
1001 template<> struct simplify_type< ::clang::QualType> {
1002 typedef const ::clang::Type *SimpleType;
1003 static SimpleType getSimplifiedValue(::clang::QualType Val) {
1004 return Val.getTypePtr();
1008 // Teach SmallPtrSet that QualType is "basically a pointer".
1010 class PointerLikeTypeTraits<clang::QualType> {
1012 static inline void *getAsVoidPointer(clang::QualType P) {
1013 return P.getAsOpaquePtr();
1015 static inline clang::QualType getFromVoidPointer(void *P) {
1016 return clang::QualType::getFromOpaquePtr(P);
1018 // Various qualifiers go in low bits.
1019 enum { NumLowBitsAvailable = 0 };
1022 } // end namespace llvm
1026 /// \brief Base class that is common to both the \c ExtQuals and \c Type
1027 /// classes, which allows \c QualType to access the common fields between the
1030 class ExtQualsTypeCommonBase {
1031 ExtQualsTypeCommonBase(const Type *baseType, QualType canon)
1032 : BaseType(baseType), CanonicalType(canon) {}
1034 /// \brief The "base" type of an extended qualifiers type (\c ExtQuals) or
1035 /// a self-referential pointer (for \c Type).
1037 /// This pointer allows an efficient mapping from a QualType to its
1038 /// underlying type pointer.
1039 const Type *const BaseType;
1041 /// \brief The canonical type of this type. A QualType.
1042 QualType CanonicalType;
1044 friend class QualType;
1046 friend class ExtQuals;
1049 /// ExtQuals - We can encode up to four bits in the low bits of a
1050 /// type pointer, but there are many more type qualifiers that we want
1051 /// to be able to apply to an arbitrary type. Therefore we have this
1052 /// struct, intended to be heap-allocated and used by QualType to
1053 /// store qualifiers.
1055 /// The current design tags the 'const', 'restrict', and 'volatile' qualifiers
1056 /// in three low bits on the QualType pointer; a fourth bit records whether
1057 /// the pointer is an ExtQuals node. The extended qualifiers (address spaces,
1058 /// Objective-C GC attributes) are much more rare.
1059 class ExtQuals : public ExtQualsTypeCommonBase, public llvm::FoldingSetNode {
1060 // NOTE: changing the fast qualifiers should be straightforward as
1061 // long as you don't make 'const' non-fast.
1063 // a) Modify the bitmasks (Qualifiers::TQ and DeclSpec::TQ).
1064 // Fast qualifiers must occupy the low-order bits.
1065 // b) Update Qualifiers::FastWidth and FastMask.
1067 // a) Update is{Volatile,Restrict}Qualified(), defined inline.
1068 // b) Update remove{Volatile,Restrict}, defined near the end of
1071 // a) Update get{Volatile,Restrict}Type.
1073 /// Quals - the immutable set of qualifiers applied by this
1074 /// node; always contains extended qualifiers.
1077 ExtQuals *this_() { return this; }
1080 ExtQuals(const Type *baseType, QualType canon, Qualifiers quals)
1081 : ExtQualsTypeCommonBase(baseType,
1082 canon.isNull() ? QualType(this_(), 0) : canon),
1085 assert(Quals.hasNonFastQualifiers()
1086 && "ExtQuals created with no fast qualifiers");
1087 assert(!Quals.hasFastQualifiers()
1088 && "ExtQuals created with fast qualifiers");
1091 Qualifiers getQualifiers() const { return Quals; }
1093 bool hasObjCGCAttr() const { return Quals.hasObjCGCAttr(); }
1094 Qualifiers::GC getObjCGCAttr() const { return Quals.getObjCGCAttr(); }
1096 bool hasObjCLifetime() const { return Quals.hasObjCLifetime(); }
1097 Qualifiers::ObjCLifetime getObjCLifetime() const {
1098 return Quals.getObjCLifetime();
1101 bool hasAddressSpace() const { return Quals.hasAddressSpace(); }
1102 unsigned getAddressSpace() const { return Quals.getAddressSpace(); }
1104 const Type *getBaseType() const { return BaseType; }
1107 void Profile(llvm::FoldingSetNodeID &ID) const {
1108 Profile(ID, getBaseType(), Quals);
1110 static void Profile(llvm::FoldingSetNodeID &ID,
1111 const Type *BaseType,
1113 assert(!Quals.hasFastQualifiers() && "fast qualifiers in ExtQuals hash!");
1114 ID.AddPointer(BaseType);
1119 /// \brief The kind of C++0x ref-qualifier associated with a function type,
1120 /// which determines whether a member function's "this" object can be an
1121 /// lvalue, rvalue, or neither.
1122 enum RefQualifierKind {
1123 /// \brief No ref-qualifier was provided.
1125 /// \brief An lvalue ref-qualifier was provided (\c &).
1127 /// \brief An rvalue ref-qualifier was provided (\c &&).
1131 /// Type - This is the base class of the type hierarchy. A central concept
1132 /// with types is that each type always has a canonical type. A canonical type
1133 /// is the type with any typedef names stripped out of it or the types it
1134 /// references. For example, consider:
1136 /// typedef int foo;
1137 /// typedef foo* bar;
1138 /// 'int *' 'foo *' 'bar'
1140 /// There will be a Type object created for 'int'. Since int is canonical, its
1141 /// canonicaltype pointer points to itself. There is also a Type for 'foo' (a
1142 /// TypedefType). Its CanonicalType pointer points to the 'int' Type. Next
1143 /// there is a PointerType that represents 'int*', which, like 'int', is
1144 /// canonical. Finally, there is a PointerType type for 'foo*' whose canonical
1145 /// type is 'int*', and there is a TypedefType for 'bar', whose canonical type
1148 /// Non-canonical types are useful for emitting diagnostics, without losing
1149 /// information about typedefs being used. Canonical types are useful for type
1150 /// comparisons (they allow by-pointer equality tests) and useful for reasoning
1151 /// about whether something has a particular form (e.g. is a function type),
1152 /// because they implicitly, recursively, strip all typedefs out of a type.
1154 /// Types, once created, are immutable.
1156 class Type : public ExtQualsTypeCommonBase {
1159 #define TYPE(Class, Base) Class,
1160 #define LAST_TYPE(Class) TypeLast = Class,
1161 #define ABSTRACT_TYPE(Class, Base)
1162 #include "clang/AST/TypeNodes.def"
1163 TagFirst = Record, TagLast = Enum
1167 Type(const Type &) LLVM_DELETED_FUNCTION;
1168 void operator=(const Type &) LLVM_DELETED_FUNCTION;
1170 /// Bitfields required by the Type class.
1171 class TypeBitfields {
1173 template <class T> friend class TypePropertyCache;
1175 /// TypeClass bitfield - Enum that specifies what subclass this belongs to.
1178 /// Dependent - Whether this type is a dependent type (C++ [temp.dep.type]).
1179 unsigned Dependent : 1;
1181 /// \brief Whether this type somehow involves a template parameter, even
1182 /// if the resolution of the type does not depend on a template parameter.
1183 unsigned InstantiationDependent : 1;
1185 /// \brief Whether this type is a variably-modified type (C99 6.7.5).
1186 unsigned VariablyModified : 1;
1188 /// \brief Whether this type contains an unexpanded parameter pack
1189 /// (for C++0x variadic templates).
1190 unsigned ContainsUnexpandedParameterPack : 1;
1192 /// \brief True if the cache (i.e. the bitfields here starting with
1193 /// 'Cache') is valid.
1194 mutable unsigned CacheValid : 1;
1196 /// \brief Linkage of this type.
1197 mutable unsigned CachedLinkage : 2;
1199 /// \brief Whether this type involves and local or unnamed types.
1200 mutable unsigned CachedLocalOrUnnamed : 1;
1202 /// \brief FromAST - Whether this type comes from an AST file.
1203 mutable unsigned FromAST : 1;
1205 bool isCacheValid() const {
1208 Linkage getLinkage() const {
1209 assert(isCacheValid() && "getting linkage from invalid cache");
1210 return static_cast<Linkage>(CachedLinkage);
1212 bool hasLocalOrUnnamedType() const {
1213 assert(isCacheValid() && "getting linkage from invalid cache");
1214 return CachedLocalOrUnnamed;
1217 enum { NumTypeBits = 19 };
1220 // These classes allow subclasses to somewhat cleanly pack bitfields
1223 class ArrayTypeBitfields {
1224 friend class ArrayType;
1226 unsigned : NumTypeBits;
1228 /// IndexTypeQuals - CVR qualifiers from declarations like
1229 /// 'int X[static restrict 4]'. For function parameters only.
1230 unsigned IndexTypeQuals : 3;
1232 /// SizeModifier - storage class qualifiers from declarations like
1233 /// 'int X[static restrict 4]'. For function parameters only.
1234 /// Actually an ArrayType::ArraySizeModifier.
1235 unsigned SizeModifier : 3;
1238 class BuiltinTypeBitfields {
1239 friend class BuiltinType;
1241 unsigned : NumTypeBits;
1243 /// The kind (BuiltinType::Kind) of builtin type this is.
1247 class FunctionTypeBitfields {
1248 friend class FunctionType;
1250 unsigned : NumTypeBits;
1252 /// Extra information which affects how the function is called, like
1253 /// regparm and the calling convention.
1254 unsigned ExtInfo : 9;
1256 /// TypeQuals - Used only by FunctionProtoType, put here to pack with the
1257 /// other bitfields.
1258 /// The qualifiers are part of FunctionProtoType because...
1260 /// C++ 8.3.5p4: The return type, the parameter type list and the
1261 /// cv-qualifier-seq, [...], are part of the function type.
1262 unsigned TypeQuals : 3;
1265 class ObjCObjectTypeBitfields {
1266 friend class ObjCObjectType;
1268 unsigned : NumTypeBits;
1270 /// NumProtocols - The number of protocols stored directly on this
1272 unsigned NumProtocols : 32 - NumTypeBits;
1275 class ReferenceTypeBitfields {
1276 friend class ReferenceType;
1278 unsigned : NumTypeBits;
1280 /// True if the type was originally spelled with an lvalue sigil.
1281 /// This is never true of rvalue references but can also be false
1282 /// on lvalue references because of C++0x [dcl.typedef]p9,
1285 /// typedef int &ref; // lvalue, spelled lvalue
1286 /// typedef int &&rvref; // rvalue
1287 /// ref &a; // lvalue, inner ref, spelled lvalue
1288 /// ref &&a; // lvalue, inner ref
1289 /// rvref &a; // lvalue, inner ref, spelled lvalue
1290 /// rvref &&a; // rvalue, inner ref
1291 unsigned SpelledAsLValue : 1;
1293 /// True if the inner type is a reference type. This only happens
1294 /// in non-canonical forms.
1295 unsigned InnerRef : 1;
1298 class TypeWithKeywordBitfields {
1299 friend class TypeWithKeyword;
1301 unsigned : NumTypeBits;
1303 /// An ElaboratedTypeKeyword. 8 bits for efficient access.
1304 unsigned Keyword : 8;
1307 class VectorTypeBitfields {
1308 friend class VectorType;
1310 unsigned : NumTypeBits;
1312 /// VecKind - The kind of vector, either a generic vector type or some
1313 /// target-specific vector type such as for AltiVec or Neon.
1314 unsigned VecKind : 3;
1316 /// NumElements - The number of elements in the vector.
1317 unsigned NumElements : 29 - NumTypeBits;
1320 class AttributedTypeBitfields {
1321 friend class AttributedType;
1323 unsigned : NumTypeBits;
1325 /// AttrKind - an AttributedType::Kind
1326 unsigned AttrKind : 32 - NumTypeBits;
1329 class AutoTypeBitfields {
1330 friend class AutoType;
1332 unsigned : NumTypeBits;
1334 /// Was this placeholder type spelled as 'decltype(auto)'?
1335 unsigned IsDecltypeAuto : 1;
1339 TypeBitfields TypeBits;
1340 ArrayTypeBitfields ArrayTypeBits;
1341 AttributedTypeBitfields AttributedTypeBits;
1342 AutoTypeBitfields AutoTypeBits;
1343 BuiltinTypeBitfields BuiltinTypeBits;
1344 FunctionTypeBitfields FunctionTypeBits;
1345 ObjCObjectTypeBitfields ObjCObjectTypeBits;
1346 ReferenceTypeBitfields ReferenceTypeBits;
1347 TypeWithKeywordBitfields TypeWithKeywordBits;
1348 VectorTypeBitfields VectorTypeBits;
1352 /// \brief Set whether this type comes from an AST file.
1353 void setFromAST(bool V = true) const {
1354 TypeBits.FromAST = V;
1357 template <class T> friend class TypePropertyCache;
1360 // silence VC++ warning C4355: 'this' : used in base member initializer list
1361 Type *this_() { return this; }
1362 Type(TypeClass tc, QualType canon, bool Dependent,
1363 bool InstantiationDependent, bool VariablyModified,
1364 bool ContainsUnexpandedParameterPack)
1365 : ExtQualsTypeCommonBase(this,
1366 canon.isNull() ? QualType(this_(), 0) : canon) {
1368 TypeBits.Dependent = Dependent;
1369 TypeBits.InstantiationDependent = Dependent || InstantiationDependent;
1370 TypeBits.VariablyModified = VariablyModified;
1371 TypeBits.ContainsUnexpandedParameterPack = ContainsUnexpandedParameterPack;
1372 TypeBits.CacheValid = false;
1373 TypeBits.CachedLocalOrUnnamed = false;
1374 TypeBits.CachedLinkage = NoLinkage;
1375 TypeBits.FromAST = false;
1377 friend class ASTContext;
1379 void setDependent(bool D = true) {
1380 TypeBits.Dependent = D;
1382 TypeBits.InstantiationDependent = true;
1384 void setInstantiationDependent(bool D = true) {
1385 TypeBits.InstantiationDependent = D; }
1386 void setVariablyModified(bool VM = true) { TypeBits.VariablyModified = VM;
1388 void setContainsUnexpandedParameterPack(bool PP = true) {
1389 TypeBits.ContainsUnexpandedParameterPack = PP;
1393 TypeClass getTypeClass() const { return static_cast<TypeClass>(TypeBits.TC); }
1395 /// \brief Whether this type comes from an AST file.
1396 bool isFromAST() const { return TypeBits.FromAST; }
1398 /// \brief Whether this type is or contains an unexpanded parameter
1399 /// pack, used to support C++0x variadic templates.
1401 /// A type that contains a parameter pack shall be expanded by the
1402 /// ellipsis operator at some point. For example, the typedef in the
1403 /// following example contains an unexpanded parameter pack 'T':
1406 /// template<typename ...T>
1408 /// typedef T* pointer_types; // ill-formed; T is a parameter pack.
1412 /// Note that this routine does not specify which
1413 bool containsUnexpandedParameterPack() const {
1414 return TypeBits.ContainsUnexpandedParameterPack;
1417 /// Determines if this type would be canonical if it had no further
1419 bool isCanonicalUnqualified() const {
1420 return CanonicalType == QualType(this, 0);
1423 /// Pull a single level of sugar off of this locally-unqualified type.
1424 /// Users should generally prefer SplitQualType::getSingleStepDesugaredType()
1425 /// or QualType::getSingleStepDesugaredType(const ASTContext&).
1426 QualType getLocallyUnqualifiedSingleStepDesugaredType() const;
1428 /// Types are partitioned into 3 broad categories (C99 6.2.5p1):
1429 /// object types, function types, and incomplete types.
1431 /// isIncompleteType - Return true if this is an incomplete type.
1432 /// A type that can describe objects, but which lacks information needed to
1433 /// determine its size (e.g. void, or a fwd declared struct). Clients of this
1434 /// routine will need to determine if the size is actually required.
1436 /// \brief Def If non-NULL, and the type refers to some kind of declaration
1437 /// that can be completed (such as a C struct, C++ class, or Objective-C
1438 /// class), will be set to the declaration.
1439 bool isIncompleteType(NamedDecl **Def = 0) const;
1441 /// isIncompleteOrObjectType - Return true if this is an incomplete or object
1442 /// type, in other words, not a function type.
1443 bool isIncompleteOrObjectType() const {
1444 return !isFunctionType();
1447 /// \brief Determine whether this type is an object type.
1448 bool isObjectType() const {
1449 // C++ [basic.types]p8:
1450 // An object type is a (possibly cv-qualified) type that is not a
1451 // function type, not a reference type, and not a void type.
1452 return !isReferenceType() && !isFunctionType() && !isVoidType();
1455 /// isLiteralType - Return true if this is a literal type
1456 /// (C++11 [basic.types]p10)
1457 bool isLiteralType(ASTContext &Ctx) const;
1459 /// \brief Test if this type is a standard-layout type.
1460 /// (C++0x [basic.type]p9)
1461 bool isStandardLayoutType() const;
1463 /// Helper methods to distinguish type categories. All type predicates
1464 /// operate on the canonical type, ignoring typedefs and qualifiers.
1466 /// isBuiltinType - returns true if the type is a builtin type.
1467 bool isBuiltinType() const;
1469 /// isSpecificBuiltinType - Test for a particular builtin type.
1470 bool isSpecificBuiltinType(unsigned K) const;
1472 /// isPlaceholderType - Test for a type which does not represent an
1473 /// actual type-system type but is instead used as a placeholder for
1474 /// various convenient purposes within Clang. All such types are
1476 bool isPlaceholderType() const;
1477 const BuiltinType *getAsPlaceholderType() const;
1479 /// isSpecificPlaceholderType - Test for a specific placeholder type.
1480 bool isSpecificPlaceholderType(unsigned K) const;
1482 /// isNonOverloadPlaceholderType - Test for a placeholder type
1483 /// other than Overload; see BuiltinType::isNonOverloadPlaceholderType.
1484 bool isNonOverloadPlaceholderType() const;
1486 /// isIntegerType() does *not* include complex integers (a GCC extension).
1487 /// isComplexIntegerType() can be used to test for complex integers.
1488 bool isIntegerType() const; // C99 6.2.5p17 (int, char, bool, enum)
1489 bool isEnumeralType() const;
1490 bool isBooleanType() const;
1491 bool isCharType() const;
1492 bool isWideCharType() const;
1493 bool isChar16Type() const;
1494 bool isChar32Type() const;
1495 bool isAnyCharacterType() const;
1496 bool isIntegralType(ASTContext &Ctx) const;
1498 /// \brief Determine whether this type is an integral or enumeration type.
1499 bool isIntegralOrEnumerationType() const;
1500 /// \brief Determine whether this type is an integral or unscoped enumeration
1502 bool isIntegralOrUnscopedEnumerationType() const;
1504 /// Floating point categories.
1505 bool isRealFloatingType() const; // C99 6.2.5p10 (float, double, long double)
1506 /// isComplexType() does *not* include complex integers (a GCC extension).
1507 /// isComplexIntegerType() can be used to test for complex integers.
1508 bool isComplexType() const; // C99 6.2.5p11 (complex)
1509 bool isAnyComplexType() const; // C99 6.2.5p11 (complex) + Complex Int.
1510 bool isFloatingType() const; // C99 6.2.5p11 (real floating + complex)
1511 bool isHalfType() const; // OpenCL 6.1.1.1, NEON (IEEE 754-2008 half)
1512 bool isRealType() const; // C99 6.2.5p17 (real floating + integer)
1513 bool isArithmeticType() const; // C99 6.2.5p18 (integer + floating)
1514 bool isVoidType() const; // C99 6.2.5p19
1515 bool isDerivedType() const; // C99 6.2.5p20
1516 bool isScalarType() const; // C99 6.2.5p21 (arithmetic + pointers)
1517 bool isAggregateType() const;
1518 bool isFundamentalType() const;
1519 bool isCompoundType() const;
1521 // Type Predicates: Check to see if this type is structurally the specified
1522 // type, ignoring typedefs and qualifiers.
1523 bool isFunctionType() const;
1524 bool isFunctionNoProtoType() const { return getAs<FunctionNoProtoType>(); }
1525 bool isFunctionProtoType() const { return getAs<FunctionProtoType>(); }
1526 bool isPointerType() const;
1527 bool isAnyPointerType() const; // Any C pointer or ObjC object pointer
1528 bool isBlockPointerType() const;
1529 bool isVoidPointerType() const;
1530 bool isReferenceType() const;
1531 bool isLValueReferenceType() const;
1532 bool isRValueReferenceType() const;
1533 bool isFunctionPointerType() const;
1534 bool isMemberPointerType() const;
1535 bool isMemberFunctionPointerType() const;
1536 bool isMemberDataPointerType() const;
1537 bool isArrayType() const;
1538 bool isConstantArrayType() const;
1539 bool isIncompleteArrayType() const;
1540 bool isVariableArrayType() const;
1541 bool isDependentSizedArrayType() const;
1542 bool isRecordType() const;
1543 bool isClassType() const;
1544 bool isStructureType() const;
1545 bool isInterfaceType() const;
1546 bool isStructureOrClassType() const;
1547 bool isUnionType() const;
1548 bool isComplexIntegerType() const; // GCC _Complex integer type.
1549 bool isVectorType() const; // GCC vector type.
1550 bool isExtVectorType() const; // Extended vector type.
1551 bool isObjCObjectPointerType() const; // pointer to ObjC object
1552 bool isObjCRetainableType() const; // ObjC object or block pointer
1553 bool isObjCLifetimeType() const; // (array of)* retainable type
1554 bool isObjCIndirectLifetimeType() const; // (pointer to)* lifetime type
1555 bool isObjCNSObjectType() const; // __attribute__((NSObject))
1556 // FIXME: change this to 'raw' interface type, so we can used 'interface' type
1557 // for the common case.
1558 bool isObjCObjectType() const; // NSString or typeof(*(id)0)
1559 bool isObjCQualifiedInterfaceType() const; // NSString<foo>
1560 bool isObjCQualifiedIdType() const; // id<foo>
1561 bool isObjCQualifiedClassType() const; // Class<foo>
1562 bool isObjCObjectOrInterfaceType() const;
1563 bool isObjCIdType() const; // id
1564 bool isObjCClassType() const; // Class
1565 bool isObjCSelType() const; // Class
1566 bool isObjCBuiltinType() const; // 'id' or 'Class'
1567 bool isObjCARCBridgableType() const;
1568 bool isCARCBridgableType() const;
1569 bool isTemplateTypeParmType() const; // C++ template type parameter
1570 bool isNullPtrType() const; // C++0x nullptr_t
1571 bool isAtomicType() const; // C11 _Atomic()
1573 bool isImage1dT() const; // OpenCL image1d_t
1574 bool isImage1dArrayT() const; // OpenCL image1d_array_t
1575 bool isImage1dBufferT() const; // OpenCL image1d_buffer_t
1576 bool isImage2dT() const; // OpenCL image2d_t
1577 bool isImage2dArrayT() const; // OpenCL image2d_array_t
1578 bool isImage3dT() const; // OpenCL image3d_t
1580 bool isImageType() const; // Any OpenCL image type
1582 bool isSamplerT() const; // OpenCL sampler_t
1583 bool isEventT() const; // OpenCL event_t
1585 bool isOpenCLSpecificType() const; // Any OpenCL specific type
1587 /// Determines if this type, which must satisfy
1588 /// isObjCLifetimeType(), is implicitly __unsafe_unretained rather
1589 /// than implicitly __strong.
1590 bool isObjCARCImplicitlyUnretainedType() const;
1592 /// Return the implicit lifetime for this type, which must not be dependent.
1593 Qualifiers::ObjCLifetime getObjCARCImplicitLifetime() const;
1595 enum ScalarTypeKind {
1598 STK_ObjCObjectPointer,
1603 STK_IntegralComplex,
1606 /// getScalarTypeKind - Given that this is a scalar type, classify it.
1607 ScalarTypeKind getScalarTypeKind() const;
1609 /// isDependentType - Whether this type is a dependent type, meaning
1610 /// that its definition somehow depends on a template parameter
1611 /// (C++ [temp.dep.type]).
1612 bool isDependentType() const { return TypeBits.Dependent; }
1614 /// \brief Determine whether this type is an instantiation-dependent type,
1615 /// meaning that the type involves a template parameter (even if the
1616 /// definition does not actually depend on the type substituted for that
1617 /// template parameter).
1618 bool isInstantiationDependentType() const {
1619 return TypeBits.InstantiationDependent;
1622 /// \brief Determine whether this type is an undeduced type, meaning that
1623 /// it somehow involves a C++11 'auto' type which has not yet been deduced.
1624 bool isUndeducedType() const;
1626 /// \brief Whether this type is a variably-modified type (C99 6.7.5).
1627 bool isVariablyModifiedType() const { return TypeBits.VariablyModified; }
1629 /// \brief Whether this type involves a variable-length array type
1630 /// with a definite size.
1631 bool hasSizedVLAType() const;
1633 /// \brief Whether this type is or contains a local or unnamed type.
1634 bool hasUnnamedOrLocalType() const;
1636 bool isOverloadableType() const;
1638 /// \brief Determine wither this type is a C++ elaborated-type-specifier.
1639 bool isElaboratedTypeSpecifier() const;
1641 bool canDecayToPointerType() const;
1643 /// hasPointerRepresentation - Whether this type is represented
1644 /// natively as a pointer; this includes pointers, references, block
1645 /// pointers, and Objective-C interface, qualified id, and qualified
1646 /// interface types, as well as nullptr_t.
1647 bool hasPointerRepresentation() const;
1649 /// hasObjCPointerRepresentation - Whether this type can represent
1650 /// an objective pointer type for the purpose of GC'ability
1651 bool hasObjCPointerRepresentation() const;
1653 /// \brief Determine whether this type has an integer representation
1654 /// of some sort, e.g., it is an integer type or a vector.
1655 bool hasIntegerRepresentation() const;
1657 /// \brief Determine whether this type has an signed integer representation
1658 /// of some sort, e.g., it is an signed integer type or a vector.
1659 bool hasSignedIntegerRepresentation() const;
1661 /// \brief Determine whether this type has an unsigned integer representation
1662 /// of some sort, e.g., it is an unsigned integer type or a vector.
1663 bool hasUnsignedIntegerRepresentation() const;
1665 /// \brief Determine whether this type has a floating-point representation
1666 /// of some sort, e.g., it is a floating-point type or a vector thereof.
1667 bool hasFloatingRepresentation() const;
1669 // Type Checking Functions: Check to see if this type is structurally the
1670 // specified type, ignoring typedefs and qualifiers, and return a pointer to
1671 // the best type we can.
1672 const RecordType *getAsStructureType() const;
1673 /// NOTE: getAs*ArrayType are methods on ASTContext.
1674 const RecordType *getAsUnionType() const;
1675 const ComplexType *getAsComplexIntegerType() const; // GCC complex int type.
1676 // The following is a convenience method that returns an ObjCObjectPointerType
1677 // for object declared using an interface.
1678 const ObjCObjectPointerType *getAsObjCInterfacePointerType() const;
1679 const ObjCObjectPointerType *getAsObjCQualifiedIdType() const;
1680 const ObjCObjectPointerType *getAsObjCQualifiedClassType() const;
1681 const ObjCObjectType *getAsObjCQualifiedInterfaceType() const;
1683 /// \brief Retrieves the CXXRecordDecl that this type refers to, either
1684 /// because the type is a RecordType or because it is the injected-class-name
1685 /// type of a class template or class template partial specialization.
1686 CXXRecordDecl *getAsCXXRecordDecl() const;
1688 /// If this is a pointer or reference to a RecordType, return the
1689 /// CXXRecordDecl that that type refers to.
1691 /// If this is not a pointer or reference, or the type being pointed to does
1692 /// not refer to a CXXRecordDecl, returns NULL.
1693 const CXXRecordDecl *getPointeeCXXRecordDecl() const;
1695 /// \brief Get the AutoType whose type will be deduced for a variable with
1696 /// an initializer of this type. This looks through declarators like pointer
1697 /// types, but not through decltype or typedefs.
1698 AutoType *getContainedAutoType() const;
1700 /// Member-template getAs<specific type>'. Look through sugar for
1701 /// an instance of \<specific type>. This scheme will eventually
1702 /// replace the specific getAsXXXX methods above.
1704 /// There are some specializations of this member template listed
1705 /// immediately following this class.
1706 template <typename T> const T *getAs() const;
1708 /// A variant of getAs<> for array types which silently discards
1709 /// qualifiers from the outermost type.
1710 const ArrayType *getAsArrayTypeUnsafe() const;
1712 /// Member-template castAs<specific type>. Look through sugar for
1713 /// the underlying instance of \<specific type>.
1715 /// This method has the same relationship to getAs<T> as cast<T> has
1716 /// to dyn_cast<T>; which is to say, the underlying type *must*
1717 /// have the intended type, and this method will never return null.
1718 template <typename T> const T *castAs() const;
1720 /// A variant of castAs<> for array type which silently discards
1721 /// qualifiers from the outermost type.
1722 const ArrayType *castAsArrayTypeUnsafe() const;
1724 /// getBaseElementTypeUnsafe - Get the base element type of this
1725 /// type, potentially discarding type qualifiers. This method
1726 /// should never be used when type qualifiers are meaningful.
1727 const Type *getBaseElementTypeUnsafe() const;
1729 /// getArrayElementTypeNoTypeQual - If this is an array type, return the
1730 /// element type of the array, potentially with type qualifiers missing.
1731 /// This method should never be used when type qualifiers are meaningful.
1732 const Type *getArrayElementTypeNoTypeQual() const;
1734 /// getPointeeType - If this is a pointer, ObjC object pointer, or block
1735 /// pointer, this returns the respective pointee.
1736 QualType getPointeeType() const;
1738 /// getUnqualifiedDesugaredType() - Return the specified type with
1739 /// any "sugar" removed from the type, removing any typedefs,
1740 /// typeofs, etc., as well as any qualifiers.
1741 const Type *getUnqualifiedDesugaredType() const;
1743 /// More type predicates useful for type checking/promotion
1744 bool isPromotableIntegerType() const; // C99 6.3.1.1p2
1746 /// isSignedIntegerType - Return true if this is an integer type that is
1747 /// signed, according to C99 6.2.5p4 [char, signed char, short, int, long..],
1748 /// or an enum decl which has a signed representation.
1749 bool isSignedIntegerType() const;
1751 /// isUnsignedIntegerType - Return true if this is an integer type that is
1752 /// unsigned, according to C99 6.2.5p6 [which returns true for _Bool],
1753 /// or an enum decl which has an unsigned representation.
1754 bool isUnsignedIntegerType() const;
1756 /// Determines whether this is an integer type that is signed or an
1757 /// enumeration types whose underlying type is a signed integer type.
1758 bool isSignedIntegerOrEnumerationType() const;
1760 /// Determines whether this is an integer type that is unsigned or an
1761 /// enumeration types whose underlying type is a unsigned integer type.
1762 bool isUnsignedIntegerOrEnumerationType() const;
1764 /// isConstantSizeType - Return true if this is not a variable sized type,
1765 /// according to the rules of C99 6.7.5p3. It is not legal to call this on
1766 /// incomplete types.
1767 bool isConstantSizeType() const;
1769 /// isSpecifierType - Returns true if this type can be represented by some
1770 /// set of type specifiers.
1771 bool isSpecifierType() const;
1773 /// \brief Determine the linkage of this type.
1774 Linkage getLinkage() const;
1776 /// \brief Determine the visibility of this type.
1777 Visibility getVisibility() const {
1778 return getLinkageAndVisibility().getVisibility();
1781 /// \brief Return true if the visibility was explicitly set is the code.
1782 bool isVisibilityExplicit() const {
1783 return getLinkageAndVisibility().isVisibilityExplicit();
1786 /// \brief Determine the linkage and visibility of this type.
1787 LinkageInfo getLinkageAndVisibility() const;
1789 /// \brief True if the computed linkage is valid. Used for consistency
1790 /// checking. Should always return true.
1791 bool isLinkageValid() const;
1793 const char *getTypeClassName() const;
1795 QualType getCanonicalTypeInternal() const {
1796 return CanonicalType;
1798 CanQualType getCanonicalTypeUnqualified() const; // in CanonicalType.h
1799 LLVM_ATTRIBUTE_USED void dump() const;
1801 friend class ASTReader;
1802 friend class ASTWriter;
1805 /// \brief This will check for a TypedefType by removing any existing sugar
1806 /// until it reaches a TypedefType or a non-sugared type.
1807 template <> const TypedefType *Type::getAs() const;
1809 /// \brief This will check for a TemplateSpecializationType by removing any
1810 /// existing sugar until it reaches a TemplateSpecializationType or a
1811 /// non-sugared type.
1812 template <> const TemplateSpecializationType *Type::getAs() const;
1814 // We can do canonical leaf types faster, because we don't have to
1815 // worry about preserving child type decoration.
1816 #define TYPE(Class, Base)
1817 #define LEAF_TYPE(Class) \
1818 template <> inline const Class##Type *Type::getAs() const { \
1819 return dyn_cast<Class##Type>(CanonicalType); \
1821 template <> inline const Class##Type *Type::castAs() const { \
1822 return cast<Class##Type>(CanonicalType); \
1824 #include "clang/AST/TypeNodes.def"
1827 /// BuiltinType - This class is used for builtin types like 'int'. Builtin
1828 /// types are always canonical and have a literal name field.
1829 class BuiltinType : public Type {
1832 #define BUILTIN_TYPE(Id, SingletonId) Id,
1833 #define LAST_BUILTIN_TYPE(Id) LastKind = Id
1834 #include "clang/AST/BuiltinTypes.def"
1839 : Type(Builtin, QualType(), /*Dependent=*/(K == Dependent),
1840 /*InstantiationDependent=*/(K == Dependent),
1841 /*VariablyModified=*/false,
1842 /*Unexpanded paramter pack=*/false) {
1843 BuiltinTypeBits.Kind = K;
1846 Kind getKind() const { return static_cast<Kind>(BuiltinTypeBits.Kind); }
1847 StringRef getName(const PrintingPolicy &Policy) const;
1848 const char *getNameAsCString(const PrintingPolicy &Policy) const {
1849 // The StringRef is null-terminated.
1850 StringRef str = getName(Policy);
1851 assert(!str.empty() && str.data()[str.size()] == '\0');
1855 bool isSugared() const { return false; }
1856 QualType desugar() const { return QualType(this, 0); }
1858 bool isInteger() const {
1859 return getKind() >= Bool && getKind() <= Int128;
1862 bool isSignedInteger() const {
1863 return getKind() >= Char_S && getKind() <= Int128;
1866 bool isUnsignedInteger() const {
1867 return getKind() >= Bool && getKind() <= UInt128;
1870 bool isFloatingPoint() const {
1871 return getKind() >= Half && getKind() <= LongDouble;
1874 /// Determines whether the given kind corresponds to a placeholder type.
1875 static bool isPlaceholderTypeKind(Kind K) {
1876 return K >= Overload;
1879 /// Determines whether this type is a placeholder type, i.e. a type
1880 /// which cannot appear in arbitrary positions in a fully-formed
1882 bool isPlaceholderType() const {
1883 return isPlaceholderTypeKind(getKind());
1886 /// Determines whether this type is a placeholder type other than
1887 /// Overload. Most placeholder types require only syntactic
1888 /// information about their context in order to be resolved (e.g.
1889 /// whether it is a call expression), which means they can (and
1890 /// should) be resolved in an earlier "phase" of analysis.
1891 /// Overload expressions sometimes pick up further information
1892 /// from their context, like whether the context expects a
1893 /// specific function-pointer type, and so frequently need
1894 /// special treatment.
1895 bool isNonOverloadPlaceholderType() const {
1896 return getKind() > Overload;
1899 static bool classof(const Type *T) { return T->getTypeClass() == Builtin; }
1902 /// ComplexType - C99 6.2.5p11 - Complex values. This supports the C99 complex
1903 /// types (_Complex float etc) as well as the GCC integer complex extensions.
1905 class ComplexType : public Type, public llvm::FoldingSetNode {
1906 QualType ElementType;
1907 ComplexType(QualType Element, QualType CanonicalPtr) :
1908 Type(Complex, CanonicalPtr, Element->isDependentType(),
1909 Element->isInstantiationDependentType(),
1910 Element->isVariablyModifiedType(),
1911 Element->containsUnexpandedParameterPack()),
1912 ElementType(Element) {
1914 friend class ASTContext; // ASTContext creates these.
1917 QualType getElementType() const { return ElementType; }
1919 bool isSugared() const { return false; }
1920 QualType desugar() const { return QualType(this, 0); }
1922 void Profile(llvm::FoldingSetNodeID &ID) {
1923 Profile(ID, getElementType());
1925 static void Profile(llvm::FoldingSetNodeID &ID, QualType Element) {
1926 ID.AddPointer(Element.getAsOpaquePtr());
1929 static bool classof(const Type *T) { return T->getTypeClass() == Complex; }
1932 /// ParenType - Sugar for parentheses used when specifying types.
1934 class ParenType : public Type, public llvm::FoldingSetNode {
1937 ParenType(QualType InnerType, QualType CanonType) :
1938 Type(Paren, CanonType, InnerType->isDependentType(),
1939 InnerType->isInstantiationDependentType(),
1940 InnerType->isVariablyModifiedType(),
1941 InnerType->containsUnexpandedParameterPack()),
1944 friend class ASTContext; // ASTContext creates these.
1948 QualType getInnerType() const { return Inner; }
1950 bool isSugared() const { return true; }
1951 QualType desugar() const { return getInnerType(); }
1953 void Profile(llvm::FoldingSetNodeID &ID) {
1954 Profile(ID, getInnerType());
1956 static void Profile(llvm::FoldingSetNodeID &ID, QualType Inner) {
1960 static bool classof(const Type *T) { return T->getTypeClass() == Paren; }
1963 /// PointerType - C99 6.7.5.1 - Pointer Declarators.
1965 class PointerType : public Type, public llvm::FoldingSetNode {
1966 QualType PointeeType;
1968 PointerType(QualType Pointee, QualType CanonicalPtr) :
1969 Type(Pointer, CanonicalPtr, Pointee->isDependentType(),
1970 Pointee->isInstantiationDependentType(),
1971 Pointee->isVariablyModifiedType(),
1972 Pointee->containsUnexpandedParameterPack()),
1973 PointeeType(Pointee) {
1975 friend class ASTContext; // ASTContext creates these.
1979 QualType getPointeeType() const { return PointeeType; }
1981 bool isSugared() const { return false; }
1982 QualType desugar() const { return QualType(this, 0); }
1984 void Profile(llvm::FoldingSetNodeID &ID) {
1985 Profile(ID, getPointeeType());
1987 static void Profile(llvm::FoldingSetNodeID &ID, QualType Pointee) {
1988 ID.AddPointer(Pointee.getAsOpaquePtr());
1991 static bool classof(const Type *T) { return T->getTypeClass() == Pointer; }
1994 /// BlockPointerType - pointer to a block type.
1995 /// This type is to represent types syntactically represented as
1996 /// "void (^)(int)", etc. Pointee is required to always be a function type.
1998 class BlockPointerType : public Type, public llvm::FoldingSetNode {
1999 QualType PointeeType; // Block is some kind of pointer type
2000 BlockPointerType(QualType Pointee, QualType CanonicalCls) :
2001 Type(BlockPointer, CanonicalCls, Pointee->isDependentType(),
2002 Pointee->isInstantiationDependentType(),
2003 Pointee->isVariablyModifiedType(),
2004 Pointee->containsUnexpandedParameterPack()),
2005 PointeeType(Pointee) {
2007 friend class ASTContext; // ASTContext creates these.
2011 // Get the pointee type. Pointee is required to always be a function type.
2012 QualType getPointeeType() const { return PointeeType; }
2014 bool isSugared() const { return false; }
2015 QualType desugar() const { return QualType(this, 0); }
2017 void Profile(llvm::FoldingSetNodeID &ID) {
2018 Profile(ID, getPointeeType());
2020 static void Profile(llvm::FoldingSetNodeID &ID, QualType Pointee) {
2021 ID.AddPointer(Pointee.getAsOpaquePtr());
2024 static bool classof(const Type *T) {
2025 return T->getTypeClass() == BlockPointer;
2029 /// ReferenceType - Base for LValueReferenceType and RValueReferenceType
2031 class ReferenceType : public Type, public llvm::FoldingSetNode {
2032 QualType PointeeType;
2035 ReferenceType(TypeClass tc, QualType Referencee, QualType CanonicalRef,
2036 bool SpelledAsLValue) :
2037 Type(tc, CanonicalRef, Referencee->isDependentType(),
2038 Referencee->isInstantiationDependentType(),
2039 Referencee->isVariablyModifiedType(),
2040 Referencee->containsUnexpandedParameterPack()),
2041 PointeeType(Referencee)
2043 ReferenceTypeBits.SpelledAsLValue = SpelledAsLValue;
2044 ReferenceTypeBits.InnerRef = Referencee->isReferenceType();
2048 bool isSpelledAsLValue() const { return ReferenceTypeBits.SpelledAsLValue; }
2049 bool isInnerRef() const { return ReferenceTypeBits.InnerRef; }
2051 QualType getPointeeTypeAsWritten() const { return PointeeType; }
2052 QualType getPointeeType() const {
2053 // FIXME: this might strip inner qualifiers; okay?
2054 const ReferenceType *T = this;
2055 while (T->isInnerRef())
2056 T = T->PointeeType->castAs<ReferenceType>();
2057 return T->PointeeType;
2060 void Profile(llvm::FoldingSetNodeID &ID) {
2061 Profile(ID, PointeeType, isSpelledAsLValue());
2063 static void Profile(llvm::FoldingSetNodeID &ID,
2064 QualType Referencee,
2065 bool SpelledAsLValue) {
2066 ID.AddPointer(Referencee.getAsOpaquePtr());
2067 ID.AddBoolean(SpelledAsLValue);
2070 static bool classof(const Type *T) {
2071 return T->getTypeClass() == LValueReference ||
2072 T->getTypeClass() == RValueReference;
2076 /// LValueReferenceType - C++ [dcl.ref] - Lvalue reference
2078 class LValueReferenceType : public ReferenceType {
2079 LValueReferenceType(QualType Referencee, QualType CanonicalRef,
2080 bool SpelledAsLValue) :
2081 ReferenceType(LValueReference, Referencee, CanonicalRef, SpelledAsLValue)
2083 friend class ASTContext; // ASTContext creates these
2085 bool isSugared() const { return false; }
2086 QualType desugar() const { return QualType(this, 0); }
2088 static bool classof(const Type *T) {
2089 return T->getTypeClass() == LValueReference;
2093 /// RValueReferenceType - C++0x [dcl.ref] - Rvalue reference
2095 class RValueReferenceType : public ReferenceType {
2096 RValueReferenceType(QualType Referencee, QualType CanonicalRef) :
2097 ReferenceType(RValueReference, Referencee, CanonicalRef, false) {
2099 friend class ASTContext; // ASTContext creates these
2101 bool isSugared() const { return false; }
2102 QualType desugar() const { return QualType(this, 0); }
2104 static bool classof(const Type *T) {
2105 return T->getTypeClass() == RValueReference;
2109 /// MemberPointerType - C++ 8.3.3 - Pointers to members
2111 class MemberPointerType : public Type, public llvm::FoldingSetNode {
2112 QualType PointeeType;
2113 /// The class of which the pointee is a member. Must ultimately be a
2114 /// RecordType, but could be a typedef or a template parameter too.
2117 MemberPointerType(QualType Pointee, const Type *Cls, QualType CanonicalPtr) :
2118 Type(MemberPointer, CanonicalPtr,
2119 Cls->isDependentType() || Pointee->isDependentType(),
2120 (Cls->isInstantiationDependentType() ||
2121 Pointee->isInstantiationDependentType()),
2122 Pointee->isVariablyModifiedType(),
2123 (Cls->containsUnexpandedParameterPack() ||
2124 Pointee->containsUnexpandedParameterPack())),
2125 PointeeType(Pointee), Class(Cls) {
2127 friend class ASTContext; // ASTContext creates these.
2130 QualType getPointeeType() const { return PointeeType; }
2132 /// Returns true if the member type (i.e. the pointee type) is a
2133 /// function type rather than a data-member type.
2134 bool isMemberFunctionPointer() const {
2135 return PointeeType->isFunctionProtoType();
2138 /// Returns true if the member type (i.e. the pointee type) is a
2139 /// data type rather than a function type.
2140 bool isMemberDataPointer() const {
2141 return !PointeeType->isFunctionProtoType();
2144 const Type *getClass() const { return Class; }
2146 bool isSugared() const { return false; }
2147 QualType desugar() const { return QualType(this, 0); }
2149 void Profile(llvm::FoldingSetNodeID &ID) {
2150 Profile(ID, getPointeeType(), getClass());
2152 static void Profile(llvm::FoldingSetNodeID &ID, QualType Pointee,
2153 const Type *Class) {
2154 ID.AddPointer(Pointee.getAsOpaquePtr());
2155 ID.AddPointer(Class);
2158 static bool classof(const Type *T) {
2159 return T->getTypeClass() == MemberPointer;
2163 /// ArrayType - C99 6.7.5.2 - Array Declarators.
2165 class ArrayType : public Type, public llvm::FoldingSetNode {
2167 /// ArraySizeModifier - Capture whether this is a normal array (e.g. int X[4])
2168 /// an array with a static size (e.g. int X[static 4]), or an array
2169 /// with a star size (e.g. int X[*]).
2170 /// 'static' is only allowed on function parameters.
2171 enum ArraySizeModifier {
2172 Normal, Static, Star
2175 /// ElementType - The element type of the array.
2176 QualType ElementType;
2179 // C++ [temp.dep.type]p1:
2180 // A type is dependent if it is...
2181 // - an array type constructed from any dependent type or whose
2182 // size is specified by a constant expression that is
2184 ArrayType(TypeClass tc, QualType et, QualType can,
2185 ArraySizeModifier sm, unsigned tq,
2186 bool ContainsUnexpandedParameterPack)
2187 : Type(tc, can, et->isDependentType() || tc == DependentSizedArray,
2188 et->isInstantiationDependentType() || tc == DependentSizedArray,
2189 (tc == VariableArray || et->isVariablyModifiedType()),
2190 ContainsUnexpandedParameterPack),
2192 ArrayTypeBits.IndexTypeQuals = tq;
2193 ArrayTypeBits.SizeModifier = sm;
2196 friend class ASTContext; // ASTContext creates these.
2199 QualType getElementType() const { return ElementType; }
2200 ArraySizeModifier getSizeModifier() const {
2201 return ArraySizeModifier(ArrayTypeBits.SizeModifier);
2203 Qualifiers getIndexTypeQualifiers() const {
2204 return Qualifiers::fromCVRMask(getIndexTypeCVRQualifiers());
2206 unsigned getIndexTypeCVRQualifiers() const {
2207 return ArrayTypeBits.IndexTypeQuals;
2210 static bool classof(const Type *T) {
2211 return T->getTypeClass() == ConstantArray ||
2212 T->getTypeClass() == VariableArray ||
2213 T->getTypeClass() == IncompleteArray ||
2214 T->getTypeClass() == DependentSizedArray;
2218 /// ConstantArrayType - This class represents the canonical version of
2219 /// C arrays with a specified constant size. For example, the canonical
2220 /// type for 'int A[4 + 4*100]' is a ConstantArrayType where the element
2221 /// type is 'int' and the size is 404.
2222 class ConstantArrayType : public ArrayType {
2223 llvm::APInt Size; // Allows us to unique the type.
2225 ConstantArrayType(QualType et, QualType can, const llvm::APInt &size,
2226 ArraySizeModifier sm, unsigned tq)
2227 : ArrayType(ConstantArray, et, can, sm, tq,
2228 et->containsUnexpandedParameterPack()),
2231 ConstantArrayType(TypeClass tc, QualType et, QualType can,
2232 const llvm::APInt &size, ArraySizeModifier sm, unsigned tq)
2233 : ArrayType(tc, et, can, sm, tq, et->containsUnexpandedParameterPack()),
2235 friend class ASTContext; // ASTContext creates these.
2237 const llvm::APInt &getSize() const { return Size; }
2238 bool isSugared() const { return false; }
2239 QualType desugar() const { return QualType(this, 0); }
2242 /// \brief Determine the number of bits required to address a member of
2243 // an array with the given element type and number of elements.
2244 static unsigned getNumAddressingBits(ASTContext &Context,
2245 QualType ElementType,
2246 const llvm::APInt &NumElements);
2248 /// \brief Determine the maximum number of active bits that an array's size
2249 /// can require, which limits the maximum size of the array.
2250 static unsigned getMaxSizeBits(ASTContext &Context);
2252 void Profile(llvm::FoldingSetNodeID &ID) {
2253 Profile(ID, getElementType(), getSize(),
2254 getSizeModifier(), getIndexTypeCVRQualifiers());
2256 static void Profile(llvm::FoldingSetNodeID &ID, QualType ET,
2257 const llvm::APInt &ArraySize, ArraySizeModifier SizeMod,
2258 unsigned TypeQuals) {
2259 ID.AddPointer(ET.getAsOpaquePtr());
2260 ID.AddInteger(ArraySize.getZExtValue());
2261 ID.AddInteger(SizeMod);
2262 ID.AddInteger(TypeQuals);
2264 static bool classof(const Type *T) {
2265 return T->getTypeClass() == ConstantArray;
2269 /// IncompleteArrayType - This class represents C arrays with an unspecified
2270 /// size. For example 'int A[]' has an IncompleteArrayType where the element
2271 /// type is 'int' and the size is unspecified.
2272 class IncompleteArrayType : public ArrayType {
2274 IncompleteArrayType(QualType et, QualType can,
2275 ArraySizeModifier sm, unsigned tq)
2276 : ArrayType(IncompleteArray, et, can, sm, tq,
2277 et->containsUnexpandedParameterPack()) {}
2278 friend class ASTContext; // ASTContext creates these.
2280 bool isSugared() const { return false; }
2281 QualType desugar() const { return QualType(this, 0); }
2283 static bool classof(const Type *T) {
2284 return T->getTypeClass() == IncompleteArray;
2287 friend class StmtIteratorBase;
2289 void Profile(llvm::FoldingSetNodeID &ID) {
2290 Profile(ID, getElementType(), getSizeModifier(),
2291 getIndexTypeCVRQualifiers());
2294 static void Profile(llvm::FoldingSetNodeID &ID, QualType ET,
2295 ArraySizeModifier SizeMod, unsigned TypeQuals) {
2296 ID.AddPointer(ET.getAsOpaquePtr());
2297 ID.AddInteger(SizeMod);
2298 ID.AddInteger(TypeQuals);
2302 /// VariableArrayType - This class represents C arrays with a specified size
2303 /// which is not an integer-constant-expression. For example, 'int s[x+foo()]'.
2304 /// Since the size expression is an arbitrary expression, we store it as such.
2306 /// Note: VariableArrayType's aren't uniqued (since the expressions aren't) and
2307 /// should not be: two lexically equivalent variable array types could mean
2308 /// different things, for example, these variables do not have the same type
2311 /// void foo(int x) {
2317 class VariableArrayType : public ArrayType {
2318 /// SizeExpr - An assignment expression. VLA's are only permitted within
2319 /// a function block.
2321 /// Brackets - The left and right array brackets.
2322 SourceRange Brackets;
2324 VariableArrayType(QualType et, QualType can, Expr *e,
2325 ArraySizeModifier sm, unsigned tq,
2326 SourceRange brackets)
2327 : ArrayType(VariableArray, et, can, sm, tq,
2328 et->containsUnexpandedParameterPack()),
2329 SizeExpr((Stmt*) e), Brackets(brackets) {}
2330 friend class ASTContext; // ASTContext creates these.
2333 Expr *getSizeExpr() const {
2334 // We use C-style casts instead of cast<> here because we do not wish
2335 // to have a dependency of Type.h on Stmt.h/Expr.h.
2336 return (Expr*) SizeExpr;
2338 SourceRange getBracketsRange() const { return Brackets; }
2339 SourceLocation getLBracketLoc() const { return Brackets.getBegin(); }
2340 SourceLocation getRBracketLoc() const { return Brackets.getEnd(); }
2342 bool isSugared() const { return false; }
2343 QualType desugar() const { return QualType(this, 0); }
2345 static bool classof(const Type *T) {
2346 return T->getTypeClass() == VariableArray;
2349 friend class StmtIteratorBase;
2351 void Profile(llvm::FoldingSetNodeID &ID) {
2352 llvm_unreachable("Cannot unique VariableArrayTypes.");
2356 /// DependentSizedArrayType - This type represents an array type in
2357 /// C++ whose size is a value-dependent expression. For example:
2360 /// template<typename T, int Size>
2366 /// For these types, we won't actually know what the array bound is
2367 /// until template instantiation occurs, at which point this will
2368 /// become either a ConstantArrayType or a VariableArrayType.
2369 class DependentSizedArrayType : public ArrayType {
2370 const ASTContext &Context;
2372 /// \brief An assignment expression that will instantiate to the
2373 /// size of the array.
2375 /// The expression itself might be NULL, in which case the array
2376 /// type will have its size deduced from an initializer.
2379 /// Brackets - The left and right array brackets.
2380 SourceRange Brackets;
2382 DependentSizedArrayType(const ASTContext &Context, QualType et, QualType can,
2383 Expr *e, ArraySizeModifier sm, unsigned tq,
2384 SourceRange brackets);
2386 friend class ASTContext; // ASTContext creates these.
2389 Expr *getSizeExpr() const {
2390 // We use C-style casts instead of cast<> here because we do not wish
2391 // to have a dependency of Type.h on Stmt.h/Expr.h.
2392 return (Expr*) SizeExpr;
2394 SourceRange getBracketsRange() const { return Brackets; }
2395 SourceLocation getLBracketLoc() const { return Brackets.getBegin(); }
2396 SourceLocation getRBracketLoc() const { return Brackets.getEnd(); }
2398 bool isSugared() const { return false; }
2399 QualType desugar() const { return QualType(this, 0); }
2401 static bool classof(const Type *T) {
2402 return T->getTypeClass() == DependentSizedArray;
2405 friend class StmtIteratorBase;
2408 void Profile(llvm::FoldingSetNodeID &ID) {
2409 Profile(ID, Context, getElementType(),
2410 getSizeModifier(), getIndexTypeCVRQualifiers(), getSizeExpr());
2413 static void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context,
2414 QualType ET, ArraySizeModifier SizeMod,
2415 unsigned TypeQuals, Expr *E);
2418 /// DependentSizedExtVectorType - This type represent an extended vector type
2419 /// where either the type or size is dependent. For example:
2421 /// template<typename T, int Size>
2423 /// typedef T __attribute__((ext_vector_type(Size))) type;
2426 class DependentSizedExtVectorType : public Type, public llvm::FoldingSetNode {
2427 const ASTContext &Context;
2429 /// ElementType - The element type of the array.
2430 QualType ElementType;
2433 DependentSizedExtVectorType(const ASTContext &Context, QualType ElementType,
2434 QualType can, Expr *SizeExpr, SourceLocation loc);
2436 friend class ASTContext;
2439 Expr *getSizeExpr() const { return SizeExpr; }
2440 QualType getElementType() const { return ElementType; }
2441 SourceLocation getAttributeLoc() const { return loc; }
2443 bool isSugared() const { return false; }
2444 QualType desugar() const { return QualType(this, 0); }
2446 static bool classof(const Type *T) {
2447 return T->getTypeClass() == DependentSizedExtVector;
2450 void Profile(llvm::FoldingSetNodeID &ID) {
2451 Profile(ID, Context, getElementType(), getSizeExpr());
2454 static void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context,
2455 QualType ElementType, Expr *SizeExpr);
2459 /// VectorType - GCC generic vector type. This type is created using
2460 /// __attribute__((vector_size(n)), where "n" specifies the vector size in
2461 /// bytes; or from an Altivec __vector or vector declaration.
2462 /// Since the constructor takes the number of vector elements, the
2463 /// client is responsible for converting the size into the number of elements.
2464 class VectorType : public Type, public llvm::FoldingSetNode {
2467 GenericVector, // not a target-specific vector type
2468 AltiVecVector, // is AltiVec vector
2469 AltiVecPixel, // is AltiVec 'vector Pixel'
2470 AltiVecBool, // is AltiVec 'vector bool ...'
2471 NeonVector, // is ARM Neon vector
2472 NeonPolyVector // is ARM Neon polynomial vector
2475 /// ElementType - The element type of the vector.
2476 QualType ElementType;
2478 VectorType(QualType vecType, unsigned nElements, QualType canonType,
2479 VectorKind vecKind);
2481 VectorType(TypeClass tc, QualType vecType, unsigned nElements,
2482 QualType canonType, VectorKind vecKind);
2484 friend class ASTContext; // ASTContext creates these.
2488 QualType getElementType() const { return ElementType; }
2489 unsigned getNumElements() const { return VectorTypeBits.NumElements; }
2491 bool isSugared() const { return false; }
2492 QualType desugar() const { return QualType(this, 0); }
2494 VectorKind getVectorKind() const {
2495 return VectorKind(VectorTypeBits.VecKind);
2498 void Profile(llvm::FoldingSetNodeID &ID) {
2499 Profile(ID, getElementType(), getNumElements(),
2500 getTypeClass(), getVectorKind());
2502 static void Profile(llvm::FoldingSetNodeID &ID, QualType ElementType,
2503 unsigned NumElements, TypeClass TypeClass,
2504 VectorKind VecKind) {
2505 ID.AddPointer(ElementType.getAsOpaquePtr());
2506 ID.AddInteger(NumElements);
2507 ID.AddInteger(TypeClass);
2508 ID.AddInteger(VecKind);
2511 static bool classof(const Type *T) {
2512 return T->getTypeClass() == Vector || T->getTypeClass() == ExtVector;
2516 /// ExtVectorType - Extended vector type. This type is created using
2517 /// __attribute__((ext_vector_type(n)), where "n" is the number of elements.
2518 /// Unlike vector_size, ext_vector_type is only allowed on typedef's. This
2519 /// class enables syntactic extensions, like Vector Components for accessing
2520 /// points, colors, and textures (modeled after OpenGL Shading Language).
2521 class ExtVectorType : public VectorType {
2522 ExtVectorType(QualType vecType, unsigned nElements, QualType canonType) :
2523 VectorType(ExtVector, vecType, nElements, canonType, GenericVector) {}
2524 friend class ASTContext; // ASTContext creates these.
2526 static int getPointAccessorIdx(char c) {
2535 static int getNumericAccessorIdx(char c) {
2549 case 'a': return 10;
2551 case 'b': return 11;
2553 case 'c': return 12;
2555 case 'd': return 13;
2557 case 'e': return 14;
2559 case 'f': return 15;
2563 static int getAccessorIdx(char c) {
2564 if (int idx = getPointAccessorIdx(c)+1) return idx-1;
2565 return getNumericAccessorIdx(c);
2568 bool isAccessorWithinNumElements(char c) const {
2569 if (int idx = getAccessorIdx(c)+1)
2570 return unsigned(idx-1) < getNumElements();
2573 bool isSugared() const { return false; }
2574 QualType desugar() const { return QualType(this, 0); }
2576 static bool classof(const Type *T) {
2577 return T->getTypeClass() == ExtVector;
2581 /// FunctionType - C99 6.7.5.3 - Function Declarators. This is the common base
2582 /// class of FunctionNoProtoType and FunctionProtoType.
2584 class FunctionType : public Type {
2585 // The type returned by the function.
2586 QualType ResultType;
2589 /// ExtInfo - A class which abstracts out some details necessary for
2592 /// It is not actually used directly for storing this information in
2593 /// a FunctionType, although FunctionType does currently use the
2594 /// same bit-pattern.
2596 // If you add a field (say Foo), other than the obvious places (both,
2597 // constructors, compile failures), what you need to update is
2601 // * functionType. Add Foo, getFoo.
2602 // * ASTContext::getFooType
2603 // * ASTContext::mergeFunctionTypes
2604 // * FunctionNoProtoType::Profile
2605 // * FunctionProtoType::Profile
2606 // * TypePrinter::PrintFunctionProto
2607 // * AST read and write
2610 // Feel free to rearrange or add bits, but if you go over 9,
2611 // you'll need to adjust both the Bits field below and
2612 // Type::FunctionTypeBitfields.
2614 // | CC |noreturn|produces|regparm|
2615 // |0 .. 3| 4 | 5 | 6 .. 8|
2617 // regparm is either 0 (no regparm attribute) or the regparm value+1.
2618 enum { CallConvMask = 0xF };
2619 enum { NoReturnMask = 0x10 };
2620 enum { ProducesResultMask = 0x20 };
2621 enum { RegParmMask = ~(CallConvMask | NoReturnMask | ProducesResultMask),
2622 RegParmOffset = 6 }; // Assumed to be the last field
2626 ExtInfo(unsigned Bits) : Bits(static_cast<uint16_t>(Bits)) {}
2628 friend class FunctionType;
2631 // Constructor with no defaults. Use this when you know that you
2632 // have all the elements (when reading an AST file for example).
2633 ExtInfo(bool noReturn, bool hasRegParm, unsigned regParm, CallingConv cc,
2634 bool producesResult) {
2635 assert((!hasRegParm || regParm < 7) && "Invalid regparm value");
2636 Bits = ((unsigned) cc) |
2637 (noReturn ? NoReturnMask : 0) |
2638 (producesResult ? ProducesResultMask : 0) |
2639 (hasRegParm ? ((regParm + 1) << RegParmOffset) : 0);
2642 // Constructor with all defaults. Use when for example creating a
2643 // function know to use defaults.
2644 ExtInfo() : Bits(0) {}
2646 bool getNoReturn() const { return Bits & NoReturnMask; }
2647 bool getProducesResult() const { return Bits & ProducesResultMask; }
2648 bool getHasRegParm() const { return (Bits >> RegParmOffset) != 0; }
2649 unsigned getRegParm() const {
2650 unsigned RegParm = Bits >> RegParmOffset;
2655 CallingConv getCC() const { return CallingConv(Bits & CallConvMask); }
2657 bool operator==(ExtInfo Other) const {
2658 return Bits == Other.Bits;
2660 bool operator!=(ExtInfo Other) const {
2661 return Bits != Other.Bits;
2664 // Note that we don't have setters. That is by design, use
2665 // the following with methods instead of mutating these objects.
2667 ExtInfo withNoReturn(bool noReturn) const {
2669 return ExtInfo(Bits | NoReturnMask);
2671 return ExtInfo(Bits & ~NoReturnMask);
2674 ExtInfo withProducesResult(bool producesResult) const {
2676 return ExtInfo(Bits | ProducesResultMask);
2678 return ExtInfo(Bits & ~ProducesResultMask);
2681 ExtInfo withRegParm(unsigned RegParm) const {
2682 assert(RegParm < 7 && "Invalid regparm value");
2683 return ExtInfo((Bits & ~RegParmMask) |
2684 ((RegParm + 1) << RegParmOffset));
2687 ExtInfo withCallingConv(CallingConv cc) const {
2688 return ExtInfo((Bits & ~CallConvMask) | (unsigned) cc);
2691 void Profile(llvm::FoldingSetNodeID &ID) const {
2692 ID.AddInteger(Bits);
2697 FunctionType(TypeClass tc, QualType res,
2698 unsigned typeQuals, QualType Canonical, bool Dependent,
2699 bool InstantiationDependent,
2700 bool VariablyModified, bool ContainsUnexpandedParameterPack,
2702 : Type(tc, Canonical, Dependent, InstantiationDependent, VariablyModified,
2703 ContainsUnexpandedParameterPack),
2705 FunctionTypeBits.ExtInfo = Info.Bits;
2706 FunctionTypeBits.TypeQuals = typeQuals;
2708 unsigned getTypeQuals() const { return FunctionTypeBits.TypeQuals; }
2712 QualType getResultType() const { return ResultType; }
2714 bool getHasRegParm() const { return getExtInfo().getHasRegParm(); }
2715 unsigned getRegParmType() const { return getExtInfo().getRegParm(); }
2716 /// \brief Determine whether this function type includes the GNU noreturn
2717 /// attribute. The C++11 [[noreturn]] attribute does not affect the function
2719 bool getNoReturnAttr() const { return getExtInfo().getNoReturn(); }
2720 CallingConv getCallConv() const { return getExtInfo().getCC(); }
2721 ExtInfo getExtInfo() const { return ExtInfo(FunctionTypeBits.ExtInfo); }
2722 bool isConst() const { return getTypeQuals() & Qualifiers::Const; }
2723 bool isVolatile() const { return getTypeQuals() & Qualifiers::Volatile; }
2724 bool isRestrict() const { return getTypeQuals() & Qualifiers::Restrict; }
2726 /// \brief Determine the type of an expression that calls a function of
2728 QualType getCallResultType(ASTContext &Context) const {
2729 return getResultType().getNonLValueExprType(Context);
2732 static StringRef getNameForCallConv(CallingConv CC);
2734 static bool classof(const Type *T) {
2735 return T->getTypeClass() == FunctionNoProto ||
2736 T->getTypeClass() == FunctionProto;
2740 /// FunctionNoProtoType - Represents a K&R-style 'int foo()' function, which has
2741 /// no information available about its arguments.
2742 class FunctionNoProtoType : public FunctionType, public llvm::FoldingSetNode {
2743 FunctionNoProtoType(QualType Result, QualType Canonical, ExtInfo Info)
2744 : FunctionType(FunctionNoProto, Result, 0, Canonical,
2745 /*Dependent=*/false, /*InstantiationDependent=*/false,
2746 Result->isVariablyModifiedType(),
2747 /*ContainsUnexpandedParameterPack=*/false, Info) {}
2749 friend class ASTContext; // ASTContext creates these.
2752 // No additional state past what FunctionType provides.
2754 bool isSugared() const { return false; }
2755 QualType desugar() const { return QualType(this, 0); }
2757 void Profile(llvm::FoldingSetNodeID &ID) {
2758 Profile(ID, getResultType(), getExtInfo());
2760 static void Profile(llvm::FoldingSetNodeID &ID, QualType ResultType,
2763 ID.AddPointer(ResultType.getAsOpaquePtr());
2766 static bool classof(const Type *T) {
2767 return T->getTypeClass() == FunctionNoProto;
2771 /// FunctionProtoType - Represents a prototype with argument type info, e.g.
2772 /// 'int foo(int)' or 'int foo(void)'. 'void' is represented as having no
2773 /// arguments, not as having a single void argument. Such a type can have an
2774 /// exception specification, but this specification is not part of the canonical
2776 class FunctionProtoType : public FunctionType, public llvm::FoldingSetNode {
2778 /// ExtProtoInfo - Extra information about a function prototype.
2779 struct ExtProtoInfo {
2781 Variadic(false), HasTrailingReturn(false), TypeQuals(0),
2782 ExceptionSpecType(EST_None), RefQualifier(RQ_None),
2783 NumExceptions(0), Exceptions(0), NoexceptExpr(0),
2784 ExceptionSpecDecl(0), ExceptionSpecTemplate(0),
2785 ConsumedArguments(0) {}
2787 FunctionType::ExtInfo ExtInfo;
2789 bool HasTrailingReturn : 1;
2790 unsigned char TypeQuals;
2791 ExceptionSpecificationType ExceptionSpecType;
2792 RefQualifierKind RefQualifier;
2793 unsigned NumExceptions;
2794 const QualType *Exceptions;
2796 FunctionDecl *ExceptionSpecDecl;
2797 FunctionDecl *ExceptionSpecTemplate;
2798 const bool *ConsumedArguments;
2802 /// \brief Determine whether there are any argument types that
2803 /// contain an unexpanded parameter pack.
2804 static bool containsAnyUnexpandedParameterPack(const QualType *ArgArray,
2806 for (unsigned Idx = 0; Idx < numArgs; ++Idx)
2807 if (ArgArray[Idx]->containsUnexpandedParameterPack())
2813 FunctionProtoType(QualType result, ArrayRef<QualType> args,
2814 QualType canonical, const ExtProtoInfo &epi);
2816 /// NumArgs - The number of arguments this function has, not counting '...'.
2817 unsigned NumArgs : 15;
2819 /// NumExceptions - The number of types in the exception spec, if any.
2820 unsigned NumExceptions : 9;
2822 /// ExceptionSpecType - The type of exception specification this function has.
2823 unsigned ExceptionSpecType : 3;
2825 /// HasAnyConsumedArgs - Whether this function has any consumed arguments.
2826 unsigned HasAnyConsumedArgs : 1;
2828 /// Variadic - Whether the function is variadic.
2829 unsigned Variadic : 1;
2831 /// HasTrailingReturn - Whether this function has a trailing return type.
2832 unsigned HasTrailingReturn : 1;
2834 /// \brief The ref-qualifier associated with a \c FunctionProtoType.
2836 /// This is a value of type \c RefQualifierKind.
2837 unsigned RefQualifier : 2;
2839 // ArgInfo - There is an variable size array after the class in memory that
2840 // holds the argument types.
2842 // Exceptions - There is another variable size array after ArgInfo that
2843 // holds the exception types.
2845 // NoexceptExpr - Instead of Exceptions, there may be a single Expr* pointing
2846 // to the expression in the noexcept() specifier.
2848 // ExceptionSpecDecl, ExceptionSpecTemplate - Instead of Exceptions, there may
2849 // be a pair of FunctionDecl* pointing to the function which should be used to
2850 // instantiate this function type's exception specification, and the function
2851 // from which it should be instantiated.
2853 // ConsumedArgs - A variable size array, following Exceptions
2854 // and of length NumArgs, holding flags indicating which arguments
2855 // are consumed. This only appears if HasAnyConsumedArgs is true.
2857 friend class ASTContext; // ASTContext creates these.
2859 const bool *getConsumedArgsBuffer() const {
2860 assert(hasAnyConsumedArgs());
2862 // Find the end of the exceptions.
2863 Expr * const *eh_end = reinterpret_cast<Expr * const *>(arg_type_end());
2864 if (getExceptionSpecType() != EST_ComputedNoexcept)
2865 eh_end += NumExceptions;
2867 eh_end += 1; // NoexceptExpr
2869 return reinterpret_cast<const bool*>(eh_end);
2873 unsigned getNumArgs() const { return NumArgs; }
2874 QualType getArgType(unsigned i) const {
2875 assert(i < NumArgs && "Invalid argument number!");
2876 return arg_type_begin()[i];
2878 ArrayRef<QualType> getArgTypes() const {
2879 return ArrayRef<QualType>(arg_type_begin(), arg_type_end());
2882 ExtProtoInfo getExtProtoInfo() const {
2884 EPI.ExtInfo = getExtInfo();
2885 EPI.Variadic = isVariadic();
2886 EPI.HasTrailingReturn = hasTrailingReturn();
2887 EPI.ExceptionSpecType = getExceptionSpecType();
2888 EPI.TypeQuals = static_cast<unsigned char>(getTypeQuals());
2889 EPI.RefQualifier = getRefQualifier();
2890 if (EPI.ExceptionSpecType == EST_Dynamic) {
2891 EPI.NumExceptions = NumExceptions;
2892 EPI.Exceptions = exception_begin();
2893 } else if (EPI.ExceptionSpecType == EST_ComputedNoexcept) {
2894 EPI.NoexceptExpr = getNoexceptExpr();
2895 } else if (EPI.ExceptionSpecType == EST_Uninstantiated) {
2896 EPI.ExceptionSpecDecl = getExceptionSpecDecl();
2897 EPI.ExceptionSpecTemplate = getExceptionSpecTemplate();
2898 } else if (EPI.ExceptionSpecType == EST_Unevaluated) {
2899 EPI.ExceptionSpecDecl = getExceptionSpecDecl();
2901 if (hasAnyConsumedArgs())
2902 EPI.ConsumedArguments = getConsumedArgsBuffer();
2906 /// \brief Get the kind of exception specification on this function.
2907 ExceptionSpecificationType getExceptionSpecType() const {
2908 return static_cast<ExceptionSpecificationType>(ExceptionSpecType);
2910 /// \brief Return whether this function has any kind of exception spec.
2911 bool hasExceptionSpec() const {
2912 return getExceptionSpecType() != EST_None;
2914 /// \brief Return whether this function has a dynamic (throw) exception spec.
2915 bool hasDynamicExceptionSpec() const {
2916 return isDynamicExceptionSpec(getExceptionSpecType());
2918 /// \brief Return whether this function has a noexcept exception spec.
2919 bool hasNoexceptExceptionSpec() const {
2920 return isNoexceptExceptionSpec(getExceptionSpecType());
2922 /// \brief Result type of getNoexceptSpec().
2923 enum NoexceptResult {
2924 NR_NoNoexcept, ///< There is no noexcept specifier.
2925 NR_BadNoexcept, ///< The noexcept specifier has a bad expression.
2926 NR_Dependent, ///< The noexcept specifier is dependent.
2927 NR_Throw, ///< The noexcept specifier evaluates to false.
2928 NR_Nothrow ///< The noexcept specifier evaluates to true.
2930 /// \brief Get the meaning of the noexcept spec on this function, if any.
2931 NoexceptResult getNoexceptSpec(ASTContext &Ctx) const;
2932 unsigned getNumExceptions() const { return NumExceptions; }
2933 QualType getExceptionType(unsigned i) const {
2934 assert(i < NumExceptions && "Invalid exception number!");
2935 return exception_begin()[i];
2937 Expr *getNoexceptExpr() const {
2938 if (getExceptionSpecType() != EST_ComputedNoexcept)
2940 // NoexceptExpr sits where the arguments end.
2941 return *reinterpret_cast<Expr *const *>(arg_type_end());
2943 /// \brief If this function type has an exception specification which hasn't
2944 /// been determined yet (either because it has not been evaluated or because
2945 /// it has not been instantiated), this is the function whose exception
2946 /// specification is represented by this type.
2947 FunctionDecl *getExceptionSpecDecl() const {
2948 if (getExceptionSpecType() != EST_Uninstantiated &&
2949 getExceptionSpecType() != EST_Unevaluated)
2951 return reinterpret_cast<FunctionDecl * const *>(arg_type_end())[0];
2953 /// \brief If this function type has an uninstantiated exception
2954 /// specification, this is the function whose exception specification
2955 /// should be instantiated to find the exception specification for
2957 FunctionDecl *getExceptionSpecTemplate() const {
2958 if (getExceptionSpecType() != EST_Uninstantiated)
2960 return reinterpret_cast<FunctionDecl * const *>(arg_type_end())[1];
2962 bool isNothrow(ASTContext &Ctx) const {
2963 ExceptionSpecificationType EST = getExceptionSpecType();
2964 assert(EST != EST_Unevaluated && EST != EST_Uninstantiated);
2965 if (EST == EST_DynamicNone || EST == EST_BasicNoexcept)
2967 if (EST != EST_ComputedNoexcept)
2969 return getNoexceptSpec(Ctx) == NR_Nothrow;
2972 bool isVariadic() const { return Variadic; }
2974 /// \brief Determines whether this function prototype contains a
2975 /// parameter pack at the end.
2977 /// A function template whose last parameter is a parameter pack can be
2978 /// called with an arbitrary number of arguments, much like a variadic
2980 bool isTemplateVariadic() const;
2982 bool hasTrailingReturn() const { return HasTrailingReturn; }
2984 unsigned getTypeQuals() const { return FunctionType::getTypeQuals(); }
2987 /// \brief Retrieve the ref-qualifier associated with this function type.
2988 RefQualifierKind getRefQualifier() const {
2989 return static_cast<RefQualifierKind>(RefQualifier);
2992 typedef const QualType *arg_type_iterator;
2993 arg_type_iterator arg_type_begin() const {
2994 return reinterpret_cast<const QualType *>(this+1);
2996 arg_type_iterator arg_type_end() const { return arg_type_begin()+NumArgs; }
2998 typedef const QualType *exception_iterator;
2999 exception_iterator exception_begin() const {
3000 // exceptions begin where arguments end
3001 return arg_type_end();
3003 exception_iterator exception_end() const {
3004 if (getExceptionSpecType() != EST_Dynamic)
3005 return exception_begin();
3006 return exception_begin() + NumExceptions;
3009 bool hasAnyConsumedArgs() const {
3010 return HasAnyConsumedArgs;
3012 bool isArgConsumed(unsigned I) const {
3013 assert(I < getNumArgs() && "argument index out of range!");
3014 if (hasAnyConsumedArgs())
3015 return getConsumedArgsBuffer()[I];
3019 bool isSugared() const { return false; }
3020 QualType desugar() const { return QualType(this, 0); }
3022 void printExceptionSpecification(raw_ostream &OS,
3023 const PrintingPolicy &Policy) const;
3025 static bool classof(const Type *T) {
3026 return T->getTypeClass() == FunctionProto;
3029 void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Ctx);
3030 static void Profile(llvm::FoldingSetNodeID &ID, QualType Result,
3031 arg_type_iterator ArgTys, unsigned NumArgs,
3032 const ExtProtoInfo &EPI, const ASTContext &Context);
3036 /// \brief Represents the dependent type named by a dependently-scoped
3037 /// typename using declaration, e.g.
3038 /// using typename Base<T>::foo;
3039 /// Template instantiation turns these into the underlying type.
3040 class UnresolvedUsingType : public Type {
3041 UnresolvedUsingTypenameDecl *Decl;
3043 UnresolvedUsingType(const UnresolvedUsingTypenameDecl *D)
3044 : Type(UnresolvedUsing, QualType(), true, true, false,
3045 /*ContainsUnexpandedParameterPack=*/false),
3046 Decl(const_cast<UnresolvedUsingTypenameDecl*>(D)) {}
3047 friend class ASTContext; // ASTContext creates these.
3050 UnresolvedUsingTypenameDecl *getDecl() const { return Decl; }
3052 bool isSugared() const { return false; }
3053 QualType desugar() const { return QualType(this, 0); }
3055 static bool classof(const Type *T) {
3056 return T->getTypeClass() == UnresolvedUsing;
3059 void Profile(llvm::FoldingSetNodeID &ID) {
3060 return Profile(ID, Decl);
3062 static void Profile(llvm::FoldingSetNodeID &ID,
3063 UnresolvedUsingTypenameDecl *D) {
3069 class TypedefType : public Type {
3070 TypedefNameDecl *Decl;
3072 TypedefType(TypeClass tc, const TypedefNameDecl *D, QualType can)
3073 : Type(tc, can, can->isDependentType(),
3074 can->isInstantiationDependentType(),
3075 can->isVariablyModifiedType(),
3076 /*ContainsUnexpandedParameterPack=*/false),
3077 Decl(const_cast<TypedefNameDecl*>(D)) {
3078 assert(!isa<TypedefType>(can) && "Invalid canonical type");
3080 friend class ASTContext; // ASTContext creates these.
3083 TypedefNameDecl *getDecl() const { return Decl; }
3085 bool isSugared() const { return true; }
3086 QualType desugar() const;
3088 static bool classof(const Type *T) { return T->getTypeClass() == Typedef; }
3091 /// TypeOfExprType (GCC extension).
3092 class TypeOfExprType : public Type {
3096 TypeOfExprType(Expr *E, QualType can = QualType());
3097 friend class ASTContext; // ASTContext creates these.
3099 Expr *getUnderlyingExpr() const { return TOExpr; }
3101 /// \brief Remove a single level of sugar.
3102 QualType desugar() const;
3104 /// \brief Returns whether this type directly provides sugar.
3105 bool isSugared() const;
3107 static bool classof(const Type *T) { return T->getTypeClass() == TypeOfExpr; }
3110 /// \brief Internal representation of canonical, dependent
3111 /// typeof(expr) types.
3113 /// This class is used internally by the ASTContext to manage
3114 /// canonical, dependent types, only. Clients will only see instances
3115 /// of this class via TypeOfExprType nodes.
3116 class DependentTypeOfExprType
3117 : public TypeOfExprType, public llvm::FoldingSetNode {
3118 const ASTContext &Context;
3121 DependentTypeOfExprType(const ASTContext &Context, Expr *E)
3122 : TypeOfExprType(E), Context(Context) { }
3124 void Profile(llvm::FoldingSetNodeID &ID) {
3125 Profile(ID, Context, getUnderlyingExpr());
3128 static void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context,
3132 /// TypeOfType (GCC extension).
3133 class TypeOfType : public Type {
3135 TypeOfType(QualType T, QualType can)
3136 : Type(TypeOf, can, T->isDependentType(),
3137 T->isInstantiationDependentType(),
3138 T->isVariablyModifiedType(),
3139 T->containsUnexpandedParameterPack()),
3141 assert(!isa<TypedefType>(can) && "Invalid canonical type");
3143 friend class ASTContext; // ASTContext creates these.
3145 QualType getUnderlyingType() const { return TOType; }
3147 /// \brief Remove a single level of sugar.
3148 QualType desugar() const { return getUnderlyingType(); }
3150 /// \brief Returns whether this type directly provides sugar.
3151 bool isSugared() const { return true; }
3153 static bool classof(const Type *T) { return T->getTypeClass() == TypeOf; }
3156 /// DecltypeType (C++0x)
3157 class DecltypeType : public Type {
3159 QualType UnderlyingType;
3162 DecltypeType(Expr *E, QualType underlyingType, QualType can = QualType());
3163 friend class ASTContext; // ASTContext creates these.
3165 Expr *getUnderlyingExpr() const { return E; }
3166 QualType getUnderlyingType() const { return UnderlyingType; }
3168 /// \brief Remove a single level of sugar.
3169 QualType desugar() const;
3171 /// \brief Returns whether this type directly provides sugar.
3172 bool isSugared() const;
3174 static bool classof(const Type *T) { return T->getTypeClass() == Decltype; }
3177 /// \brief Internal representation of canonical, dependent
3178 /// decltype(expr) types.
3180 /// This class is used internally by the ASTContext to manage
3181 /// canonical, dependent types, only. Clients will only see instances
3182 /// of this class via DecltypeType nodes.
3183 class DependentDecltypeType : public DecltypeType, public llvm::FoldingSetNode {
3184 const ASTContext &Context;
3187 DependentDecltypeType(const ASTContext &Context, Expr *E);
3189 void Profile(llvm::FoldingSetNodeID &ID) {
3190 Profile(ID, Context, getUnderlyingExpr());
3193 static void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context,
3197 /// \brief A unary type transform, which is a type constructed from another
3198 class UnaryTransformType : public Type {
3205 /// The untransformed type.
3207 /// The transformed type if not dependent, otherwise the same as BaseType.
3208 QualType UnderlyingType;
3212 UnaryTransformType(QualType BaseTy, QualType UnderlyingTy, UTTKind UKind,
3213 QualType CanonicalTy);
3214 friend class ASTContext;
3216 bool isSugared() const { return !isDependentType(); }
3217 QualType desugar() const { return UnderlyingType; }
3219 QualType getUnderlyingType() const { return UnderlyingType; }
3220 QualType getBaseType() const { return BaseType; }
3222 UTTKind getUTTKind() const { return UKind; }
3224 static bool classof(const Type *T) {
3225 return T->getTypeClass() == UnaryTransform;
3229 class TagType : public Type {
3230 /// Stores the TagDecl associated with this type. The decl may point to any
3231 /// TagDecl that declares the entity.
3234 friend class ASTReader;
3237 TagType(TypeClass TC, const TagDecl *D, QualType can);
3240 TagDecl *getDecl() const;
3242 /// @brief Determines whether this type is in the process of being
3244 bool isBeingDefined() const;
3246 static bool classof(const Type *T) {
3247 return T->getTypeClass() >= TagFirst && T->getTypeClass() <= TagLast;
3251 /// RecordType - This is a helper class that allows the use of isa/cast/dyncast
3252 /// to detect TagType objects of structs/unions/classes.
3253 class RecordType : public TagType {
3255 explicit RecordType(const RecordDecl *D)
3256 : TagType(Record, reinterpret_cast<const TagDecl*>(D), QualType()) { }
3257 explicit RecordType(TypeClass TC, RecordDecl *D)
3258 : TagType(TC, reinterpret_cast<const TagDecl*>(D), QualType()) { }
3259 friend class ASTContext; // ASTContext creates these.
3262 RecordDecl *getDecl() const {
3263 return reinterpret_cast<RecordDecl*>(TagType::getDecl());
3266 // FIXME: This predicate is a helper to QualType/Type. It needs to
3267 // recursively check all fields for const-ness. If any field is declared
3268 // const, it needs to return false.
3269 bool hasConstFields() const { return false; }
3271 bool isSugared() const { return false; }
3272 QualType desugar() const { return QualType(this, 0); }
3274 static bool classof(const Type *T) { return T->getTypeClass() == Record; }
3277 /// EnumType - This is a helper class that allows the use of isa/cast/dyncast
3278 /// to detect TagType objects of enums.
3279 class EnumType : public TagType {
3280 explicit EnumType(const EnumDecl *D)
3281 : TagType(Enum, reinterpret_cast<const TagDecl*>(D), QualType()) { }
3282 friend class ASTContext; // ASTContext creates these.
3285 EnumDecl *getDecl() const {
3286 return reinterpret_cast<EnumDecl*>(TagType::getDecl());
3289 bool isSugared() const { return false; }
3290 QualType desugar() const { return QualType(this, 0); }
3292 static bool classof(const Type *T) { return T->getTypeClass() == Enum; }
3295 /// AttributedType - An attributed type is a type to which a type
3296 /// attribute has been applied. The "modified type" is the
3297 /// fully-sugared type to which the attributed type was applied;
3298 /// generally it is not canonically equivalent to the attributed type.
3299 /// The "equivalent type" is the minimally-desugared type which the
3300 /// type is canonically equivalent to.
3302 /// For example, in the following attributed type:
3303 /// int32_t __attribute__((vector_size(16)))
3304 /// - the modified type is the TypedefType for int32_t
3305 /// - the equivalent type is VectorType(16, int32_t)
3306 /// - the canonical type is VectorType(16, int)
3307 class AttributedType : public Type, public llvm::FoldingSetNode {
3309 // It is really silly to have yet another attribute-kind enum, but
3310 // clang::attr::Kind doesn't currently cover the pure type attrs.
3312 // Expression operand.
3316 attr_neon_vector_type,
3317 attr_neon_polyvector_type,
3319 FirstExprOperandKind = attr_address_space,
3320 LastExprOperandKind = attr_neon_polyvector_type,
3322 // Enumerated operand (string or keyword).
3324 attr_objc_ownership,
3327 FirstEnumOperandKind = attr_objc_gc,
3328 LastEnumOperandKind = attr_pcs,
3342 QualType ModifiedType;
3343 QualType EquivalentType;
3345 friend class ASTContext; // creates these
3347 AttributedType(QualType canon, Kind attrKind,
3348 QualType modified, QualType equivalent)
3349 : Type(Attributed, canon, canon->isDependentType(),
3350 canon->isInstantiationDependentType(),
3351 canon->isVariablyModifiedType(),
3352 canon->containsUnexpandedParameterPack()),
3353 ModifiedType(modified), EquivalentType(equivalent) {
3354 AttributedTypeBits.AttrKind = attrKind;
3358 Kind getAttrKind() const {
3359 return static_cast<Kind>(AttributedTypeBits.AttrKind);
3362 QualType getModifiedType() const { return ModifiedType; }
3363 QualType getEquivalentType() const { return EquivalentType; }
3365 bool isSugared() const { return true; }
3366 QualType desugar() const { return getEquivalentType(); }
3368 void Profile(llvm::FoldingSetNodeID &ID) {
3369 Profile(ID, getAttrKind(), ModifiedType, EquivalentType);
3372 static void Profile(llvm::FoldingSetNodeID &ID, Kind attrKind,
3373 QualType modified, QualType equivalent) {
3374 ID.AddInteger(attrKind);
3375 ID.AddPointer(modified.getAsOpaquePtr());
3376 ID.AddPointer(equivalent.getAsOpaquePtr());
3379 static bool classof(const Type *T) {
3380 return T->getTypeClass() == Attributed;
3384 class TemplateTypeParmType : public Type, public llvm::FoldingSetNode {
3385 // Helper data collector for canonical types.
3386 struct CanonicalTTPTInfo {
3387 unsigned Depth : 15;
3388 unsigned ParameterPack : 1;
3389 unsigned Index : 16;
3393 // Info for the canonical type.
3394 CanonicalTTPTInfo CanTTPTInfo;
3395 // Info for the non-canonical type.
3396 TemplateTypeParmDecl *TTPDecl;
3399 /// Build a non-canonical type.
3400 TemplateTypeParmType(TemplateTypeParmDecl *TTPDecl, QualType Canon)
3401 : Type(TemplateTypeParm, Canon, /*Dependent=*/true,
3402 /*InstantiationDependent=*/true,
3403 /*VariablyModified=*/false,
3404 Canon->containsUnexpandedParameterPack()),
3405 TTPDecl(TTPDecl) { }
3407 /// Build the canonical type.
3408 TemplateTypeParmType(unsigned D, unsigned I, bool PP)
3409 : Type(TemplateTypeParm, QualType(this, 0),
3411 /*InstantiationDependent=*/true,
3412 /*VariablyModified=*/false, PP) {
3413 CanTTPTInfo.Depth = D;
3414 CanTTPTInfo.Index = I;
3415 CanTTPTInfo.ParameterPack = PP;
3418 friend class ASTContext; // ASTContext creates these
3420 const CanonicalTTPTInfo& getCanTTPTInfo() const {
3421 QualType Can = getCanonicalTypeInternal();
3422 return Can->castAs<TemplateTypeParmType>()->CanTTPTInfo;
3426 unsigned getDepth() const { return getCanTTPTInfo().Depth; }
3427 unsigned getIndex() const { return getCanTTPTInfo().Index; }
3428 bool isParameterPack() const { return getCanTTPTInfo().ParameterPack; }
3430 TemplateTypeParmDecl *getDecl() const {
3431 return isCanonicalUnqualified() ? 0 : TTPDecl;
3434 IdentifierInfo *getIdentifier() const;
3436 bool isSugared() const { return false; }
3437 QualType desugar() const { return QualType(this, 0); }
3439 void Profile(llvm::FoldingSetNodeID &ID) {
3440 Profile(ID, getDepth(), getIndex(), isParameterPack(), getDecl());
3443 static void Profile(llvm::FoldingSetNodeID &ID, unsigned Depth,
3444 unsigned Index, bool ParameterPack,
3445 TemplateTypeParmDecl *TTPDecl) {
3446 ID.AddInteger(Depth);
3447 ID.AddInteger(Index);
3448 ID.AddBoolean(ParameterPack);
3449 ID.AddPointer(TTPDecl);
3452 static bool classof(const Type *T) {
3453 return T->getTypeClass() == TemplateTypeParm;
3457 /// \brief Represents the result of substituting a type for a template
3460 /// Within an instantiated template, all template type parameters have
3461 /// been replaced with these. They are used solely to record that a
3462 /// type was originally written as a template type parameter;
3463 /// therefore they are never canonical.
3464 class SubstTemplateTypeParmType : public Type, public llvm::FoldingSetNode {
3465 // The original type parameter.
3466 const TemplateTypeParmType *Replaced;
3468 SubstTemplateTypeParmType(const TemplateTypeParmType *Param, QualType Canon)
3469 : Type(SubstTemplateTypeParm, Canon, Canon->isDependentType(),
3470 Canon->isInstantiationDependentType(),
3471 Canon->isVariablyModifiedType(),
3472 Canon->containsUnexpandedParameterPack()),
3475 friend class ASTContext;
3478 /// Gets the template parameter that was substituted for.
3479 const TemplateTypeParmType *getReplacedParameter() const {
3483 /// Gets the type that was substituted for the template
3485 QualType getReplacementType() const {
3486 return getCanonicalTypeInternal();
3489 bool isSugared() const { return true; }
3490 QualType desugar() const { return getReplacementType(); }
3492 void Profile(llvm::FoldingSetNodeID &ID) {
3493 Profile(ID, getReplacedParameter(), getReplacementType());
3495 static void Profile(llvm::FoldingSetNodeID &ID,
3496 const TemplateTypeParmType *Replaced,
3497 QualType Replacement) {
3498 ID.AddPointer(Replaced);
3499 ID.AddPointer(Replacement.getAsOpaquePtr());
3502 static bool classof(const Type *T) {
3503 return T->getTypeClass() == SubstTemplateTypeParm;
3507 /// \brief Represents the result of substituting a set of types for a template
3508 /// type parameter pack.
3510 /// When a pack expansion in the source code contains multiple parameter packs
3511 /// and those parameter packs correspond to different levels of template
3512 /// parameter lists, this type node is used to represent a template type
3513 /// parameter pack from an outer level, which has already had its argument pack
3514 /// substituted but that still lives within a pack expansion that itself
3515 /// could not be instantiated. When actually performing a substitution into
3516 /// that pack expansion (e.g., when all template parameters have corresponding
3517 /// arguments), this type will be replaced with the \c SubstTemplateTypeParmType
3518 /// at the current pack substitution index.
3519 class SubstTemplateTypeParmPackType : public Type, public llvm::FoldingSetNode {
3520 /// \brief The original type parameter.
3521 const TemplateTypeParmType *Replaced;
3523 /// \brief A pointer to the set of template arguments that this
3524 /// parameter pack is instantiated with.
3525 const TemplateArgument *Arguments;
3527 /// \brief The number of template arguments in \c Arguments.
3528 unsigned NumArguments;
3530 SubstTemplateTypeParmPackType(const TemplateTypeParmType *Param,
3532 const TemplateArgument &ArgPack);
3534 friend class ASTContext;
3537 IdentifierInfo *getIdentifier() const { return Replaced->getIdentifier(); }
3539 /// Gets the template parameter that was substituted for.
3540 const TemplateTypeParmType *getReplacedParameter() const {
3544 bool isSugared() const { return false; }
3545 QualType desugar() const { return QualType(this, 0); }
3547 TemplateArgument getArgumentPack() const;
3549 void Profile(llvm::FoldingSetNodeID &ID);
3550 static void Profile(llvm::FoldingSetNodeID &ID,
3551 const TemplateTypeParmType *Replaced,
3552 const TemplateArgument &ArgPack);
3554 static bool classof(const Type *T) {
3555 return T->getTypeClass() == SubstTemplateTypeParmPack;
3559 /// \brief Represents a C++11 auto or C++1y decltype(auto) type.
3561 /// These types are usually a placeholder for a deduced type. However, before
3562 /// the initializer is attached, or if the initializer is type-dependent, there
3563 /// is no deduced type and an auto type is canonical. In the latter case, it is
3564 /// also a dependent type.
3565 class AutoType : public Type, public llvm::FoldingSetNode {
3566 AutoType(QualType DeducedType, bool IsDecltypeAuto, bool IsDependent)
3567 : Type(Auto, DeducedType.isNull() ? QualType(this, 0) : DeducedType,
3568 /*Dependent=*/IsDependent, /*InstantiationDependent=*/IsDependent,
3569 /*VariablyModified=*/false, /*ContainsParameterPack=*/false) {
3570 assert((DeducedType.isNull() || !IsDependent) &&
3571 "auto deduced to dependent type");
3572 AutoTypeBits.IsDecltypeAuto = IsDecltypeAuto;
3575 friend class ASTContext; // ASTContext creates these
3578 bool isDecltypeAuto() const { return AutoTypeBits.IsDecltypeAuto; }
3580 bool isSugared() const { return !isCanonicalUnqualified(); }
3581 QualType desugar() const { return getCanonicalTypeInternal(); }
3583 /// \brief Get the type deduced for this auto type, or null if it's either
3584 /// not been deduced or was deduced to a dependent type.
3585 QualType getDeducedType() const {
3586 return !isCanonicalUnqualified() ? getCanonicalTypeInternal() : QualType();
3588 bool isDeduced() const {
3589 return !isCanonicalUnqualified() || isDependentType();
3592 void Profile(llvm::FoldingSetNodeID &ID) {
3593 Profile(ID, getDeducedType(), isDecltypeAuto(), isDependentType());
3596 static void Profile(llvm::FoldingSetNodeID &ID, QualType Deduced,
3597 bool IsDecltypeAuto, bool IsDependent) {
3598 ID.AddPointer(Deduced.getAsOpaquePtr());
3599 ID.AddBoolean(IsDecltypeAuto);
3600 ID.AddBoolean(IsDependent);
3603 static bool classof(const Type *T) {
3604 return T->getTypeClass() == Auto;
3608 /// \brief Represents a type template specialization; the template
3609 /// must be a class template, a type alias template, or a template
3610 /// template parameter. A template which cannot be resolved to one of
3611 /// these, e.g. because it is written with a dependent scope
3612 /// specifier, is instead represented as a
3613 /// @c DependentTemplateSpecializationType.
3615 /// A non-dependent template specialization type is always "sugar",
3616 /// typically for a @c RecordType. For example, a class template
3617 /// specialization type of @c vector<int> will refer to a tag type for
3618 /// the instantiation @c std::vector<int, std::allocator<int>>
3620 /// Template specializations are dependent if either the template or
3621 /// any of the template arguments are dependent, in which case the
3622 /// type may also be canonical.
3624 /// Instances of this type are allocated with a trailing array of
3625 /// TemplateArguments, followed by a QualType representing the
3626 /// non-canonical aliased type when the template is a type alias
3628 class TemplateSpecializationType
3629 : public Type, public llvm::FoldingSetNode {
3630 /// \brief The name of the template being specialized. This is
3631 /// either a TemplateName::Template (in which case it is a
3632 /// ClassTemplateDecl*, a TemplateTemplateParmDecl*, or a
3633 /// TypeAliasTemplateDecl*), a
3634 /// TemplateName::SubstTemplateTemplateParmPack, or a
3635 /// TemplateName::SubstTemplateTemplateParm (in which case the
3636 /// replacement must, recursively, be one of these).
3637 TemplateName Template;
3639 /// \brief - The number of template arguments named in this class
3640 /// template specialization.
3641 unsigned NumArgs : 31;
3643 /// \brief Whether this template specialization type is a substituted
3647 TemplateSpecializationType(TemplateName T,
3648 const TemplateArgument *Args,
3649 unsigned NumArgs, QualType Canon,
3652 friend class ASTContext; // ASTContext creates these
3655 /// \brief Determine whether any of the given template arguments are
3657 static bool anyDependentTemplateArguments(const TemplateArgument *Args,
3659 bool &InstantiationDependent);
3661 static bool anyDependentTemplateArguments(const TemplateArgumentLoc *Args,
3663 bool &InstantiationDependent);
3665 static bool anyDependentTemplateArguments(const TemplateArgumentListInfo &,
3666 bool &InstantiationDependent);
3668 /// \brief Print a template argument list, including the '<' and '>'
3669 /// enclosing the template arguments.
3670 static void PrintTemplateArgumentList(raw_ostream &OS,
3671 const TemplateArgument *Args,
3673 const PrintingPolicy &Policy,
3674 bool SkipBrackets = false);
3676 static void PrintTemplateArgumentList(raw_ostream &OS,
3677 const TemplateArgumentLoc *Args,
3679 const PrintingPolicy &Policy);
3681 static void PrintTemplateArgumentList(raw_ostream &OS,
3682 const TemplateArgumentListInfo &,
3683 const PrintingPolicy &Policy);
3685 /// True if this template specialization type matches a current
3686 /// instantiation in the context in which it is found.
3687 bool isCurrentInstantiation() const {
3688 return isa<InjectedClassNameType>(getCanonicalTypeInternal());
3691 /// \brief Determine if this template specialization type is for a type alias
3692 /// template that has been substituted.
3694 /// Nearly every template specialization type whose template is an alias
3695 /// template will be substituted. However, this is not the case when
3696 /// the specialization contains a pack expansion but the template alias
3697 /// does not have a corresponding parameter pack, e.g.,
3700 /// template<typename T, typename U, typename V> struct S;
3701 /// template<typename T, typename U> using A = S<T, int, U>;
3702 /// template<typename... Ts> struct X {
3703 /// typedef A<Ts...> type; // not a type alias
3706 bool isTypeAlias() const { return TypeAlias; }
3708 /// Get the aliased type, if this is a specialization of a type alias
3710 QualType getAliasedType() const {
3711 assert(isTypeAlias() && "not a type alias template specialization");
3712 return *reinterpret_cast<const QualType*>(end());
3715 typedef const TemplateArgument * iterator;
3717 iterator begin() const { return getArgs(); }
3718 iterator end() const; // defined inline in TemplateBase.h
3720 /// \brief Retrieve the name of the template that we are specializing.
3721 TemplateName getTemplateName() const { return Template; }
3723 /// \brief Retrieve the template arguments.
3724 const TemplateArgument *getArgs() const {
3725 return reinterpret_cast<const TemplateArgument *>(this + 1);
3728 /// \brief Retrieve the number of template arguments.
3729 unsigned getNumArgs() const { return NumArgs; }
3731 /// \brief Retrieve a specific template argument as a type.
3732 /// \pre @c isArgType(Arg)
3733 const TemplateArgument &getArg(unsigned Idx) const; // in TemplateBase.h
3735 bool isSugared() const {
3736 return !isDependentType() || isCurrentInstantiation() || isTypeAlias();
3738 QualType desugar() const { return getCanonicalTypeInternal(); }
3740 void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Ctx) {
3741 Profile(ID, Template, getArgs(), NumArgs, Ctx);
3743 getAliasedType().Profile(ID);
3746 static void Profile(llvm::FoldingSetNodeID &ID, TemplateName T,
3747 const TemplateArgument *Args,
3749 const ASTContext &Context);
3751 static bool classof(const Type *T) {
3752 return T->getTypeClass() == TemplateSpecialization;
3756 /// \brief The injected class name of a C++ class template or class
3757 /// template partial specialization. Used to record that a type was
3758 /// spelled with a bare identifier rather than as a template-id; the
3759 /// equivalent for non-templated classes is just RecordType.
3761 /// Injected class name types are always dependent. Template
3762 /// instantiation turns these into RecordTypes.
3764 /// Injected class name types are always canonical. This works
3765 /// because it is impossible to compare an injected class name type
3766 /// with the corresponding non-injected template type, for the same
3767 /// reason that it is impossible to directly compare template
3768 /// parameters from different dependent contexts: injected class name
3769 /// types can only occur within the scope of a particular templated
3770 /// declaration, and within that scope every template specialization
3771 /// will canonicalize to the injected class name (when appropriate
3772 /// according to the rules of the language).
3773 class InjectedClassNameType : public Type {
3774 CXXRecordDecl *Decl;
3776 /// The template specialization which this type represents.
3778 /// template <class T> class A { ... };
3779 /// this is A<T>, whereas in
3780 /// template <class X, class Y> class A<B<X,Y> > { ... };
3781 /// this is A<B<X,Y> >.
3783 /// It is always unqualified, always a template specialization type,
3784 /// and always dependent.
3785 QualType InjectedType;
3787 friend class ASTContext; // ASTContext creates these.
3788 friend class ASTReader; // FIXME: ASTContext::getInjectedClassNameType is not
3789 // currently suitable for AST reading, too much
3790 // interdependencies.
3791 InjectedClassNameType(CXXRecordDecl *D, QualType TST)
3792 : Type(InjectedClassName, QualType(), /*Dependent=*/true,
3793 /*InstantiationDependent=*/true,
3794 /*VariablyModified=*/false,
3795 /*ContainsUnexpandedParameterPack=*/false),
3796 Decl(D), InjectedType(TST) {
3797 assert(isa<TemplateSpecializationType>(TST));
3798 assert(!TST.hasQualifiers());
3799 assert(TST->isDependentType());
3803 QualType getInjectedSpecializationType() const { return InjectedType; }
3804 const TemplateSpecializationType *getInjectedTST() const {
3805 return cast<TemplateSpecializationType>(InjectedType.getTypePtr());
3808 CXXRecordDecl *getDecl() const;
3810 bool isSugared() const { return false; }
3811 QualType desugar() const { return QualType(this, 0); }
3813 static bool classof(const Type *T) {
3814 return T->getTypeClass() == InjectedClassName;
3818 /// \brief The kind of a tag type.
3820 /// \brief The "struct" keyword.
3822 /// \brief The "__interface" keyword.
3824 /// \brief The "union" keyword.
3826 /// \brief The "class" keyword.
3828 /// \brief The "enum" keyword.
3832 /// \brief The elaboration keyword that precedes a qualified type name or
3833 /// introduces an elaborated-type-specifier.
3834 enum ElaboratedTypeKeyword {
3835 /// \brief The "struct" keyword introduces the elaborated-type-specifier.
3837 /// \brief The "__interface" keyword introduces the elaborated-type-specifier.
3839 /// \brief The "union" keyword introduces the elaborated-type-specifier.
3841 /// \brief The "class" keyword introduces the elaborated-type-specifier.
3843 /// \brief The "enum" keyword introduces the elaborated-type-specifier.
3845 /// \brief The "typename" keyword precedes the qualified type name, e.g.,
3846 /// \c typename T::type.
3848 /// \brief No keyword precedes the qualified type name.
3852 /// A helper class for Type nodes having an ElaboratedTypeKeyword.
3853 /// The keyword in stored in the free bits of the base class.
3854 /// Also provides a few static helpers for converting and printing
3855 /// elaborated type keyword and tag type kind enumerations.
3856 class TypeWithKeyword : public Type {
3858 TypeWithKeyword(ElaboratedTypeKeyword Keyword, TypeClass tc,
3859 QualType Canonical, bool Dependent,
3860 bool InstantiationDependent, bool VariablyModified,
3861 bool ContainsUnexpandedParameterPack)
3862 : Type(tc, Canonical, Dependent, InstantiationDependent, VariablyModified,
3863 ContainsUnexpandedParameterPack) {
3864 TypeWithKeywordBits.Keyword = Keyword;
3868 ElaboratedTypeKeyword getKeyword() const {
3869 return static_cast<ElaboratedTypeKeyword>(TypeWithKeywordBits.Keyword);
3872 /// getKeywordForTypeSpec - Converts a type specifier (DeclSpec::TST)
3873 /// into an elaborated type keyword.
3874 static ElaboratedTypeKeyword getKeywordForTypeSpec(unsigned TypeSpec);
3876 /// getTagTypeKindForTypeSpec - Converts a type specifier (DeclSpec::TST)
3877 /// into a tag type kind. It is an error to provide a type specifier
3878 /// which *isn't* a tag kind here.
3879 static TagTypeKind getTagTypeKindForTypeSpec(unsigned TypeSpec);
3881 /// getKeywordForTagDeclKind - Converts a TagTypeKind into an
3882 /// elaborated type keyword.
3883 static ElaboratedTypeKeyword getKeywordForTagTypeKind(TagTypeKind Tag);
3885 /// getTagTypeKindForKeyword - Converts an elaborated type keyword into
3886 // a TagTypeKind. It is an error to provide an elaborated type keyword
3887 /// which *isn't* a tag kind here.
3888 static TagTypeKind getTagTypeKindForKeyword(ElaboratedTypeKeyword Keyword);
3890 static bool KeywordIsTagTypeKind(ElaboratedTypeKeyword Keyword);
3892 static const char *getKeywordName(ElaboratedTypeKeyword Keyword);
3894 static const char *getTagTypeKindName(TagTypeKind Kind) {
3895 return getKeywordName(getKeywordForTagTypeKind(Kind));
3898 class CannotCastToThisType {};
3899 static CannotCastToThisType classof(const Type *);
3902 /// \brief Represents a type that was referred to using an elaborated type
3903 /// keyword, e.g., struct S, or via a qualified name, e.g., N::M::type,
3906 /// This type is used to keep track of a type name as written in the
3907 /// source code, including tag keywords and any nested-name-specifiers.
3908 /// The type itself is always "sugar", used to express what was written
3909 /// in the source code but containing no additional semantic information.
3910 class ElaboratedType : public TypeWithKeyword, public llvm::FoldingSetNode {
3912 /// \brief The nested name specifier containing the qualifier.
3913 NestedNameSpecifier *NNS;
3915 /// \brief The type that this qualified name refers to.
3918 ElaboratedType(ElaboratedTypeKeyword Keyword, NestedNameSpecifier *NNS,
3919 QualType NamedType, QualType CanonType)
3920 : TypeWithKeyword(Keyword, Elaborated, CanonType,
3921 NamedType->isDependentType(),
3922 NamedType->isInstantiationDependentType(),
3923 NamedType->isVariablyModifiedType(),
3924 NamedType->containsUnexpandedParameterPack()),
3925 NNS(NNS), NamedType(NamedType) {
3926 assert(!(Keyword == ETK_None && NNS == 0) &&
3927 "ElaboratedType cannot have elaborated type keyword "
3928 "and name qualifier both null.");
3931 friend class ASTContext; // ASTContext creates these
3936 /// \brief Retrieve the qualification on this type.
3937 NestedNameSpecifier *getQualifier() const { return NNS; }
3939 /// \brief Retrieve the type named by the qualified-id.
3940 QualType getNamedType() const { return NamedType; }
3942 /// \brief Remove a single level of sugar.
3943 QualType desugar() const { return getNamedType(); }
3945 /// \brief Returns whether this type directly provides sugar.
3946 bool isSugared() const { return true; }
3948 void Profile(llvm::FoldingSetNodeID &ID) {
3949 Profile(ID, getKeyword(), NNS, NamedType);
3952 static void Profile(llvm::FoldingSetNodeID &ID, ElaboratedTypeKeyword Keyword,
3953 NestedNameSpecifier *NNS, QualType NamedType) {
3954 ID.AddInteger(Keyword);
3956 NamedType.Profile(ID);
3959 static bool classof(const Type *T) {
3960 return T->getTypeClass() == Elaborated;
3964 /// \brief Represents a qualified type name for which the type name is
3967 /// DependentNameType represents a class of dependent types that involve a
3968 /// dependent nested-name-specifier (e.g., "T::") followed by a (dependent)
3969 /// name of a type. The DependentNameType may start with a "typename" (for a
3970 /// typename-specifier), "class", "struct", "union", or "enum" (for a
3971 /// dependent elaborated-type-specifier), or nothing (in contexts where we
3972 /// know that we must be referring to a type, e.g., in a base class specifier).
3973 class DependentNameType : public TypeWithKeyword, public llvm::FoldingSetNode {
3975 /// \brief The nested name specifier containing the qualifier.
3976 NestedNameSpecifier *NNS;
3978 /// \brief The type that this typename specifier refers to.
3979 const IdentifierInfo *Name;
3981 DependentNameType(ElaboratedTypeKeyword Keyword, NestedNameSpecifier *NNS,
3982 const IdentifierInfo *Name, QualType CanonType)
3983 : TypeWithKeyword(Keyword, DependentName, CanonType, /*Dependent=*/true,
3984 /*InstantiationDependent=*/true,
3985 /*VariablyModified=*/false,
3986 NNS->containsUnexpandedParameterPack()),
3987 NNS(NNS), Name(Name) {
3988 assert(NNS->isDependent() &&
3989 "DependentNameType requires a dependent nested-name-specifier");
3992 friend class ASTContext; // ASTContext creates these
3995 /// \brief Retrieve the qualification on this type.
3996 NestedNameSpecifier *getQualifier() const { return NNS; }
3998 /// \brief Retrieve the type named by the typename specifier as an
4001 /// This routine will return a non-NULL identifier pointer when the
4002 /// form of the original typename was terminated by an identifier,
4003 /// e.g., "typename T::type".
4004 const IdentifierInfo *getIdentifier() const {
4008 bool isSugared() const { return false; }
4009 QualType desugar() const { return QualType(this, 0); }
4011 void Profile(llvm::FoldingSetNodeID &ID) {
4012 Profile(ID, getKeyword(), NNS, Name);
4015 static void Profile(llvm::FoldingSetNodeID &ID, ElaboratedTypeKeyword Keyword,
4016 NestedNameSpecifier *NNS, const IdentifierInfo *Name) {
4017 ID.AddInteger(Keyword);
4019 ID.AddPointer(Name);
4022 static bool classof(const Type *T) {
4023 return T->getTypeClass() == DependentName;
4027 /// DependentTemplateSpecializationType - Represents a template
4028 /// specialization type whose template cannot be resolved, e.g.
4029 /// A<T>::template B<T>
4030 class DependentTemplateSpecializationType :
4031 public TypeWithKeyword, public llvm::FoldingSetNode {
4033 /// \brief The nested name specifier containing the qualifier.
4034 NestedNameSpecifier *NNS;
4036 /// \brief The identifier of the template.
4037 const IdentifierInfo *Name;
4039 /// \brief - The number of template arguments named in this class
4040 /// template specialization.
4043 const TemplateArgument *getArgBuffer() const {
4044 return reinterpret_cast<const TemplateArgument*>(this+1);
4046 TemplateArgument *getArgBuffer() {
4047 return reinterpret_cast<TemplateArgument*>(this+1);
4050 DependentTemplateSpecializationType(ElaboratedTypeKeyword Keyword,
4051 NestedNameSpecifier *NNS,
4052 const IdentifierInfo *Name,
4054 const TemplateArgument *Args,
4057 friend class ASTContext; // ASTContext creates these
4060 NestedNameSpecifier *getQualifier() const { return NNS; }
4061 const IdentifierInfo *getIdentifier() const { return Name; }
4063 /// \brief Retrieve the template arguments.
4064 const TemplateArgument *getArgs() const {
4065 return getArgBuffer();
4068 /// \brief Retrieve the number of template arguments.
4069 unsigned getNumArgs() const { return NumArgs; }
4071 const TemplateArgument &getArg(unsigned Idx) const; // in TemplateBase.h
4073 typedef const TemplateArgument * iterator;
4074 iterator begin() const { return getArgs(); }
4075 iterator end() const; // inline in TemplateBase.h
4077 bool isSugared() const { return false; }
4078 QualType desugar() const { return QualType(this, 0); }
4080 void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context) {
4081 Profile(ID, Context, getKeyword(), NNS, Name, NumArgs, getArgs());
4084 static void Profile(llvm::FoldingSetNodeID &ID,
4085 const ASTContext &Context,
4086 ElaboratedTypeKeyword Keyword,
4087 NestedNameSpecifier *Qualifier,
4088 const IdentifierInfo *Name,
4090 const TemplateArgument *Args);
4092 static bool classof(const Type *T) {
4093 return T->getTypeClass() == DependentTemplateSpecialization;
4097 /// \brief Represents a pack expansion of types.
4099 /// Pack expansions are part of C++0x variadic templates. A pack
4100 /// expansion contains a pattern, which itself contains one or more
4101 /// "unexpanded" parameter packs. When instantiated, a pack expansion
4102 /// produces a series of types, each instantiated from the pattern of
4103 /// the expansion, where the Ith instantiation of the pattern uses the
4104 /// Ith arguments bound to each of the unexpanded parameter packs. The
4105 /// pack expansion is considered to "expand" these unexpanded
4106 /// parameter packs.
4109 /// template<typename ...Types> struct tuple;
4111 /// template<typename ...Types>
4112 /// struct tuple_of_references {
4113 /// typedef tuple<Types&...> type;
4117 /// Here, the pack expansion \c Types&... is represented via a
4118 /// PackExpansionType whose pattern is Types&.
4119 class PackExpansionType : public Type, public llvm::FoldingSetNode {
4120 /// \brief The pattern of the pack expansion.
4123 /// \brief The number of expansions that this pack expansion will
4124 /// generate when substituted (+1), or indicates that
4126 /// This field will only have a non-zero value when some of the parameter
4127 /// packs that occur within the pattern have been substituted but others have
4129 unsigned NumExpansions;
4131 PackExpansionType(QualType Pattern, QualType Canon,
4132 Optional<unsigned> NumExpansions)
4133 : Type(PackExpansion, Canon, /*Dependent=*/Pattern->isDependentType(),
4134 /*InstantiationDependent=*/true,
4135 /*VariableModified=*/Pattern->isVariablyModifiedType(),
4136 /*ContainsUnexpandedParameterPack=*/false),
4138 NumExpansions(NumExpansions? *NumExpansions + 1: 0) { }
4140 friend class ASTContext; // ASTContext creates these
4143 /// \brief Retrieve the pattern of this pack expansion, which is the
4144 /// type that will be repeatedly instantiated when instantiating the
4145 /// pack expansion itself.
4146 QualType getPattern() const { return Pattern; }
4148 /// \brief Retrieve the number of expansions that this pack expansion will
4149 /// generate, if known.
4150 Optional<unsigned> getNumExpansions() const {
4152 return NumExpansions - 1;
4157 bool isSugared() const { return false; }
4158 QualType desugar() const { return QualType(this, 0); }
4160 void Profile(llvm::FoldingSetNodeID &ID) {
4161 Profile(ID, getPattern(), getNumExpansions());
4164 static void Profile(llvm::FoldingSetNodeID &ID, QualType Pattern,
4165 Optional<unsigned> NumExpansions) {
4166 ID.AddPointer(Pattern.getAsOpaquePtr());
4167 ID.AddBoolean(NumExpansions.hasValue());
4169 ID.AddInteger(*NumExpansions);
4172 static bool classof(const Type *T) {
4173 return T->getTypeClass() == PackExpansion;
4177 /// ObjCObjectType - Represents a class type in Objective C.
4178 /// Every Objective C type is a combination of a base type and a
4179 /// list of protocols.
4181 /// Given the following declarations:
4187 /// 'C' is an ObjCInterfaceType C. It is sugar for an ObjCObjectType
4188 /// with base C and no protocols.
4190 /// 'C<P>' is an ObjCObjectType with base C and protocol list [P].
4192 /// 'id' is a TypedefType which is sugar for an ObjCPointerType whose
4193 /// pointee is an ObjCObjectType with base BuiltinType::ObjCIdType
4194 /// and no protocols.
4196 /// 'id<P>' is an ObjCPointerType whose pointee is an ObjCObjecType
4197 /// with base BuiltinType::ObjCIdType and protocol list [P]. Eventually
4198 /// this should get its own sugar class to better represent the source.
4199 class ObjCObjectType : public Type {
4200 // ObjCObjectType.NumProtocols - the number of protocols stored
4201 // after the ObjCObjectPointerType node.
4203 // These protocols are those written directly on the type. If
4204 // protocol qualifiers ever become additive, the iterators will need
4205 // to get kindof complicated.
4207 // In the canonical object type, these are sorted alphabetically
4210 /// Either a BuiltinType or an InterfaceType or sugar for either.
4213 ObjCProtocolDecl * const *getProtocolStorage() const {
4214 return const_cast<ObjCObjectType*>(this)->getProtocolStorage();
4217 ObjCProtocolDecl **getProtocolStorage();
4220 ObjCObjectType(QualType Canonical, QualType Base,
4221 ObjCProtocolDecl * const *Protocols, unsigned NumProtocols);
4223 enum Nonce_ObjCInterface { Nonce_ObjCInterface };
4224 ObjCObjectType(enum Nonce_ObjCInterface)
4225 : Type(ObjCInterface, QualType(), false, false, false, false),
4226 BaseType(QualType(this_(), 0)) {
4227 ObjCObjectTypeBits.NumProtocols = 0;
4231 /// getBaseType - Gets the base type of this object type. This is
4232 /// always (possibly sugar for) one of:
4233 /// - the 'id' builtin type (as opposed to the 'id' type visible to the
4234 /// user, which is a typedef for an ObjCPointerType)
4235 /// - the 'Class' builtin type (same caveat)
4236 /// - an ObjCObjectType (currently always an ObjCInterfaceType)
4237 QualType getBaseType() const { return BaseType; }
4239 bool isObjCId() const {
4240 return getBaseType()->isSpecificBuiltinType(BuiltinType::ObjCId);
4242 bool isObjCClass() const {
4243 return getBaseType()->isSpecificBuiltinType(BuiltinType::ObjCClass);
4245 bool isObjCUnqualifiedId() const { return qual_empty() && isObjCId(); }
4246 bool isObjCUnqualifiedClass() const { return qual_empty() && isObjCClass(); }
4247 bool isObjCUnqualifiedIdOrClass() const {
4248 if (!qual_empty()) return false;
4249 if (const BuiltinType *T = getBaseType()->getAs<BuiltinType>())
4250 return T->getKind() == BuiltinType::ObjCId ||
4251 T->getKind() == BuiltinType::ObjCClass;
4254 bool isObjCQualifiedId() const { return !qual_empty() && isObjCId(); }
4255 bool isObjCQualifiedClass() const { return !qual_empty() && isObjCClass(); }
4257 /// Gets the interface declaration for this object type, if the base type
4258 /// really is an interface.
4259 ObjCInterfaceDecl *getInterface() const;
4261 typedef ObjCProtocolDecl * const *qual_iterator;
4263 qual_iterator qual_begin() const { return getProtocolStorage(); }
4264 qual_iterator qual_end() const { return qual_begin() + getNumProtocols(); }
4266 bool qual_empty() const { return getNumProtocols() == 0; }
4268 /// getNumProtocols - Return the number of qualifying protocols in this
4269 /// interface type, or 0 if there are none.
4270 unsigned getNumProtocols() const { return ObjCObjectTypeBits.NumProtocols; }
4272 /// \brief Fetch a protocol by index.
4273 ObjCProtocolDecl *getProtocol(unsigned I) const {
4274 assert(I < getNumProtocols() && "Out-of-range protocol access");
4275 return qual_begin()[I];
4278 bool isSugared() const { return false; }
4279 QualType desugar() const { return QualType(this, 0); }
4281 static bool classof(const Type *T) {
4282 return T->getTypeClass() == ObjCObject ||
4283 T->getTypeClass() == ObjCInterface;
4287 /// ObjCObjectTypeImpl - A class providing a concrete implementation
4288 /// of ObjCObjectType, so as to not increase the footprint of
4289 /// ObjCInterfaceType. Code outside of ASTContext and the core type
4290 /// system should not reference this type.
4291 class ObjCObjectTypeImpl : public ObjCObjectType, public llvm::FoldingSetNode {
4292 friend class ASTContext;
4294 // If anyone adds fields here, ObjCObjectType::getProtocolStorage()
4295 // will need to be modified.
4297 ObjCObjectTypeImpl(QualType Canonical, QualType Base,
4298 ObjCProtocolDecl * const *Protocols,
4299 unsigned NumProtocols)
4300 : ObjCObjectType(Canonical, Base, Protocols, NumProtocols) {}
4303 void Profile(llvm::FoldingSetNodeID &ID);
4304 static void Profile(llvm::FoldingSetNodeID &ID,
4306 ObjCProtocolDecl *const *protocols,
4307 unsigned NumProtocols);
4310 inline ObjCProtocolDecl **ObjCObjectType::getProtocolStorage() {
4311 return reinterpret_cast<ObjCProtocolDecl**>(
4312 static_cast<ObjCObjectTypeImpl*>(this) + 1);
4315 /// ObjCInterfaceType - Interfaces are the core concept in Objective-C for
4316 /// object oriented design. They basically correspond to C++ classes. There
4317 /// are two kinds of interface types, normal interfaces like "NSString" and
4318 /// qualified interfaces, which are qualified with a protocol list like
4319 /// "NSString<NSCopyable, NSAmazing>".
4321 /// ObjCInterfaceType guarantees the following properties when considered
4322 /// as a subtype of its superclass, ObjCObjectType:
4323 /// - There are no protocol qualifiers. To reinforce this, code which
4324 /// tries to invoke the protocol methods via an ObjCInterfaceType will
4325 /// fail to compile.
4326 /// - It is its own base type. That is, if T is an ObjCInterfaceType*,
4327 /// T->getBaseType() == QualType(T, 0).
4328 class ObjCInterfaceType : public ObjCObjectType {
4329 mutable ObjCInterfaceDecl *Decl;
4331 ObjCInterfaceType(const ObjCInterfaceDecl *D)
4332 : ObjCObjectType(Nonce_ObjCInterface),
4333 Decl(const_cast<ObjCInterfaceDecl*>(D)) {}
4334 friend class ASTContext; // ASTContext creates these.
4335 friend class ASTReader;
4336 friend class ObjCInterfaceDecl;
4339 /// getDecl - Get the declaration of this interface.
4340 ObjCInterfaceDecl *getDecl() const { return Decl; }
4342 bool isSugared() const { return false; }
4343 QualType desugar() const { return QualType(this, 0); }
4345 static bool classof(const Type *T) {
4346 return T->getTypeClass() == ObjCInterface;
4349 // Nonsense to "hide" certain members of ObjCObjectType within this
4350 // class. People asking for protocols on an ObjCInterfaceType are
4351 // not going to get what they want: ObjCInterfaceTypes are
4352 // guaranteed to have no protocols.
4362 inline ObjCInterfaceDecl *ObjCObjectType::getInterface() const {
4363 if (const ObjCInterfaceType *T =
4364 getBaseType()->getAs<ObjCInterfaceType>())
4365 return T->getDecl();
4369 /// ObjCObjectPointerType - Used to represent a pointer to an
4370 /// Objective C object. These are constructed from pointer
4371 /// declarators when the pointee type is an ObjCObjectType (or sugar
4372 /// for one). In addition, the 'id' and 'Class' types are typedefs
4373 /// for these, and the protocol-qualified types 'id<P>' and 'Class<P>'
4374 /// are translated into these.
4376 /// Pointers to pointers to Objective C objects are still PointerTypes;
4377 /// only the first level of pointer gets it own type implementation.
4378 class ObjCObjectPointerType : public Type, public llvm::FoldingSetNode {
4379 QualType PointeeType;
4381 ObjCObjectPointerType(QualType Canonical, QualType Pointee)
4382 : Type(ObjCObjectPointer, Canonical, false, false, false, false),
4383 PointeeType(Pointee) {}
4384 friend class ASTContext; // ASTContext creates these.
4387 /// getPointeeType - Gets the type pointed to by this ObjC pointer.
4388 /// The result will always be an ObjCObjectType or sugar thereof.
4389 QualType getPointeeType() const { return PointeeType; }
4391 /// getObjCObjectType - Gets the type pointed to by this ObjC
4392 /// pointer. This method always returns non-null.
4394 /// This method is equivalent to getPointeeType() except that
4395 /// it discards any typedefs (or other sugar) between this
4396 /// type and the "outermost" object type. So for:
4398 /// \@class A; \@protocol P; \@protocol Q;
4399 /// typedef A<P> AP;
4401 /// typedef A1<P> A1P;
4402 /// typedef A1P<Q> A1PQ;
4404 /// For 'A*', getObjectType() will return 'A'.
4405 /// For 'A<P>*', getObjectType() will return 'A<P>'.
4406 /// For 'AP*', getObjectType() will return 'A<P>'.
4407 /// For 'A1*', getObjectType() will return 'A'.
4408 /// For 'A1<P>*', getObjectType() will return 'A1<P>'.
4409 /// For 'A1P*', getObjectType() will return 'A1<P>'.
4410 /// For 'A1PQ*', getObjectType() will return 'A1<Q>', because
4411 /// adding protocols to a protocol-qualified base discards the
4412 /// old qualifiers (for now). But if it didn't, getObjectType()
4413 /// would return 'A1P<Q>' (and we'd have to make iterating over
4414 /// qualifiers more complicated).
4415 const ObjCObjectType *getObjectType() const {
4416 return PointeeType->castAs<ObjCObjectType>();
4419 /// getInterfaceType - If this pointer points to an Objective C
4420 /// \@interface type, gets the type for that interface. Any protocol
4421 /// qualifiers on the interface are ignored.
4423 /// \return null if the base type for this pointer is 'id' or 'Class'
4424 const ObjCInterfaceType *getInterfaceType() const {
4425 return getObjectType()->getBaseType()->getAs<ObjCInterfaceType>();
4428 /// getInterfaceDecl - If this pointer points to an Objective \@interface
4429 /// type, gets the declaration for that interface.
4431 /// \return null if the base type for this pointer is 'id' or 'Class'
4432 ObjCInterfaceDecl *getInterfaceDecl() const {
4433 return getObjectType()->getInterface();
4436 /// isObjCIdType - True if this is equivalent to the 'id' type, i.e. if
4437 /// its object type is the primitive 'id' type with no protocols.
4438 bool isObjCIdType() const {
4439 return getObjectType()->isObjCUnqualifiedId();
4442 /// isObjCClassType - True if this is equivalent to the 'Class' type,
4443 /// i.e. if its object tive is the primitive 'Class' type with no protocols.
4444 bool isObjCClassType() const {
4445 return getObjectType()->isObjCUnqualifiedClass();
4448 /// isObjCQualifiedIdType - True if this is equivalent to 'id<P>' for some
4449 /// non-empty set of protocols.
4450 bool isObjCQualifiedIdType() const {
4451 return getObjectType()->isObjCQualifiedId();
4454 /// isObjCQualifiedClassType - True if this is equivalent to 'Class<P>' for
4455 /// some non-empty set of protocols.
4456 bool isObjCQualifiedClassType() const {
4457 return getObjectType()->isObjCQualifiedClass();
4460 /// An iterator over the qualifiers on the object type. Provided
4461 /// for convenience. This will always iterate over the full set of
4462 /// protocols on a type, not just those provided directly.
4463 typedef ObjCObjectType::qual_iterator qual_iterator;
4465 qual_iterator qual_begin() const {
4466 return getObjectType()->qual_begin();
4468 qual_iterator qual_end() const {
4469 return getObjectType()->qual_end();
4471 bool qual_empty() const { return getObjectType()->qual_empty(); }
4473 /// getNumProtocols - Return the number of qualifying protocols on
4474 /// the object type.
4475 unsigned getNumProtocols() const {
4476 return getObjectType()->getNumProtocols();
4479 /// \brief Retrieve a qualifying protocol by index on the object
4481 ObjCProtocolDecl *getProtocol(unsigned I) const {
4482 return getObjectType()->getProtocol(I);
4485 bool isSugared() const { return false; }
4486 QualType desugar() const { return QualType(this, 0); }
4488 void Profile(llvm::FoldingSetNodeID &ID) {
4489 Profile(ID, getPointeeType());
4491 static void Profile(llvm::FoldingSetNodeID &ID, QualType T) {
4492 ID.AddPointer(T.getAsOpaquePtr());
4494 static bool classof(const Type *T) {
4495 return T->getTypeClass() == ObjCObjectPointer;
4499 class AtomicType : public Type, public llvm::FoldingSetNode {
4502 AtomicType(QualType ValTy, QualType Canonical)
4503 : Type(Atomic, Canonical, ValTy->isDependentType(),
4504 ValTy->isInstantiationDependentType(),
4505 ValTy->isVariablyModifiedType(),
4506 ValTy->containsUnexpandedParameterPack()),
4508 friend class ASTContext; // ASTContext creates these.
4511 /// getValueType - Gets the type contained by this atomic type, i.e.
4512 /// the type returned by performing an atomic load of this atomic type.
4513 QualType getValueType() const { return ValueType; }
4515 bool isSugared() const { return false; }
4516 QualType desugar() const { return QualType(this, 0); }
4518 void Profile(llvm::FoldingSetNodeID &ID) {
4519 Profile(ID, getValueType());
4521 static void Profile(llvm::FoldingSetNodeID &ID, QualType T) {
4522 ID.AddPointer(T.getAsOpaquePtr());
4524 static bool classof(const Type *T) {
4525 return T->getTypeClass() == Atomic;
4529 /// A qualifier set is used to build a set of qualifiers.
4530 class QualifierCollector : public Qualifiers {
4532 QualifierCollector(Qualifiers Qs = Qualifiers()) : Qualifiers(Qs) {}
4534 /// Collect any qualifiers on the given type and return an
4535 /// unqualified type. The qualifiers are assumed to be consistent
4536 /// with those already in the type.
4537 const Type *strip(QualType type) {
4538 addFastQualifiers(type.getLocalFastQualifiers());
4539 if (!type.hasLocalNonFastQualifiers())
4540 return type.getTypePtrUnsafe();
4542 const ExtQuals *extQuals = type.getExtQualsUnsafe();
4543 addConsistentQualifiers(extQuals->getQualifiers());
4544 return extQuals->getBaseType();
4547 /// Apply the collected qualifiers to the given type.
4548 QualType apply(const ASTContext &Context, QualType QT) const;
4550 /// Apply the collected qualifiers to the given type.
4551 QualType apply(const ASTContext &Context, const Type* T) const;
4555 // Inline function definitions.
4557 inline SplitQualType SplitQualType::getSingleStepDesugaredType() const {
4558 SplitQualType desugar =
4559 Ty->getLocallyUnqualifiedSingleStepDesugaredType().split();
4560 desugar.Quals.addConsistentQualifiers(Quals);
4564 inline const Type *QualType::getTypePtr() const {
4565 return getCommonPtr()->BaseType;
4568 inline const Type *QualType::getTypePtrOrNull() const {
4569 return (isNull() ? 0 : getCommonPtr()->BaseType);
4572 inline SplitQualType QualType::split() const {
4573 if (!hasLocalNonFastQualifiers())
4574 return SplitQualType(getTypePtrUnsafe(),
4575 Qualifiers::fromFastMask(getLocalFastQualifiers()));
4577 const ExtQuals *eq = getExtQualsUnsafe();
4578 Qualifiers qs = eq->getQualifiers();
4579 qs.addFastQualifiers(getLocalFastQualifiers());
4580 return SplitQualType(eq->getBaseType(), qs);
4583 inline Qualifiers QualType::getLocalQualifiers() const {
4585 if (hasLocalNonFastQualifiers())
4586 Quals = getExtQualsUnsafe()->getQualifiers();
4587 Quals.addFastQualifiers(getLocalFastQualifiers());
4591 inline Qualifiers QualType::getQualifiers() const {
4592 Qualifiers quals = getCommonPtr()->CanonicalType.getLocalQualifiers();
4593 quals.addFastQualifiers(getLocalFastQualifiers());
4597 inline unsigned QualType::getCVRQualifiers() const {
4598 unsigned cvr = getCommonPtr()->CanonicalType.getLocalCVRQualifiers();
4599 cvr |= getLocalCVRQualifiers();
4603 inline QualType QualType::getCanonicalType() const {
4604 QualType canon = getCommonPtr()->CanonicalType;
4605 return canon.withFastQualifiers(getLocalFastQualifiers());
4608 inline bool QualType::isCanonical() const {
4609 return getTypePtr()->isCanonicalUnqualified();
4612 inline bool QualType::isCanonicalAsParam() const {
4613 if (!isCanonical()) return false;
4614 if (hasLocalQualifiers()) return false;
4616 const Type *T = getTypePtr();
4617 if (T->isVariablyModifiedType() && T->hasSizedVLAType())
4620 return !isa<FunctionType>(T) && !isa<ArrayType>(T);
4623 inline bool QualType::isConstQualified() const {
4624 return isLocalConstQualified() ||
4625 getCommonPtr()->CanonicalType.isLocalConstQualified();
4628 inline bool QualType::isRestrictQualified() const {
4629 return isLocalRestrictQualified() ||
4630 getCommonPtr()->CanonicalType.isLocalRestrictQualified();
4634 inline bool QualType::isVolatileQualified() const {
4635 return isLocalVolatileQualified() ||
4636 getCommonPtr()->CanonicalType.isLocalVolatileQualified();
4639 inline bool QualType::hasQualifiers() const {
4640 return hasLocalQualifiers() ||
4641 getCommonPtr()->CanonicalType.hasLocalQualifiers();
4644 inline QualType QualType::getUnqualifiedType() const {
4645 if (!getTypePtr()->getCanonicalTypeInternal().hasLocalQualifiers())
4646 return QualType(getTypePtr(), 0);
4648 return QualType(getSplitUnqualifiedTypeImpl(*this).Ty, 0);
4651 inline SplitQualType QualType::getSplitUnqualifiedType() const {
4652 if (!getTypePtr()->getCanonicalTypeInternal().hasLocalQualifiers())
4655 return getSplitUnqualifiedTypeImpl(*this);
4658 inline void QualType::removeLocalConst() {
4659 removeLocalFastQualifiers(Qualifiers::Const);
4662 inline void QualType::removeLocalRestrict() {
4663 removeLocalFastQualifiers(Qualifiers::Restrict);
4666 inline void QualType::removeLocalVolatile() {
4667 removeLocalFastQualifiers(Qualifiers::Volatile);
4670 inline void QualType::removeLocalCVRQualifiers(unsigned Mask) {
4671 assert(!(Mask & ~Qualifiers::CVRMask) && "mask has non-CVR bits");
4672 assert((int)Qualifiers::CVRMask == (int)Qualifiers::FastMask);
4674 // Fast path: we don't need to touch the slow qualifiers.
4675 removeLocalFastQualifiers(Mask);
4678 /// getAddressSpace - Return the address space of this type.
4679 inline unsigned QualType::getAddressSpace() const {
4680 return getQualifiers().getAddressSpace();
4683 /// getObjCGCAttr - Return the gc attribute of this type.
4684 inline Qualifiers::GC QualType::getObjCGCAttr() const {
4685 return getQualifiers().getObjCGCAttr();
4688 inline FunctionType::ExtInfo getFunctionExtInfo(const Type &t) {
4689 if (const PointerType *PT = t.getAs<PointerType>()) {
4690 if (const FunctionType *FT = PT->getPointeeType()->getAs<FunctionType>())
4691 return FT->getExtInfo();
4692 } else if (const FunctionType *FT = t.getAs<FunctionType>())
4693 return FT->getExtInfo();
4695 return FunctionType::ExtInfo();
4698 inline FunctionType::ExtInfo getFunctionExtInfo(QualType t) {
4699 return getFunctionExtInfo(*t);
4702 /// isMoreQualifiedThan - Determine whether this type is more
4703 /// qualified than the Other type. For example, "const volatile int"
4704 /// is more qualified than "const int", "volatile int", and
4705 /// "int". However, it is not more qualified than "const volatile
4707 inline bool QualType::isMoreQualifiedThan(QualType other) const {
4708 Qualifiers myQuals = getQualifiers();
4709 Qualifiers otherQuals = other.getQualifiers();
4710 return (myQuals != otherQuals && myQuals.compatiblyIncludes(otherQuals));
4713 /// isAtLeastAsQualifiedAs - Determine whether this type is at last
4714 /// as qualified as the Other type. For example, "const volatile
4715 /// int" is at least as qualified as "const int", "volatile int",
4716 /// "int", and "const volatile int".
4717 inline bool QualType::isAtLeastAsQualifiedAs(QualType other) const {
4718 return getQualifiers().compatiblyIncludes(other.getQualifiers());
4721 /// getNonReferenceType - If Type is a reference type (e.g., const
4722 /// int&), returns the type that the reference refers to ("const
4723 /// int"). Otherwise, returns the type itself. This routine is used
4724 /// throughout Sema to implement C++ 5p6:
4726 /// If an expression initially has the type "reference to T" (8.3.2,
4727 /// 8.5.3), the type is adjusted to "T" prior to any further
4728 /// analysis, the expression designates the object or function
4729 /// denoted by the reference, and the expression is an lvalue.
4730 inline QualType QualType::getNonReferenceType() const {
4731 if (const ReferenceType *RefType = (*this)->getAs<ReferenceType>())
4732 return RefType->getPointeeType();
4737 inline bool QualType::isCForbiddenLValueType() const {
4738 return ((getTypePtr()->isVoidType() && !hasQualifiers()) ||
4739 getTypePtr()->isFunctionType());
4742 /// \brief Tests whether the type is categorized as a fundamental type.
4744 /// \returns True for types specified in C++0x [basic.fundamental].
4745 inline bool Type::isFundamentalType() const {
4746 return isVoidType() ||
4747 // FIXME: It's really annoying that we don't have an
4748 // 'isArithmeticType()' which agrees with the standard definition.
4749 (isArithmeticType() && !isEnumeralType());
4752 /// \brief Tests whether the type is categorized as a compound type.
4754 /// \returns True for types specified in C++0x [basic.compound].
4755 inline bool Type::isCompoundType() const {
4756 // C++0x [basic.compound]p1:
4757 // Compound types can be constructed in the following ways:
4758 // -- arrays of objects of a given type [...];
4759 return isArrayType() ||
4760 // -- functions, which have parameters of given types [...];
4762 // -- pointers to void or objects or functions [...];
4764 // -- references to objects or functions of a given type. [...]
4765 isReferenceType() ||
4766 // -- classes containing a sequence of objects of various types, [...];
4768 // -- unions, which are classes capable of containing objects of different
4769 // types at different times;
4771 // -- enumerations, which comprise a set of named constant values. [...];
4773 // -- pointers to non-static class members, [...].
4774 isMemberPointerType();
4777 inline bool Type::isFunctionType() const {
4778 return isa<FunctionType>(CanonicalType);
4780 inline bool Type::isPointerType() const {
4781 return isa<PointerType>(CanonicalType);
4783 inline bool Type::isAnyPointerType() const {
4784 return isPointerType() || isObjCObjectPointerType();
4786 inline bool Type::isBlockPointerType() const {
4787 return isa<BlockPointerType>(CanonicalType);
4789 inline bool Type::isReferenceType() const {
4790 return isa<ReferenceType>(CanonicalType);
4792 inline bool Type::isLValueReferenceType() const {
4793 return isa<LValueReferenceType>(CanonicalType);
4795 inline bool Type::isRValueReferenceType() const {
4796 return isa<RValueReferenceType>(CanonicalType);
4798 inline bool Type::isFunctionPointerType() const {
4799 if (const PointerType *T = getAs<PointerType>())
4800 return T->getPointeeType()->isFunctionType();
4804 inline bool Type::isMemberPointerType() const {
4805 return isa<MemberPointerType>(CanonicalType);
4807 inline bool Type::isMemberFunctionPointerType() const {
4808 if (const MemberPointerType* T = getAs<MemberPointerType>())
4809 return T->isMemberFunctionPointer();
4813 inline bool Type::isMemberDataPointerType() const {
4814 if (const MemberPointerType* T = getAs<MemberPointerType>())
4815 return T->isMemberDataPointer();
4819 inline bool Type::isArrayType() const {
4820 return isa<ArrayType>(CanonicalType);
4822 inline bool Type::isConstantArrayType() const {
4823 return isa<ConstantArrayType>(CanonicalType);
4825 inline bool Type::isIncompleteArrayType() const {
4826 return isa<IncompleteArrayType>(CanonicalType);
4828 inline bool Type::isVariableArrayType() const {
4829 return isa<VariableArrayType>(CanonicalType);
4831 inline bool Type::isDependentSizedArrayType() const {
4832 return isa<DependentSizedArrayType>(CanonicalType);
4834 inline bool Type::isBuiltinType() const {
4835 return isa<BuiltinType>(CanonicalType);
4837 inline bool Type::isRecordType() const {
4838 return isa<RecordType>(CanonicalType);
4840 inline bool Type::isEnumeralType() const {
4841 return isa<EnumType>(CanonicalType);
4843 inline bool Type::isAnyComplexType() const {
4844 return isa<ComplexType>(CanonicalType);
4846 inline bool Type::isVectorType() const {
4847 return isa<VectorType>(CanonicalType);
4849 inline bool Type::isExtVectorType() const {
4850 return isa<ExtVectorType>(CanonicalType);
4852 inline bool Type::isObjCObjectPointerType() const {
4853 return isa<ObjCObjectPointerType>(CanonicalType);
4855 inline bool Type::isObjCObjectType() const {
4856 return isa<ObjCObjectType>(CanonicalType);
4858 inline bool Type::isObjCObjectOrInterfaceType() const {
4859 return isa<ObjCInterfaceType>(CanonicalType) ||
4860 isa<ObjCObjectType>(CanonicalType);
4862 inline bool Type::isAtomicType() const {
4863 return isa<AtomicType>(CanonicalType);
4866 inline bool Type::isObjCQualifiedIdType() const {
4867 if (const ObjCObjectPointerType *OPT = getAs<ObjCObjectPointerType>())
4868 return OPT->isObjCQualifiedIdType();
4871 inline bool Type::isObjCQualifiedClassType() const {
4872 if (const ObjCObjectPointerType *OPT = getAs<ObjCObjectPointerType>())
4873 return OPT->isObjCQualifiedClassType();
4876 inline bool Type::isObjCIdType() const {
4877 if (const ObjCObjectPointerType *OPT = getAs<ObjCObjectPointerType>())
4878 return OPT->isObjCIdType();
4881 inline bool Type::isObjCClassType() const {
4882 if (const ObjCObjectPointerType *OPT = getAs<ObjCObjectPointerType>())
4883 return OPT->isObjCClassType();
4886 inline bool Type::isObjCSelType() const {
4887 if (const PointerType *OPT = getAs<PointerType>())
4888 return OPT->getPointeeType()->isSpecificBuiltinType(BuiltinType::ObjCSel);
4891 inline bool Type::isObjCBuiltinType() const {
4892 return isObjCIdType() || isObjCClassType() || isObjCSelType();
4895 inline bool Type::isImage1dT() const {
4896 return isSpecificBuiltinType(BuiltinType::OCLImage1d);
4899 inline bool Type::isImage1dArrayT() const {
4900 return isSpecificBuiltinType(BuiltinType::OCLImage1dArray);
4903 inline bool Type::isImage1dBufferT() const {
4904 return isSpecificBuiltinType(BuiltinType::OCLImage1dBuffer);
4907 inline bool Type::isImage2dT() const {
4908 return isSpecificBuiltinType(BuiltinType::OCLImage2d);
4911 inline bool Type::isImage2dArrayT() const {
4912 return isSpecificBuiltinType(BuiltinType::OCLImage2dArray);
4915 inline bool Type::isImage3dT() const {
4916 return isSpecificBuiltinType(BuiltinType::OCLImage3d);
4919 inline bool Type::isSamplerT() const {
4920 return isSpecificBuiltinType(BuiltinType::OCLSampler);
4923 inline bool Type::isEventT() const {
4924 return isSpecificBuiltinType(BuiltinType::OCLEvent);
4927 inline bool Type::isImageType() const {
4928 return isImage3dT() ||
4929 isImage2dT() || isImage2dArrayT() ||
4930 isImage1dT() || isImage1dArrayT() || isImage1dBufferT();
4933 inline bool Type::isOpenCLSpecificType() const {
4934 return isSamplerT() || isEventT() || isImageType();
4937 inline bool Type::isTemplateTypeParmType() const {
4938 return isa<TemplateTypeParmType>(CanonicalType);
4941 inline bool Type::isSpecificBuiltinType(unsigned K) const {
4942 if (const BuiltinType *BT = getAs<BuiltinType>())
4943 if (BT->getKind() == (BuiltinType::Kind) K)
4948 inline bool Type::isPlaceholderType() const {
4949 if (const BuiltinType *BT = dyn_cast<BuiltinType>(this))
4950 return BT->isPlaceholderType();
4954 inline const BuiltinType *Type::getAsPlaceholderType() const {
4955 if (const BuiltinType *BT = dyn_cast<BuiltinType>(this))
4956 if (BT->isPlaceholderType())
4961 inline bool Type::isSpecificPlaceholderType(unsigned K) const {
4962 assert(BuiltinType::isPlaceholderTypeKind((BuiltinType::Kind) K));
4963 if (const BuiltinType *BT = dyn_cast<BuiltinType>(this))
4964 return (BT->getKind() == (BuiltinType::Kind) K);
4968 inline bool Type::isNonOverloadPlaceholderType() const {
4969 if (const BuiltinType *BT = dyn_cast<BuiltinType>(this))
4970 return BT->isNonOverloadPlaceholderType();
4974 inline bool Type::isVoidType() const {
4975 if (const BuiltinType *BT = dyn_cast<BuiltinType>(CanonicalType))
4976 return BT->getKind() == BuiltinType::Void;
4980 inline bool Type::isHalfType() const {
4981 if (const BuiltinType *BT = dyn_cast<BuiltinType>(CanonicalType))
4982 return BT->getKind() == BuiltinType::Half;
4983 // FIXME: Should we allow complex __fp16? Probably not.
4987 inline bool Type::isNullPtrType() const {
4988 if (const BuiltinType *BT = getAs<BuiltinType>())
4989 return BT->getKind() == BuiltinType::NullPtr;
4993 extern bool IsEnumDeclComplete(EnumDecl *);
4994 extern bool IsEnumDeclScoped(EnumDecl *);
4996 inline bool Type::isIntegerType() const {
4997 if (const BuiltinType *BT = dyn_cast<BuiltinType>(CanonicalType))
4998 return BT->getKind() >= BuiltinType::Bool &&
4999 BT->getKind() <= BuiltinType::Int128;
5000 if (const EnumType *ET = dyn_cast<EnumType>(CanonicalType)) {
5001 // Incomplete enum types are not treated as integer types.
5002 // FIXME: In C++, enum types are never integer types.
5003 return IsEnumDeclComplete(ET->getDecl()) &&
5004 !IsEnumDeclScoped(ET->getDecl());
5009 inline bool Type::isScalarType() const {
5010 if (const BuiltinType *BT = dyn_cast<BuiltinType>(CanonicalType))
5011 return BT->getKind() > BuiltinType::Void &&
5012 BT->getKind() <= BuiltinType::NullPtr;
5013 if (const EnumType *ET = dyn_cast<EnumType>(CanonicalType))
5014 // Enums are scalar types, but only if they are defined. Incomplete enums
5015 // are not treated as scalar types.
5016 return IsEnumDeclComplete(ET->getDecl());
5017 return isa<PointerType>(CanonicalType) ||
5018 isa<BlockPointerType>(CanonicalType) ||
5019 isa<MemberPointerType>(CanonicalType) ||
5020 isa<ComplexType>(CanonicalType) ||
5021 isa<ObjCObjectPointerType>(CanonicalType);
5024 inline bool Type::isIntegralOrEnumerationType() const {
5025 if (const BuiltinType *BT = dyn_cast<BuiltinType>(CanonicalType))
5026 return BT->getKind() >= BuiltinType::Bool &&
5027 BT->getKind() <= BuiltinType::Int128;
5029 // Check for a complete enum type; incomplete enum types are not properly an
5030 // enumeration type in the sense required here.
5031 if (const EnumType *ET = dyn_cast<EnumType>(CanonicalType))
5032 return IsEnumDeclComplete(ET->getDecl());
5037 inline bool Type::isBooleanType() const {
5038 if (const BuiltinType *BT = dyn_cast<BuiltinType>(CanonicalType))
5039 return BT->getKind() == BuiltinType::Bool;
5043 inline bool Type::isUndeducedType() const {
5044 const AutoType *AT = getContainedAutoType();
5045 return AT && !AT->isDeduced();
5048 /// \brief Determines whether this is a type for which one can define
5049 /// an overloaded operator.
5050 inline bool Type::isOverloadableType() const {
5051 return isDependentType() || isRecordType() || isEnumeralType();
5054 /// \brief Determines whether this type can decay to a pointer type.
5055 inline bool Type::canDecayToPointerType() const {
5056 return isFunctionType() || isArrayType();
5059 inline bool Type::hasPointerRepresentation() const {
5060 return (isPointerType() || isReferenceType() || isBlockPointerType() ||
5061 isObjCObjectPointerType() || isNullPtrType());
5064 inline bool Type::hasObjCPointerRepresentation() const {
5065 return isObjCObjectPointerType();
5068 inline const Type *Type::getBaseElementTypeUnsafe() const {
5069 const Type *type = this;
5070 while (const ArrayType *arrayType = type->getAsArrayTypeUnsafe())
5071 type = arrayType->getElementType().getTypePtr();
5075 /// Insertion operator for diagnostics. This allows sending QualType's into a
5076 /// diagnostic with <<.
5077 inline const DiagnosticBuilder &operator<<(const DiagnosticBuilder &DB,
5079 DB.AddTaggedVal(reinterpret_cast<intptr_t>(T.getAsOpaquePtr()),
5080 DiagnosticsEngine::ak_qualtype);
5084 /// Insertion operator for partial diagnostics. This allows sending QualType's
5085 /// into a diagnostic with <<.
5086 inline const PartialDiagnostic &operator<<(const PartialDiagnostic &PD,
5088 PD.AddTaggedVal(reinterpret_cast<intptr_t>(T.getAsOpaquePtr()),
5089 DiagnosticsEngine::ak_qualtype);
5093 // Helper class template that is used by Type::getAs to ensure that one does
5094 // not try to look through a qualified type to get to an array type.
5095 template<typename T,
5096 bool isArrayType = (llvm::is_same<T, ArrayType>::value ||
5097 llvm::is_base_of<ArrayType, T>::value)>
5098 struct ArrayType_cannot_be_used_with_getAs { };
5100 template<typename T>
5101 struct ArrayType_cannot_be_used_with_getAs<T, true>;
5103 // Member-template getAs<specific type>'.
5104 template <typename T> const T *Type::getAs() const {
5105 ArrayType_cannot_be_used_with_getAs<T> at;
5108 // If this is directly a T type, return it.
5109 if (const T *Ty = dyn_cast<T>(this))
5112 // If the canonical form of this type isn't the right kind, reject it.
5113 if (!isa<T>(CanonicalType))
5116 // If this is a typedef for the type, strip the typedef off without
5117 // losing all typedef information.
5118 return cast<T>(getUnqualifiedDesugaredType());
5121 inline const ArrayType *Type::getAsArrayTypeUnsafe() const {
5122 // If this is directly an array type, return it.
5123 if (const ArrayType *arr = dyn_cast<ArrayType>(this))
5126 // If the canonical form of this type isn't the right kind, reject it.
5127 if (!isa<ArrayType>(CanonicalType))
5130 // If this is a typedef for the type, strip the typedef off without
5131 // losing all typedef information.
5132 return cast<ArrayType>(getUnqualifiedDesugaredType());
5135 template <typename T> const T *Type::castAs() const {
5136 ArrayType_cannot_be_used_with_getAs<T> at;
5139 assert(isa<T>(CanonicalType));
5140 if (const T *ty = dyn_cast<T>(this)) return ty;
5141 return cast<T>(getUnqualifiedDesugaredType());
5144 inline const ArrayType *Type::castAsArrayTypeUnsafe() const {
5145 assert(isa<ArrayType>(CanonicalType));
5146 if (const ArrayType *arr = dyn_cast<ArrayType>(this)) return arr;
5147 return cast<ArrayType>(getUnqualifiedDesugaredType());
5150 } // end namespace clang