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 /// The kind of type we are substituting Objective-C type arguments into.
538 /// The kind of substitution affects the replacement of type parameters when
539 /// no concrete type information is provided, e.g., when dealing with an
540 /// unspecialized type.
541 enum class ObjCSubstitutionContext {
542 /// An ordinary type.
544 /// The result type of a method or function.
546 /// The parameter type of a method or function.
548 /// The type of a property.
550 /// The superclass of a type.
554 /// QualType - For efficiency, we don't store CV-qualified types as nodes on
555 /// their own: instead each reference to a type stores the qualifiers. This
556 /// greatly reduces the number of nodes we need to allocate for types (for
557 /// example we only need one for 'int', 'const int', 'volatile int',
558 /// 'const volatile int', etc).
560 /// As an added efficiency bonus, instead of making this a pair, we
561 /// just store the two bits we care about in the low bits of the
562 /// pointer. To handle the packing/unpacking, we make QualType be a
563 /// simple wrapper class that acts like a smart pointer. A third bit
564 /// indicates whether there are extended qualifiers present, in which
565 /// case the pointer points to a special structure.
567 // Thankfully, these are efficiently composable.
568 llvm::PointerIntPair<llvm::PointerUnion<const Type*,const ExtQuals*>,
569 Qualifiers::FastWidth> Value;
571 const ExtQuals *getExtQualsUnsafe() const {
572 return Value.getPointer().get<const ExtQuals*>();
575 const Type *getTypePtrUnsafe() const {
576 return Value.getPointer().get<const Type*>();
579 const ExtQualsTypeCommonBase *getCommonPtr() const {
580 assert(!isNull() && "Cannot retrieve a NULL type pointer");
581 uintptr_t CommonPtrVal
582 = reinterpret_cast<uintptr_t>(Value.getOpaqueValue());
583 CommonPtrVal &= ~(uintptr_t)((1 << TypeAlignmentInBits) - 1);
584 return reinterpret_cast<ExtQualsTypeCommonBase*>(CommonPtrVal);
587 friend class QualifierCollector;
591 QualType(const Type *Ptr, unsigned Quals)
592 : Value(Ptr, Quals) {}
593 QualType(const ExtQuals *Ptr, unsigned Quals)
594 : Value(Ptr, Quals) {}
596 unsigned getLocalFastQualifiers() const { return Value.getInt(); }
597 void setLocalFastQualifiers(unsigned Quals) { Value.setInt(Quals); }
599 /// Retrieves a pointer to the underlying (unqualified) type.
601 /// This function requires that the type not be NULL. If the type might be
602 /// NULL, use the (slightly less efficient) \c getTypePtrOrNull().
603 const Type *getTypePtr() const;
605 const Type *getTypePtrOrNull() const;
607 /// Retrieves a pointer to the name of the base type.
608 const IdentifierInfo *getBaseTypeIdentifier() const;
610 /// Divides a QualType into its unqualified type and a set of local
612 SplitQualType split() const;
614 void *getAsOpaquePtr() const { return Value.getOpaqueValue(); }
615 static QualType getFromOpaquePtr(const void *Ptr) {
617 T.Value.setFromOpaqueValue(const_cast<void*>(Ptr));
621 const Type &operator*() const {
622 return *getTypePtr();
625 const Type *operator->() const {
629 bool isCanonical() const;
630 bool isCanonicalAsParam() const;
632 /// isNull - Return true if this QualType doesn't point to a type yet.
633 bool isNull() const {
634 return Value.getPointer().isNull();
637 /// \brief Determine whether this particular QualType instance has the
638 /// "const" qualifier set, without looking through typedefs that may have
639 /// added "const" at a different level.
640 bool isLocalConstQualified() const {
641 return (getLocalFastQualifiers() & Qualifiers::Const);
644 /// \brief Determine whether this type is const-qualified.
645 bool isConstQualified() const;
647 /// \brief Determine whether this particular QualType instance has the
648 /// "restrict" qualifier set, without looking through typedefs that may have
649 /// added "restrict" at a different level.
650 bool isLocalRestrictQualified() const {
651 return (getLocalFastQualifiers() & Qualifiers::Restrict);
654 /// \brief Determine whether this type is restrict-qualified.
655 bool isRestrictQualified() const;
657 /// \brief Determine whether this particular QualType instance has the
658 /// "volatile" qualifier set, without looking through typedefs that may have
659 /// added "volatile" at a different level.
660 bool isLocalVolatileQualified() const {
661 return (getLocalFastQualifiers() & Qualifiers::Volatile);
664 /// \brief Determine whether this type is volatile-qualified.
665 bool isVolatileQualified() const;
667 /// \brief Determine whether this particular QualType instance has any
668 /// qualifiers, without looking through any typedefs that might add
669 /// qualifiers at a different level.
670 bool hasLocalQualifiers() const {
671 return getLocalFastQualifiers() || hasLocalNonFastQualifiers();
674 /// \brief Determine whether this type has any qualifiers.
675 bool hasQualifiers() const;
677 /// \brief Determine whether this particular QualType instance has any
678 /// "non-fast" qualifiers, e.g., those that are stored in an ExtQualType
680 bool hasLocalNonFastQualifiers() const {
681 return Value.getPointer().is<const ExtQuals*>();
684 /// \brief Retrieve the set of qualifiers local to this particular QualType
685 /// instance, not including any qualifiers acquired through typedefs or
687 Qualifiers getLocalQualifiers() const;
689 /// \brief Retrieve the set of qualifiers applied to this type.
690 Qualifiers getQualifiers() const;
692 /// \brief Retrieve the set of CVR (const-volatile-restrict) qualifiers
693 /// local to this particular QualType instance, not including any qualifiers
694 /// acquired through typedefs or other sugar.
695 unsigned getLocalCVRQualifiers() const {
696 return getLocalFastQualifiers();
699 /// \brief Retrieve the set of CVR (const-volatile-restrict) qualifiers
700 /// applied to this type.
701 unsigned getCVRQualifiers() const;
703 bool isConstant(ASTContext& Ctx) const {
704 return QualType::isConstant(*this, Ctx);
707 /// \brief Determine whether this is a Plain Old Data (POD) type (C++ 3.9p10).
708 bool isPODType(ASTContext &Context) const;
710 /// isCXX98PODType() - Return true if this is a POD type according to the
711 /// rules of the C++98 standard, regardless of the current compilation's
713 bool isCXX98PODType(ASTContext &Context) const;
715 /// isCXX11PODType() - Return true if this is a POD type according to the
716 /// more relaxed rules of the C++11 standard, regardless of the current
717 /// compilation's language.
718 /// (C++0x [basic.types]p9)
719 bool isCXX11PODType(ASTContext &Context) const;
721 /// isTrivialType - Return true if this is a trivial type
722 /// (C++0x [basic.types]p9)
723 bool isTrivialType(ASTContext &Context) const;
725 /// isTriviallyCopyableType - Return true if this is a trivially
726 /// copyable type (C++0x [basic.types]p9)
727 bool isTriviallyCopyableType(ASTContext &Context) const;
729 // Don't promise in the API that anything besides 'const' can be
732 /// addConst - add the specified type qualifier to this QualType.
734 addFastQualifiers(Qualifiers::Const);
736 QualType withConst() const {
737 return withFastQualifiers(Qualifiers::Const);
740 /// addVolatile - add the specified type qualifier to this QualType.
742 addFastQualifiers(Qualifiers::Volatile);
744 QualType withVolatile() const {
745 return withFastQualifiers(Qualifiers::Volatile);
748 /// Add the restrict qualifier to this QualType.
750 addFastQualifiers(Qualifiers::Restrict);
752 QualType withRestrict() const {
753 return withFastQualifiers(Qualifiers::Restrict);
756 QualType withCVRQualifiers(unsigned CVR) const {
757 return withFastQualifiers(CVR);
760 void addFastQualifiers(unsigned TQs) {
761 assert(!(TQs & ~Qualifiers::FastMask)
762 && "non-fast qualifier bits set in mask!");
763 Value.setInt(Value.getInt() | TQs);
766 void removeLocalConst();
767 void removeLocalVolatile();
768 void removeLocalRestrict();
769 void removeLocalCVRQualifiers(unsigned Mask);
771 void removeLocalFastQualifiers() { Value.setInt(0); }
772 void removeLocalFastQualifiers(unsigned Mask) {
773 assert(!(Mask & ~Qualifiers::FastMask) && "mask has non-fast qualifiers");
774 Value.setInt(Value.getInt() & ~Mask);
777 // Creates a type with the given qualifiers in addition to any
778 // qualifiers already on this type.
779 QualType withFastQualifiers(unsigned TQs) const {
781 T.addFastQualifiers(TQs);
785 // Creates a type with exactly the given fast qualifiers, removing
786 // any existing fast qualifiers.
787 QualType withExactLocalFastQualifiers(unsigned TQs) const {
788 return withoutLocalFastQualifiers().withFastQualifiers(TQs);
791 // Removes fast qualifiers, but leaves any extended qualifiers in place.
792 QualType withoutLocalFastQualifiers() const {
794 T.removeLocalFastQualifiers();
798 QualType getCanonicalType() const;
800 /// \brief Return this type with all of the instance-specific qualifiers
801 /// removed, but without removing any qualifiers that may have been applied
802 /// through typedefs.
803 QualType getLocalUnqualifiedType() const { return QualType(getTypePtr(), 0); }
805 /// \brief Retrieve the unqualified variant of the given type,
806 /// removing as little sugar as possible.
808 /// This routine looks through various kinds of sugar to find the
809 /// least-desugared type that is unqualified. For example, given:
812 /// typedef int Integer;
813 /// typedef const Integer CInteger;
814 /// typedef CInteger DifferenceType;
817 /// Executing \c getUnqualifiedType() on the type \c DifferenceType will
818 /// desugar until we hit the type \c Integer, which has no qualifiers on it.
820 /// The resulting type might still be qualified if it's sugar for an array
821 /// type. To strip qualifiers even from within a sugared array type, use
822 /// ASTContext::getUnqualifiedArrayType.
823 inline QualType getUnqualifiedType() const;
825 /// getSplitUnqualifiedType - Retrieve the unqualified variant of the
826 /// given type, removing as little sugar as possible.
828 /// Like getUnqualifiedType(), but also returns the set of
829 /// qualifiers that were built up.
831 /// The resulting type might still be qualified if it's sugar for an array
832 /// type. To strip qualifiers even from within a sugared array type, use
833 /// ASTContext::getUnqualifiedArrayType.
834 inline SplitQualType getSplitUnqualifiedType() const;
836 /// \brief Determine whether this type is more qualified than the other
837 /// given type, requiring exact equality for non-CVR qualifiers.
838 bool isMoreQualifiedThan(QualType Other) const;
840 /// \brief Determine whether this type is at least as qualified as the other
841 /// given type, requiring exact equality for non-CVR qualifiers.
842 bool isAtLeastAsQualifiedAs(QualType Other) const;
844 QualType getNonReferenceType() const;
846 /// \brief Determine the type of a (typically non-lvalue) expression with the
847 /// specified result type.
849 /// This routine should be used for expressions for which the return type is
850 /// explicitly specified (e.g., in a cast or call) and isn't necessarily
851 /// an lvalue. It removes a top-level reference (since there are no
852 /// expressions of reference type) and deletes top-level cvr-qualifiers
853 /// from non-class types (in C++) or all types (in C).
854 QualType getNonLValueExprType(const ASTContext &Context) const;
856 /// getDesugaredType - Return the specified type with any "sugar" removed from
857 /// the type. This takes off typedefs, typeof's etc. If the outer level of
858 /// the type is already concrete, it returns it unmodified. This is similar
859 /// to getting the canonical type, but it doesn't remove *all* typedefs. For
860 /// example, it returns "T*" as "T*", (not as "int*"), because the pointer is
863 /// Qualifiers are left in place.
864 QualType getDesugaredType(const ASTContext &Context) const {
865 return getDesugaredType(*this, Context);
868 SplitQualType getSplitDesugaredType() const {
869 return getSplitDesugaredType(*this);
872 /// \brief Return the specified type with one level of "sugar" removed from
875 /// This routine takes off the first typedef, typeof, etc. If the outer level
876 /// of the type is already concrete, it returns it unmodified.
877 QualType getSingleStepDesugaredType(const ASTContext &Context) const {
878 return getSingleStepDesugaredTypeImpl(*this, Context);
881 /// IgnoreParens - Returns the specified type after dropping any
882 /// outer-level parentheses.
883 QualType IgnoreParens() const {
884 if (isa<ParenType>(*this))
885 return QualType::IgnoreParens(*this);
889 /// operator==/!= - Indicate whether the specified types and qualifiers are
891 friend bool operator==(const QualType &LHS, const QualType &RHS) {
892 return LHS.Value == RHS.Value;
894 friend bool operator!=(const QualType &LHS, const QualType &RHS) {
895 return LHS.Value != RHS.Value;
897 std::string getAsString() const {
898 return getAsString(split());
900 static std::string getAsString(SplitQualType split) {
901 return getAsString(split.Ty, split.Quals);
903 static std::string getAsString(const Type *ty, Qualifiers qs);
905 std::string getAsString(const PrintingPolicy &Policy) const;
907 void print(raw_ostream &OS, const PrintingPolicy &Policy,
908 const Twine &PlaceHolder = Twine()) const {
909 print(split(), OS, Policy, PlaceHolder);
911 static void print(SplitQualType split, raw_ostream &OS,
912 const PrintingPolicy &policy, const Twine &PlaceHolder) {
913 return print(split.Ty, split.Quals, OS, policy, PlaceHolder);
915 static void print(const Type *ty, Qualifiers qs,
916 raw_ostream &OS, const PrintingPolicy &policy,
917 const Twine &PlaceHolder);
919 void getAsStringInternal(std::string &Str,
920 const PrintingPolicy &Policy) const {
921 return getAsStringInternal(split(), Str, Policy);
923 static void getAsStringInternal(SplitQualType split, std::string &out,
924 const PrintingPolicy &policy) {
925 return getAsStringInternal(split.Ty, split.Quals, out, policy);
927 static void getAsStringInternal(const Type *ty, Qualifiers qs,
929 const PrintingPolicy &policy);
931 class StreamedQualTypeHelper {
933 const PrintingPolicy &Policy;
934 const Twine &PlaceHolder;
936 StreamedQualTypeHelper(const QualType &T, const PrintingPolicy &Policy,
937 const Twine &PlaceHolder)
938 : T(T), Policy(Policy), PlaceHolder(PlaceHolder) { }
940 friend raw_ostream &operator<<(raw_ostream &OS,
941 const StreamedQualTypeHelper &SQT) {
942 SQT.T.print(OS, SQT.Policy, SQT.PlaceHolder);
947 StreamedQualTypeHelper stream(const PrintingPolicy &Policy,
948 const Twine &PlaceHolder = Twine()) const {
949 return StreamedQualTypeHelper(*this, Policy, PlaceHolder);
952 void dump(const char *s) const;
955 void Profile(llvm::FoldingSetNodeID &ID) const {
956 ID.AddPointer(getAsOpaquePtr());
959 /// getAddressSpace - Return the address space of this type.
960 inline unsigned getAddressSpace() const;
962 /// getObjCGCAttr - Returns gc attribute of this type.
963 inline Qualifiers::GC getObjCGCAttr() const;
965 /// isObjCGCWeak true when Type is objc's weak.
966 bool isObjCGCWeak() const {
967 return getObjCGCAttr() == Qualifiers::Weak;
970 /// isObjCGCStrong true when Type is objc's strong.
971 bool isObjCGCStrong() const {
972 return getObjCGCAttr() == Qualifiers::Strong;
975 /// getObjCLifetime - Returns lifetime attribute of this type.
976 Qualifiers::ObjCLifetime getObjCLifetime() const {
977 return getQualifiers().getObjCLifetime();
980 bool hasNonTrivialObjCLifetime() const {
981 return getQualifiers().hasNonTrivialObjCLifetime();
984 bool hasStrongOrWeakObjCLifetime() const {
985 return getQualifiers().hasStrongOrWeakObjCLifetime();
988 enum DestructionKind {
991 DK_objc_strong_lifetime,
992 DK_objc_weak_lifetime
995 /// isDestructedType - nonzero if objects of this type require
996 /// non-trivial work to clean up after. Non-zero because it's
997 /// conceivable that qualifiers (objc_gc(weak)?) could make
998 /// something require destruction.
999 DestructionKind isDestructedType() const {
1000 return isDestructedTypeImpl(*this);
1003 /// \brief Determine whether expressions of the given type are forbidden
1004 /// from being lvalues in C.
1006 /// The expression types that are forbidden to be lvalues are:
1007 /// - 'void', but not qualified void
1008 /// - function types
1010 /// The exact rule here is C99 6.3.2.1:
1011 /// An lvalue is an expression with an object type or an incomplete
1012 /// type other than void.
1013 bool isCForbiddenLValueType() const;
1015 /// Substitute type arguments for the Objective-C type parameters used in the
1018 /// \param ctx ASTContext in which the type exists.
1020 /// \param typeArgs The type arguments that will be substituted for the
1021 /// Objective-C type parameters in the subject type, which are generally
1022 /// computed via \c Type::getObjCSubstitutions. If empty, the type
1023 /// parameters will be replaced with their bounds or id/Class, as appropriate
1024 /// for the context.
1026 /// \param context The context in which the subject type was written.
1028 /// \returns the resulting type.
1029 QualType substObjCTypeArgs(ASTContext &ctx,
1030 ArrayRef<QualType> typeArgs,
1031 ObjCSubstitutionContext context) const;
1033 /// Substitute type arguments from an object type for the Objective-C type
1034 /// parameters used in the subject type.
1036 /// This operation combines the computation of type arguments for
1037 /// substitution (\c Type::getObjCSubstitutions) with the actual process of
1038 /// substitution (\c QualType::substObjCTypeArgs) for the convenience of
1039 /// callers that need to perform a single substitution in isolation.
1041 /// \param objectType The type of the object whose member type we're
1042 /// substituting into. For example, this might be the receiver of a message
1043 /// or the base of a property access.
1045 /// \param dc The declaration context from which the subject type was
1046 /// retrieved, which indicates (for example) which type parameters should
1049 /// \param context The context in which the subject type was written.
1051 /// \returns the subject type after replacing all of the Objective-C type
1052 /// parameters with their corresponding arguments.
1053 QualType substObjCMemberType(QualType objectType,
1054 const DeclContext *dc,
1055 ObjCSubstitutionContext context) const;
1057 /// Strip Objective-C "__kindof" types from the given type.
1058 QualType stripObjCKindOfType(const ASTContext &ctx) const;
1061 // These methods are implemented in a separate translation unit;
1062 // "static"-ize them to avoid creating temporary QualTypes in the
1064 static bool isConstant(QualType T, ASTContext& Ctx);
1065 static QualType getDesugaredType(QualType T, const ASTContext &Context);
1066 static SplitQualType getSplitDesugaredType(QualType T);
1067 static SplitQualType getSplitUnqualifiedTypeImpl(QualType type);
1068 static QualType getSingleStepDesugaredTypeImpl(QualType type,
1069 const ASTContext &C);
1070 static QualType IgnoreParens(QualType T);
1071 static DestructionKind isDestructedTypeImpl(QualType type);
1077 /// Implement simplify_type for QualType, so that we can dyn_cast from QualType
1078 /// to a specific Type class.
1079 template<> struct simplify_type< ::clang::QualType> {
1080 typedef const ::clang::Type *SimpleType;
1081 static SimpleType getSimplifiedValue(::clang::QualType Val) {
1082 return Val.getTypePtr();
1086 // Teach SmallPtrSet that QualType is "basically a pointer".
1088 class PointerLikeTypeTraits<clang::QualType> {
1090 static inline void *getAsVoidPointer(clang::QualType P) {
1091 return P.getAsOpaquePtr();
1093 static inline clang::QualType getFromVoidPointer(void *P) {
1094 return clang::QualType::getFromOpaquePtr(P);
1096 // Various qualifiers go in low bits.
1097 enum { NumLowBitsAvailable = 0 };
1100 } // end namespace llvm
1104 /// \brief Base class that is common to both the \c ExtQuals and \c Type
1105 /// classes, which allows \c QualType to access the common fields between the
1108 class ExtQualsTypeCommonBase {
1109 ExtQualsTypeCommonBase(const Type *baseType, QualType canon)
1110 : BaseType(baseType), CanonicalType(canon) {}
1112 /// \brief The "base" type of an extended qualifiers type (\c ExtQuals) or
1113 /// a self-referential pointer (for \c Type).
1115 /// This pointer allows an efficient mapping from a QualType to its
1116 /// underlying type pointer.
1117 const Type *const BaseType;
1119 /// \brief The canonical type of this type. A QualType.
1120 QualType CanonicalType;
1122 friend class QualType;
1124 friend class ExtQuals;
1127 /// ExtQuals - We can encode up to four bits in the low bits of a
1128 /// type pointer, but there are many more type qualifiers that we want
1129 /// to be able to apply to an arbitrary type. Therefore we have this
1130 /// struct, intended to be heap-allocated and used by QualType to
1131 /// store qualifiers.
1133 /// The current design tags the 'const', 'restrict', and 'volatile' qualifiers
1134 /// in three low bits on the QualType pointer; a fourth bit records whether
1135 /// the pointer is an ExtQuals node. The extended qualifiers (address spaces,
1136 /// Objective-C GC attributes) are much more rare.
1137 class ExtQuals : public ExtQualsTypeCommonBase, public llvm::FoldingSetNode {
1138 // NOTE: changing the fast qualifiers should be straightforward as
1139 // long as you don't make 'const' non-fast.
1141 // a) Modify the bitmasks (Qualifiers::TQ and DeclSpec::TQ).
1142 // Fast qualifiers must occupy the low-order bits.
1143 // b) Update Qualifiers::FastWidth and FastMask.
1145 // a) Update is{Volatile,Restrict}Qualified(), defined inline.
1146 // b) Update remove{Volatile,Restrict}, defined near the end of
1149 // a) Update get{Volatile,Restrict}Type.
1151 /// Quals - the immutable set of qualifiers applied by this
1152 /// node; always contains extended qualifiers.
1155 ExtQuals *this_() { return this; }
1158 ExtQuals(const Type *baseType, QualType canon, Qualifiers quals)
1159 : ExtQualsTypeCommonBase(baseType,
1160 canon.isNull() ? QualType(this_(), 0) : canon),
1163 assert(Quals.hasNonFastQualifiers()
1164 && "ExtQuals created with no fast qualifiers");
1165 assert(!Quals.hasFastQualifiers()
1166 && "ExtQuals created with fast qualifiers");
1169 Qualifiers getQualifiers() const { return Quals; }
1171 bool hasObjCGCAttr() const { return Quals.hasObjCGCAttr(); }
1172 Qualifiers::GC getObjCGCAttr() const { return Quals.getObjCGCAttr(); }
1174 bool hasObjCLifetime() const { return Quals.hasObjCLifetime(); }
1175 Qualifiers::ObjCLifetime getObjCLifetime() const {
1176 return Quals.getObjCLifetime();
1179 bool hasAddressSpace() const { return Quals.hasAddressSpace(); }
1180 unsigned getAddressSpace() const { return Quals.getAddressSpace(); }
1182 const Type *getBaseType() const { return BaseType; }
1185 void Profile(llvm::FoldingSetNodeID &ID) const {
1186 Profile(ID, getBaseType(), Quals);
1188 static void Profile(llvm::FoldingSetNodeID &ID,
1189 const Type *BaseType,
1191 assert(!Quals.hasFastQualifiers() && "fast qualifiers in ExtQuals hash!");
1192 ID.AddPointer(BaseType);
1197 /// \brief The kind of C++0x ref-qualifier associated with a function type,
1198 /// which determines whether a member function's "this" object can be an
1199 /// lvalue, rvalue, or neither.
1200 enum RefQualifierKind {
1201 /// \brief No ref-qualifier was provided.
1203 /// \brief An lvalue ref-qualifier was provided (\c &).
1205 /// \brief An rvalue ref-qualifier was provided (\c &&).
1209 /// Type - This is the base class of the type hierarchy. A central concept
1210 /// with types is that each type always has a canonical type. A canonical type
1211 /// is the type with any typedef names stripped out of it or the types it
1212 /// references. For example, consider:
1214 /// typedef int foo;
1215 /// typedef foo* bar;
1216 /// 'int *' 'foo *' 'bar'
1218 /// There will be a Type object created for 'int'. Since int is canonical, its
1219 /// canonicaltype pointer points to itself. There is also a Type for 'foo' (a
1220 /// TypedefType). Its CanonicalType pointer points to the 'int' Type. Next
1221 /// there is a PointerType that represents 'int*', which, like 'int', is
1222 /// canonical. Finally, there is a PointerType type for 'foo*' whose canonical
1223 /// type is 'int*', and there is a TypedefType for 'bar', whose canonical type
1226 /// Non-canonical types are useful for emitting diagnostics, without losing
1227 /// information about typedefs being used. Canonical types are useful for type
1228 /// comparisons (they allow by-pointer equality tests) and useful for reasoning
1229 /// about whether something has a particular form (e.g. is a function type),
1230 /// because they implicitly, recursively, strip all typedefs out of a type.
1232 /// Types, once created, are immutable.
1234 class Type : public ExtQualsTypeCommonBase {
1237 #define TYPE(Class, Base) Class,
1238 #define LAST_TYPE(Class) TypeLast = Class,
1239 #define ABSTRACT_TYPE(Class, Base)
1240 #include "clang/AST/TypeNodes.def"
1241 TagFirst = Record, TagLast = Enum
1245 Type(const Type &) = delete;
1246 void operator=(const Type &) = delete;
1248 /// Bitfields required by the Type class.
1249 class TypeBitfields {
1251 template <class T> friend class TypePropertyCache;
1253 /// TypeClass bitfield - Enum that specifies what subclass this belongs to.
1256 /// Dependent - Whether this type is a dependent type (C++ [temp.dep.type]).
1257 unsigned Dependent : 1;
1259 /// \brief Whether this type somehow involves a template parameter, even
1260 /// if the resolution of the type does not depend on a template parameter.
1261 unsigned InstantiationDependent : 1;
1263 /// \brief Whether this type is a variably-modified type (C99 6.7.5).
1264 unsigned VariablyModified : 1;
1266 /// \brief Whether this type contains an unexpanded parameter pack
1267 /// (for C++0x variadic templates).
1268 unsigned ContainsUnexpandedParameterPack : 1;
1270 /// \brief True if the cache (i.e. the bitfields here starting with
1271 /// 'Cache') is valid.
1272 mutable unsigned CacheValid : 1;
1274 /// \brief Linkage of this type.
1275 mutable unsigned CachedLinkage : 3;
1277 /// \brief Whether this type involves and local or unnamed types.
1278 mutable unsigned CachedLocalOrUnnamed : 1;
1280 /// \brief FromAST - Whether this type comes from an AST file.
1281 mutable unsigned FromAST : 1;
1283 bool isCacheValid() const {
1286 Linkage getLinkage() const {
1287 assert(isCacheValid() && "getting linkage from invalid cache");
1288 return static_cast<Linkage>(CachedLinkage);
1290 bool hasLocalOrUnnamedType() const {
1291 assert(isCacheValid() && "getting linkage from invalid cache");
1292 return CachedLocalOrUnnamed;
1295 enum { NumTypeBits = 18 };
1298 // These classes allow subclasses to somewhat cleanly pack bitfields
1301 class ArrayTypeBitfields {
1302 friend class ArrayType;
1304 unsigned : NumTypeBits;
1306 /// IndexTypeQuals - CVR qualifiers from declarations like
1307 /// 'int X[static restrict 4]'. For function parameters only.
1308 unsigned IndexTypeQuals : 3;
1310 /// SizeModifier - storage class qualifiers from declarations like
1311 /// 'int X[static restrict 4]'. For function parameters only.
1312 /// Actually an ArrayType::ArraySizeModifier.
1313 unsigned SizeModifier : 3;
1316 class BuiltinTypeBitfields {
1317 friend class BuiltinType;
1319 unsigned : NumTypeBits;
1321 /// The kind (BuiltinType::Kind) of builtin type this is.
1325 class FunctionTypeBitfields {
1326 friend class FunctionType;
1327 friend class FunctionProtoType;
1329 unsigned : NumTypeBits;
1331 /// Extra information which affects how the function is called, like
1332 /// regparm and the calling convention.
1333 unsigned ExtInfo : 9;
1335 /// TypeQuals - Used only by FunctionProtoType, put here to pack with the
1336 /// other bitfields.
1337 /// The qualifiers are part of FunctionProtoType because...
1339 /// C++ 8.3.5p4: The return type, the parameter type list and the
1340 /// cv-qualifier-seq, [...], are part of the function type.
1341 unsigned TypeQuals : 3;
1343 /// \brief The ref-qualifier associated with a \c FunctionProtoType.
1345 /// This is a value of type \c RefQualifierKind.
1346 unsigned RefQualifier : 2;
1349 class ObjCObjectTypeBitfields {
1350 friend class ObjCObjectType;
1352 unsigned : NumTypeBits;
1354 /// The number of type arguments stored directly on this object type.
1355 unsigned NumTypeArgs : 7;
1357 /// NumProtocols - The number of protocols stored directly on this
1359 unsigned NumProtocols : 6;
1361 /// Whether this is a "kindof" type.
1362 unsigned IsKindOf : 1;
1364 static_assert(NumTypeBits + 7 + 6 + 1 <= 32, "Does not fit in an unsigned");
1366 class ReferenceTypeBitfields {
1367 friend class ReferenceType;
1369 unsigned : NumTypeBits;
1371 /// True if the type was originally spelled with an lvalue sigil.
1372 /// This is never true of rvalue references but can also be false
1373 /// on lvalue references because of C++0x [dcl.typedef]p9,
1376 /// typedef int &ref; // lvalue, spelled lvalue
1377 /// typedef int &&rvref; // rvalue
1378 /// ref &a; // lvalue, inner ref, spelled lvalue
1379 /// ref &&a; // lvalue, inner ref
1380 /// rvref &a; // lvalue, inner ref, spelled lvalue
1381 /// rvref &&a; // rvalue, inner ref
1382 unsigned SpelledAsLValue : 1;
1384 /// True if the inner type is a reference type. This only happens
1385 /// in non-canonical forms.
1386 unsigned InnerRef : 1;
1389 class TypeWithKeywordBitfields {
1390 friend class TypeWithKeyword;
1392 unsigned : NumTypeBits;
1394 /// An ElaboratedTypeKeyword. 8 bits for efficient access.
1395 unsigned Keyword : 8;
1398 class VectorTypeBitfields {
1399 friend class VectorType;
1401 unsigned : NumTypeBits;
1403 /// VecKind - The kind of vector, either a generic vector type or some
1404 /// target-specific vector type such as for AltiVec or Neon.
1405 unsigned VecKind : 3;
1407 /// NumElements - The number of elements in the vector.
1408 unsigned NumElements : 29 - NumTypeBits;
1410 enum { MaxNumElements = (1 << (29 - NumTypeBits)) - 1 };
1413 class AttributedTypeBitfields {
1414 friend class AttributedType;
1416 unsigned : NumTypeBits;
1418 /// AttrKind - an AttributedType::Kind
1419 unsigned AttrKind : 32 - NumTypeBits;
1422 class AutoTypeBitfields {
1423 friend class AutoType;
1425 unsigned : NumTypeBits;
1427 /// Was this placeholder type spelled as 'decltype(auto)'?
1428 unsigned IsDecltypeAuto : 1;
1432 TypeBitfields TypeBits;
1433 ArrayTypeBitfields ArrayTypeBits;
1434 AttributedTypeBitfields AttributedTypeBits;
1435 AutoTypeBitfields AutoTypeBits;
1436 BuiltinTypeBitfields BuiltinTypeBits;
1437 FunctionTypeBitfields FunctionTypeBits;
1438 ObjCObjectTypeBitfields ObjCObjectTypeBits;
1439 ReferenceTypeBitfields ReferenceTypeBits;
1440 TypeWithKeywordBitfields TypeWithKeywordBits;
1441 VectorTypeBitfields VectorTypeBits;
1445 /// \brief Set whether this type comes from an AST file.
1446 void setFromAST(bool V = true) const {
1447 TypeBits.FromAST = V;
1450 template <class T> friend class TypePropertyCache;
1453 // silence VC++ warning C4355: 'this' : used in base member initializer list
1454 Type *this_() { return this; }
1455 Type(TypeClass tc, QualType canon, bool Dependent,
1456 bool InstantiationDependent, bool VariablyModified,
1457 bool ContainsUnexpandedParameterPack)
1458 : ExtQualsTypeCommonBase(this,
1459 canon.isNull() ? QualType(this_(), 0) : canon) {
1461 TypeBits.Dependent = Dependent;
1462 TypeBits.InstantiationDependent = Dependent || InstantiationDependent;
1463 TypeBits.VariablyModified = VariablyModified;
1464 TypeBits.ContainsUnexpandedParameterPack = ContainsUnexpandedParameterPack;
1465 TypeBits.CacheValid = false;
1466 TypeBits.CachedLocalOrUnnamed = false;
1467 TypeBits.CachedLinkage = NoLinkage;
1468 TypeBits.FromAST = false;
1470 friend class ASTContext;
1472 void setDependent(bool D = true) {
1473 TypeBits.Dependent = D;
1475 TypeBits.InstantiationDependent = true;
1477 void setInstantiationDependent(bool D = true) {
1478 TypeBits.InstantiationDependent = D; }
1479 void setVariablyModified(bool VM = true) { TypeBits.VariablyModified = VM;
1481 void setContainsUnexpandedParameterPack(bool PP = true) {
1482 TypeBits.ContainsUnexpandedParameterPack = PP;
1486 TypeClass getTypeClass() const { return static_cast<TypeClass>(TypeBits.TC); }
1488 /// \brief Whether this type comes from an AST file.
1489 bool isFromAST() const { return TypeBits.FromAST; }
1491 /// \brief Whether this type is or contains an unexpanded parameter
1492 /// pack, used to support C++0x variadic templates.
1494 /// A type that contains a parameter pack shall be expanded by the
1495 /// ellipsis operator at some point. For example, the typedef in the
1496 /// following example contains an unexpanded parameter pack 'T':
1499 /// template<typename ...T>
1501 /// typedef T* pointer_types; // ill-formed; T is a parameter pack.
1505 /// Note that this routine does not specify which
1506 bool containsUnexpandedParameterPack() const {
1507 return TypeBits.ContainsUnexpandedParameterPack;
1510 /// Determines if this type would be canonical if it had no further
1512 bool isCanonicalUnqualified() const {
1513 return CanonicalType == QualType(this, 0);
1516 /// Pull a single level of sugar off of this locally-unqualified type.
1517 /// Users should generally prefer SplitQualType::getSingleStepDesugaredType()
1518 /// or QualType::getSingleStepDesugaredType(const ASTContext&).
1519 QualType getLocallyUnqualifiedSingleStepDesugaredType() const;
1521 /// Types are partitioned into 3 broad categories (C99 6.2.5p1):
1522 /// object types, function types, and incomplete types.
1524 /// isIncompleteType - Return true if this is an incomplete type.
1525 /// A type that can describe objects, but which lacks information needed to
1526 /// determine its size (e.g. void, or a fwd declared struct). Clients of this
1527 /// routine will need to determine if the size is actually required.
1529 /// \brief Def If non-NULL, and the type refers to some kind of declaration
1530 /// that can be completed (such as a C struct, C++ class, or Objective-C
1531 /// class), will be set to the declaration.
1532 bool isIncompleteType(NamedDecl **Def = nullptr) const;
1534 /// isIncompleteOrObjectType - Return true if this is an incomplete or object
1535 /// type, in other words, not a function type.
1536 bool isIncompleteOrObjectType() const {
1537 return !isFunctionType();
1540 /// \brief Determine whether this type is an object type.
1541 bool isObjectType() const {
1542 // C++ [basic.types]p8:
1543 // An object type is a (possibly cv-qualified) type that is not a
1544 // function type, not a reference type, and not a void type.
1545 return !isReferenceType() && !isFunctionType() && !isVoidType();
1548 /// isLiteralType - Return true if this is a literal type
1549 /// (C++11 [basic.types]p10)
1550 bool isLiteralType(const ASTContext &Ctx) const;
1552 /// \brief Test if this type is a standard-layout type.
1553 /// (C++0x [basic.type]p9)
1554 bool isStandardLayoutType() const;
1556 /// Helper methods to distinguish type categories. All type predicates
1557 /// operate on the canonical type, ignoring typedefs and qualifiers.
1559 /// isBuiltinType - returns true if the type is a builtin type.
1560 bool isBuiltinType() const;
1562 /// isSpecificBuiltinType - Test for a particular builtin type.
1563 bool isSpecificBuiltinType(unsigned K) const;
1565 /// isPlaceholderType - Test for a type which does not represent an
1566 /// actual type-system type but is instead used as a placeholder for
1567 /// various convenient purposes within Clang. All such types are
1569 bool isPlaceholderType() const;
1570 const BuiltinType *getAsPlaceholderType() const;
1572 /// isSpecificPlaceholderType - Test for a specific placeholder type.
1573 bool isSpecificPlaceholderType(unsigned K) const;
1575 /// isNonOverloadPlaceholderType - Test for a placeholder type
1576 /// other than Overload; see BuiltinType::isNonOverloadPlaceholderType.
1577 bool isNonOverloadPlaceholderType() const;
1579 /// isIntegerType() does *not* include complex integers (a GCC extension).
1580 /// isComplexIntegerType() can be used to test for complex integers.
1581 bool isIntegerType() const; // C99 6.2.5p17 (int, char, bool, enum)
1582 bool isEnumeralType() const;
1583 bool isBooleanType() const;
1584 bool isCharType() const;
1585 bool isWideCharType() const;
1586 bool isChar16Type() const;
1587 bool isChar32Type() const;
1588 bool isAnyCharacterType() const;
1589 bool isIntegralType(ASTContext &Ctx) const;
1591 /// \brief Determine whether this type is an integral or enumeration type.
1592 bool isIntegralOrEnumerationType() const;
1593 /// \brief Determine whether this type is an integral or unscoped enumeration
1595 bool isIntegralOrUnscopedEnumerationType() const;
1597 /// Floating point categories.
1598 bool isRealFloatingType() const; // C99 6.2.5p10 (float, double, long double)
1599 /// isComplexType() does *not* include complex integers (a GCC extension).
1600 /// isComplexIntegerType() can be used to test for complex integers.
1601 bool isComplexType() const; // C99 6.2.5p11 (complex)
1602 bool isAnyComplexType() const; // C99 6.2.5p11 (complex) + Complex Int.
1603 bool isFloatingType() const; // C99 6.2.5p11 (real floating + complex)
1604 bool isHalfType() const; // OpenCL 6.1.1.1, NEON (IEEE 754-2008 half)
1605 bool isRealType() const; // C99 6.2.5p17 (real floating + integer)
1606 bool isArithmeticType() const; // C99 6.2.5p18 (integer + floating)
1607 bool isVoidType() const; // C99 6.2.5p19
1608 bool isScalarType() const; // C99 6.2.5p21 (arithmetic + pointers)
1609 bool isAggregateType() const;
1610 bool isFundamentalType() const;
1611 bool isCompoundType() const;
1613 // Type Predicates: Check to see if this type is structurally the specified
1614 // type, ignoring typedefs and qualifiers.
1615 bool isFunctionType() const;
1616 bool isFunctionNoProtoType() const { return getAs<FunctionNoProtoType>(); }
1617 bool isFunctionProtoType() const { return getAs<FunctionProtoType>(); }
1618 bool isPointerType() const;
1619 bool isAnyPointerType() const; // Any C pointer or ObjC object pointer
1620 bool isBlockPointerType() const;
1621 bool isVoidPointerType() const;
1622 bool isReferenceType() const;
1623 bool isLValueReferenceType() const;
1624 bool isRValueReferenceType() const;
1625 bool isFunctionPointerType() const;
1626 bool isMemberPointerType() const;
1627 bool isMemberFunctionPointerType() const;
1628 bool isMemberDataPointerType() const;
1629 bool isArrayType() const;
1630 bool isConstantArrayType() const;
1631 bool isIncompleteArrayType() const;
1632 bool isVariableArrayType() const;
1633 bool isDependentSizedArrayType() const;
1634 bool isRecordType() const;
1635 bool isClassType() const;
1636 bool isStructureType() const;
1637 bool isObjCBoxableRecordType() const;
1638 bool isInterfaceType() const;
1639 bool isStructureOrClassType() const;
1640 bool isUnionType() const;
1641 bool isComplexIntegerType() const; // GCC _Complex integer type.
1642 bool isVectorType() const; // GCC vector type.
1643 bool isExtVectorType() const; // Extended vector type.
1644 bool isObjCObjectPointerType() const; // pointer to ObjC object
1645 bool isObjCRetainableType() const; // ObjC object or block pointer
1646 bool isObjCLifetimeType() const; // (array of)* retainable type
1647 bool isObjCIndirectLifetimeType() const; // (pointer to)* lifetime type
1648 bool isObjCNSObjectType() const; // __attribute__((NSObject))
1649 bool isObjCIndependentClassType() const; // __attribute__((objc_independent_class))
1650 // FIXME: change this to 'raw' interface type, so we can used 'interface' type
1651 // for the common case.
1652 bool isObjCObjectType() const; // NSString or typeof(*(id)0)
1653 bool isObjCQualifiedInterfaceType() const; // NSString<foo>
1654 bool isObjCQualifiedIdType() const; // id<foo>
1655 bool isObjCQualifiedClassType() const; // Class<foo>
1656 bool isObjCObjectOrInterfaceType() const;
1657 bool isObjCIdType() const; // id
1659 /// Whether the type is Objective-C 'id' or a __kindof type of an
1660 /// object type, e.g., __kindof NSView * or __kindof id
1663 /// \param bound Will be set to the bound on non-id subtype types,
1664 /// which will be (possibly specialized) Objective-C class type, or
1666 bool isObjCIdOrObjectKindOfType(const ASTContext &ctx,
1667 const ObjCObjectType *&bound) const;
1669 bool isObjCClassType() const; // Class
1671 /// Whether the type is Objective-C 'Class' or a __kindof type of an
1672 /// Class type, e.g., __kindof Class <NSCopying>.
1674 /// Unlike \c isObjCIdOrObjectKindOfType, there is no relevant bound
1675 /// here because Objective-C's type system cannot express "a class
1676 /// object for a subclass of NSFoo".
1677 bool isObjCClassOrClassKindOfType() const;
1679 bool isBlockCompatibleObjCPointerType(ASTContext &ctx) const;
1680 bool isObjCSelType() const; // Class
1681 bool isObjCBuiltinType() const; // 'id' or 'Class'
1682 bool isObjCARCBridgableType() const;
1683 bool isCARCBridgableType() const;
1684 bool isTemplateTypeParmType() const; // C++ template type parameter
1685 bool isNullPtrType() const; // C++0x nullptr_t
1686 bool isAtomicType() const; // C11 _Atomic()
1688 bool isImage1dT() const; // OpenCL image1d_t
1689 bool isImage1dArrayT() const; // OpenCL image1d_array_t
1690 bool isImage1dBufferT() const; // OpenCL image1d_buffer_t
1691 bool isImage2dT() const; // OpenCL image2d_t
1692 bool isImage2dArrayT() const; // OpenCL image2d_array_t
1693 bool isImage3dT() const; // OpenCL image3d_t
1695 bool isImageType() const; // Any OpenCL image type
1697 bool isSamplerT() const; // OpenCL sampler_t
1698 bool isEventT() const; // OpenCL event_t
1700 bool isOpenCLSpecificType() const; // Any OpenCL specific type
1702 /// Determines if this type, which must satisfy
1703 /// isObjCLifetimeType(), is implicitly __unsafe_unretained rather
1704 /// than implicitly __strong.
1705 bool isObjCARCImplicitlyUnretainedType() const;
1707 /// Return the implicit lifetime for this type, which must not be dependent.
1708 Qualifiers::ObjCLifetime getObjCARCImplicitLifetime() const;
1710 enum ScalarTypeKind {
1713 STK_ObjCObjectPointer,
1718 STK_IntegralComplex,
1721 /// getScalarTypeKind - Given that this is a scalar type, classify it.
1722 ScalarTypeKind getScalarTypeKind() const;
1724 /// isDependentType - Whether this type is a dependent type, meaning
1725 /// that its definition somehow depends on a template parameter
1726 /// (C++ [temp.dep.type]).
1727 bool isDependentType() const { return TypeBits.Dependent; }
1729 /// \brief Determine whether this type is an instantiation-dependent type,
1730 /// meaning that the type involves a template parameter (even if the
1731 /// definition does not actually depend on the type substituted for that
1732 /// template parameter).
1733 bool isInstantiationDependentType() const {
1734 return TypeBits.InstantiationDependent;
1737 /// \brief Determine whether this type is an undeduced type, meaning that
1738 /// it somehow involves a C++11 'auto' type which has not yet been deduced.
1739 bool isUndeducedType() const;
1741 /// \brief Whether this type is a variably-modified type (C99 6.7.5).
1742 bool isVariablyModifiedType() const { return TypeBits.VariablyModified; }
1744 /// \brief Whether this type involves a variable-length array type
1745 /// with a definite size.
1746 bool hasSizedVLAType() const;
1748 /// \brief Whether this type is or contains a local or unnamed type.
1749 bool hasUnnamedOrLocalType() const;
1751 bool isOverloadableType() const;
1753 /// \brief Determine wither this type is a C++ elaborated-type-specifier.
1754 bool isElaboratedTypeSpecifier() const;
1756 bool canDecayToPointerType() const;
1758 /// hasPointerRepresentation - Whether this type is represented
1759 /// natively as a pointer; this includes pointers, references, block
1760 /// pointers, and Objective-C interface, qualified id, and qualified
1761 /// interface types, as well as nullptr_t.
1762 bool hasPointerRepresentation() const;
1764 /// hasObjCPointerRepresentation - Whether this type can represent
1765 /// an objective pointer type for the purpose of GC'ability
1766 bool hasObjCPointerRepresentation() const;
1768 /// \brief Determine whether this type has an integer representation
1769 /// of some sort, e.g., it is an integer type or a vector.
1770 bool hasIntegerRepresentation() const;
1772 /// \brief Determine whether this type has an signed integer representation
1773 /// of some sort, e.g., it is an signed integer type or a vector.
1774 bool hasSignedIntegerRepresentation() const;
1776 /// \brief Determine whether this type has an unsigned integer representation
1777 /// of some sort, e.g., it is an unsigned integer type or a vector.
1778 bool hasUnsignedIntegerRepresentation() const;
1780 /// \brief Determine whether this type has a floating-point representation
1781 /// of some sort, e.g., it is a floating-point type or a vector thereof.
1782 bool hasFloatingRepresentation() const;
1784 // Type Checking Functions: Check to see if this type is structurally the
1785 // specified type, ignoring typedefs and qualifiers, and return a pointer to
1786 // the best type we can.
1787 const RecordType *getAsStructureType() const;
1788 /// NOTE: getAs*ArrayType are methods on ASTContext.
1789 const RecordType *getAsUnionType() const;
1790 const ComplexType *getAsComplexIntegerType() const; // GCC complex int type.
1791 const ObjCObjectType *getAsObjCInterfaceType() const;
1792 // The following is a convenience method that returns an ObjCObjectPointerType
1793 // for object declared using an interface.
1794 const ObjCObjectPointerType *getAsObjCInterfacePointerType() const;
1795 const ObjCObjectPointerType *getAsObjCQualifiedIdType() const;
1796 const ObjCObjectPointerType *getAsObjCQualifiedClassType() const;
1797 const ObjCObjectType *getAsObjCQualifiedInterfaceType() const;
1799 /// \brief Retrieves the CXXRecordDecl that this type refers to, either
1800 /// because the type is a RecordType or because it is the injected-class-name
1801 /// type of a class template or class template partial specialization.
1802 CXXRecordDecl *getAsCXXRecordDecl() const;
1804 /// \brief Retrieves the TagDecl that this type refers to, either
1805 /// because the type is a TagType or because it is the injected-class-name
1806 /// type of a class template or class template partial specialization.
1807 TagDecl *getAsTagDecl() const;
1809 /// If this is a pointer or reference to a RecordType, return the
1810 /// CXXRecordDecl that that type refers to.
1812 /// If this is not a pointer or reference, or the type being pointed to does
1813 /// not refer to a CXXRecordDecl, returns NULL.
1814 const CXXRecordDecl *getPointeeCXXRecordDecl() const;
1816 /// \brief Get the AutoType whose type will be deduced for a variable with
1817 /// an initializer of this type. This looks through declarators like pointer
1818 /// types, but not through decltype or typedefs.
1819 AutoType *getContainedAutoType() const;
1821 /// Member-template getAs<specific type>'. Look through sugar for
1822 /// an instance of \<specific type>. This scheme will eventually
1823 /// replace the specific getAsXXXX methods above.
1825 /// There are some specializations of this member template listed
1826 /// immediately following this class.
1827 template <typename T> const T *getAs() const;
1829 /// A variant of getAs<> for array types which silently discards
1830 /// qualifiers from the outermost type.
1831 const ArrayType *getAsArrayTypeUnsafe() const;
1833 /// Member-template castAs<specific type>. Look through sugar for
1834 /// the underlying instance of \<specific type>.
1836 /// This method has the same relationship to getAs<T> as cast<T> has
1837 /// to dyn_cast<T>; which is to say, the underlying type *must*
1838 /// have the intended type, and this method will never return null.
1839 template <typename T> const T *castAs() const;
1841 /// A variant of castAs<> for array type which silently discards
1842 /// qualifiers from the outermost type.
1843 const ArrayType *castAsArrayTypeUnsafe() const;
1845 /// getBaseElementTypeUnsafe - Get the base element type of this
1846 /// type, potentially discarding type qualifiers. This method
1847 /// should never be used when type qualifiers are meaningful.
1848 const Type *getBaseElementTypeUnsafe() const;
1850 /// getArrayElementTypeNoTypeQual - If this is an array type, return the
1851 /// element type of the array, potentially with type qualifiers missing.
1852 /// This method should never be used when type qualifiers are meaningful.
1853 const Type *getArrayElementTypeNoTypeQual() const;
1855 /// getPointeeType - If this is a pointer, ObjC object pointer, or block
1856 /// pointer, this returns the respective pointee.
1857 QualType getPointeeType() const;
1859 /// getUnqualifiedDesugaredType() - Return the specified type with
1860 /// any "sugar" removed from the type, removing any typedefs,
1861 /// typeofs, etc., as well as any qualifiers.
1862 const Type *getUnqualifiedDesugaredType() const;
1864 /// More type predicates useful for type checking/promotion
1865 bool isPromotableIntegerType() const; // C99 6.3.1.1p2
1867 /// isSignedIntegerType - Return true if this is an integer type that is
1868 /// signed, according to C99 6.2.5p4 [char, signed char, short, int, long..],
1869 /// or an enum decl which has a signed representation.
1870 bool isSignedIntegerType() const;
1872 /// isUnsignedIntegerType - Return true if this is an integer type that is
1873 /// unsigned, according to C99 6.2.5p6 [which returns true for _Bool],
1874 /// or an enum decl which has an unsigned representation.
1875 bool isUnsignedIntegerType() const;
1877 /// Determines whether this is an integer type that is signed or an
1878 /// enumeration types whose underlying type is a signed integer type.
1879 bool isSignedIntegerOrEnumerationType() const;
1881 /// Determines whether this is an integer type that is unsigned or an
1882 /// enumeration types whose underlying type is a unsigned integer type.
1883 bool isUnsignedIntegerOrEnumerationType() const;
1885 /// isConstantSizeType - Return true if this is not a variable sized type,
1886 /// according to the rules of C99 6.7.5p3. It is not legal to call this on
1887 /// incomplete types.
1888 bool isConstantSizeType() const;
1890 /// isSpecifierType - Returns true if this type can be represented by some
1891 /// set of type specifiers.
1892 bool isSpecifierType() const;
1894 /// \brief Determine the linkage of this type.
1895 Linkage getLinkage() const;
1897 /// \brief Determine the visibility of this type.
1898 Visibility getVisibility() const {
1899 return getLinkageAndVisibility().getVisibility();
1902 /// \brief Return true if the visibility was explicitly set is the code.
1903 bool isVisibilityExplicit() const {
1904 return getLinkageAndVisibility().isVisibilityExplicit();
1907 /// \brief Determine the linkage and visibility of this type.
1908 LinkageInfo getLinkageAndVisibility() const;
1910 /// \brief True if the computed linkage is valid. Used for consistency
1911 /// checking. Should always return true.
1912 bool isLinkageValid() const;
1914 /// Determine the nullability of the given type.
1916 /// Note that nullability is only captured as sugar within the type
1917 /// system, not as part of the canonical type, so nullability will
1918 /// be lost by canonicalization and desugaring.
1919 Optional<NullabilityKind> getNullability(const ASTContext &context) const;
1921 /// Determine whether the given type can have a nullability
1922 /// specifier applied to it, i.e., if it is any kind of pointer type
1923 /// or a dependent type that could instantiate to any kind of
1925 bool canHaveNullability() const;
1927 /// Retrieve the set of substitutions required when accessing a member
1928 /// of the Objective-C receiver type that is declared in the given context.
1930 /// \c *this is the type of the object we're operating on, e.g., the
1931 /// receiver for a message send or the base of a property access, and is
1932 /// expected to be of some object or object pointer type.
1934 /// \param dc The declaration context for which we are building up a
1935 /// substitution mapping, which should be an Objective-C class, extension,
1936 /// category, or method within.
1938 /// \returns an array of type arguments that can be substituted for
1939 /// the type parameters of the given declaration context in any type described
1940 /// within that context, or an empty optional to indicate that no
1941 /// substitution is required.
1942 Optional<ArrayRef<QualType>>
1943 getObjCSubstitutions(const DeclContext *dc) const;
1945 /// Determines if this is an ObjC interface type that may accept type
1947 bool acceptsObjCTypeParams() const;
1949 const char *getTypeClassName() const;
1951 QualType getCanonicalTypeInternal() const {
1952 return CanonicalType;
1954 CanQualType getCanonicalTypeUnqualified() const; // in CanonicalType.h
1957 friend class ASTReader;
1958 friend class ASTWriter;
1961 /// \brief This will check for a TypedefType by removing any existing sugar
1962 /// until it reaches a TypedefType or a non-sugared type.
1963 template <> const TypedefType *Type::getAs() const;
1965 /// \brief This will check for a TemplateSpecializationType by removing any
1966 /// existing sugar until it reaches a TemplateSpecializationType or a
1967 /// non-sugared type.
1968 template <> const TemplateSpecializationType *Type::getAs() const;
1970 /// \brief This will check for an AttributedType by removing any existing sugar
1971 /// until it reaches an AttributedType or a non-sugared type.
1972 template <> const AttributedType *Type::getAs() const;
1974 // We can do canonical leaf types faster, because we don't have to
1975 // worry about preserving child type decoration.
1976 #define TYPE(Class, Base)
1977 #define LEAF_TYPE(Class) \
1978 template <> inline const Class##Type *Type::getAs() const { \
1979 return dyn_cast<Class##Type>(CanonicalType); \
1981 template <> inline const Class##Type *Type::castAs() const { \
1982 return cast<Class##Type>(CanonicalType); \
1984 #include "clang/AST/TypeNodes.def"
1987 /// BuiltinType - This class is used for builtin types like 'int'. Builtin
1988 /// types are always canonical and have a literal name field.
1989 class BuiltinType : public Type {
1992 #define BUILTIN_TYPE(Id, SingletonId) Id,
1993 #define LAST_BUILTIN_TYPE(Id) LastKind = Id
1994 #include "clang/AST/BuiltinTypes.def"
1999 : Type(Builtin, QualType(), /*Dependent=*/(K == Dependent),
2000 /*InstantiationDependent=*/(K == Dependent),
2001 /*VariablyModified=*/false,
2002 /*Unexpanded paramter pack=*/false) {
2003 BuiltinTypeBits.Kind = K;
2006 Kind getKind() const { return static_cast<Kind>(BuiltinTypeBits.Kind); }
2007 StringRef getName(const PrintingPolicy &Policy) const;
2008 const char *getNameAsCString(const PrintingPolicy &Policy) const {
2009 // The StringRef is null-terminated.
2010 StringRef str = getName(Policy);
2011 assert(!str.empty() && str.data()[str.size()] == '\0');
2015 bool isSugared() const { return false; }
2016 QualType desugar() const { return QualType(this, 0); }
2018 bool isInteger() const {
2019 return getKind() >= Bool && getKind() <= Int128;
2022 bool isSignedInteger() const {
2023 return getKind() >= Char_S && getKind() <= Int128;
2026 bool isUnsignedInteger() const {
2027 return getKind() >= Bool && getKind() <= UInt128;
2030 bool isFloatingPoint() const {
2031 return getKind() >= Half && getKind() <= LongDouble;
2034 /// Determines whether the given kind corresponds to a placeholder type.
2035 static bool isPlaceholderTypeKind(Kind K) {
2036 return K >= Overload;
2039 /// Determines whether this type is a placeholder type, i.e. a type
2040 /// which cannot appear in arbitrary positions in a fully-formed
2042 bool isPlaceholderType() const {
2043 return isPlaceholderTypeKind(getKind());
2046 /// Determines whether this type is a placeholder type other than
2047 /// Overload. Most placeholder types require only syntactic
2048 /// information about their context in order to be resolved (e.g.
2049 /// whether it is a call expression), which means they can (and
2050 /// should) be resolved in an earlier "phase" of analysis.
2051 /// Overload expressions sometimes pick up further information
2052 /// from their context, like whether the context expects a
2053 /// specific function-pointer type, and so frequently need
2054 /// special treatment.
2055 bool isNonOverloadPlaceholderType() const {
2056 return getKind() > Overload;
2059 static bool classof(const Type *T) { return T->getTypeClass() == Builtin; }
2062 /// ComplexType - C99 6.2.5p11 - Complex values. This supports the C99 complex
2063 /// types (_Complex float etc) as well as the GCC integer complex extensions.
2065 class ComplexType : public Type, public llvm::FoldingSetNode {
2066 QualType ElementType;
2067 ComplexType(QualType Element, QualType CanonicalPtr) :
2068 Type(Complex, CanonicalPtr, Element->isDependentType(),
2069 Element->isInstantiationDependentType(),
2070 Element->isVariablyModifiedType(),
2071 Element->containsUnexpandedParameterPack()),
2072 ElementType(Element) {
2074 friend class ASTContext; // ASTContext creates these.
2077 QualType getElementType() const { return ElementType; }
2079 bool isSugared() const { return false; }
2080 QualType desugar() const { return QualType(this, 0); }
2082 void Profile(llvm::FoldingSetNodeID &ID) {
2083 Profile(ID, getElementType());
2085 static void Profile(llvm::FoldingSetNodeID &ID, QualType Element) {
2086 ID.AddPointer(Element.getAsOpaquePtr());
2089 static bool classof(const Type *T) { return T->getTypeClass() == Complex; }
2092 /// ParenType - Sugar for parentheses used when specifying types.
2094 class ParenType : public Type, public llvm::FoldingSetNode {
2097 ParenType(QualType InnerType, QualType CanonType) :
2098 Type(Paren, CanonType, InnerType->isDependentType(),
2099 InnerType->isInstantiationDependentType(),
2100 InnerType->isVariablyModifiedType(),
2101 InnerType->containsUnexpandedParameterPack()),
2104 friend class ASTContext; // ASTContext creates these.
2108 QualType getInnerType() const { return Inner; }
2110 bool isSugared() const { return true; }
2111 QualType desugar() const { return getInnerType(); }
2113 void Profile(llvm::FoldingSetNodeID &ID) {
2114 Profile(ID, getInnerType());
2116 static void Profile(llvm::FoldingSetNodeID &ID, QualType Inner) {
2120 static bool classof(const Type *T) { return T->getTypeClass() == Paren; }
2123 /// PointerType - C99 6.7.5.1 - Pointer Declarators.
2125 class PointerType : public Type, public llvm::FoldingSetNode {
2126 QualType PointeeType;
2128 PointerType(QualType Pointee, QualType CanonicalPtr) :
2129 Type(Pointer, CanonicalPtr, Pointee->isDependentType(),
2130 Pointee->isInstantiationDependentType(),
2131 Pointee->isVariablyModifiedType(),
2132 Pointee->containsUnexpandedParameterPack()),
2133 PointeeType(Pointee) {
2135 friend class ASTContext; // ASTContext creates these.
2139 QualType getPointeeType() const { return PointeeType; }
2141 /// \brief Returns true if address spaces of pointers overlap.
2142 /// OpenCL v2.0 defines conversion rules for pointers to different
2143 /// address spaces (OpenCLC v2.0 s6.5.5) and notion of overlapping
2146 /// address spaces overlap iff they are they same.
2148 /// __generic overlaps with any address space except for __constant.
2149 bool isAddressSpaceOverlapping(const PointerType &other) const {
2150 Qualifiers thisQuals = PointeeType.getQualifiers();
2151 Qualifiers otherQuals = other.getPointeeType().getQualifiers();
2152 // Address spaces overlap if at least one of them is a superset of another
2153 return thisQuals.isAddressSpaceSupersetOf(otherQuals) ||
2154 otherQuals.isAddressSpaceSupersetOf(thisQuals);
2157 bool isSugared() const { return false; }
2158 QualType desugar() const { return QualType(this, 0); }
2160 void Profile(llvm::FoldingSetNodeID &ID) {
2161 Profile(ID, getPointeeType());
2163 static void Profile(llvm::FoldingSetNodeID &ID, QualType Pointee) {
2164 ID.AddPointer(Pointee.getAsOpaquePtr());
2167 static bool classof(const Type *T) { return T->getTypeClass() == Pointer; }
2170 /// \brief Represents a type which was implicitly adjusted by the semantic
2171 /// engine for arbitrary reasons. For example, array and function types can
2172 /// decay, and function types can have their calling conventions adjusted.
2173 class AdjustedType : public Type, public llvm::FoldingSetNode {
2174 QualType OriginalTy;
2175 QualType AdjustedTy;
2178 AdjustedType(TypeClass TC, QualType OriginalTy, QualType AdjustedTy,
2179 QualType CanonicalPtr)
2180 : Type(TC, CanonicalPtr, OriginalTy->isDependentType(),
2181 OriginalTy->isInstantiationDependentType(),
2182 OriginalTy->isVariablyModifiedType(),
2183 OriginalTy->containsUnexpandedParameterPack()),
2184 OriginalTy(OriginalTy), AdjustedTy(AdjustedTy) {}
2186 friend class ASTContext; // ASTContext creates these.
2189 QualType getOriginalType() const { return OriginalTy; }
2190 QualType getAdjustedType() const { return AdjustedTy; }
2192 bool isSugared() const { return true; }
2193 QualType desugar() const { return AdjustedTy; }
2195 void Profile(llvm::FoldingSetNodeID &ID) {
2196 Profile(ID, OriginalTy, AdjustedTy);
2198 static void Profile(llvm::FoldingSetNodeID &ID, QualType Orig, QualType New) {
2199 ID.AddPointer(Orig.getAsOpaquePtr());
2200 ID.AddPointer(New.getAsOpaquePtr());
2203 static bool classof(const Type *T) {
2204 return T->getTypeClass() == Adjusted || T->getTypeClass() == Decayed;
2208 /// \brief Represents a pointer type decayed from an array or function type.
2209 class DecayedType : public AdjustedType {
2211 DecayedType(QualType OriginalType, QualType DecayedPtr, QualType CanonicalPtr)
2212 : AdjustedType(Decayed, OriginalType, DecayedPtr, CanonicalPtr) {
2213 assert(isa<PointerType>(getAdjustedType()));
2216 friend class ASTContext; // ASTContext creates these.
2219 QualType getDecayedType() const { return getAdjustedType(); }
2221 QualType getPointeeType() const {
2222 return cast<PointerType>(getDecayedType())->getPointeeType();
2225 static bool classof(const Type *T) { return T->getTypeClass() == Decayed; }
2228 /// BlockPointerType - pointer to a block type.
2229 /// This type is to represent types syntactically represented as
2230 /// "void (^)(int)", etc. Pointee is required to always be a function type.
2232 class BlockPointerType : public Type, public llvm::FoldingSetNode {
2233 QualType PointeeType; // Block is some kind of pointer type
2234 BlockPointerType(QualType Pointee, QualType CanonicalCls) :
2235 Type(BlockPointer, CanonicalCls, Pointee->isDependentType(),
2236 Pointee->isInstantiationDependentType(),
2237 Pointee->isVariablyModifiedType(),
2238 Pointee->containsUnexpandedParameterPack()),
2239 PointeeType(Pointee) {
2241 friend class ASTContext; // ASTContext creates these.
2245 // Get the pointee type. Pointee is required to always be a function type.
2246 QualType getPointeeType() const { return PointeeType; }
2248 bool isSugared() const { return false; }
2249 QualType desugar() const { return QualType(this, 0); }
2251 void Profile(llvm::FoldingSetNodeID &ID) {
2252 Profile(ID, getPointeeType());
2254 static void Profile(llvm::FoldingSetNodeID &ID, QualType Pointee) {
2255 ID.AddPointer(Pointee.getAsOpaquePtr());
2258 static bool classof(const Type *T) {
2259 return T->getTypeClass() == BlockPointer;
2263 /// ReferenceType - Base for LValueReferenceType and RValueReferenceType
2265 class ReferenceType : public Type, public llvm::FoldingSetNode {
2266 QualType PointeeType;
2269 ReferenceType(TypeClass tc, QualType Referencee, QualType CanonicalRef,
2270 bool SpelledAsLValue) :
2271 Type(tc, CanonicalRef, Referencee->isDependentType(),
2272 Referencee->isInstantiationDependentType(),
2273 Referencee->isVariablyModifiedType(),
2274 Referencee->containsUnexpandedParameterPack()),
2275 PointeeType(Referencee)
2277 ReferenceTypeBits.SpelledAsLValue = SpelledAsLValue;
2278 ReferenceTypeBits.InnerRef = Referencee->isReferenceType();
2282 bool isSpelledAsLValue() const { return ReferenceTypeBits.SpelledAsLValue; }
2283 bool isInnerRef() const { return ReferenceTypeBits.InnerRef; }
2285 QualType getPointeeTypeAsWritten() const { return PointeeType; }
2286 QualType getPointeeType() const {
2287 // FIXME: this might strip inner qualifiers; okay?
2288 const ReferenceType *T = this;
2289 while (T->isInnerRef())
2290 T = T->PointeeType->castAs<ReferenceType>();
2291 return T->PointeeType;
2294 void Profile(llvm::FoldingSetNodeID &ID) {
2295 Profile(ID, PointeeType, isSpelledAsLValue());
2297 static void Profile(llvm::FoldingSetNodeID &ID,
2298 QualType Referencee,
2299 bool SpelledAsLValue) {
2300 ID.AddPointer(Referencee.getAsOpaquePtr());
2301 ID.AddBoolean(SpelledAsLValue);
2304 static bool classof(const Type *T) {
2305 return T->getTypeClass() == LValueReference ||
2306 T->getTypeClass() == RValueReference;
2310 /// LValueReferenceType - C++ [dcl.ref] - Lvalue reference
2312 class LValueReferenceType : public ReferenceType {
2313 LValueReferenceType(QualType Referencee, QualType CanonicalRef,
2314 bool SpelledAsLValue) :
2315 ReferenceType(LValueReference, Referencee, CanonicalRef, SpelledAsLValue)
2317 friend class ASTContext; // ASTContext creates these
2319 bool isSugared() const { return false; }
2320 QualType desugar() const { return QualType(this, 0); }
2322 static bool classof(const Type *T) {
2323 return T->getTypeClass() == LValueReference;
2327 /// RValueReferenceType - C++0x [dcl.ref] - Rvalue reference
2329 class RValueReferenceType : public ReferenceType {
2330 RValueReferenceType(QualType Referencee, QualType CanonicalRef) :
2331 ReferenceType(RValueReference, Referencee, CanonicalRef, false) {
2333 friend class ASTContext; // ASTContext creates these
2335 bool isSugared() const { return false; }
2336 QualType desugar() const { return QualType(this, 0); }
2338 static bool classof(const Type *T) {
2339 return T->getTypeClass() == RValueReference;
2343 /// MemberPointerType - C++ 8.3.3 - Pointers to members
2345 class MemberPointerType : public Type, public llvm::FoldingSetNode {
2346 QualType PointeeType;
2347 /// The class of which the pointee is a member. Must ultimately be a
2348 /// RecordType, but could be a typedef or a template parameter too.
2351 MemberPointerType(QualType Pointee, const Type *Cls, QualType CanonicalPtr) :
2352 Type(MemberPointer, CanonicalPtr,
2353 Cls->isDependentType() || Pointee->isDependentType(),
2354 (Cls->isInstantiationDependentType() ||
2355 Pointee->isInstantiationDependentType()),
2356 Pointee->isVariablyModifiedType(),
2357 (Cls->containsUnexpandedParameterPack() ||
2358 Pointee->containsUnexpandedParameterPack())),
2359 PointeeType(Pointee), Class(Cls) {
2361 friend class ASTContext; // ASTContext creates these.
2364 QualType getPointeeType() const { return PointeeType; }
2366 /// Returns true if the member type (i.e. the pointee type) is a
2367 /// function type rather than a data-member type.
2368 bool isMemberFunctionPointer() const {
2369 return PointeeType->isFunctionProtoType();
2372 /// Returns true if the member type (i.e. the pointee type) is a
2373 /// data type rather than a function type.
2374 bool isMemberDataPointer() const {
2375 return !PointeeType->isFunctionProtoType();
2378 const Type *getClass() const { return Class; }
2379 CXXRecordDecl *getMostRecentCXXRecordDecl() const;
2381 bool isSugared() const { return false; }
2382 QualType desugar() const { return QualType(this, 0); }
2384 void Profile(llvm::FoldingSetNodeID &ID) {
2385 Profile(ID, getPointeeType(), getClass());
2387 static void Profile(llvm::FoldingSetNodeID &ID, QualType Pointee,
2388 const Type *Class) {
2389 ID.AddPointer(Pointee.getAsOpaquePtr());
2390 ID.AddPointer(Class);
2393 static bool classof(const Type *T) {
2394 return T->getTypeClass() == MemberPointer;
2398 /// ArrayType - C99 6.7.5.2 - Array Declarators.
2400 class ArrayType : public Type, public llvm::FoldingSetNode {
2402 /// ArraySizeModifier - Capture whether this is a normal array (e.g. int X[4])
2403 /// an array with a static size (e.g. int X[static 4]), or an array
2404 /// with a star size (e.g. int X[*]).
2405 /// 'static' is only allowed on function parameters.
2406 enum ArraySizeModifier {
2407 Normal, Static, Star
2410 /// ElementType - The element type of the array.
2411 QualType ElementType;
2414 // C++ [temp.dep.type]p1:
2415 // A type is dependent if it is...
2416 // - an array type constructed from any dependent type or whose
2417 // size is specified by a constant expression that is
2419 ArrayType(TypeClass tc, QualType et, QualType can,
2420 ArraySizeModifier sm, unsigned tq,
2421 bool ContainsUnexpandedParameterPack)
2422 : Type(tc, can, et->isDependentType() || tc == DependentSizedArray,
2423 et->isInstantiationDependentType() || tc == DependentSizedArray,
2424 (tc == VariableArray || et->isVariablyModifiedType()),
2425 ContainsUnexpandedParameterPack),
2427 ArrayTypeBits.IndexTypeQuals = tq;
2428 ArrayTypeBits.SizeModifier = sm;
2431 friend class ASTContext; // ASTContext creates these.
2434 QualType getElementType() const { return ElementType; }
2435 ArraySizeModifier getSizeModifier() const {
2436 return ArraySizeModifier(ArrayTypeBits.SizeModifier);
2438 Qualifiers getIndexTypeQualifiers() const {
2439 return Qualifiers::fromCVRMask(getIndexTypeCVRQualifiers());
2441 unsigned getIndexTypeCVRQualifiers() const {
2442 return ArrayTypeBits.IndexTypeQuals;
2445 static bool classof(const Type *T) {
2446 return T->getTypeClass() == ConstantArray ||
2447 T->getTypeClass() == VariableArray ||
2448 T->getTypeClass() == IncompleteArray ||
2449 T->getTypeClass() == DependentSizedArray;
2453 /// ConstantArrayType - This class represents the canonical version of
2454 /// C arrays with a specified constant size. For example, the canonical
2455 /// type for 'int A[4 + 4*100]' is a ConstantArrayType where the element
2456 /// type is 'int' and the size is 404.
2457 class ConstantArrayType : public ArrayType {
2458 llvm::APInt Size; // Allows us to unique the type.
2460 ConstantArrayType(QualType et, QualType can, const llvm::APInt &size,
2461 ArraySizeModifier sm, unsigned tq)
2462 : ArrayType(ConstantArray, et, can, sm, tq,
2463 et->containsUnexpandedParameterPack()),
2466 ConstantArrayType(TypeClass tc, QualType et, QualType can,
2467 const llvm::APInt &size, ArraySizeModifier sm, unsigned tq)
2468 : ArrayType(tc, et, can, sm, tq, et->containsUnexpandedParameterPack()),
2470 friend class ASTContext; // ASTContext creates these.
2472 const llvm::APInt &getSize() const { return Size; }
2473 bool isSugared() const { return false; }
2474 QualType desugar() const { return QualType(this, 0); }
2477 /// \brief Determine the number of bits required to address a member of
2478 // an array with the given element type and number of elements.
2479 static unsigned getNumAddressingBits(ASTContext &Context,
2480 QualType ElementType,
2481 const llvm::APInt &NumElements);
2483 /// \brief Determine the maximum number of active bits that an array's size
2484 /// can require, which limits the maximum size of the array.
2485 static unsigned getMaxSizeBits(ASTContext &Context);
2487 void Profile(llvm::FoldingSetNodeID &ID) {
2488 Profile(ID, getElementType(), getSize(),
2489 getSizeModifier(), getIndexTypeCVRQualifiers());
2491 static void Profile(llvm::FoldingSetNodeID &ID, QualType ET,
2492 const llvm::APInt &ArraySize, ArraySizeModifier SizeMod,
2493 unsigned TypeQuals) {
2494 ID.AddPointer(ET.getAsOpaquePtr());
2495 ID.AddInteger(ArraySize.getZExtValue());
2496 ID.AddInteger(SizeMod);
2497 ID.AddInteger(TypeQuals);
2499 static bool classof(const Type *T) {
2500 return T->getTypeClass() == ConstantArray;
2504 /// IncompleteArrayType - This class represents C arrays with an unspecified
2505 /// size. For example 'int A[]' has an IncompleteArrayType where the element
2506 /// type is 'int' and the size is unspecified.
2507 class IncompleteArrayType : public ArrayType {
2509 IncompleteArrayType(QualType et, QualType can,
2510 ArraySizeModifier sm, unsigned tq)
2511 : ArrayType(IncompleteArray, et, can, sm, tq,
2512 et->containsUnexpandedParameterPack()) {}
2513 friend class ASTContext; // ASTContext creates these.
2515 bool isSugared() const { return false; }
2516 QualType desugar() const { return QualType(this, 0); }
2518 static bool classof(const Type *T) {
2519 return T->getTypeClass() == IncompleteArray;
2522 friend class StmtIteratorBase;
2524 void Profile(llvm::FoldingSetNodeID &ID) {
2525 Profile(ID, getElementType(), getSizeModifier(),
2526 getIndexTypeCVRQualifiers());
2529 static void Profile(llvm::FoldingSetNodeID &ID, QualType ET,
2530 ArraySizeModifier SizeMod, unsigned TypeQuals) {
2531 ID.AddPointer(ET.getAsOpaquePtr());
2532 ID.AddInteger(SizeMod);
2533 ID.AddInteger(TypeQuals);
2537 /// VariableArrayType - This class represents C arrays with a specified size
2538 /// which is not an integer-constant-expression. For example, 'int s[x+foo()]'.
2539 /// Since the size expression is an arbitrary expression, we store it as such.
2541 /// Note: VariableArrayType's aren't uniqued (since the expressions aren't) and
2542 /// should not be: two lexically equivalent variable array types could mean
2543 /// different things, for example, these variables do not have the same type
2546 /// void foo(int x) {
2552 class VariableArrayType : public ArrayType {
2553 /// SizeExpr - An assignment expression. VLA's are only permitted within
2554 /// a function block.
2556 /// Brackets - The left and right array brackets.
2557 SourceRange Brackets;
2559 VariableArrayType(QualType et, QualType can, Expr *e,
2560 ArraySizeModifier sm, unsigned tq,
2561 SourceRange brackets)
2562 : ArrayType(VariableArray, et, can, sm, tq,
2563 et->containsUnexpandedParameterPack()),
2564 SizeExpr((Stmt*) e), Brackets(brackets) {}
2565 friend class ASTContext; // ASTContext creates these.
2568 Expr *getSizeExpr() const {
2569 // We use C-style casts instead of cast<> here because we do not wish
2570 // to have a dependency of Type.h on Stmt.h/Expr.h.
2571 return (Expr*) SizeExpr;
2573 SourceRange getBracketsRange() const { return Brackets; }
2574 SourceLocation getLBracketLoc() const { return Brackets.getBegin(); }
2575 SourceLocation getRBracketLoc() const { return Brackets.getEnd(); }
2577 bool isSugared() const { return false; }
2578 QualType desugar() const { return QualType(this, 0); }
2580 static bool classof(const Type *T) {
2581 return T->getTypeClass() == VariableArray;
2584 friend class StmtIteratorBase;
2586 void Profile(llvm::FoldingSetNodeID &ID) {
2587 llvm_unreachable("Cannot unique VariableArrayTypes.");
2591 /// DependentSizedArrayType - This type represents an array type in
2592 /// C++ whose size is a value-dependent expression. For example:
2595 /// template<typename T, int Size>
2601 /// For these types, we won't actually know what the array bound is
2602 /// until template instantiation occurs, at which point this will
2603 /// become either a ConstantArrayType or a VariableArrayType.
2604 class DependentSizedArrayType : public ArrayType {
2605 const ASTContext &Context;
2607 /// \brief An assignment expression that will instantiate to the
2608 /// size of the array.
2610 /// The expression itself might be NULL, in which case the array
2611 /// type will have its size deduced from an initializer.
2614 /// Brackets - The left and right array brackets.
2615 SourceRange Brackets;
2617 DependentSizedArrayType(const ASTContext &Context, QualType et, QualType can,
2618 Expr *e, ArraySizeModifier sm, unsigned tq,
2619 SourceRange brackets);
2621 friend class ASTContext; // ASTContext creates these.
2624 Expr *getSizeExpr() const {
2625 // We use C-style casts instead of cast<> here because we do not wish
2626 // to have a dependency of Type.h on Stmt.h/Expr.h.
2627 return (Expr*) SizeExpr;
2629 SourceRange getBracketsRange() const { return Brackets; }
2630 SourceLocation getLBracketLoc() const { return Brackets.getBegin(); }
2631 SourceLocation getRBracketLoc() const { return Brackets.getEnd(); }
2633 bool isSugared() const { return false; }
2634 QualType desugar() const { return QualType(this, 0); }
2636 static bool classof(const Type *T) {
2637 return T->getTypeClass() == DependentSizedArray;
2640 friend class StmtIteratorBase;
2643 void Profile(llvm::FoldingSetNodeID &ID) {
2644 Profile(ID, Context, getElementType(),
2645 getSizeModifier(), getIndexTypeCVRQualifiers(), getSizeExpr());
2648 static void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context,
2649 QualType ET, ArraySizeModifier SizeMod,
2650 unsigned TypeQuals, Expr *E);
2653 /// DependentSizedExtVectorType - This type represent an extended vector type
2654 /// where either the type or size is dependent. For example:
2656 /// template<typename T, int Size>
2658 /// typedef T __attribute__((ext_vector_type(Size))) type;
2661 class DependentSizedExtVectorType : public Type, public llvm::FoldingSetNode {
2662 const ASTContext &Context;
2664 /// ElementType - The element type of the array.
2665 QualType ElementType;
2668 DependentSizedExtVectorType(const ASTContext &Context, QualType ElementType,
2669 QualType can, Expr *SizeExpr, SourceLocation loc);
2671 friend class ASTContext;
2674 Expr *getSizeExpr() const { return SizeExpr; }
2675 QualType getElementType() const { return ElementType; }
2676 SourceLocation getAttributeLoc() const { return loc; }
2678 bool isSugared() const { return false; }
2679 QualType desugar() const { return QualType(this, 0); }
2681 static bool classof(const Type *T) {
2682 return T->getTypeClass() == DependentSizedExtVector;
2685 void Profile(llvm::FoldingSetNodeID &ID) {
2686 Profile(ID, Context, getElementType(), getSizeExpr());
2689 static void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context,
2690 QualType ElementType, Expr *SizeExpr);
2694 /// VectorType - GCC generic vector type. This type is created using
2695 /// __attribute__((vector_size(n)), where "n" specifies the vector size in
2696 /// bytes; or from an Altivec __vector or vector declaration.
2697 /// Since the constructor takes the number of vector elements, the
2698 /// client is responsible for converting the size into the number of elements.
2699 class VectorType : public Type, public llvm::FoldingSetNode {
2702 GenericVector, // not a target-specific vector type
2703 AltiVecVector, // is AltiVec vector
2704 AltiVecPixel, // is AltiVec 'vector Pixel'
2705 AltiVecBool, // is AltiVec 'vector bool ...'
2706 NeonVector, // is ARM Neon vector
2707 NeonPolyVector // is ARM Neon polynomial vector
2710 /// ElementType - The element type of the vector.
2711 QualType ElementType;
2713 VectorType(QualType vecType, unsigned nElements, QualType canonType,
2714 VectorKind vecKind);
2716 VectorType(TypeClass tc, QualType vecType, unsigned nElements,
2717 QualType canonType, VectorKind vecKind);
2719 friend class ASTContext; // ASTContext creates these.
2723 QualType getElementType() const { return ElementType; }
2724 unsigned getNumElements() const { return VectorTypeBits.NumElements; }
2725 static bool isVectorSizeTooLarge(unsigned NumElements) {
2726 return NumElements > VectorTypeBitfields::MaxNumElements;
2729 bool isSugared() const { return false; }
2730 QualType desugar() const { return QualType(this, 0); }
2732 VectorKind getVectorKind() const {
2733 return VectorKind(VectorTypeBits.VecKind);
2736 void Profile(llvm::FoldingSetNodeID &ID) {
2737 Profile(ID, getElementType(), getNumElements(),
2738 getTypeClass(), getVectorKind());
2740 static void Profile(llvm::FoldingSetNodeID &ID, QualType ElementType,
2741 unsigned NumElements, TypeClass TypeClass,
2742 VectorKind VecKind) {
2743 ID.AddPointer(ElementType.getAsOpaquePtr());
2744 ID.AddInteger(NumElements);
2745 ID.AddInteger(TypeClass);
2746 ID.AddInteger(VecKind);
2749 static bool classof(const Type *T) {
2750 return T->getTypeClass() == Vector || T->getTypeClass() == ExtVector;
2754 /// ExtVectorType - Extended vector type. This type is created using
2755 /// __attribute__((ext_vector_type(n)), where "n" is the number of elements.
2756 /// Unlike vector_size, ext_vector_type is only allowed on typedef's. This
2757 /// class enables syntactic extensions, like Vector Components for accessing
2758 /// points, colors, and textures (modeled after OpenGL Shading Language).
2759 class ExtVectorType : public VectorType {
2760 ExtVectorType(QualType vecType, unsigned nElements, QualType canonType) :
2761 VectorType(ExtVector, vecType, nElements, canonType, GenericVector) {}
2762 friend class ASTContext; // ASTContext creates these.
2764 static int getPointAccessorIdx(char c) {
2773 static int getNumericAccessorIdx(char c) {
2787 case 'a': return 10;
2789 case 'b': return 11;
2791 case 'c': return 12;
2793 case 'd': return 13;
2795 case 'e': return 14;
2797 case 'f': return 15;
2801 static int getAccessorIdx(char c) {
2802 if (int idx = getPointAccessorIdx(c)+1) return idx-1;
2803 return getNumericAccessorIdx(c);
2806 bool isAccessorWithinNumElements(char c) const {
2807 if (int idx = getAccessorIdx(c)+1)
2808 return unsigned(idx-1) < getNumElements();
2811 bool isSugared() const { return false; }
2812 QualType desugar() const { return QualType(this, 0); }
2814 static bool classof(const Type *T) {
2815 return T->getTypeClass() == ExtVector;
2819 /// FunctionType - C99 6.7.5.3 - Function Declarators. This is the common base
2820 /// class of FunctionNoProtoType and FunctionProtoType.
2822 class FunctionType : public Type {
2823 // The type returned by the function.
2824 QualType ResultType;
2827 /// ExtInfo - A class which abstracts out some details necessary for
2830 /// It is not actually used directly for storing this information in
2831 /// a FunctionType, although FunctionType does currently use the
2832 /// same bit-pattern.
2834 // If you add a field (say Foo), other than the obvious places (both,
2835 // constructors, compile failures), what you need to update is
2839 // * functionType. Add Foo, getFoo.
2840 // * ASTContext::getFooType
2841 // * ASTContext::mergeFunctionTypes
2842 // * FunctionNoProtoType::Profile
2843 // * FunctionProtoType::Profile
2844 // * TypePrinter::PrintFunctionProto
2845 // * AST read and write
2848 // Feel free to rearrange or add bits, but if you go over 9,
2849 // you'll need to adjust both the Bits field below and
2850 // Type::FunctionTypeBitfields.
2852 // | CC |noreturn|produces|regparm|
2853 // |0 .. 3| 4 | 5 | 6 .. 8|
2855 // regparm is either 0 (no regparm attribute) or the regparm value+1.
2856 enum { CallConvMask = 0xF };
2857 enum { NoReturnMask = 0x10 };
2858 enum { ProducesResultMask = 0x20 };
2859 enum { RegParmMask = ~(CallConvMask | NoReturnMask | ProducesResultMask),
2860 RegParmOffset = 6 }; // Assumed to be the last field
2864 ExtInfo(unsigned Bits) : Bits(static_cast<uint16_t>(Bits)) {}
2866 friend class FunctionType;
2869 // Constructor with no defaults. Use this when you know that you
2870 // have all the elements (when reading an AST file for example).
2871 ExtInfo(bool noReturn, bool hasRegParm, unsigned regParm, CallingConv cc,
2872 bool producesResult) {
2873 assert((!hasRegParm || regParm < 7) && "Invalid regparm value");
2874 Bits = ((unsigned) cc) |
2875 (noReturn ? NoReturnMask : 0) |
2876 (producesResult ? ProducesResultMask : 0) |
2877 (hasRegParm ? ((regParm + 1) << RegParmOffset) : 0);
2880 // Constructor with all defaults. Use when for example creating a
2881 // function know to use defaults.
2882 ExtInfo() : Bits(CC_C) { }
2884 // Constructor with just the calling convention, which is an important part
2885 // of the canonical type.
2886 ExtInfo(CallingConv CC) : Bits(CC) { }
2888 bool getNoReturn() const { return Bits & NoReturnMask; }
2889 bool getProducesResult() const { return Bits & ProducesResultMask; }
2890 bool getHasRegParm() const { return (Bits >> RegParmOffset) != 0; }
2891 unsigned getRegParm() const {
2892 unsigned RegParm = Bits >> RegParmOffset;
2897 CallingConv getCC() const { return CallingConv(Bits & CallConvMask); }
2899 bool operator==(ExtInfo Other) const {
2900 return Bits == Other.Bits;
2902 bool operator!=(ExtInfo Other) const {
2903 return Bits != Other.Bits;
2906 // Note that we don't have setters. That is by design, use
2907 // the following with methods instead of mutating these objects.
2909 ExtInfo withNoReturn(bool noReturn) const {
2911 return ExtInfo(Bits | NoReturnMask);
2913 return ExtInfo(Bits & ~NoReturnMask);
2916 ExtInfo withProducesResult(bool producesResult) const {
2918 return ExtInfo(Bits | ProducesResultMask);
2920 return ExtInfo(Bits & ~ProducesResultMask);
2923 ExtInfo withRegParm(unsigned RegParm) const {
2924 assert(RegParm < 7 && "Invalid regparm value");
2925 return ExtInfo((Bits & ~RegParmMask) |
2926 ((RegParm + 1) << RegParmOffset));
2929 ExtInfo withCallingConv(CallingConv cc) const {
2930 return ExtInfo((Bits & ~CallConvMask) | (unsigned) cc);
2933 void Profile(llvm::FoldingSetNodeID &ID) const {
2934 ID.AddInteger(Bits);
2939 FunctionType(TypeClass tc, QualType res,
2940 QualType Canonical, bool Dependent,
2941 bool InstantiationDependent,
2942 bool VariablyModified, bool ContainsUnexpandedParameterPack,
2944 : Type(tc, Canonical, Dependent, InstantiationDependent, VariablyModified,
2945 ContainsUnexpandedParameterPack),
2947 FunctionTypeBits.ExtInfo = Info.Bits;
2949 unsigned getTypeQuals() const { return FunctionTypeBits.TypeQuals; }
2952 QualType getReturnType() const { return ResultType; }
2954 bool getHasRegParm() const { return getExtInfo().getHasRegParm(); }
2955 unsigned getRegParmType() const { return getExtInfo().getRegParm(); }
2956 /// \brief Determine whether this function type includes the GNU noreturn
2957 /// attribute. The C++11 [[noreturn]] attribute does not affect the function
2959 bool getNoReturnAttr() const { return getExtInfo().getNoReturn(); }
2960 CallingConv getCallConv() const { return getExtInfo().getCC(); }
2961 ExtInfo getExtInfo() const { return ExtInfo(FunctionTypeBits.ExtInfo); }
2962 bool isConst() const { return getTypeQuals() & Qualifiers::Const; }
2963 bool isVolatile() const { return getTypeQuals() & Qualifiers::Volatile; }
2964 bool isRestrict() const { return getTypeQuals() & Qualifiers::Restrict; }
2966 /// \brief Determine the type of an expression that calls a function of
2968 QualType getCallResultType(ASTContext &Context) const {
2969 return getReturnType().getNonLValueExprType(Context);
2972 static StringRef getNameForCallConv(CallingConv CC);
2974 static bool classof(const Type *T) {
2975 return T->getTypeClass() == FunctionNoProto ||
2976 T->getTypeClass() == FunctionProto;
2980 /// FunctionNoProtoType - Represents a K&R-style 'int foo()' function, which has
2981 /// no information available about its arguments.
2982 class FunctionNoProtoType : public FunctionType, public llvm::FoldingSetNode {
2983 FunctionNoProtoType(QualType Result, QualType Canonical, ExtInfo Info)
2984 : FunctionType(FunctionNoProto, Result, Canonical,
2985 /*Dependent=*/false, /*InstantiationDependent=*/false,
2986 Result->isVariablyModifiedType(),
2987 /*ContainsUnexpandedParameterPack=*/false, Info) {}
2989 friend class ASTContext; // ASTContext creates these.
2992 // No additional state past what FunctionType provides.
2994 bool isSugared() const { return false; }
2995 QualType desugar() const { return QualType(this, 0); }
2997 void Profile(llvm::FoldingSetNodeID &ID) {
2998 Profile(ID, getReturnType(), getExtInfo());
3000 static void Profile(llvm::FoldingSetNodeID &ID, QualType ResultType,
3003 ID.AddPointer(ResultType.getAsOpaquePtr());
3006 static bool classof(const Type *T) {
3007 return T->getTypeClass() == FunctionNoProto;
3011 /// FunctionProtoType - Represents a prototype with parameter type info, e.g.
3012 /// 'int foo(int)' or 'int foo(void)'. 'void' is represented as having no
3013 /// parameters, not as having a single void parameter. Such a type can have an
3014 /// exception specification, but this specification is not part of the canonical
3016 class FunctionProtoType : public FunctionType, public llvm::FoldingSetNode {
3018 struct ExceptionSpecInfo {
3020 : Type(EST_None), NoexceptExpr(nullptr),
3021 SourceDecl(nullptr), SourceTemplate(nullptr) {}
3023 ExceptionSpecInfo(ExceptionSpecificationType EST)
3024 : Type(EST), NoexceptExpr(nullptr), SourceDecl(nullptr),
3025 SourceTemplate(nullptr) {}
3027 /// The kind of exception specification this is.
3028 ExceptionSpecificationType Type;
3029 /// Explicitly-specified list of exception types.
3030 ArrayRef<QualType> Exceptions;
3031 /// Noexcept expression, if this is EST_ComputedNoexcept.
3033 /// The function whose exception specification this is, for
3034 /// EST_Unevaluated and EST_Uninstantiated.
3035 FunctionDecl *SourceDecl;
3036 /// The function template whose exception specification this is instantiated
3037 /// from, for EST_Uninstantiated.
3038 FunctionDecl *SourceTemplate;
3041 /// ExtProtoInfo - Extra information about a function prototype.
3042 struct ExtProtoInfo {
3044 : Variadic(false), HasTrailingReturn(false), TypeQuals(0),
3045 RefQualifier(RQ_None), ConsumedParameters(nullptr) {}
3047 ExtProtoInfo(CallingConv CC)
3048 : ExtInfo(CC), Variadic(false), HasTrailingReturn(false), TypeQuals(0),
3049 RefQualifier(RQ_None), ConsumedParameters(nullptr) {}
3051 ExtProtoInfo withExceptionSpec(const ExceptionSpecInfo &O) {
3052 ExtProtoInfo Result(*this);
3053 Result.ExceptionSpec = O;
3057 FunctionType::ExtInfo ExtInfo;
3059 bool HasTrailingReturn : 1;
3060 unsigned char TypeQuals;
3061 RefQualifierKind RefQualifier;
3062 ExceptionSpecInfo ExceptionSpec;
3063 const bool *ConsumedParameters;
3067 /// \brief Determine whether there are any argument types that
3068 /// contain an unexpanded parameter pack.
3069 static bool containsAnyUnexpandedParameterPack(const QualType *ArgArray,
3071 for (unsigned Idx = 0; Idx < numArgs; ++Idx)
3072 if (ArgArray[Idx]->containsUnexpandedParameterPack())
3078 FunctionProtoType(QualType result, ArrayRef<QualType> params,
3079 QualType canonical, const ExtProtoInfo &epi);
3081 /// The number of parameters this function has, not counting '...'.
3082 unsigned NumParams : 15;
3084 /// NumExceptions - The number of types in the exception spec, if any.
3085 unsigned NumExceptions : 9;
3087 /// ExceptionSpecType - The type of exception specification this function has.
3088 unsigned ExceptionSpecType : 4;
3090 /// HasAnyConsumedParams - Whether this function has any consumed parameters.
3091 unsigned HasAnyConsumedParams : 1;
3093 /// Variadic - Whether the function is variadic.
3094 unsigned Variadic : 1;
3096 /// HasTrailingReturn - Whether this function has a trailing return type.
3097 unsigned HasTrailingReturn : 1;
3099 // ParamInfo - There is an variable size array after the class in memory that
3100 // holds the parameter types.
3102 // Exceptions - There is another variable size array after ArgInfo that
3103 // holds the exception types.
3105 // NoexceptExpr - Instead of Exceptions, there may be a single Expr* pointing
3106 // to the expression in the noexcept() specifier.
3108 // ExceptionSpecDecl, ExceptionSpecTemplate - Instead of Exceptions, there may
3109 // be a pair of FunctionDecl* pointing to the function which should be used to
3110 // instantiate this function type's exception specification, and the function
3111 // from which it should be instantiated.
3113 // ConsumedParameters - A variable size array, following Exceptions
3114 // and of length NumParams, holding flags indicating which parameters
3115 // are consumed. This only appears if HasAnyConsumedParams is true.
3117 friend class ASTContext; // ASTContext creates these.
3119 const bool *getConsumedParamsBuffer() const {
3120 assert(hasAnyConsumedParams());
3122 // Find the end of the exceptions.
3123 Expr *const *eh_end = reinterpret_cast<Expr *const *>(param_type_end());
3124 if (getExceptionSpecType() != EST_ComputedNoexcept)
3125 eh_end += NumExceptions;
3127 eh_end += 1; // NoexceptExpr
3129 return reinterpret_cast<const bool*>(eh_end);
3133 unsigned getNumParams() const { return NumParams; }
3134 QualType getParamType(unsigned i) const {
3135 assert(i < NumParams && "invalid parameter index");
3136 return param_type_begin()[i];
3138 ArrayRef<QualType> getParamTypes() const {
3139 return llvm::makeArrayRef(param_type_begin(), param_type_end());
3142 ExtProtoInfo getExtProtoInfo() const {
3144 EPI.ExtInfo = getExtInfo();
3145 EPI.Variadic = isVariadic();
3146 EPI.HasTrailingReturn = hasTrailingReturn();
3147 EPI.ExceptionSpec.Type = getExceptionSpecType();
3148 EPI.TypeQuals = static_cast<unsigned char>(getTypeQuals());
3149 EPI.RefQualifier = getRefQualifier();
3150 if (EPI.ExceptionSpec.Type == EST_Dynamic) {
3151 EPI.ExceptionSpec.Exceptions = exceptions();
3152 } else if (EPI.ExceptionSpec.Type == EST_ComputedNoexcept) {
3153 EPI.ExceptionSpec.NoexceptExpr = getNoexceptExpr();
3154 } else if (EPI.ExceptionSpec.Type == EST_Uninstantiated) {
3155 EPI.ExceptionSpec.SourceDecl = getExceptionSpecDecl();
3156 EPI.ExceptionSpec.SourceTemplate = getExceptionSpecTemplate();
3157 } else if (EPI.ExceptionSpec.Type == EST_Unevaluated) {
3158 EPI.ExceptionSpec.SourceDecl = getExceptionSpecDecl();
3160 if (hasAnyConsumedParams())
3161 EPI.ConsumedParameters = getConsumedParamsBuffer();
3165 /// \brief Get the kind of exception specification on this function.
3166 ExceptionSpecificationType getExceptionSpecType() const {
3167 return static_cast<ExceptionSpecificationType>(ExceptionSpecType);
3169 /// \brief Return whether this function has any kind of exception spec.
3170 bool hasExceptionSpec() const {
3171 return getExceptionSpecType() != EST_None;
3173 /// \brief Return whether this function has a dynamic (throw) exception spec.
3174 bool hasDynamicExceptionSpec() const {
3175 return isDynamicExceptionSpec(getExceptionSpecType());
3177 /// \brief Return whether this function has a noexcept exception spec.
3178 bool hasNoexceptExceptionSpec() const {
3179 return isNoexceptExceptionSpec(getExceptionSpecType());
3181 /// \brief Return whether this function has a dependent exception spec.
3182 bool hasDependentExceptionSpec() const;
3183 /// \brief Result type of getNoexceptSpec().
3184 enum NoexceptResult {
3185 NR_NoNoexcept, ///< There is no noexcept specifier.
3186 NR_BadNoexcept, ///< The noexcept specifier has a bad expression.
3187 NR_Dependent, ///< The noexcept specifier is dependent.
3188 NR_Throw, ///< The noexcept specifier evaluates to false.
3189 NR_Nothrow ///< The noexcept specifier evaluates to true.
3191 /// \brief Get the meaning of the noexcept spec on this function, if any.
3192 NoexceptResult getNoexceptSpec(const ASTContext &Ctx) const;
3193 unsigned getNumExceptions() const { return NumExceptions; }
3194 QualType getExceptionType(unsigned i) const {
3195 assert(i < NumExceptions && "Invalid exception number!");
3196 return exception_begin()[i];
3198 Expr *getNoexceptExpr() const {
3199 if (getExceptionSpecType() != EST_ComputedNoexcept)
3201 // NoexceptExpr sits where the arguments end.
3202 return *reinterpret_cast<Expr *const *>(param_type_end());
3204 /// \brief If this function type has an exception specification which hasn't
3205 /// been determined yet (either because it has not been evaluated or because
3206 /// it has not been instantiated), this is the function whose exception
3207 /// specification is represented by this type.
3208 FunctionDecl *getExceptionSpecDecl() const {
3209 if (getExceptionSpecType() != EST_Uninstantiated &&
3210 getExceptionSpecType() != EST_Unevaluated)
3212 return reinterpret_cast<FunctionDecl *const *>(param_type_end())[0];
3214 /// \brief If this function type has an uninstantiated exception
3215 /// specification, this is the function whose exception specification
3216 /// should be instantiated to find the exception specification for
3218 FunctionDecl *getExceptionSpecTemplate() const {
3219 if (getExceptionSpecType() != EST_Uninstantiated)
3221 return reinterpret_cast<FunctionDecl *const *>(param_type_end())[1];
3223 /// \brief Determine whether this function type has a non-throwing exception
3224 /// specification. If this depends on template arguments, returns
3225 /// \c ResultIfDependent.
3226 bool isNothrow(const ASTContext &Ctx, bool ResultIfDependent = false) const;
3228 bool isVariadic() const { return Variadic; }
3230 /// \brief Determines whether this function prototype contains a
3231 /// parameter pack at the end.
3233 /// A function template whose last parameter is a parameter pack can be
3234 /// called with an arbitrary number of arguments, much like a variadic
3236 bool isTemplateVariadic() const;
3238 bool hasTrailingReturn() const { return HasTrailingReturn; }
3240 unsigned getTypeQuals() const { return FunctionType::getTypeQuals(); }
3243 /// \brief Retrieve the ref-qualifier associated with this function type.
3244 RefQualifierKind getRefQualifier() const {
3245 return static_cast<RefQualifierKind>(FunctionTypeBits.RefQualifier);
3248 typedef const QualType *param_type_iterator;
3249 typedef llvm::iterator_range<param_type_iterator> param_type_range;
3251 param_type_range param_types() const {
3252 return param_type_range(param_type_begin(), param_type_end());
3254 param_type_iterator param_type_begin() const {
3255 return reinterpret_cast<const QualType *>(this+1);
3257 param_type_iterator param_type_end() const {
3258 return param_type_begin() + NumParams;
3261 typedef const QualType *exception_iterator;
3263 ArrayRef<QualType> exceptions() const {
3264 return llvm::makeArrayRef(exception_begin(), exception_end());
3266 exception_iterator exception_begin() const {
3267 // exceptions begin where arguments end
3268 return param_type_end();
3270 exception_iterator exception_end() const {
3271 if (getExceptionSpecType() != EST_Dynamic)
3272 return exception_begin();
3273 return exception_begin() + NumExceptions;
3276 bool hasAnyConsumedParams() const { return HasAnyConsumedParams; }
3277 bool isParamConsumed(unsigned I) const {
3278 assert(I < getNumParams() && "parameter index out of range");
3279 if (hasAnyConsumedParams())
3280 return getConsumedParamsBuffer()[I];
3284 bool isSugared() const { return false; }
3285 QualType desugar() const { return QualType(this, 0); }
3287 void printExceptionSpecification(raw_ostream &OS,
3288 const PrintingPolicy &Policy) const;
3290 static bool classof(const Type *T) {
3291 return T->getTypeClass() == FunctionProto;
3294 void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Ctx);
3295 static void Profile(llvm::FoldingSetNodeID &ID, QualType Result,
3296 param_type_iterator ArgTys, unsigned NumArgs,
3297 const ExtProtoInfo &EPI, const ASTContext &Context);
3301 /// \brief Represents the dependent type named by a dependently-scoped
3302 /// typename using declaration, e.g.
3303 /// using typename Base<T>::foo;
3304 /// Template instantiation turns these into the underlying type.
3305 class UnresolvedUsingType : public Type {
3306 UnresolvedUsingTypenameDecl *Decl;
3308 UnresolvedUsingType(const UnresolvedUsingTypenameDecl *D)
3309 : Type(UnresolvedUsing, QualType(), true, true, false,
3310 /*ContainsUnexpandedParameterPack=*/false),
3311 Decl(const_cast<UnresolvedUsingTypenameDecl*>(D)) {}
3312 friend class ASTContext; // ASTContext creates these.
3315 UnresolvedUsingTypenameDecl *getDecl() const { return Decl; }
3317 bool isSugared() const { return false; }
3318 QualType desugar() const { return QualType(this, 0); }
3320 static bool classof(const Type *T) {
3321 return T->getTypeClass() == UnresolvedUsing;
3324 void Profile(llvm::FoldingSetNodeID &ID) {
3325 return Profile(ID, Decl);
3327 static void Profile(llvm::FoldingSetNodeID &ID,
3328 UnresolvedUsingTypenameDecl *D) {
3334 class TypedefType : public Type {
3335 TypedefNameDecl *Decl;
3337 TypedefType(TypeClass tc, const TypedefNameDecl *D, QualType can)
3338 : Type(tc, can, can->isDependentType(),
3339 can->isInstantiationDependentType(),
3340 can->isVariablyModifiedType(),
3341 /*ContainsUnexpandedParameterPack=*/false),
3342 Decl(const_cast<TypedefNameDecl*>(D)) {
3343 assert(!isa<TypedefType>(can) && "Invalid canonical type");
3345 friend class ASTContext; // ASTContext creates these.
3348 TypedefNameDecl *getDecl() const { return Decl; }
3350 bool isSugared() const { return true; }
3351 QualType desugar() const;
3353 static bool classof(const Type *T) { return T->getTypeClass() == Typedef; }
3356 /// TypeOfExprType (GCC extension).
3357 class TypeOfExprType : public Type {
3361 TypeOfExprType(Expr *E, QualType can = QualType());
3362 friend class ASTContext; // ASTContext creates these.
3364 Expr *getUnderlyingExpr() const { return TOExpr; }
3366 /// \brief Remove a single level of sugar.
3367 QualType desugar() const;
3369 /// \brief Returns whether this type directly provides sugar.
3370 bool isSugared() const;
3372 static bool classof(const Type *T) { return T->getTypeClass() == TypeOfExpr; }
3375 /// \brief Internal representation of canonical, dependent
3376 /// typeof(expr) types.
3378 /// This class is used internally by the ASTContext to manage
3379 /// canonical, dependent types, only. Clients will only see instances
3380 /// of this class via TypeOfExprType nodes.
3381 class DependentTypeOfExprType
3382 : public TypeOfExprType, public llvm::FoldingSetNode {
3383 const ASTContext &Context;
3386 DependentTypeOfExprType(const ASTContext &Context, Expr *E)
3387 : TypeOfExprType(E), Context(Context) { }
3389 void Profile(llvm::FoldingSetNodeID &ID) {
3390 Profile(ID, Context, getUnderlyingExpr());
3393 static void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context,
3397 /// TypeOfType (GCC extension).
3398 class TypeOfType : public Type {
3400 TypeOfType(QualType T, QualType can)
3401 : Type(TypeOf, can, T->isDependentType(),
3402 T->isInstantiationDependentType(),
3403 T->isVariablyModifiedType(),
3404 T->containsUnexpandedParameterPack()),
3406 assert(!isa<TypedefType>(can) && "Invalid canonical type");
3408 friend class ASTContext; // ASTContext creates these.
3410 QualType getUnderlyingType() const { return TOType; }
3412 /// \brief Remove a single level of sugar.
3413 QualType desugar() const { return getUnderlyingType(); }
3415 /// \brief Returns whether this type directly provides sugar.
3416 bool isSugared() const { return true; }
3418 static bool classof(const Type *T) { return T->getTypeClass() == TypeOf; }
3421 /// DecltypeType (C++0x)
3422 class DecltypeType : public Type {
3424 QualType UnderlyingType;
3427 DecltypeType(Expr *E, QualType underlyingType, QualType can = QualType());
3428 friend class ASTContext; // ASTContext creates these.
3430 Expr *getUnderlyingExpr() const { return E; }
3431 QualType getUnderlyingType() const { return UnderlyingType; }
3433 /// \brief Remove a single level of sugar.
3434 QualType desugar() const;
3436 /// \brief Returns whether this type directly provides sugar.
3437 bool isSugared() const;
3439 static bool classof(const Type *T) { return T->getTypeClass() == Decltype; }
3442 /// \brief Internal representation of canonical, dependent
3443 /// decltype(expr) types.
3445 /// This class is used internally by the ASTContext to manage
3446 /// canonical, dependent types, only. Clients will only see instances
3447 /// of this class via DecltypeType nodes.
3448 class DependentDecltypeType : public DecltypeType, public llvm::FoldingSetNode {
3449 const ASTContext &Context;
3452 DependentDecltypeType(const ASTContext &Context, Expr *E);
3454 void Profile(llvm::FoldingSetNodeID &ID) {
3455 Profile(ID, Context, getUnderlyingExpr());
3458 static void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context,
3462 /// \brief A unary type transform, which is a type constructed from another
3463 class UnaryTransformType : public Type {
3470 /// The untransformed type.
3472 /// The transformed type if not dependent, otherwise the same as BaseType.
3473 QualType UnderlyingType;
3477 UnaryTransformType(QualType BaseTy, QualType UnderlyingTy, UTTKind UKind,
3478 QualType CanonicalTy);
3479 friend class ASTContext;
3481 bool isSugared() const { return !isDependentType(); }
3482 QualType desugar() const { return UnderlyingType; }
3484 QualType getUnderlyingType() const { return UnderlyingType; }
3485 QualType getBaseType() const { return BaseType; }
3487 UTTKind getUTTKind() const { return UKind; }
3489 static bool classof(const Type *T) {
3490 return T->getTypeClass() == UnaryTransform;
3494 class TagType : public Type {
3495 /// Stores the TagDecl associated with this type. The decl may point to any
3496 /// TagDecl that declares the entity.
3499 friend class ASTReader;
3502 TagType(TypeClass TC, const TagDecl *D, QualType can);
3505 TagDecl *getDecl() const;
3507 /// @brief Determines whether this type is in the process of being
3509 bool isBeingDefined() const;
3511 static bool classof(const Type *T) {
3512 return T->getTypeClass() >= TagFirst && T->getTypeClass() <= TagLast;
3516 /// RecordType - This is a helper class that allows the use of isa/cast/dyncast
3517 /// to detect TagType objects of structs/unions/classes.
3518 class RecordType : public TagType {
3520 explicit RecordType(const RecordDecl *D)
3521 : TagType(Record, reinterpret_cast<const TagDecl*>(D), QualType()) { }
3522 explicit RecordType(TypeClass TC, RecordDecl *D)
3523 : TagType(TC, reinterpret_cast<const TagDecl*>(D), QualType()) { }
3524 friend class ASTContext; // ASTContext creates these.
3527 RecordDecl *getDecl() const {
3528 return reinterpret_cast<RecordDecl*>(TagType::getDecl());
3531 // FIXME: This predicate is a helper to QualType/Type. It needs to
3532 // recursively check all fields for const-ness. If any field is declared
3533 // const, it needs to return false.
3534 bool hasConstFields() const { return false; }
3536 bool isSugared() const { return false; }
3537 QualType desugar() const { return QualType(this, 0); }
3539 static bool classof(const Type *T) { return T->getTypeClass() == Record; }
3542 /// EnumType - This is a helper class that allows the use of isa/cast/dyncast
3543 /// to detect TagType objects of enums.
3544 class EnumType : public TagType {
3545 explicit EnumType(const EnumDecl *D)
3546 : TagType(Enum, reinterpret_cast<const TagDecl*>(D), QualType()) { }
3547 friend class ASTContext; // ASTContext creates these.
3550 EnumDecl *getDecl() const {
3551 return reinterpret_cast<EnumDecl*>(TagType::getDecl());
3554 bool isSugared() const { return false; }
3555 QualType desugar() const { return QualType(this, 0); }
3557 static bool classof(const Type *T) { return T->getTypeClass() == Enum; }
3560 /// AttributedType - An attributed type is a type to which a type
3561 /// attribute has been applied. The "modified type" is the
3562 /// fully-sugared type to which the attributed type was applied;
3563 /// generally it is not canonically equivalent to the attributed type.
3564 /// The "equivalent type" is the minimally-desugared type which the
3565 /// type is canonically equivalent to.
3567 /// For example, in the following attributed type:
3568 /// int32_t __attribute__((vector_size(16)))
3569 /// - the modified type is the TypedefType for int32_t
3570 /// - the equivalent type is VectorType(16, int32_t)
3571 /// - the canonical type is VectorType(16, int)
3572 class AttributedType : public Type, public llvm::FoldingSetNode {
3574 // It is really silly to have yet another attribute-kind enum, but
3575 // clang::attr::Kind doesn't currently cover the pure type attrs.
3577 // Expression operand.
3581 attr_neon_vector_type,
3582 attr_neon_polyvector_type,
3584 FirstExprOperandKind = attr_address_space,
3585 LastExprOperandKind = attr_neon_polyvector_type,
3587 // Enumerated operand (string or keyword).
3589 attr_objc_ownership,
3593 FirstEnumOperandKind = attr_objc_gc,
3594 LastEnumOperandKind = attr_pcs_vfp,
3613 attr_null_unspecified,
3618 QualType ModifiedType;
3619 QualType EquivalentType;
3621 friend class ASTContext; // creates these
3623 AttributedType(QualType canon, Kind attrKind,
3624 QualType modified, QualType equivalent)
3625 : Type(Attributed, canon, canon->isDependentType(),
3626 canon->isInstantiationDependentType(),
3627 canon->isVariablyModifiedType(),
3628 canon->containsUnexpandedParameterPack()),
3629 ModifiedType(modified), EquivalentType(equivalent) {
3630 AttributedTypeBits.AttrKind = attrKind;
3634 Kind getAttrKind() const {
3635 return static_cast<Kind>(AttributedTypeBits.AttrKind);
3638 QualType getModifiedType() const { return ModifiedType; }
3639 QualType getEquivalentType() const { return EquivalentType; }
3641 bool isSugared() const { return true; }
3642 QualType desugar() const { return getEquivalentType(); }
3644 bool isMSTypeSpec() const;
3646 bool isCallingConv() const;
3648 llvm::Optional<NullabilityKind> getImmediateNullability() const;
3650 /// Retrieve the attribute kind corresponding to the given
3651 /// nullability kind.
3652 static Kind getNullabilityAttrKind(NullabilityKind kind) {
3654 case NullabilityKind::NonNull:
3655 return attr_nonnull;
3657 case NullabilityKind::Nullable:
3658 return attr_nullable;
3660 case NullabilityKind::Unspecified:
3661 return attr_null_unspecified;
3663 llvm_unreachable("Unknown nullability kind.");
3666 /// Strip off the top-level nullability annotation on the given
3667 /// type, if it's there.
3669 /// \param T The type to strip. If the type is exactly an
3670 /// AttributedType specifying nullability (without looking through
3671 /// type sugar), the nullability is returned and this type changed
3672 /// to the underlying modified type.
3674 /// \returns the top-level nullability, if present.
3675 static Optional<NullabilityKind> stripOuterNullability(QualType &T);
3677 void Profile(llvm::FoldingSetNodeID &ID) {
3678 Profile(ID, getAttrKind(), ModifiedType, EquivalentType);
3681 static void Profile(llvm::FoldingSetNodeID &ID, Kind attrKind,
3682 QualType modified, QualType equivalent) {
3683 ID.AddInteger(attrKind);
3684 ID.AddPointer(modified.getAsOpaquePtr());
3685 ID.AddPointer(equivalent.getAsOpaquePtr());
3688 static bool classof(const Type *T) {
3689 return T->getTypeClass() == Attributed;
3693 class TemplateTypeParmType : public Type, public llvm::FoldingSetNode {
3694 // Helper data collector for canonical types.
3695 struct CanonicalTTPTInfo {
3696 unsigned Depth : 15;
3697 unsigned ParameterPack : 1;
3698 unsigned Index : 16;
3702 // Info for the canonical type.
3703 CanonicalTTPTInfo CanTTPTInfo;
3704 // Info for the non-canonical type.
3705 TemplateTypeParmDecl *TTPDecl;
3708 /// Build a non-canonical type.
3709 TemplateTypeParmType(TemplateTypeParmDecl *TTPDecl, QualType Canon)
3710 : Type(TemplateTypeParm, Canon, /*Dependent=*/true,
3711 /*InstantiationDependent=*/true,
3712 /*VariablyModified=*/false,
3713 Canon->containsUnexpandedParameterPack()),
3714 TTPDecl(TTPDecl) { }
3716 /// Build the canonical type.
3717 TemplateTypeParmType(unsigned D, unsigned I, bool PP)
3718 : Type(TemplateTypeParm, QualType(this, 0),
3720 /*InstantiationDependent=*/true,
3721 /*VariablyModified=*/false, PP) {
3722 CanTTPTInfo.Depth = D;
3723 CanTTPTInfo.Index = I;
3724 CanTTPTInfo.ParameterPack = PP;
3727 friend class ASTContext; // ASTContext creates these
3729 const CanonicalTTPTInfo& getCanTTPTInfo() const {
3730 QualType Can = getCanonicalTypeInternal();
3731 return Can->castAs<TemplateTypeParmType>()->CanTTPTInfo;
3735 unsigned getDepth() const { return getCanTTPTInfo().Depth; }
3736 unsigned getIndex() const { return getCanTTPTInfo().Index; }
3737 bool isParameterPack() const { return getCanTTPTInfo().ParameterPack; }
3739 TemplateTypeParmDecl *getDecl() const {
3740 return isCanonicalUnqualified() ? nullptr : TTPDecl;
3743 IdentifierInfo *getIdentifier() const;
3745 bool isSugared() const { return false; }
3746 QualType desugar() const { return QualType(this, 0); }
3748 void Profile(llvm::FoldingSetNodeID &ID) {
3749 Profile(ID, getDepth(), getIndex(), isParameterPack(), getDecl());
3752 static void Profile(llvm::FoldingSetNodeID &ID, unsigned Depth,
3753 unsigned Index, bool ParameterPack,
3754 TemplateTypeParmDecl *TTPDecl) {
3755 ID.AddInteger(Depth);
3756 ID.AddInteger(Index);
3757 ID.AddBoolean(ParameterPack);
3758 ID.AddPointer(TTPDecl);
3761 static bool classof(const Type *T) {
3762 return T->getTypeClass() == TemplateTypeParm;
3766 /// \brief Represents the result of substituting a type for a template
3769 /// Within an instantiated template, all template type parameters have
3770 /// been replaced with these. They are used solely to record that a
3771 /// type was originally written as a template type parameter;
3772 /// therefore they are never canonical.
3773 class SubstTemplateTypeParmType : public Type, public llvm::FoldingSetNode {
3774 // The original type parameter.
3775 const TemplateTypeParmType *Replaced;
3777 SubstTemplateTypeParmType(const TemplateTypeParmType *Param, QualType Canon)
3778 : Type(SubstTemplateTypeParm, Canon, Canon->isDependentType(),
3779 Canon->isInstantiationDependentType(),
3780 Canon->isVariablyModifiedType(),
3781 Canon->containsUnexpandedParameterPack()),
3784 friend class ASTContext;
3787 /// Gets the template parameter that was substituted for.
3788 const TemplateTypeParmType *getReplacedParameter() const {
3792 /// Gets the type that was substituted for the template
3794 QualType getReplacementType() const {
3795 return getCanonicalTypeInternal();
3798 bool isSugared() const { return true; }
3799 QualType desugar() const { return getReplacementType(); }
3801 void Profile(llvm::FoldingSetNodeID &ID) {
3802 Profile(ID, getReplacedParameter(), getReplacementType());
3804 static void Profile(llvm::FoldingSetNodeID &ID,
3805 const TemplateTypeParmType *Replaced,
3806 QualType Replacement) {
3807 ID.AddPointer(Replaced);
3808 ID.AddPointer(Replacement.getAsOpaquePtr());
3811 static bool classof(const Type *T) {
3812 return T->getTypeClass() == SubstTemplateTypeParm;
3816 /// \brief Represents the result of substituting a set of types for a template
3817 /// type parameter pack.
3819 /// When a pack expansion in the source code contains multiple parameter packs
3820 /// and those parameter packs correspond to different levels of template
3821 /// parameter lists, this type node is used to represent a template type
3822 /// parameter pack from an outer level, which has already had its argument pack
3823 /// substituted but that still lives within a pack expansion that itself
3824 /// could not be instantiated. When actually performing a substitution into
3825 /// that pack expansion (e.g., when all template parameters have corresponding
3826 /// arguments), this type will be replaced with the \c SubstTemplateTypeParmType
3827 /// at the current pack substitution index.
3828 class SubstTemplateTypeParmPackType : public Type, public llvm::FoldingSetNode {
3829 /// \brief The original type parameter.
3830 const TemplateTypeParmType *Replaced;
3832 /// \brief A pointer to the set of template arguments that this
3833 /// parameter pack is instantiated with.
3834 const TemplateArgument *Arguments;
3836 /// \brief The number of template arguments in \c Arguments.
3837 unsigned NumArguments;
3839 SubstTemplateTypeParmPackType(const TemplateTypeParmType *Param,
3841 const TemplateArgument &ArgPack);
3843 friend class ASTContext;
3846 IdentifierInfo *getIdentifier() const { return Replaced->getIdentifier(); }
3848 /// Gets the template parameter that was substituted for.
3849 const TemplateTypeParmType *getReplacedParameter() const {
3853 bool isSugared() const { return false; }
3854 QualType desugar() const { return QualType(this, 0); }
3856 TemplateArgument getArgumentPack() const;
3858 void Profile(llvm::FoldingSetNodeID &ID);
3859 static void Profile(llvm::FoldingSetNodeID &ID,
3860 const TemplateTypeParmType *Replaced,
3861 const TemplateArgument &ArgPack);
3863 static bool classof(const Type *T) {
3864 return T->getTypeClass() == SubstTemplateTypeParmPack;
3868 /// \brief Represents a C++11 auto or C++1y decltype(auto) type.
3870 /// These types are usually a placeholder for a deduced type. However, before
3871 /// the initializer is attached, or if the initializer is type-dependent, there
3872 /// is no deduced type and an auto type is canonical. In the latter case, it is
3873 /// also a dependent type.
3874 class AutoType : public Type, public llvm::FoldingSetNode {
3875 AutoType(QualType DeducedType, bool IsDecltypeAuto,
3877 : Type(Auto, DeducedType.isNull() ? QualType(this, 0) : DeducedType,
3878 /*Dependent=*/IsDependent, /*InstantiationDependent=*/IsDependent,
3879 /*VariablyModified=*/false,
3880 /*ContainsParameterPack=*/DeducedType.isNull()
3881 ? false : DeducedType->containsUnexpandedParameterPack()) {
3882 assert((DeducedType.isNull() || !IsDependent) &&
3883 "auto deduced to dependent type");
3884 AutoTypeBits.IsDecltypeAuto = IsDecltypeAuto;
3887 friend class ASTContext; // ASTContext creates these
3890 bool isDecltypeAuto() const { return AutoTypeBits.IsDecltypeAuto; }
3892 bool isSugared() const { return !isCanonicalUnqualified(); }
3893 QualType desugar() const { return getCanonicalTypeInternal(); }
3895 /// \brief Get the type deduced for this auto type, or null if it's either
3896 /// not been deduced or was deduced to a dependent type.
3897 QualType getDeducedType() const {
3898 return !isCanonicalUnqualified() ? getCanonicalTypeInternal() : QualType();
3900 bool isDeduced() const {
3901 return !isCanonicalUnqualified() || isDependentType();
3904 void Profile(llvm::FoldingSetNodeID &ID) {
3905 Profile(ID, getDeducedType(), isDecltypeAuto(),
3909 static void Profile(llvm::FoldingSetNodeID &ID, QualType Deduced,
3910 bool IsDecltypeAuto, bool IsDependent) {
3911 ID.AddPointer(Deduced.getAsOpaquePtr());
3912 ID.AddBoolean(IsDecltypeAuto);
3913 ID.AddBoolean(IsDependent);
3916 static bool classof(const Type *T) {
3917 return T->getTypeClass() == Auto;
3921 /// \brief Represents a type template specialization; the template
3922 /// must be a class template, a type alias template, or a template
3923 /// template parameter. A template which cannot be resolved to one of
3924 /// these, e.g. because it is written with a dependent scope
3925 /// specifier, is instead represented as a
3926 /// @c DependentTemplateSpecializationType.
3928 /// A non-dependent template specialization type is always "sugar",
3929 /// typically for a @c RecordType. For example, a class template
3930 /// specialization type of @c vector<int> will refer to a tag type for
3931 /// the instantiation @c std::vector<int, std::allocator<int>>
3933 /// Template specializations are dependent if either the template or
3934 /// any of the template arguments are dependent, in which case the
3935 /// type may also be canonical.
3937 /// Instances of this type are allocated with a trailing array of
3938 /// TemplateArguments, followed by a QualType representing the
3939 /// non-canonical aliased type when the template is a type alias
3941 class TemplateSpecializationType
3942 : public Type, public llvm::FoldingSetNode {
3943 /// \brief The name of the template being specialized. This is
3944 /// either a TemplateName::Template (in which case it is a
3945 /// ClassTemplateDecl*, a TemplateTemplateParmDecl*, or a
3946 /// TypeAliasTemplateDecl*), a
3947 /// TemplateName::SubstTemplateTemplateParmPack, or a
3948 /// TemplateName::SubstTemplateTemplateParm (in which case the
3949 /// replacement must, recursively, be one of these).
3950 TemplateName Template;
3952 /// \brief - The number of template arguments named in this class
3953 /// template specialization.
3954 unsigned NumArgs : 31;
3956 /// \brief Whether this template specialization type is a substituted
3960 TemplateSpecializationType(TemplateName T,
3961 const TemplateArgument *Args,
3962 unsigned NumArgs, QualType Canon,
3965 friend class ASTContext; // ASTContext creates these
3968 /// \brief Determine whether any of the given template arguments are
3970 static bool anyDependentTemplateArguments(const TemplateArgumentLoc *Args,
3972 bool &InstantiationDependent);
3974 static bool anyDependentTemplateArguments(const TemplateArgumentListInfo &,
3975 bool &InstantiationDependent);
3977 /// \brief Print a template argument list, including the '<' and '>'
3978 /// enclosing the template arguments.
3979 static void PrintTemplateArgumentList(raw_ostream &OS,
3980 const TemplateArgument *Args,
3982 const PrintingPolicy &Policy,
3983 bool SkipBrackets = false);
3985 static void PrintTemplateArgumentList(raw_ostream &OS,
3986 const TemplateArgumentLoc *Args,
3988 const PrintingPolicy &Policy);
3990 static void PrintTemplateArgumentList(raw_ostream &OS,
3991 const TemplateArgumentListInfo &,
3992 const PrintingPolicy &Policy);
3994 /// True if this template specialization type matches a current
3995 /// instantiation in the context in which it is found.
3996 bool isCurrentInstantiation() const {
3997 return isa<InjectedClassNameType>(getCanonicalTypeInternal());
4000 /// \brief Determine if this template specialization type is for a type alias
4001 /// template that has been substituted.
4003 /// Nearly every template specialization type whose template is an alias
4004 /// template will be substituted. However, this is not the case when
4005 /// the specialization contains a pack expansion but the template alias
4006 /// does not have a corresponding parameter pack, e.g.,
4009 /// template<typename T, typename U, typename V> struct S;
4010 /// template<typename T, typename U> using A = S<T, int, U>;
4011 /// template<typename... Ts> struct X {
4012 /// typedef A<Ts...> type; // not a type alias
4015 bool isTypeAlias() const { return TypeAlias; }
4017 /// Get the aliased type, if this is a specialization of a type alias
4019 QualType getAliasedType() const {
4020 assert(isTypeAlias() && "not a type alias template specialization");
4021 return *reinterpret_cast<const QualType*>(end());
4024 typedef const TemplateArgument * iterator;
4026 iterator begin() const { return getArgs(); }
4027 iterator end() const; // defined inline in TemplateBase.h
4029 /// \brief Retrieve the name of the template that we are specializing.
4030 TemplateName getTemplateName() const { return Template; }
4032 /// \brief Retrieve the template arguments.
4033 const TemplateArgument *getArgs() const {
4034 return reinterpret_cast<const TemplateArgument *>(this + 1);
4037 /// \brief Retrieve the number of template arguments.
4038 unsigned getNumArgs() const { return NumArgs; }
4040 /// \brief Retrieve a specific template argument as a type.
4041 /// \pre @c isArgType(Arg)
4042 const TemplateArgument &getArg(unsigned Idx) const; // in TemplateBase.h
4044 bool isSugared() const {
4045 return !isDependentType() || isCurrentInstantiation() || isTypeAlias();
4047 QualType desugar() const { return getCanonicalTypeInternal(); }
4049 void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Ctx) {
4050 Profile(ID, Template, getArgs(), NumArgs, Ctx);
4052 getAliasedType().Profile(ID);
4055 static void Profile(llvm::FoldingSetNodeID &ID, TemplateName T,
4056 const TemplateArgument *Args,
4058 const ASTContext &Context);
4060 static bool classof(const Type *T) {
4061 return T->getTypeClass() == TemplateSpecialization;
4065 /// \brief The injected class name of a C++ class template or class
4066 /// template partial specialization. Used to record that a type was
4067 /// spelled with a bare identifier rather than as a template-id; the
4068 /// equivalent for non-templated classes is just RecordType.
4070 /// Injected class name types are always dependent. Template
4071 /// instantiation turns these into RecordTypes.
4073 /// Injected class name types are always canonical. This works
4074 /// because it is impossible to compare an injected class name type
4075 /// with the corresponding non-injected template type, for the same
4076 /// reason that it is impossible to directly compare template
4077 /// parameters from different dependent contexts: injected class name
4078 /// types can only occur within the scope of a particular templated
4079 /// declaration, and within that scope every template specialization
4080 /// will canonicalize to the injected class name (when appropriate
4081 /// according to the rules of the language).
4082 class InjectedClassNameType : public Type {
4083 CXXRecordDecl *Decl;
4085 /// The template specialization which this type represents.
4087 /// template <class T> class A { ... };
4088 /// this is A<T>, whereas in
4089 /// template <class X, class Y> class A<B<X,Y> > { ... };
4090 /// this is A<B<X,Y> >.
4092 /// It is always unqualified, always a template specialization type,
4093 /// and always dependent.
4094 QualType InjectedType;
4096 friend class ASTContext; // ASTContext creates these.
4097 friend class ASTReader; // FIXME: ASTContext::getInjectedClassNameType is not
4098 // currently suitable for AST reading, too much
4099 // interdependencies.
4100 InjectedClassNameType(CXXRecordDecl *D, QualType TST)
4101 : Type(InjectedClassName, QualType(), /*Dependent=*/true,
4102 /*InstantiationDependent=*/true,
4103 /*VariablyModified=*/false,
4104 /*ContainsUnexpandedParameterPack=*/false),
4105 Decl(D), InjectedType(TST) {
4106 assert(isa<TemplateSpecializationType>(TST));
4107 assert(!TST.hasQualifiers());
4108 assert(TST->isDependentType());
4112 QualType getInjectedSpecializationType() const { return InjectedType; }
4113 const TemplateSpecializationType *getInjectedTST() const {
4114 return cast<TemplateSpecializationType>(InjectedType.getTypePtr());
4117 CXXRecordDecl *getDecl() const;
4119 bool isSugared() const { return false; }
4120 QualType desugar() const { return QualType(this, 0); }
4122 static bool classof(const Type *T) {
4123 return T->getTypeClass() == InjectedClassName;
4127 /// \brief The kind of a tag type.
4129 /// \brief The "struct" keyword.
4131 /// \brief The "__interface" keyword.
4133 /// \brief The "union" keyword.
4135 /// \brief The "class" keyword.
4137 /// \brief The "enum" keyword.
4141 /// \brief The elaboration keyword that precedes a qualified type name or
4142 /// introduces an elaborated-type-specifier.
4143 enum ElaboratedTypeKeyword {
4144 /// \brief The "struct" keyword introduces the elaborated-type-specifier.
4146 /// \brief The "__interface" keyword introduces the elaborated-type-specifier.
4148 /// \brief The "union" keyword introduces the elaborated-type-specifier.
4150 /// \brief The "class" keyword introduces the elaborated-type-specifier.
4152 /// \brief The "enum" keyword introduces the elaborated-type-specifier.
4154 /// \brief The "typename" keyword precedes the qualified type name, e.g.,
4155 /// \c typename T::type.
4157 /// \brief No keyword precedes the qualified type name.
4161 /// A helper class for Type nodes having an ElaboratedTypeKeyword.
4162 /// The keyword in stored in the free bits of the base class.
4163 /// Also provides a few static helpers for converting and printing
4164 /// elaborated type keyword and tag type kind enumerations.
4165 class TypeWithKeyword : public Type {
4167 TypeWithKeyword(ElaboratedTypeKeyword Keyword, TypeClass tc,
4168 QualType Canonical, bool Dependent,
4169 bool InstantiationDependent, bool VariablyModified,
4170 bool ContainsUnexpandedParameterPack)
4171 : Type(tc, Canonical, Dependent, InstantiationDependent, VariablyModified,
4172 ContainsUnexpandedParameterPack) {
4173 TypeWithKeywordBits.Keyword = Keyword;
4177 ElaboratedTypeKeyword getKeyword() const {
4178 return static_cast<ElaboratedTypeKeyword>(TypeWithKeywordBits.Keyword);
4181 /// getKeywordForTypeSpec - Converts a type specifier (DeclSpec::TST)
4182 /// into an elaborated type keyword.
4183 static ElaboratedTypeKeyword getKeywordForTypeSpec(unsigned TypeSpec);
4185 /// getTagTypeKindForTypeSpec - Converts a type specifier (DeclSpec::TST)
4186 /// into a tag type kind. It is an error to provide a type specifier
4187 /// which *isn't* a tag kind here.
4188 static TagTypeKind getTagTypeKindForTypeSpec(unsigned TypeSpec);
4190 /// getKeywordForTagDeclKind - Converts a TagTypeKind into an
4191 /// elaborated type keyword.
4192 static ElaboratedTypeKeyword getKeywordForTagTypeKind(TagTypeKind Tag);
4194 /// getTagTypeKindForKeyword - Converts an elaborated type keyword into
4195 // a TagTypeKind. It is an error to provide an elaborated type keyword
4196 /// which *isn't* a tag kind here.
4197 static TagTypeKind getTagTypeKindForKeyword(ElaboratedTypeKeyword Keyword);
4199 static bool KeywordIsTagTypeKind(ElaboratedTypeKeyword Keyword);
4201 static StringRef getKeywordName(ElaboratedTypeKeyword Keyword);
4203 static StringRef getTagTypeKindName(TagTypeKind Kind) {
4204 return getKeywordName(getKeywordForTagTypeKind(Kind));
4207 class CannotCastToThisType {};
4208 static CannotCastToThisType classof(const Type *);
4211 /// \brief Represents a type that was referred to using an elaborated type
4212 /// keyword, e.g., struct S, or via a qualified name, e.g., N::M::type,
4215 /// This type is used to keep track of a type name as written in the
4216 /// source code, including tag keywords and any nested-name-specifiers.
4217 /// The type itself is always "sugar", used to express what was written
4218 /// in the source code but containing no additional semantic information.
4219 class ElaboratedType : public TypeWithKeyword, public llvm::FoldingSetNode {
4221 /// \brief The nested name specifier containing the qualifier.
4222 NestedNameSpecifier *NNS;
4224 /// \brief The type that this qualified name refers to.
4227 ElaboratedType(ElaboratedTypeKeyword Keyword, NestedNameSpecifier *NNS,
4228 QualType NamedType, QualType CanonType)
4229 : TypeWithKeyword(Keyword, Elaborated, CanonType,
4230 NamedType->isDependentType(),
4231 NamedType->isInstantiationDependentType(),
4232 NamedType->isVariablyModifiedType(),
4233 NamedType->containsUnexpandedParameterPack()),
4234 NNS(NNS), NamedType(NamedType) {
4235 assert(!(Keyword == ETK_None && NNS == nullptr) &&
4236 "ElaboratedType cannot have elaborated type keyword "
4237 "and name qualifier both null.");
4240 friend class ASTContext; // ASTContext creates these
4245 /// \brief Retrieve the qualification on this type.
4246 NestedNameSpecifier *getQualifier() const { return NNS; }
4248 /// \brief Retrieve the type named by the qualified-id.
4249 QualType getNamedType() const { return NamedType; }
4251 /// \brief Remove a single level of sugar.
4252 QualType desugar() const { return getNamedType(); }
4254 /// \brief Returns whether this type directly provides sugar.
4255 bool isSugared() const { return true; }
4257 void Profile(llvm::FoldingSetNodeID &ID) {
4258 Profile(ID, getKeyword(), NNS, NamedType);
4261 static void Profile(llvm::FoldingSetNodeID &ID, ElaboratedTypeKeyword Keyword,
4262 NestedNameSpecifier *NNS, QualType NamedType) {
4263 ID.AddInteger(Keyword);
4265 NamedType.Profile(ID);
4268 static bool classof(const Type *T) {
4269 return T->getTypeClass() == Elaborated;
4273 /// \brief Represents a qualified type name for which the type name is
4276 /// DependentNameType represents a class of dependent types that involve a
4277 /// possibly dependent nested-name-specifier (e.g., "T::") followed by a
4278 /// name of a type. The DependentNameType may start with a "typename" (for a
4279 /// typename-specifier), "class", "struct", "union", or "enum" (for a
4280 /// dependent elaborated-type-specifier), or nothing (in contexts where we
4281 /// know that we must be referring to a type, e.g., in a base class specifier).
4282 /// Typically the nested-name-specifier is dependent, but in MSVC compatibility
4283 /// mode, this type is used with non-dependent names to delay name lookup until
4285 class DependentNameType : public TypeWithKeyword, public llvm::FoldingSetNode {
4287 /// \brief The nested name specifier containing the qualifier.
4288 NestedNameSpecifier *NNS;
4290 /// \brief The type that this typename specifier refers to.
4291 const IdentifierInfo *Name;
4293 DependentNameType(ElaboratedTypeKeyword Keyword, NestedNameSpecifier *NNS,
4294 const IdentifierInfo *Name, QualType CanonType)
4295 : TypeWithKeyword(Keyword, DependentName, CanonType, /*Dependent=*/true,
4296 /*InstantiationDependent=*/true,
4297 /*VariablyModified=*/false,
4298 NNS->containsUnexpandedParameterPack()),
4299 NNS(NNS), Name(Name) {}
4301 friend class ASTContext; // ASTContext creates these
4304 /// \brief Retrieve the qualification on this type.
4305 NestedNameSpecifier *getQualifier() const { return NNS; }
4307 /// \brief Retrieve the type named by the typename specifier as an
4310 /// This routine will return a non-NULL identifier pointer when the
4311 /// form of the original typename was terminated by an identifier,
4312 /// e.g., "typename T::type".
4313 const IdentifierInfo *getIdentifier() const {
4317 bool isSugared() const { return false; }
4318 QualType desugar() const { return QualType(this, 0); }
4320 void Profile(llvm::FoldingSetNodeID &ID) {
4321 Profile(ID, getKeyword(), NNS, Name);
4324 static void Profile(llvm::FoldingSetNodeID &ID, ElaboratedTypeKeyword Keyword,
4325 NestedNameSpecifier *NNS, const IdentifierInfo *Name) {
4326 ID.AddInteger(Keyword);
4328 ID.AddPointer(Name);
4331 static bool classof(const Type *T) {
4332 return T->getTypeClass() == DependentName;
4336 /// DependentTemplateSpecializationType - Represents a template
4337 /// specialization type whose template cannot be resolved, e.g.
4338 /// A<T>::template B<T>
4339 class DependentTemplateSpecializationType :
4340 public TypeWithKeyword, public llvm::FoldingSetNode {
4342 /// \brief The nested name specifier containing the qualifier.
4343 NestedNameSpecifier *NNS;
4345 /// \brief The identifier of the template.
4346 const IdentifierInfo *Name;
4348 /// \brief - The number of template arguments named in this class
4349 /// template specialization.
4352 const TemplateArgument *getArgBuffer() const {
4353 return reinterpret_cast<const TemplateArgument*>(this+1);
4355 TemplateArgument *getArgBuffer() {
4356 return reinterpret_cast<TemplateArgument*>(this+1);
4359 DependentTemplateSpecializationType(ElaboratedTypeKeyword Keyword,
4360 NestedNameSpecifier *NNS,
4361 const IdentifierInfo *Name,
4363 const TemplateArgument *Args,
4366 friend class ASTContext; // ASTContext creates these
4369 NestedNameSpecifier *getQualifier() const { return NNS; }
4370 const IdentifierInfo *getIdentifier() const { return Name; }
4372 /// \brief Retrieve the template arguments.
4373 const TemplateArgument *getArgs() const {
4374 return getArgBuffer();
4377 /// \brief Retrieve the number of template arguments.
4378 unsigned getNumArgs() const { return NumArgs; }
4380 const TemplateArgument &getArg(unsigned Idx) const; // in TemplateBase.h
4382 typedef const TemplateArgument * iterator;
4383 iterator begin() const { return getArgs(); }
4384 iterator end() const; // inline in TemplateBase.h
4386 bool isSugared() const { return false; }
4387 QualType desugar() const { return QualType(this, 0); }
4389 void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context) {
4390 Profile(ID, Context, getKeyword(), NNS, Name, NumArgs, getArgs());
4393 static void Profile(llvm::FoldingSetNodeID &ID,
4394 const ASTContext &Context,
4395 ElaboratedTypeKeyword Keyword,
4396 NestedNameSpecifier *Qualifier,
4397 const IdentifierInfo *Name,
4399 const TemplateArgument *Args);
4401 static bool classof(const Type *T) {
4402 return T->getTypeClass() == DependentTemplateSpecialization;
4406 /// \brief Represents a pack expansion of types.
4408 /// Pack expansions are part of C++0x variadic templates. A pack
4409 /// expansion contains a pattern, which itself contains one or more
4410 /// "unexpanded" parameter packs. When instantiated, a pack expansion
4411 /// produces a series of types, each instantiated from the pattern of
4412 /// the expansion, where the Ith instantiation of the pattern uses the
4413 /// Ith arguments bound to each of the unexpanded parameter packs. The
4414 /// pack expansion is considered to "expand" these unexpanded
4415 /// parameter packs.
4418 /// template<typename ...Types> struct tuple;
4420 /// template<typename ...Types>
4421 /// struct tuple_of_references {
4422 /// typedef tuple<Types&...> type;
4426 /// Here, the pack expansion \c Types&... is represented via a
4427 /// PackExpansionType whose pattern is Types&.
4428 class PackExpansionType : public Type, public llvm::FoldingSetNode {
4429 /// \brief The pattern of the pack expansion.
4432 /// \brief The number of expansions that this pack expansion will
4433 /// generate when substituted (+1), or indicates that
4435 /// This field will only have a non-zero value when some of the parameter
4436 /// packs that occur within the pattern have been substituted but others have
4438 unsigned NumExpansions;
4440 PackExpansionType(QualType Pattern, QualType Canon,
4441 Optional<unsigned> NumExpansions)
4442 : Type(PackExpansion, Canon, /*Dependent=*/Pattern->isDependentType(),
4443 /*InstantiationDependent=*/true,
4444 /*VariablyModified=*/Pattern->isVariablyModifiedType(),
4445 /*ContainsUnexpandedParameterPack=*/false),
4447 NumExpansions(NumExpansions? *NumExpansions + 1: 0) { }
4449 friend class ASTContext; // ASTContext creates these
4452 /// \brief Retrieve the pattern of this pack expansion, which is the
4453 /// type that will be repeatedly instantiated when instantiating the
4454 /// pack expansion itself.
4455 QualType getPattern() const { return Pattern; }
4457 /// \brief Retrieve the number of expansions that this pack expansion will
4458 /// generate, if known.
4459 Optional<unsigned> getNumExpansions() const {
4461 return NumExpansions - 1;
4466 bool isSugared() const { return !Pattern->isDependentType(); }
4467 QualType desugar() const { return isSugared() ? Pattern : QualType(this, 0); }
4469 void Profile(llvm::FoldingSetNodeID &ID) {
4470 Profile(ID, getPattern(), getNumExpansions());
4473 static void Profile(llvm::FoldingSetNodeID &ID, QualType Pattern,
4474 Optional<unsigned> NumExpansions) {
4475 ID.AddPointer(Pattern.getAsOpaquePtr());
4476 ID.AddBoolean(NumExpansions.hasValue());
4478 ID.AddInteger(*NumExpansions);
4481 static bool classof(const Type *T) {
4482 return T->getTypeClass() == PackExpansion;
4486 /// ObjCObjectType - Represents a class type in Objective C.
4488 /// Every Objective C type is a combination of a base type, a set of
4489 /// type arguments (optional, for parameterized classes) and a list of
4492 /// Given the following declarations:
4498 /// 'C' is an ObjCInterfaceType C. It is sugar for an ObjCObjectType
4499 /// with base C and no protocols.
4501 /// 'C<P>' is an unspecialized ObjCObjectType with base C and protocol list [P].
4502 /// 'C<C*>' is a specialized ObjCObjectType with type arguments 'C*' and no
4504 /// 'C<C*><P>' is a specialized ObjCObjectType with base C, type arguments 'C*',
4505 /// and protocol list [P].
4507 /// 'id' is a TypedefType which is sugar for an ObjCObjectPointerType whose
4508 /// pointee is an ObjCObjectType with base BuiltinType::ObjCIdType
4509 /// and no protocols.
4511 /// 'id<P>' is an ObjCObjectPointerType whose pointee is an ObjCObjectType
4512 /// with base BuiltinType::ObjCIdType and protocol list [P]. Eventually
4513 /// this should get its own sugar class to better represent the source.
4514 class ObjCObjectType : public Type {
4515 // ObjCObjectType.NumTypeArgs - the number of type arguments stored
4516 // after the ObjCObjectPointerType node.
4517 // ObjCObjectType.NumProtocols - the number of protocols stored
4518 // after the type arguments of ObjCObjectPointerType node.
4520 // These protocols are those written directly on the type. If
4521 // protocol qualifiers ever become additive, the iterators will need
4522 // to get kindof complicated.
4524 // In the canonical object type, these are sorted alphabetically
4527 /// Either a BuiltinType or an InterfaceType or sugar for either.
4530 /// Cached superclass type.
4531 mutable llvm::PointerIntPair<const ObjCObjectType *, 1, bool>
4532 CachedSuperClassType;
4534 ObjCProtocolDecl * const *getProtocolStorage() const {
4535 return const_cast<ObjCObjectType*>(this)->getProtocolStorage();
4538 QualType *getTypeArgStorage();
4539 const QualType *getTypeArgStorage() const {
4540 return const_cast<ObjCObjectType *>(this)->getTypeArgStorage();
4543 ObjCProtocolDecl **getProtocolStorage();
4546 ObjCObjectType(QualType Canonical, QualType Base,
4547 ArrayRef<QualType> typeArgs,
4548 ArrayRef<ObjCProtocolDecl *> protocols,
4551 enum Nonce_ObjCInterface { Nonce_ObjCInterface };
4552 ObjCObjectType(enum Nonce_ObjCInterface)
4553 : Type(ObjCInterface, QualType(), false, false, false, false),
4554 BaseType(QualType(this_(), 0)) {
4555 ObjCObjectTypeBits.NumProtocols = 0;
4556 ObjCObjectTypeBits.NumTypeArgs = 0;
4557 ObjCObjectTypeBits.IsKindOf = 0;
4560 void computeSuperClassTypeSlow() const;
4563 /// getBaseType - Gets the base type of this object type. This is
4564 /// always (possibly sugar for) one of:
4565 /// - the 'id' builtin type (as opposed to the 'id' type visible to the
4566 /// user, which is a typedef for an ObjCObjectPointerType)
4567 /// - the 'Class' builtin type (same caveat)
4568 /// - an ObjCObjectType (currently always an ObjCInterfaceType)
4569 QualType getBaseType() const { return BaseType; }
4571 bool isObjCId() const {
4572 return getBaseType()->isSpecificBuiltinType(BuiltinType::ObjCId);
4574 bool isObjCClass() const {
4575 return getBaseType()->isSpecificBuiltinType(BuiltinType::ObjCClass);
4577 bool isObjCUnqualifiedId() const { return qual_empty() && isObjCId(); }
4578 bool isObjCUnqualifiedClass() const { return qual_empty() && isObjCClass(); }
4579 bool isObjCUnqualifiedIdOrClass() const {
4580 if (!qual_empty()) return false;
4581 if (const BuiltinType *T = getBaseType()->getAs<BuiltinType>())
4582 return T->getKind() == BuiltinType::ObjCId ||
4583 T->getKind() == BuiltinType::ObjCClass;
4586 bool isObjCQualifiedId() const { return !qual_empty() && isObjCId(); }
4587 bool isObjCQualifiedClass() const { return !qual_empty() && isObjCClass(); }
4589 /// Gets the interface declaration for this object type, if the base type
4590 /// really is an interface.
4591 ObjCInterfaceDecl *getInterface() const;
4593 /// Determine whether this object type is "specialized", meaning
4594 /// that it has type arguments.
4595 bool isSpecialized() const;
4597 /// Determine whether this object type was written with type arguments.
4598 bool isSpecializedAsWritten() const {
4599 return ObjCObjectTypeBits.NumTypeArgs > 0;
4602 /// Determine whether this object type is "unspecialized", meaning
4603 /// that it has no type arguments.
4604 bool isUnspecialized() const { return !isSpecialized(); }
4606 /// Determine whether this object type is "unspecialized" as
4607 /// written, meaning that it has no type arguments.
4608 bool isUnspecializedAsWritten() const { return !isSpecializedAsWritten(); }
4610 /// Retrieve the type arguments of this object type (semantically).
4611 ArrayRef<QualType> getTypeArgs() const;
4613 /// Retrieve the type arguments of this object type as they were
4615 ArrayRef<QualType> getTypeArgsAsWritten() const {
4616 return ArrayRef<QualType>(getTypeArgStorage(),
4617 ObjCObjectTypeBits.NumTypeArgs);
4620 typedef ObjCProtocolDecl * const *qual_iterator;
4621 typedef llvm::iterator_range<qual_iterator> qual_range;
4623 qual_range quals() const { return qual_range(qual_begin(), qual_end()); }
4624 qual_iterator qual_begin() const { return getProtocolStorage(); }
4625 qual_iterator qual_end() const { return qual_begin() + getNumProtocols(); }
4627 bool qual_empty() const { return getNumProtocols() == 0; }
4629 /// getNumProtocols - Return the number of qualifying protocols in this
4630 /// interface type, or 0 if there are none.
4631 unsigned getNumProtocols() const { return ObjCObjectTypeBits.NumProtocols; }
4633 /// \brief Fetch a protocol by index.
4634 ObjCProtocolDecl *getProtocol(unsigned I) const {
4635 assert(I < getNumProtocols() && "Out-of-range protocol access");
4636 return qual_begin()[I];
4639 /// Retrieve all of the protocol qualifiers.
4640 ArrayRef<ObjCProtocolDecl *> getProtocols() const {
4641 return ArrayRef<ObjCProtocolDecl *>(qual_begin(), getNumProtocols());
4644 /// Whether this is a "__kindof" type as written.
4645 bool isKindOfTypeAsWritten() const { return ObjCObjectTypeBits.IsKindOf; }
4647 /// Whether this ia a "__kindof" type (semantically).
4648 bool isKindOfType() const;
4650 /// Retrieve the type of the superclass of this object type.
4652 /// This operation substitutes any type arguments into the
4653 /// superclass of the current class type, potentially producing a
4654 /// specialization of the superclass type. Produces a null type if
4655 /// there is no superclass.
4656 QualType getSuperClassType() const {
4657 if (!CachedSuperClassType.getInt())
4658 computeSuperClassTypeSlow();
4660 assert(CachedSuperClassType.getInt() && "Superclass not set?");
4661 return QualType(CachedSuperClassType.getPointer(), 0);
4664 /// Strip off the Objective-C "kindof" type and (with it) any
4665 /// protocol qualifiers.
4666 QualType stripObjCKindOfTypeAndQuals(const ASTContext &ctx) const;
4668 bool isSugared() const { return false; }
4669 QualType desugar() const { return QualType(this, 0); }
4671 static bool classof(const Type *T) {
4672 return T->getTypeClass() == ObjCObject ||
4673 T->getTypeClass() == ObjCInterface;
4677 /// ObjCObjectTypeImpl - A class providing a concrete implementation
4678 /// of ObjCObjectType, so as to not increase the footprint of
4679 /// ObjCInterfaceType. Code outside of ASTContext and the core type
4680 /// system should not reference this type.
4681 class ObjCObjectTypeImpl : public ObjCObjectType, public llvm::FoldingSetNode {
4682 friend class ASTContext;
4684 // If anyone adds fields here, ObjCObjectType::getProtocolStorage()
4685 // will need to be modified.
4687 ObjCObjectTypeImpl(QualType Canonical, QualType Base,
4688 ArrayRef<QualType> typeArgs,
4689 ArrayRef<ObjCProtocolDecl *> protocols,
4691 : ObjCObjectType(Canonical, Base, typeArgs, protocols, isKindOf) {}
4694 void Profile(llvm::FoldingSetNodeID &ID);
4695 static void Profile(llvm::FoldingSetNodeID &ID,
4697 ArrayRef<QualType> typeArgs,
4698 ArrayRef<ObjCProtocolDecl *> protocols,
4702 inline QualType *ObjCObjectType::getTypeArgStorage() {
4703 return reinterpret_cast<QualType *>(static_cast<ObjCObjectTypeImpl*>(this)+1);
4706 inline ObjCProtocolDecl **ObjCObjectType::getProtocolStorage() {
4707 return reinterpret_cast<ObjCProtocolDecl**>(
4708 getTypeArgStorage() + ObjCObjectTypeBits.NumTypeArgs);
4711 /// ObjCInterfaceType - Interfaces are the core concept in Objective-C for
4712 /// object oriented design. They basically correspond to C++ classes. There
4713 /// are two kinds of interface types, normal interfaces like "NSString" and
4714 /// qualified interfaces, which are qualified with a protocol list like
4715 /// "NSString<NSCopyable, NSAmazing>".
4717 /// ObjCInterfaceType guarantees the following properties when considered
4718 /// as a subtype of its superclass, ObjCObjectType:
4719 /// - There are no protocol qualifiers. To reinforce this, code which
4720 /// tries to invoke the protocol methods via an ObjCInterfaceType will
4721 /// fail to compile.
4722 /// - It is its own base type. That is, if T is an ObjCInterfaceType*,
4723 /// T->getBaseType() == QualType(T, 0).
4724 class ObjCInterfaceType : public ObjCObjectType {
4725 mutable ObjCInterfaceDecl *Decl;
4727 ObjCInterfaceType(const ObjCInterfaceDecl *D)
4728 : ObjCObjectType(Nonce_ObjCInterface),
4729 Decl(const_cast<ObjCInterfaceDecl*>(D)) {}
4730 friend class ASTContext; // ASTContext creates these.
4731 friend class ASTReader;
4732 friend class ObjCInterfaceDecl;
4735 /// getDecl - Get the declaration of this interface.
4736 ObjCInterfaceDecl *getDecl() const { return Decl; }
4738 bool isSugared() const { return false; }
4739 QualType desugar() const { return QualType(this, 0); }
4741 static bool classof(const Type *T) {
4742 return T->getTypeClass() == ObjCInterface;
4745 // Nonsense to "hide" certain members of ObjCObjectType within this
4746 // class. People asking for protocols on an ObjCInterfaceType are
4747 // not going to get what they want: ObjCInterfaceTypes are
4748 // guaranteed to have no protocols.
4758 inline ObjCInterfaceDecl *ObjCObjectType::getInterface() const {
4759 QualType baseType = getBaseType();
4760 while (const ObjCObjectType *ObjT = baseType->getAs<ObjCObjectType>()) {
4761 if (const ObjCInterfaceType *T = dyn_cast<ObjCInterfaceType>(ObjT))
4762 return T->getDecl();
4764 baseType = ObjT->getBaseType();
4770 /// ObjCObjectPointerType - Used to represent a pointer to an
4771 /// Objective C object. These are constructed from pointer
4772 /// declarators when the pointee type is an ObjCObjectType (or sugar
4773 /// for one). In addition, the 'id' and 'Class' types are typedefs
4774 /// for these, and the protocol-qualified types 'id<P>' and 'Class<P>'
4775 /// are translated into these.
4777 /// Pointers to pointers to Objective C objects are still PointerTypes;
4778 /// only the first level of pointer gets it own type implementation.
4779 class ObjCObjectPointerType : public Type, public llvm::FoldingSetNode {
4780 QualType PointeeType;
4782 ObjCObjectPointerType(QualType Canonical, QualType Pointee)
4783 : Type(ObjCObjectPointer, Canonical,
4784 Pointee->isDependentType(),
4785 Pointee->isInstantiationDependentType(),
4786 Pointee->isVariablyModifiedType(),
4787 Pointee->containsUnexpandedParameterPack()),
4788 PointeeType(Pointee) {}
4789 friend class ASTContext; // ASTContext creates these.
4792 /// getPointeeType - Gets the type pointed to by this ObjC pointer.
4793 /// The result will always be an ObjCObjectType or sugar thereof.
4794 QualType getPointeeType() const { return PointeeType; }
4796 /// getObjCObjectType - Gets the type pointed to by this ObjC
4797 /// pointer. This method always returns non-null.
4799 /// This method is equivalent to getPointeeType() except that
4800 /// it discards any typedefs (or other sugar) between this
4801 /// type and the "outermost" object type. So for:
4803 /// \@class A; \@protocol P; \@protocol Q;
4804 /// typedef A<P> AP;
4806 /// typedef A1<P> A1P;
4807 /// typedef A1P<Q> A1PQ;
4809 /// For 'A*', getObjectType() will return 'A'.
4810 /// For 'A<P>*', getObjectType() will return 'A<P>'.
4811 /// For 'AP*', getObjectType() will return 'A<P>'.
4812 /// For 'A1*', getObjectType() will return 'A'.
4813 /// For 'A1<P>*', getObjectType() will return 'A1<P>'.
4814 /// For 'A1P*', getObjectType() will return 'A1<P>'.
4815 /// For 'A1PQ*', getObjectType() will return 'A1<Q>', because
4816 /// adding protocols to a protocol-qualified base discards the
4817 /// old qualifiers (for now). But if it didn't, getObjectType()
4818 /// would return 'A1P<Q>' (and we'd have to make iterating over
4819 /// qualifiers more complicated).
4820 const ObjCObjectType *getObjectType() const {
4821 return PointeeType->castAs<ObjCObjectType>();
4824 /// getInterfaceType - If this pointer points to an Objective C
4825 /// \@interface type, gets the type for that interface. Any protocol
4826 /// qualifiers on the interface are ignored.
4828 /// \return null if the base type for this pointer is 'id' or 'Class'
4829 const ObjCInterfaceType *getInterfaceType() const;
4831 /// getInterfaceDecl - If this pointer points to an Objective \@interface
4832 /// type, gets the declaration for that interface.
4834 /// \return null if the base type for this pointer is 'id' or 'Class'
4835 ObjCInterfaceDecl *getInterfaceDecl() const {
4836 return getObjectType()->getInterface();
4839 /// isObjCIdType - True if this is equivalent to the 'id' type, i.e. if
4840 /// its object type is the primitive 'id' type with no protocols.
4841 bool isObjCIdType() const {
4842 return getObjectType()->isObjCUnqualifiedId();
4845 /// isObjCClassType - True if this is equivalent to the 'Class' type,
4846 /// i.e. if its object tive is the primitive 'Class' type with no protocols.
4847 bool isObjCClassType() const {
4848 return getObjectType()->isObjCUnqualifiedClass();
4851 /// isObjCIdOrClassType - True if this is equivalent to the 'id' or
4853 bool isObjCIdOrClassType() const {
4854 return getObjectType()->isObjCUnqualifiedIdOrClass();
4857 /// isObjCQualifiedIdType - True if this is equivalent to 'id<P>' for some
4858 /// non-empty set of protocols.
4859 bool isObjCQualifiedIdType() const {
4860 return getObjectType()->isObjCQualifiedId();
4863 /// isObjCQualifiedClassType - True if this is equivalent to 'Class<P>' for
4864 /// some non-empty set of protocols.
4865 bool isObjCQualifiedClassType() const {
4866 return getObjectType()->isObjCQualifiedClass();
4869 /// Whether this is a "__kindof" type.
4870 bool isKindOfType() const { return getObjectType()->isKindOfType(); }
4872 /// Whether this type is specialized, meaning that it has type arguments.
4873 bool isSpecialized() const { return getObjectType()->isSpecialized(); }
4875 /// Whether this type is specialized, meaning that it has type arguments.
4876 bool isSpecializedAsWritten() const {
4877 return getObjectType()->isSpecializedAsWritten();
4880 /// Whether this type is unspecialized, meaning that is has no type arguments.
4881 bool isUnspecialized() const { return getObjectType()->isUnspecialized(); }
4883 /// Determine whether this object type is "unspecialized" as
4884 /// written, meaning that it has no type arguments.
4885 bool isUnspecializedAsWritten() const { return !isSpecializedAsWritten(); }
4887 /// Retrieve the type arguments for this type.
4888 ArrayRef<QualType> getTypeArgs() const {
4889 return getObjectType()->getTypeArgs();
4892 /// Retrieve the type arguments for this type.
4893 ArrayRef<QualType> getTypeArgsAsWritten() const {
4894 return getObjectType()->getTypeArgsAsWritten();
4897 /// An iterator over the qualifiers on the object type. Provided
4898 /// for convenience. This will always iterate over the full set of
4899 /// protocols on a type, not just those provided directly.
4900 typedef ObjCObjectType::qual_iterator qual_iterator;
4901 typedef llvm::iterator_range<qual_iterator> qual_range;
4903 qual_range quals() const { return qual_range(qual_begin(), qual_end()); }
4904 qual_iterator qual_begin() const {
4905 return getObjectType()->qual_begin();
4907 qual_iterator qual_end() const {
4908 return getObjectType()->qual_end();
4910 bool qual_empty() const { return getObjectType()->qual_empty(); }
4912 /// getNumProtocols - Return the number of qualifying protocols on
4913 /// the object type.
4914 unsigned getNumProtocols() const {
4915 return getObjectType()->getNumProtocols();
4918 /// \brief Retrieve a qualifying protocol by index on the object
4920 ObjCProtocolDecl *getProtocol(unsigned I) const {
4921 return getObjectType()->getProtocol(I);
4924 bool isSugared() const { return false; }
4925 QualType desugar() const { return QualType(this, 0); }
4927 /// Retrieve the type of the superclass of this object pointer type.
4929 /// This operation substitutes any type arguments into the
4930 /// superclass of the current class type, potentially producing a
4931 /// pointer to a specialization of the superclass type. Produces a
4932 /// null type if there is no superclass.
4933 QualType getSuperClassType() const;
4935 /// Strip off the Objective-C "kindof" type and (with it) any
4936 /// protocol qualifiers.
4937 const ObjCObjectPointerType *stripObjCKindOfTypeAndQuals(
4938 const ASTContext &ctx) const;
4940 void Profile(llvm::FoldingSetNodeID &ID) {
4941 Profile(ID, getPointeeType());
4943 static void Profile(llvm::FoldingSetNodeID &ID, QualType T) {
4944 ID.AddPointer(T.getAsOpaquePtr());
4946 static bool classof(const Type *T) {
4947 return T->getTypeClass() == ObjCObjectPointer;
4951 class AtomicType : public Type, public llvm::FoldingSetNode {
4954 AtomicType(QualType ValTy, QualType Canonical)
4955 : Type(Atomic, Canonical, ValTy->isDependentType(),
4956 ValTy->isInstantiationDependentType(),
4957 ValTy->isVariablyModifiedType(),
4958 ValTy->containsUnexpandedParameterPack()),
4960 friend class ASTContext; // ASTContext creates these.
4963 /// getValueType - Gets the type contained by this atomic type, i.e.
4964 /// the type returned by performing an atomic load of this atomic type.
4965 QualType getValueType() const { return ValueType; }
4967 bool isSugared() const { return false; }
4968 QualType desugar() const { return QualType(this, 0); }
4970 void Profile(llvm::FoldingSetNodeID &ID) {
4971 Profile(ID, getValueType());
4973 static void Profile(llvm::FoldingSetNodeID &ID, QualType T) {
4974 ID.AddPointer(T.getAsOpaquePtr());
4976 static bool classof(const Type *T) {
4977 return T->getTypeClass() == Atomic;
4981 /// A qualifier set is used to build a set of qualifiers.
4982 class QualifierCollector : public Qualifiers {
4984 QualifierCollector(Qualifiers Qs = Qualifiers()) : Qualifiers(Qs) {}
4986 /// Collect any qualifiers on the given type and return an
4987 /// unqualified type. The qualifiers are assumed to be consistent
4988 /// with those already in the type.
4989 const Type *strip(QualType type) {
4990 addFastQualifiers(type.getLocalFastQualifiers());
4991 if (!type.hasLocalNonFastQualifiers())
4992 return type.getTypePtrUnsafe();
4994 const ExtQuals *extQuals = type.getExtQualsUnsafe();
4995 addConsistentQualifiers(extQuals->getQualifiers());
4996 return extQuals->getBaseType();
4999 /// Apply the collected qualifiers to the given type.
5000 QualType apply(const ASTContext &Context, QualType QT) const;
5002 /// Apply the collected qualifiers to the given type.
5003 QualType apply(const ASTContext &Context, const Type* T) const;
5007 // Inline function definitions.
5009 inline SplitQualType SplitQualType::getSingleStepDesugaredType() const {
5010 SplitQualType desugar =
5011 Ty->getLocallyUnqualifiedSingleStepDesugaredType().split();
5012 desugar.Quals.addConsistentQualifiers(Quals);
5016 inline const Type *QualType::getTypePtr() const {
5017 return getCommonPtr()->BaseType;
5020 inline const Type *QualType::getTypePtrOrNull() const {
5021 return (isNull() ? nullptr : getCommonPtr()->BaseType);
5024 inline SplitQualType QualType::split() const {
5025 if (!hasLocalNonFastQualifiers())
5026 return SplitQualType(getTypePtrUnsafe(),
5027 Qualifiers::fromFastMask(getLocalFastQualifiers()));
5029 const ExtQuals *eq = getExtQualsUnsafe();
5030 Qualifiers qs = eq->getQualifiers();
5031 qs.addFastQualifiers(getLocalFastQualifiers());
5032 return SplitQualType(eq->getBaseType(), qs);
5035 inline Qualifiers QualType::getLocalQualifiers() const {
5037 if (hasLocalNonFastQualifiers())
5038 Quals = getExtQualsUnsafe()->getQualifiers();
5039 Quals.addFastQualifiers(getLocalFastQualifiers());
5043 inline Qualifiers QualType::getQualifiers() const {
5044 Qualifiers quals = getCommonPtr()->CanonicalType.getLocalQualifiers();
5045 quals.addFastQualifiers(getLocalFastQualifiers());
5049 inline unsigned QualType::getCVRQualifiers() const {
5050 unsigned cvr = getCommonPtr()->CanonicalType.getLocalCVRQualifiers();
5051 cvr |= getLocalCVRQualifiers();
5055 inline QualType QualType::getCanonicalType() const {
5056 QualType canon = getCommonPtr()->CanonicalType;
5057 return canon.withFastQualifiers(getLocalFastQualifiers());
5060 inline bool QualType::isCanonical() const {
5061 return getTypePtr()->isCanonicalUnqualified();
5064 inline bool QualType::isCanonicalAsParam() const {
5065 if (!isCanonical()) return false;
5066 if (hasLocalQualifiers()) return false;
5068 const Type *T = getTypePtr();
5069 if (T->isVariablyModifiedType() && T->hasSizedVLAType())
5072 return !isa<FunctionType>(T) && !isa<ArrayType>(T);
5075 inline bool QualType::isConstQualified() const {
5076 return isLocalConstQualified() ||
5077 getCommonPtr()->CanonicalType.isLocalConstQualified();
5080 inline bool QualType::isRestrictQualified() const {
5081 return isLocalRestrictQualified() ||
5082 getCommonPtr()->CanonicalType.isLocalRestrictQualified();
5086 inline bool QualType::isVolatileQualified() const {
5087 return isLocalVolatileQualified() ||
5088 getCommonPtr()->CanonicalType.isLocalVolatileQualified();
5091 inline bool QualType::hasQualifiers() const {
5092 return hasLocalQualifiers() ||
5093 getCommonPtr()->CanonicalType.hasLocalQualifiers();
5096 inline QualType QualType::getUnqualifiedType() const {
5097 if (!getTypePtr()->getCanonicalTypeInternal().hasLocalQualifiers())
5098 return QualType(getTypePtr(), 0);
5100 return QualType(getSplitUnqualifiedTypeImpl(*this).Ty, 0);
5103 inline SplitQualType QualType::getSplitUnqualifiedType() const {
5104 if (!getTypePtr()->getCanonicalTypeInternal().hasLocalQualifiers())
5107 return getSplitUnqualifiedTypeImpl(*this);
5110 inline void QualType::removeLocalConst() {
5111 removeLocalFastQualifiers(Qualifiers::Const);
5114 inline void QualType::removeLocalRestrict() {
5115 removeLocalFastQualifiers(Qualifiers::Restrict);
5118 inline void QualType::removeLocalVolatile() {
5119 removeLocalFastQualifiers(Qualifiers::Volatile);
5122 inline void QualType::removeLocalCVRQualifiers(unsigned Mask) {
5123 assert(!(Mask & ~Qualifiers::CVRMask) && "mask has non-CVR bits");
5124 assert((int)Qualifiers::CVRMask == (int)Qualifiers::FastMask);
5126 // Fast path: we don't need to touch the slow qualifiers.
5127 removeLocalFastQualifiers(Mask);
5130 /// getAddressSpace - Return the address space of this type.
5131 inline unsigned QualType::getAddressSpace() const {
5132 return getQualifiers().getAddressSpace();
5135 /// getObjCGCAttr - Return the gc attribute of this type.
5136 inline Qualifiers::GC QualType::getObjCGCAttr() const {
5137 return getQualifiers().getObjCGCAttr();
5140 inline FunctionType::ExtInfo getFunctionExtInfo(const Type &t) {
5141 if (const PointerType *PT = t.getAs<PointerType>()) {
5142 if (const FunctionType *FT = PT->getPointeeType()->getAs<FunctionType>())
5143 return FT->getExtInfo();
5144 } else if (const FunctionType *FT = t.getAs<FunctionType>())
5145 return FT->getExtInfo();
5147 return FunctionType::ExtInfo();
5150 inline FunctionType::ExtInfo getFunctionExtInfo(QualType t) {
5151 return getFunctionExtInfo(*t);
5154 /// isMoreQualifiedThan - Determine whether this type is more
5155 /// qualified than the Other type. For example, "const volatile int"
5156 /// is more qualified than "const int", "volatile int", and
5157 /// "int". However, it is not more qualified than "const volatile
5159 inline bool QualType::isMoreQualifiedThan(QualType other) const {
5160 Qualifiers myQuals = getQualifiers();
5161 Qualifiers otherQuals = other.getQualifiers();
5162 return (myQuals != otherQuals && myQuals.compatiblyIncludes(otherQuals));
5165 /// isAtLeastAsQualifiedAs - Determine whether this type is at last
5166 /// as qualified as the Other type. For example, "const volatile
5167 /// int" is at least as qualified as "const int", "volatile int",
5168 /// "int", and "const volatile int".
5169 inline bool QualType::isAtLeastAsQualifiedAs(QualType other) const {
5170 return getQualifiers().compatiblyIncludes(other.getQualifiers());
5173 /// getNonReferenceType - If Type is a reference type (e.g., const
5174 /// int&), returns the type that the reference refers to ("const
5175 /// int"). Otherwise, returns the type itself. This routine is used
5176 /// throughout Sema to implement C++ 5p6:
5178 /// If an expression initially has the type "reference to T" (8.3.2,
5179 /// 8.5.3), the type is adjusted to "T" prior to any further
5180 /// analysis, the expression designates the object or function
5181 /// denoted by the reference, and the expression is an lvalue.
5182 inline QualType QualType::getNonReferenceType() const {
5183 if (const ReferenceType *RefType = (*this)->getAs<ReferenceType>())
5184 return RefType->getPointeeType();
5189 inline bool QualType::isCForbiddenLValueType() const {
5190 return ((getTypePtr()->isVoidType() && !hasQualifiers()) ||
5191 getTypePtr()->isFunctionType());
5194 /// \brief Tests whether the type is categorized as a fundamental type.
5196 /// \returns True for types specified in C++0x [basic.fundamental].
5197 inline bool Type::isFundamentalType() const {
5198 return isVoidType() ||
5199 // FIXME: It's really annoying that we don't have an
5200 // 'isArithmeticType()' which agrees with the standard definition.
5201 (isArithmeticType() && !isEnumeralType());
5204 /// \brief Tests whether the type is categorized as a compound type.
5206 /// \returns True for types specified in C++0x [basic.compound].
5207 inline bool Type::isCompoundType() const {
5208 // C++0x [basic.compound]p1:
5209 // Compound types can be constructed in the following ways:
5210 // -- arrays of objects of a given type [...];
5211 return isArrayType() ||
5212 // -- functions, which have parameters of given types [...];
5214 // -- pointers to void or objects or functions [...];
5216 // -- references to objects or functions of a given type. [...]
5217 isReferenceType() ||
5218 // -- classes containing a sequence of objects of various types, [...];
5220 // -- unions, which are classes capable of containing objects of different
5221 // types at different times;
5223 // -- enumerations, which comprise a set of named constant values. [...];
5225 // -- pointers to non-static class members, [...].
5226 isMemberPointerType();
5229 inline bool Type::isFunctionType() const {
5230 return isa<FunctionType>(CanonicalType);
5232 inline bool Type::isPointerType() const {
5233 return isa<PointerType>(CanonicalType);
5235 inline bool Type::isAnyPointerType() const {
5236 return isPointerType() || isObjCObjectPointerType();
5238 inline bool Type::isBlockPointerType() const {
5239 return isa<BlockPointerType>(CanonicalType);
5241 inline bool Type::isReferenceType() const {
5242 return isa<ReferenceType>(CanonicalType);
5244 inline bool Type::isLValueReferenceType() const {
5245 return isa<LValueReferenceType>(CanonicalType);
5247 inline bool Type::isRValueReferenceType() const {
5248 return isa<RValueReferenceType>(CanonicalType);
5250 inline bool Type::isFunctionPointerType() const {
5251 if (const PointerType *T = getAs<PointerType>())
5252 return T->getPointeeType()->isFunctionType();
5256 inline bool Type::isMemberPointerType() const {
5257 return isa<MemberPointerType>(CanonicalType);
5259 inline bool Type::isMemberFunctionPointerType() const {
5260 if (const MemberPointerType* T = getAs<MemberPointerType>())
5261 return T->isMemberFunctionPointer();
5265 inline bool Type::isMemberDataPointerType() const {
5266 if (const MemberPointerType* T = getAs<MemberPointerType>())
5267 return T->isMemberDataPointer();
5271 inline bool Type::isArrayType() const {
5272 return isa<ArrayType>(CanonicalType);
5274 inline bool Type::isConstantArrayType() const {
5275 return isa<ConstantArrayType>(CanonicalType);
5277 inline bool Type::isIncompleteArrayType() const {
5278 return isa<IncompleteArrayType>(CanonicalType);
5280 inline bool Type::isVariableArrayType() const {
5281 return isa<VariableArrayType>(CanonicalType);
5283 inline bool Type::isDependentSizedArrayType() const {
5284 return isa<DependentSizedArrayType>(CanonicalType);
5286 inline bool Type::isBuiltinType() const {
5287 return isa<BuiltinType>(CanonicalType);
5289 inline bool Type::isRecordType() const {
5290 return isa<RecordType>(CanonicalType);
5292 inline bool Type::isEnumeralType() const {
5293 return isa<EnumType>(CanonicalType);
5295 inline bool Type::isAnyComplexType() const {
5296 return isa<ComplexType>(CanonicalType);
5298 inline bool Type::isVectorType() const {
5299 return isa<VectorType>(CanonicalType);
5301 inline bool Type::isExtVectorType() const {
5302 return isa<ExtVectorType>(CanonicalType);
5304 inline bool Type::isObjCObjectPointerType() const {
5305 return isa<ObjCObjectPointerType>(CanonicalType);
5307 inline bool Type::isObjCObjectType() const {
5308 return isa<ObjCObjectType>(CanonicalType);
5310 inline bool Type::isObjCObjectOrInterfaceType() const {
5311 return isa<ObjCInterfaceType>(CanonicalType) ||
5312 isa<ObjCObjectType>(CanonicalType);
5314 inline bool Type::isAtomicType() const {
5315 return isa<AtomicType>(CanonicalType);
5318 inline bool Type::isObjCQualifiedIdType() const {
5319 if (const ObjCObjectPointerType *OPT = getAs<ObjCObjectPointerType>())
5320 return OPT->isObjCQualifiedIdType();
5323 inline bool Type::isObjCQualifiedClassType() const {
5324 if (const ObjCObjectPointerType *OPT = getAs<ObjCObjectPointerType>())
5325 return OPT->isObjCQualifiedClassType();
5328 inline bool Type::isObjCIdType() const {
5329 if (const ObjCObjectPointerType *OPT = getAs<ObjCObjectPointerType>())
5330 return OPT->isObjCIdType();
5333 inline bool Type::isObjCClassType() const {
5334 if (const ObjCObjectPointerType *OPT = getAs<ObjCObjectPointerType>())
5335 return OPT->isObjCClassType();
5338 inline bool Type::isObjCSelType() const {
5339 if (const PointerType *OPT = getAs<PointerType>())
5340 return OPT->getPointeeType()->isSpecificBuiltinType(BuiltinType::ObjCSel);
5343 inline bool Type::isObjCBuiltinType() const {
5344 return isObjCIdType() || isObjCClassType() || isObjCSelType();
5347 inline bool Type::isImage1dT() const {
5348 return isSpecificBuiltinType(BuiltinType::OCLImage1d);
5351 inline bool Type::isImage1dArrayT() const {
5352 return isSpecificBuiltinType(BuiltinType::OCLImage1dArray);
5355 inline bool Type::isImage1dBufferT() const {
5356 return isSpecificBuiltinType(BuiltinType::OCLImage1dBuffer);
5359 inline bool Type::isImage2dT() const {
5360 return isSpecificBuiltinType(BuiltinType::OCLImage2d);
5363 inline bool Type::isImage2dArrayT() const {
5364 return isSpecificBuiltinType(BuiltinType::OCLImage2dArray);
5367 inline bool Type::isImage3dT() const {
5368 return isSpecificBuiltinType(BuiltinType::OCLImage3d);
5371 inline bool Type::isSamplerT() const {
5372 return isSpecificBuiltinType(BuiltinType::OCLSampler);
5375 inline bool Type::isEventT() const {
5376 return isSpecificBuiltinType(BuiltinType::OCLEvent);
5379 inline bool Type::isImageType() const {
5380 return isImage3dT() ||
5381 isImage2dT() || isImage2dArrayT() ||
5382 isImage1dT() || isImage1dArrayT() || isImage1dBufferT();
5385 inline bool Type::isOpenCLSpecificType() const {
5386 return isSamplerT() || isEventT() || isImageType();
5389 inline bool Type::isTemplateTypeParmType() const {
5390 return isa<TemplateTypeParmType>(CanonicalType);
5393 inline bool Type::isSpecificBuiltinType(unsigned K) const {
5394 if (const BuiltinType *BT = getAs<BuiltinType>())
5395 if (BT->getKind() == (BuiltinType::Kind) K)
5400 inline bool Type::isPlaceholderType() const {
5401 if (const BuiltinType *BT = dyn_cast<BuiltinType>(this))
5402 return BT->isPlaceholderType();
5406 inline const BuiltinType *Type::getAsPlaceholderType() const {
5407 if (const BuiltinType *BT = dyn_cast<BuiltinType>(this))
5408 if (BT->isPlaceholderType())
5413 inline bool Type::isSpecificPlaceholderType(unsigned K) const {
5414 assert(BuiltinType::isPlaceholderTypeKind((BuiltinType::Kind) K));
5415 if (const BuiltinType *BT = dyn_cast<BuiltinType>(this))
5416 return (BT->getKind() == (BuiltinType::Kind) K);
5420 inline bool Type::isNonOverloadPlaceholderType() const {
5421 if (const BuiltinType *BT = dyn_cast<BuiltinType>(this))
5422 return BT->isNonOverloadPlaceholderType();
5426 inline bool Type::isVoidType() const {
5427 if (const BuiltinType *BT = dyn_cast<BuiltinType>(CanonicalType))
5428 return BT->getKind() == BuiltinType::Void;
5432 inline bool Type::isHalfType() const {
5433 if (const BuiltinType *BT = dyn_cast<BuiltinType>(CanonicalType))
5434 return BT->getKind() == BuiltinType::Half;
5435 // FIXME: Should we allow complex __fp16? Probably not.
5439 inline bool Type::isNullPtrType() const {
5440 if (const BuiltinType *BT = getAs<BuiltinType>())
5441 return BT->getKind() == BuiltinType::NullPtr;
5445 extern bool IsEnumDeclComplete(EnumDecl *);
5446 extern bool IsEnumDeclScoped(EnumDecl *);
5448 inline bool Type::isIntegerType() const {
5449 if (const BuiltinType *BT = dyn_cast<BuiltinType>(CanonicalType))
5450 return BT->getKind() >= BuiltinType::Bool &&
5451 BT->getKind() <= BuiltinType::Int128;
5452 if (const EnumType *ET = dyn_cast<EnumType>(CanonicalType)) {
5453 // Incomplete enum types are not treated as integer types.
5454 // FIXME: In C++, enum types are never integer types.
5455 return IsEnumDeclComplete(ET->getDecl()) &&
5456 !IsEnumDeclScoped(ET->getDecl());
5461 inline bool Type::isScalarType() const {
5462 if (const BuiltinType *BT = dyn_cast<BuiltinType>(CanonicalType))
5463 return BT->getKind() > BuiltinType::Void &&
5464 BT->getKind() <= BuiltinType::NullPtr;
5465 if (const EnumType *ET = dyn_cast<EnumType>(CanonicalType))
5466 // Enums are scalar types, but only if they are defined. Incomplete enums
5467 // are not treated as scalar types.
5468 return IsEnumDeclComplete(ET->getDecl());
5469 return isa<PointerType>(CanonicalType) ||
5470 isa<BlockPointerType>(CanonicalType) ||
5471 isa<MemberPointerType>(CanonicalType) ||
5472 isa<ComplexType>(CanonicalType) ||
5473 isa<ObjCObjectPointerType>(CanonicalType);
5476 inline bool Type::isIntegralOrEnumerationType() const {
5477 if (const BuiltinType *BT = dyn_cast<BuiltinType>(CanonicalType))
5478 return BT->getKind() >= BuiltinType::Bool &&
5479 BT->getKind() <= BuiltinType::Int128;
5481 // Check for a complete enum type; incomplete enum types are not properly an
5482 // enumeration type in the sense required here.
5483 if (const EnumType *ET = dyn_cast<EnumType>(CanonicalType))
5484 return IsEnumDeclComplete(ET->getDecl());
5489 inline bool Type::isBooleanType() const {
5490 if (const BuiltinType *BT = dyn_cast<BuiltinType>(CanonicalType))
5491 return BT->getKind() == BuiltinType::Bool;
5495 inline bool Type::isUndeducedType() const {
5496 const AutoType *AT = getContainedAutoType();
5497 return AT && !AT->isDeduced();
5500 /// \brief Determines whether this is a type for which one can define
5501 /// an overloaded operator.
5502 inline bool Type::isOverloadableType() const {
5503 return isDependentType() || isRecordType() || isEnumeralType();
5506 /// \brief Determines whether this type can decay to a pointer type.
5507 inline bool Type::canDecayToPointerType() const {
5508 return isFunctionType() || isArrayType();
5511 inline bool Type::hasPointerRepresentation() const {
5512 return (isPointerType() || isReferenceType() || isBlockPointerType() ||
5513 isObjCObjectPointerType() || isNullPtrType());
5516 inline bool Type::hasObjCPointerRepresentation() const {
5517 return isObjCObjectPointerType();
5520 inline const Type *Type::getBaseElementTypeUnsafe() const {
5521 const Type *type = this;
5522 while (const ArrayType *arrayType = type->getAsArrayTypeUnsafe())
5523 type = arrayType->getElementType().getTypePtr();
5527 /// Insertion operator for diagnostics. This allows sending QualType's into a
5528 /// diagnostic with <<.
5529 inline const DiagnosticBuilder &operator<<(const DiagnosticBuilder &DB,
5531 DB.AddTaggedVal(reinterpret_cast<intptr_t>(T.getAsOpaquePtr()),
5532 DiagnosticsEngine::ak_qualtype);
5536 /// Insertion operator for partial diagnostics. This allows sending QualType's
5537 /// into a diagnostic with <<.
5538 inline const PartialDiagnostic &operator<<(const PartialDiagnostic &PD,
5540 PD.AddTaggedVal(reinterpret_cast<intptr_t>(T.getAsOpaquePtr()),
5541 DiagnosticsEngine::ak_qualtype);
5545 // Helper class template that is used by Type::getAs to ensure that one does
5546 // not try to look through a qualified type to get to an array type.
5547 template <typename T, bool isArrayType = (std::is_same<T, ArrayType>::value ||
5548 std::is_base_of<ArrayType, T>::value)>
5549 struct ArrayType_cannot_be_used_with_getAs {};
5551 template<typename T>
5552 struct ArrayType_cannot_be_used_with_getAs<T, true>;
5554 // Member-template getAs<specific type>'.
5555 template <typename T> const T *Type::getAs() const {
5556 ArrayType_cannot_be_used_with_getAs<T> at;
5559 // If this is directly a T type, return it.
5560 if (const T *Ty = dyn_cast<T>(this))
5563 // If the canonical form of this type isn't the right kind, reject it.
5564 if (!isa<T>(CanonicalType))
5567 // If this is a typedef for the type, strip the typedef off without
5568 // losing all typedef information.
5569 return cast<T>(getUnqualifiedDesugaredType());
5572 inline const ArrayType *Type::getAsArrayTypeUnsafe() const {
5573 // If this is directly an array type, return it.
5574 if (const ArrayType *arr = dyn_cast<ArrayType>(this))
5577 // If the canonical form of this type isn't the right kind, reject it.
5578 if (!isa<ArrayType>(CanonicalType))
5581 // If this is a typedef for the type, strip the typedef off without
5582 // losing all typedef information.
5583 return cast<ArrayType>(getUnqualifiedDesugaredType());
5586 template <typename T> const T *Type::castAs() const {
5587 ArrayType_cannot_be_used_with_getAs<T> at;
5590 if (const T *ty = dyn_cast<T>(this)) return ty;
5591 assert(isa<T>(CanonicalType));
5592 return cast<T>(getUnqualifiedDesugaredType());
5595 inline const ArrayType *Type::castAsArrayTypeUnsafe() const {
5596 assert(isa<ArrayType>(CanonicalType));
5597 if (const ArrayType *arr = dyn_cast<ArrayType>(this)) return arr;
5598 return cast<ArrayType>(getUnqualifiedDesugaredType());
5601 } // end namespace clang