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 LLVM_EXPLICIT 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(const 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 : 3;
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 = 18 };
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;
1319 enum { MaxNumElements = (1 << (29 - NumTypeBits)) - 1 };
1322 class AttributedTypeBitfields {
1323 friend class AttributedType;
1325 unsigned : NumTypeBits;
1327 /// AttrKind - an AttributedType::Kind
1328 unsigned AttrKind : 32 - NumTypeBits;
1331 class AutoTypeBitfields {
1332 friend class AutoType;
1334 unsigned : NumTypeBits;
1336 /// Was this placeholder type spelled as 'decltype(auto)'?
1337 unsigned IsDecltypeAuto : 1;
1341 TypeBitfields TypeBits;
1342 ArrayTypeBitfields ArrayTypeBits;
1343 AttributedTypeBitfields AttributedTypeBits;
1344 AutoTypeBitfields AutoTypeBits;
1345 BuiltinTypeBitfields BuiltinTypeBits;
1346 FunctionTypeBitfields FunctionTypeBits;
1347 ObjCObjectTypeBitfields ObjCObjectTypeBits;
1348 ReferenceTypeBitfields ReferenceTypeBits;
1349 TypeWithKeywordBitfields TypeWithKeywordBits;
1350 VectorTypeBitfields VectorTypeBits;
1354 /// \brief Set whether this type comes from an AST file.
1355 void setFromAST(bool V = true) const {
1356 TypeBits.FromAST = V;
1359 template <class T> friend class TypePropertyCache;
1362 // silence VC++ warning C4355: 'this' : used in base member initializer list
1363 Type *this_() { return this; }
1364 Type(TypeClass tc, QualType canon, bool Dependent,
1365 bool InstantiationDependent, bool VariablyModified,
1366 bool ContainsUnexpandedParameterPack)
1367 : ExtQualsTypeCommonBase(this,
1368 canon.isNull() ? QualType(this_(), 0) : canon) {
1370 TypeBits.Dependent = Dependent;
1371 TypeBits.InstantiationDependent = Dependent || InstantiationDependent;
1372 TypeBits.VariablyModified = VariablyModified;
1373 TypeBits.ContainsUnexpandedParameterPack = ContainsUnexpandedParameterPack;
1374 TypeBits.CacheValid = false;
1375 TypeBits.CachedLocalOrUnnamed = false;
1376 TypeBits.CachedLinkage = NoLinkage;
1377 TypeBits.FromAST = false;
1379 friend class ASTContext;
1381 void setDependent(bool D = true) {
1382 TypeBits.Dependent = D;
1384 TypeBits.InstantiationDependent = true;
1386 void setInstantiationDependent(bool D = true) {
1387 TypeBits.InstantiationDependent = D; }
1388 void setVariablyModified(bool VM = true) { TypeBits.VariablyModified = VM;
1390 void setContainsUnexpandedParameterPack(bool PP = true) {
1391 TypeBits.ContainsUnexpandedParameterPack = PP;
1395 TypeClass getTypeClass() const { return static_cast<TypeClass>(TypeBits.TC); }
1397 /// \brief Whether this type comes from an AST file.
1398 bool isFromAST() const { return TypeBits.FromAST; }
1400 /// \brief Whether this type is or contains an unexpanded parameter
1401 /// pack, used to support C++0x variadic templates.
1403 /// A type that contains a parameter pack shall be expanded by the
1404 /// ellipsis operator at some point. For example, the typedef in the
1405 /// following example contains an unexpanded parameter pack 'T':
1408 /// template<typename ...T>
1410 /// typedef T* pointer_types; // ill-formed; T is a parameter pack.
1414 /// Note that this routine does not specify which
1415 bool containsUnexpandedParameterPack() const {
1416 return TypeBits.ContainsUnexpandedParameterPack;
1419 /// Determines if this type would be canonical if it had no further
1421 bool isCanonicalUnqualified() const {
1422 return CanonicalType == QualType(this, 0);
1425 /// Pull a single level of sugar off of this locally-unqualified type.
1426 /// Users should generally prefer SplitQualType::getSingleStepDesugaredType()
1427 /// or QualType::getSingleStepDesugaredType(const ASTContext&).
1428 QualType getLocallyUnqualifiedSingleStepDesugaredType() const;
1430 /// Types are partitioned into 3 broad categories (C99 6.2.5p1):
1431 /// object types, function types, and incomplete types.
1433 /// isIncompleteType - Return true if this is an incomplete type.
1434 /// A type that can describe objects, but which lacks information needed to
1435 /// determine its size (e.g. void, or a fwd declared struct). Clients of this
1436 /// routine will need to determine if the size is actually required.
1438 /// \brief Def If non-NULL, and the type refers to some kind of declaration
1439 /// that can be completed (such as a C struct, C++ class, or Objective-C
1440 /// class), will be set to the declaration.
1441 bool isIncompleteType(NamedDecl **Def = 0) const;
1443 /// isIncompleteOrObjectType - Return true if this is an incomplete or object
1444 /// type, in other words, not a function type.
1445 bool isIncompleteOrObjectType() const {
1446 return !isFunctionType();
1449 /// \brief Determine whether this type is an object type.
1450 bool isObjectType() const {
1451 // C++ [basic.types]p8:
1452 // An object type is a (possibly cv-qualified) type that is not a
1453 // function type, not a reference type, and not a void type.
1454 return !isReferenceType() && !isFunctionType() && !isVoidType();
1457 /// isLiteralType - Return true if this is a literal type
1458 /// (C++11 [basic.types]p10)
1459 bool isLiteralType(const ASTContext &Ctx) const;
1461 /// \brief Test if this type is a standard-layout type.
1462 /// (C++0x [basic.type]p9)
1463 bool isStandardLayoutType() const;
1465 /// Helper methods to distinguish type categories. All type predicates
1466 /// operate on the canonical type, ignoring typedefs and qualifiers.
1468 /// isBuiltinType - returns true if the type is a builtin type.
1469 bool isBuiltinType() const;
1471 /// isSpecificBuiltinType - Test for a particular builtin type.
1472 bool isSpecificBuiltinType(unsigned K) const;
1474 /// isPlaceholderType - Test for a type which does not represent an
1475 /// actual type-system type but is instead used as a placeholder for
1476 /// various convenient purposes within Clang. All such types are
1478 bool isPlaceholderType() const;
1479 const BuiltinType *getAsPlaceholderType() const;
1481 /// isSpecificPlaceholderType - Test for a specific placeholder type.
1482 bool isSpecificPlaceholderType(unsigned K) const;
1484 /// isNonOverloadPlaceholderType - Test for a placeholder type
1485 /// other than Overload; see BuiltinType::isNonOverloadPlaceholderType.
1486 bool isNonOverloadPlaceholderType() const;
1488 /// isIntegerType() does *not* include complex integers (a GCC extension).
1489 /// isComplexIntegerType() can be used to test for complex integers.
1490 bool isIntegerType() const; // C99 6.2.5p17 (int, char, bool, enum)
1491 bool isEnumeralType() const;
1492 bool isBooleanType() const;
1493 bool isCharType() const;
1494 bool isWideCharType() const;
1495 bool isChar16Type() const;
1496 bool isChar32Type() const;
1497 bool isAnyCharacterType() const;
1498 bool isIntegralType(ASTContext &Ctx) const;
1500 /// \brief Determine whether this type is an integral or enumeration type.
1501 bool isIntegralOrEnumerationType() const;
1502 /// \brief Determine whether this type is an integral or unscoped enumeration
1504 bool isIntegralOrUnscopedEnumerationType() const;
1506 /// Floating point categories.
1507 bool isRealFloatingType() const; // C99 6.2.5p10 (float, double, long double)
1508 /// isComplexType() does *not* include complex integers (a GCC extension).
1509 /// isComplexIntegerType() can be used to test for complex integers.
1510 bool isComplexType() const; // C99 6.2.5p11 (complex)
1511 bool isAnyComplexType() const; // C99 6.2.5p11 (complex) + Complex Int.
1512 bool isFloatingType() const; // C99 6.2.5p11 (real floating + complex)
1513 bool isHalfType() const; // OpenCL 6.1.1.1, NEON (IEEE 754-2008 half)
1514 bool isRealType() const; // C99 6.2.5p17 (real floating + integer)
1515 bool isArithmeticType() const; // C99 6.2.5p18 (integer + floating)
1516 bool isVoidType() const; // C99 6.2.5p19
1517 bool isScalarType() const; // C99 6.2.5p21 (arithmetic + pointers)
1518 bool isAggregateType() const;
1519 bool isFundamentalType() const;
1520 bool isCompoundType() const;
1522 // Type Predicates: Check to see if this type is structurally the specified
1523 // type, ignoring typedefs and qualifiers.
1524 bool isFunctionType() const;
1525 bool isFunctionNoProtoType() const { return getAs<FunctionNoProtoType>(); }
1526 bool isFunctionProtoType() const { return getAs<FunctionProtoType>(); }
1527 bool isPointerType() const;
1528 bool isAnyPointerType() const; // Any C pointer or ObjC object pointer
1529 bool isBlockPointerType() const;
1530 bool isVoidPointerType() const;
1531 bool isReferenceType() const;
1532 bool isLValueReferenceType() const;
1533 bool isRValueReferenceType() const;
1534 bool isFunctionPointerType() const;
1535 bool isMemberPointerType() const;
1536 bool isMemberFunctionPointerType() const;
1537 bool isMemberDataPointerType() const;
1538 bool isArrayType() const;
1539 bool isConstantArrayType() const;
1540 bool isIncompleteArrayType() const;
1541 bool isVariableArrayType() const;
1542 bool isDependentSizedArrayType() const;
1543 bool isRecordType() const;
1544 bool isClassType() const;
1545 bool isStructureType() const;
1546 bool isInterfaceType() const;
1547 bool isStructureOrClassType() const;
1548 bool isUnionType() const;
1549 bool isComplexIntegerType() const; // GCC _Complex integer type.
1550 bool isVectorType() const; // GCC vector type.
1551 bool isExtVectorType() const; // Extended vector type.
1552 bool isObjCObjectPointerType() const; // pointer to ObjC object
1553 bool isObjCRetainableType() const; // ObjC object or block pointer
1554 bool isObjCLifetimeType() const; // (array of)* retainable type
1555 bool isObjCIndirectLifetimeType() const; // (pointer to)* lifetime type
1556 bool isObjCNSObjectType() const; // __attribute__((NSObject))
1557 // FIXME: change this to 'raw' interface type, so we can used 'interface' type
1558 // for the common case.
1559 bool isObjCObjectType() const; // NSString or typeof(*(id)0)
1560 bool isObjCQualifiedInterfaceType() const; // NSString<foo>
1561 bool isObjCQualifiedIdType() const; // id<foo>
1562 bool isObjCQualifiedClassType() const; // Class<foo>
1563 bool isObjCObjectOrInterfaceType() const;
1564 bool isObjCIdType() const; // id
1565 bool isObjCClassType() const; // Class
1566 bool isObjCSelType() const; // Class
1567 bool isObjCBuiltinType() const; // 'id' or 'Class'
1568 bool isObjCARCBridgableType() const;
1569 bool isCARCBridgableType() const;
1570 bool isTemplateTypeParmType() const; // C++ template type parameter
1571 bool isNullPtrType() const; // C++0x nullptr_t
1572 bool isAtomicType() const; // C11 _Atomic()
1574 bool isImage1dT() const; // OpenCL image1d_t
1575 bool isImage1dArrayT() const; // OpenCL image1d_array_t
1576 bool isImage1dBufferT() const; // OpenCL image1d_buffer_t
1577 bool isImage2dT() const; // OpenCL image2d_t
1578 bool isImage2dArrayT() const; // OpenCL image2d_array_t
1579 bool isImage3dT() const; // OpenCL image3d_t
1581 bool isImageType() const; // Any OpenCL image type
1583 bool isSamplerT() const; // OpenCL sampler_t
1584 bool isEventT() const; // OpenCL event_t
1586 bool isOpenCLSpecificType() const; // Any OpenCL specific type
1588 /// Determines if this type, which must satisfy
1589 /// isObjCLifetimeType(), is implicitly __unsafe_unretained rather
1590 /// than implicitly __strong.
1591 bool isObjCARCImplicitlyUnretainedType() const;
1593 /// Return the implicit lifetime for this type, which must not be dependent.
1594 Qualifiers::ObjCLifetime getObjCARCImplicitLifetime() const;
1596 enum ScalarTypeKind {
1599 STK_ObjCObjectPointer,
1604 STK_IntegralComplex,
1607 /// getScalarTypeKind - Given that this is a scalar type, classify it.
1608 ScalarTypeKind getScalarTypeKind() const;
1610 /// isDependentType - Whether this type is a dependent type, meaning
1611 /// that its definition somehow depends on a template parameter
1612 /// (C++ [temp.dep.type]).
1613 bool isDependentType() const { return TypeBits.Dependent; }
1615 /// \brief Determine whether this type is an instantiation-dependent type,
1616 /// meaning that the type involves a template parameter (even if the
1617 /// definition does not actually depend on the type substituted for that
1618 /// template parameter).
1619 bool isInstantiationDependentType() const {
1620 return TypeBits.InstantiationDependent;
1623 /// \brief Determine whether this type is an undeduced type, meaning that
1624 /// it somehow involves a C++11 'auto' type which has not yet been deduced.
1625 bool isUndeducedType() const;
1627 /// \brief Whether this type is a variably-modified type (C99 6.7.5).
1628 bool isVariablyModifiedType() const { return TypeBits.VariablyModified; }
1630 /// \brief Whether this type involves a variable-length array type
1631 /// with a definite size.
1632 bool hasSizedVLAType() const;
1634 /// \brief Whether this type is or contains a local or unnamed type.
1635 bool hasUnnamedOrLocalType() const;
1637 bool isOverloadableType() const;
1639 /// \brief Determine wither this type is a C++ elaborated-type-specifier.
1640 bool isElaboratedTypeSpecifier() const;
1642 bool canDecayToPointerType() const;
1644 /// hasPointerRepresentation - Whether this type is represented
1645 /// natively as a pointer; this includes pointers, references, block
1646 /// pointers, and Objective-C interface, qualified id, and qualified
1647 /// interface types, as well as nullptr_t.
1648 bool hasPointerRepresentation() const;
1650 /// hasObjCPointerRepresentation - Whether this type can represent
1651 /// an objective pointer type for the purpose of GC'ability
1652 bool hasObjCPointerRepresentation() const;
1654 /// \brief Determine whether this type has an integer representation
1655 /// of some sort, e.g., it is an integer type or a vector.
1656 bool hasIntegerRepresentation() const;
1658 /// \brief Determine whether this type has an signed integer representation
1659 /// of some sort, e.g., it is an signed integer type or a vector.
1660 bool hasSignedIntegerRepresentation() const;
1662 /// \brief Determine whether this type has an unsigned integer representation
1663 /// of some sort, e.g., it is an unsigned integer type or a vector.
1664 bool hasUnsignedIntegerRepresentation() const;
1666 /// \brief Determine whether this type has a floating-point representation
1667 /// of some sort, e.g., it is a floating-point type or a vector thereof.
1668 bool hasFloatingRepresentation() const;
1670 // Type Checking Functions: Check to see if this type is structurally the
1671 // specified type, ignoring typedefs and qualifiers, and return a pointer to
1672 // the best type we can.
1673 const RecordType *getAsStructureType() const;
1674 /// NOTE: getAs*ArrayType are methods on ASTContext.
1675 const RecordType *getAsUnionType() const;
1676 const ComplexType *getAsComplexIntegerType() const; // GCC complex int type.
1677 // The following is a convenience method that returns an ObjCObjectPointerType
1678 // for object declared using an interface.
1679 const ObjCObjectPointerType *getAsObjCInterfacePointerType() const;
1680 const ObjCObjectPointerType *getAsObjCQualifiedIdType() const;
1681 const ObjCObjectPointerType *getAsObjCQualifiedClassType() const;
1682 const ObjCObjectType *getAsObjCQualifiedInterfaceType() const;
1684 /// \brief Retrieves the CXXRecordDecl that this type refers to, either
1685 /// because the type is a RecordType or because it is the injected-class-name
1686 /// type of a class template or class template partial specialization.
1687 CXXRecordDecl *getAsCXXRecordDecl() const;
1689 /// If this is a pointer or reference to a RecordType, return the
1690 /// CXXRecordDecl that that type refers to.
1692 /// If this is not a pointer or reference, or the type being pointed to does
1693 /// not refer to a CXXRecordDecl, returns NULL.
1694 const CXXRecordDecl *getPointeeCXXRecordDecl() const;
1696 /// \brief Get the AutoType whose type will be deduced for a variable with
1697 /// an initializer of this type. This looks through declarators like pointer
1698 /// types, but not through decltype or typedefs.
1699 AutoType *getContainedAutoType() const;
1701 /// Member-template getAs<specific type>'. Look through sugar for
1702 /// an instance of \<specific type>. This scheme will eventually
1703 /// replace the specific getAsXXXX methods above.
1705 /// There are some specializations of this member template listed
1706 /// immediately following this class.
1707 template <typename T> const T *getAs() const;
1709 /// A variant of getAs<> for array types which silently discards
1710 /// qualifiers from the outermost type.
1711 const ArrayType *getAsArrayTypeUnsafe() const;
1713 /// Member-template castAs<specific type>. Look through sugar for
1714 /// the underlying instance of \<specific type>.
1716 /// This method has the same relationship to getAs<T> as cast<T> has
1717 /// to dyn_cast<T>; which is to say, the underlying type *must*
1718 /// have the intended type, and this method will never return null.
1719 template <typename T> const T *castAs() const;
1721 /// A variant of castAs<> for array type which silently discards
1722 /// qualifiers from the outermost type.
1723 const ArrayType *castAsArrayTypeUnsafe() const;
1725 /// getBaseElementTypeUnsafe - Get the base element type of this
1726 /// type, potentially discarding type qualifiers. This method
1727 /// should never be used when type qualifiers are meaningful.
1728 const Type *getBaseElementTypeUnsafe() const;
1730 /// getArrayElementTypeNoTypeQual - If this is an array type, return the
1731 /// element type of the array, potentially with type qualifiers missing.
1732 /// This method should never be used when type qualifiers are meaningful.
1733 const Type *getArrayElementTypeNoTypeQual() const;
1735 /// getPointeeType - If this is a pointer, ObjC object pointer, or block
1736 /// pointer, this returns the respective pointee.
1737 QualType getPointeeType() const;
1739 /// getUnqualifiedDesugaredType() - Return the specified type with
1740 /// any "sugar" removed from the type, removing any typedefs,
1741 /// typeofs, etc., as well as any qualifiers.
1742 const Type *getUnqualifiedDesugaredType() const;
1744 /// More type predicates useful for type checking/promotion
1745 bool isPromotableIntegerType() const; // C99 6.3.1.1p2
1747 /// isSignedIntegerType - Return true if this is an integer type that is
1748 /// signed, according to C99 6.2.5p4 [char, signed char, short, int, long..],
1749 /// or an enum decl which has a signed representation.
1750 bool isSignedIntegerType() const;
1752 /// isUnsignedIntegerType - Return true if this is an integer type that is
1753 /// unsigned, according to C99 6.2.5p6 [which returns true for _Bool],
1754 /// or an enum decl which has an unsigned representation.
1755 bool isUnsignedIntegerType() const;
1757 /// Determines whether this is an integer type that is signed or an
1758 /// enumeration types whose underlying type is a signed integer type.
1759 bool isSignedIntegerOrEnumerationType() const;
1761 /// Determines whether this is an integer type that is unsigned or an
1762 /// enumeration types whose underlying type is a unsigned integer type.
1763 bool isUnsignedIntegerOrEnumerationType() const;
1765 /// isConstantSizeType - Return true if this is not a variable sized type,
1766 /// according to the rules of C99 6.7.5p3. It is not legal to call this on
1767 /// incomplete types.
1768 bool isConstantSizeType() const;
1770 /// isSpecifierType - Returns true if this type can be represented by some
1771 /// set of type specifiers.
1772 bool isSpecifierType() const;
1774 /// \brief Determine the linkage of this type.
1775 Linkage getLinkage() const;
1777 /// \brief Determine the visibility of this type.
1778 Visibility getVisibility() const {
1779 return getLinkageAndVisibility().getVisibility();
1782 /// \brief Return true if the visibility was explicitly set is the code.
1783 bool isVisibilityExplicit() const {
1784 return getLinkageAndVisibility().isVisibilityExplicit();
1787 /// \brief Determine the linkage and visibility of this type.
1788 LinkageInfo getLinkageAndVisibility() const;
1790 /// \brief True if the computed linkage is valid. Used for consistency
1791 /// checking. Should always return true.
1792 bool isLinkageValid() const;
1794 const char *getTypeClassName() const;
1796 QualType getCanonicalTypeInternal() const {
1797 return CanonicalType;
1799 CanQualType getCanonicalTypeUnqualified() const; // in CanonicalType.h
1800 LLVM_ATTRIBUTE_USED void dump() const;
1802 friend class ASTReader;
1803 friend class ASTWriter;
1806 /// \brief This will check for a TypedefType by removing any existing sugar
1807 /// until it reaches a TypedefType or a non-sugared type.
1808 template <> const TypedefType *Type::getAs() const;
1810 /// \brief This will check for a TemplateSpecializationType by removing any
1811 /// existing sugar until it reaches a TemplateSpecializationType or a
1812 /// non-sugared type.
1813 template <> const TemplateSpecializationType *Type::getAs() const;
1815 /// \brief This will check for an AttributedType by removing any existing sugar
1816 /// until it reaches an AttributedType or a non-sugared type.
1817 template <> const AttributedType *Type::getAs() const;
1819 // We can do canonical leaf types faster, because we don't have to
1820 // worry about preserving child type decoration.
1821 #define TYPE(Class, Base)
1822 #define LEAF_TYPE(Class) \
1823 template <> inline const Class##Type *Type::getAs() const { \
1824 return dyn_cast<Class##Type>(CanonicalType); \
1826 template <> inline const Class##Type *Type::castAs() const { \
1827 return cast<Class##Type>(CanonicalType); \
1829 #include "clang/AST/TypeNodes.def"
1832 /// BuiltinType - This class is used for builtin types like 'int'. Builtin
1833 /// types are always canonical and have a literal name field.
1834 class BuiltinType : public Type {
1837 #define BUILTIN_TYPE(Id, SingletonId) Id,
1838 #define LAST_BUILTIN_TYPE(Id) LastKind = Id
1839 #include "clang/AST/BuiltinTypes.def"
1844 : Type(Builtin, QualType(), /*Dependent=*/(K == Dependent),
1845 /*InstantiationDependent=*/(K == Dependent),
1846 /*VariablyModified=*/false,
1847 /*Unexpanded paramter pack=*/false) {
1848 BuiltinTypeBits.Kind = K;
1851 Kind getKind() const { return static_cast<Kind>(BuiltinTypeBits.Kind); }
1852 StringRef getName(const PrintingPolicy &Policy) const;
1853 const char *getNameAsCString(const PrintingPolicy &Policy) const {
1854 // The StringRef is null-terminated.
1855 StringRef str = getName(Policy);
1856 assert(!str.empty() && str.data()[str.size()] == '\0');
1860 bool isSugared() const { return false; }
1861 QualType desugar() const { return QualType(this, 0); }
1863 bool isInteger() const {
1864 return getKind() >= Bool && getKind() <= Int128;
1867 bool isSignedInteger() const {
1868 return getKind() >= Char_S && getKind() <= Int128;
1871 bool isUnsignedInteger() const {
1872 return getKind() >= Bool && getKind() <= UInt128;
1875 bool isFloatingPoint() const {
1876 return getKind() >= Half && getKind() <= LongDouble;
1879 /// Determines whether the given kind corresponds to a placeholder type.
1880 static bool isPlaceholderTypeKind(Kind K) {
1881 return K >= Overload;
1884 /// Determines whether this type is a placeholder type, i.e. a type
1885 /// which cannot appear in arbitrary positions in a fully-formed
1887 bool isPlaceholderType() const {
1888 return isPlaceholderTypeKind(getKind());
1891 /// Determines whether this type is a placeholder type other than
1892 /// Overload. Most placeholder types require only syntactic
1893 /// information about their context in order to be resolved (e.g.
1894 /// whether it is a call expression), which means they can (and
1895 /// should) be resolved in an earlier "phase" of analysis.
1896 /// Overload expressions sometimes pick up further information
1897 /// from their context, like whether the context expects a
1898 /// specific function-pointer type, and so frequently need
1899 /// special treatment.
1900 bool isNonOverloadPlaceholderType() const {
1901 return getKind() > Overload;
1904 static bool classof(const Type *T) { return T->getTypeClass() == Builtin; }
1907 /// ComplexType - C99 6.2.5p11 - Complex values. This supports the C99 complex
1908 /// types (_Complex float etc) as well as the GCC integer complex extensions.
1910 class ComplexType : public Type, public llvm::FoldingSetNode {
1911 QualType ElementType;
1912 ComplexType(QualType Element, QualType CanonicalPtr) :
1913 Type(Complex, CanonicalPtr, Element->isDependentType(),
1914 Element->isInstantiationDependentType(),
1915 Element->isVariablyModifiedType(),
1916 Element->containsUnexpandedParameterPack()),
1917 ElementType(Element) {
1919 friend class ASTContext; // ASTContext creates these.
1922 QualType getElementType() const { return ElementType; }
1924 bool isSugared() const { return false; }
1925 QualType desugar() const { return QualType(this, 0); }
1927 void Profile(llvm::FoldingSetNodeID &ID) {
1928 Profile(ID, getElementType());
1930 static void Profile(llvm::FoldingSetNodeID &ID, QualType Element) {
1931 ID.AddPointer(Element.getAsOpaquePtr());
1934 static bool classof(const Type *T) { return T->getTypeClass() == Complex; }
1937 /// ParenType - Sugar for parentheses used when specifying types.
1939 class ParenType : public Type, public llvm::FoldingSetNode {
1942 ParenType(QualType InnerType, QualType CanonType) :
1943 Type(Paren, CanonType, InnerType->isDependentType(),
1944 InnerType->isInstantiationDependentType(),
1945 InnerType->isVariablyModifiedType(),
1946 InnerType->containsUnexpandedParameterPack()),
1949 friend class ASTContext; // ASTContext creates these.
1953 QualType getInnerType() const { return Inner; }
1955 bool isSugared() const { return true; }
1956 QualType desugar() const { return getInnerType(); }
1958 void Profile(llvm::FoldingSetNodeID &ID) {
1959 Profile(ID, getInnerType());
1961 static void Profile(llvm::FoldingSetNodeID &ID, QualType Inner) {
1965 static bool classof(const Type *T) { return T->getTypeClass() == Paren; }
1968 /// PointerType - C99 6.7.5.1 - Pointer Declarators.
1970 class PointerType : public Type, public llvm::FoldingSetNode {
1971 QualType PointeeType;
1973 PointerType(QualType Pointee, QualType CanonicalPtr) :
1974 Type(Pointer, CanonicalPtr, Pointee->isDependentType(),
1975 Pointee->isInstantiationDependentType(),
1976 Pointee->isVariablyModifiedType(),
1977 Pointee->containsUnexpandedParameterPack()),
1978 PointeeType(Pointee) {
1980 friend class ASTContext; // ASTContext creates these.
1984 QualType getPointeeType() const { return PointeeType; }
1986 bool isSugared() const { return false; }
1987 QualType desugar() const { return QualType(this, 0); }
1989 void Profile(llvm::FoldingSetNodeID &ID) {
1990 Profile(ID, getPointeeType());
1992 static void Profile(llvm::FoldingSetNodeID &ID, QualType Pointee) {
1993 ID.AddPointer(Pointee.getAsOpaquePtr());
1996 static bool classof(const Type *T) { return T->getTypeClass() == Pointer; }
1999 /// \brief Represents a pointer type decayed from an array or function type.
2000 class DecayedType : public Type, public llvm::FoldingSetNode {
2001 QualType OriginalType;
2002 QualType DecayedPointer;
2004 DecayedType(QualType OriginalType, QualType DecayedPointer,
2005 QualType CanonicalPtr)
2006 : Type(Decayed, CanonicalPtr, OriginalType->isDependentType(),
2007 OriginalType->isInstantiationDependentType(),
2008 OriginalType->isVariablyModifiedType(),
2009 OriginalType->containsUnexpandedParameterPack()),
2010 OriginalType(OriginalType), DecayedPointer(DecayedPointer) {
2011 assert(isa<PointerType>(DecayedPointer));
2014 friend class ASTContext; // ASTContext creates these.
2017 QualType getDecayedType() const { return DecayedPointer; }
2018 QualType getOriginalType() const { return OriginalType; }
2020 QualType getPointeeType() const {
2021 return cast<PointerType>(DecayedPointer)->getPointeeType();
2024 bool isSugared() const { return true; }
2025 QualType desugar() const { return DecayedPointer; }
2027 void Profile(llvm::FoldingSetNodeID &ID) {
2028 Profile(ID, OriginalType);
2030 static void Profile(llvm::FoldingSetNodeID &ID, QualType OriginalType) {
2031 ID.AddPointer(OriginalType.getAsOpaquePtr());
2034 static bool classof(const Type *T) { return T->getTypeClass() == Decayed; }
2037 /// BlockPointerType - pointer to a block type.
2038 /// This type is to represent types syntactically represented as
2039 /// "void (^)(int)", etc. Pointee is required to always be a function type.
2041 class BlockPointerType : public Type, public llvm::FoldingSetNode {
2042 QualType PointeeType; // Block is some kind of pointer type
2043 BlockPointerType(QualType Pointee, QualType CanonicalCls) :
2044 Type(BlockPointer, CanonicalCls, Pointee->isDependentType(),
2045 Pointee->isInstantiationDependentType(),
2046 Pointee->isVariablyModifiedType(),
2047 Pointee->containsUnexpandedParameterPack()),
2048 PointeeType(Pointee) {
2050 friend class ASTContext; // ASTContext creates these.
2054 // Get the pointee type. Pointee is required to always be a function type.
2055 QualType getPointeeType() const { return PointeeType; }
2057 bool isSugared() const { return false; }
2058 QualType desugar() const { return QualType(this, 0); }
2060 void Profile(llvm::FoldingSetNodeID &ID) {
2061 Profile(ID, getPointeeType());
2063 static void Profile(llvm::FoldingSetNodeID &ID, QualType Pointee) {
2064 ID.AddPointer(Pointee.getAsOpaquePtr());
2067 static bool classof(const Type *T) {
2068 return T->getTypeClass() == BlockPointer;
2072 /// ReferenceType - Base for LValueReferenceType and RValueReferenceType
2074 class ReferenceType : public Type, public llvm::FoldingSetNode {
2075 QualType PointeeType;
2078 ReferenceType(TypeClass tc, QualType Referencee, QualType CanonicalRef,
2079 bool SpelledAsLValue) :
2080 Type(tc, CanonicalRef, Referencee->isDependentType(),
2081 Referencee->isInstantiationDependentType(),
2082 Referencee->isVariablyModifiedType(),
2083 Referencee->containsUnexpandedParameterPack()),
2084 PointeeType(Referencee)
2086 ReferenceTypeBits.SpelledAsLValue = SpelledAsLValue;
2087 ReferenceTypeBits.InnerRef = Referencee->isReferenceType();
2091 bool isSpelledAsLValue() const { return ReferenceTypeBits.SpelledAsLValue; }
2092 bool isInnerRef() const { return ReferenceTypeBits.InnerRef; }
2094 QualType getPointeeTypeAsWritten() const { return PointeeType; }
2095 QualType getPointeeType() const {
2096 // FIXME: this might strip inner qualifiers; okay?
2097 const ReferenceType *T = this;
2098 while (T->isInnerRef())
2099 T = T->PointeeType->castAs<ReferenceType>();
2100 return T->PointeeType;
2103 void Profile(llvm::FoldingSetNodeID &ID) {
2104 Profile(ID, PointeeType, isSpelledAsLValue());
2106 static void Profile(llvm::FoldingSetNodeID &ID,
2107 QualType Referencee,
2108 bool SpelledAsLValue) {
2109 ID.AddPointer(Referencee.getAsOpaquePtr());
2110 ID.AddBoolean(SpelledAsLValue);
2113 static bool classof(const Type *T) {
2114 return T->getTypeClass() == LValueReference ||
2115 T->getTypeClass() == RValueReference;
2119 /// LValueReferenceType - C++ [dcl.ref] - Lvalue reference
2121 class LValueReferenceType : public ReferenceType {
2122 LValueReferenceType(QualType Referencee, QualType CanonicalRef,
2123 bool SpelledAsLValue) :
2124 ReferenceType(LValueReference, Referencee, CanonicalRef, SpelledAsLValue)
2126 friend class ASTContext; // ASTContext creates these
2128 bool isSugared() const { return false; }
2129 QualType desugar() const { return QualType(this, 0); }
2131 static bool classof(const Type *T) {
2132 return T->getTypeClass() == LValueReference;
2136 /// RValueReferenceType - C++0x [dcl.ref] - Rvalue reference
2138 class RValueReferenceType : public ReferenceType {
2139 RValueReferenceType(QualType Referencee, QualType CanonicalRef) :
2140 ReferenceType(RValueReference, Referencee, CanonicalRef, false) {
2142 friend class ASTContext; // ASTContext creates these
2144 bool isSugared() const { return false; }
2145 QualType desugar() const { return QualType(this, 0); }
2147 static bool classof(const Type *T) {
2148 return T->getTypeClass() == RValueReference;
2152 /// MemberPointerType - C++ 8.3.3 - Pointers to members
2154 class MemberPointerType : public Type, public llvm::FoldingSetNode {
2155 QualType PointeeType;
2156 /// The class of which the pointee is a member. Must ultimately be a
2157 /// RecordType, but could be a typedef or a template parameter too.
2160 MemberPointerType(QualType Pointee, const Type *Cls, QualType CanonicalPtr) :
2161 Type(MemberPointer, CanonicalPtr,
2162 Cls->isDependentType() || Pointee->isDependentType(),
2163 (Cls->isInstantiationDependentType() ||
2164 Pointee->isInstantiationDependentType()),
2165 Pointee->isVariablyModifiedType(),
2166 (Cls->containsUnexpandedParameterPack() ||
2167 Pointee->containsUnexpandedParameterPack())),
2168 PointeeType(Pointee), Class(Cls) {
2170 friend class ASTContext; // ASTContext creates these.
2173 QualType getPointeeType() const { return PointeeType; }
2175 /// Returns true if the member type (i.e. the pointee type) is a
2176 /// function type rather than a data-member type.
2177 bool isMemberFunctionPointer() const {
2178 return PointeeType->isFunctionProtoType();
2181 /// Returns true if the member type (i.e. the pointee type) is a
2182 /// data type rather than a function type.
2183 bool isMemberDataPointer() const {
2184 return !PointeeType->isFunctionProtoType();
2187 const Type *getClass() const { return Class; }
2189 bool isSugared() const { return false; }
2190 QualType desugar() const { return QualType(this, 0); }
2192 void Profile(llvm::FoldingSetNodeID &ID) {
2193 Profile(ID, getPointeeType(), getClass());
2195 static void Profile(llvm::FoldingSetNodeID &ID, QualType Pointee,
2196 const Type *Class) {
2197 ID.AddPointer(Pointee.getAsOpaquePtr());
2198 ID.AddPointer(Class);
2201 static bool classof(const Type *T) {
2202 return T->getTypeClass() == MemberPointer;
2206 /// ArrayType - C99 6.7.5.2 - Array Declarators.
2208 class ArrayType : public Type, public llvm::FoldingSetNode {
2210 /// ArraySizeModifier - Capture whether this is a normal array (e.g. int X[4])
2211 /// an array with a static size (e.g. int X[static 4]), or an array
2212 /// with a star size (e.g. int X[*]).
2213 /// 'static' is only allowed on function parameters.
2214 enum ArraySizeModifier {
2215 Normal, Static, Star
2218 /// ElementType - The element type of the array.
2219 QualType ElementType;
2222 // C++ [temp.dep.type]p1:
2223 // A type is dependent if it is...
2224 // - an array type constructed from any dependent type or whose
2225 // size is specified by a constant expression that is
2227 ArrayType(TypeClass tc, QualType et, QualType can,
2228 ArraySizeModifier sm, unsigned tq,
2229 bool ContainsUnexpandedParameterPack)
2230 : Type(tc, can, et->isDependentType() || tc == DependentSizedArray,
2231 et->isInstantiationDependentType() || tc == DependentSizedArray,
2232 (tc == VariableArray || et->isVariablyModifiedType()),
2233 ContainsUnexpandedParameterPack),
2235 ArrayTypeBits.IndexTypeQuals = tq;
2236 ArrayTypeBits.SizeModifier = sm;
2239 friend class ASTContext; // ASTContext creates these.
2242 QualType getElementType() const { return ElementType; }
2243 ArraySizeModifier getSizeModifier() const {
2244 return ArraySizeModifier(ArrayTypeBits.SizeModifier);
2246 Qualifiers getIndexTypeQualifiers() const {
2247 return Qualifiers::fromCVRMask(getIndexTypeCVRQualifiers());
2249 unsigned getIndexTypeCVRQualifiers() const {
2250 return ArrayTypeBits.IndexTypeQuals;
2253 static bool classof(const Type *T) {
2254 return T->getTypeClass() == ConstantArray ||
2255 T->getTypeClass() == VariableArray ||
2256 T->getTypeClass() == IncompleteArray ||
2257 T->getTypeClass() == DependentSizedArray;
2261 /// ConstantArrayType - This class represents the canonical version of
2262 /// C arrays with a specified constant size. For example, the canonical
2263 /// type for 'int A[4 + 4*100]' is a ConstantArrayType where the element
2264 /// type is 'int' and the size is 404.
2265 class ConstantArrayType : public ArrayType {
2266 llvm::APInt Size; // Allows us to unique the type.
2268 ConstantArrayType(QualType et, QualType can, const llvm::APInt &size,
2269 ArraySizeModifier sm, unsigned tq)
2270 : ArrayType(ConstantArray, et, can, sm, tq,
2271 et->containsUnexpandedParameterPack()),
2274 ConstantArrayType(TypeClass tc, QualType et, QualType can,
2275 const llvm::APInt &size, ArraySizeModifier sm, unsigned tq)
2276 : ArrayType(tc, et, can, sm, tq, et->containsUnexpandedParameterPack()),
2278 friend class ASTContext; // ASTContext creates these.
2280 const llvm::APInt &getSize() const { return Size; }
2281 bool isSugared() const { return false; }
2282 QualType desugar() const { return QualType(this, 0); }
2285 /// \brief Determine the number of bits required to address a member of
2286 // an array with the given element type and number of elements.
2287 static unsigned getNumAddressingBits(ASTContext &Context,
2288 QualType ElementType,
2289 const llvm::APInt &NumElements);
2291 /// \brief Determine the maximum number of active bits that an array's size
2292 /// can require, which limits the maximum size of the array.
2293 static unsigned getMaxSizeBits(ASTContext &Context);
2295 void Profile(llvm::FoldingSetNodeID &ID) {
2296 Profile(ID, getElementType(), getSize(),
2297 getSizeModifier(), getIndexTypeCVRQualifiers());
2299 static void Profile(llvm::FoldingSetNodeID &ID, QualType ET,
2300 const llvm::APInt &ArraySize, ArraySizeModifier SizeMod,
2301 unsigned TypeQuals) {
2302 ID.AddPointer(ET.getAsOpaquePtr());
2303 ID.AddInteger(ArraySize.getZExtValue());
2304 ID.AddInteger(SizeMod);
2305 ID.AddInteger(TypeQuals);
2307 static bool classof(const Type *T) {
2308 return T->getTypeClass() == ConstantArray;
2312 /// IncompleteArrayType - This class represents C arrays with an unspecified
2313 /// size. For example 'int A[]' has an IncompleteArrayType where the element
2314 /// type is 'int' and the size is unspecified.
2315 class IncompleteArrayType : public ArrayType {
2317 IncompleteArrayType(QualType et, QualType can,
2318 ArraySizeModifier sm, unsigned tq)
2319 : ArrayType(IncompleteArray, et, can, sm, tq,
2320 et->containsUnexpandedParameterPack()) {}
2321 friend class ASTContext; // ASTContext creates these.
2323 bool isSugared() const { return false; }
2324 QualType desugar() const { return QualType(this, 0); }
2326 static bool classof(const Type *T) {
2327 return T->getTypeClass() == IncompleteArray;
2330 friend class StmtIteratorBase;
2332 void Profile(llvm::FoldingSetNodeID &ID) {
2333 Profile(ID, getElementType(), getSizeModifier(),
2334 getIndexTypeCVRQualifiers());
2337 static void Profile(llvm::FoldingSetNodeID &ID, QualType ET,
2338 ArraySizeModifier SizeMod, unsigned TypeQuals) {
2339 ID.AddPointer(ET.getAsOpaquePtr());
2340 ID.AddInteger(SizeMod);
2341 ID.AddInteger(TypeQuals);
2345 /// VariableArrayType - This class represents C arrays with a specified size
2346 /// which is not an integer-constant-expression. For example, 'int s[x+foo()]'.
2347 /// Since the size expression is an arbitrary expression, we store it as such.
2349 /// Note: VariableArrayType's aren't uniqued (since the expressions aren't) and
2350 /// should not be: two lexically equivalent variable array types could mean
2351 /// different things, for example, these variables do not have the same type
2354 /// void foo(int x) {
2360 class VariableArrayType : public ArrayType {
2361 /// SizeExpr - An assignment expression. VLA's are only permitted within
2362 /// a function block.
2364 /// Brackets - The left and right array brackets.
2365 SourceRange Brackets;
2367 VariableArrayType(QualType et, QualType can, Expr *e,
2368 ArraySizeModifier sm, unsigned tq,
2369 SourceRange brackets)
2370 : ArrayType(VariableArray, et, can, sm, tq,
2371 et->containsUnexpandedParameterPack()),
2372 SizeExpr((Stmt*) e), Brackets(brackets) {}
2373 friend class ASTContext; // ASTContext creates these.
2376 Expr *getSizeExpr() const {
2377 // We use C-style casts instead of cast<> here because we do not wish
2378 // to have a dependency of Type.h on Stmt.h/Expr.h.
2379 return (Expr*) SizeExpr;
2381 SourceRange getBracketsRange() const { return Brackets; }
2382 SourceLocation getLBracketLoc() const { return Brackets.getBegin(); }
2383 SourceLocation getRBracketLoc() const { return Brackets.getEnd(); }
2385 bool isSugared() const { return false; }
2386 QualType desugar() const { return QualType(this, 0); }
2388 static bool classof(const Type *T) {
2389 return T->getTypeClass() == VariableArray;
2392 friend class StmtIteratorBase;
2394 void Profile(llvm::FoldingSetNodeID &ID) {
2395 llvm_unreachable("Cannot unique VariableArrayTypes.");
2399 /// DependentSizedArrayType - This type represents an array type in
2400 /// C++ whose size is a value-dependent expression. For example:
2403 /// template<typename T, int Size>
2409 /// For these types, we won't actually know what the array bound is
2410 /// until template instantiation occurs, at which point this will
2411 /// become either a ConstantArrayType or a VariableArrayType.
2412 class DependentSizedArrayType : public ArrayType {
2413 const ASTContext &Context;
2415 /// \brief An assignment expression that will instantiate to the
2416 /// size of the array.
2418 /// The expression itself might be NULL, in which case the array
2419 /// type will have its size deduced from an initializer.
2422 /// Brackets - The left and right array brackets.
2423 SourceRange Brackets;
2425 DependentSizedArrayType(const ASTContext &Context, QualType et, QualType can,
2426 Expr *e, ArraySizeModifier sm, unsigned tq,
2427 SourceRange brackets);
2429 friend class ASTContext; // ASTContext creates these.
2432 Expr *getSizeExpr() const {
2433 // We use C-style casts instead of cast<> here because we do not wish
2434 // to have a dependency of Type.h on Stmt.h/Expr.h.
2435 return (Expr*) SizeExpr;
2437 SourceRange getBracketsRange() const { return Brackets; }
2438 SourceLocation getLBracketLoc() const { return Brackets.getBegin(); }
2439 SourceLocation getRBracketLoc() const { return Brackets.getEnd(); }
2441 bool isSugared() const { return false; }
2442 QualType desugar() const { return QualType(this, 0); }
2444 static bool classof(const Type *T) {
2445 return T->getTypeClass() == DependentSizedArray;
2448 friend class StmtIteratorBase;
2451 void Profile(llvm::FoldingSetNodeID &ID) {
2452 Profile(ID, Context, getElementType(),
2453 getSizeModifier(), getIndexTypeCVRQualifiers(), getSizeExpr());
2456 static void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context,
2457 QualType ET, ArraySizeModifier SizeMod,
2458 unsigned TypeQuals, Expr *E);
2461 /// DependentSizedExtVectorType - This type represent an extended vector type
2462 /// where either the type or size is dependent. For example:
2464 /// template<typename T, int Size>
2466 /// typedef T __attribute__((ext_vector_type(Size))) type;
2469 class DependentSizedExtVectorType : public Type, public llvm::FoldingSetNode {
2470 const ASTContext &Context;
2472 /// ElementType - The element type of the array.
2473 QualType ElementType;
2476 DependentSizedExtVectorType(const ASTContext &Context, QualType ElementType,
2477 QualType can, Expr *SizeExpr, SourceLocation loc);
2479 friend class ASTContext;
2482 Expr *getSizeExpr() const { return SizeExpr; }
2483 QualType getElementType() const { return ElementType; }
2484 SourceLocation getAttributeLoc() const { return loc; }
2486 bool isSugared() const { return false; }
2487 QualType desugar() const { return QualType(this, 0); }
2489 static bool classof(const Type *T) {
2490 return T->getTypeClass() == DependentSizedExtVector;
2493 void Profile(llvm::FoldingSetNodeID &ID) {
2494 Profile(ID, Context, getElementType(), getSizeExpr());
2497 static void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context,
2498 QualType ElementType, Expr *SizeExpr);
2502 /// VectorType - GCC generic vector type. This type is created using
2503 /// __attribute__((vector_size(n)), where "n" specifies the vector size in
2504 /// bytes; or from an Altivec __vector or vector declaration.
2505 /// Since the constructor takes the number of vector elements, the
2506 /// client is responsible for converting the size into the number of elements.
2507 class VectorType : public Type, public llvm::FoldingSetNode {
2510 GenericVector, // not a target-specific vector type
2511 AltiVecVector, // is AltiVec vector
2512 AltiVecPixel, // is AltiVec 'vector Pixel'
2513 AltiVecBool, // is AltiVec 'vector bool ...'
2514 NeonVector, // is ARM Neon vector
2515 NeonPolyVector // is ARM Neon polynomial vector
2518 /// ElementType - The element type of the vector.
2519 QualType ElementType;
2521 VectorType(QualType vecType, unsigned nElements, QualType canonType,
2522 VectorKind vecKind);
2524 VectorType(TypeClass tc, QualType vecType, unsigned nElements,
2525 QualType canonType, VectorKind vecKind);
2527 friend class ASTContext; // ASTContext creates these.
2531 QualType getElementType() const { return ElementType; }
2532 unsigned getNumElements() const { return VectorTypeBits.NumElements; }
2533 static bool isVectorSizeTooLarge(unsigned NumElements) {
2534 return NumElements > VectorTypeBitfields::MaxNumElements;
2537 bool isSugared() const { return false; }
2538 QualType desugar() const { return QualType(this, 0); }
2540 VectorKind getVectorKind() const {
2541 return VectorKind(VectorTypeBits.VecKind);
2544 void Profile(llvm::FoldingSetNodeID &ID) {
2545 Profile(ID, getElementType(), getNumElements(),
2546 getTypeClass(), getVectorKind());
2548 static void Profile(llvm::FoldingSetNodeID &ID, QualType ElementType,
2549 unsigned NumElements, TypeClass TypeClass,
2550 VectorKind VecKind) {
2551 ID.AddPointer(ElementType.getAsOpaquePtr());
2552 ID.AddInteger(NumElements);
2553 ID.AddInteger(TypeClass);
2554 ID.AddInteger(VecKind);
2557 static bool classof(const Type *T) {
2558 return T->getTypeClass() == Vector || T->getTypeClass() == ExtVector;
2562 /// ExtVectorType - Extended vector type. This type is created using
2563 /// __attribute__((ext_vector_type(n)), where "n" is the number of elements.
2564 /// Unlike vector_size, ext_vector_type is only allowed on typedef's. This
2565 /// class enables syntactic extensions, like Vector Components for accessing
2566 /// points, colors, and textures (modeled after OpenGL Shading Language).
2567 class ExtVectorType : public VectorType {
2568 ExtVectorType(QualType vecType, unsigned nElements, QualType canonType) :
2569 VectorType(ExtVector, vecType, nElements, canonType, GenericVector) {}
2570 friend class ASTContext; // ASTContext creates these.
2572 static int getPointAccessorIdx(char c) {
2581 static int getNumericAccessorIdx(char c) {
2595 case 'a': return 10;
2597 case 'b': return 11;
2599 case 'c': return 12;
2601 case 'd': return 13;
2603 case 'e': return 14;
2605 case 'f': return 15;
2609 static int getAccessorIdx(char c) {
2610 if (int idx = getPointAccessorIdx(c)+1) return idx-1;
2611 return getNumericAccessorIdx(c);
2614 bool isAccessorWithinNumElements(char c) const {
2615 if (int idx = getAccessorIdx(c)+1)
2616 return unsigned(idx-1) < getNumElements();
2619 bool isSugared() const { return false; }
2620 QualType desugar() const { return QualType(this, 0); }
2622 static bool classof(const Type *T) {
2623 return T->getTypeClass() == ExtVector;
2627 /// FunctionType - C99 6.7.5.3 - Function Declarators. This is the common base
2628 /// class of FunctionNoProtoType and FunctionProtoType.
2630 class FunctionType : public Type {
2631 // The type returned by the function.
2632 QualType ResultType;
2635 /// ExtInfo - A class which abstracts out some details necessary for
2638 /// It is not actually used directly for storing this information in
2639 /// a FunctionType, although FunctionType does currently use the
2640 /// same bit-pattern.
2642 // If you add a field (say Foo), other than the obvious places (both,
2643 // constructors, compile failures), what you need to update is
2647 // * functionType. Add Foo, getFoo.
2648 // * ASTContext::getFooType
2649 // * ASTContext::mergeFunctionTypes
2650 // * FunctionNoProtoType::Profile
2651 // * FunctionProtoType::Profile
2652 // * TypePrinter::PrintFunctionProto
2653 // * AST read and write
2656 // Feel free to rearrange or add bits, but if you go over 9,
2657 // you'll need to adjust both the Bits field below and
2658 // Type::FunctionTypeBitfields.
2660 // | CC |noreturn|produces|regparm|
2661 // |0 .. 3| 4 | 5 | 6 .. 8|
2663 // regparm is either 0 (no regparm attribute) or the regparm value+1.
2664 enum { CallConvMask = 0xF };
2665 enum { NoReturnMask = 0x10 };
2666 enum { ProducesResultMask = 0x20 };
2667 enum { RegParmMask = ~(CallConvMask | NoReturnMask | ProducesResultMask),
2668 RegParmOffset = 6 }; // Assumed to be the last field
2672 ExtInfo(unsigned Bits) : Bits(static_cast<uint16_t>(Bits)) {}
2674 friend class FunctionType;
2677 // Constructor with no defaults. Use this when you know that you
2678 // have all the elements (when reading an AST file for example).
2679 ExtInfo(bool noReturn, bool hasRegParm, unsigned regParm, CallingConv cc,
2680 bool producesResult) {
2681 assert((!hasRegParm || regParm < 7) && "Invalid regparm value");
2682 Bits = ((unsigned) cc) |
2683 (noReturn ? NoReturnMask : 0) |
2684 (producesResult ? ProducesResultMask : 0) |
2685 (hasRegParm ? ((regParm + 1) << RegParmOffset) : 0);
2688 // Constructor with all defaults. Use when for example creating a
2689 // function know to use defaults.
2690 ExtInfo() : Bits(CC_C) { }
2692 // Constructor with just the calling convention, which is an important part
2693 // of the canonical type.
2694 ExtInfo(CallingConv CC) : Bits(CC) { }
2696 bool getNoReturn() const { return Bits & NoReturnMask; }
2697 bool getProducesResult() const { return Bits & ProducesResultMask; }
2698 bool getHasRegParm() const { return (Bits >> RegParmOffset) != 0; }
2699 unsigned getRegParm() const {
2700 unsigned RegParm = Bits >> RegParmOffset;
2705 CallingConv getCC() const { return CallingConv(Bits & CallConvMask); }
2707 bool operator==(ExtInfo Other) const {
2708 return Bits == Other.Bits;
2710 bool operator!=(ExtInfo Other) const {
2711 return Bits != Other.Bits;
2714 // Note that we don't have setters. That is by design, use
2715 // the following with methods instead of mutating these objects.
2717 ExtInfo withNoReturn(bool noReturn) const {
2719 return ExtInfo(Bits | NoReturnMask);
2721 return ExtInfo(Bits & ~NoReturnMask);
2724 ExtInfo withProducesResult(bool producesResult) const {
2726 return ExtInfo(Bits | ProducesResultMask);
2728 return ExtInfo(Bits & ~ProducesResultMask);
2731 ExtInfo withRegParm(unsigned RegParm) const {
2732 assert(RegParm < 7 && "Invalid regparm value");
2733 return ExtInfo((Bits & ~RegParmMask) |
2734 ((RegParm + 1) << RegParmOffset));
2737 ExtInfo withCallingConv(CallingConv cc) const {
2738 return ExtInfo((Bits & ~CallConvMask) | (unsigned) cc);
2741 void Profile(llvm::FoldingSetNodeID &ID) const {
2742 ID.AddInteger(Bits);
2747 FunctionType(TypeClass tc, QualType res,
2748 unsigned typeQuals, QualType Canonical, bool Dependent,
2749 bool InstantiationDependent,
2750 bool VariablyModified, bool ContainsUnexpandedParameterPack,
2752 : Type(tc, Canonical, Dependent, InstantiationDependent, VariablyModified,
2753 ContainsUnexpandedParameterPack),
2755 FunctionTypeBits.ExtInfo = Info.Bits;
2756 FunctionTypeBits.TypeQuals = typeQuals;
2758 unsigned getTypeQuals() const { return FunctionTypeBits.TypeQuals; }
2762 QualType getResultType() const { return ResultType; }
2764 bool getHasRegParm() const { return getExtInfo().getHasRegParm(); }
2765 unsigned getRegParmType() const { return getExtInfo().getRegParm(); }
2766 /// \brief Determine whether this function type includes the GNU noreturn
2767 /// attribute. The C++11 [[noreturn]] attribute does not affect the function
2769 bool getNoReturnAttr() const { return getExtInfo().getNoReturn(); }
2770 CallingConv getCallConv() const { return getExtInfo().getCC(); }
2771 ExtInfo getExtInfo() const { return ExtInfo(FunctionTypeBits.ExtInfo); }
2772 bool isConst() const { return getTypeQuals() & Qualifiers::Const; }
2773 bool isVolatile() const { return getTypeQuals() & Qualifiers::Volatile; }
2774 bool isRestrict() const { return getTypeQuals() & Qualifiers::Restrict; }
2776 /// \brief Determine the type of an expression that calls a function of
2778 QualType getCallResultType(ASTContext &Context) const {
2779 return getResultType().getNonLValueExprType(Context);
2782 static StringRef getNameForCallConv(CallingConv CC);
2784 static bool classof(const Type *T) {
2785 return T->getTypeClass() == FunctionNoProto ||
2786 T->getTypeClass() == FunctionProto;
2790 /// FunctionNoProtoType - Represents a K&R-style 'int foo()' function, which has
2791 /// no information available about its arguments.
2792 class FunctionNoProtoType : public FunctionType, public llvm::FoldingSetNode {
2793 FunctionNoProtoType(QualType Result, QualType Canonical, ExtInfo Info)
2794 : FunctionType(FunctionNoProto, Result, 0, Canonical,
2795 /*Dependent=*/false, /*InstantiationDependent=*/false,
2796 Result->isVariablyModifiedType(),
2797 /*ContainsUnexpandedParameterPack=*/false, Info) {}
2799 friend class ASTContext; // ASTContext creates these.
2802 // No additional state past what FunctionType provides.
2804 bool isSugared() const { return false; }
2805 QualType desugar() const { return QualType(this, 0); }
2807 void Profile(llvm::FoldingSetNodeID &ID) {
2808 Profile(ID, getResultType(), getExtInfo());
2810 static void Profile(llvm::FoldingSetNodeID &ID, QualType ResultType,
2813 ID.AddPointer(ResultType.getAsOpaquePtr());
2816 static bool classof(const Type *T) {
2817 return T->getTypeClass() == FunctionNoProto;
2821 /// FunctionProtoType - Represents a prototype with argument type info, e.g.
2822 /// 'int foo(int)' or 'int foo(void)'. 'void' is represented as having no
2823 /// arguments, not as having a single void argument. Such a type can have an
2824 /// exception specification, but this specification is not part of the canonical
2826 class FunctionProtoType : public FunctionType, public llvm::FoldingSetNode {
2828 /// ExtProtoInfo - Extra information about a function prototype.
2829 struct ExtProtoInfo {
2831 Variadic(false), HasTrailingReturn(false), TypeQuals(0),
2832 ExceptionSpecType(EST_None), RefQualifier(RQ_None),
2833 NumExceptions(0), Exceptions(0), NoexceptExpr(0),
2834 ExceptionSpecDecl(0), ExceptionSpecTemplate(0),
2835 ConsumedArguments(0) {}
2837 ExtProtoInfo(CallingConv CC)
2838 : ExtInfo(CC), Variadic(false), HasTrailingReturn(false), TypeQuals(0),
2839 ExceptionSpecType(EST_None), RefQualifier(RQ_None), NumExceptions(0),
2840 Exceptions(0), NoexceptExpr(0), ExceptionSpecDecl(0),
2841 ExceptionSpecTemplate(0), ConsumedArguments(0) {}
2843 FunctionType::ExtInfo ExtInfo;
2845 bool HasTrailingReturn : 1;
2846 unsigned char TypeQuals;
2847 ExceptionSpecificationType ExceptionSpecType;
2848 RefQualifierKind RefQualifier;
2849 unsigned NumExceptions;
2850 const QualType *Exceptions;
2852 FunctionDecl *ExceptionSpecDecl;
2853 FunctionDecl *ExceptionSpecTemplate;
2854 const bool *ConsumedArguments;
2858 /// \brief Determine whether there are any argument types that
2859 /// contain an unexpanded parameter pack.
2860 static bool containsAnyUnexpandedParameterPack(const QualType *ArgArray,
2862 for (unsigned Idx = 0; Idx < numArgs; ++Idx)
2863 if (ArgArray[Idx]->containsUnexpandedParameterPack())
2869 FunctionProtoType(QualType result, ArrayRef<QualType> args,
2870 QualType canonical, const ExtProtoInfo &epi);
2872 /// NumArgs - The number of arguments this function has, not counting '...'.
2873 unsigned NumArgs : 15;
2875 /// NumExceptions - The number of types in the exception spec, if any.
2876 unsigned NumExceptions : 9;
2878 /// ExceptionSpecType - The type of exception specification this function has.
2879 unsigned ExceptionSpecType : 3;
2881 /// HasAnyConsumedArgs - Whether this function has any consumed arguments.
2882 unsigned HasAnyConsumedArgs : 1;
2884 /// Variadic - Whether the function is variadic.
2885 unsigned Variadic : 1;
2887 /// HasTrailingReturn - Whether this function has a trailing return type.
2888 unsigned HasTrailingReturn : 1;
2890 /// \brief The ref-qualifier associated with a \c FunctionProtoType.
2892 /// This is a value of type \c RefQualifierKind.
2893 unsigned RefQualifier : 2;
2895 // ArgInfo - There is an variable size array after the class in memory that
2896 // holds the argument types.
2898 // Exceptions - There is another variable size array after ArgInfo that
2899 // holds the exception types.
2901 // NoexceptExpr - Instead of Exceptions, there may be a single Expr* pointing
2902 // to the expression in the noexcept() specifier.
2904 // ExceptionSpecDecl, ExceptionSpecTemplate - Instead of Exceptions, there may
2905 // be a pair of FunctionDecl* pointing to the function which should be used to
2906 // instantiate this function type's exception specification, and the function
2907 // from which it should be instantiated.
2909 // ConsumedArgs - A variable size array, following Exceptions
2910 // and of length NumArgs, holding flags indicating which arguments
2911 // are consumed. This only appears if HasAnyConsumedArgs is true.
2913 friend class ASTContext; // ASTContext creates these.
2915 const bool *getConsumedArgsBuffer() const {
2916 assert(hasAnyConsumedArgs());
2918 // Find the end of the exceptions.
2919 Expr * const *eh_end = reinterpret_cast<Expr * const *>(arg_type_end());
2920 if (getExceptionSpecType() != EST_ComputedNoexcept)
2921 eh_end += NumExceptions;
2923 eh_end += 1; // NoexceptExpr
2925 return reinterpret_cast<const bool*>(eh_end);
2929 unsigned getNumArgs() const { return NumArgs; }
2930 QualType getArgType(unsigned i) const {
2931 assert(i < NumArgs && "Invalid argument number!");
2932 return arg_type_begin()[i];
2934 ArrayRef<QualType> getArgTypes() const {
2935 return ArrayRef<QualType>(arg_type_begin(), arg_type_end());
2938 ExtProtoInfo getExtProtoInfo() const {
2940 EPI.ExtInfo = getExtInfo();
2941 EPI.Variadic = isVariadic();
2942 EPI.HasTrailingReturn = hasTrailingReturn();
2943 EPI.ExceptionSpecType = getExceptionSpecType();
2944 EPI.TypeQuals = static_cast<unsigned char>(getTypeQuals());
2945 EPI.RefQualifier = getRefQualifier();
2946 if (EPI.ExceptionSpecType == EST_Dynamic) {
2947 EPI.NumExceptions = NumExceptions;
2948 EPI.Exceptions = exception_begin();
2949 } else if (EPI.ExceptionSpecType == EST_ComputedNoexcept) {
2950 EPI.NoexceptExpr = getNoexceptExpr();
2951 } else if (EPI.ExceptionSpecType == EST_Uninstantiated) {
2952 EPI.ExceptionSpecDecl = getExceptionSpecDecl();
2953 EPI.ExceptionSpecTemplate = getExceptionSpecTemplate();
2954 } else if (EPI.ExceptionSpecType == EST_Unevaluated) {
2955 EPI.ExceptionSpecDecl = getExceptionSpecDecl();
2957 if (hasAnyConsumedArgs())
2958 EPI.ConsumedArguments = getConsumedArgsBuffer();
2962 /// \brief Get the kind of exception specification on this function.
2963 ExceptionSpecificationType getExceptionSpecType() const {
2964 return static_cast<ExceptionSpecificationType>(ExceptionSpecType);
2966 /// \brief Return whether this function has any kind of exception spec.
2967 bool hasExceptionSpec() const {
2968 return getExceptionSpecType() != EST_None;
2970 /// \brief Return whether this function has a dynamic (throw) exception spec.
2971 bool hasDynamicExceptionSpec() const {
2972 return isDynamicExceptionSpec(getExceptionSpecType());
2974 /// \brief Return whether this function has a noexcept exception spec.
2975 bool hasNoexceptExceptionSpec() const {
2976 return isNoexceptExceptionSpec(getExceptionSpecType());
2978 /// \brief Result type of getNoexceptSpec().
2979 enum NoexceptResult {
2980 NR_NoNoexcept, ///< There is no noexcept specifier.
2981 NR_BadNoexcept, ///< The noexcept specifier has a bad expression.
2982 NR_Dependent, ///< The noexcept specifier is dependent.
2983 NR_Throw, ///< The noexcept specifier evaluates to false.
2984 NR_Nothrow ///< The noexcept specifier evaluates to true.
2986 /// \brief Get the meaning of the noexcept spec on this function, if any.
2987 NoexceptResult getNoexceptSpec(const ASTContext &Ctx) const;
2988 unsigned getNumExceptions() const { return NumExceptions; }
2989 QualType getExceptionType(unsigned i) const {
2990 assert(i < NumExceptions && "Invalid exception number!");
2991 return exception_begin()[i];
2993 Expr *getNoexceptExpr() const {
2994 if (getExceptionSpecType() != EST_ComputedNoexcept)
2996 // NoexceptExpr sits where the arguments end.
2997 return *reinterpret_cast<Expr *const *>(arg_type_end());
2999 /// \brief If this function type has an exception specification which hasn't
3000 /// been determined yet (either because it has not been evaluated or because
3001 /// it has not been instantiated), this is the function whose exception
3002 /// specification is represented by this type.
3003 FunctionDecl *getExceptionSpecDecl() const {
3004 if (getExceptionSpecType() != EST_Uninstantiated &&
3005 getExceptionSpecType() != EST_Unevaluated)
3007 return reinterpret_cast<FunctionDecl * const *>(arg_type_end())[0];
3009 /// \brief If this function type has an uninstantiated exception
3010 /// specification, this is the function whose exception specification
3011 /// should be instantiated to find the exception specification for
3013 FunctionDecl *getExceptionSpecTemplate() const {
3014 if (getExceptionSpecType() != EST_Uninstantiated)
3016 return reinterpret_cast<FunctionDecl * const *>(arg_type_end())[1];
3018 bool isNothrow(const ASTContext &Ctx) const {
3019 ExceptionSpecificationType EST = getExceptionSpecType();
3020 assert(EST != EST_Unevaluated && EST != EST_Uninstantiated);
3021 if (EST == EST_DynamicNone || EST == EST_BasicNoexcept)
3023 if (EST != EST_ComputedNoexcept)
3025 return getNoexceptSpec(Ctx) == NR_Nothrow;
3028 bool isVariadic() const { return Variadic; }
3030 /// \brief Determines whether this function prototype contains a
3031 /// parameter pack at the end.
3033 /// A function template whose last parameter is a parameter pack can be
3034 /// called with an arbitrary number of arguments, much like a variadic
3036 bool isTemplateVariadic() const;
3038 bool hasTrailingReturn() const { return HasTrailingReturn; }
3040 unsigned getTypeQuals() const { return FunctionType::getTypeQuals(); }
3043 /// \brief Retrieve the ref-qualifier associated with this function type.
3044 RefQualifierKind getRefQualifier() const {
3045 return static_cast<RefQualifierKind>(RefQualifier);
3048 typedef const QualType *arg_type_iterator;
3049 arg_type_iterator arg_type_begin() const {
3050 return reinterpret_cast<const QualType *>(this+1);
3052 arg_type_iterator arg_type_end() const { return arg_type_begin()+NumArgs; }
3054 typedef const QualType *exception_iterator;
3055 exception_iterator exception_begin() const {
3056 // exceptions begin where arguments end
3057 return arg_type_end();
3059 exception_iterator exception_end() const {
3060 if (getExceptionSpecType() != EST_Dynamic)
3061 return exception_begin();
3062 return exception_begin() + NumExceptions;
3065 bool hasAnyConsumedArgs() const {
3066 return HasAnyConsumedArgs;
3068 bool isArgConsumed(unsigned I) const {
3069 assert(I < getNumArgs() && "argument index out of range!");
3070 if (hasAnyConsumedArgs())
3071 return getConsumedArgsBuffer()[I];
3075 bool isSugared() const { return false; }
3076 QualType desugar() const { return QualType(this, 0); }
3078 void printExceptionSpecification(raw_ostream &OS,
3079 const PrintingPolicy &Policy) const;
3081 static bool classof(const Type *T) {
3082 return T->getTypeClass() == FunctionProto;
3085 void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Ctx);
3086 static void Profile(llvm::FoldingSetNodeID &ID, QualType Result,
3087 arg_type_iterator ArgTys, unsigned NumArgs,
3088 const ExtProtoInfo &EPI, const ASTContext &Context);
3092 /// \brief Represents the dependent type named by a dependently-scoped
3093 /// typename using declaration, e.g.
3094 /// using typename Base<T>::foo;
3095 /// Template instantiation turns these into the underlying type.
3096 class UnresolvedUsingType : public Type {
3097 UnresolvedUsingTypenameDecl *Decl;
3099 UnresolvedUsingType(const UnresolvedUsingTypenameDecl *D)
3100 : Type(UnresolvedUsing, QualType(), true, true, false,
3101 /*ContainsUnexpandedParameterPack=*/false),
3102 Decl(const_cast<UnresolvedUsingTypenameDecl*>(D)) {}
3103 friend class ASTContext; // ASTContext creates these.
3106 UnresolvedUsingTypenameDecl *getDecl() const { return Decl; }
3108 bool isSugared() const { return false; }
3109 QualType desugar() const { return QualType(this, 0); }
3111 static bool classof(const Type *T) {
3112 return T->getTypeClass() == UnresolvedUsing;
3115 void Profile(llvm::FoldingSetNodeID &ID) {
3116 return Profile(ID, Decl);
3118 static void Profile(llvm::FoldingSetNodeID &ID,
3119 UnresolvedUsingTypenameDecl *D) {
3125 class TypedefType : public Type {
3126 TypedefNameDecl *Decl;
3128 TypedefType(TypeClass tc, const TypedefNameDecl *D, QualType can)
3129 : Type(tc, can, can->isDependentType(),
3130 can->isInstantiationDependentType(),
3131 can->isVariablyModifiedType(),
3132 /*ContainsUnexpandedParameterPack=*/false),
3133 Decl(const_cast<TypedefNameDecl*>(D)) {
3134 assert(!isa<TypedefType>(can) && "Invalid canonical type");
3136 friend class ASTContext; // ASTContext creates these.
3139 TypedefNameDecl *getDecl() const { return Decl; }
3141 bool isSugared() const { return true; }
3142 QualType desugar() const;
3144 static bool classof(const Type *T) { return T->getTypeClass() == Typedef; }
3147 /// TypeOfExprType (GCC extension).
3148 class TypeOfExprType : public Type {
3152 TypeOfExprType(Expr *E, QualType can = QualType());
3153 friend class ASTContext; // ASTContext creates these.
3155 Expr *getUnderlyingExpr() const { return TOExpr; }
3157 /// \brief Remove a single level of sugar.
3158 QualType desugar() const;
3160 /// \brief Returns whether this type directly provides sugar.
3161 bool isSugared() const;
3163 static bool classof(const Type *T) { return T->getTypeClass() == TypeOfExpr; }
3166 /// \brief Internal representation of canonical, dependent
3167 /// typeof(expr) types.
3169 /// This class is used internally by the ASTContext to manage
3170 /// canonical, dependent types, only. Clients will only see instances
3171 /// of this class via TypeOfExprType nodes.
3172 class DependentTypeOfExprType
3173 : public TypeOfExprType, public llvm::FoldingSetNode {
3174 const ASTContext &Context;
3177 DependentTypeOfExprType(const ASTContext &Context, Expr *E)
3178 : TypeOfExprType(E), Context(Context) { }
3180 void Profile(llvm::FoldingSetNodeID &ID) {
3181 Profile(ID, Context, getUnderlyingExpr());
3184 static void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context,
3188 /// TypeOfType (GCC extension).
3189 class TypeOfType : public Type {
3191 TypeOfType(QualType T, QualType can)
3192 : Type(TypeOf, can, T->isDependentType(),
3193 T->isInstantiationDependentType(),
3194 T->isVariablyModifiedType(),
3195 T->containsUnexpandedParameterPack()),
3197 assert(!isa<TypedefType>(can) && "Invalid canonical type");
3199 friend class ASTContext; // ASTContext creates these.
3201 QualType getUnderlyingType() const { return TOType; }
3203 /// \brief Remove a single level of sugar.
3204 QualType desugar() const { return getUnderlyingType(); }
3206 /// \brief Returns whether this type directly provides sugar.
3207 bool isSugared() const { return true; }
3209 static bool classof(const Type *T) { return T->getTypeClass() == TypeOf; }
3212 /// DecltypeType (C++0x)
3213 class DecltypeType : public Type {
3215 QualType UnderlyingType;
3218 DecltypeType(Expr *E, QualType underlyingType, QualType can = QualType());
3219 friend class ASTContext; // ASTContext creates these.
3221 Expr *getUnderlyingExpr() const { return E; }
3222 QualType getUnderlyingType() const { return UnderlyingType; }
3224 /// \brief Remove a single level of sugar.
3225 QualType desugar() const;
3227 /// \brief Returns whether this type directly provides sugar.
3228 bool isSugared() const;
3230 static bool classof(const Type *T) { return T->getTypeClass() == Decltype; }
3233 /// \brief Internal representation of canonical, dependent
3234 /// decltype(expr) types.
3236 /// This class is used internally by the ASTContext to manage
3237 /// canonical, dependent types, only. Clients will only see instances
3238 /// of this class via DecltypeType nodes.
3239 class DependentDecltypeType : public DecltypeType, public llvm::FoldingSetNode {
3240 const ASTContext &Context;
3243 DependentDecltypeType(const ASTContext &Context, Expr *E);
3245 void Profile(llvm::FoldingSetNodeID &ID) {
3246 Profile(ID, Context, getUnderlyingExpr());
3249 static void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context,
3253 /// \brief A unary type transform, which is a type constructed from another
3254 class UnaryTransformType : public Type {
3261 /// The untransformed type.
3263 /// The transformed type if not dependent, otherwise the same as BaseType.
3264 QualType UnderlyingType;
3268 UnaryTransformType(QualType BaseTy, QualType UnderlyingTy, UTTKind UKind,
3269 QualType CanonicalTy);
3270 friend class ASTContext;
3272 bool isSugared() const { return !isDependentType(); }
3273 QualType desugar() const { return UnderlyingType; }
3275 QualType getUnderlyingType() const { return UnderlyingType; }
3276 QualType getBaseType() const { return BaseType; }
3278 UTTKind getUTTKind() const { return UKind; }
3280 static bool classof(const Type *T) {
3281 return T->getTypeClass() == UnaryTransform;
3285 class TagType : public Type {
3286 /// Stores the TagDecl associated with this type. The decl may point to any
3287 /// TagDecl that declares the entity.
3290 friend class ASTReader;
3293 TagType(TypeClass TC, const TagDecl *D, QualType can);
3296 TagDecl *getDecl() const;
3298 /// @brief Determines whether this type is in the process of being
3300 bool isBeingDefined() const;
3302 static bool classof(const Type *T) {
3303 return T->getTypeClass() >= TagFirst && T->getTypeClass() <= TagLast;
3307 /// RecordType - This is a helper class that allows the use of isa/cast/dyncast
3308 /// to detect TagType objects of structs/unions/classes.
3309 class RecordType : public TagType {
3311 explicit RecordType(const RecordDecl *D)
3312 : TagType(Record, reinterpret_cast<const TagDecl*>(D), QualType()) { }
3313 explicit RecordType(TypeClass TC, RecordDecl *D)
3314 : TagType(TC, reinterpret_cast<const TagDecl*>(D), QualType()) { }
3315 friend class ASTContext; // ASTContext creates these.
3318 RecordDecl *getDecl() const {
3319 return reinterpret_cast<RecordDecl*>(TagType::getDecl());
3322 // FIXME: This predicate is a helper to QualType/Type. It needs to
3323 // recursively check all fields for const-ness. If any field is declared
3324 // const, it needs to return false.
3325 bool hasConstFields() const { return false; }
3327 bool isSugared() const { return false; }
3328 QualType desugar() const { return QualType(this, 0); }
3330 static bool classof(const Type *T) { return T->getTypeClass() == Record; }
3333 /// EnumType - This is a helper class that allows the use of isa/cast/dyncast
3334 /// to detect TagType objects of enums.
3335 class EnumType : public TagType {
3336 explicit EnumType(const EnumDecl *D)
3337 : TagType(Enum, reinterpret_cast<const TagDecl*>(D), QualType()) { }
3338 friend class ASTContext; // ASTContext creates these.
3341 EnumDecl *getDecl() const {
3342 return reinterpret_cast<EnumDecl*>(TagType::getDecl());
3345 bool isSugared() const { return false; }
3346 QualType desugar() const { return QualType(this, 0); }
3348 static bool classof(const Type *T) { return T->getTypeClass() == Enum; }
3351 /// AttributedType - An attributed type is a type to which a type
3352 /// attribute has been applied. The "modified type" is the
3353 /// fully-sugared type to which the attributed type was applied;
3354 /// generally it is not canonically equivalent to the attributed type.
3355 /// The "equivalent type" is the minimally-desugared type which the
3356 /// type is canonically equivalent to.
3358 /// For example, in the following attributed type:
3359 /// int32_t __attribute__((vector_size(16)))
3360 /// - the modified type is the TypedefType for int32_t
3361 /// - the equivalent type is VectorType(16, int32_t)
3362 /// - the canonical type is VectorType(16, int)
3363 class AttributedType : public Type, public llvm::FoldingSetNode {
3365 // It is really silly to have yet another attribute-kind enum, but
3366 // clang::attr::Kind doesn't currently cover the pure type attrs.
3368 // Expression operand.
3372 attr_neon_vector_type,
3373 attr_neon_polyvector_type,
3375 FirstExprOperandKind = attr_address_space,
3376 LastExprOperandKind = attr_neon_polyvector_type,
3378 // Enumerated operand (string or keyword).
3380 attr_objc_ownership,
3384 FirstEnumOperandKind = attr_objc_gc,
3385 LastEnumOperandKind = attr_pcs_vfp,
3405 QualType ModifiedType;
3406 QualType EquivalentType;
3408 friend class ASTContext; // creates these
3410 AttributedType(QualType canon, Kind attrKind,
3411 QualType modified, QualType equivalent)
3412 : Type(Attributed, canon, canon->isDependentType(),
3413 canon->isInstantiationDependentType(),
3414 canon->isVariablyModifiedType(),
3415 canon->containsUnexpandedParameterPack()),
3416 ModifiedType(modified), EquivalentType(equivalent) {
3417 AttributedTypeBits.AttrKind = attrKind;
3421 Kind getAttrKind() const {
3422 return static_cast<Kind>(AttributedTypeBits.AttrKind);
3425 QualType getModifiedType() const { return ModifiedType; }
3426 QualType getEquivalentType() const { return EquivalentType; }
3428 bool isSugared() const { return true; }
3429 QualType desugar() const { return getEquivalentType(); }
3431 bool isMSTypeSpec() const;
3433 bool isCallingConv() const;
3435 void Profile(llvm::FoldingSetNodeID &ID) {
3436 Profile(ID, getAttrKind(), ModifiedType, EquivalentType);
3439 static void Profile(llvm::FoldingSetNodeID &ID, Kind attrKind,
3440 QualType modified, QualType equivalent) {
3441 ID.AddInteger(attrKind);
3442 ID.AddPointer(modified.getAsOpaquePtr());
3443 ID.AddPointer(equivalent.getAsOpaquePtr());
3446 static bool classof(const Type *T) {
3447 return T->getTypeClass() == Attributed;
3451 class TemplateTypeParmType : public Type, public llvm::FoldingSetNode {
3452 // Helper data collector for canonical types.
3453 struct CanonicalTTPTInfo {
3454 unsigned Depth : 15;
3455 unsigned ParameterPack : 1;
3456 unsigned Index : 16;
3460 // Info for the canonical type.
3461 CanonicalTTPTInfo CanTTPTInfo;
3462 // Info for the non-canonical type.
3463 TemplateTypeParmDecl *TTPDecl;
3466 /// Build a non-canonical type.
3467 TemplateTypeParmType(TemplateTypeParmDecl *TTPDecl, QualType Canon)
3468 : Type(TemplateTypeParm, Canon, /*Dependent=*/true,
3469 /*InstantiationDependent=*/true,
3470 /*VariablyModified=*/false,
3471 Canon->containsUnexpandedParameterPack()),
3472 TTPDecl(TTPDecl) { }
3474 /// Build the canonical type.
3475 TemplateTypeParmType(unsigned D, unsigned I, bool PP)
3476 : Type(TemplateTypeParm, QualType(this, 0),
3478 /*InstantiationDependent=*/true,
3479 /*VariablyModified=*/false, PP) {
3480 CanTTPTInfo.Depth = D;
3481 CanTTPTInfo.Index = I;
3482 CanTTPTInfo.ParameterPack = PP;
3485 friend class ASTContext; // ASTContext creates these
3487 const CanonicalTTPTInfo& getCanTTPTInfo() const {
3488 QualType Can = getCanonicalTypeInternal();
3489 return Can->castAs<TemplateTypeParmType>()->CanTTPTInfo;
3493 unsigned getDepth() const { return getCanTTPTInfo().Depth; }
3494 unsigned getIndex() const { return getCanTTPTInfo().Index; }
3495 bool isParameterPack() const { return getCanTTPTInfo().ParameterPack; }
3497 TemplateTypeParmDecl *getDecl() const {
3498 return isCanonicalUnqualified() ? 0 : TTPDecl;
3501 IdentifierInfo *getIdentifier() const;
3503 bool isSugared() const { return false; }
3504 QualType desugar() const { return QualType(this, 0); }
3506 void Profile(llvm::FoldingSetNodeID &ID) {
3507 Profile(ID, getDepth(), getIndex(), isParameterPack(), getDecl());
3510 static void Profile(llvm::FoldingSetNodeID &ID, unsigned Depth,
3511 unsigned Index, bool ParameterPack,
3512 TemplateTypeParmDecl *TTPDecl) {
3513 ID.AddInteger(Depth);
3514 ID.AddInteger(Index);
3515 ID.AddBoolean(ParameterPack);
3516 ID.AddPointer(TTPDecl);
3519 static bool classof(const Type *T) {
3520 return T->getTypeClass() == TemplateTypeParm;
3524 /// \brief Represents the result of substituting a type for a template
3527 /// Within an instantiated template, all template type parameters have
3528 /// been replaced with these. They are used solely to record that a
3529 /// type was originally written as a template type parameter;
3530 /// therefore they are never canonical.
3531 class SubstTemplateTypeParmType : public Type, public llvm::FoldingSetNode {
3532 // The original type parameter.
3533 const TemplateTypeParmType *Replaced;
3535 SubstTemplateTypeParmType(const TemplateTypeParmType *Param, QualType Canon)
3536 : Type(SubstTemplateTypeParm, Canon, Canon->isDependentType(),
3537 Canon->isInstantiationDependentType(),
3538 Canon->isVariablyModifiedType(),
3539 Canon->containsUnexpandedParameterPack()),
3542 friend class ASTContext;
3545 /// Gets the template parameter that was substituted for.
3546 const TemplateTypeParmType *getReplacedParameter() const {
3550 /// Gets the type that was substituted for the template
3552 QualType getReplacementType() const {
3553 return getCanonicalTypeInternal();
3556 bool isSugared() const { return true; }
3557 QualType desugar() const { return getReplacementType(); }
3559 void Profile(llvm::FoldingSetNodeID &ID) {
3560 Profile(ID, getReplacedParameter(), getReplacementType());
3562 static void Profile(llvm::FoldingSetNodeID &ID,
3563 const TemplateTypeParmType *Replaced,
3564 QualType Replacement) {
3565 ID.AddPointer(Replaced);
3566 ID.AddPointer(Replacement.getAsOpaquePtr());
3569 static bool classof(const Type *T) {
3570 return T->getTypeClass() == SubstTemplateTypeParm;
3574 /// \brief Represents the result of substituting a set of types for a template
3575 /// type parameter pack.
3577 /// When a pack expansion in the source code contains multiple parameter packs
3578 /// and those parameter packs correspond to different levels of template
3579 /// parameter lists, this type node is used to represent a template type
3580 /// parameter pack from an outer level, which has already had its argument pack
3581 /// substituted but that still lives within a pack expansion that itself
3582 /// could not be instantiated. When actually performing a substitution into
3583 /// that pack expansion (e.g., when all template parameters have corresponding
3584 /// arguments), this type will be replaced with the \c SubstTemplateTypeParmType
3585 /// at the current pack substitution index.
3586 class SubstTemplateTypeParmPackType : public Type, public llvm::FoldingSetNode {
3587 /// \brief The original type parameter.
3588 const TemplateTypeParmType *Replaced;
3590 /// \brief A pointer to the set of template arguments that this
3591 /// parameter pack is instantiated with.
3592 const TemplateArgument *Arguments;
3594 /// \brief The number of template arguments in \c Arguments.
3595 unsigned NumArguments;
3597 SubstTemplateTypeParmPackType(const TemplateTypeParmType *Param,
3599 const TemplateArgument &ArgPack);
3601 friend class ASTContext;
3604 IdentifierInfo *getIdentifier() const { return Replaced->getIdentifier(); }
3606 /// Gets the template parameter that was substituted for.
3607 const TemplateTypeParmType *getReplacedParameter() const {
3611 bool isSugared() const { return false; }
3612 QualType desugar() const { return QualType(this, 0); }
3614 TemplateArgument getArgumentPack() const;
3616 void Profile(llvm::FoldingSetNodeID &ID);
3617 static void Profile(llvm::FoldingSetNodeID &ID,
3618 const TemplateTypeParmType *Replaced,
3619 const TemplateArgument &ArgPack);
3621 static bool classof(const Type *T) {
3622 return T->getTypeClass() == SubstTemplateTypeParmPack;
3626 /// \brief Represents a C++11 auto or C++1y decltype(auto) type.
3628 /// These types are usually a placeholder for a deduced type. However, before
3629 /// the initializer is attached, or if the initializer is type-dependent, there
3630 /// is no deduced type and an auto type is canonical. In the latter case, it is
3631 /// also a dependent type.
3632 class AutoType : public Type, public llvm::FoldingSetNode {
3633 AutoType(QualType DeducedType, bool IsDecltypeAuto,
3635 : Type(Auto, DeducedType.isNull() ? QualType(this, 0) : DeducedType,
3636 /*Dependent=*/IsDependent, /*InstantiationDependent=*/IsDependent,
3637 /*VariablyModified=*/false,
3638 /*ContainsParameterPack=*/DeducedType.isNull()
3639 ? false : DeducedType->containsUnexpandedParameterPack()) {
3640 assert((DeducedType.isNull() || !IsDependent) &&
3641 "auto deduced to dependent type");
3642 AutoTypeBits.IsDecltypeAuto = IsDecltypeAuto;
3645 friend class ASTContext; // ASTContext creates these
3648 bool isDecltypeAuto() const { return AutoTypeBits.IsDecltypeAuto; }
3650 bool isSugared() const { return !isCanonicalUnqualified(); }
3651 QualType desugar() const { return getCanonicalTypeInternal(); }
3653 /// \brief Get the type deduced for this auto type, or null if it's either
3654 /// not been deduced or was deduced to a dependent type.
3655 QualType getDeducedType() const {
3656 return !isCanonicalUnqualified() ? getCanonicalTypeInternal() : QualType();
3658 bool isDeduced() const {
3659 return !isCanonicalUnqualified() || isDependentType();
3662 void Profile(llvm::FoldingSetNodeID &ID) {
3663 Profile(ID, getDeducedType(), isDecltypeAuto(),
3667 static void Profile(llvm::FoldingSetNodeID &ID, QualType Deduced,
3668 bool IsDecltypeAuto, bool IsDependent) {
3669 ID.AddPointer(Deduced.getAsOpaquePtr());
3670 ID.AddBoolean(IsDecltypeAuto);
3671 ID.AddBoolean(IsDependent);
3674 static bool classof(const Type *T) {
3675 return T->getTypeClass() == Auto;
3679 /// \brief Represents a type template specialization; the template
3680 /// must be a class template, a type alias template, or a template
3681 /// template parameter. A template which cannot be resolved to one of
3682 /// these, e.g. because it is written with a dependent scope
3683 /// specifier, is instead represented as a
3684 /// @c DependentTemplateSpecializationType.
3686 /// A non-dependent template specialization type is always "sugar",
3687 /// typically for a @c RecordType. For example, a class template
3688 /// specialization type of @c vector<int> will refer to a tag type for
3689 /// the instantiation @c std::vector<int, std::allocator<int>>
3691 /// Template specializations are dependent if either the template or
3692 /// any of the template arguments are dependent, in which case the
3693 /// type may also be canonical.
3695 /// Instances of this type are allocated with a trailing array of
3696 /// TemplateArguments, followed by a QualType representing the
3697 /// non-canonical aliased type when the template is a type alias
3699 class TemplateSpecializationType
3700 : public Type, public llvm::FoldingSetNode {
3701 /// \brief The name of the template being specialized. This is
3702 /// either a TemplateName::Template (in which case it is a
3703 /// ClassTemplateDecl*, a TemplateTemplateParmDecl*, or a
3704 /// TypeAliasTemplateDecl*), a
3705 /// TemplateName::SubstTemplateTemplateParmPack, or a
3706 /// TemplateName::SubstTemplateTemplateParm (in which case the
3707 /// replacement must, recursively, be one of these).
3708 TemplateName Template;
3710 /// \brief - The number of template arguments named in this class
3711 /// template specialization.
3712 unsigned NumArgs : 31;
3714 /// \brief Whether this template specialization type is a substituted
3718 TemplateSpecializationType(TemplateName T,
3719 const TemplateArgument *Args,
3720 unsigned NumArgs, QualType Canon,
3723 friend class ASTContext; // ASTContext creates these
3726 /// \brief Determine whether any of the given template arguments are
3728 static bool anyDependentTemplateArguments(const TemplateArgumentLoc *Args,
3730 bool &InstantiationDependent);
3732 static bool anyDependentTemplateArguments(const TemplateArgumentListInfo &,
3733 bool &InstantiationDependent);
3735 /// \brief Print a template argument list, including the '<' and '>'
3736 /// enclosing the template arguments.
3737 static void PrintTemplateArgumentList(raw_ostream &OS,
3738 const TemplateArgument *Args,
3740 const PrintingPolicy &Policy,
3741 bool SkipBrackets = false);
3743 static void PrintTemplateArgumentList(raw_ostream &OS,
3744 const TemplateArgumentLoc *Args,
3746 const PrintingPolicy &Policy);
3748 static void PrintTemplateArgumentList(raw_ostream &OS,
3749 const TemplateArgumentListInfo &,
3750 const PrintingPolicy &Policy);
3752 /// True if this template specialization type matches a current
3753 /// instantiation in the context in which it is found.
3754 bool isCurrentInstantiation() const {
3755 return isa<InjectedClassNameType>(getCanonicalTypeInternal());
3758 /// \brief Determine if this template specialization type is for a type alias
3759 /// template that has been substituted.
3761 /// Nearly every template specialization type whose template is an alias
3762 /// template will be substituted. However, this is not the case when
3763 /// the specialization contains a pack expansion but the template alias
3764 /// does not have a corresponding parameter pack, e.g.,
3767 /// template<typename T, typename U, typename V> struct S;
3768 /// template<typename T, typename U> using A = S<T, int, U>;
3769 /// template<typename... Ts> struct X {
3770 /// typedef A<Ts...> type; // not a type alias
3773 bool isTypeAlias() const { return TypeAlias; }
3775 /// Get the aliased type, if this is a specialization of a type alias
3777 QualType getAliasedType() const {
3778 assert(isTypeAlias() && "not a type alias template specialization");
3779 return *reinterpret_cast<const QualType*>(end());
3782 typedef const TemplateArgument * iterator;
3784 iterator begin() const { return getArgs(); }
3785 iterator end() const; // defined inline in TemplateBase.h
3787 /// \brief Retrieve the name of the template that we are specializing.
3788 TemplateName getTemplateName() const { return Template; }
3790 /// \brief Retrieve the template arguments.
3791 const TemplateArgument *getArgs() const {
3792 return reinterpret_cast<const TemplateArgument *>(this + 1);
3795 /// \brief Retrieve the number of template arguments.
3796 unsigned getNumArgs() const { return NumArgs; }
3798 /// \brief Retrieve a specific template argument as a type.
3799 /// \pre @c isArgType(Arg)
3800 const TemplateArgument &getArg(unsigned Idx) const; // in TemplateBase.h
3802 bool isSugared() const {
3803 return !isDependentType() || isCurrentInstantiation() || isTypeAlias();
3805 QualType desugar() const { return getCanonicalTypeInternal(); }
3807 void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Ctx) {
3808 Profile(ID, Template, getArgs(), NumArgs, Ctx);
3810 getAliasedType().Profile(ID);
3813 static void Profile(llvm::FoldingSetNodeID &ID, TemplateName T,
3814 const TemplateArgument *Args,
3816 const ASTContext &Context);
3818 static bool classof(const Type *T) {
3819 return T->getTypeClass() == TemplateSpecialization;
3823 /// \brief The injected class name of a C++ class template or class
3824 /// template partial specialization. Used to record that a type was
3825 /// spelled with a bare identifier rather than as a template-id; the
3826 /// equivalent for non-templated classes is just RecordType.
3828 /// Injected class name types are always dependent. Template
3829 /// instantiation turns these into RecordTypes.
3831 /// Injected class name types are always canonical. This works
3832 /// because it is impossible to compare an injected class name type
3833 /// with the corresponding non-injected template type, for the same
3834 /// reason that it is impossible to directly compare template
3835 /// parameters from different dependent contexts: injected class name
3836 /// types can only occur within the scope of a particular templated
3837 /// declaration, and within that scope every template specialization
3838 /// will canonicalize to the injected class name (when appropriate
3839 /// according to the rules of the language).
3840 class InjectedClassNameType : public Type {
3841 CXXRecordDecl *Decl;
3843 /// The template specialization which this type represents.
3845 /// template <class T> class A { ... };
3846 /// this is A<T>, whereas in
3847 /// template <class X, class Y> class A<B<X,Y> > { ... };
3848 /// this is A<B<X,Y> >.
3850 /// It is always unqualified, always a template specialization type,
3851 /// and always dependent.
3852 QualType InjectedType;
3854 friend class ASTContext; // ASTContext creates these.
3855 friend class ASTReader; // FIXME: ASTContext::getInjectedClassNameType is not
3856 // currently suitable for AST reading, too much
3857 // interdependencies.
3858 InjectedClassNameType(CXXRecordDecl *D, QualType TST)
3859 : Type(InjectedClassName, QualType(), /*Dependent=*/true,
3860 /*InstantiationDependent=*/true,
3861 /*VariablyModified=*/false,
3862 /*ContainsUnexpandedParameterPack=*/false),
3863 Decl(D), InjectedType(TST) {
3864 assert(isa<TemplateSpecializationType>(TST));
3865 assert(!TST.hasQualifiers());
3866 assert(TST->isDependentType());
3870 QualType getInjectedSpecializationType() const { return InjectedType; }
3871 const TemplateSpecializationType *getInjectedTST() const {
3872 return cast<TemplateSpecializationType>(InjectedType.getTypePtr());
3875 CXXRecordDecl *getDecl() const;
3877 bool isSugared() const { return false; }
3878 QualType desugar() const { return QualType(this, 0); }
3880 static bool classof(const Type *T) {
3881 return T->getTypeClass() == InjectedClassName;
3885 /// \brief The kind of a tag type.
3887 /// \brief The "struct" keyword.
3889 /// \brief The "__interface" keyword.
3891 /// \brief The "union" keyword.
3893 /// \brief The "class" keyword.
3895 /// \brief The "enum" keyword.
3899 /// \brief The elaboration keyword that precedes a qualified type name or
3900 /// introduces an elaborated-type-specifier.
3901 enum ElaboratedTypeKeyword {
3902 /// \brief The "struct" keyword introduces the elaborated-type-specifier.
3904 /// \brief The "__interface" keyword introduces the elaborated-type-specifier.
3906 /// \brief The "union" keyword introduces the elaborated-type-specifier.
3908 /// \brief The "class" keyword introduces the elaborated-type-specifier.
3910 /// \brief The "enum" keyword introduces the elaborated-type-specifier.
3912 /// \brief The "typename" keyword precedes the qualified type name, e.g.,
3913 /// \c typename T::type.
3915 /// \brief No keyword precedes the qualified type name.
3919 /// A helper class for Type nodes having an ElaboratedTypeKeyword.
3920 /// The keyword in stored in the free bits of the base class.
3921 /// Also provides a few static helpers for converting and printing
3922 /// elaborated type keyword and tag type kind enumerations.
3923 class TypeWithKeyword : public Type {
3925 TypeWithKeyword(ElaboratedTypeKeyword Keyword, TypeClass tc,
3926 QualType Canonical, bool Dependent,
3927 bool InstantiationDependent, bool VariablyModified,
3928 bool ContainsUnexpandedParameterPack)
3929 : Type(tc, Canonical, Dependent, InstantiationDependent, VariablyModified,
3930 ContainsUnexpandedParameterPack) {
3931 TypeWithKeywordBits.Keyword = Keyword;
3935 ElaboratedTypeKeyword getKeyword() const {
3936 return static_cast<ElaboratedTypeKeyword>(TypeWithKeywordBits.Keyword);
3939 /// getKeywordForTypeSpec - Converts a type specifier (DeclSpec::TST)
3940 /// into an elaborated type keyword.
3941 static ElaboratedTypeKeyword getKeywordForTypeSpec(unsigned TypeSpec);
3943 /// getTagTypeKindForTypeSpec - Converts a type specifier (DeclSpec::TST)
3944 /// into a tag type kind. It is an error to provide a type specifier
3945 /// which *isn't* a tag kind here.
3946 static TagTypeKind getTagTypeKindForTypeSpec(unsigned TypeSpec);
3948 /// getKeywordForTagDeclKind - Converts a TagTypeKind into an
3949 /// elaborated type keyword.
3950 static ElaboratedTypeKeyword getKeywordForTagTypeKind(TagTypeKind Tag);
3952 /// getTagTypeKindForKeyword - Converts an elaborated type keyword into
3953 // a TagTypeKind. It is an error to provide an elaborated type keyword
3954 /// which *isn't* a tag kind here.
3955 static TagTypeKind getTagTypeKindForKeyword(ElaboratedTypeKeyword Keyword);
3957 static bool KeywordIsTagTypeKind(ElaboratedTypeKeyword Keyword);
3959 static const char *getKeywordName(ElaboratedTypeKeyword Keyword);
3961 static const char *getTagTypeKindName(TagTypeKind Kind) {
3962 return getKeywordName(getKeywordForTagTypeKind(Kind));
3965 class CannotCastToThisType {};
3966 static CannotCastToThisType classof(const Type *);
3969 /// \brief Represents a type that was referred to using an elaborated type
3970 /// keyword, e.g., struct S, or via a qualified name, e.g., N::M::type,
3973 /// This type is used to keep track of a type name as written in the
3974 /// source code, including tag keywords and any nested-name-specifiers.
3975 /// The type itself is always "sugar", used to express what was written
3976 /// in the source code but containing no additional semantic information.
3977 class ElaboratedType : public TypeWithKeyword, public llvm::FoldingSetNode {
3979 /// \brief The nested name specifier containing the qualifier.
3980 NestedNameSpecifier *NNS;
3982 /// \brief The type that this qualified name refers to.
3985 ElaboratedType(ElaboratedTypeKeyword Keyword, NestedNameSpecifier *NNS,
3986 QualType NamedType, QualType CanonType)
3987 : TypeWithKeyword(Keyword, Elaborated, CanonType,
3988 NamedType->isDependentType(),
3989 NamedType->isInstantiationDependentType(),
3990 NamedType->isVariablyModifiedType(),
3991 NamedType->containsUnexpandedParameterPack()),
3992 NNS(NNS), NamedType(NamedType) {
3993 assert(!(Keyword == ETK_None && NNS == 0) &&
3994 "ElaboratedType cannot have elaborated type keyword "
3995 "and name qualifier both null.");
3998 friend class ASTContext; // ASTContext creates these
4003 /// \brief Retrieve the qualification on this type.
4004 NestedNameSpecifier *getQualifier() const { return NNS; }
4006 /// \brief Retrieve the type named by the qualified-id.
4007 QualType getNamedType() const { return NamedType; }
4009 /// \brief Remove a single level of sugar.
4010 QualType desugar() const { return getNamedType(); }
4012 /// \brief Returns whether this type directly provides sugar.
4013 bool isSugared() const { return true; }
4015 void Profile(llvm::FoldingSetNodeID &ID) {
4016 Profile(ID, getKeyword(), NNS, NamedType);
4019 static void Profile(llvm::FoldingSetNodeID &ID, ElaboratedTypeKeyword Keyword,
4020 NestedNameSpecifier *NNS, QualType NamedType) {
4021 ID.AddInteger(Keyword);
4023 NamedType.Profile(ID);
4026 static bool classof(const Type *T) {
4027 return T->getTypeClass() == Elaborated;
4031 /// \brief Represents a qualified type name for which the type name is
4034 /// DependentNameType represents a class of dependent types that involve a
4035 /// dependent nested-name-specifier (e.g., "T::") followed by a (dependent)
4036 /// name of a type. The DependentNameType may start with a "typename" (for a
4037 /// typename-specifier), "class", "struct", "union", or "enum" (for a
4038 /// dependent elaborated-type-specifier), or nothing (in contexts where we
4039 /// know that we must be referring to a type, e.g., in a base class specifier).
4040 class DependentNameType : public TypeWithKeyword, public llvm::FoldingSetNode {
4042 /// \brief The nested name specifier containing the qualifier.
4043 NestedNameSpecifier *NNS;
4045 /// \brief The type that this typename specifier refers to.
4046 const IdentifierInfo *Name;
4048 DependentNameType(ElaboratedTypeKeyword Keyword, NestedNameSpecifier *NNS,
4049 const IdentifierInfo *Name, QualType CanonType)
4050 : TypeWithKeyword(Keyword, DependentName, CanonType, /*Dependent=*/true,
4051 /*InstantiationDependent=*/true,
4052 /*VariablyModified=*/false,
4053 NNS->containsUnexpandedParameterPack()),
4054 NNS(NNS), Name(Name) {
4055 assert(NNS->isDependent() &&
4056 "DependentNameType requires a dependent nested-name-specifier");
4059 friend class ASTContext; // ASTContext creates these
4062 /// \brief Retrieve the qualification on this type.
4063 NestedNameSpecifier *getQualifier() const { return NNS; }
4065 /// \brief Retrieve the type named by the typename specifier as an
4068 /// This routine will return a non-NULL identifier pointer when the
4069 /// form of the original typename was terminated by an identifier,
4070 /// e.g., "typename T::type".
4071 const IdentifierInfo *getIdentifier() const {
4075 bool isSugared() const { return false; }
4076 QualType desugar() const { return QualType(this, 0); }
4078 void Profile(llvm::FoldingSetNodeID &ID) {
4079 Profile(ID, getKeyword(), NNS, Name);
4082 static void Profile(llvm::FoldingSetNodeID &ID, ElaboratedTypeKeyword Keyword,
4083 NestedNameSpecifier *NNS, const IdentifierInfo *Name) {
4084 ID.AddInteger(Keyword);
4086 ID.AddPointer(Name);
4089 static bool classof(const Type *T) {
4090 return T->getTypeClass() == DependentName;
4094 /// DependentTemplateSpecializationType - Represents a template
4095 /// specialization type whose template cannot be resolved, e.g.
4096 /// A<T>::template B<T>
4097 class DependentTemplateSpecializationType :
4098 public TypeWithKeyword, public llvm::FoldingSetNode {
4100 /// \brief The nested name specifier containing the qualifier.
4101 NestedNameSpecifier *NNS;
4103 /// \brief The identifier of the template.
4104 const IdentifierInfo *Name;
4106 /// \brief - The number of template arguments named in this class
4107 /// template specialization.
4110 const TemplateArgument *getArgBuffer() const {
4111 return reinterpret_cast<const TemplateArgument*>(this+1);
4113 TemplateArgument *getArgBuffer() {
4114 return reinterpret_cast<TemplateArgument*>(this+1);
4117 DependentTemplateSpecializationType(ElaboratedTypeKeyword Keyword,
4118 NestedNameSpecifier *NNS,
4119 const IdentifierInfo *Name,
4121 const TemplateArgument *Args,
4124 friend class ASTContext; // ASTContext creates these
4127 NestedNameSpecifier *getQualifier() const { return NNS; }
4128 const IdentifierInfo *getIdentifier() const { return Name; }
4130 /// \brief Retrieve the template arguments.
4131 const TemplateArgument *getArgs() const {
4132 return getArgBuffer();
4135 /// \brief Retrieve the number of template arguments.
4136 unsigned getNumArgs() const { return NumArgs; }
4138 const TemplateArgument &getArg(unsigned Idx) const; // in TemplateBase.h
4140 typedef const TemplateArgument * iterator;
4141 iterator begin() const { return getArgs(); }
4142 iterator end() const; // inline in TemplateBase.h
4144 bool isSugared() const { return false; }
4145 QualType desugar() const { return QualType(this, 0); }
4147 void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context) {
4148 Profile(ID, Context, getKeyword(), NNS, Name, NumArgs, getArgs());
4151 static void Profile(llvm::FoldingSetNodeID &ID,
4152 const ASTContext &Context,
4153 ElaboratedTypeKeyword Keyword,
4154 NestedNameSpecifier *Qualifier,
4155 const IdentifierInfo *Name,
4157 const TemplateArgument *Args);
4159 static bool classof(const Type *T) {
4160 return T->getTypeClass() == DependentTemplateSpecialization;
4164 /// \brief Represents a pack expansion of types.
4166 /// Pack expansions are part of C++0x variadic templates. A pack
4167 /// expansion contains a pattern, which itself contains one or more
4168 /// "unexpanded" parameter packs. When instantiated, a pack expansion
4169 /// produces a series of types, each instantiated from the pattern of
4170 /// the expansion, where the Ith instantiation of the pattern uses the
4171 /// Ith arguments bound to each of the unexpanded parameter packs. The
4172 /// pack expansion is considered to "expand" these unexpanded
4173 /// parameter packs.
4176 /// template<typename ...Types> struct tuple;
4178 /// template<typename ...Types>
4179 /// struct tuple_of_references {
4180 /// typedef tuple<Types&...> type;
4184 /// Here, the pack expansion \c Types&... is represented via a
4185 /// PackExpansionType whose pattern is Types&.
4186 class PackExpansionType : public Type, public llvm::FoldingSetNode {
4187 /// \brief The pattern of the pack expansion.
4190 /// \brief The number of expansions that this pack expansion will
4191 /// generate when substituted (+1), or indicates that
4193 /// This field will only have a non-zero value when some of the parameter
4194 /// packs that occur within the pattern have been substituted but others have
4196 unsigned NumExpansions;
4198 PackExpansionType(QualType Pattern, QualType Canon,
4199 Optional<unsigned> NumExpansions)
4200 : Type(PackExpansion, Canon, /*Dependent=*/Pattern->isDependentType(),
4201 /*InstantiationDependent=*/true,
4202 /*VariableModified=*/Pattern->isVariablyModifiedType(),
4203 /*ContainsUnexpandedParameterPack=*/false),
4205 NumExpansions(NumExpansions? *NumExpansions + 1: 0) { }
4207 friend class ASTContext; // ASTContext creates these
4210 /// \brief Retrieve the pattern of this pack expansion, which is the
4211 /// type that will be repeatedly instantiated when instantiating the
4212 /// pack expansion itself.
4213 QualType getPattern() const { return Pattern; }
4215 /// \brief Retrieve the number of expansions that this pack expansion will
4216 /// generate, if known.
4217 Optional<unsigned> getNumExpansions() const {
4219 return NumExpansions - 1;
4224 bool isSugared() const { return !Pattern->isDependentType(); }
4225 QualType desugar() const { return isSugared() ? Pattern : QualType(this, 0); }
4227 void Profile(llvm::FoldingSetNodeID &ID) {
4228 Profile(ID, getPattern(), getNumExpansions());
4231 static void Profile(llvm::FoldingSetNodeID &ID, QualType Pattern,
4232 Optional<unsigned> NumExpansions) {
4233 ID.AddPointer(Pattern.getAsOpaquePtr());
4234 ID.AddBoolean(NumExpansions.hasValue());
4236 ID.AddInteger(*NumExpansions);
4239 static bool classof(const Type *T) {
4240 return T->getTypeClass() == PackExpansion;
4244 /// ObjCObjectType - Represents a class type in Objective C.
4245 /// Every Objective C type is a combination of a base type and a
4246 /// list of protocols.
4248 /// Given the following declarations:
4254 /// 'C' is an ObjCInterfaceType C. It is sugar for an ObjCObjectType
4255 /// with base C and no protocols.
4257 /// 'C<P>' is an ObjCObjectType with base C and protocol list [P].
4259 /// 'id' is a TypedefType which is sugar for an ObjCObjectPointerType whose
4260 /// pointee is an ObjCObjectType with base BuiltinType::ObjCIdType
4261 /// and no protocols.
4263 /// 'id<P>' is an ObjCObjectPointerType whose pointee is an ObjCObjectType
4264 /// with base BuiltinType::ObjCIdType and protocol list [P]. Eventually
4265 /// this should get its own sugar class to better represent the source.
4266 class ObjCObjectType : public Type {
4267 // ObjCObjectType.NumProtocols - the number of protocols stored
4268 // after the ObjCObjectPointerType node.
4270 // These protocols are those written directly on the type. If
4271 // protocol qualifiers ever become additive, the iterators will need
4272 // to get kindof complicated.
4274 // In the canonical object type, these are sorted alphabetically
4277 /// Either a BuiltinType or an InterfaceType or sugar for either.
4280 ObjCProtocolDecl * const *getProtocolStorage() const {
4281 return const_cast<ObjCObjectType*>(this)->getProtocolStorage();
4284 ObjCProtocolDecl **getProtocolStorage();
4287 ObjCObjectType(QualType Canonical, QualType Base,
4288 ObjCProtocolDecl * const *Protocols, unsigned NumProtocols);
4290 enum Nonce_ObjCInterface { Nonce_ObjCInterface };
4291 ObjCObjectType(enum Nonce_ObjCInterface)
4292 : Type(ObjCInterface, QualType(), false, false, false, false),
4293 BaseType(QualType(this_(), 0)) {
4294 ObjCObjectTypeBits.NumProtocols = 0;
4298 /// getBaseType - Gets the base type of this object type. This is
4299 /// always (possibly sugar for) one of:
4300 /// - the 'id' builtin type (as opposed to the 'id' type visible to the
4301 /// user, which is a typedef for an ObjCObjectPointerType)
4302 /// - the 'Class' builtin type (same caveat)
4303 /// - an ObjCObjectType (currently always an ObjCInterfaceType)
4304 QualType getBaseType() const { return BaseType; }
4306 bool isObjCId() const {
4307 return getBaseType()->isSpecificBuiltinType(BuiltinType::ObjCId);
4309 bool isObjCClass() const {
4310 return getBaseType()->isSpecificBuiltinType(BuiltinType::ObjCClass);
4312 bool isObjCUnqualifiedId() const { return qual_empty() && isObjCId(); }
4313 bool isObjCUnqualifiedClass() const { return qual_empty() && isObjCClass(); }
4314 bool isObjCUnqualifiedIdOrClass() const {
4315 if (!qual_empty()) return false;
4316 if (const BuiltinType *T = getBaseType()->getAs<BuiltinType>())
4317 return T->getKind() == BuiltinType::ObjCId ||
4318 T->getKind() == BuiltinType::ObjCClass;
4321 bool isObjCQualifiedId() const { return !qual_empty() && isObjCId(); }
4322 bool isObjCQualifiedClass() const { return !qual_empty() && isObjCClass(); }
4324 /// Gets the interface declaration for this object type, if the base type
4325 /// really is an interface.
4326 ObjCInterfaceDecl *getInterface() const;
4328 typedef ObjCProtocolDecl * const *qual_iterator;
4330 qual_iterator qual_begin() const { return getProtocolStorage(); }
4331 qual_iterator qual_end() const { return qual_begin() + getNumProtocols(); }
4333 bool qual_empty() const { return getNumProtocols() == 0; }
4335 /// getNumProtocols - Return the number of qualifying protocols in this
4336 /// interface type, or 0 if there are none.
4337 unsigned getNumProtocols() const { return ObjCObjectTypeBits.NumProtocols; }
4339 /// \brief Fetch a protocol by index.
4340 ObjCProtocolDecl *getProtocol(unsigned I) const {
4341 assert(I < getNumProtocols() && "Out-of-range protocol access");
4342 return qual_begin()[I];
4345 bool isSugared() const { return false; }
4346 QualType desugar() const { return QualType(this, 0); }
4348 static bool classof(const Type *T) {
4349 return T->getTypeClass() == ObjCObject ||
4350 T->getTypeClass() == ObjCInterface;
4354 /// ObjCObjectTypeImpl - A class providing a concrete implementation
4355 /// of ObjCObjectType, so as to not increase the footprint of
4356 /// ObjCInterfaceType. Code outside of ASTContext and the core type
4357 /// system should not reference this type.
4358 class ObjCObjectTypeImpl : public ObjCObjectType, public llvm::FoldingSetNode {
4359 friend class ASTContext;
4361 // If anyone adds fields here, ObjCObjectType::getProtocolStorage()
4362 // will need to be modified.
4364 ObjCObjectTypeImpl(QualType Canonical, QualType Base,
4365 ObjCProtocolDecl * const *Protocols,
4366 unsigned NumProtocols)
4367 : ObjCObjectType(Canonical, Base, Protocols, NumProtocols) {}
4370 void Profile(llvm::FoldingSetNodeID &ID);
4371 static void Profile(llvm::FoldingSetNodeID &ID,
4373 ObjCProtocolDecl *const *protocols,
4374 unsigned NumProtocols);
4377 inline ObjCProtocolDecl **ObjCObjectType::getProtocolStorage() {
4378 return reinterpret_cast<ObjCProtocolDecl**>(
4379 static_cast<ObjCObjectTypeImpl*>(this) + 1);
4382 /// ObjCInterfaceType - Interfaces are the core concept in Objective-C for
4383 /// object oriented design. They basically correspond to C++ classes. There
4384 /// are two kinds of interface types, normal interfaces like "NSString" and
4385 /// qualified interfaces, which are qualified with a protocol list like
4386 /// "NSString<NSCopyable, NSAmazing>".
4388 /// ObjCInterfaceType guarantees the following properties when considered
4389 /// as a subtype of its superclass, ObjCObjectType:
4390 /// - There are no protocol qualifiers. To reinforce this, code which
4391 /// tries to invoke the protocol methods via an ObjCInterfaceType will
4392 /// fail to compile.
4393 /// - It is its own base type. That is, if T is an ObjCInterfaceType*,
4394 /// T->getBaseType() == QualType(T, 0).
4395 class ObjCInterfaceType : public ObjCObjectType {
4396 mutable ObjCInterfaceDecl *Decl;
4398 ObjCInterfaceType(const ObjCInterfaceDecl *D)
4399 : ObjCObjectType(Nonce_ObjCInterface),
4400 Decl(const_cast<ObjCInterfaceDecl*>(D)) {}
4401 friend class ASTContext; // ASTContext creates these.
4402 friend class ASTReader;
4403 friend class ObjCInterfaceDecl;
4406 /// getDecl - Get the declaration of this interface.
4407 ObjCInterfaceDecl *getDecl() const { return Decl; }
4409 bool isSugared() const { return false; }
4410 QualType desugar() const { return QualType(this, 0); }
4412 static bool classof(const Type *T) {
4413 return T->getTypeClass() == ObjCInterface;
4416 // Nonsense to "hide" certain members of ObjCObjectType within this
4417 // class. People asking for protocols on an ObjCInterfaceType are
4418 // not going to get what they want: ObjCInterfaceTypes are
4419 // guaranteed to have no protocols.
4429 inline ObjCInterfaceDecl *ObjCObjectType::getInterface() const {
4430 if (const ObjCInterfaceType *T =
4431 getBaseType()->getAs<ObjCInterfaceType>())
4432 return T->getDecl();
4436 /// ObjCObjectPointerType - Used to represent a pointer to an
4437 /// Objective C object. These are constructed from pointer
4438 /// declarators when the pointee type is an ObjCObjectType (or sugar
4439 /// for one). In addition, the 'id' and 'Class' types are typedefs
4440 /// for these, and the protocol-qualified types 'id<P>' and 'Class<P>'
4441 /// are translated into these.
4443 /// Pointers to pointers to Objective C objects are still PointerTypes;
4444 /// only the first level of pointer gets it own type implementation.
4445 class ObjCObjectPointerType : public Type, public llvm::FoldingSetNode {
4446 QualType PointeeType;
4448 ObjCObjectPointerType(QualType Canonical, QualType Pointee)
4449 : Type(ObjCObjectPointer, Canonical, false, false, false, false),
4450 PointeeType(Pointee) {}
4451 friend class ASTContext; // ASTContext creates these.
4454 /// getPointeeType - Gets the type pointed to by this ObjC pointer.
4455 /// The result will always be an ObjCObjectType or sugar thereof.
4456 QualType getPointeeType() const { return PointeeType; }
4458 /// getObjCObjectType - Gets the type pointed to by this ObjC
4459 /// pointer. This method always returns non-null.
4461 /// This method is equivalent to getPointeeType() except that
4462 /// it discards any typedefs (or other sugar) between this
4463 /// type and the "outermost" object type. So for:
4465 /// \@class A; \@protocol P; \@protocol Q;
4466 /// typedef A<P> AP;
4468 /// typedef A1<P> A1P;
4469 /// typedef A1P<Q> A1PQ;
4471 /// For 'A*', getObjectType() will return 'A'.
4472 /// For 'A<P>*', getObjectType() will return 'A<P>'.
4473 /// For 'AP*', getObjectType() will return 'A<P>'.
4474 /// For 'A1*', getObjectType() will return 'A'.
4475 /// For 'A1<P>*', getObjectType() will return 'A1<P>'.
4476 /// For 'A1P*', getObjectType() will return 'A1<P>'.
4477 /// For 'A1PQ*', getObjectType() will return 'A1<Q>', because
4478 /// adding protocols to a protocol-qualified base discards the
4479 /// old qualifiers (for now). But if it didn't, getObjectType()
4480 /// would return 'A1P<Q>' (and we'd have to make iterating over
4481 /// qualifiers more complicated).
4482 const ObjCObjectType *getObjectType() const {
4483 return PointeeType->castAs<ObjCObjectType>();
4486 /// getInterfaceType - If this pointer points to an Objective C
4487 /// \@interface type, gets the type for that interface. Any protocol
4488 /// qualifiers on the interface are ignored.
4490 /// \return null if the base type for this pointer is 'id' or 'Class'
4491 const ObjCInterfaceType *getInterfaceType() const {
4492 return getObjectType()->getBaseType()->getAs<ObjCInterfaceType>();
4495 /// getInterfaceDecl - If this pointer points to an Objective \@interface
4496 /// type, gets the declaration for that interface.
4498 /// \return null if the base type for this pointer is 'id' or 'Class'
4499 ObjCInterfaceDecl *getInterfaceDecl() const {
4500 return getObjectType()->getInterface();
4503 /// isObjCIdType - True if this is equivalent to the 'id' type, i.e. if
4504 /// its object type is the primitive 'id' type with no protocols.
4505 bool isObjCIdType() const {
4506 return getObjectType()->isObjCUnqualifiedId();
4509 /// isObjCClassType - True if this is equivalent to the 'Class' type,
4510 /// i.e. if its object tive is the primitive 'Class' type with no protocols.
4511 bool isObjCClassType() const {
4512 return getObjectType()->isObjCUnqualifiedClass();
4515 /// isObjCQualifiedIdType - True if this is equivalent to 'id<P>' for some
4516 /// non-empty set of protocols.
4517 bool isObjCQualifiedIdType() const {
4518 return getObjectType()->isObjCQualifiedId();
4521 /// isObjCQualifiedClassType - True if this is equivalent to 'Class<P>' for
4522 /// some non-empty set of protocols.
4523 bool isObjCQualifiedClassType() const {
4524 return getObjectType()->isObjCQualifiedClass();
4527 /// An iterator over the qualifiers on the object type. Provided
4528 /// for convenience. This will always iterate over the full set of
4529 /// protocols on a type, not just those provided directly.
4530 typedef ObjCObjectType::qual_iterator qual_iterator;
4532 qual_iterator qual_begin() const {
4533 return getObjectType()->qual_begin();
4535 qual_iterator qual_end() const {
4536 return getObjectType()->qual_end();
4538 bool qual_empty() const { return getObjectType()->qual_empty(); }
4540 /// getNumProtocols - Return the number of qualifying protocols on
4541 /// the object type.
4542 unsigned getNumProtocols() const {
4543 return getObjectType()->getNumProtocols();
4546 /// \brief Retrieve a qualifying protocol by index on the object
4548 ObjCProtocolDecl *getProtocol(unsigned I) const {
4549 return getObjectType()->getProtocol(I);
4552 bool isSugared() const { return false; }
4553 QualType desugar() const { return QualType(this, 0); }
4555 void Profile(llvm::FoldingSetNodeID &ID) {
4556 Profile(ID, getPointeeType());
4558 static void Profile(llvm::FoldingSetNodeID &ID, QualType T) {
4559 ID.AddPointer(T.getAsOpaquePtr());
4561 static bool classof(const Type *T) {
4562 return T->getTypeClass() == ObjCObjectPointer;
4566 class AtomicType : public Type, public llvm::FoldingSetNode {
4569 AtomicType(QualType ValTy, QualType Canonical)
4570 : Type(Atomic, Canonical, ValTy->isDependentType(),
4571 ValTy->isInstantiationDependentType(),
4572 ValTy->isVariablyModifiedType(),
4573 ValTy->containsUnexpandedParameterPack()),
4575 friend class ASTContext; // ASTContext creates these.
4578 /// getValueType - Gets the type contained by this atomic type, i.e.
4579 /// the type returned by performing an atomic load of this atomic type.
4580 QualType getValueType() const { return ValueType; }
4582 bool isSugared() const { return false; }
4583 QualType desugar() const { return QualType(this, 0); }
4585 void Profile(llvm::FoldingSetNodeID &ID) {
4586 Profile(ID, getValueType());
4588 static void Profile(llvm::FoldingSetNodeID &ID, QualType T) {
4589 ID.AddPointer(T.getAsOpaquePtr());
4591 static bool classof(const Type *T) {
4592 return T->getTypeClass() == Atomic;
4596 /// A qualifier set is used to build a set of qualifiers.
4597 class QualifierCollector : public Qualifiers {
4599 QualifierCollector(Qualifiers Qs = Qualifiers()) : Qualifiers(Qs) {}
4601 /// Collect any qualifiers on the given type and return an
4602 /// unqualified type. The qualifiers are assumed to be consistent
4603 /// with those already in the type.
4604 const Type *strip(QualType type) {
4605 addFastQualifiers(type.getLocalFastQualifiers());
4606 if (!type.hasLocalNonFastQualifiers())
4607 return type.getTypePtrUnsafe();
4609 const ExtQuals *extQuals = type.getExtQualsUnsafe();
4610 addConsistentQualifiers(extQuals->getQualifiers());
4611 return extQuals->getBaseType();
4614 /// Apply the collected qualifiers to the given type.
4615 QualType apply(const ASTContext &Context, QualType QT) const;
4617 /// Apply the collected qualifiers to the given type.
4618 QualType apply(const ASTContext &Context, const Type* T) const;
4622 // Inline function definitions.
4624 inline SplitQualType SplitQualType::getSingleStepDesugaredType() const {
4625 SplitQualType desugar =
4626 Ty->getLocallyUnqualifiedSingleStepDesugaredType().split();
4627 desugar.Quals.addConsistentQualifiers(Quals);
4631 inline const Type *QualType::getTypePtr() const {
4632 return getCommonPtr()->BaseType;
4635 inline const Type *QualType::getTypePtrOrNull() const {
4636 return (isNull() ? 0 : getCommonPtr()->BaseType);
4639 inline SplitQualType QualType::split() const {
4640 if (!hasLocalNonFastQualifiers())
4641 return SplitQualType(getTypePtrUnsafe(),
4642 Qualifiers::fromFastMask(getLocalFastQualifiers()));
4644 const ExtQuals *eq = getExtQualsUnsafe();
4645 Qualifiers qs = eq->getQualifiers();
4646 qs.addFastQualifiers(getLocalFastQualifiers());
4647 return SplitQualType(eq->getBaseType(), qs);
4650 inline Qualifiers QualType::getLocalQualifiers() const {
4652 if (hasLocalNonFastQualifiers())
4653 Quals = getExtQualsUnsafe()->getQualifiers();
4654 Quals.addFastQualifiers(getLocalFastQualifiers());
4658 inline Qualifiers QualType::getQualifiers() const {
4659 Qualifiers quals = getCommonPtr()->CanonicalType.getLocalQualifiers();
4660 quals.addFastQualifiers(getLocalFastQualifiers());
4664 inline unsigned QualType::getCVRQualifiers() const {
4665 unsigned cvr = getCommonPtr()->CanonicalType.getLocalCVRQualifiers();
4666 cvr |= getLocalCVRQualifiers();
4670 inline QualType QualType::getCanonicalType() const {
4671 QualType canon = getCommonPtr()->CanonicalType;
4672 return canon.withFastQualifiers(getLocalFastQualifiers());
4675 inline bool QualType::isCanonical() const {
4676 return getTypePtr()->isCanonicalUnqualified();
4679 inline bool QualType::isCanonicalAsParam() const {
4680 if (!isCanonical()) return false;
4681 if (hasLocalQualifiers()) return false;
4683 const Type *T = getTypePtr();
4684 if (T->isVariablyModifiedType() && T->hasSizedVLAType())
4687 return !isa<FunctionType>(T) && !isa<ArrayType>(T);
4690 inline bool QualType::isConstQualified() const {
4691 return isLocalConstQualified() ||
4692 getCommonPtr()->CanonicalType.isLocalConstQualified();
4695 inline bool QualType::isRestrictQualified() const {
4696 return isLocalRestrictQualified() ||
4697 getCommonPtr()->CanonicalType.isLocalRestrictQualified();
4701 inline bool QualType::isVolatileQualified() const {
4702 return isLocalVolatileQualified() ||
4703 getCommonPtr()->CanonicalType.isLocalVolatileQualified();
4706 inline bool QualType::hasQualifiers() const {
4707 return hasLocalQualifiers() ||
4708 getCommonPtr()->CanonicalType.hasLocalQualifiers();
4711 inline QualType QualType::getUnqualifiedType() const {
4712 if (!getTypePtr()->getCanonicalTypeInternal().hasLocalQualifiers())
4713 return QualType(getTypePtr(), 0);
4715 return QualType(getSplitUnqualifiedTypeImpl(*this).Ty, 0);
4718 inline SplitQualType QualType::getSplitUnqualifiedType() const {
4719 if (!getTypePtr()->getCanonicalTypeInternal().hasLocalQualifiers())
4722 return getSplitUnqualifiedTypeImpl(*this);
4725 inline void QualType::removeLocalConst() {
4726 removeLocalFastQualifiers(Qualifiers::Const);
4729 inline void QualType::removeLocalRestrict() {
4730 removeLocalFastQualifiers(Qualifiers::Restrict);
4733 inline void QualType::removeLocalVolatile() {
4734 removeLocalFastQualifiers(Qualifiers::Volatile);
4737 inline void QualType::removeLocalCVRQualifiers(unsigned Mask) {
4738 assert(!(Mask & ~Qualifiers::CVRMask) && "mask has non-CVR bits");
4739 assert((int)Qualifiers::CVRMask == (int)Qualifiers::FastMask);
4741 // Fast path: we don't need to touch the slow qualifiers.
4742 removeLocalFastQualifiers(Mask);
4745 /// getAddressSpace - Return the address space of this type.
4746 inline unsigned QualType::getAddressSpace() const {
4747 return getQualifiers().getAddressSpace();
4750 /// getObjCGCAttr - Return the gc attribute of this type.
4751 inline Qualifiers::GC QualType::getObjCGCAttr() const {
4752 return getQualifiers().getObjCGCAttr();
4755 inline FunctionType::ExtInfo getFunctionExtInfo(const Type &t) {
4756 if (const PointerType *PT = t.getAs<PointerType>()) {
4757 if (const FunctionType *FT = PT->getPointeeType()->getAs<FunctionType>())
4758 return FT->getExtInfo();
4759 } else if (const FunctionType *FT = t.getAs<FunctionType>())
4760 return FT->getExtInfo();
4762 return FunctionType::ExtInfo();
4765 inline FunctionType::ExtInfo getFunctionExtInfo(QualType t) {
4766 return getFunctionExtInfo(*t);
4769 /// isMoreQualifiedThan - Determine whether this type is more
4770 /// qualified than the Other type. For example, "const volatile int"
4771 /// is more qualified than "const int", "volatile int", and
4772 /// "int". However, it is not more qualified than "const volatile
4774 inline bool QualType::isMoreQualifiedThan(QualType other) const {
4775 Qualifiers myQuals = getQualifiers();
4776 Qualifiers otherQuals = other.getQualifiers();
4777 return (myQuals != otherQuals && myQuals.compatiblyIncludes(otherQuals));
4780 /// isAtLeastAsQualifiedAs - Determine whether this type is at last
4781 /// as qualified as the Other type. For example, "const volatile
4782 /// int" is at least as qualified as "const int", "volatile int",
4783 /// "int", and "const volatile int".
4784 inline bool QualType::isAtLeastAsQualifiedAs(QualType other) const {
4785 return getQualifiers().compatiblyIncludes(other.getQualifiers());
4788 /// getNonReferenceType - If Type is a reference type (e.g., const
4789 /// int&), returns the type that the reference refers to ("const
4790 /// int"). Otherwise, returns the type itself. This routine is used
4791 /// throughout Sema to implement C++ 5p6:
4793 /// If an expression initially has the type "reference to T" (8.3.2,
4794 /// 8.5.3), the type is adjusted to "T" prior to any further
4795 /// analysis, the expression designates the object or function
4796 /// denoted by the reference, and the expression is an lvalue.
4797 inline QualType QualType::getNonReferenceType() const {
4798 if (const ReferenceType *RefType = (*this)->getAs<ReferenceType>())
4799 return RefType->getPointeeType();
4804 inline bool QualType::isCForbiddenLValueType() const {
4805 return ((getTypePtr()->isVoidType() && !hasQualifiers()) ||
4806 getTypePtr()->isFunctionType());
4809 /// \brief Tests whether the type is categorized as a fundamental type.
4811 /// \returns True for types specified in C++0x [basic.fundamental].
4812 inline bool Type::isFundamentalType() const {
4813 return isVoidType() ||
4814 // FIXME: It's really annoying that we don't have an
4815 // 'isArithmeticType()' which agrees with the standard definition.
4816 (isArithmeticType() && !isEnumeralType());
4819 /// \brief Tests whether the type is categorized as a compound type.
4821 /// \returns True for types specified in C++0x [basic.compound].
4822 inline bool Type::isCompoundType() const {
4823 // C++0x [basic.compound]p1:
4824 // Compound types can be constructed in the following ways:
4825 // -- arrays of objects of a given type [...];
4826 return isArrayType() ||
4827 // -- functions, which have parameters of given types [...];
4829 // -- pointers to void or objects or functions [...];
4831 // -- references to objects or functions of a given type. [...]
4832 isReferenceType() ||
4833 // -- classes containing a sequence of objects of various types, [...];
4835 // -- unions, which are classes capable of containing objects of different
4836 // types at different times;
4838 // -- enumerations, which comprise a set of named constant values. [...];
4840 // -- pointers to non-static class members, [...].
4841 isMemberPointerType();
4844 inline bool Type::isFunctionType() const {
4845 return isa<FunctionType>(CanonicalType);
4847 inline bool Type::isPointerType() const {
4848 return isa<PointerType>(CanonicalType);
4850 inline bool Type::isAnyPointerType() const {
4851 return isPointerType() || isObjCObjectPointerType();
4853 inline bool Type::isBlockPointerType() const {
4854 return isa<BlockPointerType>(CanonicalType);
4856 inline bool Type::isReferenceType() const {
4857 return isa<ReferenceType>(CanonicalType);
4859 inline bool Type::isLValueReferenceType() const {
4860 return isa<LValueReferenceType>(CanonicalType);
4862 inline bool Type::isRValueReferenceType() const {
4863 return isa<RValueReferenceType>(CanonicalType);
4865 inline bool Type::isFunctionPointerType() const {
4866 if (const PointerType *T = getAs<PointerType>())
4867 return T->getPointeeType()->isFunctionType();
4871 inline bool Type::isMemberPointerType() const {
4872 return isa<MemberPointerType>(CanonicalType);
4874 inline bool Type::isMemberFunctionPointerType() const {
4875 if (const MemberPointerType* T = getAs<MemberPointerType>())
4876 return T->isMemberFunctionPointer();
4880 inline bool Type::isMemberDataPointerType() const {
4881 if (const MemberPointerType* T = getAs<MemberPointerType>())
4882 return T->isMemberDataPointer();
4886 inline bool Type::isArrayType() const {
4887 return isa<ArrayType>(CanonicalType);
4889 inline bool Type::isConstantArrayType() const {
4890 return isa<ConstantArrayType>(CanonicalType);
4892 inline bool Type::isIncompleteArrayType() const {
4893 return isa<IncompleteArrayType>(CanonicalType);
4895 inline bool Type::isVariableArrayType() const {
4896 return isa<VariableArrayType>(CanonicalType);
4898 inline bool Type::isDependentSizedArrayType() const {
4899 return isa<DependentSizedArrayType>(CanonicalType);
4901 inline bool Type::isBuiltinType() const {
4902 return isa<BuiltinType>(CanonicalType);
4904 inline bool Type::isRecordType() const {
4905 return isa<RecordType>(CanonicalType);
4907 inline bool Type::isEnumeralType() const {
4908 return isa<EnumType>(CanonicalType);
4910 inline bool Type::isAnyComplexType() const {
4911 return isa<ComplexType>(CanonicalType);
4913 inline bool Type::isVectorType() const {
4914 return isa<VectorType>(CanonicalType);
4916 inline bool Type::isExtVectorType() const {
4917 return isa<ExtVectorType>(CanonicalType);
4919 inline bool Type::isObjCObjectPointerType() const {
4920 return isa<ObjCObjectPointerType>(CanonicalType);
4922 inline bool Type::isObjCObjectType() const {
4923 return isa<ObjCObjectType>(CanonicalType);
4925 inline bool Type::isObjCObjectOrInterfaceType() const {
4926 return isa<ObjCInterfaceType>(CanonicalType) ||
4927 isa<ObjCObjectType>(CanonicalType);
4929 inline bool Type::isAtomicType() const {
4930 return isa<AtomicType>(CanonicalType);
4933 inline bool Type::isObjCQualifiedIdType() const {
4934 if (const ObjCObjectPointerType *OPT = getAs<ObjCObjectPointerType>())
4935 return OPT->isObjCQualifiedIdType();
4938 inline bool Type::isObjCQualifiedClassType() const {
4939 if (const ObjCObjectPointerType *OPT = getAs<ObjCObjectPointerType>())
4940 return OPT->isObjCQualifiedClassType();
4943 inline bool Type::isObjCIdType() const {
4944 if (const ObjCObjectPointerType *OPT = getAs<ObjCObjectPointerType>())
4945 return OPT->isObjCIdType();
4948 inline bool Type::isObjCClassType() const {
4949 if (const ObjCObjectPointerType *OPT = getAs<ObjCObjectPointerType>())
4950 return OPT->isObjCClassType();
4953 inline bool Type::isObjCSelType() const {
4954 if (const PointerType *OPT = getAs<PointerType>())
4955 return OPT->getPointeeType()->isSpecificBuiltinType(BuiltinType::ObjCSel);
4958 inline bool Type::isObjCBuiltinType() const {
4959 return isObjCIdType() || isObjCClassType() || isObjCSelType();
4962 inline bool Type::isImage1dT() const {
4963 return isSpecificBuiltinType(BuiltinType::OCLImage1d);
4966 inline bool Type::isImage1dArrayT() const {
4967 return isSpecificBuiltinType(BuiltinType::OCLImage1dArray);
4970 inline bool Type::isImage1dBufferT() const {
4971 return isSpecificBuiltinType(BuiltinType::OCLImage1dBuffer);
4974 inline bool Type::isImage2dT() const {
4975 return isSpecificBuiltinType(BuiltinType::OCLImage2d);
4978 inline bool Type::isImage2dArrayT() const {
4979 return isSpecificBuiltinType(BuiltinType::OCLImage2dArray);
4982 inline bool Type::isImage3dT() const {
4983 return isSpecificBuiltinType(BuiltinType::OCLImage3d);
4986 inline bool Type::isSamplerT() const {
4987 return isSpecificBuiltinType(BuiltinType::OCLSampler);
4990 inline bool Type::isEventT() const {
4991 return isSpecificBuiltinType(BuiltinType::OCLEvent);
4994 inline bool Type::isImageType() const {
4995 return isImage3dT() ||
4996 isImage2dT() || isImage2dArrayT() ||
4997 isImage1dT() || isImage1dArrayT() || isImage1dBufferT();
5000 inline bool Type::isOpenCLSpecificType() const {
5001 return isSamplerT() || isEventT() || isImageType();
5004 inline bool Type::isTemplateTypeParmType() const {
5005 return isa<TemplateTypeParmType>(CanonicalType);
5008 inline bool Type::isSpecificBuiltinType(unsigned K) const {
5009 if (const BuiltinType *BT = getAs<BuiltinType>())
5010 if (BT->getKind() == (BuiltinType::Kind) K)
5015 inline bool Type::isPlaceholderType() const {
5016 if (const BuiltinType *BT = dyn_cast<BuiltinType>(this))
5017 return BT->isPlaceholderType();
5021 inline const BuiltinType *Type::getAsPlaceholderType() const {
5022 if (const BuiltinType *BT = dyn_cast<BuiltinType>(this))
5023 if (BT->isPlaceholderType())
5028 inline bool Type::isSpecificPlaceholderType(unsigned K) const {
5029 assert(BuiltinType::isPlaceholderTypeKind((BuiltinType::Kind) K));
5030 if (const BuiltinType *BT = dyn_cast<BuiltinType>(this))
5031 return (BT->getKind() == (BuiltinType::Kind) K);
5035 inline bool Type::isNonOverloadPlaceholderType() const {
5036 if (const BuiltinType *BT = dyn_cast<BuiltinType>(this))
5037 return BT->isNonOverloadPlaceholderType();
5041 inline bool Type::isVoidType() const {
5042 if (const BuiltinType *BT = dyn_cast<BuiltinType>(CanonicalType))
5043 return BT->getKind() == BuiltinType::Void;
5047 inline bool Type::isHalfType() const {
5048 if (const BuiltinType *BT = dyn_cast<BuiltinType>(CanonicalType))
5049 return BT->getKind() == BuiltinType::Half;
5050 // FIXME: Should we allow complex __fp16? Probably not.
5054 inline bool Type::isNullPtrType() const {
5055 if (const BuiltinType *BT = getAs<BuiltinType>())
5056 return BT->getKind() == BuiltinType::NullPtr;
5060 extern bool IsEnumDeclComplete(EnumDecl *);
5061 extern bool IsEnumDeclScoped(EnumDecl *);
5063 inline bool Type::isIntegerType() const {
5064 if (const BuiltinType *BT = dyn_cast<BuiltinType>(CanonicalType))
5065 return BT->getKind() >= BuiltinType::Bool &&
5066 BT->getKind() <= BuiltinType::Int128;
5067 if (const EnumType *ET = dyn_cast<EnumType>(CanonicalType)) {
5068 // Incomplete enum types are not treated as integer types.
5069 // FIXME: In C++, enum types are never integer types.
5070 return IsEnumDeclComplete(ET->getDecl()) &&
5071 !IsEnumDeclScoped(ET->getDecl());
5076 inline bool Type::isScalarType() const {
5077 if (const BuiltinType *BT = dyn_cast<BuiltinType>(CanonicalType))
5078 return BT->getKind() > BuiltinType::Void &&
5079 BT->getKind() <= BuiltinType::NullPtr;
5080 if (const EnumType *ET = dyn_cast<EnumType>(CanonicalType))
5081 // Enums are scalar types, but only if they are defined. Incomplete enums
5082 // are not treated as scalar types.
5083 return IsEnumDeclComplete(ET->getDecl());
5084 return isa<PointerType>(CanonicalType) ||
5085 isa<BlockPointerType>(CanonicalType) ||
5086 isa<MemberPointerType>(CanonicalType) ||
5087 isa<ComplexType>(CanonicalType) ||
5088 isa<ObjCObjectPointerType>(CanonicalType);
5091 inline bool Type::isIntegralOrEnumerationType() const {
5092 if (const BuiltinType *BT = dyn_cast<BuiltinType>(CanonicalType))
5093 return BT->getKind() >= BuiltinType::Bool &&
5094 BT->getKind() <= BuiltinType::Int128;
5096 // Check for a complete enum type; incomplete enum types are not properly an
5097 // enumeration type in the sense required here.
5098 if (const EnumType *ET = dyn_cast<EnumType>(CanonicalType))
5099 return IsEnumDeclComplete(ET->getDecl());
5104 inline bool Type::isBooleanType() const {
5105 if (const BuiltinType *BT = dyn_cast<BuiltinType>(CanonicalType))
5106 return BT->getKind() == BuiltinType::Bool;
5110 inline bool Type::isUndeducedType() const {
5111 const AutoType *AT = getContainedAutoType();
5112 return AT && !AT->isDeduced();
5115 /// \brief Determines whether this is a type for which one can define
5116 /// an overloaded operator.
5117 inline bool Type::isOverloadableType() const {
5118 return isDependentType() || isRecordType() || isEnumeralType();
5121 /// \brief Determines whether this type can decay to a pointer type.
5122 inline bool Type::canDecayToPointerType() const {
5123 return isFunctionType() || isArrayType();
5126 inline bool Type::hasPointerRepresentation() const {
5127 return (isPointerType() || isReferenceType() || isBlockPointerType() ||
5128 isObjCObjectPointerType() || isNullPtrType());
5131 inline bool Type::hasObjCPointerRepresentation() const {
5132 return isObjCObjectPointerType();
5135 inline const Type *Type::getBaseElementTypeUnsafe() const {
5136 const Type *type = this;
5137 while (const ArrayType *arrayType = type->getAsArrayTypeUnsafe())
5138 type = arrayType->getElementType().getTypePtr();
5142 /// Insertion operator for diagnostics. This allows sending QualType's into a
5143 /// diagnostic with <<.
5144 inline const DiagnosticBuilder &operator<<(const DiagnosticBuilder &DB,
5146 DB.AddTaggedVal(reinterpret_cast<intptr_t>(T.getAsOpaquePtr()),
5147 DiagnosticsEngine::ak_qualtype);
5151 /// Insertion operator for partial diagnostics. This allows sending QualType's
5152 /// into a diagnostic with <<.
5153 inline const PartialDiagnostic &operator<<(const PartialDiagnostic &PD,
5155 PD.AddTaggedVal(reinterpret_cast<intptr_t>(T.getAsOpaquePtr()),
5156 DiagnosticsEngine::ak_qualtype);
5160 // Helper class template that is used by Type::getAs to ensure that one does
5161 // not try to look through a qualified type to get to an array type.
5162 template<typename T,
5163 bool isArrayType = (llvm::is_same<T, ArrayType>::value ||
5164 llvm::is_base_of<ArrayType, T>::value)>
5165 struct ArrayType_cannot_be_used_with_getAs { };
5167 template<typename T>
5168 struct ArrayType_cannot_be_used_with_getAs<T, true>;
5170 // Member-template getAs<specific type>'.
5171 template <typename T> const T *Type::getAs() const {
5172 ArrayType_cannot_be_used_with_getAs<T> at;
5175 // If this is directly a T type, return it.
5176 if (const T *Ty = dyn_cast<T>(this))
5179 // If the canonical form of this type isn't the right kind, reject it.
5180 if (!isa<T>(CanonicalType))
5183 // If this is a typedef for the type, strip the typedef off without
5184 // losing all typedef information.
5185 return cast<T>(getUnqualifiedDesugaredType());
5188 inline const ArrayType *Type::getAsArrayTypeUnsafe() const {
5189 // If this is directly an array type, return it.
5190 if (const ArrayType *arr = dyn_cast<ArrayType>(this))
5193 // If the canonical form of this type isn't the right kind, reject it.
5194 if (!isa<ArrayType>(CanonicalType))
5197 // If this is a typedef for the type, strip the typedef off without
5198 // losing all typedef information.
5199 return cast<ArrayType>(getUnqualifiedDesugaredType());
5202 template <typename T> const T *Type::castAs() const {
5203 ArrayType_cannot_be_used_with_getAs<T> at;
5206 assert(isa<T>(CanonicalType));
5207 if (const T *ty = dyn_cast<T>(this)) return ty;
5208 return cast<T>(getUnqualifiedDesugaredType());
5211 inline const ArrayType *Type::castAsArrayTypeUnsafe() const {
5212 assert(isa<ArrayType>(CanonicalType));
5213 if (const ArrayType *arr = dyn_cast<ArrayType>(this)) return arr;
5214 return cast<ArrayType>(getUnqualifiedDesugaredType());
5217 } // end namespace clang