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/AddressSpaces.h"
20 #include "clang/Basic/Diagnostic.h"
21 #include "clang/Basic/ExceptionSpecificationType.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/APInt.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/ADT/iterator_range.h"
34 #include "llvm/Support/ErrorHandling.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 Returns true if this address space is a superset of the other one.
405 /// OpenCL v2.0 defines conversion rules (OpenCLC v2.0 s6.5.5) and notion of
406 /// overlapping address spaces.
408 /// every address space is a superset of itself.
410 /// __generic is a superset of any address space except for __constant.
411 bool isAddressSpaceSupersetOf(Qualifiers other) const {
413 // Address spaces must match exactly.
414 getAddressSpace() == other.getAddressSpace() ||
415 // Otherwise in OpenCLC v2.0 s6.5.5: every address space except
416 // for __constant can be used as __generic.
417 (getAddressSpace() == LangAS::opencl_generic &&
418 other.getAddressSpace() != LangAS::opencl_constant);
421 /// \brief Determines if these qualifiers compatibly include another set.
422 /// Generally this answers the question of whether an object with the other
423 /// qualifiers can be safely used as an object with these qualifiers.
424 bool compatiblyIncludes(Qualifiers other) const {
425 return isAddressSpaceSupersetOf(other) &&
426 // ObjC GC qualifiers can match, be added, or be removed, but can't
428 (getObjCGCAttr() == other.getObjCGCAttr() || !hasObjCGCAttr() ||
429 !other.hasObjCGCAttr()) &&
430 // ObjC lifetime qualifiers must match exactly.
431 getObjCLifetime() == other.getObjCLifetime() &&
432 // CVR qualifiers may subset.
433 (((Mask & CVRMask) | (other.Mask & CVRMask)) == (Mask & CVRMask));
436 /// \brief Determines if these qualifiers compatibly include another set of
437 /// qualifiers from the narrow perspective of Objective-C ARC lifetime.
439 /// One set of Objective-C lifetime qualifiers compatibly includes the other
440 /// if the lifetime qualifiers match, or if both are non-__weak and the
441 /// including set also contains the 'const' qualifier.
442 bool compatiblyIncludesObjCLifetime(Qualifiers other) const {
443 if (getObjCLifetime() == other.getObjCLifetime())
446 if (getObjCLifetime() == OCL_Weak || other.getObjCLifetime() == OCL_Weak)
452 /// \brief Determine whether this set of qualifiers is a strict superset of
453 /// another set of qualifiers, not considering qualifier compatibility.
454 bool isStrictSupersetOf(Qualifiers Other) const;
456 bool operator==(Qualifiers Other) const { return Mask == Other.Mask; }
457 bool operator!=(Qualifiers Other) const { return Mask != Other.Mask; }
459 explicit operator bool() const { return hasQualifiers(); }
461 Qualifiers &operator+=(Qualifiers R) {
466 // Union two qualifier sets. If an enumerated qualifier appears
467 // in both sets, use the one from the right.
468 friend Qualifiers operator+(Qualifiers L, Qualifiers R) {
473 Qualifiers &operator-=(Qualifiers R) {
478 /// \brief Compute the difference between two qualifier sets.
479 friend Qualifiers operator-(Qualifiers L, Qualifiers R) {
484 std::string getAsString() const;
485 std::string getAsString(const PrintingPolicy &Policy) const;
487 bool isEmptyWhenPrinted(const PrintingPolicy &Policy) const;
488 void print(raw_ostream &OS, const PrintingPolicy &Policy,
489 bool appendSpaceIfNonEmpty = false) const;
491 void Profile(llvm::FoldingSetNodeID &ID) const {
497 // bits: |0 1 2|3 .. 4|5 .. 7|8 ... 31|
498 // |C R V|GCAttr|Lifetime|AddressSpace|
501 static const uint32_t GCAttrMask = 0x18;
502 static const uint32_t GCAttrShift = 3;
503 static const uint32_t LifetimeMask = 0xE0;
504 static const uint32_t LifetimeShift = 5;
505 static const uint32_t AddressSpaceMask = ~(CVRMask|GCAttrMask|LifetimeMask);
506 static const uint32_t AddressSpaceShift = 8;
509 /// A std::pair-like structure for storing a qualified type split
510 /// into its local qualifiers and its locally-unqualified type.
511 struct SplitQualType {
512 /// The locally-unqualified type.
515 /// The local qualifiers.
518 SplitQualType() : Ty(nullptr), Quals() {}
519 SplitQualType(const Type *ty, Qualifiers qs) : Ty(ty), Quals(qs) {}
521 SplitQualType getSingleStepDesugaredType() const; // end of this file
523 // Make std::tie work.
524 std::pair<const Type *,Qualifiers> asPair() const {
525 return std::pair<const Type *, Qualifiers>(Ty, Quals);
528 friend bool operator==(SplitQualType a, SplitQualType b) {
529 return a.Ty == b.Ty && a.Quals == b.Quals;
531 friend bool operator!=(SplitQualType a, SplitQualType b) {
532 return a.Ty != b.Ty || a.Quals != b.Quals;
536 /// QualType - For efficiency, we don't store CV-qualified types as nodes on
537 /// their own: instead each reference to a type stores the qualifiers. This
538 /// greatly reduces the number of nodes we need to allocate for types (for
539 /// example we only need one for 'int', 'const int', 'volatile int',
540 /// 'const volatile int', etc).
542 /// As an added efficiency bonus, instead of making this a pair, we
543 /// just store the two bits we care about in the low bits of the
544 /// pointer. To handle the packing/unpacking, we make QualType be a
545 /// simple wrapper class that acts like a smart pointer. A third bit
546 /// indicates whether there are extended qualifiers present, in which
547 /// case the pointer points to a special structure.
549 // Thankfully, these are efficiently composable.
550 llvm::PointerIntPair<llvm::PointerUnion<const Type*,const ExtQuals*>,
551 Qualifiers::FastWidth> Value;
553 const ExtQuals *getExtQualsUnsafe() const {
554 return Value.getPointer().get<const ExtQuals*>();
557 const Type *getTypePtrUnsafe() const {
558 return Value.getPointer().get<const Type*>();
561 const ExtQualsTypeCommonBase *getCommonPtr() const {
562 assert(!isNull() && "Cannot retrieve a NULL type pointer");
563 uintptr_t CommonPtrVal
564 = reinterpret_cast<uintptr_t>(Value.getOpaqueValue());
565 CommonPtrVal &= ~(uintptr_t)((1 << TypeAlignmentInBits) - 1);
566 return reinterpret_cast<ExtQualsTypeCommonBase*>(CommonPtrVal);
569 friend class QualifierCollector;
573 QualType(const Type *Ptr, unsigned Quals)
574 : Value(Ptr, Quals) {}
575 QualType(const ExtQuals *Ptr, unsigned Quals)
576 : Value(Ptr, Quals) {}
578 unsigned getLocalFastQualifiers() const { return Value.getInt(); }
579 void setLocalFastQualifiers(unsigned Quals) { Value.setInt(Quals); }
581 /// Retrieves a pointer to the underlying (unqualified) type.
583 /// This function requires that the type not be NULL. If the type might be
584 /// NULL, use the (slightly less efficient) \c getTypePtrOrNull().
585 const Type *getTypePtr() const;
587 const Type *getTypePtrOrNull() const;
589 /// Retrieves a pointer to the name of the base type.
590 const IdentifierInfo *getBaseTypeIdentifier() const;
592 /// Divides a QualType into its unqualified type and a set of local
594 SplitQualType split() const;
596 void *getAsOpaquePtr() const { return Value.getOpaqueValue(); }
597 static QualType getFromOpaquePtr(const void *Ptr) {
599 T.Value.setFromOpaqueValue(const_cast<void*>(Ptr));
603 const Type &operator*() const {
604 return *getTypePtr();
607 const Type *operator->() const {
611 bool isCanonical() const;
612 bool isCanonicalAsParam() const;
614 /// isNull - Return true if this QualType doesn't point to a type yet.
615 bool isNull() const {
616 return Value.getPointer().isNull();
619 /// \brief Determine whether this particular QualType instance has the
620 /// "const" qualifier set, without looking through typedefs that may have
621 /// added "const" at a different level.
622 bool isLocalConstQualified() const {
623 return (getLocalFastQualifiers() & Qualifiers::Const);
626 /// \brief Determine whether this type is const-qualified.
627 bool isConstQualified() const;
629 /// \brief Determine whether this particular QualType instance has the
630 /// "restrict" qualifier set, without looking through typedefs that may have
631 /// added "restrict" at a different level.
632 bool isLocalRestrictQualified() const {
633 return (getLocalFastQualifiers() & Qualifiers::Restrict);
636 /// \brief Determine whether this type is restrict-qualified.
637 bool isRestrictQualified() const;
639 /// \brief Determine whether this particular QualType instance has the
640 /// "volatile" qualifier set, without looking through typedefs that may have
641 /// added "volatile" at a different level.
642 bool isLocalVolatileQualified() const {
643 return (getLocalFastQualifiers() & Qualifiers::Volatile);
646 /// \brief Determine whether this type is volatile-qualified.
647 bool isVolatileQualified() const;
649 /// \brief Determine whether this particular QualType instance has any
650 /// qualifiers, without looking through any typedefs that might add
651 /// qualifiers at a different level.
652 bool hasLocalQualifiers() const {
653 return getLocalFastQualifiers() || hasLocalNonFastQualifiers();
656 /// \brief Determine whether this type has any qualifiers.
657 bool hasQualifiers() const;
659 /// \brief Determine whether this particular QualType instance has any
660 /// "non-fast" qualifiers, e.g., those that are stored in an ExtQualType
662 bool hasLocalNonFastQualifiers() const {
663 return Value.getPointer().is<const ExtQuals*>();
666 /// \brief Retrieve the set of qualifiers local to this particular QualType
667 /// instance, not including any qualifiers acquired through typedefs or
669 Qualifiers getLocalQualifiers() const;
671 /// \brief Retrieve the set of qualifiers applied to this type.
672 Qualifiers getQualifiers() const;
674 /// \brief Retrieve the set of CVR (const-volatile-restrict) qualifiers
675 /// local to this particular QualType instance, not including any qualifiers
676 /// acquired through typedefs or other sugar.
677 unsigned getLocalCVRQualifiers() const {
678 return getLocalFastQualifiers();
681 /// \brief Retrieve the set of CVR (const-volatile-restrict) qualifiers
682 /// applied to this type.
683 unsigned getCVRQualifiers() const;
685 bool isConstant(ASTContext& Ctx) const {
686 return QualType::isConstant(*this, Ctx);
689 /// \brief Determine whether this is a Plain Old Data (POD) type (C++ 3.9p10).
690 bool isPODType(ASTContext &Context) const;
692 /// isCXX98PODType() - Return true if this is a POD type according to the
693 /// rules of the C++98 standard, regardless of the current compilation's
695 bool isCXX98PODType(ASTContext &Context) const;
697 /// isCXX11PODType() - Return true if this is a POD type according to the
698 /// more relaxed rules of the C++11 standard, regardless of the current
699 /// compilation's language.
700 /// (C++0x [basic.types]p9)
701 bool isCXX11PODType(ASTContext &Context) const;
703 /// isTrivialType - Return true if this is a trivial type
704 /// (C++0x [basic.types]p9)
705 bool isTrivialType(ASTContext &Context) const;
707 /// isTriviallyCopyableType - Return true if this is a trivially
708 /// copyable type (C++0x [basic.types]p9)
709 bool isTriviallyCopyableType(ASTContext &Context) const;
711 // Don't promise in the API that anything besides 'const' can be
714 /// addConst - add the specified type qualifier to this QualType.
716 addFastQualifiers(Qualifiers::Const);
718 QualType withConst() const {
719 return withFastQualifiers(Qualifiers::Const);
722 /// addVolatile - add the specified type qualifier to this QualType.
724 addFastQualifiers(Qualifiers::Volatile);
726 QualType withVolatile() const {
727 return withFastQualifiers(Qualifiers::Volatile);
730 /// Add the restrict qualifier to this QualType.
732 addFastQualifiers(Qualifiers::Restrict);
734 QualType withRestrict() const {
735 return withFastQualifiers(Qualifiers::Restrict);
738 QualType withCVRQualifiers(unsigned CVR) const {
739 return withFastQualifiers(CVR);
742 void addFastQualifiers(unsigned TQs) {
743 assert(!(TQs & ~Qualifiers::FastMask)
744 && "non-fast qualifier bits set in mask!");
745 Value.setInt(Value.getInt() | TQs);
748 void removeLocalConst();
749 void removeLocalVolatile();
750 void removeLocalRestrict();
751 void removeLocalCVRQualifiers(unsigned Mask);
753 void removeLocalFastQualifiers() { Value.setInt(0); }
754 void removeLocalFastQualifiers(unsigned Mask) {
755 assert(!(Mask & ~Qualifiers::FastMask) && "mask has non-fast qualifiers");
756 Value.setInt(Value.getInt() & ~Mask);
759 // Creates a type with the given qualifiers in addition to any
760 // qualifiers already on this type.
761 QualType withFastQualifiers(unsigned TQs) const {
763 T.addFastQualifiers(TQs);
767 // Creates a type with exactly the given fast qualifiers, removing
768 // any existing fast qualifiers.
769 QualType withExactLocalFastQualifiers(unsigned TQs) const {
770 return withoutLocalFastQualifiers().withFastQualifiers(TQs);
773 // Removes fast qualifiers, but leaves any extended qualifiers in place.
774 QualType withoutLocalFastQualifiers() const {
776 T.removeLocalFastQualifiers();
780 QualType getCanonicalType() const;
782 /// \brief Return this type with all of the instance-specific qualifiers
783 /// removed, but without removing any qualifiers that may have been applied
784 /// through typedefs.
785 QualType getLocalUnqualifiedType() const { return QualType(getTypePtr(), 0); }
787 /// \brief Retrieve the unqualified variant of the given type,
788 /// removing as little sugar as possible.
790 /// This routine looks through various kinds of sugar to find the
791 /// least-desugared type that is unqualified. For example, given:
794 /// typedef int Integer;
795 /// typedef const Integer CInteger;
796 /// typedef CInteger DifferenceType;
799 /// Executing \c getUnqualifiedType() on the type \c DifferenceType will
800 /// desugar until we hit the type \c Integer, which has no qualifiers on it.
802 /// The resulting type might still be qualified if it's sugar for an array
803 /// type. To strip qualifiers even from within a sugared array type, use
804 /// ASTContext::getUnqualifiedArrayType.
805 inline QualType getUnqualifiedType() const;
807 /// getSplitUnqualifiedType - Retrieve the unqualified variant of the
808 /// given type, removing as little sugar as possible.
810 /// Like getUnqualifiedType(), but also returns the set of
811 /// qualifiers that were built up.
813 /// The resulting type might still be qualified if it's sugar for an array
814 /// type. To strip qualifiers even from within a sugared array type, use
815 /// ASTContext::getUnqualifiedArrayType.
816 inline SplitQualType getSplitUnqualifiedType() const;
818 /// \brief Determine whether this type is more qualified than the other
819 /// given type, requiring exact equality for non-CVR qualifiers.
820 bool isMoreQualifiedThan(QualType Other) const;
822 /// \brief Determine whether this type is at least as qualified as the other
823 /// given type, requiring exact equality for non-CVR qualifiers.
824 bool isAtLeastAsQualifiedAs(QualType Other) const;
826 QualType getNonReferenceType() const;
828 /// \brief Determine the type of a (typically non-lvalue) expression with the
829 /// specified result type.
831 /// This routine should be used for expressions for which the return type is
832 /// explicitly specified (e.g., in a cast or call) and isn't necessarily
833 /// an lvalue. It removes a top-level reference (since there are no
834 /// expressions of reference type) and deletes top-level cvr-qualifiers
835 /// from non-class types (in C++) or all types (in C).
836 QualType getNonLValueExprType(const ASTContext &Context) const;
838 /// getDesugaredType - Return the specified type with any "sugar" removed from
839 /// the type. This takes off typedefs, typeof's etc. If the outer level of
840 /// the type is already concrete, it returns it unmodified. This is similar
841 /// to getting the canonical type, but it doesn't remove *all* typedefs. For
842 /// example, it returns "T*" as "T*", (not as "int*"), because the pointer is
845 /// Qualifiers are left in place.
846 QualType getDesugaredType(const ASTContext &Context) const {
847 return getDesugaredType(*this, Context);
850 SplitQualType getSplitDesugaredType() const {
851 return getSplitDesugaredType(*this);
854 /// \brief Return the specified type with one level of "sugar" removed from
857 /// This routine takes off the first typedef, typeof, etc. If the outer level
858 /// of the type is already concrete, it returns it unmodified.
859 QualType getSingleStepDesugaredType(const ASTContext &Context) const {
860 return getSingleStepDesugaredTypeImpl(*this, Context);
863 /// IgnoreParens - Returns the specified type after dropping any
864 /// outer-level parentheses.
865 QualType IgnoreParens() const {
866 if (isa<ParenType>(*this))
867 return QualType::IgnoreParens(*this);
871 /// operator==/!= - Indicate whether the specified types and qualifiers are
873 friend bool operator==(const QualType &LHS, const QualType &RHS) {
874 return LHS.Value == RHS.Value;
876 friend bool operator!=(const QualType &LHS, const QualType &RHS) {
877 return LHS.Value != RHS.Value;
879 std::string getAsString() const {
880 return getAsString(split());
882 static std::string getAsString(SplitQualType split) {
883 return getAsString(split.Ty, split.Quals);
885 static std::string getAsString(const Type *ty, Qualifiers qs);
887 std::string getAsString(const PrintingPolicy &Policy) const;
889 void print(raw_ostream &OS, const PrintingPolicy &Policy,
890 const Twine &PlaceHolder = Twine()) const {
891 print(split(), OS, Policy, PlaceHolder);
893 static void print(SplitQualType split, raw_ostream &OS,
894 const PrintingPolicy &policy, const Twine &PlaceHolder) {
895 return print(split.Ty, split.Quals, OS, policy, PlaceHolder);
897 static void print(const Type *ty, Qualifiers qs,
898 raw_ostream &OS, const PrintingPolicy &policy,
899 const Twine &PlaceHolder);
901 void getAsStringInternal(std::string &Str,
902 const PrintingPolicy &Policy) const {
903 return getAsStringInternal(split(), Str, Policy);
905 static void getAsStringInternal(SplitQualType split, std::string &out,
906 const PrintingPolicy &policy) {
907 return getAsStringInternal(split.Ty, split.Quals, out, policy);
909 static void getAsStringInternal(const Type *ty, Qualifiers qs,
911 const PrintingPolicy &policy);
913 class StreamedQualTypeHelper {
915 const PrintingPolicy &Policy;
916 const Twine &PlaceHolder;
918 StreamedQualTypeHelper(const QualType &T, const PrintingPolicy &Policy,
919 const Twine &PlaceHolder)
920 : T(T), Policy(Policy), PlaceHolder(PlaceHolder) { }
922 friend raw_ostream &operator<<(raw_ostream &OS,
923 const StreamedQualTypeHelper &SQT) {
924 SQT.T.print(OS, SQT.Policy, SQT.PlaceHolder);
929 StreamedQualTypeHelper stream(const PrintingPolicy &Policy,
930 const Twine &PlaceHolder = Twine()) const {
931 return StreamedQualTypeHelper(*this, Policy, PlaceHolder);
934 void dump(const char *s) const;
937 void Profile(llvm::FoldingSetNodeID &ID) const {
938 ID.AddPointer(getAsOpaquePtr());
941 /// getAddressSpace - Return the address space of this type.
942 inline unsigned getAddressSpace() const;
944 /// getObjCGCAttr - Returns gc attribute of this type.
945 inline Qualifiers::GC getObjCGCAttr() const;
947 /// isObjCGCWeak true when Type is objc's weak.
948 bool isObjCGCWeak() const {
949 return getObjCGCAttr() == Qualifiers::Weak;
952 /// isObjCGCStrong true when Type is objc's strong.
953 bool isObjCGCStrong() const {
954 return getObjCGCAttr() == Qualifiers::Strong;
957 /// getObjCLifetime - Returns lifetime attribute of this type.
958 Qualifiers::ObjCLifetime getObjCLifetime() const {
959 return getQualifiers().getObjCLifetime();
962 bool hasNonTrivialObjCLifetime() const {
963 return getQualifiers().hasNonTrivialObjCLifetime();
966 bool hasStrongOrWeakObjCLifetime() const {
967 return getQualifiers().hasStrongOrWeakObjCLifetime();
970 enum DestructionKind {
973 DK_objc_strong_lifetime,
974 DK_objc_weak_lifetime
977 /// isDestructedType - nonzero if objects of this type require
978 /// non-trivial work to clean up after. Non-zero because it's
979 /// conceivable that qualifiers (objc_gc(weak)?) could make
980 /// something require destruction.
981 DestructionKind isDestructedType() const {
982 return isDestructedTypeImpl(*this);
985 /// \brief Determine whether expressions of the given type are forbidden
986 /// from being lvalues in C.
988 /// The expression types that are forbidden to be lvalues are:
989 /// - 'void', but not qualified void
992 /// The exact rule here is C99 6.3.2.1:
993 /// An lvalue is an expression with an object type or an incomplete
994 /// type other than void.
995 bool isCForbiddenLValueType() const;
998 // These methods are implemented in a separate translation unit;
999 // "static"-ize them to avoid creating temporary QualTypes in the
1001 static bool isConstant(QualType T, ASTContext& Ctx);
1002 static QualType getDesugaredType(QualType T, const ASTContext &Context);
1003 static SplitQualType getSplitDesugaredType(QualType T);
1004 static SplitQualType getSplitUnqualifiedTypeImpl(QualType type);
1005 static QualType getSingleStepDesugaredTypeImpl(QualType type,
1006 const ASTContext &C);
1007 static QualType IgnoreParens(QualType T);
1008 static DestructionKind isDestructedTypeImpl(QualType type);
1014 /// Implement simplify_type for QualType, so that we can dyn_cast from QualType
1015 /// to a specific Type class.
1016 template<> struct simplify_type< ::clang::QualType> {
1017 typedef const ::clang::Type *SimpleType;
1018 static SimpleType getSimplifiedValue(::clang::QualType Val) {
1019 return Val.getTypePtr();
1023 // Teach SmallPtrSet that QualType is "basically a pointer".
1025 class PointerLikeTypeTraits<clang::QualType> {
1027 static inline void *getAsVoidPointer(clang::QualType P) {
1028 return P.getAsOpaquePtr();
1030 static inline clang::QualType getFromVoidPointer(void *P) {
1031 return clang::QualType::getFromOpaquePtr(P);
1033 // Various qualifiers go in low bits.
1034 enum { NumLowBitsAvailable = 0 };
1037 } // end namespace llvm
1041 /// \brief Base class that is common to both the \c ExtQuals and \c Type
1042 /// classes, which allows \c QualType to access the common fields between the
1045 class ExtQualsTypeCommonBase {
1046 ExtQualsTypeCommonBase(const Type *baseType, QualType canon)
1047 : BaseType(baseType), CanonicalType(canon) {}
1049 /// \brief The "base" type of an extended qualifiers type (\c ExtQuals) or
1050 /// a self-referential pointer (for \c Type).
1052 /// This pointer allows an efficient mapping from a QualType to its
1053 /// underlying type pointer.
1054 const Type *const BaseType;
1056 /// \brief The canonical type of this type. A QualType.
1057 QualType CanonicalType;
1059 friend class QualType;
1061 friend class ExtQuals;
1064 /// ExtQuals - We can encode up to four bits in the low bits of a
1065 /// type pointer, but there are many more type qualifiers that we want
1066 /// to be able to apply to an arbitrary type. Therefore we have this
1067 /// struct, intended to be heap-allocated and used by QualType to
1068 /// store qualifiers.
1070 /// The current design tags the 'const', 'restrict', and 'volatile' qualifiers
1071 /// in three low bits on the QualType pointer; a fourth bit records whether
1072 /// the pointer is an ExtQuals node. The extended qualifiers (address spaces,
1073 /// Objective-C GC attributes) are much more rare.
1074 class ExtQuals : public ExtQualsTypeCommonBase, public llvm::FoldingSetNode {
1075 // NOTE: changing the fast qualifiers should be straightforward as
1076 // long as you don't make 'const' non-fast.
1078 // a) Modify the bitmasks (Qualifiers::TQ and DeclSpec::TQ).
1079 // Fast qualifiers must occupy the low-order bits.
1080 // b) Update Qualifiers::FastWidth and FastMask.
1082 // a) Update is{Volatile,Restrict}Qualified(), defined inline.
1083 // b) Update remove{Volatile,Restrict}, defined near the end of
1086 // a) Update get{Volatile,Restrict}Type.
1088 /// Quals - the immutable set of qualifiers applied by this
1089 /// node; always contains extended qualifiers.
1092 ExtQuals *this_() { return this; }
1095 ExtQuals(const Type *baseType, QualType canon, Qualifiers quals)
1096 : ExtQualsTypeCommonBase(baseType,
1097 canon.isNull() ? QualType(this_(), 0) : canon),
1100 assert(Quals.hasNonFastQualifiers()
1101 && "ExtQuals created with no fast qualifiers");
1102 assert(!Quals.hasFastQualifiers()
1103 && "ExtQuals created with fast qualifiers");
1106 Qualifiers getQualifiers() const { return Quals; }
1108 bool hasObjCGCAttr() const { return Quals.hasObjCGCAttr(); }
1109 Qualifiers::GC getObjCGCAttr() const { return Quals.getObjCGCAttr(); }
1111 bool hasObjCLifetime() const { return Quals.hasObjCLifetime(); }
1112 Qualifiers::ObjCLifetime getObjCLifetime() const {
1113 return Quals.getObjCLifetime();
1116 bool hasAddressSpace() const { return Quals.hasAddressSpace(); }
1117 unsigned getAddressSpace() const { return Quals.getAddressSpace(); }
1119 const Type *getBaseType() const { return BaseType; }
1122 void Profile(llvm::FoldingSetNodeID &ID) const {
1123 Profile(ID, getBaseType(), Quals);
1125 static void Profile(llvm::FoldingSetNodeID &ID,
1126 const Type *BaseType,
1128 assert(!Quals.hasFastQualifiers() && "fast qualifiers in ExtQuals hash!");
1129 ID.AddPointer(BaseType);
1134 /// \brief The kind of C++0x ref-qualifier associated with a function type,
1135 /// which determines whether a member function's "this" object can be an
1136 /// lvalue, rvalue, or neither.
1137 enum RefQualifierKind {
1138 /// \brief No ref-qualifier was provided.
1140 /// \brief An lvalue ref-qualifier was provided (\c &).
1142 /// \brief An rvalue ref-qualifier was provided (\c &&).
1146 /// Type - This is the base class of the type hierarchy. A central concept
1147 /// with types is that each type always has a canonical type. A canonical type
1148 /// is the type with any typedef names stripped out of it or the types it
1149 /// references. For example, consider:
1151 /// typedef int foo;
1152 /// typedef foo* bar;
1153 /// 'int *' 'foo *' 'bar'
1155 /// There will be a Type object created for 'int'. Since int is canonical, its
1156 /// canonicaltype pointer points to itself. There is also a Type for 'foo' (a
1157 /// TypedefType). Its CanonicalType pointer points to the 'int' Type. Next
1158 /// there is a PointerType that represents 'int*', which, like 'int', is
1159 /// canonical. Finally, there is a PointerType type for 'foo*' whose canonical
1160 /// type is 'int*', and there is a TypedefType for 'bar', whose canonical type
1163 /// Non-canonical types are useful for emitting diagnostics, without losing
1164 /// information about typedefs being used. Canonical types are useful for type
1165 /// comparisons (they allow by-pointer equality tests) and useful for reasoning
1166 /// about whether something has a particular form (e.g. is a function type),
1167 /// because they implicitly, recursively, strip all typedefs out of a type.
1169 /// Types, once created, are immutable.
1171 class Type : public ExtQualsTypeCommonBase {
1174 #define TYPE(Class, Base) Class,
1175 #define LAST_TYPE(Class) TypeLast = Class,
1176 #define ABSTRACT_TYPE(Class, Base)
1177 #include "clang/AST/TypeNodes.def"
1178 TagFirst = Record, TagLast = Enum
1182 Type(const Type &) = delete;
1183 void operator=(const Type &) = delete;
1185 /// Bitfields required by the Type class.
1186 class TypeBitfields {
1188 template <class T> friend class TypePropertyCache;
1190 /// TypeClass bitfield - Enum that specifies what subclass this belongs to.
1193 /// Dependent - Whether this type is a dependent type (C++ [temp.dep.type]).
1194 unsigned Dependent : 1;
1196 /// \brief Whether this type somehow involves a template parameter, even
1197 /// if the resolution of the type does not depend on a template parameter.
1198 unsigned InstantiationDependent : 1;
1200 /// \brief Whether this type is a variably-modified type (C99 6.7.5).
1201 unsigned VariablyModified : 1;
1203 /// \brief Whether this type contains an unexpanded parameter pack
1204 /// (for C++0x variadic templates).
1205 unsigned ContainsUnexpandedParameterPack : 1;
1207 /// \brief True if the cache (i.e. the bitfields here starting with
1208 /// 'Cache') is valid.
1209 mutable unsigned CacheValid : 1;
1211 /// \brief Linkage of this type.
1212 mutable unsigned CachedLinkage : 3;
1214 /// \brief Whether this type involves and local or unnamed types.
1215 mutable unsigned CachedLocalOrUnnamed : 1;
1217 /// \brief FromAST - Whether this type comes from an AST file.
1218 mutable unsigned FromAST : 1;
1220 bool isCacheValid() const {
1223 Linkage getLinkage() const {
1224 assert(isCacheValid() && "getting linkage from invalid cache");
1225 return static_cast<Linkage>(CachedLinkage);
1227 bool hasLocalOrUnnamedType() const {
1228 assert(isCacheValid() && "getting linkage from invalid cache");
1229 return CachedLocalOrUnnamed;
1232 enum { NumTypeBits = 18 };
1235 // These classes allow subclasses to somewhat cleanly pack bitfields
1238 class ArrayTypeBitfields {
1239 friend class ArrayType;
1241 unsigned : NumTypeBits;
1243 /// IndexTypeQuals - CVR qualifiers from declarations like
1244 /// 'int X[static restrict 4]'. For function parameters only.
1245 unsigned IndexTypeQuals : 3;
1247 /// SizeModifier - storage class qualifiers from declarations like
1248 /// 'int X[static restrict 4]'. For function parameters only.
1249 /// Actually an ArrayType::ArraySizeModifier.
1250 unsigned SizeModifier : 3;
1253 class BuiltinTypeBitfields {
1254 friend class BuiltinType;
1256 unsigned : NumTypeBits;
1258 /// The kind (BuiltinType::Kind) of builtin type this is.
1262 class FunctionTypeBitfields {
1263 friend class FunctionType;
1264 friend class FunctionProtoType;
1266 unsigned : NumTypeBits;
1268 /// Extra information which affects how the function is called, like
1269 /// regparm and the calling convention.
1270 unsigned ExtInfo : 9;
1272 /// TypeQuals - Used only by FunctionProtoType, put here to pack with the
1273 /// other bitfields.
1274 /// The qualifiers are part of FunctionProtoType because...
1276 /// C++ 8.3.5p4: The return type, the parameter type list and the
1277 /// cv-qualifier-seq, [...], are part of the function type.
1278 unsigned TypeQuals : 3;
1280 /// \brief The ref-qualifier associated with a \c FunctionProtoType.
1282 /// This is a value of type \c RefQualifierKind.
1283 unsigned RefQualifier : 2;
1286 class ObjCObjectTypeBitfields {
1287 friend class ObjCObjectType;
1289 unsigned : NumTypeBits;
1291 /// NumProtocols - The number of protocols stored directly on this
1293 unsigned NumProtocols : 32 - NumTypeBits;
1296 class ReferenceTypeBitfields {
1297 friend class ReferenceType;
1299 unsigned : NumTypeBits;
1301 /// True if the type was originally spelled with an lvalue sigil.
1302 /// This is never true of rvalue references but can also be false
1303 /// on lvalue references because of C++0x [dcl.typedef]p9,
1306 /// typedef int &ref; // lvalue, spelled lvalue
1307 /// typedef int &&rvref; // rvalue
1308 /// ref &a; // lvalue, inner ref, spelled lvalue
1309 /// ref &&a; // lvalue, inner ref
1310 /// rvref &a; // lvalue, inner ref, spelled lvalue
1311 /// rvref &&a; // rvalue, inner ref
1312 unsigned SpelledAsLValue : 1;
1314 /// True if the inner type is a reference type. This only happens
1315 /// in non-canonical forms.
1316 unsigned InnerRef : 1;
1319 class TypeWithKeywordBitfields {
1320 friend class TypeWithKeyword;
1322 unsigned : NumTypeBits;
1324 /// An ElaboratedTypeKeyword. 8 bits for efficient access.
1325 unsigned Keyword : 8;
1328 class VectorTypeBitfields {
1329 friend class VectorType;
1331 unsigned : NumTypeBits;
1333 /// VecKind - The kind of vector, either a generic vector type or some
1334 /// target-specific vector type such as for AltiVec or Neon.
1335 unsigned VecKind : 3;
1337 /// NumElements - The number of elements in the vector.
1338 unsigned NumElements : 29 - NumTypeBits;
1340 enum { MaxNumElements = (1 << (29 - NumTypeBits)) - 1 };
1343 class AttributedTypeBitfields {
1344 friend class AttributedType;
1346 unsigned : NumTypeBits;
1348 /// AttrKind - an AttributedType::Kind
1349 unsigned AttrKind : 32 - NumTypeBits;
1352 class AutoTypeBitfields {
1353 friend class AutoType;
1355 unsigned : NumTypeBits;
1357 /// Was this placeholder type spelled as 'decltype(auto)'?
1358 unsigned IsDecltypeAuto : 1;
1362 TypeBitfields TypeBits;
1363 ArrayTypeBitfields ArrayTypeBits;
1364 AttributedTypeBitfields AttributedTypeBits;
1365 AutoTypeBitfields AutoTypeBits;
1366 BuiltinTypeBitfields BuiltinTypeBits;
1367 FunctionTypeBitfields FunctionTypeBits;
1368 ObjCObjectTypeBitfields ObjCObjectTypeBits;
1369 ReferenceTypeBitfields ReferenceTypeBits;
1370 TypeWithKeywordBitfields TypeWithKeywordBits;
1371 VectorTypeBitfields VectorTypeBits;
1375 /// \brief Set whether this type comes from an AST file.
1376 void setFromAST(bool V = true) const {
1377 TypeBits.FromAST = V;
1380 template <class T> friend class TypePropertyCache;
1383 // silence VC++ warning C4355: 'this' : used in base member initializer list
1384 Type *this_() { return this; }
1385 Type(TypeClass tc, QualType canon, bool Dependent,
1386 bool InstantiationDependent, bool VariablyModified,
1387 bool ContainsUnexpandedParameterPack)
1388 : ExtQualsTypeCommonBase(this,
1389 canon.isNull() ? QualType(this_(), 0) : canon) {
1391 TypeBits.Dependent = Dependent;
1392 TypeBits.InstantiationDependent = Dependent || InstantiationDependent;
1393 TypeBits.VariablyModified = VariablyModified;
1394 TypeBits.ContainsUnexpandedParameterPack = ContainsUnexpandedParameterPack;
1395 TypeBits.CacheValid = false;
1396 TypeBits.CachedLocalOrUnnamed = false;
1397 TypeBits.CachedLinkage = NoLinkage;
1398 TypeBits.FromAST = false;
1400 friend class ASTContext;
1402 void setDependent(bool D = true) {
1403 TypeBits.Dependent = D;
1405 TypeBits.InstantiationDependent = true;
1407 void setInstantiationDependent(bool D = true) {
1408 TypeBits.InstantiationDependent = D; }
1409 void setVariablyModified(bool VM = true) { TypeBits.VariablyModified = VM;
1411 void setContainsUnexpandedParameterPack(bool PP = true) {
1412 TypeBits.ContainsUnexpandedParameterPack = PP;
1416 TypeClass getTypeClass() const { return static_cast<TypeClass>(TypeBits.TC); }
1418 /// \brief Whether this type comes from an AST file.
1419 bool isFromAST() const { return TypeBits.FromAST; }
1421 /// \brief Whether this type is or contains an unexpanded parameter
1422 /// pack, used to support C++0x variadic templates.
1424 /// A type that contains a parameter pack shall be expanded by the
1425 /// ellipsis operator at some point. For example, the typedef in the
1426 /// following example contains an unexpanded parameter pack 'T':
1429 /// template<typename ...T>
1431 /// typedef T* pointer_types; // ill-formed; T is a parameter pack.
1435 /// Note that this routine does not specify which
1436 bool containsUnexpandedParameterPack() const {
1437 return TypeBits.ContainsUnexpandedParameterPack;
1440 /// Determines if this type would be canonical if it had no further
1442 bool isCanonicalUnqualified() const {
1443 return CanonicalType == QualType(this, 0);
1446 /// Pull a single level of sugar off of this locally-unqualified type.
1447 /// Users should generally prefer SplitQualType::getSingleStepDesugaredType()
1448 /// or QualType::getSingleStepDesugaredType(const ASTContext&).
1449 QualType getLocallyUnqualifiedSingleStepDesugaredType() const;
1451 /// Types are partitioned into 3 broad categories (C99 6.2.5p1):
1452 /// object types, function types, and incomplete types.
1454 /// isIncompleteType - Return true if this is an incomplete type.
1455 /// A type that can describe objects, but which lacks information needed to
1456 /// determine its size (e.g. void, or a fwd declared struct). Clients of this
1457 /// routine will need to determine if the size is actually required.
1459 /// \brief Def If non-NULL, and the type refers to some kind of declaration
1460 /// that can be completed (such as a C struct, C++ class, or Objective-C
1461 /// class), will be set to the declaration.
1462 bool isIncompleteType(NamedDecl **Def = nullptr) const;
1464 /// isIncompleteOrObjectType - Return true if this is an incomplete or object
1465 /// type, in other words, not a function type.
1466 bool isIncompleteOrObjectType() const {
1467 return !isFunctionType();
1470 /// \brief Determine whether this type is an object type.
1471 bool isObjectType() const {
1472 // C++ [basic.types]p8:
1473 // An object type is a (possibly cv-qualified) type that is not a
1474 // function type, not a reference type, and not a void type.
1475 return !isReferenceType() && !isFunctionType() && !isVoidType();
1478 /// isLiteralType - Return true if this is a literal type
1479 /// (C++11 [basic.types]p10)
1480 bool isLiteralType(const ASTContext &Ctx) const;
1482 /// \brief Test if this type is a standard-layout type.
1483 /// (C++0x [basic.type]p9)
1484 bool isStandardLayoutType() const;
1486 /// Helper methods to distinguish type categories. All type predicates
1487 /// operate on the canonical type, ignoring typedefs and qualifiers.
1489 /// isBuiltinType - returns true if the type is a builtin type.
1490 bool isBuiltinType() const;
1492 /// isSpecificBuiltinType - Test for a particular builtin type.
1493 bool isSpecificBuiltinType(unsigned K) const;
1495 /// isPlaceholderType - Test for a type which does not represent an
1496 /// actual type-system type but is instead used as a placeholder for
1497 /// various convenient purposes within Clang. All such types are
1499 bool isPlaceholderType() const;
1500 const BuiltinType *getAsPlaceholderType() const;
1502 /// isSpecificPlaceholderType - Test for a specific placeholder type.
1503 bool isSpecificPlaceholderType(unsigned K) const;
1505 /// isNonOverloadPlaceholderType - Test for a placeholder type
1506 /// other than Overload; see BuiltinType::isNonOverloadPlaceholderType.
1507 bool isNonOverloadPlaceholderType() const;
1509 /// isIntegerType() does *not* include complex integers (a GCC extension).
1510 /// isComplexIntegerType() can be used to test for complex integers.
1511 bool isIntegerType() const; // C99 6.2.5p17 (int, char, bool, enum)
1512 bool isEnumeralType() const;
1513 bool isBooleanType() const;
1514 bool isCharType() const;
1515 bool isWideCharType() const;
1516 bool isChar16Type() const;
1517 bool isChar32Type() const;
1518 bool isAnyCharacterType() const;
1519 bool isIntegralType(ASTContext &Ctx) const;
1521 /// \brief Determine whether this type is an integral or enumeration type.
1522 bool isIntegralOrEnumerationType() const;
1523 /// \brief Determine whether this type is an integral or unscoped enumeration
1525 bool isIntegralOrUnscopedEnumerationType() const;
1527 /// Floating point categories.
1528 bool isRealFloatingType() const; // C99 6.2.5p10 (float, double, long double)
1529 /// isComplexType() does *not* include complex integers (a GCC extension).
1530 /// isComplexIntegerType() can be used to test for complex integers.
1531 bool isComplexType() const; // C99 6.2.5p11 (complex)
1532 bool isAnyComplexType() const; // C99 6.2.5p11 (complex) + Complex Int.
1533 bool isFloatingType() const; // C99 6.2.5p11 (real floating + complex)
1534 bool isHalfType() const; // OpenCL 6.1.1.1, NEON (IEEE 754-2008 half)
1535 bool isRealType() const; // C99 6.2.5p17 (real floating + integer)
1536 bool isArithmeticType() const; // C99 6.2.5p18 (integer + floating)
1537 bool isVoidType() const; // C99 6.2.5p19
1538 bool isScalarType() const; // C99 6.2.5p21 (arithmetic + pointers)
1539 bool isAggregateType() const;
1540 bool isFundamentalType() const;
1541 bool isCompoundType() const;
1543 // Type Predicates: Check to see if this type is structurally the specified
1544 // type, ignoring typedefs and qualifiers.
1545 bool isFunctionType() const;
1546 bool isFunctionNoProtoType() const { return getAs<FunctionNoProtoType>(); }
1547 bool isFunctionProtoType() const { return getAs<FunctionProtoType>(); }
1548 bool isPointerType() const;
1549 bool isAnyPointerType() const; // Any C pointer or ObjC object pointer
1550 bool isBlockPointerType() const;
1551 bool isVoidPointerType() const;
1552 bool isReferenceType() const;
1553 bool isLValueReferenceType() const;
1554 bool isRValueReferenceType() const;
1555 bool isFunctionPointerType() const;
1556 bool isMemberPointerType() const;
1557 bool isMemberFunctionPointerType() const;
1558 bool isMemberDataPointerType() const;
1559 bool isArrayType() const;
1560 bool isConstantArrayType() const;
1561 bool isIncompleteArrayType() const;
1562 bool isVariableArrayType() const;
1563 bool isDependentSizedArrayType() const;
1564 bool isRecordType() const;
1565 bool isClassType() const;
1566 bool isStructureType() const;
1567 bool isInterfaceType() const;
1568 bool isStructureOrClassType() const;
1569 bool isUnionType() const;
1570 bool isComplexIntegerType() const; // GCC _Complex integer type.
1571 bool isVectorType() const; // GCC vector type.
1572 bool isExtVectorType() const; // Extended vector type.
1573 bool isObjCObjectPointerType() const; // pointer to ObjC object
1574 bool isObjCRetainableType() const; // ObjC object or block pointer
1575 bool isObjCLifetimeType() const; // (array of)* retainable type
1576 bool isObjCIndirectLifetimeType() const; // (pointer to)* lifetime type
1577 bool isObjCNSObjectType() const; // __attribute__((NSObject))
1578 bool isObjCIndependentClassType() const; // __attribute__((objc_independent_class))
1579 // FIXME: change this to 'raw' interface type, so we can used 'interface' type
1580 // for the common case.
1581 bool isObjCObjectType() const; // NSString or typeof(*(id)0)
1582 bool isObjCQualifiedInterfaceType() const; // NSString<foo>
1583 bool isObjCQualifiedIdType() const; // id<foo>
1584 bool isObjCQualifiedClassType() const; // Class<foo>
1585 bool isObjCObjectOrInterfaceType() const;
1586 bool isObjCIdType() const; // id
1587 bool isObjCClassType() const; // Class
1588 bool isObjCSelType() const; // Class
1589 bool isObjCBuiltinType() const; // 'id' or 'Class'
1590 bool isObjCARCBridgableType() const;
1591 bool isCARCBridgableType() const;
1592 bool isTemplateTypeParmType() const; // C++ template type parameter
1593 bool isNullPtrType() const; // C++0x nullptr_t
1594 bool isAtomicType() const; // C11 _Atomic()
1596 bool isImage1dT() const; // OpenCL image1d_t
1597 bool isImage1dArrayT() const; // OpenCL image1d_array_t
1598 bool isImage1dBufferT() const; // OpenCL image1d_buffer_t
1599 bool isImage2dT() const; // OpenCL image2d_t
1600 bool isImage2dArrayT() const; // OpenCL image2d_array_t
1601 bool isImage3dT() const; // OpenCL image3d_t
1603 bool isImageType() const; // Any OpenCL image type
1605 bool isSamplerT() const; // OpenCL sampler_t
1606 bool isEventT() const; // OpenCL event_t
1608 bool isOpenCLSpecificType() const; // Any OpenCL specific type
1610 /// Determines if this type, which must satisfy
1611 /// isObjCLifetimeType(), is implicitly __unsafe_unretained rather
1612 /// than implicitly __strong.
1613 bool isObjCARCImplicitlyUnretainedType() const;
1615 /// Return the implicit lifetime for this type, which must not be dependent.
1616 Qualifiers::ObjCLifetime getObjCARCImplicitLifetime() const;
1618 enum ScalarTypeKind {
1621 STK_ObjCObjectPointer,
1626 STK_IntegralComplex,
1629 /// getScalarTypeKind - Given that this is a scalar type, classify it.
1630 ScalarTypeKind getScalarTypeKind() const;
1632 /// isDependentType - Whether this type is a dependent type, meaning
1633 /// that its definition somehow depends on a template parameter
1634 /// (C++ [temp.dep.type]).
1635 bool isDependentType() const { return TypeBits.Dependent; }
1637 /// \brief Determine whether this type is an instantiation-dependent type,
1638 /// meaning that the type involves a template parameter (even if the
1639 /// definition does not actually depend on the type substituted for that
1640 /// template parameter).
1641 bool isInstantiationDependentType() const {
1642 return TypeBits.InstantiationDependent;
1645 /// \brief Determine whether this type is an undeduced type, meaning that
1646 /// it somehow involves a C++11 'auto' type which has not yet been deduced.
1647 bool isUndeducedType() const;
1649 /// \brief Whether this type is a variably-modified type (C99 6.7.5).
1650 bool isVariablyModifiedType() const { return TypeBits.VariablyModified; }
1652 /// \brief Whether this type involves a variable-length array type
1653 /// with a definite size.
1654 bool hasSizedVLAType() const;
1656 /// \brief Whether this type is or contains a local or unnamed type.
1657 bool hasUnnamedOrLocalType() const;
1659 bool isOverloadableType() const;
1661 /// \brief Determine wither this type is a C++ elaborated-type-specifier.
1662 bool isElaboratedTypeSpecifier() const;
1664 bool canDecayToPointerType() const;
1666 /// hasPointerRepresentation - Whether this type is represented
1667 /// natively as a pointer; this includes pointers, references, block
1668 /// pointers, and Objective-C interface, qualified id, and qualified
1669 /// interface types, as well as nullptr_t.
1670 bool hasPointerRepresentation() const;
1672 /// hasObjCPointerRepresentation - Whether this type can represent
1673 /// an objective pointer type for the purpose of GC'ability
1674 bool hasObjCPointerRepresentation() const;
1676 /// \brief Determine whether this type has an integer representation
1677 /// of some sort, e.g., it is an integer type or a vector.
1678 bool hasIntegerRepresentation() const;
1680 /// \brief Determine whether this type has an signed integer representation
1681 /// of some sort, e.g., it is an signed integer type or a vector.
1682 bool hasSignedIntegerRepresentation() const;
1684 /// \brief Determine whether this type has an unsigned integer representation
1685 /// of some sort, e.g., it is an unsigned integer type or a vector.
1686 bool hasUnsignedIntegerRepresentation() const;
1688 /// \brief Determine whether this type has a floating-point representation
1689 /// of some sort, e.g., it is a floating-point type or a vector thereof.
1690 bool hasFloatingRepresentation() const;
1692 // Type Checking Functions: Check to see if this type is structurally the
1693 // specified type, ignoring typedefs and qualifiers, and return a pointer to
1694 // the best type we can.
1695 const RecordType *getAsStructureType() const;
1696 /// NOTE: getAs*ArrayType are methods on ASTContext.
1697 const RecordType *getAsUnionType() const;
1698 const ComplexType *getAsComplexIntegerType() const; // GCC complex int type.
1699 // The following is a convenience method that returns an ObjCObjectPointerType
1700 // for object declared using an interface.
1701 const ObjCObjectPointerType *getAsObjCInterfacePointerType() const;
1702 const ObjCObjectPointerType *getAsObjCQualifiedIdType() const;
1703 const ObjCObjectPointerType *getAsObjCQualifiedClassType() const;
1704 const ObjCObjectType *getAsObjCQualifiedInterfaceType() const;
1706 /// \brief Retrieves the CXXRecordDecl that this type refers to, either
1707 /// because the type is a RecordType or because it is the injected-class-name
1708 /// type of a class template or class template partial specialization.
1709 CXXRecordDecl *getAsCXXRecordDecl() const;
1711 /// \brief Retrieves the TagDecl that this type refers to, either
1712 /// because the type is a TagType or because it is the injected-class-name
1713 /// type of a class template or class template partial specialization.
1714 TagDecl *getAsTagDecl() const;
1716 /// If this is a pointer or reference to a RecordType, return the
1717 /// CXXRecordDecl that that type refers to.
1719 /// If this is not a pointer or reference, or the type being pointed to does
1720 /// not refer to a CXXRecordDecl, returns NULL.
1721 const CXXRecordDecl *getPointeeCXXRecordDecl() const;
1723 /// \brief Get the AutoType whose type will be deduced for a variable with
1724 /// an initializer of this type. This looks through declarators like pointer
1725 /// types, but not through decltype or typedefs.
1726 AutoType *getContainedAutoType() const;
1728 /// Member-template getAs<specific type>'. Look through sugar for
1729 /// an instance of \<specific type>. This scheme will eventually
1730 /// replace the specific getAsXXXX methods above.
1732 /// There are some specializations of this member template listed
1733 /// immediately following this class.
1734 template <typename T> const T *getAs() const;
1736 /// A variant of getAs<> for array types which silently discards
1737 /// qualifiers from the outermost type.
1738 const ArrayType *getAsArrayTypeUnsafe() const;
1740 /// Member-template castAs<specific type>. Look through sugar for
1741 /// the underlying instance of \<specific type>.
1743 /// This method has the same relationship to getAs<T> as cast<T> has
1744 /// to dyn_cast<T>; which is to say, the underlying type *must*
1745 /// have the intended type, and this method will never return null.
1746 template <typename T> const T *castAs() const;
1748 /// A variant of castAs<> for array type which silently discards
1749 /// qualifiers from the outermost type.
1750 const ArrayType *castAsArrayTypeUnsafe() const;
1752 /// getBaseElementTypeUnsafe - Get the base element type of this
1753 /// type, potentially discarding type qualifiers. This method
1754 /// should never be used when type qualifiers are meaningful.
1755 const Type *getBaseElementTypeUnsafe() const;
1757 /// getArrayElementTypeNoTypeQual - If this is an array type, return the
1758 /// element type of the array, potentially with type qualifiers missing.
1759 /// This method should never be used when type qualifiers are meaningful.
1760 const Type *getArrayElementTypeNoTypeQual() const;
1762 /// getPointeeType - If this is a pointer, ObjC object pointer, or block
1763 /// pointer, this returns the respective pointee.
1764 QualType getPointeeType() const;
1766 /// getUnqualifiedDesugaredType() - Return the specified type with
1767 /// any "sugar" removed from the type, removing any typedefs,
1768 /// typeofs, etc., as well as any qualifiers.
1769 const Type *getUnqualifiedDesugaredType() const;
1771 /// More type predicates useful for type checking/promotion
1772 bool isPromotableIntegerType() const; // C99 6.3.1.1p2
1774 /// isSignedIntegerType - Return true if this is an integer type that is
1775 /// signed, according to C99 6.2.5p4 [char, signed char, short, int, long..],
1776 /// or an enum decl which has a signed representation.
1777 bool isSignedIntegerType() const;
1779 /// isUnsignedIntegerType - Return true if this is an integer type that is
1780 /// unsigned, according to C99 6.2.5p6 [which returns true for _Bool],
1781 /// or an enum decl which has an unsigned representation.
1782 bool isUnsignedIntegerType() const;
1784 /// Determines whether this is an integer type that is signed or an
1785 /// enumeration types whose underlying type is a signed integer type.
1786 bool isSignedIntegerOrEnumerationType() const;
1788 /// Determines whether this is an integer type that is unsigned or an
1789 /// enumeration types whose underlying type is a unsigned integer type.
1790 bool isUnsignedIntegerOrEnumerationType() const;
1792 /// isConstantSizeType - Return true if this is not a variable sized type,
1793 /// according to the rules of C99 6.7.5p3. It is not legal to call this on
1794 /// incomplete types.
1795 bool isConstantSizeType() const;
1797 /// isSpecifierType - Returns true if this type can be represented by some
1798 /// set of type specifiers.
1799 bool isSpecifierType() const;
1801 /// \brief Determine the linkage of this type.
1802 Linkage getLinkage() const;
1804 /// \brief Determine the visibility of this type.
1805 Visibility getVisibility() const {
1806 return getLinkageAndVisibility().getVisibility();
1809 /// \brief Return true if the visibility was explicitly set is the code.
1810 bool isVisibilityExplicit() const {
1811 return getLinkageAndVisibility().isVisibilityExplicit();
1814 /// \brief Determine the linkage and visibility of this type.
1815 LinkageInfo getLinkageAndVisibility() const;
1817 /// \brief True if the computed linkage is valid. Used for consistency
1818 /// checking. Should always return true.
1819 bool isLinkageValid() const;
1821 const char *getTypeClassName() const;
1823 QualType getCanonicalTypeInternal() const {
1824 return CanonicalType;
1826 CanQualType getCanonicalTypeUnqualified() const; // in CanonicalType.h
1829 friend class ASTReader;
1830 friend class ASTWriter;
1833 /// \brief This will check for a TypedefType by removing any existing sugar
1834 /// until it reaches a TypedefType or a non-sugared type.
1835 template <> const TypedefType *Type::getAs() const;
1837 /// \brief This will check for a TemplateSpecializationType by removing any
1838 /// existing sugar until it reaches a TemplateSpecializationType or a
1839 /// non-sugared type.
1840 template <> const TemplateSpecializationType *Type::getAs() const;
1842 /// \brief This will check for an AttributedType by removing any existing sugar
1843 /// until it reaches an AttributedType or a non-sugared type.
1844 template <> const AttributedType *Type::getAs() const;
1846 // We can do canonical leaf types faster, because we don't have to
1847 // worry about preserving child type decoration.
1848 #define TYPE(Class, Base)
1849 #define LEAF_TYPE(Class) \
1850 template <> inline const Class##Type *Type::getAs() const { \
1851 return dyn_cast<Class##Type>(CanonicalType); \
1853 template <> inline const Class##Type *Type::castAs() const { \
1854 return cast<Class##Type>(CanonicalType); \
1856 #include "clang/AST/TypeNodes.def"
1859 /// BuiltinType - This class is used for builtin types like 'int'. Builtin
1860 /// types are always canonical and have a literal name field.
1861 class BuiltinType : public Type {
1864 #define BUILTIN_TYPE(Id, SingletonId) Id,
1865 #define LAST_BUILTIN_TYPE(Id) LastKind = Id
1866 #include "clang/AST/BuiltinTypes.def"
1871 : Type(Builtin, QualType(), /*Dependent=*/(K == Dependent),
1872 /*InstantiationDependent=*/(K == Dependent),
1873 /*VariablyModified=*/false,
1874 /*Unexpanded paramter pack=*/false) {
1875 BuiltinTypeBits.Kind = K;
1878 Kind getKind() const { return static_cast<Kind>(BuiltinTypeBits.Kind); }
1879 StringRef getName(const PrintingPolicy &Policy) const;
1880 const char *getNameAsCString(const PrintingPolicy &Policy) const {
1881 // The StringRef is null-terminated.
1882 StringRef str = getName(Policy);
1883 assert(!str.empty() && str.data()[str.size()] == '\0');
1887 bool isSugared() const { return false; }
1888 QualType desugar() const { return QualType(this, 0); }
1890 bool isInteger() const {
1891 return getKind() >= Bool && getKind() <= Int128;
1894 bool isSignedInteger() const {
1895 return getKind() >= Char_S && getKind() <= Int128;
1898 bool isUnsignedInteger() const {
1899 return getKind() >= Bool && getKind() <= UInt128;
1902 bool isFloatingPoint() const {
1903 return getKind() >= Half && getKind() <= LongDouble;
1906 /// Determines whether the given kind corresponds to a placeholder type.
1907 static bool isPlaceholderTypeKind(Kind K) {
1908 return K >= Overload;
1911 /// Determines whether this type is a placeholder type, i.e. a type
1912 /// which cannot appear in arbitrary positions in a fully-formed
1914 bool isPlaceholderType() const {
1915 return isPlaceholderTypeKind(getKind());
1918 /// Determines whether this type is a placeholder type other than
1919 /// Overload. Most placeholder types require only syntactic
1920 /// information about their context in order to be resolved (e.g.
1921 /// whether it is a call expression), which means they can (and
1922 /// should) be resolved in an earlier "phase" of analysis.
1923 /// Overload expressions sometimes pick up further information
1924 /// from their context, like whether the context expects a
1925 /// specific function-pointer type, and so frequently need
1926 /// special treatment.
1927 bool isNonOverloadPlaceholderType() const {
1928 return getKind() > Overload;
1931 static bool classof(const Type *T) { return T->getTypeClass() == Builtin; }
1934 /// ComplexType - C99 6.2.5p11 - Complex values. This supports the C99 complex
1935 /// types (_Complex float etc) as well as the GCC integer complex extensions.
1937 class ComplexType : public Type, public llvm::FoldingSetNode {
1938 QualType ElementType;
1939 ComplexType(QualType Element, QualType CanonicalPtr) :
1940 Type(Complex, CanonicalPtr, Element->isDependentType(),
1941 Element->isInstantiationDependentType(),
1942 Element->isVariablyModifiedType(),
1943 Element->containsUnexpandedParameterPack()),
1944 ElementType(Element) {
1946 friend class ASTContext; // ASTContext creates these.
1949 QualType getElementType() const { return ElementType; }
1951 bool isSugared() const { return false; }
1952 QualType desugar() const { return QualType(this, 0); }
1954 void Profile(llvm::FoldingSetNodeID &ID) {
1955 Profile(ID, getElementType());
1957 static void Profile(llvm::FoldingSetNodeID &ID, QualType Element) {
1958 ID.AddPointer(Element.getAsOpaquePtr());
1961 static bool classof(const Type *T) { return T->getTypeClass() == Complex; }
1964 /// ParenType - Sugar for parentheses used when specifying types.
1966 class ParenType : public Type, public llvm::FoldingSetNode {
1969 ParenType(QualType InnerType, QualType CanonType) :
1970 Type(Paren, CanonType, InnerType->isDependentType(),
1971 InnerType->isInstantiationDependentType(),
1972 InnerType->isVariablyModifiedType(),
1973 InnerType->containsUnexpandedParameterPack()),
1976 friend class ASTContext; // ASTContext creates these.
1980 QualType getInnerType() const { return Inner; }
1982 bool isSugared() const { return true; }
1983 QualType desugar() const { return getInnerType(); }
1985 void Profile(llvm::FoldingSetNodeID &ID) {
1986 Profile(ID, getInnerType());
1988 static void Profile(llvm::FoldingSetNodeID &ID, QualType Inner) {
1992 static bool classof(const Type *T) { return T->getTypeClass() == Paren; }
1995 /// PointerType - C99 6.7.5.1 - Pointer Declarators.
1997 class PointerType : public Type, public llvm::FoldingSetNode {
1998 QualType PointeeType;
2000 PointerType(QualType Pointee, QualType CanonicalPtr) :
2001 Type(Pointer, CanonicalPtr, Pointee->isDependentType(),
2002 Pointee->isInstantiationDependentType(),
2003 Pointee->isVariablyModifiedType(),
2004 Pointee->containsUnexpandedParameterPack()),
2005 PointeeType(Pointee) {
2007 friend class ASTContext; // ASTContext creates these.
2011 QualType getPointeeType() const { return PointeeType; }
2013 /// \brief Returns true if address spaces of pointers overlap.
2014 /// OpenCL v2.0 defines conversion rules for pointers to different
2015 /// address spaces (OpenCLC v2.0 s6.5.5) and notion of overlapping
2018 /// address spaces overlap iff they are they same.
2020 /// __generic overlaps with any address space except for __constant.
2021 bool isAddressSpaceOverlapping(const PointerType &other) const {
2022 Qualifiers thisQuals = PointeeType.getQualifiers();
2023 Qualifiers otherQuals = other.getPointeeType().getQualifiers();
2024 // Address spaces overlap if at least one of them is a superset of another
2025 return thisQuals.isAddressSpaceSupersetOf(otherQuals) ||
2026 otherQuals.isAddressSpaceSupersetOf(thisQuals);
2029 bool isSugared() const { return false; }
2030 QualType desugar() const { return QualType(this, 0); }
2032 void Profile(llvm::FoldingSetNodeID &ID) {
2033 Profile(ID, getPointeeType());
2035 static void Profile(llvm::FoldingSetNodeID &ID, QualType Pointee) {
2036 ID.AddPointer(Pointee.getAsOpaquePtr());
2039 static bool classof(const Type *T) { return T->getTypeClass() == Pointer; }
2042 /// \brief Represents a type which was implicitly adjusted by the semantic
2043 /// engine for arbitrary reasons. For example, array and function types can
2044 /// decay, and function types can have their calling conventions adjusted.
2045 class AdjustedType : public Type, public llvm::FoldingSetNode {
2046 QualType OriginalTy;
2047 QualType AdjustedTy;
2050 AdjustedType(TypeClass TC, QualType OriginalTy, QualType AdjustedTy,
2051 QualType CanonicalPtr)
2052 : Type(TC, CanonicalPtr, OriginalTy->isDependentType(),
2053 OriginalTy->isInstantiationDependentType(),
2054 OriginalTy->isVariablyModifiedType(),
2055 OriginalTy->containsUnexpandedParameterPack()),
2056 OriginalTy(OriginalTy), AdjustedTy(AdjustedTy) {}
2058 friend class ASTContext; // ASTContext creates these.
2061 QualType getOriginalType() const { return OriginalTy; }
2062 QualType getAdjustedType() const { return AdjustedTy; }
2064 bool isSugared() const { return true; }
2065 QualType desugar() const { return AdjustedTy; }
2067 void Profile(llvm::FoldingSetNodeID &ID) {
2068 Profile(ID, OriginalTy, AdjustedTy);
2070 static void Profile(llvm::FoldingSetNodeID &ID, QualType Orig, QualType New) {
2071 ID.AddPointer(Orig.getAsOpaquePtr());
2072 ID.AddPointer(New.getAsOpaquePtr());
2075 static bool classof(const Type *T) {
2076 return T->getTypeClass() == Adjusted || T->getTypeClass() == Decayed;
2080 /// \brief Represents a pointer type decayed from an array or function type.
2081 class DecayedType : public AdjustedType {
2083 DecayedType(QualType OriginalType, QualType DecayedPtr, QualType CanonicalPtr)
2084 : AdjustedType(Decayed, OriginalType, DecayedPtr, CanonicalPtr) {
2085 assert(isa<PointerType>(getAdjustedType()));
2088 friend class ASTContext; // ASTContext creates these.
2091 QualType getDecayedType() const { return getAdjustedType(); }
2093 QualType getPointeeType() const {
2094 return cast<PointerType>(getDecayedType())->getPointeeType();
2097 static bool classof(const Type *T) { return T->getTypeClass() == Decayed; }
2100 /// BlockPointerType - pointer to a block type.
2101 /// This type is to represent types syntactically represented as
2102 /// "void (^)(int)", etc. Pointee is required to always be a function type.
2104 class BlockPointerType : public Type, public llvm::FoldingSetNode {
2105 QualType PointeeType; // Block is some kind of pointer type
2106 BlockPointerType(QualType Pointee, QualType CanonicalCls) :
2107 Type(BlockPointer, CanonicalCls, Pointee->isDependentType(),
2108 Pointee->isInstantiationDependentType(),
2109 Pointee->isVariablyModifiedType(),
2110 Pointee->containsUnexpandedParameterPack()),
2111 PointeeType(Pointee) {
2113 friend class ASTContext; // ASTContext creates these.
2117 // Get the pointee type. Pointee is required to always be a function type.
2118 QualType getPointeeType() const { return PointeeType; }
2120 bool isSugared() const { return false; }
2121 QualType desugar() const { return QualType(this, 0); }
2123 void Profile(llvm::FoldingSetNodeID &ID) {
2124 Profile(ID, getPointeeType());
2126 static void Profile(llvm::FoldingSetNodeID &ID, QualType Pointee) {
2127 ID.AddPointer(Pointee.getAsOpaquePtr());
2130 static bool classof(const Type *T) {
2131 return T->getTypeClass() == BlockPointer;
2135 /// ReferenceType - Base for LValueReferenceType and RValueReferenceType
2137 class ReferenceType : public Type, public llvm::FoldingSetNode {
2138 QualType PointeeType;
2141 ReferenceType(TypeClass tc, QualType Referencee, QualType CanonicalRef,
2142 bool SpelledAsLValue) :
2143 Type(tc, CanonicalRef, Referencee->isDependentType(),
2144 Referencee->isInstantiationDependentType(),
2145 Referencee->isVariablyModifiedType(),
2146 Referencee->containsUnexpandedParameterPack()),
2147 PointeeType(Referencee)
2149 ReferenceTypeBits.SpelledAsLValue = SpelledAsLValue;
2150 ReferenceTypeBits.InnerRef = Referencee->isReferenceType();
2154 bool isSpelledAsLValue() const { return ReferenceTypeBits.SpelledAsLValue; }
2155 bool isInnerRef() const { return ReferenceTypeBits.InnerRef; }
2157 QualType getPointeeTypeAsWritten() const { return PointeeType; }
2158 QualType getPointeeType() const {
2159 // FIXME: this might strip inner qualifiers; okay?
2160 const ReferenceType *T = this;
2161 while (T->isInnerRef())
2162 T = T->PointeeType->castAs<ReferenceType>();
2163 return T->PointeeType;
2166 void Profile(llvm::FoldingSetNodeID &ID) {
2167 Profile(ID, PointeeType, isSpelledAsLValue());
2169 static void Profile(llvm::FoldingSetNodeID &ID,
2170 QualType Referencee,
2171 bool SpelledAsLValue) {
2172 ID.AddPointer(Referencee.getAsOpaquePtr());
2173 ID.AddBoolean(SpelledAsLValue);
2176 static bool classof(const Type *T) {
2177 return T->getTypeClass() == LValueReference ||
2178 T->getTypeClass() == RValueReference;
2182 /// LValueReferenceType - C++ [dcl.ref] - Lvalue reference
2184 class LValueReferenceType : public ReferenceType {
2185 LValueReferenceType(QualType Referencee, QualType CanonicalRef,
2186 bool SpelledAsLValue) :
2187 ReferenceType(LValueReference, Referencee, CanonicalRef, SpelledAsLValue)
2189 friend class ASTContext; // ASTContext creates these
2191 bool isSugared() const { return false; }
2192 QualType desugar() const { return QualType(this, 0); }
2194 static bool classof(const Type *T) {
2195 return T->getTypeClass() == LValueReference;
2199 /// RValueReferenceType - C++0x [dcl.ref] - Rvalue reference
2201 class RValueReferenceType : public ReferenceType {
2202 RValueReferenceType(QualType Referencee, QualType CanonicalRef) :
2203 ReferenceType(RValueReference, Referencee, CanonicalRef, false) {
2205 friend class ASTContext; // ASTContext creates these
2207 bool isSugared() const { return false; }
2208 QualType desugar() const { return QualType(this, 0); }
2210 static bool classof(const Type *T) {
2211 return T->getTypeClass() == RValueReference;
2215 /// MemberPointerType - C++ 8.3.3 - Pointers to members
2217 class MemberPointerType : public Type, public llvm::FoldingSetNode {
2218 QualType PointeeType;
2219 /// The class of which the pointee is a member. Must ultimately be a
2220 /// RecordType, but could be a typedef or a template parameter too.
2223 MemberPointerType(QualType Pointee, const Type *Cls, QualType CanonicalPtr) :
2224 Type(MemberPointer, CanonicalPtr,
2225 Cls->isDependentType() || Pointee->isDependentType(),
2226 (Cls->isInstantiationDependentType() ||
2227 Pointee->isInstantiationDependentType()),
2228 Pointee->isVariablyModifiedType(),
2229 (Cls->containsUnexpandedParameterPack() ||
2230 Pointee->containsUnexpandedParameterPack())),
2231 PointeeType(Pointee), Class(Cls) {
2233 friend class ASTContext; // ASTContext creates these.
2236 QualType getPointeeType() const { return PointeeType; }
2238 /// Returns true if the member type (i.e. the pointee type) is a
2239 /// function type rather than a data-member type.
2240 bool isMemberFunctionPointer() const {
2241 return PointeeType->isFunctionProtoType();
2244 /// Returns true if the member type (i.e. the pointee type) is a
2245 /// data type rather than a function type.
2246 bool isMemberDataPointer() const {
2247 return !PointeeType->isFunctionProtoType();
2250 const Type *getClass() const { return Class; }
2251 CXXRecordDecl *getMostRecentCXXRecordDecl() const;
2253 bool isSugared() const { return false; }
2254 QualType desugar() const { return QualType(this, 0); }
2256 void Profile(llvm::FoldingSetNodeID &ID) {
2257 Profile(ID, getPointeeType(), getClass());
2259 static void Profile(llvm::FoldingSetNodeID &ID, QualType Pointee,
2260 const Type *Class) {
2261 ID.AddPointer(Pointee.getAsOpaquePtr());
2262 ID.AddPointer(Class);
2265 static bool classof(const Type *T) {
2266 return T->getTypeClass() == MemberPointer;
2270 /// ArrayType - C99 6.7.5.2 - Array Declarators.
2272 class ArrayType : public Type, public llvm::FoldingSetNode {
2274 /// ArraySizeModifier - Capture whether this is a normal array (e.g. int X[4])
2275 /// an array with a static size (e.g. int X[static 4]), or an array
2276 /// with a star size (e.g. int X[*]).
2277 /// 'static' is only allowed on function parameters.
2278 enum ArraySizeModifier {
2279 Normal, Static, Star
2282 /// ElementType - The element type of the array.
2283 QualType ElementType;
2286 // C++ [temp.dep.type]p1:
2287 // A type is dependent if it is...
2288 // - an array type constructed from any dependent type or whose
2289 // size is specified by a constant expression that is
2291 ArrayType(TypeClass tc, QualType et, QualType can,
2292 ArraySizeModifier sm, unsigned tq,
2293 bool ContainsUnexpandedParameterPack)
2294 : Type(tc, can, et->isDependentType() || tc == DependentSizedArray,
2295 et->isInstantiationDependentType() || tc == DependentSizedArray,
2296 (tc == VariableArray || et->isVariablyModifiedType()),
2297 ContainsUnexpandedParameterPack),
2299 ArrayTypeBits.IndexTypeQuals = tq;
2300 ArrayTypeBits.SizeModifier = sm;
2303 friend class ASTContext; // ASTContext creates these.
2306 QualType getElementType() const { return ElementType; }
2307 ArraySizeModifier getSizeModifier() const {
2308 return ArraySizeModifier(ArrayTypeBits.SizeModifier);
2310 Qualifiers getIndexTypeQualifiers() const {
2311 return Qualifiers::fromCVRMask(getIndexTypeCVRQualifiers());
2313 unsigned getIndexTypeCVRQualifiers() const {
2314 return ArrayTypeBits.IndexTypeQuals;
2317 static bool classof(const Type *T) {
2318 return T->getTypeClass() == ConstantArray ||
2319 T->getTypeClass() == VariableArray ||
2320 T->getTypeClass() == IncompleteArray ||
2321 T->getTypeClass() == DependentSizedArray;
2325 /// ConstantArrayType - This class represents the canonical version of
2326 /// C arrays with a specified constant size. For example, the canonical
2327 /// type for 'int A[4 + 4*100]' is a ConstantArrayType where the element
2328 /// type is 'int' and the size is 404.
2329 class ConstantArrayType : public ArrayType {
2330 llvm::APInt Size; // Allows us to unique the type.
2332 ConstantArrayType(QualType et, QualType can, const llvm::APInt &size,
2333 ArraySizeModifier sm, unsigned tq)
2334 : ArrayType(ConstantArray, et, can, sm, tq,
2335 et->containsUnexpandedParameterPack()),
2338 ConstantArrayType(TypeClass tc, QualType et, QualType can,
2339 const llvm::APInt &size, ArraySizeModifier sm, unsigned tq)
2340 : ArrayType(tc, et, can, sm, tq, et->containsUnexpandedParameterPack()),
2342 friend class ASTContext; // ASTContext creates these.
2344 const llvm::APInt &getSize() const { return Size; }
2345 bool isSugared() const { return false; }
2346 QualType desugar() const { return QualType(this, 0); }
2349 /// \brief Determine the number of bits required to address a member of
2350 // an array with the given element type and number of elements.
2351 static unsigned getNumAddressingBits(ASTContext &Context,
2352 QualType ElementType,
2353 const llvm::APInt &NumElements);
2355 /// \brief Determine the maximum number of active bits that an array's size
2356 /// can require, which limits the maximum size of the array.
2357 static unsigned getMaxSizeBits(ASTContext &Context);
2359 void Profile(llvm::FoldingSetNodeID &ID) {
2360 Profile(ID, getElementType(), getSize(),
2361 getSizeModifier(), getIndexTypeCVRQualifiers());
2363 static void Profile(llvm::FoldingSetNodeID &ID, QualType ET,
2364 const llvm::APInt &ArraySize, ArraySizeModifier SizeMod,
2365 unsigned TypeQuals) {
2366 ID.AddPointer(ET.getAsOpaquePtr());
2367 ID.AddInteger(ArraySize.getZExtValue());
2368 ID.AddInteger(SizeMod);
2369 ID.AddInteger(TypeQuals);
2371 static bool classof(const Type *T) {
2372 return T->getTypeClass() == ConstantArray;
2376 /// IncompleteArrayType - This class represents C arrays with an unspecified
2377 /// size. For example 'int A[]' has an IncompleteArrayType where the element
2378 /// type is 'int' and the size is unspecified.
2379 class IncompleteArrayType : public ArrayType {
2381 IncompleteArrayType(QualType et, QualType can,
2382 ArraySizeModifier sm, unsigned tq)
2383 : ArrayType(IncompleteArray, et, can, sm, tq,
2384 et->containsUnexpandedParameterPack()) {}
2385 friend class ASTContext; // ASTContext creates these.
2387 bool isSugared() const { return false; }
2388 QualType desugar() const { return QualType(this, 0); }
2390 static bool classof(const Type *T) {
2391 return T->getTypeClass() == IncompleteArray;
2394 friend class StmtIteratorBase;
2396 void Profile(llvm::FoldingSetNodeID &ID) {
2397 Profile(ID, getElementType(), getSizeModifier(),
2398 getIndexTypeCVRQualifiers());
2401 static void Profile(llvm::FoldingSetNodeID &ID, QualType ET,
2402 ArraySizeModifier SizeMod, unsigned TypeQuals) {
2403 ID.AddPointer(ET.getAsOpaquePtr());
2404 ID.AddInteger(SizeMod);
2405 ID.AddInteger(TypeQuals);
2409 /// VariableArrayType - This class represents C arrays with a specified size
2410 /// which is not an integer-constant-expression. For example, 'int s[x+foo()]'.
2411 /// Since the size expression is an arbitrary expression, we store it as such.
2413 /// Note: VariableArrayType's aren't uniqued (since the expressions aren't) and
2414 /// should not be: two lexically equivalent variable array types could mean
2415 /// different things, for example, these variables do not have the same type
2418 /// void foo(int x) {
2424 class VariableArrayType : public ArrayType {
2425 /// SizeExpr - An assignment expression. VLA's are only permitted within
2426 /// a function block.
2428 /// Brackets - The left and right array brackets.
2429 SourceRange Brackets;
2431 VariableArrayType(QualType et, QualType can, Expr *e,
2432 ArraySizeModifier sm, unsigned tq,
2433 SourceRange brackets)
2434 : ArrayType(VariableArray, et, can, sm, tq,
2435 et->containsUnexpandedParameterPack()),
2436 SizeExpr((Stmt*) e), Brackets(brackets) {}
2437 friend class ASTContext; // ASTContext creates these.
2440 Expr *getSizeExpr() const {
2441 // We use C-style casts instead of cast<> here because we do not wish
2442 // to have a dependency of Type.h on Stmt.h/Expr.h.
2443 return (Expr*) SizeExpr;
2445 SourceRange getBracketsRange() const { return Brackets; }
2446 SourceLocation getLBracketLoc() const { return Brackets.getBegin(); }
2447 SourceLocation getRBracketLoc() const { return Brackets.getEnd(); }
2449 bool isSugared() const { return false; }
2450 QualType desugar() const { return QualType(this, 0); }
2452 static bool classof(const Type *T) {
2453 return T->getTypeClass() == VariableArray;
2456 friend class StmtIteratorBase;
2458 void Profile(llvm::FoldingSetNodeID &ID) {
2459 llvm_unreachable("Cannot unique VariableArrayTypes.");
2463 /// DependentSizedArrayType - This type represents an array type in
2464 /// C++ whose size is a value-dependent expression. For example:
2467 /// template<typename T, int Size>
2473 /// For these types, we won't actually know what the array bound is
2474 /// until template instantiation occurs, at which point this will
2475 /// become either a ConstantArrayType or a VariableArrayType.
2476 class DependentSizedArrayType : public ArrayType {
2477 const ASTContext &Context;
2479 /// \brief An assignment expression that will instantiate to the
2480 /// size of the array.
2482 /// The expression itself might be NULL, in which case the array
2483 /// type will have its size deduced from an initializer.
2486 /// Brackets - The left and right array brackets.
2487 SourceRange Brackets;
2489 DependentSizedArrayType(const ASTContext &Context, QualType et, QualType can,
2490 Expr *e, ArraySizeModifier sm, unsigned tq,
2491 SourceRange brackets);
2493 friend class ASTContext; // ASTContext creates these.
2496 Expr *getSizeExpr() const {
2497 // We use C-style casts instead of cast<> here because we do not wish
2498 // to have a dependency of Type.h on Stmt.h/Expr.h.
2499 return (Expr*) SizeExpr;
2501 SourceRange getBracketsRange() const { return Brackets; }
2502 SourceLocation getLBracketLoc() const { return Brackets.getBegin(); }
2503 SourceLocation getRBracketLoc() const { return Brackets.getEnd(); }
2505 bool isSugared() const { return false; }
2506 QualType desugar() const { return QualType(this, 0); }
2508 static bool classof(const Type *T) {
2509 return T->getTypeClass() == DependentSizedArray;
2512 friend class StmtIteratorBase;
2515 void Profile(llvm::FoldingSetNodeID &ID) {
2516 Profile(ID, Context, getElementType(),
2517 getSizeModifier(), getIndexTypeCVRQualifiers(), getSizeExpr());
2520 static void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context,
2521 QualType ET, ArraySizeModifier SizeMod,
2522 unsigned TypeQuals, Expr *E);
2525 /// DependentSizedExtVectorType - This type represent an extended vector type
2526 /// where either the type or size is dependent. For example:
2528 /// template<typename T, int Size>
2530 /// typedef T __attribute__((ext_vector_type(Size))) type;
2533 class DependentSizedExtVectorType : public Type, public llvm::FoldingSetNode {
2534 const ASTContext &Context;
2536 /// ElementType - The element type of the array.
2537 QualType ElementType;
2540 DependentSizedExtVectorType(const ASTContext &Context, QualType ElementType,
2541 QualType can, Expr *SizeExpr, SourceLocation loc);
2543 friend class ASTContext;
2546 Expr *getSizeExpr() const { return SizeExpr; }
2547 QualType getElementType() const { return ElementType; }
2548 SourceLocation getAttributeLoc() const { return loc; }
2550 bool isSugared() const { return false; }
2551 QualType desugar() const { return QualType(this, 0); }
2553 static bool classof(const Type *T) {
2554 return T->getTypeClass() == DependentSizedExtVector;
2557 void Profile(llvm::FoldingSetNodeID &ID) {
2558 Profile(ID, Context, getElementType(), getSizeExpr());
2561 static void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context,
2562 QualType ElementType, Expr *SizeExpr);
2566 /// VectorType - GCC generic vector type. This type is created using
2567 /// __attribute__((vector_size(n)), where "n" specifies the vector size in
2568 /// bytes; or from an Altivec __vector or vector declaration.
2569 /// Since the constructor takes the number of vector elements, the
2570 /// client is responsible for converting the size into the number of elements.
2571 class VectorType : public Type, public llvm::FoldingSetNode {
2574 GenericVector, // not a target-specific vector type
2575 AltiVecVector, // is AltiVec vector
2576 AltiVecPixel, // is AltiVec 'vector Pixel'
2577 AltiVecBool, // is AltiVec 'vector bool ...'
2578 NeonVector, // is ARM Neon vector
2579 NeonPolyVector // is ARM Neon polynomial vector
2582 /// ElementType - The element type of the vector.
2583 QualType ElementType;
2585 VectorType(QualType vecType, unsigned nElements, QualType canonType,
2586 VectorKind vecKind);
2588 VectorType(TypeClass tc, QualType vecType, unsigned nElements,
2589 QualType canonType, VectorKind vecKind);
2591 friend class ASTContext; // ASTContext creates these.
2595 QualType getElementType() const { return ElementType; }
2596 unsigned getNumElements() const { return VectorTypeBits.NumElements; }
2597 static bool isVectorSizeTooLarge(unsigned NumElements) {
2598 return NumElements > VectorTypeBitfields::MaxNumElements;
2601 bool isSugared() const { return false; }
2602 QualType desugar() const { return QualType(this, 0); }
2604 VectorKind getVectorKind() const {
2605 return VectorKind(VectorTypeBits.VecKind);
2608 void Profile(llvm::FoldingSetNodeID &ID) {
2609 Profile(ID, getElementType(), getNumElements(),
2610 getTypeClass(), getVectorKind());
2612 static void Profile(llvm::FoldingSetNodeID &ID, QualType ElementType,
2613 unsigned NumElements, TypeClass TypeClass,
2614 VectorKind VecKind) {
2615 ID.AddPointer(ElementType.getAsOpaquePtr());
2616 ID.AddInteger(NumElements);
2617 ID.AddInteger(TypeClass);
2618 ID.AddInteger(VecKind);
2621 static bool classof(const Type *T) {
2622 return T->getTypeClass() == Vector || T->getTypeClass() == ExtVector;
2626 /// ExtVectorType - Extended vector type. This type is created using
2627 /// __attribute__((ext_vector_type(n)), where "n" is the number of elements.
2628 /// Unlike vector_size, ext_vector_type is only allowed on typedef's. This
2629 /// class enables syntactic extensions, like Vector Components for accessing
2630 /// points, colors, and textures (modeled after OpenGL Shading Language).
2631 class ExtVectorType : public VectorType {
2632 ExtVectorType(QualType vecType, unsigned nElements, QualType canonType) :
2633 VectorType(ExtVector, vecType, nElements, canonType, GenericVector) {}
2634 friend class ASTContext; // ASTContext creates these.
2636 static int getPointAccessorIdx(char c) {
2645 static int getNumericAccessorIdx(char c) {
2659 case 'a': return 10;
2661 case 'b': return 11;
2663 case 'c': return 12;
2665 case 'd': return 13;
2667 case 'e': return 14;
2669 case 'f': return 15;
2673 static int getAccessorIdx(char c) {
2674 if (int idx = getPointAccessorIdx(c)+1) return idx-1;
2675 return getNumericAccessorIdx(c);
2678 bool isAccessorWithinNumElements(char c) const {
2679 if (int idx = getAccessorIdx(c)+1)
2680 return unsigned(idx-1) < getNumElements();
2683 bool isSugared() const { return false; }
2684 QualType desugar() const { return QualType(this, 0); }
2686 static bool classof(const Type *T) {
2687 return T->getTypeClass() == ExtVector;
2691 /// FunctionType - C99 6.7.5.3 - Function Declarators. This is the common base
2692 /// class of FunctionNoProtoType and FunctionProtoType.
2694 class FunctionType : public Type {
2695 // The type returned by the function.
2696 QualType ResultType;
2699 /// ExtInfo - A class which abstracts out some details necessary for
2702 /// It is not actually used directly for storing this information in
2703 /// a FunctionType, although FunctionType does currently use the
2704 /// same bit-pattern.
2706 // If you add a field (say Foo), other than the obvious places (both,
2707 // constructors, compile failures), what you need to update is
2711 // * functionType. Add Foo, getFoo.
2712 // * ASTContext::getFooType
2713 // * ASTContext::mergeFunctionTypes
2714 // * FunctionNoProtoType::Profile
2715 // * FunctionProtoType::Profile
2716 // * TypePrinter::PrintFunctionProto
2717 // * AST read and write
2720 // Feel free to rearrange or add bits, but if you go over 9,
2721 // you'll need to adjust both the Bits field below and
2722 // Type::FunctionTypeBitfields.
2724 // | CC |noreturn|produces|regparm|
2725 // |0 .. 3| 4 | 5 | 6 .. 8|
2727 // regparm is either 0 (no regparm attribute) or the regparm value+1.
2728 enum { CallConvMask = 0xF };
2729 enum { NoReturnMask = 0x10 };
2730 enum { ProducesResultMask = 0x20 };
2731 enum { RegParmMask = ~(CallConvMask | NoReturnMask | ProducesResultMask),
2732 RegParmOffset = 6 }; // Assumed to be the last field
2736 ExtInfo(unsigned Bits) : Bits(static_cast<uint16_t>(Bits)) {}
2738 friend class FunctionType;
2741 // Constructor with no defaults. Use this when you know that you
2742 // have all the elements (when reading an AST file for example).
2743 ExtInfo(bool noReturn, bool hasRegParm, unsigned regParm, CallingConv cc,
2744 bool producesResult) {
2745 assert((!hasRegParm || regParm < 7) && "Invalid regparm value");
2746 Bits = ((unsigned) cc) |
2747 (noReturn ? NoReturnMask : 0) |
2748 (producesResult ? ProducesResultMask : 0) |
2749 (hasRegParm ? ((regParm + 1) << RegParmOffset) : 0);
2752 // Constructor with all defaults. Use when for example creating a
2753 // function know to use defaults.
2754 ExtInfo() : Bits(CC_C) { }
2756 // Constructor with just the calling convention, which is an important part
2757 // of the canonical type.
2758 ExtInfo(CallingConv CC) : Bits(CC) { }
2760 bool getNoReturn() const { return Bits & NoReturnMask; }
2761 bool getProducesResult() const { return Bits & ProducesResultMask; }
2762 bool getHasRegParm() const { return (Bits >> RegParmOffset) != 0; }
2763 unsigned getRegParm() const {
2764 unsigned RegParm = Bits >> RegParmOffset;
2769 CallingConv getCC() const { return CallingConv(Bits & CallConvMask); }
2771 bool operator==(ExtInfo Other) const {
2772 return Bits == Other.Bits;
2774 bool operator!=(ExtInfo Other) const {
2775 return Bits != Other.Bits;
2778 // Note that we don't have setters. That is by design, use
2779 // the following with methods instead of mutating these objects.
2781 ExtInfo withNoReturn(bool noReturn) const {
2783 return ExtInfo(Bits | NoReturnMask);
2785 return ExtInfo(Bits & ~NoReturnMask);
2788 ExtInfo withProducesResult(bool producesResult) const {
2790 return ExtInfo(Bits | ProducesResultMask);
2792 return ExtInfo(Bits & ~ProducesResultMask);
2795 ExtInfo withRegParm(unsigned RegParm) const {
2796 assert(RegParm < 7 && "Invalid regparm value");
2797 return ExtInfo((Bits & ~RegParmMask) |
2798 ((RegParm + 1) << RegParmOffset));
2801 ExtInfo withCallingConv(CallingConv cc) const {
2802 return ExtInfo((Bits & ~CallConvMask) | (unsigned) cc);
2805 void Profile(llvm::FoldingSetNodeID &ID) const {
2806 ID.AddInteger(Bits);
2811 FunctionType(TypeClass tc, QualType res,
2812 QualType Canonical, bool Dependent,
2813 bool InstantiationDependent,
2814 bool VariablyModified, bool ContainsUnexpandedParameterPack,
2816 : Type(tc, Canonical, Dependent, InstantiationDependent, VariablyModified,
2817 ContainsUnexpandedParameterPack),
2819 FunctionTypeBits.ExtInfo = Info.Bits;
2821 unsigned getTypeQuals() const { return FunctionTypeBits.TypeQuals; }
2824 QualType getReturnType() const { return ResultType; }
2826 bool getHasRegParm() const { return getExtInfo().getHasRegParm(); }
2827 unsigned getRegParmType() const { return getExtInfo().getRegParm(); }
2828 /// \brief Determine whether this function type includes the GNU noreturn
2829 /// attribute. The C++11 [[noreturn]] attribute does not affect the function
2831 bool getNoReturnAttr() const { return getExtInfo().getNoReturn(); }
2832 CallingConv getCallConv() const { return getExtInfo().getCC(); }
2833 ExtInfo getExtInfo() const { return ExtInfo(FunctionTypeBits.ExtInfo); }
2834 bool isConst() const { return getTypeQuals() & Qualifiers::Const; }
2835 bool isVolatile() const { return getTypeQuals() & Qualifiers::Volatile; }
2836 bool isRestrict() const { return getTypeQuals() & Qualifiers::Restrict; }
2838 /// \brief Determine the type of an expression that calls a function of
2840 QualType getCallResultType(ASTContext &Context) const {
2841 return getReturnType().getNonLValueExprType(Context);
2844 static StringRef getNameForCallConv(CallingConv CC);
2846 static bool classof(const Type *T) {
2847 return T->getTypeClass() == FunctionNoProto ||
2848 T->getTypeClass() == FunctionProto;
2852 /// FunctionNoProtoType - Represents a K&R-style 'int foo()' function, which has
2853 /// no information available about its arguments.
2854 class FunctionNoProtoType : public FunctionType, public llvm::FoldingSetNode {
2855 FunctionNoProtoType(QualType Result, QualType Canonical, ExtInfo Info)
2856 : FunctionType(FunctionNoProto, Result, Canonical,
2857 /*Dependent=*/false, /*InstantiationDependent=*/false,
2858 Result->isVariablyModifiedType(),
2859 /*ContainsUnexpandedParameterPack=*/false, Info) {}
2861 friend class ASTContext; // ASTContext creates these.
2864 // No additional state past what FunctionType provides.
2866 bool isSugared() const { return false; }
2867 QualType desugar() const { return QualType(this, 0); }
2869 void Profile(llvm::FoldingSetNodeID &ID) {
2870 Profile(ID, getReturnType(), getExtInfo());
2872 static void Profile(llvm::FoldingSetNodeID &ID, QualType ResultType,
2875 ID.AddPointer(ResultType.getAsOpaquePtr());
2878 static bool classof(const Type *T) {
2879 return T->getTypeClass() == FunctionNoProto;
2883 /// FunctionProtoType - Represents a prototype with parameter type info, e.g.
2884 /// 'int foo(int)' or 'int foo(void)'. 'void' is represented as having no
2885 /// parameters, not as having a single void parameter. Such a type can have an
2886 /// exception specification, but this specification is not part of the canonical
2888 class FunctionProtoType : public FunctionType, public llvm::FoldingSetNode {
2890 struct ExceptionSpecInfo {
2892 : Type(EST_None), NoexceptExpr(nullptr),
2893 SourceDecl(nullptr), SourceTemplate(nullptr) {}
2895 ExceptionSpecInfo(ExceptionSpecificationType EST)
2896 : Type(EST), NoexceptExpr(nullptr), SourceDecl(nullptr),
2897 SourceTemplate(nullptr) {}
2899 /// The kind of exception specification this is.
2900 ExceptionSpecificationType Type;
2901 /// Explicitly-specified list of exception types.
2902 ArrayRef<QualType> Exceptions;
2903 /// Noexcept expression, if this is EST_ComputedNoexcept.
2905 /// The function whose exception specification this is, for
2906 /// EST_Unevaluated and EST_Uninstantiated.
2907 FunctionDecl *SourceDecl;
2908 /// The function template whose exception specification this is instantiated
2909 /// from, for EST_Uninstantiated.
2910 FunctionDecl *SourceTemplate;
2913 /// ExtProtoInfo - Extra information about a function prototype.
2914 struct ExtProtoInfo {
2916 : Variadic(false), HasTrailingReturn(false), TypeQuals(0),
2917 RefQualifier(RQ_None), ConsumedParameters(nullptr) {}
2919 ExtProtoInfo(CallingConv CC)
2920 : ExtInfo(CC), Variadic(false), HasTrailingReturn(false), TypeQuals(0),
2921 RefQualifier(RQ_None), ConsumedParameters(nullptr) {}
2923 ExtProtoInfo withExceptionSpec(const ExceptionSpecInfo &O) {
2924 ExtProtoInfo Result(*this);
2925 Result.ExceptionSpec = O;
2929 FunctionType::ExtInfo ExtInfo;
2931 bool HasTrailingReturn : 1;
2932 unsigned char TypeQuals;
2933 RefQualifierKind RefQualifier;
2934 ExceptionSpecInfo ExceptionSpec;
2935 const bool *ConsumedParameters;
2939 /// \brief Determine whether there are any argument types that
2940 /// contain an unexpanded parameter pack.
2941 static bool containsAnyUnexpandedParameterPack(const QualType *ArgArray,
2943 for (unsigned Idx = 0; Idx < numArgs; ++Idx)
2944 if (ArgArray[Idx]->containsUnexpandedParameterPack())
2950 FunctionProtoType(QualType result, ArrayRef<QualType> params,
2951 QualType canonical, const ExtProtoInfo &epi);
2953 /// The number of parameters this function has, not counting '...'.
2954 unsigned NumParams : 15;
2956 /// NumExceptions - The number of types in the exception spec, if any.
2957 unsigned NumExceptions : 9;
2959 /// ExceptionSpecType - The type of exception specification this function has.
2960 unsigned ExceptionSpecType : 4;
2962 /// HasAnyConsumedParams - Whether this function has any consumed parameters.
2963 unsigned HasAnyConsumedParams : 1;
2965 /// Variadic - Whether the function is variadic.
2966 unsigned Variadic : 1;
2968 /// HasTrailingReturn - Whether this function has a trailing return type.
2969 unsigned HasTrailingReturn : 1;
2971 // ParamInfo - There is an variable size array after the class in memory that
2972 // holds the parameter types.
2974 // Exceptions - There is another variable size array after ArgInfo that
2975 // holds the exception types.
2977 // NoexceptExpr - Instead of Exceptions, there may be a single Expr* pointing
2978 // to the expression in the noexcept() specifier.
2980 // ExceptionSpecDecl, ExceptionSpecTemplate - Instead of Exceptions, there may
2981 // be a pair of FunctionDecl* pointing to the function which should be used to
2982 // instantiate this function type's exception specification, and the function
2983 // from which it should be instantiated.
2985 // ConsumedParameters - A variable size array, following Exceptions
2986 // and of length NumParams, holding flags indicating which parameters
2987 // are consumed. This only appears if HasAnyConsumedParams is true.
2989 friend class ASTContext; // ASTContext creates these.
2991 const bool *getConsumedParamsBuffer() const {
2992 assert(hasAnyConsumedParams());
2994 // Find the end of the exceptions.
2995 Expr *const *eh_end = reinterpret_cast<Expr *const *>(param_type_end());
2996 if (getExceptionSpecType() != EST_ComputedNoexcept)
2997 eh_end += NumExceptions;
2999 eh_end += 1; // NoexceptExpr
3001 return reinterpret_cast<const bool*>(eh_end);
3005 unsigned getNumParams() const { return NumParams; }
3006 QualType getParamType(unsigned i) const {
3007 assert(i < NumParams && "invalid parameter index");
3008 return param_type_begin()[i];
3010 ArrayRef<QualType> getParamTypes() const {
3011 return llvm::makeArrayRef(param_type_begin(), param_type_end());
3014 ExtProtoInfo getExtProtoInfo() const {
3016 EPI.ExtInfo = getExtInfo();
3017 EPI.Variadic = isVariadic();
3018 EPI.HasTrailingReturn = hasTrailingReturn();
3019 EPI.ExceptionSpec.Type = getExceptionSpecType();
3020 EPI.TypeQuals = static_cast<unsigned char>(getTypeQuals());
3021 EPI.RefQualifier = getRefQualifier();
3022 if (EPI.ExceptionSpec.Type == EST_Dynamic) {
3023 EPI.ExceptionSpec.Exceptions = exceptions();
3024 } else if (EPI.ExceptionSpec.Type == EST_ComputedNoexcept) {
3025 EPI.ExceptionSpec.NoexceptExpr = getNoexceptExpr();
3026 } else if (EPI.ExceptionSpec.Type == EST_Uninstantiated) {
3027 EPI.ExceptionSpec.SourceDecl = getExceptionSpecDecl();
3028 EPI.ExceptionSpec.SourceTemplate = getExceptionSpecTemplate();
3029 } else if (EPI.ExceptionSpec.Type == EST_Unevaluated) {
3030 EPI.ExceptionSpec.SourceDecl = getExceptionSpecDecl();
3032 if (hasAnyConsumedParams())
3033 EPI.ConsumedParameters = getConsumedParamsBuffer();
3037 /// \brief Get the kind of exception specification on this function.
3038 ExceptionSpecificationType getExceptionSpecType() const {
3039 return static_cast<ExceptionSpecificationType>(ExceptionSpecType);
3041 /// \brief Return whether this function has any kind of exception spec.
3042 bool hasExceptionSpec() const {
3043 return getExceptionSpecType() != EST_None;
3045 /// \brief Return whether this function has a dynamic (throw) exception spec.
3046 bool hasDynamicExceptionSpec() const {
3047 return isDynamicExceptionSpec(getExceptionSpecType());
3049 /// \brief Return whether this function has a noexcept exception spec.
3050 bool hasNoexceptExceptionSpec() const {
3051 return isNoexceptExceptionSpec(getExceptionSpecType());
3053 /// \brief Return whether this function has a dependent exception spec.
3054 bool hasDependentExceptionSpec() const;
3055 /// \brief Result type of getNoexceptSpec().
3056 enum NoexceptResult {
3057 NR_NoNoexcept, ///< There is no noexcept specifier.
3058 NR_BadNoexcept, ///< The noexcept specifier has a bad expression.
3059 NR_Dependent, ///< The noexcept specifier is dependent.
3060 NR_Throw, ///< The noexcept specifier evaluates to false.
3061 NR_Nothrow ///< The noexcept specifier evaluates to true.
3063 /// \brief Get the meaning of the noexcept spec on this function, if any.
3064 NoexceptResult getNoexceptSpec(const ASTContext &Ctx) const;
3065 unsigned getNumExceptions() const { return NumExceptions; }
3066 QualType getExceptionType(unsigned i) const {
3067 assert(i < NumExceptions && "Invalid exception number!");
3068 return exception_begin()[i];
3070 Expr *getNoexceptExpr() const {
3071 if (getExceptionSpecType() != EST_ComputedNoexcept)
3073 // NoexceptExpr sits where the arguments end.
3074 return *reinterpret_cast<Expr *const *>(param_type_end());
3076 /// \brief If this function type has an exception specification which hasn't
3077 /// been determined yet (either because it has not been evaluated or because
3078 /// it has not been instantiated), this is the function whose exception
3079 /// specification is represented by this type.
3080 FunctionDecl *getExceptionSpecDecl() const {
3081 if (getExceptionSpecType() != EST_Uninstantiated &&
3082 getExceptionSpecType() != EST_Unevaluated)
3084 return reinterpret_cast<FunctionDecl *const *>(param_type_end())[0];
3086 /// \brief If this function type has an uninstantiated exception
3087 /// specification, this is the function whose exception specification
3088 /// should be instantiated to find the exception specification for
3090 FunctionDecl *getExceptionSpecTemplate() const {
3091 if (getExceptionSpecType() != EST_Uninstantiated)
3093 return reinterpret_cast<FunctionDecl *const *>(param_type_end())[1];
3095 /// \brief Determine whether this function type has a non-throwing exception
3096 /// specification. If this depends on template arguments, returns
3097 /// \c ResultIfDependent.
3098 bool isNothrow(const ASTContext &Ctx, bool ResultIfDependent = false) const;
3100 bool isVariadic() const { return Variadic; }
3102 /// \brief Determines whether this function prototype contains a
3103 /// parameter pack at the end.
3105 /// A function template whose last parameter is a parameter pack can be
3106 /// called with an arbitrary number of arguments, much like a variadic
3108 bool isTemplateVariadic() const;
3110 bool hasTrailingReturn() const { return HasTrailingReturn; }
3112 unsigned getTypeQuals() const { return FunctionType::getTypeQuals(); }
3115 /// \brief Retrieve the ref-qualifier associated with this function type.
3116 RefQualifierKind getRefQualifier() const {
3117 return static_cast<RefQualifierKind>(FunctionTypeBits.RefQualifier);
3120 typedef const QualType *param_type_iterator;
3121 typedef llvm::iterator_range<param_type_iterator> param_type_range;
3123 param_type_range param_types() const {
3124 return param_type_range(param_type_begin(), param_type_end());
3126 param_type_iterator param_type_begin() const {
3127 return reinterpret_cast<const QualType *>(this+1);
3129 param_type_iterator param_type_end() const {
3130 return param_type_begin() + NumParams;
3133 typedef const QualType *exception_iterator;
3135 ArrayRef<QualType> exceptions() const {
3136 return llvm::makeArrayRef(exception_begin(), exception_end());
3138 exception_iterator exception_begin() const {
3139 // exceptions begin where arguments end
3140 return param_type_end();
3142 exception_iterator exception_end() const {
3143 if (getExceptionSpecType() != EST_Dynamic)
3144 return exception_begin();
3145 return exception_begin() + NumExceptions;
3148 bool hasAnyConsumedParams() const { return HasAnyConsumedParams; }
3149 bool isParamConsumed(unsigned I) const {
3150 assert(I < getNumParams() && "parameter index out of range");
3151 if (hasAnyConsumedParams())
3152 return getConsumedParamsBuffer()[I];
3156 bool isSugared() const { return false; }
3157 QualType desugar() const { return QualType(this, 0); }
3159 void printExceptionSpecification(raw_ostream &OS,
3160 const PrintingPolicy &Policy) const;
3162 static bool classof(const Type *T) {
3163 return T->getTypeClass() == FunctionProto;
3166 void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Ctx);
3167 static void Profile(llvm::FoldingSetNodeID &ID, QualType Result,
3168 param_type_iterator ArgTys, unsigned NumArgs,
3169 const ExtProtoInfo &EPI, const ASTContext &Context);
3173 /// \brief Represents the dependent type named by a dependently-scoped
3174 /// typename using declaration, e.g.
3175 /// using typename Base<T>::foo;
3176 /// Template instantiation turns these into the underlying type.
3177 class UnresolvedUsingType : public Type {
3178 UnresolvedUsingTypenameDecl *Decl;
3180 UnresolvedUsingType(const UnresolvedUsingTypenameDecl *D)
3181 : Type(UnresolvedUsing, QualType(), true, true, false,
3182 /*ContainsUnexpandedParameterPack=*/false),
3183 Decl(const_cast<UnresolvedUsingTypenameDecl*>(D)) {}
3184 friend class ASTContext; // ASTContext creates these.
3187 UnresolvedUsingTypenameDecl *getDecl() const { return Decl; }
3189 bool isSugared() const { return false; }
3190 QualType desugar() const { return QualType(this, 0); }
3192 static bool classof(const Type *T) {
3193 return T->getTypeClass() == UnresolvedUsing;
3196 void Profile(llvm::FoldingSetNodeID &ID) {
3197 return Profile(ID, Decl);
3199 static void Profile(llvm::FoldingSetNodeID &ID,
3200 UnresolvedUsingTypenameDecl *D) {
3206 class TypedefType : public Type {
3207 TypedefNameDecl *Decl;
3209 TypedefType(TypeClass tc, const TypedefNameDecl *D, QualType can)
3210 : Type(tc, can, can->isDependentType(),
3211 can->isInstantiationDependentType(),
3212 can->isVariablyModifiedType(),
3213 /*ContainsUnexpandedParameterPack=*/false),
3214 Decl(const_cast<TypedefNameDecl*>(D)) {
3215 assert(!isa<TypedefType>(can) && "Invalid canonical type");
3217 friend class ASTContext; // ASTContext creates these.
3220 TypedefNameDecl *getDecl() const { return Decl; }
3222 bool isSugared() const { return true; }
3223 QualType desugar() const;
3225 static bool classof(const Type *T) { return T->getTypeClass() == Typedef; }
3228 /// TypeOfExprType (GCC extension).
3229 class TypeOfExprType : public Type {
3233 TypeOfExprType(Expr *E, QualType can = QualType());
3234 friend class ASTContext; // ASTContext creates these.
3236 Expr *getUnderlyingExpr() const { return TOExpr; }
3238 /// \brief Remove a single level of sugar.
3239 QualType desugar() const;
3241 /// \brief Returns whether this type directly provides sugar.
3242 bool isSugared() const;
3244 static bool classof(const Type *T) { return T->getTypeClass() == TypeOfExpr; }
3247 /// \brief Internal representation of canonical, dependent
3248 /// typeof(expr) types.
3250 /// This class is used internally by the ASTContext to manage
3251 /// canonical, dependent types, only. Clients will only see instances
3252 /// of this class via TypeOfExprType nodes.
3253 class DependentTypeOfExprType
3254 : public TypeOfExprType, public llvm::FoldingSetNode {
3255 const ASTContext &Context;
3258 DependentTypeOfExprType(const ASTContext &Context, Expr *E)
3259 : TypeOfExprType(E), Context(Context) { }
3261 void Profile(llvm::FoldingSetNodeID &ID) {
3262 Profile(ID, Context, getUnderlyingExpr());
3265 static void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context,
3269 /// TypeOfType (GCC extension).
3270 class TypeOfType : public Type {
3272 TypeOfType(QualType T, QualType can)
3273 : Type(TypeOf, can, T->isDependentType(),
3274 T->isInstantiationDependentType(),
3275 T->isVariablyModifiedType(),
3276 T->containsUnexpandedParameterPack()),
3278 assert(!isa<TypedefType>(can) && "Invalid canonical type");
3280 friend class ASTContext; // ASTContext creates these.
3282 QualType getUnderlyingType() const { return TOType; }
3284 /// \brief Remove a single level of sugar.
3285 QualType desugar() const { return getUnderlyingType(); }
3287 /// \brief Returns whether this type directly provides sugar.
3288 bool isSugared() const { return true; }
3290 static bool classof(const Type *T) { return T->getTypeClass() == TypeOf; }
3293 /// DecltypeType (C++0x)
3294 class DecltypeType : public Type {
3296 QualType UnderlyingType;
3299 DecltypeType(Expr *E, QualType underlyingType, QualType can = QualType());
3300 friend class ASTContext; // ASTContext creates these.
3302 Expr *getUnderlyingExpr() const { return E; }
3303 QualType getUnderlyingType() const { return UnderlyingType; }
3305 /// \brief Remove a single level of sugar.
3306 QualType desugar() const;
3308 /// \brief Returns whether this type directly provides sugar.
3309 bool isSugared() const;
3311 static bool classof(const Type *T) { return T->getTypeClass() == Decltype; }
3314 /// \brief Internal representation of canonical, dependent
3315 /// decltype(expr) types.
3317 /// This class is used internally by the ASTContext to manage
3318 /// canonical, dependent types, only. Clients will only see instances
3319 /// of this class via DecltypeType nodes.
3320 class DependentDecltypeType : public DecltypeType, public llvm::FoldingSetNode {
3321 const ASTContext &Context;
3324 DependentDecltypeType(const ASTContext &Context, Expr *E);
3326 void Profile(llvm::FoldingSetNodeID &ID) {
3327 Profile(ID, Context, getUnderlyingExpr());
3330 static void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context,
3334 /// \brief A unary type transform, which is a type constructed from another
3335 class UnaryTransformType : public Type {
3342 /// The untransformed type.
3344 /// The transformed type if not dependent, otherwise the same as BaseType.
3345 QualType UnderlyingType;
3349 UnaryTransformType(QualType BaseTy, QualType UnderlyingTy, UTTKind UKind,
3350 QualType CanonicalTy);
3351 friend class ASTContext;
3353 bool isSugared() const { return !isDependentType(); }
3354 QualType desugar() const { return UnderlyingType; }
3356 QualType getUnderlyingType() const { return UnderlyingType; }
3357 QualType getBaseType() const { return BaseType; }
3359 UTTKind getUTTKind() const { return UKind; }
3361 static bool classof(const Type *T) {
3362 return T->getTypeClass() == UnaryTransform;
3366 class TagType : public Type {
3367 /// Stores the TagDecl associated with this type. The decl may point to any
3368 /// TagDecl that declares the entity.
3371 friend class ASTReader;
3374 TagType(TypeClass TC, const TagDecl *D, QualType can);
3377 TagDecl *getDecl() const;
3379 /// @brief Determines whether this type is in the process of being
3381 bool isBeingDefined() const;
3383 static bool classof(const Type *T) {
3384 return T->getTypeClass() >= TagFirst && T->getTypeClass() <= TagLast;
3388 /// RecordType - This is a helper class that allows the use of isa/cast/dyncast
3389 /// to detect TagType objects of structs/unions/classes.
3390 class RecordType : public TagType {
3392 explicit RecordType(const RecordDecl *D)
3393 : TagType(Record, reinterpret_cast<const TagDecl*>(D), QualType()) { }
3394 explicit RecordType(TypeClass TC, RecordDecl *D)
3395 : TagType(TC, reinterpret_cast<const TagDecl*>(D), QualType()) { }
3396 friend class ASTContext; // ASTContext creates these.
3399 RecordDecl *getDecl() const {
3400 return reinterpret_cast<RecordDecl*>(TagType::getDecl());
3403 // FIXME: This predicate is a helper to QualType/Type. It needs to
3404 // recursively check all fields for const-ness. If any field is declared
3405 // const, it needs to return false.
3406 bool hasConstFields() const { return false; }
3408 bool isSugared() const { return false; }
3409 QualType desugar() const { return QualType(this, 0); }
3411 static bool classof(const Type *T) { return T->getTypeClass() == Record; }
3414 /// EnumType - This is a helper class that allows the use of isa/cast/dyncast
3415 /// to detect TagType objects of enums.
3416 class EnumType : public TagType {
3417 explicit EnumType(const EnumDecl *D)
3418 : TagType(Enum, reinterpret_cast<const TagDecl*>(D), QualType()) { }
3419 friend class ASTContext; // ASTContext creates these.
3422 EnumDecl *getDecl() const {
3423 return reinterpret_cast<EnumDecl*>(TagType::getDecl());
3426 bool isSugared() const { return false; }
3427 QualType desugar() const { return QualType(this, 0); }
3429 static bool classof(const Type *T) { return T->getTypeClass() == Enum; }
3432 /// AttributedType - An attributed type is a type to which a type
3433 /// attribute has been applied. The "modified type" is the
3434 /// fully-sugared type to which the attributed type was applied;
3435 /// generally it is not canonically equivalent to the attributed type.
3436 /// The "equivalent type" is the minimally-desugared type which the
3437 /// type is canonically equivalent to.
3439 /// For example, in the following attributed type:
3440 /// int32_t __attribute__((vector_size(16)))
3441 /// - the modified type is the TypedefType for int32_t
3442 /// - the equivalent type is VectorType(16, int32_t)
3443 /// - the canonical type is VectorType(16, int)
3444 class AttributedType : public Type, public llvm::FoldingSetNode {
3446 // It is really silly to have yet another attribute-kind enum, but
3447 // clang::attr::Kind doesn't currently cover the pure type attrs.
3449 // Expression operand.
3453 attr_neon_vector_type,
3454 attr_neon_polyvector_type,
3456 FirstExprOperandKind = attr_address_space,
3457 LastExprOperandKind = attr_neon_polyvector_type,
3459 // Enumerated operand (string or keyword).
3461 attr_objc_ownership,
3465 FirstEnumOperandKind = attr_objc_gc,
3466 LastEnumOperandKind = attr_pcs_vfp,
3486 QualType ModifiedType;
3487 QualType EquivalentType;
3489 friend class ASTContext; // creates these
3491 AttributedType(QualType canon, Kind attrKind,
3492 QualType modified, QualType equivalent)
3493 : Type(Attributed, canon, canon->isDependentType(),
3494 canon->isInstantiationDependentType(),
3495 canon->isVariablyModifiedType(),
3496 canon->containsUnexpandedParameterPack()),
3497 ModifiedType(modified), EquivalentType(equivalent) {
3498 AttributedTypeBits.AttrKind = attrKind;
3502 Kind getAttrKind() const {
3503 return static_cast<Kind>(AttributedTypeBits.AttrKind);
3506 QualType getModifiedType() const { return ModifiedType; }
3507 QualType getEquivalentType() const { return EquivalentType; }
3509 bool isSugared() const { return true; }
3510 QualType desugar() const { return getEquivalentType(); }
3512 bool isMSTypeSpec() const;
3514 bool isCallingConv() const;
3516 void Profile(llvm::FoldingSetNodeID &ID) {
3517 Profile(ID, getAttrKind(), ModifiedType, EquivalentType);
3520 static void Profile(llvm::FoldingSetNodeID &ID, Kind attrKind,
3521 QualType modified, QualType equivalent) {
3522 ID.AddInteger(attrKind);
3523 ID.AddPointer(modified.getAsOpaquePtr());
3524 ID.AddPointer(equivalent.getAsOpaquePtr());
3527 static bool classof(const Type *T) {
3528 return T->getTypeClass() == Attributed;
3532 class TemplateTypeParmType : public Type, public llvm::FoldingSetNode {
3533 // Helper data collector for canonical types.
3534 struct CanonicalTTPTInfo {
3535 unsigned Depth : 15;
3536 unsigned ParameterPack : 1;
3537 unsigned Index : 16;
3541 // Info for the canonical type.
3542 CanonicalTTPTInfo CanTTPTInfo;
3543 // Info for the non-canonical type.
3544 TemplateTypeParmDecl *TTPDecl;
3547 /// Build a non-canonical type.
3548 TemplateTypeParmType(TemplateTypeParmDecl *TTPDecl, QualType Canon)
3549 : Type(TemplateTypeParm, Canon, /*Dependent=*/true,
3550 /*InstantiationDependent=*/true,
3551 /*VariablyModified=*/false,
3552 Canon->containsUnexpandedParameterPack()),
3553 TTPDecl(TTPDecl) { }
3555 /// Build the canonical type.
3556 TemplateTypeParmType(unsigned D, unsigned I, bool PP)
3557 : Type(TemplateTypeParm, QualType(this, 0),
3559 /*InstantiationDependent=*/true,
3560 /*VariablyModified=*/false, PP) {
3561 CanTTPTInfo.Depth = D;
3562 CanTTPTInfo.Index = I;
3563 CanTTPTInfo.ParameterPack = PP;
3566 friend class ASTContext; // ASTContext creates these
3568 const CanonicalTTPTInfo& getCanTTPTInfo() const {
3569 QualType Can = getCanonicalTypeInternal();
3570 return Can->castAs<TemplateTypeParmType>()->CanTTPTInfo;
3574 unsigned getDepth() const { return getCanTTPTInfo().Depth; }
3575 unsigned getIndex() const { return getCanTTPTInfo().Index; }
3576 bool isParameterPack() const { return getCanTTPTInfo().ParameterPack; }
3578 TemplateTypeParmDecl *getDecl() const {
3579 return isCanonicalUnqualified() ? nullptr : TTPDecl;
3582 IdentifierInfo *getIdentifier() const;
3584 bool isSugared() const { return false; }
3585 QualType desugar() const { return QualType(this, 0); }
3587 void Profile(llvm::FoldingSetNodeID &ID) {
3588 Profile(ID, getDepth(), getIndex(), isParameterPack(), getDecl());
3591 static void Profile(llvm::FoldingSetNodeID &ID, unsigned Depth,
3592 unsigned Index, bool ParameterPack,
3593 TemplateTypeParmDecl *TTPDecl) {
3594 ID.AddInteger(Depth);
3595 ID.AddInteger(Index);
3596 ID.AddBoolean(ParameterPack);
3597 ID.AddPointer(TTPDecl);
3600 static bool classof(const Type *T) {
3601 return T->getTypeClass() == TemplateTypeParm;
3605 /// \brief Represents the result of substituting a type for a template
3608 /// Within an instantiated template, all template type parameters have
3609 /// been replaced with these. They are used solely to record that a
3610 /// type was originally written as a template type parameter;
3611 /// therefore they are never canonical.
3612 class SubstTemplateTypeParmType : public Type, public llvm::FoldingSetNode {
3613 // The original type parameter.
3614 const TemplateTypeParmType *Replaced;
3616 SubstTemplateTypeParmType(const TemplateTypeParmType *Param, QualType Canon)
3617 : Type(SubstTemplateTypeParm, Canon, Canon->isDependentType(),
3618 Canon->isInstantiationDependentType(),
3619 Canon->isVariablyModifiedType(),
3620 Canon->containsUnexpandedParameterPack()),
3623 friend class ASTContext;
3626 /// Gets the template parameter that was substituted for.
3627 const TemplateTypeParmType *getReplacedParameter() const {
3631 /// Gets the type that was substituted for the template
3633 QualType getReplacementType() const {
3634 return getCanonicalTypeInternal();
3637 bool isSugared() const { return true; }
3638 QualType desugar() const { return getReplacementType(); }
3640 void Profile(llvm::FoldingSetNodeID &ID) {
3641 Profile(ID, getReplacedParameter(), getReplacementType());
3643 static void Profile(llvm::FoldingSetNodeID &ID,
3644 const TemplateTypeParmType *Replaced,
3645 QualType Replacement) {
3646 ID.AddPointer(Replaced);
3647 ID.AddPointer(Replacement.getAsOpaquePtr());
3650 static bool classof(const Type *T) {
3651 return T->getTypeClass() == SubstTemplateTypeParm;
3655 /// \brief Represents the result of substituting a set of types for a template
3656 /// type parameter pack.
3658 /// When a pack expansion in the source code contains multiple parameter packs
3659 /// and those parameter packs correspond to different levels of template
3660 /// parameter lists, this type node is used to represent a template type
3661 /// parameter pack from an outer level, which has already had its argument pack
3662 /// substituted but that still lives within a pack expansion that itself
3663 /// could not be instantiated. When actually performing a substitution into
3664 /// that pack expansion (e.g., when all template parameters have corresponding
3665 /// arguments), this type will be replaced with the \c SubstTemplateTypeParmType
3666 /// at the current pack substitution index.
3667 class SubstTemplateTypeParmPackType : public Type, public llvm::FoldingSetNode {
3668 /// \brief The original type parameter.
3669 const TemplateTypeParmType *Replaced;
3671 /// \brief A pointer to the set of template arguments that this
3672 /// parameter pack is instantiated with.
3673 const TemplateArgument *Arguments;
3675 /// \brief The number of template arguments in \c Arguments.
3676 unsigned NumArguments;
3678 SubstTemplateTypeParmPackType(const TemplateTypeParmType *Param,
3680 const TemplateArgument &ArgPack);
3682 friend class ASTContext;
3685 IdentifierInfo *getIdentifier() const { return Replaced->getIdentifier(); }
3687 /// Gets the template parameter that was substituted for.
3688 const TemplateTypeParmType *getReplacedParameter() const {
3692 bool isSugared() const { return false; }
3693 QualType desugar() const { return QualType(this, 0); }
3695 TemplateArgument getArgumentPack() const;
3697 void Profile(llvm::FoldingSetNodeID &ID);
3698 static void Profile(llvm::FoldingSetNodeID &ID,
3699 const TemplateTypeParmType *Replaced,
3700 const TemplateArgument &ArgPack);
3702 static bool classof(const Type *T) {
3703 return T->getTypeClass() == SubstTemplateTypeParmPack;
3707 /// \brief Represents a C++11 auto or C++1y decltype(auto) type.
3709 /// These types are usually a placeholder for a deduced type. However, before
3710 /// the initializer is attached, or if the initializer is type-dependent, there
3711 /// is no deduced type and an auto type is canonical. In the latter case, it is
3712 /// also a dependent type.
3713 class AutoType : public Type, public llvm::FoldingSetNode {
3714 AutoType(QualType DeducedType, bool IsDecltypeAuto,
3716 : Type(Auto, DeducedType.isNull() ? QualType(this, 0) : DeducedType,
3717 /*Dependent=*/IsDependent, /*InstantiationDependent=*/IsDependent,
3718 /*VariablyModified=*/false,
3719 /*ContainsParameterPack=*/DeducedType.isNull()
3720 ? false : DeducedType->containsUnexpandedParameterPack()) {
3721 assert((DeducedType.isNull() || !IsDependent) &&
3722 "auto deduced to dependent type");
3723 AutoTypeBits.IsDecltypeAuto = IsDecltypeAuto;
3726 friend class ASTContext; // ASTContext creates these
3729 bool isDecltypeAuto() const { return AutoTypeBits.IsDecltypeAuto; }
3731 bool isSugared() const { return !isCanonicalUnqualified(); }
3732 QualType desugar() const { return getCanonicalTypeInternal(); }
3734 /// \brief Get the type deduced for this auto type, or null if it's either
3735 /// not been deduced or was deduced to a dependent type.
3736 QualType getDeducedType() const {
3737 return !isCanonicalUnqualified() ? getCanonicalTypeInternal() : QualType();
3739 bool isDeduced() const {
3740 return !isCanonicalUnqualified() || isDependentType();
3743 void Profile(llvm::FoldingSetNodeID &ID) {
3744 Profile(ID, getDeducedType(), isDecltypeAuto(),
3748 static void Profile(llvm::FoldingSetNodeID &ID, QualType Deduced,
3749 bool IsDecltypeAuto, bool IsDependent) {
3750 ID.AddPointer(Deduced.getAsOpaquePtr());
3751 ID.AddBoolean(IsDecltypeAuto);
3752 ID.AddBoolean(IsDependent);
3755 static bool classof(const Type *T) {
3756 return T->getTypeClass() == Auto;
3760 /// \brief Represents a type template specialization; the template
3761 /// must be a class template, a type alias template, or a template
3762 /// template parameter. A template which cannot be resolved to one of
3763 /// these, e.g. because it is written with a dependent scope
3764 /// specifier, is instead represented as a
3765 /// @c DependentTemplateSpecializationType.
3767 /// A non-dependent template specialization type is always "sugar",
3768 /// typically for a @c RecordType. For example, a class template
3769 /// specialization type of @c vector<int> will refer to a tag type for
3770 /// the instantiation @c std::vector<int, std::allocator<int>>
3772 /// Template specializations are dependent if either the template or
3773 /// any of the template arguments are dependent, in which case the
3774 /// type may also be canonical.
3776 /// Instances of this type are allocated with a trailing array of
3777 /// TemplateArguments, followed by a QualType representing the
3778 /// non-canonical aliased type when the template is a type alias
3780 class TemplateSpecializationType
3781 : public Type, public llvm::FoldingSetNode {
3782 /// \brief The name of the template being specialized. This is
3783 /// either a TemplateName::Template (in which case it is a
3784 /// ClassTemplateDecl*, a TemplateTemplateParmDecl*, or a
3785 /// TypeAliasTemplateDecl*), a
3786 /// TemplateName::SubstTemplateTemplateParmPack, or a
3787 /// TemplateName::SubstTemplateTemplateParm (in which case the
3788 /// replacement must, recursively, be one of these).
3789 TemplateName Template;
3791 /// \brief - The number of template arguments named in this class
3792 /// template specialization.
3793 unsigned NumArgs : 31;
3795 /// \brief Whether this template specialization type is a substituted
3799 TemplateSpecializationType(TemplateName T,
3800 const TemplateArgument *Args,
3801 unsigned NumArgs, QualType Canon,
3804 friend class ASTContext; // ASTContext creates these
3807 /// \brief Determine whether any of the given template arguments are
3809 static bool anyDependentTemplateArguments(const TemplateArgumentLoc *Args,
3811 bool &InstantiationDependent);
3813 static bool anyDependentTemplateArguments(const TemplateArgumentListInfo &,
3814 bool &InstantiationDependent);
3816 /// \brief Print a template argument list, including the '<' and '>'
3817 /// enclosing the template arguments.
3818 static void PrintTemplateArgumentList(raw_ostream &OS,
3819 const TemplateArgument *Args,
3821 const PrintingPolicy &Policy,
3822 bool SkipBrackets = false);
3824 static void PrintTemplateArgumentList(raw_ostream &OS,
3825 const TemplateArgumentLoc *Args,
3827 const PrintingPolicy &Policy);
3829 static void PrintTemplateArgumentList(raw_ostream &OS,
3830 const TemplateArgumentListInfo &,
3831 const PrintingPolicy &Policy);
3833 /// True if this template specialization type matches a current
3834 /// instantiation in the context in which it is found.
3835 bool isCurrentInstantiation() const {
3836 return isa<InjectedClassNameType>(getCanonicalTypeInternal());
3839 /// \brief Determine if this template specialization type is for a type alias
3840 /// template that has been substituted.
3842 /// Nearly every template specialization type whose template is an alias
3843 /// template will be substituted. However, this is not the case when
3844 /// the specialization contains a pack expansion but the template alias
3845 /// does not have a corresponding parameter pack, e.g.,
3848 /// template<typename T, typename U, typename V> struct S;
3849 /// template<typename T, typename U> using A = S<T, int, U>;
3850 /// template<typename... Ts> struct X {
3851 /// typedef A<Ts...> type; // not a type alias
3854 bool isTypeAlias() const { return TypeAlias; }
3856 /// Get the aliased type, if this is a specialization of a type alias
3858 QualType getAliasedType() const {
3859 assert(isTypeAlias() && "not a type alias template specialization");
3860 return *reinterpret_cast<const QualType*>(end());
3863 typedef const TemplateArgument * iterator;
3865 iterator begin() const { return getArgs(); }
3866 iterator end() const; // defined inline in TemplateBase.h
3868 /// \brief Retrieve the name of the template that we are specializing.
3869 TemplateName getTemplateName() const { return Template; }
3871 /// \brief Retrieve the template arguments.
3872 const TemplateArgument *getArgs() const {
3873 return reinterpret_cast<const TemplateArgument *>(this + 1);
3876 /// \brief Retrieve the number of template arguments.
3877 unsigned getNumArgs() const { return NumArgs; }
3879 /// \brief Retrieve a specific template argument as a type.
3880 /// \pre @c isArgType(Arg)
3881 const TemplateArgument &getArg(unsigned Idx) const; // in TemplateBase.h
3883 bool isSugared() const {
3884 return !isDependentType() || isCurrentInstantiation() || isTypeAlias();
3886 QualType desugar() const { return getCanonicalTypeInternal(); }
3888 void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Ctx) {
3889 Profile(ID, Template, getArgs(), NumArgs, Ctx);
3891 getAliasedType().Profile(ID);
3894 static void Profile(llvm::FoldingSetNodeID &ID, TemplateName T,
3895 const TemplateArgument *Args,
3897 const ASTContext &Context);
3899 static bool classof(const Type *T) {
3900 return T->getTypeClass() == TemplateSpecialization;
3904 /// \brief The injected class name of a C++ class template or class
3905 /// template partial specialization. Used to record that a type was
3906 /// spelled with a bare identifier rather than as a template-id; the
3907 /// equivalent for non-templated classes is just RecordType.
3909 /// Injected class name types are always dependent. Template
3910 /// instantiation turns these into RecordTypes.
3912 /// Injected class name types are always canonical. This works
3913 /// because it is impossible to compare an injected class name type
3914 /// with the corresponding non-injected template type, for the same
3915 /// reason that it is impossible to directly compare template
3916 /// parameters from different dependent contexts: injected class name
3917 /// types can only occur within the scope of a particular templated
3918 /// declaration, and within that scope every template specialization
3919 /// will canonicalize to the injected class name (when appropriate
3920 /// according to the rules of the language).
3921 class InjectedClassNameType : public Type {
3922 CXXRecordDecl *Decl;
3924 /// The template specialization which this type represents.
3926 /// template <class T> class A { ... };
3927 /// this is A<T>, whereas in
3928 /// template <class X, class Y> class A<B<X,Y> > { ... };
3929 /// this is A<B<X,Y> >.
3931 /// It is always unqualified, always a template specialization type,
3932 /// and always dependent.
3933 QualType InjectedType;
3935 friend class ASTContext; // ASTContext creates these.
3936 friend class ASTReader; // FIXME: ASTContext::getInjectedClassNameType is not
3937 // currently suitable for AST reading, too much
3938 // interdependencies.
3939 InjectedClassNameType(CXXRecordDecl *D, QualType TST)
3940 : Type(InjectedClassName, QualType(), /*Dependent=*/true,
3941 /*InstantiationDependent=*/true,
3942 /*VariablyModified=*/false,
3943 /*ContainsUnexpandedParameterPack=*/false),
3944 Decl(D), InjectedType(TST) {
3945 assert(isa<TemplateSpecializationType>(TST));
3946 assert(!TST.hasQualifiers());
3947 assert(TST->isDependentType());
3951 QualType getInjectedSpecializationType() const { return InjectedType; }
3952 const TemplateSpecializationType *getInjectedTST() const {
3953 return cast<TemplateSpecializationType>(InjectedType.getTypePtr());
3956 CXXRecordDecl *getDecl() const;
3958 bool isSugared() const { return false; }
3959 QualType desugar() const { return QualType(this, 0); }
3961 static bool classof(const Type *T) {
3962 return T->getTypeClass() == InjectedClassName;
3966 /// \brief The kind of a tag type.
3968 /// \brief The "struct" keyword.
3970 /// \brief The "__interface" keyword.
3972 /// \brief The "union" keyword.
3974 /// \brief The "class" keyword.
3976 /// \brief The "enum" keyword.
3980 /// \brief The elaboration keyword that precedes a qualified type name or
3981 /// introduces an elaborated-type-specifier.
3982 enum ElaboratedTypeKeyword {
3983 /// \brief The "struct" keyword introduces the elaborated-type-specifier.
3985 /// \brief The "__interface" keyword introduces the elaborated-type-specifier.
3987 /// \brief The "union" keyword introduces the elaborated-type-specifier.
3989 /// \brief The "class" keyword introduces the elaborated-type-specifier.
3991 /// \brief The "enum" keyword introduces the elaborated-type-specifier.
3993 /// \brief The "typename" keyword precedes the qualified type name, e.g.,
3994 /// \c typename T::type.
3996 /// \brief No keyword precedes the qualified type name.
4000 /// A helper class for Type nodes having an ElaboratedTypeKeyword.
4001 /// The keyword in stored in the free bits of the base class.
4002 /// Also provides a few static helpers for converting and printing
4003 /// elaborated type keyword and tag type kind enumerations.
4004 class TypeWithKeyword : public Type {
4006 TypeWithKeyword(ElaboratedTypeKeyword Keyword, TypeClass tc,
4007 QualType Canonical, bool Dependent,
4008 bool InstantiationDependent, bool VariablyModified,
4009 bool ContainsUnexpandedParameterPack)
4010 : Type(tc, Canonical, Dependent, InstantiationDependent, VariablyModified,
4011 ContainsUnexpandedParameterPack) {
4012 TypeWithKeywordBits.Keyword = Keyword;
4016 ElaboratedTypeKeyword getKeyword() const {
4017 return static_cast<ElaboratedTypeKeyword>(TypeWithKeywordBits.Keyword);
4020 /// getKeywordForTypeSpec - Converts a type specifier (DeclSpec::TST)
4021 /// into an elaborated type keyword.
4022 static ElaboratedTypeKeyword getKeywordForTypeSpec(unsigned TypeSpec);
4024 /// getTagTypeKindForTypeSpec - Converts a type specifier (DeclSpec::TST)
4025 /// into a tag type kind. It is an error to provide a type specifier
4026 /// which *isn't* a tag kind here.
4027 static TagTypeKind getTagTypeKindForTypeSpec(unsigned TypeSpec);
4029 /// getKeywordForTagDeclKind - Converts a TagTypeKind into an
4030 /// elaborated type keyword.
4031 static ElaboratedTypeKeyword getKeywordForTagTypeKind(TagTypeKind Tag);
4033 /// getTagTypeKindForKeyword - Converts an elaborated type keyword into
4034 // a TagTypeKind. It is an error to provide an elaborated type keyword
4035 /// which *isn't* a tag kind here.
4036 static TagTypeKind getTagTypeKindForKeyword(ElaboratedTypeKeyword Keyword);
4038 static bool KeywordIsTagTypeKind(ElaboratedTypeKeyword Keyword);
4040 static StringRef getKeywordName(ElaboratedTypeKeyword Keyword);
4042 static StringRef getTagTypeKindName(TagTypeKind Kind) {
4043 return getKeywordName(getKeywordForTagTypeKind(Kind));
4046 class CannotCastToThisType {};
4047 static CannotCastToThisType classof(const Type *);
4050 /// \brief Represents a type that was referred to using an elaborated type
4051 /// keyword, e.g., struct S, or via a qualified name, e.g., N::M::type,
4054 /// This type is used to keep track of a type name as written in the
4055 /// source code, including tag keywords and any nested-name-specifiers.
4056 /// The type itself is always "sugar", used to express what was written
4057 /// in the source code but containing no additional semantic information.
4058 class ElaboratedType : public TypeWithKeyword, public llvm::FoldingSetNode {
4060 /// \brief The nested name specifier containing the qualifier.
4061 NestedNameSpecifier *NNS;
4063 /// \brief The type that this qualified name refers to.
4066 ElaboratedType(ElaboratedTypeKeyword Keyword, NestedNameSpecifier *NNS,
4067 QualType NamedType, QualType CanonType)
4068 : TypeWithKeyword(Keyword, Elaborated, CanonType,
4069 NamedType->isDependentType(),
4070 NamedType->isInstantiationDependentType(),
4071 NamedType->isVariablyModifiedType(),
4072 NamedType->containsUnexpandedParameterPack()),
4073 NNS(NNS), NamedType(NamedType) {
4074 assert(!(Keyword == ETK_None && NNS == nullptr) &&
4075 "ElaboratedType cannot have elaborated type keyword "
4076 "and name qualifier both null.");
4079 friend class ASTContext; // ASTContext creates these
4084 /// \brief Retrieve the qualification on this type.
4085 NestedNameSpecifier *getQualifier() const { return NNS; }
4087 /// \brief Retrieve the type named by the qualified-id.
4088 QualType getNamedType() const { return NamedType; }
4090 /// \brief Remove a single level of sugar.
4091 QualType desugar() const { return getNamedType(); }
4093 /// \brief Returns whether this type directly provides sugar.
4094 bool isSugared() const { return true; }
4096 void Profile(llvm::FoldingSetNodeID &ID) {
4097 Profile(ID, getKeyword(), NNS, NamedType);
4100 static void Profile(llvm::FoldingSetNodeID &ID, ElaboratedTypeKeyword Keyword,
4101 NestedNameSpecifier *NNS, QualType NamedType) {
4102 ID.AddInteger(Keyword);
4104 NamedType.Profile(ID);
4107 static bool classof(const Type *T) {
4108 return T->getTypeClass() == Elaborated;
4112 /// \brief Represents a qualified type name for which the type name is
4115 /// DependentNameType represents a class of dependent types that involve a
4116 /// possibly dependent nested-name-specifier (e.g., "T::") followed by a
4117 /// name of a type. The DependentNameType may start with a "typename" (for a
4118 /// typename-specifier), "class", "struct", "union", or "enum" (for a
4119 /// dependent elaborated-type-specifier), or nothing (in contexts where we
4120 /// know that we must be referring to a type, e.g., in a base class specifier).
4121 /// Typically the nested-name-specifier is dependent, but in MSVC compatibility
4122 /// mode, this type is used with non-dependent names to delay name lookup until
4124 class DependentNameType : public TypeWithKeyword, public llvm::FoldingSetNode {
4126 /// \brief The nested name specifier containing the qualifier.
4127 NestedNameSpecifier *NNS;
4129 /// \brief The type that this typename specifier refers to.
4130 const IdentifierInfo *Name;
4132 DependentNameType(ElaboratedTypeKeyword Keyword, NestedNameSpecifier *NNS,
4133 const IdentifierInfo *Name, QualType CanonType)
4134 : TypeWithKeyword(Keyword, DependentName, CanonType, /*Dependent=*/true,
4135 /*InstantiationDependent=*/true,
4136 /*VariablyModified=*/false,
4137 NNS->containsUnexpandedParameterPack()),
4138 NNS(NNS), Name(Name) {}
4140 friend class ASTContext; // ASTContext creates these
4143 /// \brief Retrieve the qualification on this type.
4144 NestedNameSpecifier *getQualifier() const { return NNS; }
4146 /// \brief Retrieve the type named by the typename specifier as an
4149 /// This routine will return a non-NULL identifier pointer when the
4150 /// form of the original typename was terminated by an identifier,
4151 /// e.g., "typename T::type".
4152 const IdentifierInfo *getIdentifier() const {
4156 bool isSugared() const { return false; }
4157 QualType desugar() const { return QualType(this, 0); }
4159 void Profile(llvm::FoldingSetNodeID &ID) {
4160 Profile(ID, getKeyword(), NNS, Name);
4163 static void Profile(llvm::FoldingSetNodeID &ID, ElaboratedTypeKeyword Keyword,
4164 NestedNameSpecifier *NNS, const IdentifierInfo *Name) {
4165 ID.AddInteger(Keyword);
4167 ID.AddPointer(Name);
4170 static bool classof(const Type *T) {
4171 return T->getTypeClass() == DependentName;
4175 /// DependentTemplateSpecializationType - Represents a template
4176 /// specialization type whose template cannot be resolved, e.g.
4177 /// A<T>::template B<T>
4178 class DependentTemplateSpecializationType :
4179 public TypeWithKeyword, public llvm::FoldingSetNode {
4181 /// \brief The nested name specifier containing the qualifier.
4182 NestedNameSpecifier *NNS;
4184 /// \brief The identifier of the template.
4185 const IdentifierInfo *Name;
4187 /// \brief - The number of template arguments named in this class
4188 /// template specialization.
4191 const TemplateArgument *getArgBuffer() const {
4192 return reinterpret_cast<const TemplateArgument*>(this+1);
4194 TemplateArgument *getArgBuffer() {
4195 return reinterpret_cast<TemplateArgument*>(this+1);
4198 DependentTemplateSpecializationType(ElaboratedTypeKeyword Keyword,
4199 NestedNameSpecifier *NNS,
4200 const IdentifierInfo *Name,
4202 const TemplateArgument *Args,
4205 friend class ASTContext; // ASTContext creates these
4208 NestedNameSpecifier *getQualifier() const { return NNS; }
4209 const IdentifierInfo *getIdentifier() const { return Name; }
4211 /// \brief Retrieve the template arguments.
4212 const TemplateArgument *getArgs() const {
4213 return getArgBuffer();
4216 /// \brief Retrieve the number of template arguments.
4217 unsigned getNumArgs() const { return NumArgs; }
4219 const TemplateArgument &getArg(unsigned Idx) const; // in TemplateBase.h
4221 typedef const TemplateArgument * iterator;
4222 iterator begin() const { return getArgs(); }
4223 iterator end() const; // inline in TemplateBase.h
4225 bool isSugared() const { return false; }
4226 QualType desugar() const { return QualType(this, 0); }
4228 void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context) {
4229 Profile(ID, Context, getKeyword(), NNS, Name, NumArgs, getArgs());
4232 static void Profile(llvm::FoldingSetNodeID &ID,
4233 const ASTContext &Context,
4234 ElaboratedTypeKeyword Keyword,
4235 NestedNameSpecifier *Qualifier,
4236 const IdentifierInfo *Name,
4238 const TemplateArgument *Args);
4240 static bool classof(const Type *T) {
4241 return T->getTypeClass() == DependentTemplateSpecialization;
4245 /// \brief Represents a pack expansion of types.
4247 /// Pack expansions are part of C++0x variadic templates. A pack
4248 /// expansion contains a pattern, which itself contains one or more
4249 /// "unexpanded" parameter packs. When instantiated, a pack expansion
4250 /// produces a series of types, each instantiated from the pattern of
4251 /// the expansion, where the Ith instantiation of the pattern uses the
4252 /// Ith arguments bound to each of the unexpanded parameter packs. The
4253 /// pack expansion is considered to "expand" these unexpanded
4254 /// parameter packs.
4257 /// template<typename ...Types> struct tuple;
4259 /// template<typename ...Types>
4260 /// struct tuple_of_references {
4261 /// typedef tuple<Types&...> type;
4265 /// Here, the pack expansion \c Types&... is represented via a
4266 /// PackExpansionType whose pattern is Types&.
4267 class PackExpansionType : public Type, public llvm::FoldingSetNode {
4268 /// \brief The pattern of the pack expansion.
4271 /// \brief The number of expansions that this pack expansion will
4272 /// generate when substituted (+1), or indicates that
4274 /// This field will only have a non-zero value when some of the parameter
4275 /// packs that occur within the pattern have been substituted but others have
4277 unsigned NumExpansions;
4279 PackExpansionType(QualType Pattern, QualType Canon,
4280 Optional<unsigned> NumExpansions)
4281 : Type(PackExpansion, Canon, /*Dependent=*/Pattern->isDependentType(),
4282 /*InstantiationDependent=*/true,
4283 /*VariablyModified=*/Pattern->isVariablyModifiedType(),
4284 /*ContainsUnexpandedParameterPack=*/false),
4286 NumExpansions(NumExpansions? *NumExpansions + 1: 0) { }
4288 friend class ASTContext; // ASTContext creates these
4291 /// \brief Retrieve the pattern of this pack expansion, which is the
4292 /// type that will be repeatedly instantiated when instantiating the
4293 /// pack expansion itself.
4294 QualType getPattern() const { return Pattern; }
4296 /// \brief Retrieve the number of expansions that this pack expansion will
4297 /// generate, if known.
4298 Optional<unsigned> getNumExpansions() const {
4300 return NumExpansions - 1;
4305 bool isSugared() const { return !Pattern->isDependentType(); }
4306 QualType desugar() const { return isSugared() ? Pattern : QualType(this, 0); }
4308 void Profile(llvm::FoldingSetNodeID &ID) {
4309 Profile(ID, getPattern(), getNumExpansions());
4312 static void Profile(llvm::FoldingSetNodeID &ID, QualType Pattern,
4313 Optional<unsigned> NumExpansions) {
4314 ID.AddPointer(Pattern.getAsOpaquePtr());
4315 ID.AddBoolean(NumExpansions.hasValue());
4317 ID.AddInteger(*NumExpansions);
4320 static bool classof(const Type *T) {
4321 return T->getTypeClass() == PackExpansion;
4325 /// ObjCObjectType - Represents a class type in Objective C.
4326 /// Every Objective C type is a combination of a base type and a
4327 /// list of protocols.
4329 /// Given the following declarations:
4335 /// 'C' is an ObjCInterfaceType C. It is sugar for an ObjCObjectType
4336 /// with base C and no protocols.
4338 /// 'C<P>' is an ObjCObjectType with base C and protocol list [P].
4340 /// 'id' is a TypedefType which is sugar for an ObjCObjectPointerType whose
4341 /// pointee is an ObjCObjectType with base BuiltinType::ObjCIdType
4342 /// and no protocols.
4344 /// 'id<P>' is an ObjCObjectPointerType whose pointee is an ObjCObjectType
4345 /// with base BuiltinType::ObjCIdType and protocol list [P]. Eventually
4346 /// this should get its own sugar class to better represent the source.
4347 class ObjCObjectType : public Type {
4348 // ObjCObjectType.NumProtocols - the number of protocols stored
4349 // after the ObjCObjectPointerType node.
4351 // These protocols are those written directly on the type. If
4352 // protocol qualifiers ever become additive, the iterators will need
4353 // to get kindof complicated.
4355 // In the canonical object type, these are sorted alphabetically
4358 /// Either a BuiltinType or an InterfaceType or sugar for either.
4361 ObjCProtocolDecl * const *getProtocolStorage() const {
4362 return const_cast<ObjCObjectType*>(this)->getProtocolStorage();
4365 ObjCProtocolDecl **getProtocolStorage();
4368 ObjCObjectType(QualType Canonical, QualType Base,
4369 ObjCProtocolDecl * const *Protocols, unsigned NumProtocols);
4371 enum Nonce_ObjCInterface { Nonce_ObjCInterface };
4372 ObjCObjectType(enum Nonce_ObjCInterface)
4373 : Type(ObjCInterface, QualType(), false, false, false, false),
4374 BaseType(QualType(this_(), 0)) {
4375 ObjCObjectTypeBits.NumProtocols = 0;
4379 /// getBaseType - Gets the base type of this object type. This is
4380 /// always (possibly sugar for) one of:
4381 /// - the 'id' builtin type (as opposed to the 'id' type visible to the
4382 /// user, which is a typedef for an ObjCObjectPointerType)
4383 /// - the 'Class' builtin type (same caveat)
4384 /// - an ObjCObjectType (currently always an ObjCInterfaceType)
4385 QualType getBaseType() const { return BaseType; }
4387 bool isObjCId() const {
4388 return getBaseType()->isSpecificBuiltinType(BuiltinType::ObjCId);
4390 bool isObjCClass() const {
4391 return getBaseType()->isSpecificBuiltinType(BuiltinType::ObjCClass);
4393 bool isObjCUnqualifiedId() const { return qual_empty() && isObjCId(); }
4394 bool isObjCUnqualifiedClass() const { return qual_empty() && isObjCClass(); }
4395 bool isObjCUnqualifiedIdOrClass() const {
4396 if (!qual_empty()) return false;
4397 if (const BuiltinType *T = getBaseType()->getAs<BuiltinType>())
4398 return T->getKind() == BuiltinType::ObjCId ||
4399 T->getKind() == BuiltinType::ObjCClass;
4402 bool isObjCQualifiedId() const { return !qual_empty() && isObjCId(); }
4403 bool isObjCQualifiedClass() const { return !qual_empty() && isObjCClass(); }
4405 /// Gets the interface declaration for this object type, if the base type
4406 /// really is an interface.
4407 ObjCInterfaceDecl *getInterface() const;
4409 typedef ObjCProtocolDecl * const *qual_iterator;
4410 typedef llvm::iterator_range<qual_iterator> qual_range;
4412 qual_range quals() const { return qual_range(qual_begin(), qual_end()); }
4413 qual_iterator qual_begin() const { return getProtocolStorage(); }
4414 qual_iterator qual_end() const { return qual_begin() + getNumProtocols(); }
4416 bool qual_empty() const { return getNumProtocols() == 0; }
4418 /// getNumProtocols - Return the number of qualifying protocols in this
4419 /// interface type, or 0 if there are none.
4420 unsigned getNumProtocols() const { return ObjCObjectTypeBits.NumProtocols; }
4422 /// \brief Fetch a protocol by index.
4423 ObjCProtocolDecl *getProtocol(unsigned I) const {
4424 assert(I < getNumProtocols() && "Out-of-range protocol access");
4425 return qual_begin()[I];
4428 bool isSugared() const { return false; }
4429 QualType desugar() const { return QualType(this, 0); }
4431 static bool classof(const Type *T) {
4432 return T->getTypeClass() == ObjCObject ||
4433 T->getTypeClass() == ObjCInterface;
4437 /// ObjCObjectTypeImpl - A class providing a concrete implementation
4438 /// of ObjCObjectType, so as to not increase the footprint of
4439 /// ObjCInterfaceType. Code outside of ASTContext and the core type
4440 /// system should not reference this type.
4441 class ObjCObjectTypeImpl : public ObjCObjectType, public llvm::FoldingSetNode {
4442 friend class ASTContext;
4444 // If anyone adds fields here, ObjCObjectType::getProtocolStorage()
4445 // will need to be modified.
4447 ObjCObjectTypeImpl(QualType Canonical, QualType Base,
4448 ObjCProtocolDecl * const *Protocols,
4449 unsigned NumProtocols)
4450 : ObjCObjectType(Canonical, Base, Protocols, NumProtocols) {}
4453 void Profile(llvm::FoldingSetNodeID &ID);
4454 static void Profile(llvm::FoldingSetNodeID &ID,
4456 ObjCProtocolDecl *const *protocols,
4457 unsigned NumProtocols);
4460 inline ObjCProtocolDecl **ObjCObjectType::getProtocolStorage() {
4461 return reinterpret_cast<ObjCProtocolDecl**>(
4462 static_cast<ObjCObjectTypeImpl*>(this) + 1);
4465 /// ObjCInterfaceType - Interfaces are the core concept in Objective-C for
4466 /// object oriented design. They basically correspond to C++ classes. There
4467 /// are two kinds of interface types, normal interfaces like "NSString" and
4468 /// qualified interfaces, which are qualified with a protocol list like
4469 /// "NSString<NSCopyable, NSAmazing>".
4471 /// ObjCInterfaceType guarantees the following properties when considered
4472 /// as a subtype of its superclass, ObjCObjectType:
4473 /// - There are no protocol qualifiers. To reinforce this, code which
4474 /// tries to invoke the protocol methods via an ObjCInterfaceType will
4475 /// fail to compile.
4476 /// - It is its own base type. That is, if T is an ObjCInterfaceType*,
4477 /// T->getBaseType() == QualType(T, 0).
4478 class ObjCInterfaceType : public ObjCObjectType {
4479 mutable ObjCInterfaceDecl *Decl;
4481 ObjCInterfaceType(const ObjCInterfaceDecl *D)
4482 : ObjCObjectType(Nonce_ObjCInterface),
4483 Decl(const_cast<ObjCInterfaceDecl*>(D)) {}
4484 friend class ASTContext; // ASTContext creates these.
4485 friend class ASTReader;
4486 friend class ObjCInterfaceDecl;
4489 /// getDecl - Get the declaration of this interface.
4490 ObjCInterfaceDecl *getDecl() const { return Decl; }
4492 bool isSugared() const { return false; }
4493 QualType desugar() const { return QualType(this, 0); }
4495 static bool classof(const Type *T) {
4496 return T->getTypeClass() == ObjCInterface;
4499 // Nonsense to "hide" certain members of ObjCObjectType within this
4500 // class. People asking for protocols on an ObjCInterfaceType are
4501 // not going to get what they want: ObjCInterfaceTypes are
4502 // guaranteed to have no protocols.
4512 inline ObjCInterfaceDecl *ObjCObjectType::getInterface() const {
4513 if (const ObjCInterfaceType *T =
4514 getBaseType()->getAs<ObjCInterfaceType>())
4515 return T->getDecl();
4519 /// ObjCObjectPointerType - Used to represent a pointer to an
4520 /// Objective C object. These are constructed from pointer
4521 /// declarators when the pointee type is an ObjCObjectType (or sugar
4522 /// for one). In addition, the 'id' and 'Class' types are typedefs
4523 /// for these, and the protocol-qualified types 'id<P>' and 'Class<P>'
4524 /// are translated into these.
4526 /// Pointers to pointers to Objective C objects are still PointerTypes;
4527 /// only the first level of pointer gets it own type implementation.
4528 class ObjCObjectPointerType : public Type, public llvm::FoldingSetNode {
4529 QualType PointeeType;
4531 ObjCObjectPointerType(QualType Canonical, QualType Pointee)
4532 : Type(ObjCObjectPointer, Canonical, false, false, false, false),
4533 PointeeType(Pointee) {}
4534 friend class ASTContext; // ASTContext creates these.
4537 /// getPointeeType - Gets the type pointed to by this ObjC pointer.
4538 /// The result will always be an ObjCObjectType or sugar thereof.
4539 QualType getPointeeType() const { return PointeeType; }
4541 /// getObjCObjectType - Gets the type pointed to by this ObjC
4542 /// pointer. This method always returns non-null.
4544 /// This method is equivalent to getPointeeType() except that
4545 /// it discards any typedefs (or other sugar) between this
4546 /// type and the "outermost" object type. So for:
4548 /// \@class A; \@protocol P; \@protocol Q;
4549 /// typedef A<P> AP;
4551 /// typedef A1<P> A1P;
4552 /// typedef A1P<Q> A1PQ;
4554 /// For 'A*', getObjectType() will return 'A'.
4555 /// For 'A<P>*', getObjectType() will return 'A<P>'.
4556 /// For 'AP*', getObjectType() will return 'A<P>'.
4557 /// For 'A1*', getObjectType() will return 'A'.
4558 /// For 'A1<P>*', getObjectType() will return 'A1<P>'.
4559 /// For 'A1P*', getObjectType() will return 'A1<P>'.
4560 /// For 'A1PQ*', getObjectType() will return 'A1<Q>', because
4561 /// adding protocols to a protocol-qualified base discards the
4562 /// old qualifiers (for now). But if it didn't, getObjectType()
4563 /// would return 'A1P<Q>' (and we'd have to make iterating over
4564 /// qualifiers more complicated).
4565 const ObjCObjectType *getObjectType() const {
4566 return PointeeType->castAs<ObjCObjectType>();
4569 /// getInterfaceType - If this pointer points to an Objective C
4570 /// \@interface type, gets the type for that interface. Any protocol
4571 /// qualifiers on the interface are ignored.
4573 /// \return null if the base type for this pointer is 'id' or 'Class'
4574 const ObjCInterfaceType *getInterfaceType() const {
4575 return getObjectType()->getBaseType()->getAs<ObjCInterfaceType>();
4578 /// getInterfaceDecl - If this pointer points to an Objective \@interface
4579 /// type, gets the declaration for that interface.
4581 /// \return null if the base type for this pointer is 'id' or 'Class'
4582 ObjCInterfaceDecl *getInterfaceDecl() const {
4583 return getObjectType()->getInterface();
4586 /// isObjCIdType - True if this is equivalent to the 'id' type, i.e. if
4587 /// its object type is the primitive 'id' type with no protocols.
4588 bool isObjCIdType() const {
4589 return getObjectType()->isObjCUnqualifiedId();
4592 /// isObjCClassType - True if this is equivalent to the 'Class' type,
4593 /// i.e. if its object tive is the primitive 'Class' type with no protocols.
4594 bool isObjCClassType() const {
4595 return getObjectType()->isObjCUnqualifiedClass();
4598 /// isObjCQualifiedIdType - True if this is equivalent to 'id<P>' for some
4599 /// non-empty set of protocols.
4600 bool isObjCQualifiedIdType() const {
4601 return getObjectType()->isObjCQualifiedId();
4604 /// isObjCQualifiedClassType - True if this is equivalent to 'Class<P>' for
4605 /// some non-empty set of protocols.
4606 bool isObjCQualifiedClassType() const {
4607 return getObjectType()->isObjCQualifiedClass();
4610 /// An iterator over the qualifiers on the object type. Provided
4611 /// for convenience. This will always iterate over the full set of
4612 /// protocols on a type, not just those provided directly.
4613 typedef ObjCObjectType::qual_iterator qual_iterator;
4614 typedef llvm::iterator_range<qual_iterator> qual_range;
4616 qual_range quals() const { return qual_range(qual_begin(), qual_end()); }
4617 qual_iterator qual_begin() const {
4618 return getObjectType()->qual_begin();
4620 qual_iterator qual_end() const {
4621 return getObjectType()->qual_end();
4623 bool qual_empty() const { return getObjectType()->qual_empty(); }
4625 /// getNumProtocols - Return the number of qualifying protocols on
4626 /// the object type.
4627 unsigned getNumProtocols() const {
4628 return getObjectType()->getNumProtocols();
4631 /// \brief Retrieve a qualifying protocol by index on the object
4633 ObjCProtocolDecl *getProtocol(unsigned I) const {
4634 return getObjectType()->getProtocol(I);
4637 bool isSugared() const { return false; }
4638 QualType desugar() const { return QualType(this, 0); }
4640 void Profile(llvm::FoldingSetNodeID &ID) {
4641 Profile(ID, getPointeeType());
4643 static void Profile(llvm::FoldingSetNodeID &ID, QualType T) {
4644 ID.AddPointer(T.getAsOpaquePtr());
4646 static bool classof(const Type *T) {
4647 return T->getTypeClass() == ObjCObjectPointer;
4651 class AtomicType : public Type, public llvm::FoldingSetNode {
4654 AtomicType(QualType ValTy, QualType Canonical)
4655 : Type(Atomic, Canonical, ValTy->isDependentType(),
4656 ValTy->isInstantiationDependentType(),
4657 ValTy->isVariablyModifiedType(),
4658 ValTy->containsUnexpandedParameterPack()),
4660 friend class ASTContext; // ASTContext creates these.
4663 /// getValueType - Gets the type contained by this atomic type, i.e.
4664 /// the type returned by performing an atomic load of this atomic type.
4665 QualType getValueType() const { return ValueType; }
4667 bool isSugared() const { return false; }
4668 QualType desugar() const { return QualType(this, 0); }
4670 void Profile(llvm::FoldingSetNodeID &ID) {
4671 Profile(ID, getValueType());
4673 static void Profile(llvm::FoldingSetNodeID &ID, QualType T) {
4674 ID.AddPointer(T.getAsOpaquePtr());
4676 static bool classof(const Type *T) {
4677 return T->getTypeClass() == Atomic;
4681 /// A qualifier set is used to build a set of qualifiers.
4682 class QualifierCollector : public Qualifiers {
4684 QualifierCollector(Qualifiers Qs = Qualifiers()) : Qualifiers(Qs) {}
4686 /// Collect any qualifiers on the given type and return an
4687 /// unqualified type. The qualifiers are assumed to be consistent
4688 /// with those already in the type.
4689 const Type *strip(QualType type) {
4690 addFastQualifiers(type.getLocalFastQualifiers());
4691 if (!type.hasLocalNonFastQualifiers())
4692 return type.getTypePtrUnsafe();
4694 const ExtQuals *extQuals = type.getExtQualsUnsafe();
4695 addConsistentQualifiers(extQuals->getQualifiers());
4696 return extQuals->getBaseType();
4699 /// Apply the collected qualifiers to the given type.
4700 QualType apply(const ASTContext &Context, QualType QT) const;
4702 /// Apply the collected qualifiers to the given type.
4703 QualType apply(const ASTContext &Context, const Type* T) const;
4707 // Inline function definitions.
4709 inline SplitQualType SplitQualType::getSingleStepDesugaredType() const {
4710 SplitQualType desugar =
4711 Ty->getLocallyUnqualifiedSingleStepDesugaredType().split();
4712 desugar.Quals.addConsistentQualifiers(Quals);
4716 inline const Type *QualType::getTypePtr() const {
4717 return getCommonPtr()->BaseType;
4720 inline const Type *QualType::getTypePtrOrNull() const {
4721 return (isNull() ? nullptr : getCommonPtr()->BaseType);
4724 inline SplitQualType QualType::split() const {
4725 if (!hasLocalNonFastQualifiers())
4726 return SplitQualType(getTypePtrUnsafe(),
4727 Qualifiers::fromFastMask(getLocalFastQualifiers()));
4729 const ExtQuals *eq = getExtQualsUnsafe();
4730 Qualifiers qs = eq->getQualifiers();
4731 qs.addFastQualifiers(getLocalFastQualifiers());
4732 return SplitQualType(eq->getBaseType(), qs);
4735 inline Qualifiers QualType::getLocalQualifiers() const {
4737 if (hasLocalNonFastQualifiers())
4738 Quals = getExtQualsUnsafe()->getQualifiers();
4739 Quals.addFastQualifiers(getLocalFastQualifiers());
4743 inline Qualifiers QualType::getQualifiers() const {
4744 Qualifiers quals = getCommonPtr()->CanonicalType.getLocalQualifiers();
4745 quals.addFastQualifiers(getLocalFastQualifiers());
4749 inline unsigned QualType::getCVRQualifiers() const {
4750 unsigned cvr = getCommonPtr()->CanonicalType.getLocalCVRQualifiers();
4751 cvr |= getLocalCVRQualifiers();
4755 inline QualType QualType::getCanonicalType() const {
4756 QualType canon = getCommonPtr()->CanonicalType;
4757 return canon.withFastQualifiers(getLocalFastQualifiers());
4760 inline bool QualType::isCanonical() const {
4761 return getTypePtr()->isCanonicalUnqualified();
4764 inline bool QualType::isCanonicalAsParam() const {
4765 if (!isCanonical()) return false;
4766 if (hasLocalQualifiers()) return false;
4768 const Type *T = getTypePtr();
4769 if (T->isVariablyModifiedType() && T->hasSizedVLAType())
4772 return !isa<FunctionType>(T) && !isa<ArrayType>(T);
4775 inline bool QualType::isConstQualified() const {
4776 return isLocalConstQualified() ||
4777 getCommonPtr()->CanonicalType.isLocalConstQualified();
4780 inline bool QualType::isRestrictQualified() const {
4781 return isLocalRestrictQualified() ||
4782 getCommonPtr()->CanonicalType.isLocalRestrictQualified();
4786 inline bool QualType::isVolatileQualified() const {
4787 return isLocalVolatileQualified() ||
4788 getCommonPtr()->CanonicalType.isLocalVolatileQualified();
4791 inline bool QualType::hasQualifiers() const {
4792 return hasLocalQualifiers() ||
4793 getCommonPtr()->CanonicalType.hasLocalQualifiers();
4796 inline QualType QualType::getUnqualifiedType() const {
4797 if (!getTypePtr()->getCanonicalTypeInternal().hasLocalQualifiers())
4798 return QualType(getTypePtr(), 0);
4800 return QualType(getSplitUnqualifiedTypeImpl(*this).Ty, 0);
4803 inline SplitQualType QualType::getSplitUnqualifiedType() const {
4804 if (!getTypePtr()->getCanonicalTypeInternal().hasLocalQualifiers())
4807 return getSplitUnqualifiedTypeImpl(*this);
4810 inline void QualType::removeLocalConst() {
4811 removeLocalFastQualifiers(Qualifiers::Const);
4814 inline void QualType::removeLocalRestrict() {
4815 removeLocalFastQualifiers(Qualifiers::Restrict);
4818 inline void QualType::removeLocalVolatile() {
4819 removeLocalFastQualifiers(Qualifiers::Volatile);
4822 inline void QualType::removeLocalCVRQualifiers(unsigned Mask) {
4823 assert(!(Mask & ~Qualifiers::CVRMask) && "mask has non-CVR bits");
4824 assert((int)Qualifiers::CVRMask == (int)Qualifiers::FastMask);
4826 // Fast path: we don't need to touch the slow qualifiers.
4827 removeLocalFastQualifiers(Mask);
4830 /// getAddressSpace - Return the address space of this type.
4831 inline unsigned QualType::getAddressSpace() const {
4832 return getQualifiers().getAddressSpace();
4835 /// getObjCGCAttr - Return the gc attribute of this type.
4836 inline Qualifiers::GC QualType::getObjCGCAttr() const {
4837 return getQualifiers().getObjCGCAttr();
4840 inline FunctionType::ExtInfo getFunctionExtInfo(const Type &t) {
4841 if (const PointerType *PT = t.getAs<PointerType>()) {
4842 if (const FunctionType *FT = PT->getPointeeType()->getAs<FunctionType>())
4843 return FT->getExtInfo();
4844 } else if (const FunctionType *FT = t.getAs<FunctionType>())
4845 return FT->getExtInfo();
4847 return FunctionType::ExtInfo();
4850 inline FunctionType::ExtInfo getFunctionExtInfo(QualType t) {
4851 return getFunctionExtInfo(*t);
4854 /// isMoreQualifiedThan - Determine whether this type is more
4855 /// qualified than the Other type. For example, "const volatile int"
4856 /// is more qualified than "const int", "volatile int", and
4857 /// "int". However, it is not more qualified than "const volatile
4859 inline bool QualType::isMoreQualifiedThan(QualType other) const {
4860 Qualifiers myQuals = getQualifiers();
4861 Qualifiers otherQuals = other.getQualifiers();
4862 return (myQuals != otherQuals && myQuals.compatiblyIncludes(otherQuals));
4865 /// isAtLeastAsQualifiedAs - Determine whether this type is at last
4866 /// as qualified as the Other type. For example, "const volatile
4867 /// int" is at least as qualified as "const int", "volatile int",
4868 /// "int", and "const volatile int".
4869 inline bool QualType::isAtLeastAsQualifiedAs(QualType other) const {
4870 return getQualifiers().compatiblyIncludes(other.getQualifiers());
4873 /// getNonReferenceType - If Type is a reference type (e.g., const
4874 /// int&), returns the type that the reference refers to ("const
4875 /// int"). Otherwise, returns the type itself. This routine is used
4876 /// throughout Sema to implement C++ 5p6:
4878 /// If an expression initially has the type "reference to T" (8.3.2,
4879 /// 8.5.3), the type is adjusted to "T" prior to any further
4880 /// analysis, the expression designates the object or function
4881 /// denoted by the reference, and the expression is an lvalue.
4882 inline QualType QualType::getNonReferenceType() const {
4883 if (const ReferenceType *RefType = (*this)->getAs<ReferenceType>())
4884 return RefType->getPointeeType();
4889 inline bool QualType::isCForbiddenLValueType() const {
4890 return ((getTypePtr()->isVoidType() && !hasQualifiers()) ||
4891 getTypePtr()->isFunctionType());
4894 /// \brief Tests whether the type is categorized as a fundamental type.
4896 /// \returns True for types specified in C++0x [basic.fundamental].
4897 inline bool Type::isFundamentalType() const {
4898 return isVoidType() ||
4899 // FIXME: It's really annoying that we don't have an
4900 // 'isArithmeticType()' which agrees with the standard definition.
4901 (isArithmeticType() && !isEnumeralType());
4904 /// \brief Tests whether the type is categorized as a compound type.
4906 /// \returns True for types specified in C++0x [basic.compound].
4907 inline bool Type::isCompoundType() const {
4908 // C++0x [basic.compound]p1:
4909 // Compound types can be constructed in the following ways:
4910 // -- arrays of objects of a given type [...];
4911 return isArrayType() ||
4912 // -- functions, which have parameters of given types [...];
4914 // -- pointers to void or objects or functions [...];
4916 // -- references to objects or functions of a given type. [...]
4917 isReferenceType() ||
4918 // -- classes containing a sequence of objects of various types, [...];
4920 // -- unions, which are classes capable of containing objects of different
4921 // types at different times;
4923 // -- enumerations, which comprise a set of named constant values. [...];
4925 // -- pointers to non-static class members, [...].
4926 isMemberPointerType();
4929 inline bool Type::isFunctionType() const {
4930 return isa<FunctionType>(CanonicalType);
4932 inline bool Type::isPointerType() const {
4933 return isa<PointerType>(CanonicalType);
4935 inline bool Type::isAnyPointerType() const {
4936 return isPointerType() || isObjCObjectPointerType();
4938 inline bool Type::isBlockPointerType() const {
4939 return isa<BlockPointerType>(CanonicalType);
4941 inline bool Type::isReferenceType() const {
4942 return isa<ReferenceType>(CanonicalType);
4944 inline bool Type::isLValueReferenceType() const {
4945 return isa<LValueReferenceType>(CanonicalType);
4947 inline bool Type::isRValueReferenceType() const {
4948 return isa<RValueReferenceType>(CanonicalType);
4950 inline bool Type::isFunctionPointerType() const {
4951 if (const PointerType *T = getAs<PointerType>())
4952 return T->getPointeeType()->isFunctionType();
4956 inline bool Type::isMemberPointerType() const {
4957 return isa<MemberPointerType>(CanonicalType);
4959 inline bool Type::isMemberFunctionPointerType() const {
4960 if (const MemberPointerType* T = getAs<MemberPointerType>())
4961 return T->isMemberFunctionPointer();
4965 inline bool Type::isMemberDataPointerType() const {
4966 if (const MemberPointerType* T = getAs<MemberPointerType>())
4967 return T->isMemberDataPointer();
4971 inline bool Type::isArrayType() const {
4972 return isa<ArrayType>(CanonicalType);
4974 inline bool Type::isConstantArrayType() const {
4975 return isa<ConstantArrayType>(CanonicalType);
4977 inline bool Type::isIncompleteArrayType() const {
4978 return isa<IncompleteArrayType>(CanonicalType);
4980 inline bool Type::isVariableArrayType() const {
4981 return isa<VariableArrayType>(CanonicalType);
4983 inline bool Type::isDependentSizedArrayType() const {
4984 return isa<DependentSizedArrayType>(CanonicalType);
4986 inline bool Type::isBuiltinType() const {
4987 return isa<BuiltinType>(CanonicalType);
4989 inline bool Type::isRecordType() const {
4990 return isa<RecordType>(CanonicalType);
4992 inline bool Type::isEnumeralType() const {
4993 return isa<EnumType>(CanonicalType);
4995 inline bool Type::isAnyComplexType() const {
4996 return isa<ComplexType>(CanonicalType);
4998 inline bool Type::isVectorType() const {
4999 return isa<VectorType>(CanonicalType);
5001 inline bool Type::isExtVectorType() const {
5002 return isa<ExtVectorType>(CanonicalType);
5004 inline bool Type::isObjCObjectPointerType() const {
5005 return isa<ObjCObjectPointerType>(CanonicalType);
5007 inline bool Type::isObjCObjectType() const {
5008 return isa<ObjCObjectType>(CanonicalType);
5010 inline bool Type::isObjCObjectOrInterfaceType() const {
5011 return isa<ObjCInterfaceType>(CanonicalType) ||
5012 isa<ObjCObjectType>(CanonicalType);
5014 inline bool Type::isAtomicType() const {
5015 return isa<AtomicType>(CanonicalType);
5018 inline bool Type::isObjCQualifiedIdType() const {
5019 if (const ObjCObjectPointerType *OPT = getAs<ObjCObjectPointerType>())
5020 return OPT->isObjCQualifiedIdType();
5023 inline bool Type::isObjCQualifiedClassType() const {
5024 if (const ObjCObjectPointerType *OPT = getAs<ObjCObjectPointerType>())
5025 return OPT->isObjCQualifiedClassType();
5028 inline bool Type::isObjCIdType() const {
5029 if (const ObjCObjectPointerType *OPT = getAs<ObjCObjectPointerType>())
5030 return OPT->isObjCIdType();
5033 inline bool Type::isObjCClassType() const {
5034 if (const ObjCObjectPointerType *OPT = getAs<ObjCObjectPointerType>())
5035 return OPT->isObjCClassType();
5038 inline bool Type::isObjCSelType() const {
5039 if (const PointerType *OPT = getAs<PointerType>())
5040 return OPT->getPointeeType()->isSpecificBuiltinType(BuiltinType::ObjCSel);
5043 inline bool Type::isObjCBuiltinType() const {
5044 return isObjCIdType() || isObjCClassType() || isObjCSelType();
5047 inline bool Type::isImage1dT() const {
5048 return isSpecificBuiltinType(BuiltinType::OCLImage1d);
5051 inline bool Type::isImage1dArrayT() const {
5052 return isSpecificBuiltinType(BuiltinType::OCLImage1dArray);
5055 inline bool Type::isImage1dBufferT() const {
5056 return isSpecificBuiltinType(BuiltinType::OCLImage1dBuffer);
5059 inline bool Type::isImage2dT() const {
5060 return isSpecificBuiltinType(BuiltinType::OCLImage2d);
5063 inline bool Type::isImage2dArrayT() const {
5064 return isSpecificBuiltinType(BuiltinType::OCLImage2dArray);
5067 inline bool Type::isImage3dT() const {
5068 return isSpecificBuiltinType(BuiltinType::OCLImage3d);
5071 inline bool Type::isSamplerT() const {
5072 return isSpecificBuiltinType(BuiltinType::OCLSampler);
5075 inline bool Type::isEventT() const {
5076 return isSpecificBuiltinType(BuiltinType::OCLEvent);
5079 inline bool Type::isImageType() const {
5080 return isImage3dT() ||
5081 isImage2dT() || isImage2dArrayT() ||
5082 isImage1dT() || isImage1dArrayT() || isImage1dBufferT();
5085 inline bool Type::isOpenCLSpecificType() const {
5086 return isSamplerT() || isEventT() || isImageType();
5089 inline bool Type::isTemplateTypeParmType() const {
5090 return isa<TemplateTypeParmType>(CanonicalType);
5093 inline bool Type::isSpecificBuiltinType(unsigned K) const {
5094 if (const BuiltinType *BT = getAs<BuiltinType>())
5095 if (BT->getKind() == (BuiltinType::Kind) K)
5100 inline bool Type::isPlaceholderType() const {
5101 if (const BuiltinType *BT = dyn_cast<BuiltinType>(this))
5102 return BT->isPlaceholderType();
5106 inline const BuiltinType *Type::getAsPlaceholderType() const {
5107 if (const BuiltinType *BT = dyn_cast<BuiltinType>(this))
5108 if (BT->isPlaceholderType())
5113 inline bool Type::isSpecificPlaceholderType(unsigned K) const {
5114 assert(BuiltinType::isPlaceholderTypeKind((BuiltinType::Kind) K));
5115 if (const BuiltinType *BT = dyn_cast<BuiltinType>(this))
5116 return (BT->getKind() == (BuiltinType::Kind) K);
5120 inline bool Type::isNonOverloadPlaceholderType() const {
5121 if (const BuiltinType *BT = dyn_cast<BuiltinType>(this))
5122 return BT->isNonOverloadPlaceholderType();
5126 inline bool Type::isVoidType() const {
5127 if (const BuiltinType *BT = dyn_cast<BuiltinType>(CanonicalType))
5128 return BT->getKind() == BuiltinType::Void;
5132 inline bool Type::isHalfType() const {
5133 if (const BuiltinType *BT = dyn_cast<BuiltinType>(CanonicalType))
5134 return BT->getKind() == BuiltinType::Half;
5135 // FIXME: Should we allow complex __fp16? Probably not.
5139 inline bool Type::isNullPtrType() const {
5140 if (const BuiltinType *BT = getAs<BuiltinType>())
5141 return BT->getKind() == BuiltinType::NullPtr;
5145 extern bool IsEnumDeclComplete(EnumDecl *);
5146 extern bool IsEnumDeclScoped(EnumDecl *);
5148 inline bool Type::isIntegerType() const {
5149 if (const BuiltinType *BT = dyn_cast<BuiltinType>(CanonicalType))
5150 return BT->getKind() >= BuiltinType::Bool &&
5151 BT->getKind() <= BuiltinType::Int128;
5152 if (const EnumType *ET = dyn_cast<EnumType>(CanonicalType)) {
5153 // Incomplete enum types are not treated as integer types.
5154 // FIXME: In C++, enum types are never integer types.
5155 return IsEnumDeclComplete(ET->getDecl()) &&
5156 !IsEnumDeclScoped(ET->getDecl());
5161 inline bool Type::isScalarType() const {
5162 if (const BuiltinType *BT = dyn_cast<BuiltinType>(CanonicalType))
5163 return BT->getKind() > BuiltinType::Void &&
5164 BT->getKind() <= BuiltinType::NullPtr;
5165 if (const EnumType *ET = dyn_cast<EnumType>(CanonicalType))
5166 // Enums are scalar types, but only if they are defined. Incomplete enums
5167 // are not treated as scalar types.
5168 return IsEnumDeclComplete(ET->getDecl());
5169 return isa<PointerType>(CanonicalType) ||
5170 isa<BlockPointerType>(CanonicalType) ||
5171 isa<MemberPointerType>(CanonicalType) ||
5172 isa<ComplexType>(CanonicalType) ||
5173 isa<ObjCObjectPointerType>(CanonicalType);
5176 inline bool Type::isIntegralOrEnumerationType() const {
5177 if (const BuiltinType *BT = dyn_cast<BuiltinType>(CanonicalType))
5178 return BT->getKind() >= BuiltinType::Bool &&
5179 BT->getKind() <= BuiltinType::Int128;
5181 // Check for a complete enum type; incomplete enum types are not properly an
5182 // enumeration type in the sense required here.
5183 if (const EnumType *ET = dyn_cast<EnumType>(CanonicalType))
5184 return IsEnumDeclComplete(ET->getDecl());
5189 inline bool Type::isBooleanType() const {
5190 if (const BuiltinType *BT = dyn_cast<BuiltinType>(CanonicalType))
5191 return BT->getKind() == BuiltinType::Bool;
5195 inline bool Type::isUndeducedType() const {
5196 const AutoType *AT = getContainedAutoType();
5197 return AT && !AT->isDeduced();
5200 /// \brief Determines whether this is a type for which one can define
5201 /// an overloaded operator.
5202 inline bool Type::isOverloadableType() const {
5203 return isDependentType() || isRecordType() || isEnumeralType();
5206 /// \brief Determines whether this type can decay to a pointer type.
5207 inline bool Type::canDecayToPointerType() const {
5208 return isFunctionType() || isArrayType();
5211 inline bool Type::hasPointerRepresentation() const {
5212 return (isPointerType() || isReferenceType() || isBlockPointerType() ||
5213 isObjCObjectPointerType() || isNullPtrType());
5216 inline bool Type::hasObjCPointerRepresentation() const {
5217 return isObjCObjectPointerType();
5220 inline const Type *Type::getBaseElementTypeUnsafe() const {
5221 const Type *type = this;
5222 while (const ArrayType *arrayType = type->getAsArrayTypeUnsafe())
5223 type = arrayType->getElementType().getTypePtr();
5227 /// Insertion operator for diagnostics. This allows sending QualType's into a
5228 /// diagnostic with <<.
5229 inline const DiagnosticBuilder &operator<<(const DiagnosticBuilder &DB,
5231 DB.AddTaggedVal(reinterpret_cast<intptr_t>(T.getAsOpaquePtr()),
5232 DiagnosticsEngine::ak_qualtype);
5236 /// Insertion operator for partial diagnostics. This allows sending QualType's
5237 /// into a diagnostic with <<.
5238 inline const PartialDiagnostic &operator<<(const PartialDiagnostic &PD,
5240 PD.AddTaggedVal(reinterpret_cast<intptr_t>(T.getAsOpaquePtr()),
5241 DiagnosticsEngine::ak_qualtype);
5245 // Helper class template that is used by Type::getAs to ensure that one does
5246 // not try to look through a qualified type to get to an array type.
5247 template <typename T, bool isArrayType = (std::is_same<T, ArrayType>::value ||
5248 std::is_base_of<ArrayType, T>::value)>
5249 struct ArrayType_cannot_be_used_with_getAs {};
5251 template<typename T>
5252 struct ArrayType_cannot_be_used_with_getAs<T, true>;
5254 // Member-template getAs<specific type>'.
5255 template <typename T> const T *Type::getAs() const {
5256 ArrayType_cannot_be_used_with_getAs<T> at;
5259 // If this is directly a T type, return it.
5260 if (const T *Ty = dyn_cast<T>(this))
5263 // If the canonical form of this type isn't the right kind, reject it.
5264 if (!isa<T>(CanonicalType))
5267 // If this is a typedef for the type, strip the typedef off without
5268 // losing all typedef information.
5269 return cast<T>(getUnqualifiedDesugaredType());
5272 inline const ArrayType *Type::getAsArrayTypeUnsafe() const {
5273 // If this is directly an array type, return it.
5274 if (const ArrayType *arr = dyn_cast<ArrayType>(this))
5277 // If the canonical form of this type isn't the right kind, reject it.
5278 if (!isa<ArrayType>(CanonicalType))
5281 // If this is a typedef for the type, strip the typedef off without
5282 // losing all typedef information.
5283 return cast<ArrayType>(getUnqualifiedDesugaredType());
5286 template <typename T> const T *Type::castAs() const {
5287 ArrayType_cannot_be_used_with_getAs<T> at;
5290 if (const T *ty = dyn_cast<T>(this)) return ty;
5291 assert(isa<T>(CanonicalType));
5292 return cast<T>(getUnqualifiedDesugaredType());
5295 inline const ArrayType *Type::castAsArrayTypeUnsafe() const {
5296 assert(isa<ArrayType>(CanonicalType));
5297 if (const ArrayType *arr = dyn_cast<ArrayType>(this)) return arr;
5298 return cast<ArrayType>(getUnqualifiedDesugaredType());
5301 } // end namespace clang