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 /// \brief C Language Family Type Representation
12 /// This file defines the clang::Type interface and subclasses, used to
13 /// represent types for languages in the C family.
15 //===----------------------------------------------------------------------===//
17 #ifndef LLVM_CLANG_AST_TYPE_H
18 #define LLVM_CLANG_AST_TYPE_H
20 #include "clang/AST/NestedNameSpecifier.h"
21 #include "clang/AST/TemplateName.h"
22 #include "clang/Basic/AddressSpaces.h"
23 #include "clang/Basic/Diagnostic.h"
24 #include "clang/Basic/ExceptionSpecificationType.h"
25 #include "clang/Basic/LLVM.h"
26 #include "clang/Basic/Linkage.h"
27 #include "clang/Basic/PartialDiagnostic.h"
28 #include "clang/Basic/Specifiers.h"
29 #include "clang/Basic/Visibility.h"
30 #include "llvm/ADT/APInt.h"
31 #include "llvm/ADT/FoldingSet.h"
32 #include "llvm/ADT/Optional.h"
33 #include "llvm/ADT/PointerIntPair.h"
34 #include "llvm/ADT/PointerUnion.h"
35 #include "llvm/ADT/Twine.h"
36 #include "llvm/ADT/iterator_range.h"
37 #include "llvm/Support/ErrorHandling.h"
41 TypeAlignmentInBits = 4,
42 TypeAlignment = 1 << TypeAlignmentInBits
51 class PointerLikeTypeTraits;
53 class PointerLikeTypeTraits< ::clang::Type*> {
55 static inline void *getAsVoidPointer(::clang::Type *P) { return P; }
56 static inline ::clang::Type *getFromVoidPointer(void *P) {
57 return static_cast< ::clang::Type*>(P);
59 enum { NumLowBitsAvailable = clang::TypeAlignmentInBits };
62 class PointerLikeTypeTraits< ::clang::ExtQuals*> {
64 static inline void *getAsVoidPointer(::clang::ExtQuals *P) { return P; }
65 static inline ::clang::ExtQuals *getFromVoidPointer(void *P) {
66 return static_cast< ::clang::ExtQuals*>(P);
68 enum { NumLowBitsAvailable = clang::TypeAlignmentInBits };
72 struct isPodLike<clang::QualType> { static const bool value = true; };
77 class TypedefNameDecl;
79 class TemplateTypeParmDecl;
80 class NonTypeTemplateParmDecl;
81 class TemplateTemplateParmDecl;
88 class ObjCInterfaceDecl;
89 class ObjCProtocolDecl;
91 class ObjCTypeParamDecl;
92 class UnresolvedUsingTypenameDecl;
96 class StmtIteratorBase;
97 class TemplateArgument;
98 class TemplateArgumentLoc;
99 class TemplateArgumentListInfo;
100 class ElaboratedType;
102 class ExtQualsTypeCommonBase;
103 struct PrintingPolicy;
105 template <typename> class CanQual;
106 typedef CanQual<Type> CanQualType;
108 // Provide forward declarations for all of the *Type classes
109 #define TYPE(Class, Base) class Class##Type;
110 #include "clang/AST/TypeNodes.def"
112 /// The collection of all-type qualifiers we support.
113 /// Clang supports five independent qualifiers:
114 /// * C99: const, volatile, and restrict
115 /// * MS: __unaligned
116 /// * Embedded C (TR18037): address spaces
117 /// * Objective C: the GC attributes (none, weak, or strong)
120 enum TQ { // NOTE: These flags must be kept in sync with DeclSpec::TQ.
124 CVRMask = Const | Volatile | Restrict
134 /// There is no lifetime qualification on this type.
137 /// This object can be modified without requiring retains or
141 /// Assigning into this object requires the old value to be
142 /// released and the new value to be retained. The timing of the
143 /// release of the old value is inexact: it may be moved to
144 /// immediately after the last known point where the value is
148 /// Reading or writing from this object requires a barrier call.
151 /// Assigning into this object requires a lifetime extension.
156 /// The maximum supported address space number.
157 /// 23 bits should be enough for anyone.
158 MaxAddressSpace = 0x7fffffu,
160 /// The width of the "fast" qualifier mask.
163 /// The fast qualifier mask.
164 FastMask = (1 << FastWidth) - 1
167 Qualifiers() : Mask(0) {}
169 /// Returns the common set of qualifiers while removing them from
171 static Qualifiers removeCommonQualifiers(Qualifiers &L, Qualifiers &R) {
172 // If both are only CVR-qualified, bit operations are sufficient.
173 if (!(L.Mask & ~CVRMask) && !(R.Mask & ~CVRMask)) {
175 Q.Mask = L.Mask & R.Mask;
182 unsigned CommonCRV = L.getCVRQualifiers() & R.getCVRQualifiers();
183 Q.addCVRQualifiers(CommonCRV);
184 L.removeCVRQualifiers(CommonCRV);
185 R.removeCVRQualifiers(CommonCRV);
187 if (L.getObjCGCAttr() == R.getObjCGCAttr()) {
188 Q.setObjCGCAttr(L.getObjCGCAttr());
189 L.removeObjCGCAttr();
190 R.removeObjCGCAttr();
193 if (L.getObjCLifetime() == R.getObjCLifetime()) {
194 Q.setObjCLifetime(L.getObjCLifetime());
195 L.removeObjCLifetime();
196 R.removeObjCLifetime();
199 if (L.getAddressSpace() == R.getAddressSpace()) {
200 Q.setAddressSpace(L.getAddressSpace());
201 L.removeAddressSpace();
202 R.removeAddressSpace();
207 static Qualifiers fromFastMask(unsigned Mask) {
209 Qs.addFastQualifiers(Mask);
213 static Qualifiers fromCVRMask(unsigned CVR) {
215 Qs.addCVRQualifiers(CVR);
219 static Qualifiers fromCVRUMask(unsigned CVRU) {
221 Qs.addCVRUQualifiers(CVRU);
225 // Deserialize qualifiers from an opaque representation.
226 static Qualifiers fromOpaqueValue(unsigned opaque) {
232 // Serialize these qualifiers into an opaque representation.
233 unsigned getAsOpaqueValue() const {
237 bool hasConst() const { return Mask & Const; }
238 void setConst(bool flag) {
239 Mask = (Mask & ~Const) | (flag ? Const : 0);
241 void removeConst() { Mask &= ~Const; }
242 void addConst() { Mask |= Const; }
244 bool hasVolatile() const { return Mask & Volatile; }
245 void setVolatile(bool flag) {
246 Mask = (Mask & ~Volatile) | (flag ? Volatile : 0);
248 void removeVolatile() { Mask &= ~Volatile; }
249 void addVolatile() { Mask |= Volatile; }
251 bool hasRestrict() const { return Mask & Restrict; }
252 void setRestrict(bool flag) {
253 Mask = (Mask & ~Restrict) | (flag ? Restrict : 0);
255 void removeRestrict() { Mask &= ~Restrict; }
256 void addRestrict() { Mask |= Restrict; }
258 bool hasCVRQualifiers() const { return getCVRQualifiers(); }
259 unsigned getCVRQualifiers() const { return Mask & CVRMask; }
260 void setCVRQualifiers(unsigned mask) {
261 assert(!(mask & ~CVRMask) && "bitmask contains non-CVR bits");
262 Mask = (Mask & ~CVRMask) | mask;
264 void removeCVRQualifiers(unsigned mask) {
265 assert(!(mask & ~CVRMask) && "bitmask contains non-CVR bits");
268 void removeCVRQualifiers() {
269 removeCVRQualifiers(CVRMask);
271 void addCVRQualifiers(unsigned mask) {
272 assert(!(mask & ~CVRMask) && "bitmask contains non-CVR bits");
275 void addCVRUQualifiers(unsigned mask) {
276 assert(!(mask & ~CVRMask & ~UMask) && "bitmask contains non-CVRU bits");
280 bool hasUnaligned() const { return Mask & UMask; }
281 void setUnaligned(bool flag) {
282 Mask = (Mask & ~UMask) | (flag ? UMask : 0);
284 void removeUnaligned() { Mask &= ~UMask; }
285 void addUnaligned() { Mask |= UMask; }
287 bool hasObjCGCAttr() const { return Mask & GCAttrMask; }
288 GC getObjCGCAttr() const { return GC((Mask & GCAttrMask) >> GCAttrShift); }
289 void setObjCGCAttr(GC type) {
290 Mask = (Mask & ~GCAttrMask) | (type << GCAttrShift);
292 void removeObjCGCAttr() { setObjCGCAttr(GCNone); }
293 void addObjCGCAttr(GC type) {
297 Qualifiers withoutObjCGCAttr() const {
298 Qualifiers qs = *this;
299 qs.removeObjCGCAttr();
302 Qualifiers withoutObjCLifetime() const {
303 Qualifiers qs = *this;
304 qs.removeObjCLifetime();
308 bool hasObjCLifetime() const { return Mask & LifetimeMask; }
309 ObjCLifetime getObjCLifetime() const {
310 return ObjCLifetime((Mask & LifetimeMask) >> LifetimeShift);
312 void setObjCLifetime(ObjCLifetime type) {
313 Mask = (Mask & ~LifetimeMask) | (type << LifetimeShift);
315 void removeObjCLifetime() { setObjCLifetime(OCL_None); }
316 void addObjCLifetime(ObjCLifetime type) {
318 assert(!hasObjCLifetime());
319 Mask |= (type << LifetimeShift);
322 /// True if the lifetime is neither None or ExplicitNone.
323 bool hasNonTrivialObjCLifetime() const {
324 ObjCLifetime lifetime = getObjCLifetime();
325 return (lifetime > OCL_ExplicitNone);
328 /// True if the lifetime is either strong or weak.
329 bool hasStrongOrWeakObjCLifetime() const {
330 ObjCLifetime lifetime = getObjCLifetime();
331 return (lifetime == OCL_Strong || lifetime == OCL_Weak);
334 bool hasAddressSpace() const { return Mask & AddressSpaceMask; }
335 unsigned getAddressSpace() const { return Mask >> AddressSpaceShift; }
336 void setAddressSpace(unsigned space) {
337 assert(space <= MaxAddressSpace);
338 Mask = (Mask & ~AddressSpaceMask)
339 | (((uint32_t) space) << AddressSpaceShift);
341 void removeAddressSpace() { setAddressSpace(0); }
342 void addAddressSpace(unsigned space) {
344 setAddressSpace(space);
347 // Fast qualifiers are those that can be allocated directly
348 // on a QualType object.
349 bool hasFastQualifiers() const { return getFastQualifiers(); }
350 unsigned getFastQualifiers() const { return Mask & FastMask; }
351 void setFastQualifiers(unsigned mask) {
352 assert(!(mask & ~FastMask) && "bitmask contains non-fast qualifier bits");
353 Mask = (Mask & ~FastMask) | mask;
355 void removeFastQualifiers(unsigned mask) {
356 assert(!(mask & ~FastMask) && "bitmask contains non-fast qualifier bits");
359 void removeFastQualifiers() {
360 removeFastQualifiers(FastMask);
362 void addFastQualifiers(unsigned mask) {
363 assert(!(mask & ~FastMask) && "bitmask contains non-fast qualifier bits");
367 /// Return true if the set contains any qualifiers which require an ExtQuals
368 /// node to be allocated.
369 bool hasNonFastQualifiers() const { return Mask & ~FastMask; }
370 Qualifiers getNonFastQualifiers() const {
371 Qualifiers Quals = *this;
372 Quals.setFastQualifiers(0);
376 /// Return true if the set contains any qualifiers.
377 bool hasQualifiers() const { return Mask; }
378 bool empty() const { return !Mask; }
380 /// Add the qualifiers from the given set to this set.
381 void addQualifiers(Qualifiers Q) {
382 // If the other set doesn't have any non-boolean qualifiers, just
384 if (!(Q.Mask & ~CVRMask))
387 Mask |= (Q.Mask & CVRMask);
388 if (Q.hasAddressSpace())
389 addAddressSpace(Q.getAddressSpace());
390 if (Q.hasObjCGCAttr())
391 addObjCGCAttr(Q.getObjCGCAttr());
392 if (Q.hasObjCLifetime())
393 addObjCLifetime(Q.getObjCLifetime());
397 /// \brief Remove the qualifiers from the given set from this set.
398 void removeQualifiers(Qualifiers Q) {
399 // If the other set doesn't have any non-boolean qualifiers, just
400 // bit-and the inverse in.
401 if (!(Q.Mask & ~CVRMask))
404 Mask &= ~(Q.Mask & CVRMask);
405 if (getObjCGCAttr() == Q.getObjCGCAttr())
407 if (getObjCLifetime() == Q.getObjCLifetime())
408 removeObjCLifetime();
409 if (getAddressSpace() == Q.getAddressSpace())
410 removeAddressSpace();
414 /// Add the qualifiers from the given set to this set, given that
415 /// they don't conflict.
416 void addConsistentQualifiers(Qualifiers qs) {
417 assert(getAddressSpace() == qs.getAddressSpace() ||
418 !hasAddressSpace() || !qs.hasAddressSpace());
419 assert(getObjCGCAttr() == qs.getObjCGCAttr() ||
420 !hasObjCGCAttr() || !qs.hasObjCGCAttr());
421 assert(getObjCLifetime() == qs.getObjCLifetime() ||
422 !hasObjCLifetime() || !qs.hasObjCLifetime());
426 /// Returns true if this address space is a superset of the other one.
427 /// OpenCL v2.0 defines conversion rules (OpenCLC v2.0 s6.5.5) and notion of
428 /// overlapping address spaces.
430 /// every address space is a superset of itself.
432 /// __generic is a superset of any address space except for __constant.
433 bool isAddressSpaceSupersetOf(Qualifiers other) const {
435 // Address spaces must match exactly.
436 getAddressSpace() == other.getAddressSpace() ||
437 // Otherwise in OpenCLC v2.0 s6.5.5: every address space except
438 // for __constant can be used as __generic.
439 (getAddressSpace() == LangAS::opencl_generic &&
440 other.getAddressSpace() != LangAS::opencl_constant);
443 /// Determines if these qualifiers compatibly include another set.
444 /// Generally this answers the question of whether an object with the other
445 /// qualifiers can be safely used as an object with these qualifiers.
446 bool compatiblyIncludes(Qualifiers other) const {
447 return isAddressSpaceSupersetOf(other) &&
448 // ObjC GC qualifiers can match, be added, or be removed, but can't
450 (getObjCGCAttr() == other.getObjCGCAttr() || !hasObjCGCAttr() ||
451 !other.hasObjCGCAttr()) &&
452 // ObjC lifetime qualifiers must match exactly.
453 getObjCLifetime() == other.getObjCLifetime() &&
454 // CVR qualifiers may subset.
455 (((Mask & CVRMask) | (other.Mask & CVRMask)) == (Mask & CVRMask)) &&
456 // U qualifier may superset.
457 (!other.hasUnaligned() || hasUnaligned());
460 /// \brief Determines if these qualifiers compatibly include another set of
461 /// qualifiers from the narrow perspective of Objective-C ARC lifetime.
463 /// One set of Objective-C lifetime qualifiers compatibly includes the other
464 /// if the lifetime qualifiers match, or if both are non-__weak and the
465 /// including set also contains the 'const' qualifier, or both are non-__weak
466 /// and one is None (which can only happen in non-ARC modes).
467 bool compatiblyIncludesObjCLifetime(Qualifiers other) const {
468 if (getObjCLifetime() == other.getObjCLifetime())
471 if (getObjCLifetime() == OCL_Weak || other.getObjCLifetime() == OCL_Weak)
474 if (getObjCLifetime() == OCL_None || other.getObjCLifetime() == OCL_None)
480 /// \brief Determine whether this set of qualifiers is a strict superset of
481 /// another set of qualifiers, not considering qualifier compatibility.
482 bool isStrictSupersetOf(Qualifiers Other) const;
484 bool operator==(Qualifiers Other) const { return Mask == Other.Mask; }
485 bool operator!=(Qualifiers Other) const { return Mask != Other.Mask; }
487 explicit operator bool() const { return hasQualifiers(); }
489 Qualifiers &operator+=(Qualifiers R) {
494 // Union two qualifier sets. If an enumerated qualifier appears
495 // in both sets, use the one from the right.
496 friend Qualifiers operator+(Qualifiers L, Qualifiers R) {
501 Qualifiers &operator-=(Qualifiers R) {
506 /// \brief Compute the difference between two qualifier sets.
507 friend Qualifiers operator-(Qualifiers L, Qualifiers R) {
512 std::string getAsString() const;
513 std::string getAsString(const PrintingPolicy &Policy) const;
515 bool isEmptyWhenPrinted(const PrintingPolicy &Policy) const;
516 void print(raw_ostream &OS, const PrintingPolicy &Policy,
517 bool appendSpaceIfNonEmpty = false) const;
519 void Profile(llvm::FoldingSetNodeID &ID) const {
525 // bits: |0 1 2|3|4 .. 5|6 .. 8|9 ... 31|
526 // |C R V|U|GCAttr|Lifetime|AddressSpace|
529 static const uint32_t UMask = 0x8;
530 static const uint32_t UShift = 3;
531 static const uint32_t GCAttrMask = 0x30;
532 static const uint32_t GCAttrShift = 4;
533 static const uint32_t LifetimeMask = 0x1C0;
534 static const uint32_t LifetimeShift = 6;
535 static const uint32_t AddressSpaceMask =
536 ~(CVRMask | UMask | GCAttrMask | LifetimeMask);
537 static const uint32_t AddressSpaceShift = 9;
540 /// A std::pair-like structure for storing a qualified type split
541 /// into its local qualifiers and its locally-unqualified type.
542 struct SplitQualType {
543 /// The locally-unqualified type.
546 /// The local qualifiers.
549 SplitQualType() : Ty(nullptr), Quals() {}
550 SplitQualType(const Type *ty, Qualifiers qs) : Ty(ty), Quals(qs) {}
552 SplitQualType getSingleStepDesugaredType() const; // end of this file
554 // Make std::tie work.
555 std::pair<const Type *,Qualifiers> asPair() const {
556 return std::pair<const Type *, Qualifiers>(Ty, Quals);
559 friend bool operator==(SplitQualType a, SplitQualType b) {
560 return a.Ty == b.Ty && a.Quals == b.Quals;
562 friend bool operator!=(SplitQualType a, SplitQualType b) {
563 return a.Ty != b.Ty || a.Quals != b.Quals;
567 /// The kind of type we are substituting Objective-C type arguments into.
569 /// The kind of substitution affects the replacement of type parameters when
570 /// no concrete type information is provided, e.g., when dealing with an
571 /// unspecialized type.
572 enum class ObjCSubstitutionContext {
573 /// An ordinary type.
575 /// The result type of a method or function.
577 /// The parameter type of a method or function.
579 /// The type of a property.
581 /// The superclass of a type.
585 /// A (possibly-)qualified type.
587 /// For efficiency, we don't store CV-qualified types as nodes on their
588 /// own: instead each reference to a type stores the qualifiers. This
589 /// greatly reduces the number of nodes we need to allocate for types (for
590 /// example we only need one for 'int', 'const int', 'volatile int',
591 /// 'const volatile int', etc).
593 /// As an added efficiency bonus, instead of making this a pair, we
594 /// just store the two bits we care about in the low bits of the
595 /// pointer. To handle the packing/unpacking, we make QualType be a
596 /// simple wrapper class that acts like a smart pointer. A third bit
597 /// indicates whether there are extended qualifiers present, in which
598 /// case the pointer points to a special structure.
600 // Thankfully, these are efficiently composable.
601 llvm::PointerIntPair<llvm::PointerUnion<const Type*,const ExtQuals*>,
602 Qualifiers::FastWidth> Value;
604 const ExtQuals *getExtQualsUnsafe() const {
605 return Value.getPointer().get<const ExtQuals*>();
608 const Type *getTypePtrUnsafe() const {
609 return Value.getPointer().get<const Type*>();
612 const ExtQualsTypeCommonBase *getCommonPtr() const {
613 assert(!isNull() && "Cannot retrieve a NULL type pointer");
614 uintptr_t CommonPtrVal
615 = reinterpret_cast<uintptr_t>(Value.getOpaqueValue());
616 CommonPtrVal &= ~(uintptr_t)((1 << TypeAlignmentInBits) - 1);
617 return reinterpret_cast<ExtQualsTypeCommonBase*>(CommonPtrVal);
620 friend class QualifierCollector;
624 QualType(const Type *Ptr, unsigned Quals)
625 : Value(Ptr, Quals) {}
626 QualType(const ExtQuals *Ptr, unsigned Quals)
627 : Value(Ptr, Quals) {}
629 unsigned getLocalFastQualifiers() const { return Value.getInt(); }
630 void setLocalFastQualifiers(unsigned Quals) { Value.setInt(Quals); }
632 /// Retrieves a pointer to the underlying (unqualified) type.
634 /// This function requires that the type not be NULL. If the type might be
635 /// NULL, use the (slightly less efficient) \c getTypePtrOrNull().
636 const Type *getTypePtr() const;
638 const Type *getTypePtrOrNull() const;
640 /// Retrieves a pointer to the name of the base type.
641 const IdentifierInfo *getBaseTypeIdentifier() const;
643 /// Divides a QualType into its unqualified type and a set of local
645 SplitQualType split() const;
647 void *getAsOpaquePtr() const { return Value.getOpaqueValue(); }
648 static QualType getFromOpaquePtr(const void *Ptr) {
650 T.Value.setFromOpaqueValue(const_cast<void*>(Ptr));
654 const Type &operator*() const {
655 return *getTypePtr();
658 const Type *operator->() const {
662 bool isCanonical() const;
663 bool isCanonicalAsParam() const;
665 /// Return true if this QualType doesn't point to a type yet.
666 bool isNull() const {
667 return Value.getPointer().isNull();
670 /// \brief Determine whether this particular QualType instance has the
671 /// "const" qualifier set, without looking through typedefs that may have
672 /// added "const" at a different level.
673 bool isLocalConstQualified() const {
674 return (getLocalFastQualifiers() & Qualifiers::Const);
677 /// \brief Determine whether this type is const-qualified.
678 bool isConstQualified() const;
680 /// \brief Determine whether this particular QualType instance has the
681 /// "restrict" qualifier set, without looking through typedefs that may have
682 /// added "restrict" at a different level.
683 bool isLocalRestrictQualified() const {
684 return (getLocalFastQualifiers() & Qualifiers::Restrict);
687 /// \brief Determine whether this type is restrict-qualified.
688 bool isRestrictQualified() const;
690 /// \brief Determine whether this particular QualType instance has the
691 /// "volatile" qualifier set, without looking through typedefs that may have
692 /// added "volatile" at a different level.
693 bool isLocalVolatileQualified() const {
694 return (getLocalFastQualifiers() & Qualifiers::Volatile);
697 /// \brief Determine whether this type is volatile-qualified.
698 bool isVolatileQualified() const;
700 /// \brief Determine whether this particular QualType instance has any
701 /// qualifiers, without looking through any typedefs that might add
702 /// qualifiers at a different level.
703 bool hasLocalQualifiers() const {
704 return getLocalFastQualifiers() || hasLocalNonFastQualifiers();
707 /// \brief Determine whether this type has any qualifiers.
708 bool hasQualifiers() const;
710 /// \brief Determine whether this particular QualType instance has any
711 /// "non-fast" qualifiers, e.g., those that are stored in an ExtQualType
713 bool hasLocalNonFastQualifiers() const {
714 return Value.getPointer().is<const ExtQuals*>();
717 /// \brief Retrieve the set of qualifiers local to this particular QualType
718 /// instance, not including any qualifiers acquired through typedefs or
720 Qualifiers getLocalQualifiers() const;
722 /// \brief Retrieve the set of qualifiers applied to this type.
723 Qualifiers getQualifiers() const;
725 /// \brief Retrieve the set of CVR (const-volatile-restrict) qualifiers
726 /// local to this particular QualType instance, not including any qualifiers
727 /// acquired through typedefs or other sugar.
728 unsigned getLocalCVRQualifiers() const {
729 return getLocalFastQualifiers();
732 /// \brief Retrieve the set of CVR (const-volatile-restrict) qualifiers
733 /// applied to this type.
734 unsigned getCVRQualifiers() const;
736 bool isConstant(const ASTContext& Ctx) const {
737 return QualType::isConstant(*this, Ctx);
740 /// \brief Determine whether this is a Plain Old Data (POD) type (C++ 3.9p10).
741 bool isPODType(const ASTContext &Context) const;
743 /// Return true if this is a POD type according to the rules of the C++98
744 /// standard, regardless of the current compilation's language.
745 bool isCXX98PODType(const ASTContext &Context) const;
747 /// Return true if this is a POD type according to the more relaxed rules
748 /// of the C++11 standard, regardless of the current compilation's language.
749 /// (C++0x [basic.types]p9)
750 bool isCXX11PODType(const ASTContext &Context) const;
752 /// Return true if this is a trivial type per (C++0x [basic.types]p9)
753 bool isTrivialType(const ASTContext &Context) const;
755 /// Return true if this is a trivially copyable type (C++0x [basic.types]p9)
756 bool isTriviallyCopyableType(const ASTContext &Context) const;
758 // Don't promise in the API that anything besides 'const' can be
761 /// Add the `const` type qualifier to this QualType.
763 addFastQualifiers(Qualifiers::Const);
765 QualType withConst() const {
766 return withFastQualifiers(Qualifiers::Const);
769 /// Add the `volatile` type qualifier to this QualType.
771 addFastQualifiers(Qualifiers::Volatile);
773 QualType withVolatile() const {
774 return withFastQualifiers(Qualifiers::Volatile);
777 /// Add the `restrict` qualifier to this QualType.
779 addFastQualifiers(Qualifiers::Restrict);
781 QualType withRestrict() const {
782 return withFastQualifiers(Qualifiers::Restrict);
785 QualType withCVRQualifiers(unsigned CVR) const {
786 return withFastQualifiers(CVR);
789 void addFastQualifiers(unsigned TQs) {
790 assert(!(TQs & ~Qualifiers::FastMask)
791 && "non-fast qualifier bits set in mask!");
792 Value.setInt(Value.getInt() | TQs);
795 void removeLocalConst();
796 void removeLocalVolatile();
797 void removeLocalRestrict();
798 void removeLocalCVRQualifiers(unsigned Mask);
800 void removeLocalFastQualifiers() { Value.setInt(0); }
801 void removeLocalFastQualifiers(unsigned Mask) {
802 assert(!(Mask & ~Qualifiers::FastMask) && "mask has non-fast qualifiers");
803 Value.setInt(Value.getInt() & ~Mask);
806 // Creates a type with the given qualifiers in addition to any
807 // qualifiers already on this type.
808 QualType withFastQualifiers(unsigned TQs) const {
810 T.addFastQualifiers(TQs);
814 // Creates a type with exactly the given fast qualifiers, removing
815 // any existing fast qualifiers.
816 QualType withExactLocalFastQualifiers(unsigned TQs) const {
817 return withoutLocalFastQualifiers().withFastQualifiers(TQs);
820 // Removes fast qualifiers, but leaves any extended qualifiers in place.
821 QualType withoutLocalFastQualifiers() const {
823 T.removeLocalFastQualifiers();
827 QualType getCanonicalType() const;
829 /// \brief Return this type with all of the instance-specific qualifiers
830 /// removed, but without removing any qualifiers that may have been applied
831 /// through typedefs.
832 QualType getLocalUnqualifiedType() const { return QualType(getTypePtr(), 0); }
834 /// \brief Retrieve the unqualified variant of the given type,
835 /// removing as little sugar as possible.
837 /// This routine looks through various kinds of sugar to find the
838 /// least-desugared type that is unqualified. For example, given:
841 /// typedef int Integer;
842 /// typedef const Integer CInteger;
843 /// typedef CInteger DifferenceType;
846 /// Executing \c getUnqualifiedType() on the type \c DifferenceType will
847 /// desugar until we hit the type \c Integer, which has no qualifiers on it.
849 /// The resulting type might still be qualified if it's sugar for an array
850 /// type. To strip qualifiers even from within a sugared array type, use
851 /// ASTContext::getUnqualifiedArrayType.
852 inline QualType getUnqualifiedType() const;
854 /// Retrieve the unqualified variant of the given type, removing as little
855 /// sugar as possible.
857 /// Like getUnqualifiedType(), but also returns the set of
858 /// qualifiers that were built up.
860 /// The resulting type might still be qualified if it's sugar for an array
861 /// type. To strip qualifiers even from within a sugared array type, use
862 /// ASTContext::getUnqualifiedArrayType.
863 inline SplitQualType getSplitUnqualifiedType() const;
865 /// \brief Determine whether this type is more qualified than the other
866 /// given type, requiring exact equality for non-CVR qualifiers.
867 bool isMoreQualifiedThan(QualType Other) const;
869 /// \brief Determine whether this type is at least as qualified as the other
870 /// given type, requiring exact equality for non-CVR qualifiers.
871 bool isAtLeastAsQualifiedAs(QualType Other) const;
873 QualType getNonReferenceType() const;
875 /// \brief Determine the type of a (typically non-lvalue) expression with the
876 /// specified result type.
878 /// This routine should be used for expressions for which the return type is
879 /// explicitly specified (e.g., in a cast or call) and isn't necessarily
880 /// an lvalue. It removes a top-level reference (since there are no
881 /// expressions of reference type) and deletes top-level cvr-qualifiers
882 /// from non-class types (in C++) or all types (in C).
883 QualType getNonLValueExprType(const ASTContext &Context) const;
885 /// Return the specified type with any "sugar" removed from
886 /// the type. This takes off typedefs, typeof's etc. If the outer level of
887 /// the type is already concrete, it returns it unmodified. This is similar
888 /// to getting the canonical type, but it doesn't remove *all* typedefs. For
889 /// example, it returns "T*" as "T*", (not as "int*"), because the pointer is
892 /// Qualifiers are left in place.
893 QualType getDesugaredType(const ASTContext &Context) const {
894 return getDesugaredType(*this, Context);
897 SplitQualType getSplitDesugaredType() const {
898 return getSplitDesugaredType(*this);
901 /// \brief Return the specified type with one level of "sugar" removed from
904 /// This routine takes off the first typedef, typeof, etc. If the outer level
905 /// of the type is already concrete, it returns it unmodified.
906 QualType getSingleStepDesugaredType(const ASTContext &Context) const {
907 return getSingleStepDesugaredTypeImpl(*this, Context);
910 /// Returns the specified type after dropping any
911 /// outer-level parentheses.
912 QualType IgnoreParens() const {
913 if (isa<ParenType>(*this))
914 return QualType::IgnoreParens(*this);
918 /// Indicate whether the specified types and qualifiers are identical.
919 friend bool operator==(const QualType &LHS, const QualType &RHS) {
920 return LHS.Value == RHS.Value;
922 friend bool operator!=(const QualType &LHS, const QualType &RHS) {
923 return LHS.Value != RHS.Value;
925 std::string getAsString() const {
926 return getAsString(split());
928 static std::string getAsString(SplitQualType split) {
929 return getAsString(split.Ty, split.Quals);
931 static std::string getAsString(const Type *ty, Qualifiers qs);
933 std::string getAsString(const PrintingPolicy &Policy) const;
935 void print(raw_ostream &OS, const PrintingPolicy &Policy,
936 const Twine &PlaceHolder = Twine(),
937 unsigned Indentation = 0) const {
938 print(split(), OS, Policy, PlaceHolder, Indentation);
940 static void print(SplitQualType split, raw_ostream &OS,
941 const PrintingPolicy &policy, const Twine &PlaceHolder,
942 unsigned Indentation = 0) {
943 return print(split.Ty, split.Quals, OS, policy, PlaceHolder, Indentation);
945 static void print(const Type *ty, Qualifiers qs,
946 raw_ostream &OS, const PrintingPolicy &policy,
947 const Twine &PlaceHolder,
948 unsigned Indentation = 0);
950 void getAsStringInternal(std::string &Str,
951 const PrintingPolicy &Policy) const {
952 return getAsStringInternal(split(), Str, Policy);
954 static void getAsStringInternal(SplitQualType split, std::string &out,
955 const PrintingPolicy &policy) {
956 return getAsStringInternal(split.Ty, split.Quals, out, policy);
958 static void getAsStringInternal(const Type *ty, Qualifiers qs,
960 const PrintingPolicy &policy);
962 class StreamedQualTypeHelper {
964 const PrintingPolicy &Policy;
965 const Twine &PlaceHolder;
966 unsigned Indentation;
968 StreamedQualTypeHelper(const QualType &T, const PrintingPolicy &Policy,
969 const Twine &PlaceHolder, unsigned Indentation)
970 : T(T), Policy(Policy), PlaceHolder(PlaceHolder),
971 Indentation(Indentation) { }
973 friend raw_ostream &operator<<(raw_ostream &OS,
974 const StreamedQualTypeHelper &SQT) {
975 SQT.T.print(OS, SQT.Policy, SQT.PlaceHolder, SQT.Indentation);
980 StreamedQualTypeHelper stream(const PrintingPolicy &Policy,
981 const Twine &PlaceHolder = Twine(),
982 unsigned Indentation = 0) const {
983 return StreamedQualTypeHelper(*this, Policy, PlaceHolder, Indentation);
986 void dump(const char *s) const;
988 void dump(llvm::raw_ostream &OS) const;
990 void Profile(llvm::FoldingSetNodeID &ID) const {
991 ID.AddPointer(getAsOpaquePtr());
994 /// Return the address space of this type.
995 inline unsigned getAddressSpace() const;
997 /// Returns gc attribute of this type.
998 inline Qualifiers::GC getObjCGCAttr() const;
1000 /// true when Type is objc's weak.
1001 bool isObjCGCWeak() const {
1002 return getObjCGCAttr() == Qualifiers::Weak;
1005 /// true when Type is objc's strong.
1006 bool isObjCGCStrong() const {
1007 return getObjCGCAttr() == Qualifiers::Strong;
1010 /// Returns lifetime attribute of this type.
1011 Qualifiers::ObjCLifetime getObjCLifetime() const {
1012 return getQualifiers().getObjCLifetime();
1015 bool hasNonTrivialObjCLifetime() const {
1016 return getQualifiers().hasNonTrivialObjCLifetime();
1019 bool hasStrongOrWeakObjCLifetime() const {
1020 return getQualifiers().hasStrongOrWeakObjCLifetime();
1023 enum DestructionKind {
1026 DK_objc_strong_lifetime,
1027 DK_objc_weak_lifetime
1030 /// Returns a nonzero value if objects of this type require
1031 /// non-trivial work to clean up after. Non-zero because it's
1032 /// conceivable that qualifiers (objc_gc(weak)?) could make
1033 /// something require destruction.
1034 DestructionKind isDestructedType() const {
1035 return isDestructedTypeImpl(*this);
1038 /// Determine whether expressions of the given type are forbidden
1039 /// from being lvalues in C.
1041 /// The expression types that are forbidden to be lvalues are:
1042 /// - 'void', but not qualified void
1043 /// - function types
1045 /// The exact rule here is C99 6.3.2.1:
1046 /// An lvalue is an expression with an object type or an incomplete
1047 /// type other than void.
1048 bool isCForbiddenLValueType() const;
1050 /// Substitute type arguments for the Objective-C type parameters used in the
1053 /// \param ctx ASTContext in which the type exists.
1055 /// \param typeArgs The type arguments that will be substituted for the
1056 /// Objective-C type parameters in the subject type, which are generally
1057 /// computed via \c Type::getObjCSubstitutions. If empty, the type
1058 /// parameters will be replaced with their bounds or id/Class, as appropriate
1059 /// for the context.
1061 /// \param context The context in which the subject type was written.
1063 /// \returns the resulting type.
1064 QualType substObjCTypeArgs(ASTContext &ctx,
1065 ArrayRef<QualType> typeArgs,
1066 ObjCSubstitutionContext context) const;
1068 /// Substitute type arguments from an object type for the Objective-C type
1069 /// parameters used in the subject type.
1071 /// This operation combines the computation of type arguments for
1072 /// substitution (\c Type::getObjCSubstitutions) with the actual process of
1073 /// substitution (\c QualType::substObjCTypeArgs) for the convenience of
1074 /// callers that need to perform a single substitution in isolation.
1076 /// \param objectType The type of the object whose member type we're
1077 /// substituting into. For example, this might be the receiver of a message
1078 /// or the base of a property access.
1080 /// \param dc The declaration context from which the subject type was
1081 /// retrieved, which indicates (for example) which type parameters should
1084 /// \param context The context in which the subject type was written.
1086 /// \returns the subject type after replacing all of the Objective-C type
1087 /// parameters with their corresponding arguments.
1088 QualType substObjCMemberType(QualType objectType,
1089 const DeclContext *dc,
1090 ObjCSubstitutionContext context) const;
1092 /// Strip Objective-C "__kindof" types from the given type.
1093 QualType stripObjCKindOfType(const ASTContext &ctx) const;
1095 /// Remove all qualifiers including _Atomic.
1096 QualType getAtomicUnqualifiedType() const;
1099 // These methods are implemented in a separate translation unit;
1100 // "static"-ize them to avoid creating temporary QualTypes in the
1102 static bool isConstant(QualType T, const ASTContext& Ctx);
1103 static QualType getDesugaredType(QualType T, const ASTContext &Context);
1104 static SplitQualType getSplitDesugaredType(QualType T);
1105 static SplitQualType getSplitUnqualifiedTypeImpl(QualType type);
1106 static QualType getSingleStepDesugaredTypeImpl(QualType type,
1107 const ASTContext &C);
1108 static QualType IgnoreParens(QualType T);
1109 static DestructionKind isDestructedTypeImpl(QualType type);
1115 /// Implement simplify_type for QualType, so that we can dyn_cast from QualType
1116 /// to a specific Type class.
1117 template<> struct simplify_type< ::clang::QualType> {
1118 typedef const ::clang::Type *SimpleType;
1119 static SimpleType getSimplifiedValue(::clang::QualType Val) {
1120 return Val.getTypePtr();
1124 // Teach SmallPtrSet that QualType is "basically a pointer".
1126 class PointerLikeTypeTraits<clang::QualType> {
1128 static inline void *getAsVoidPointer(clang::QualType P) {
1129 return P.getAsOpaquePtr();
1131 static inline clang::QualType getFromVoidPointer(void *P) {
1132 return clang::QualType::getFromOpaquePtr(P);
1134 // Various qualifiers go in low bits.
1135 enum { NumLowBitsAvailable = 0 };
1138 } // end namespace llvm
1142 /// \brief Base class that is common to both the \c ExtQuals and \c Type
1143 /// classes, which allows \c QualType to access the common fields between the
1146 class ExtQualsTypeCommonBase {
1147 ExtQualsTypeCommonBase(const Type *baseType, QualType canon)
1148 : BaseType(baseType), CanonicalType(canon) {}
1150 /// \brief The "base" type of an extended qualifiers type (\c ExtQuals) or
1151 /// a self-referential pointer (for \c Type).
1153 /// This pointer allows an efficient mapping from a QualType to its
1154 /// underlying type pointer.
1155 const Type *const BaseType;
1157 /// \brief The canonical type of this type. A QualType.
1158 QualType CanonicalType;
1160 friend class QualType;
1162 friend class ExtQuals;
1165 /// We can encode up to four bits in the low bits of a
1166 /// type pointer, but there are many more type qualifiers that we want
1167 /// to be able to apply to an arbitrary type. Therefore we have this
1168 /// struct, intended to be heap-allocated and used by QualType to
1169 /// store qualifiers.
1171 /// The current design tags the 'const', 'restrict', and 'volatile' qualifiers
1172 /// in three low bits on the QualType pointer; a fourth bit records whether
1173 /// the pointer is an ExtQuals node. The extended qualifiers (address spaces,
1174 /// Objective-C GC attributes) are much more rare.
1175 class ExtQuals : public ExtQualsTypeCommonBase, public llvm::FoldingSetNode {
1176 // NOTE: changing the fast qualifiers should be straightforward as
1177 // long as you don't make 'const' non-fast.
1179 // a) Modify the bitmasks (Qualifiers::TQ and DeclSpec::TQ).
1180 // Fast qualifiers must occupy the low-order bits.
1181 // b) Update Qualifiers::FastWidth and FastMask.
1183 // a) Update is{Volatile,Restrict}Qualified(), defined inline.
1184 // b) Update remove{Volatile,Restrict}, defined near the end of
1187 // a) Update get{Volatile,Restrict}Type.
1189 /// The immutable set of qualifiers applied by this node. Always contains
1190 /// extended qualifiers.
1193 ExtQuals *this_() { return this; }
1196 ExtQuals(const Type *baseType, QualType canon, Qualifiers quals)
1197 : ExtQualsTypeCommonBase(baseType,
1198 canon.isNull() ? QualType(this_(), 0) : canon),
1201 assert(Quals.hasNonFastQualifiers()
1202 && "ExtQuals created with no fast qualifiers");
1203 assert(!Quals.hasFastQualifiers()
1204 && "ExtQuals created with fast qualifiers");
1207 Qualifiers getQualifiers() const { return Quals; }
1209 bool hasObjCGCAttr() const { return Quals.hasObjCGCAttr(); }
1210 Qualifiers::GC getObjCGCAttr() const { return Quals.getObjCGCAttr(); }
1212 bool hasObjCLifetime() const { return Quals.hasObjCLifetime(); }
1213 Qualifiers::ObjCLifetime getObjCLifetime() const {
1214 return Quals.getObjCLifetime();
1217 bool hasAddressSpace() const { return Quals.hasAddressSpace(); }
1218 unsigned getAddressSpace() const { return Quals.getAddressSpace(); }
1220 const Type *getBaseType() const { return BaseType; }
1223 void Profile(llvm::FoldingSetNodeID &ID) const {
1224 Profile(ID, getBaseType(), Quals);
1226 static void Profile(llvm::FoldingSetNodeID &ID,
1227 const Type *BaseType,
1229 assert(!Quals.hasFastQualifiers() && "fast qualifiers in ExtQuals hash!");
1230 ID.AddPointer(BaseType);
1235 /// The kind of C++11 ref-qualifier associated with a function type.
1236 /// This determines whether a member function's "this" object can be an
1237 /// lvalue, rvalue, or neither.
1238 enum RefQualifierKind {
1239 /// \brief No ref-qualifier was provided.
1241 /// \brief An lvalue ref-qualifier was provided (\c &).
1243 /// \brief An rvalue ref-qualifier was provided (\c &&).
1247 /// Which keyword(s) were used to create an AutoType.
1248 enum class AutoTypeKeyword {
1251 /// \brief decltype(auto)
1253 /// \brief __auto_type (GNU extension)
1257 /// The base class of the type hierarchy.
1259 /// A central concept with types is that each type always has a canonical
1260 /// type. A canonical type is the type with any typedef names stripped out
1261 /// of it or the types it references. For example, consider:
1263 /// typedef int foo;
1264 /// typedef foo* bar;
1265 /// 'int *' 'foo *' 'bar'
1267 /// There will be a Type object created for 'int'. Since int is canonical, its
1268 /// CanonicalType pointer points to itself. There is also a Type for 'foo' (a
1269 /// TypedefType). Its CanonicalType pointer points to the 'int' Type. Next
1270 /// there is a PointerType that represents 'int*', which, like 'int', is
1271 /// canonical. Finally, there is a PointerType type for 'foo*' whose canonical
1272 /// type is 'int*', and there is a TypedefType for 'bar', whose canonical type
1275 /// Non-canonical types are useful for emitting diagnostics, without losing
1276 /// information about typedefs being used. Canonical types are useful for type
1277 /// comparisons (they allow by-pointer equality tests) and useful for reasoning
1278 /// about whether something has a particular form (e.g. is a function type),
1279 /// because they implicitly, recursively, strip all typedefs out of a type.
1281 /// Types, once created, are immutable.
1283 class Type : public ExtQualsTypeCommonBase {
1286 #define TYPE(Class, Base) Class,
1287 #define LAST_TYPE(Class) TypeLast = Class,
1288 #define ABSTRACT_TYPE(Class, Base)
1289 #include "clang/AST/TypeNodes.def"
1290 TagFirst = Record, TagLast = Enum
1294 Type(const Type &) = delete;
1295 void operator=(const Type &) = delete;
1297 /// Bitfields required by the Type class.
1298 class TypeBitfields {
1300 template <class T> friend class TypePropertyCache;
1302 /// TypeClass bitfield - Enum that specifies what subclass this belongs to.
1305 /// Whether this type is a dependent type (C++ [temp.dep.type]).
1306 unsigned Dependent : 1;
1308 /// Whether this type somehow involves a template parameter, even
1309 /// if the resolution of the type does not depend on a template parameter.
1310 unsigned InstantiationDependent : 1;
1312 /// Whether this type is a variably-modified type (C99 6.7.5).
1313 unsigned VariablyModified : 1;
1315 /// \brief Whether this type contains an unexpanded parameter pack
1316 /// (for C++11 variadic templates).
1317 unsigned ContainsUnexpandedParameterPack : 1;
1319 /// \brief True if the cache (i.e. the bitfields here starting with
1320 /// 'Cache') is valid.
1321 mutable unsigned CacheValid : 1;
1323 /// \brief Linkage of this type.
1324 mutable unsigned CachedLinkage : 3;
1326 /// \brief Whether this type involves and local or unnamed types.
1327 mutable unsigned CachedLocalOrUnnamed : 1;
1329 /// \brief Whether this type comes from an AST file.
1330 mutable unsigned FromAST : 1;
1332 bool isCacheValid() const {
1335 Linkage getLinkage() const {
1336 assert(isCacheValid() && "getting linkage from invalid cache");
1337 return static_cast<Linkage>(CachedLinkage);
1339 bool hasLocalOrUnnamedType() const {
1340 assert(isCacheValid() && "getting linkage from invalid cache");
1341 return CachedLocalOrUnnamed;
1344 enum { NumTypeBits = 18 };
1347 // These classes allow subclasses to somewhat cleanly pack bitfields
1350 class ArrayTypeBitfields {
1351 friend class ArrayType;
1353 unsigned : NumTypeBits;
1355 /// CVR qualifiers from declarations like
1356 /// 'int X[static restrict 4]'. For function parameters only.
1357 unsigned IndexTypeQuals : 3;
1359 /// Storage class qualifiers from declarations like
1360 /// 'int X[static restrict 4]'. For function parameters only.
1361 /// Actually an ArrayType::ArraySizeModifier.
1362 unsigned SizeModifier : 3;
1365 class BuiltinTypeBitfields {
1366 friend class BuiltinType;
1368 unsigned : NumTypeBits;
1370 /// The kind (BuiltinType::Kind) of builtin type this is.
1374 class FunctionTypeBitfields {
1375 friend class FunctionType;
1376 friend class FunctionProtoType;
1378 unsigned : NumTypeBits;
1380 /// Extra information which affects how the function is called, like
1381 /// regparm and the calling convention.
1382 unsigned ExtInfo : 10;
1384 /// Used only by FunctionProtoType, put here to pack with the
1385 /// other bitfields.
1386 /// The qualifiers are part of FunctionProtoType because...
1388 /// C++ 8.3.5p4: The return type, the parameter type list and the
1389 /// cv-qualifier-seq, [...], are part of the function type.
1390 unsigned TypeQuals : 4;
1392 /// \brief The ref-qualifier associated with a \c FunctionProtoType.
1394 /// This is a value of type \c RefQualifierKind.
1395 unsigned RefQualifier : 2;
1398 class ObjCObjectTypeBitfields {
1399 friend class ObjCObjectType;
1401 unsigned : NumTypeBits;
1403 /// The number of type arguments stored directly on this object type.
1404 unsigned NumTypeArgs : 7;
1406 /// The number of protocols stored directly on this object type.
1407 unsigned NumProtocols : 6;
1409 /// Whether this is a "kindof" type.
1410 unsigned IsKindOf : 1;
1412 static_assert(NumTypeBits + 7 + 6 + 1 <= 32, "Does not fit in an unsigned");
1414 class ReferenceTypeBitfields {
1415 friend class ReferenceType;
1417 unsigned : NumTypeBits;
1419 /// True if the type was originally spelled with an lvalue sigil.
1420 /// This is never true of rvalue references but can also be false
1421 /// on lvalue references because of C++0x [dcl.typedef]p9,
1424 /// typedef int &ref; // lvalue, spelled lvalue
1425 /// typedef int &&rvref; // rvalue
1426 /// ref &a; // lvalue, inner ref, spelled lvalue
1427 /// ref &&a; // lvalue, inner ref
1428 /// rvref &a; // lvalue, inner ref, spelled lvalue
1429 /// rvref &&a; // rvalue, inner ref
1430 unsigned SpelledAsLValue : 1;
1432 /// True if the inner type is a reference type. This only happens
1433 /// in non-canonical forms.
1434 unsigned InnerRef : 1;
1437 class TypeWithKeywordBitfields {
1438 friend class TypeWithKeyword;
1440 unsigned : NumTypeBits;
1442 /// An ElaboratedTypeKeyword. 8 bits for efficient access.
1443 unsigned Keyword : 8;
1446 class VectorTypeBitfields {
1447 friend class VectorType;
1449 unsigned : NumTypeBits;
1451 /// The kind of vector, either a generic vector type or some
1452 /// target-specific vector type such as for AltiVec or Neon.
1453 unsigned VecKind : 3;
1455 /// The number of elements in the vector.
1456 unsigned NumElements : 29 - NumTypeBits;
1458 enum { MaxNumElements = (1 << (29 - NumTypeBits)) - 1 };
1461 class AttributedTypeBitfields {
1462 friend class AttributedType;
1464 unsigned : NumTypeBits;
1466 /// An AttributedType::Kind
1467 unsigned AttrKind : 32 - NumTypeBits;
1470 class AutoTypeBitfields {
1471 friend class AutoType;
1473 unsigned : NumTypeBits;
1475 /// Was this placeholder type spelled as 'auto', 'decltype(auto)',
1476 /// or '__auto_type'? AutoTypeKeyword value.
1477 unsigned Keyword : 2;
1481 TypeBitfields TypeBits;
1482 ArrayTypeBitfields ArrayTypeBits;
1483 AttributedTypeBitfields AttributedTypeBits;
1484 AutoTypeBitfields AutoTypeBits;
1485 BuiltinTypeBitfields BuiltinTypeBits;
1486 FunctionTypeBitfields FunctionTypeBits;
1487 ObjCObjectTypeBitfields ObjCObjectTypeBits;
1488 ReferenceTypeBitfields ReferenceTypeBits;
1489 TypeWithKeywordBitfields TypeWithKeywordBits;
1490 VectorTypeBitfields VectorTypeBits;
1494 /// \brief Set whether this type comes from an AST file.
1495 void setFromAST(bool V = true) const {
1496 TypeBits.FromAST = V;
1499 template <class T> friend class TypePropertyCache;
1502 // silence VC++ warning C4355: 'this' : used in base member initializer list
1503 Type *this_() { return this; }
1504 Type(TypeClass tc, QualType canon, bool Dependent,
1505 bool InstantiationDependent, bool VariablyModified,
1506 bool ContainsUnexpandedParameterPack)
1507 : ExtQualsTypeCommonBase(this,
1508 canon.isNull() ? QualType(this_(), 0) : canon) {
1510 TypeBits.Dependent = Dependent;
1511 TypeBits.InstantiationDependent = Dependent || InstantiationDependent;
1512 TypeBits.VariablyModified = VariablyModified;
1513 TypeBits.ContainsUnexpandedParameterPack = ContainsUnexpandedParameterPack;
1514 TypeBits.CacheValid = false;
1515 TypeBits.CachedLocalOrUnnamed = false;
1516 TypeBits.CachedLinkage = NoLinkage;
1517 TypeBits.FromAST = false;
1519 friend class ASTContext;
1521 void setDependent(bool D = true) {
1522 TypeBits.Dependent = D;
1524 TypeBits.InstantiationDependent = true;
1526 void setInstantiationDependent(bool D = true) {
1527 TypeBits.InstantiationDependent = D; }
1528 void setVariablyModified(bool VM = true) { TypeBits.VariablyModified = VM;
1530 void setContainsUnexpandedParameterPack(bool PP = true) {
1531 TypeBits.ContainsUnexpandedParameterPack = PP;
1535 TypeClass getTypeClass() const { return static_cast<TypeClass>(TypeBits.TC); }
1537 /// \brief Whether this type comes from an AST file.
1538 bool isFromAST() const { return TypeBits.FromAST; }
1540 /// \brief Whether this type is or contains an unexpanded parameter
1541 /// pack, used to support C++0x variadic templates.
1543 /// A type that contains a parameter pack shall be expanded by the
1544 /// ellipsis operator at some point. For example, the typedef in the
1545 /// following example contains an unexpanded parameter pack 'T':
1548 /// template<typename ...T>
1550 /// typedef T* pointer_types; // ill-formed; T is a parameter pack.
1554 /// Note that this routine does not specify which
1555 bool containsUnexpandedParameterPack() const {
1556 return TypeBits.ContainsUnexpandedParameterPack;
1559 /// Determines if this type would be canonical if it had no further
1561 bool isCanonicalUnqualified() const {
1562 return CanonicalType == QualType(this, 0);
1565 /// Pull a single level of sugar off of this locally-unqualified type.
1566 /// Users should generally prefer SplitQualType::getSingleStepDesugaredType()
1567 /// or QualType::getSingleStepDesugaredType(const ASTContext&).
1568 QualType getLocallyUnqualifiedSingleStepDesugaredType() const;
1570 /// Types are partitioned into 3 broad categories (C99 6.2.5p1):
1571 /// object types, function types, and incomplete types.
1573 /// Return true if this is an incomplete type.
1574 /// A type that can describe objects, but which lacks information needed to
1575 /// determine its size (e.g. void, or a fwd declared struct). Clients of this
1576 /// routine will need to determine if the size is actually required.
1578 /// \brief Def If non-null, and the type refers to some kind of declaration
1579 /// that can be completed (such as a C struct, C++ class, or Objective-C
1580 /// class), will be set to the declaration.
1581 bool isIncompleteType(NamedDecl **Def = nullptr) const;
1583 /// Return true if this is an incomplete or object
1584 /// type, in other words, not a function type.
1585 bool isIncompleteOrObjectType() const {
1586 return !isFunctionType();
1589 /// \brief Determine whether this type is an object type.
1590 bool isObjectType() const {
1591 // C++ [basic.types]p8:
1592 // An object type is a (possibly cv-qualified) type that is not a
1593 // function type, not a reference type, and not a void type.
1594 return !isReferenceType() && !isFunctionType() && !isVoidType();
1597 /// Return true if this is a literal type
1598 /// (C++11 [basic.types]p10)
1599 bool isLiteralType(const ASTContext &Ctx) const;
1601 /// Test if this type is a standard-layout type.
1602 /// (C++0x [basic.type]p9)
1603 bool isStandardLayoutType() const;
1605 /// Helper methods to distinguish type categories. All type predicates
1606 /// operate on the canonical type, ignoring typedefs and qualifiers.
1608 /// Returns true if the type is a builtin type.
1609 bool isBuiltinType() const;
1611 /// Test for a particular builtin type.
1612 bool isSpecificBuiltinType(unsigned K) const;
1614 /// Test for a type which does not represent an actual type-system type but
1615 /// is instead used as a placeholder for various convenient purposes within
1616 /// Clang. All such types are BuiltinTypes.
1617 bool isPlaceholderType() const;
1618 const BuiltinType *getAsPlaceholderType() const;
1620 /// Test for a specific placeholder type.
1621 bool isSpecificPlaceholderType(unsigned K) const;
1623 /// Test for a placeholder type other than Overload; see
1624 /// BuiltinType::isNonOverloadPlaceholderType.
1625 bool isNonOverloadPlaceholderType() const;
1627 /// isIntegerType() does *not* include complex integers (a GCC extension).
1628 /// isComplexIntegerType() can be used to test for complex integers.
1629 bool isIntegerType() const; // C99 6.2.5p17 (int, char, bool, enum)
1630 bool isEnumeralType() const;
1631 bool isBooleanType() const;
1632 bool isCharType() const;
1633 bool isWideCharType() const;
1634 bool isChar16Type() const;
1635 bool isChar32Type() const;
1636 bool isAnyCharacterType() const;
1637 bool isIntegralType(const ASTContext &Ctx) const;
1639 /// Determine whether this type is an integral or enumeration type.
1640 bool isIntegralOrEnumerationType() const;
1641 /// Determine whether this type is an integral or unscoped enumeration type.
1642 bool isIntegralOrUnscopedEnumerationType() const;
1644 /// Floating point categories.
1645 bool isRealFloatingType() const; // C99 6.2.5p10 (float, double, long double)
1646 /// isComplexType() does *not* include complex integers (a GCC extension).
1647 /// isComplexIntegerType() can be used to test for complex integers.
1648 bool isComplexType() const; // C99 6.2.5p11 (complex)
1649 bool isAnyComplexType() const; // C99 6.2.5p11 (complex) + Complex Int.
1650 bool isFloatingType() const; // C99 6.2.5p11 (real floating + complex)
1651 bool isHalfType() const; // OpenCL 6.1.1.1, NEON (IEEE 754-2008 half)
1652 bool isRealType() const; // C99 6.2.5p17 (real floating + integer)
1653 bool isArithmeticType() const; // C99 6.2.5p18 (integer + floating)
1654 bool isVoidType() const; // C99 6.2.5p19
1655 bool isScalarType() const; // C99 6.2.5p21 (arithmetic + pointers)
1656 bool isAggregateType() const;
1657 bool isFundamentalType() const;
1658 bool isCompoundType() const;
1660 // Type Predicates: Check to see if this type is structurally the specified
1661 // type, ignoring typedefs and qualifiers.
1662 bool isFunctionType() const;
1663 bool isFunctionNoProtoType() const { return getAs<FunctionNoProtoType>(); }
1664 bool isFunctionProtoType() const { return getAs<FunctionProtoType>(); }
1665 bool isPointerType() const;
1666 bool isAnyPointerType() const; // Any C pointer or ObjC object pointer
1667 bool isBlockPointerType() const;
1668 bool isVoidPointerType() const;
1669 bool isReferenceType() const;
1670 bool isLValueReferenceType() const;
1671 bool isRValueReferenceType() const;
1672 bool isFunctionPointerType() const;
1673 bool isMemberPointerType() const;
1674 bool isMemberFunctionPointerType() const;
1675 bool isMemberDataPointerType() const;
1676 bool isArrayType() const;
1677 bool isConstantArrayType() const;
1678 bool isIncompleteArrayType() const;
1679 bool isVariableArrayType() const;
1680 bool isDependentSizedArrayType() const;
1681 bool isRecordType() const;
1682 bool isClassType() const;
1683 bool isStructureType() const;
1684 bool isObjCBoxableRecordType() const;
1685 bool isInterfaceType() const;
1686 bool isStructureOrClassType() const;
1687 bool isUnionType() const;
1688 bool isComplexIntegerType() const; // GCC _Complex integer type.
1689 bool isVectorType() const; // GCC vector type.
1690 bool isExtVectorType() const; // Extended vector type.
1691 bool isObjCObjectPointerType() const; // pointer to ObjC object
1692 bool isObjCRetainableType() const; // ObjC object or block pointer
1693 bool isObjCLifetimeType() const; // (array of)* retainable type
1694 bool isObjCIndirectLifetimeType() const; // (pointer to)* lifetime type
1695 bool isObjCNSObjectType() const; // __attribute__((NSObject))
1696 bool isObjCIndependentClassType() const; // __attribute__((objc_independent_class))
1697 // FIXME: change this to 'raw' interface type, so we can used 'interface' type
1698 // for the common case.
1699 bool isObjCObjectType() const; // NSString or typeof(*(id)0)
1700 bool isObjCQualifiedInterfaceType() const; // NSString<foo>
1701 bool isObjCQualifiedIdType() const; // id<foo>
1702 bool isObjCQualifiedClassType() const; // Class<foo>
1703 bool isObjCObjectOrInterfaceType() const;
1704 bool isObjCIdType() const; // id
1705 bool isObjCInertUnsafeUnretainedType() const;
1707 /// Whether the type is Objective-C 'id' or a __kindof type of an
1708 /// object type, e.g., __kindof NSView * or __kindof id
1711 /// \param bound Will be set to the bound on non-id subtype types,
1712 /// which will be (possibly specialized) Objective-C class type, or
1714 bool isObjCIdOrObjectKindOfType(const ASTContext &ctx,
1715 const ObjCObjectType *&bound) const;
1717 bool isObjCClassType() const; // Class
1719 /// Whether the type is Objective-C 'Class' or a __kindof type of an
1720 /// Class type, e.g., __kindof Class <NSCopying>.
1722 /// Unlike \c isObjCIdOrObjectKindOfType, there is no relevant bound
1723 /// here because Objective-C's type system cannot express "a class
1724 /// object for a subclass of NSFoo".
1725 bool isObjCClassOrClassKindOfType() const;
1727 bool isBlockCompatibleObjCPointerType(ASTContext &ctx) const;
1728 bool isObjCSelType() const; // Class
1729 bool isObjCBuiltinType() const; // 'id' or 'Class'
1730 bool isObjCARCBridgableType() const;
1731 bool isCARCBridgableType() const;
1732 bool isTemplateTypeParmType() const; // C++ template type parameter
1733 bool isNullPtrType() const; // C++11 std::nullptr_t
1734 bool isAlignValT() const; // C++17 std::align_val_t
1735 bool isAtomicType() const; // C11 _Atomic()
1737 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
1738 bool is##Id##Type() const;
1739 #include "clang/Basic/OpenCLImageTypes.def"
1741 bool isImageType() const; // Any OpenCL image type
1743 bool isSamplerT() const; // OpenCL sampler_t
1744 bool isEventT() const; // OpenCL event_t
1745 bool isClkEventT() const; // OpenCL clk_event_t
1746 bool isQueueT() const; // OpenCL queue_t
1747 bool isNDRangeT() const; // OpenCL ndrange_t
1748 bool isReserveIDT() const; // OpenCL reserve_id_t
1750 bool isPipeType() const; // OpenCL pipe type
1751 bool isOpenCLSpecificType() const; // Any OpenCL specific type
1753 /// Determines if this type, which must satisfy
1754 /// isObjCLifetimeType(), is implicitly __unsafe_unretained rather
1755 /// than implicitly __strong.
1756 bool isObjCARCImplicitlyUnretainedType() const;
1758 /// Return the implicit lifetime for this type, which must not be dependent.
1759 Qualifiers::ObjCLifetime getObjCARCImplicitLifetime() const;
1761 enum ScalarTypeKind {
1764 STK_ObjCObjectPointer,
1769 STK_IntegralComplex,
1772 /// Given that this is a scalar type, classify it.
1773 ScalarTypeKind getScalarTypeKind() const;
1775 /// Whether this type is a dependent type, meaning that its definition
1776 /// somehow depends on a template parameter (C++ [temp.dep.type]).
1777 bool isDependentType() const { return TypeBits.Dependent; }
1779 /// \brief Determine whether this type is an instantiation-dependent type,
1780 /// meaning that the type involves a template parameter (even if the
1781 /// definition does not actually depend on the type substituted for that
1782 /// template parameter).
1783 bool isInstantiationDependentType() const {
1784 return TypeBits.InstantiationDependent;
1787 /// \brief Determine whether this type is an undeduced type, meaning that
1788 /// it somehow involves a C++11 'auto' type which has not yet been deduced.
1789 bool isUndeducedType() const;
1791 /// \brief Whether this type is a variably-modified type (C99 6.7.5).
1792 bool isVariablyModifiedType() const { return TypeBits.VariablyModified; }
1794 /// \brief Whether this type involves a variable-length array type
1795 /// with a definite size.
1796 bool hasSizedVLAType() const;
1798 /// \brief Whether this type is or contains a local or unnamed type.
1799 bool hasUnnamedOrLocalType() const;
1801 bool isOverloadableType() const;
1803 /// \brief Determine wither this type is a C++ elaborated-type-specifier.
1804 bool isElaboratedTypeSpecifier() const;
1806 bool canDecayToPointerType() const;
1808 /// Whether this type is represented natively as a pointer. This includes
1809 /// pointers, references, block pointers, and Objective-C interface,
1810 /// qualified id, and qualified interface types, as well as nullptr_t.
1811 bool hasPointerRepresentation() const;
1813 /// Whether this type can represent an objective pointer type for the
1814 /// purpose of GC'ability
1815 bool hasObjCPointerRepresentation() const;
1817 /// \brief Determine whether this type has an integer representation
1818 /// of some sort, e.g., it is an integer type or a vector.
1819 bool hasIntegerRepresentation() const;
1821 /// \brief Determine whether this type has an signed integer representation
1822 /// of some sort, e.g., it is an signed integer type or a vector.
1823 bool hasSignedIntegerRepresentation() const;
1825 /// \brief Determine whether this type has an unsigned integer representation
1826 /// of some sort, e.g., it is an unsigned integer type or a vector.
1827 bool hasUnsignedIntegerRepresentation() const;
1829 /// \brief Determine whether this type has a floating-point representation
1830 /// of some sort, e.g., it is a floating-point type or a vector thereof.
1831 bool hasFloatingRepresentation() const;
1833 // Type Checking Functions: Check to see if this type is structurally the
1834 // specified type, ignoring typedefs and qualifiers, and return a pointer to
1835 // the best type we can.
1836 const RecordType *getAsStructureType() const;
1837 /// NOTE: getAs*ArrayType are methods on ASTContext.
1838 const RecordType *getAsUnionType() const;
1839 const ComplexType *getAsComplexIntegerType() const; // GCC complex int type.
1840 const ObjCObjectType *getAsObjCInterfaceType() const;
1841 // The following is a convenience method that returns an ObjCObjectPointerType
1842 // for object declared using an interface.
1843 const ObjCObjectPointerType *getAsObjCInterfacePointerType() const;
1844 const ObjCObjectPointerType *getAsObjCQualifiedIdType() const;
1845 const ObjCObjectPointerType *getAsObjCQualifiedClassType() const;
1846 const ObjCObjectType *getAsObjCQualifiedInterfaceType() const;
1848 /// \brief Retrieves the CXXRecordDecl that this type refers to, either
1849 /// because the type is a RecordType or because it is the injected-class-name
1850 /// type of a class template or class template partial specialization.
1851 CXXRecordDecl *getAsCXXRecordDecl() const;
1853 /// \brief Retrieves the TagDecl that this type refers to, either
1854 /// because the type is a TagType or because it is the injected-class-name
1855 /// type of a class template or class template partial specialization.
1856 TagDecl *getAsTagDecl() const;
1858 /// If this is a pointer or reference to a RecordType, return the
1859 /// CXXRecordDecl that that type refers to.
1861 /// If this is not a pointer or reference, or the type being pointed to does
1862 /// not refer to a CXXRecordDecl, returns NULL.
1863 const CXXRecordDecl *getPointeeCXXRecordDecl() const;
1865 /// Get the AutoType whose type will be deduced for a variable with
1866 /// an initializer of this type. This looks through declarators like pointer
1867 /// types, but not through decltype or typedefs.
1868 AutoType *getContainedAutoType() const;
1870 /// Member-template getAs<specific type>'. Look through sugar for
1871 /// an instance of \<specific type>. This scheme will eventually
1872 /// replace the specific getAsXXXX methods above.
1874 /// There are some specializations of this member template listed
1875 /// immediately following this class.
1876 template <typename T> const T *getAs() const;
1878 /// A variant of getAs<> for array types which silently discards
1879 /// qualifiers from the outermost type.
1880 const ArrayType *getAsArrayTypeUnsafe() const;
1882 /// Member-template castAs<specific type>. Look through sugar for
1883 /// the underlying instance of \<specific type>.
1885 /// This method has the same relationship to getAs<T> as cast<T> has
1886 /// to dyn_cast<T>; which is to say, the underlying type *must*
1887 /// have the intended type, and this method will never return null.
1888 template <typename T> const T *castAs() const;
1890 /// A variant of castAs<> for array type which silently discards
1891 /// qualifiers from the outermost type.
1892 const ArrayType *castAsArrayTypeUnsafe() const;
1894 /// Get the base element type of this type, potentially discarding type
1895 /// qualifiers. This should never be used when type qualifiers
1897 const Type *getBaseElementTypeUnsafe() const;
1899 /// If this is an array type, return the element type of the array,
1900 /// potentially with type qualifiers missing.
1901 /// This should never be used when type qualifiers are meaningful.
1902 const Type *getArrayElementTypeNoTypeQual() const;
1904 /// If this is a pointer type, return the pointee type.
1905 /// If this is an array type, return the array element type.
1906 /// This should never be used when type qualifiers are meaningful.
1907 const Type *getPointeeOrArrayElementType() const;
1909 /// If this is a pointer, ObjC object pointer, or block
1910 /// pointer, this returns the respective pointee.
1911 QualType getPointeeType() const;
1913 /// Return the specified type with any "sugar" removed from the type,
1914 /// removing any typedefs, typeofs, etc., as well as any qualifiers.
1915 const Type *getUnqualifiedDesugaredType() const;
1917 /// More type predicates useful for type checking/promotion
1918 bool isPromotableIntegerType() const; // C99 6.3.1.1p2
1920 /// Return true if this is an integer type that is
1921 /// signed, according to C99 6.2.5p4 [char, signed char, short, int, long..],
1922 /// or an enum decl which has a signed representation.
1923 bool isSignedIntegerType() const;
1925 /// Return true if this is an integer type that is
1926 /// unsigned, according to C99 6.2.5p6 [which returns true for _Bool],
1927 /// or an enum decl which has an unsigned representation.
1928 bool isUnsignedIntegerType() const;
1930 /// Determines whether this is an integer type that is signed or an
1931 /// enumeration types whose underlying type is a signed integer type.
1932 bool isSignedIntegerOrEnumerationType() const;
1934 /// Determines whether this is an integer type that is unsigned or an
1935 /// enumeration types whose underlying type is a unsigned integer type.
1936 bool isUnsignedIntegerOrEnumerationType() const;
1938 /// Return true if this is not a variable sized type,
1939 /// according to the rules of C99 6.7.5p3. It is not legal to call this on
1940 /// incomplete types.
1941 bool isConstantSizeType() const;
1943 /// Returns true if this type can be represented by some
1944 /// set of type specifiers.
1945 bool isSpecifierType() const;
1947 /// Determine the linkage of this type.
1948 Linkage getLinkage() const;
1950 /// Determine the visibility of this type.
1951 Visibility getVisibility() const {
1952 return getLinkageAndVisibility().getVisibility();
1955 /// Return true if the visibility was explicitly set is the code.
1956 bool isVisibilityExplicit() const {
1957 return getLinkageAndVisibility().isVisibilityExplicit();
1960 /// Determine the linkage and visibility of this type.
1961 LinkageInfo getLinkageAndVisibility() const;
1963 /// True if the computed linkage is valid. Used for consistency
1964 /// checking. Should always return true.
1965 bool isLinkageValid() const;
1967 /// Determine the nullability of the given type.
1969 /// Note that nullability is only captured as sugar within the type
1970 /// system, not as part of the canonical type, so nullability will
1971 /// be lost by canonicalization and desugaring.
1972 Optional<NullabilityKind> getNullability(const ASTContext &context) const;
1974 /// Determine whether the given type can have a nullability
1975 /// specifier applied to it, i.e., if it is any kind of pointer type
1976 /// or a dependent type that could instantiate to any kind of
1978 bool canHaveNullability() const;
1980 /// Retrieve the set of substitutions required when accessing a member
1981 /// of the Objective-C receiver type that is declared in the given context.
1983 /// \c *this is the type of the object we're operating on, e.g., the
1984 /// receiver for a message send or the base of a property access, and is
1985 /// expected to be of some object or object pointer type.
1987 /// \param dc The declaration context for which we are building up a
1988 /// substitution mapping, which should be an Objective-C class, extension,
1989 /// category, or method within.
1991 /// \returns an array of type arguments that can be substituted for
1992 /// the type parameters of the given declaration context in any type described
1993 /// within that context, or an empty optional to indicate that no
1994 /// substitution is required.
1995 Optional<ArrayRef<QualType>>
1996 getObjCSubstitutions(const DeclContext *dc) const;
1998 /// Determines if this is an ObjC interface type that may accept type
2000 bool acceptsObjCTypeParams() const;
2002 const char *getTypeClassName() const;
2004 QualType getCanonicalTypeInternal() const {
2005 return CanonicalType;
2007 CanQualType getCanonicalTypeUnqualified() const; // in CanonicalType.h
2009 void dump(llvm::raw_ostream &OS) const;
2011 friend class ASTReader;
2012 friend class ASTWriter;
2015 /// \brief This will check for a TypedefType by removing any existing sugar
2016 /// until it reaches a TypedefType or a non-sugared type.
2017 template <> const TypedefType *Type::getAs() const;
2019 /// \brief This will check for a TemplateSpecializationType by removing any
2020 /// existing sugar until it reaches a TemplateSpecializationType or a
2021 /// non-sugared type.
2022 template <> const TemplateSpecializationType *Type::getAs() const;
2024 /// \brief This will check for an AttributedType by removing any existing sugar
2025 /// until it reaches an AttributedType or a non-sugared type.
2026 template <> const AttributedType *Type::getAs() const;
2028 // We can do canonical leaf types faster, because we don't have to
2029 // worry about preserving child type decoration.
2030 #define TYPE(Class, Base)
2031 #define LEAF_TYPE(Class) \
2032 template <> inline const Class##Type *Type::getAs() const { \
2033 return dyn_cast<Class##Type>(CanonicalType); \
2035 template <> inline const Class##Type *Type::castAs() const { \
2036 return cast<Class##Type>(CanonicalType); \
2038 #include "clang/AST/TypeNodes.def"
2041 /// This class is used for builtin types like 'int'. Builtin
2042 /// types are always canonical and have a literal name field.
2043 class BuiltinType : public Type {
2046 // OpenCL image types
2047 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) Id,
2048 #include "clang/Basic/OpenCLImageTypes.def"
2049 // All other builtin types
2050 #define BUILTIN_TYPE(Id, SingletonId) Id,
2051 #define LAST_BUILTIN_TYPE(Id) LastKind = Id
2052 #include "clang/AST/BuiltinTypes.def"
2057 : Type(Builtin, QualType(), /*Dependent=*/(K == Dependent),
2058 /*InstantiationDependent=*/(K == Dependent),
2059 /*VariablyModified=*/false,
2060 /*Unexpanded paramter pack=*/false) {
2061 BuiltinTypeBits.Kind = K;
2064 Kind getKind() const { return static_cast<Kind>(BuiltinTypeBits.Kind); }
2065 StringRef getName(const PrintingPolicy &Policy) const;
2066 const char *getNameAsCString(const PrintingPolicy &Policy) const {
2067 // The StringRef is null-terminated.
2068 StringRef str = getName(Policy);
2069 assert(!str.empty() && str.data()[str.size()] == '\0');
2073 bool isSugared() const { return false; }
2074 QualType desugar() const { return QualType(this, 0); }
2076 bool isInteger() const {
2077 return getKind() >= Bool && getKind() <= Int128;
2080 bool isSignedInteger() const {
2081 return getKind() >= Char_S && getKind() <= Int128;
2084 bool isUnsignedInteger() const {
2085 return getKind() >= Bool && getKind() <= UInt128;
2088 bool isFloatingPoint() const {
2089 return getKind() >= Half && getKind() <= Float128;
2092 /// Determines whether the given kind corresponds to a placeholder type.
2093 static bool isPlaceholderTypeKind(Kind K) {
2094 return K >= Overload;
2097 /// Determines whether this type is a placeholder type, i.e. a type
2098 /// which cannot appear in arbitrary positions in a fully-formed
2100 bool isPlaceholderType() const {
2101 return isPlaceholderTypeKind(getKind());
2104 /// Determines whether this type is a placeholder type other than
2105 /// Overload. Most placeholder types require only syntactic
2106 /// information about their context in order to be resolved (e.g.
2107 /// whether it is a call expression), which means they can (and
2108 /// should) be resolved in an earlier "phase" of analysis.
2109 /// Overload expressions sometimes pick up further information
2110 /// from their context, like whether the context expects a
2111 /// specific function-pointer type, and so frequently need
2112 /// special treatment.
2113 bool isNonOverloadPlaceholderType() const {
2114 return getKind() > Overload;
2117 static bool classof(const Type *T) { return T->getTypeClass() == Builtin; }
2120 /// Complex values, per C99 6.2.5p11. This supports the C99 complex
2121 /// types (_Complex float etc) as well as the GCC integer complex extensions.
2123 class ComplexType : public Type, public llvm::FoldingSetNode {
2124 QualType ElementType;
2125 ComplexType(QualType Element, QualType CanonicalPtr) :
2126 Type(Complex, CanonicalPtr, Element->isDependentType(),
2127 Element->isInstantiationDependentType(),
2128 Element->isVariablyModifiedType(),
2129 Element->containsUnexpandedParameterPack()),
2130 ElementType(Element) {
2132 friend class ASTContext; // ASTContext creates these.
2135 QualType getElementType() const { return ElementType; }
2137 bool isSugared() const { return false; }
2138 QualType desugar() const { return QualType(this, 0); }
2140 void Profile(llvm::FoldingSetNodeID &ID) {
2141 Profile(ID, getElementType());
2143 static void Profile(llvm::FoldingSetNodeID &ID, QualType Element) {
2144 ID.AddPointer(Element.getAsOpaquePtr());
2147 static bool classof(const Type *T) { return T->getTypeClass() == Complex; }
2150 /// Sugar for parentheses used when specifying types.
2152 class ParenType : public Type, public llvm::FoldingSetNode {
2155 ParenType(QualType InnerType, QualType CanonType) :
2156 Type(Paren, CanonType, InnerType->isDependentType(),
2157 InnerType->isInstantiationDependentType(),
2158 InnerType->isVariablyModifiedType(),
2159 InnerType->containsUnexpandedParameterPack()),
2162 friend class ASTContext; // ASTContext creates these.
2166 QualType getInnerType() const { return Inner; }
2168 bool isSugared() const { return true; }
2169 QualType desugar() const { return getInnerType(); }
2171 void Profile(llvm::FoldingSetNodeID &ID) {
2172 Profile(ID, getInnerType());
2174 static void Profile(llvm::FoldingSetNodeID &ID, QualType Inner) {
2178 static bool classof(const Type *T) { return T->getTypeClass() == Paren; }
2181 /// PointerType - C99 6.7.5.1 - Pointer Declarators.
2183 class PointerType : public Type, public llvm::FoldingSetNode {
2184 QualType PointeeType;
2186 PointerType(QualType Pointee, QualType CanonicalPtr) :
2187 Type(Pointer, CanonicalPtr, Pointee->isDependentType(),
2188 Pointee->isInstantiationDependentType(),
2189 Pointee->isVariablyModifiedType(),
2190 Pointee->containsUnexpandedParameterPack()),
2191 PointeeType(Pointee) {
2193 friend class ASTContext; // ASTContext creates these.
2197 QualType getPointeeType() const { return PointeeType; }
2199 /// Returns true if address spaces of pointers overlap.
2200 /// OpenCL v2.0 defines conversion rules for pointers to different
2201 /// address spaces (OpenCLC v2.0 s6.5.5) and notion of overlapping
2204 /// address spaces overlap iff they are they same.
2206 /// __generic overlaps with any address space except for __constant.
2207 bool isAddressSpaceOverlapping(const PointerType &other) const {
2208 Qualifiers thisQuals = PointeeType.getQualifiers();
2209 Qualifiers otherQuals = other.getPointeeType().getQualifiers();
2210 // Address spaces overlap if at least one of them is a superset of another
2211 return thisQuals.isAddressSpaceSupersetOf(otherQuals) ||
2212 otherQuals.isAddressSpaceSupersetOf(thisQuals);
2215 bool isSugared() const { return false; }
2216 QualType desugar() const { return QualType(this, 0); }
2218 void Profile(llvm::FoldingSetNodeID &ID) {
2219 Profile(ID, getPointeeType());
2221 static void Profile(llvm::FoldingSetNodeID &ID, QualType Pointee) {
2222 ID.AddPointer(Pointee.getAsOpaquePtr());
2225 static bool classof(const Type *T) { return T->getTypeClass() == Pointer; }
2228 /// Represents a type which was implicitly adjusted by the semantic
2229 /// engine for arbitrary reasons. For example, array and function types can
2230 /// decay, and function types can have their calling conventions adjusted.
2231 class AdjustedType : public Type, public llvm::FoldingSetNode {
2232 QualType OriginalTy;
2233 QualType AdjustedTy;
2236 AdjustedType(TypeClass TC, QualType OriginalTy, QualType AdjustedTy,
2237 QualType CanonicalPtr)
2238 : Type(TC, CanonicalPtr, OriginalTy->isDependentType(),
2239 OriginalTy->isInstantiationDependentType(),
2240 OriginalTy->isVariablyModifiedType(),
2241 OriginalTy->containsUnexpandedParameterPack()),
2242 OriginalTy(OriginalTy), AdjustedTy(AdjustedTy) {}
2244 friend class ASTContext; // ASTContext creates these.
2247 QualType getOriginalType() const { return OriginalTy; }
2248 QualType getAdjustedType() const { return AdjustedTy; }
2250 bool isSugared() const { return true; }
2251 QualType desugar() const { return AdjustedTy; }
2253 void Profile(llvm::FoldingSetNodeID &ID) {
2254 Profile(ID, OriginalTy, AdjustedTy);
2256 static void Profile(llvm::FoldingSetNodeID &ID, QualType Orig, QualType New) {
2257 ID.AddPointer(Orig.getAsOpaquePtr());
2258 ID.AddPointer(New.getAsOpaquePtr());
2261 static bool classof(const Type *T) {
2262 return T->getTypeClass() == Adjusted || T->getTypeClass() == Decayed;
2266 /// Represents a pointer type decayed from an array or function type.
2267 class DecayedType : public AdjustedType {
2270 DecayedType(QualType OriginalType, QualType Decayed, QualType Canonical);
2272 friend class ASTContext; // ASTContext creates these.
2275 QualType getDecayedType() const { return getAdjustedType(); }
2277 inline QualType getPointeeType() const;
2279 static bool classof(const Type *T) { return T->getTypeClass() == Decayed; }
2282 /// Pointer to a block type.
2283 /// This type is to represent types syntactically represented as
2284 /// "void (^)(int)", etc. Pointee is required to always be a function type.
2286 class BlockPointerType : public Type, public llvm::FoldingSetNode {
2287 QualType PointeeType; // Block is some kind of pointer type
2288 BlockPointerType(QualType Pointee, QualType CanonicalCls) :
2289 Type(BlockPointer, CanonicalCls, Pointee->isDependentType(),
2290 Pointee->isInstantiationDependentType(),
2291 Pointee->isVariablyModifiedType(),
2292 Pointee->containsUnexpandedParameterPack()),
2293 PointeeType(Pointee) {
2295 friend class ASTContext; // ASTContext creates these.
2299 // Get the pointee type. Pointee is required to always be a function type.
2300 QualType getPointeeType() const { return PointeeType; }
2302 bool isSugared() const { return false; }
2303 QualType desugar() const { return QualType(this, 0); }
2305 void Profile(llvm::FoldingSetNodeID &ID) {
2306 Profile(ID, getPointeeType());
2308 static void Profile(llvm::FoldingSetNodeID &ID, QualType Pointee) {
2309 ID.AddPointer(Pointee.getAsOpaquePtr());
2312 static bool classof(const Type *T) {
2313 return T->getTypeClass() == BlockPointer;
2317 /// Base for LValueReferenceType and RValueReferenceType
2319 class ReferenceType : public Type, public llvm::FoldingSetNode {
2320 QualType PointeeType;
2323 ReferenceType(TypeClass tc, QualType Referencee, QualType CanonicalRef,
2324 bool SpelledAsLValue) :
2325 Type(tc, CanonicalRef, Referencee->isDependentType(),
2326 Referencee->isInstantiationDependentType(),
2327 Referencee->isVariablyModifiedType(),
2328 Referencee->containsUnexpandedParameterPack()),
2329 PointeeType(Referencee)
2331 ReferenceTypeBits.SpelledAsLValue = SpelledAsLValue;
2332 ReferenceTypeBits.InnerRef = Referencee->isReferenceType();
2336 bool isSpelledAsLValue() const { return ReferenceTypeBits.SpelledAsLValue; }
2337 bool isInnerRef() const { return ReferenceTypeBits.InnerRef; }
2339 QualType getPointeeTypeAsWritten() const { return PointeeType; }
2340 QualType getPointeeType() const {
2341 // FIXME: this might strip inner qualifiers; okay?
2342 const ReferenceType *T = this;
2343 while (T->isInnerRef())
2344 T = T->PointeeType->castAs<ReferenceType>();
2345 return T->PointeeType;
2348 void Profile(llvm::FoldingSetNodeID &ID) {
2349 Profile(ID, PointeeType, isSpelledAsLValue());
2351 static void Profile(llvm::FoldingSetNodeID &ID,
2352 QualType Referencee,
2353 bool SpelledAsLValue) {
2354 ID.AddPointer(Referencee.getAsOpaquePtr());
2355 ID.AddBoolean(SpelledAsLValue);
2358 static bool classof(const Type *T) {
2359 return T->getTypeClass() == LValueReference ||
2360 T->getTypeClass() == RValueReference;
2364 /// An lvalue reference type, per C++11 [dcl.ref].
2366 class LValueReferenceType : public ReferenceType {
2367 LValueReferenceType(QualType Referencee, QualType CanonicalRef,
2368 bool SpelledAsLValue) :
2369 ReferenceType(LValueReference, Referencee, CanonicalRef, SpelledAsLValue)
2371 friend class ASTContext; // ASTContext creates these
2373 bool isSugared() const { return false; }
2374 QualType desugar() const { return QualType(this, 0); }
2376 static bool classof(const Type *T) {
2377 return T->getTypeClass() == LValueReference;
2381 /// An rvalue reference type, per C++11 [dcl.ref].
2383 class RValueReferenceType : public ReferenceType {
2384 RValueReferenceType(QualType Referencee, QualType CanonicalRef) :
2385 ReferenceType(RValueReference, Referencee, CanonicalRef, false) {
2387 friend class ASTContext; // ASTContext creates these
2389 bool isSugared() const { return false; }
2390 QualType desugar() const { return QualType(this, 0); }
2392 static bool classof(const Type *T) {
2393 return T->getTypeClass() == RValueReference;
2397 /// A pointer to member type per C++ 8.3.3 - Pointers to members.
2399 /// This includes both pointers to data members and pointer to member functions.
2401 class MemberPointerType : public Type, public llvm::FoldingSetNode {
2402 QualType PointeeType;
2403 /// The class of which the pointee is a member. Must ultimately be a
2404 /// RecordType, but could be a typedef or a template parameter too.
2407 MemberPointerType(QualType Pointee, const Type *Cls, QualType CanonicalPtr) :
2408 Type(MemberPointer, CanonicalPtr,
2409 Cls->isDependentType() || Pointee->isDependentType(),
2410 (Cls->isInstantiationDependentType() ||
2411 Pointee->isInstantiationDependentType()),
2412 Pointee->isVariablyModifiedType(),
2413 (Cls->containsUnexpandedParameterPack() ||
2414 Pointee->containsUnexpandedParameterPack())),
2415 PointeeType(Pointee), Class(Cls) {
2417 friend class ASTContext; // ASTContext creates these.
2420 QualType getPointeeType() const { return PointeeType; }
2422 /// Returns true if the member type (i.e. the pointee type) is a
2423 /// function type rather than a data-member type.
2424 bool isMemberFunctionPointer() const {
2425 return PointeeType->isFunctionProtoType();
2428 /// Returns true if the member type (i.e. the pointee type) is a
2429 /// data type rather than a function type.
2430 bool isMemberDataPointer() const {
2431 return !PointeeType->isFunctionProtoType();
2434 const Type *getClass() const { return Class; }
2435 CXXRecordDecl *getMostRecentCXXRecordDecl() const;
2437 bool isSugared() const { return false; }
2438 QualType desugar() const { return QualType(this, 0); }
2440 void Profile(llvm::FoldingSetNodeID &ID) {
2441 Profile(ID, getPointeeType(), getClass());
2443 static void Profile(llvm::FoldingSetNodeID &ID, QualType Pointee,
2444 const Type *Class) {
2445 ID.AddPointer(Pointee.getAsOpaquePtr());
2446 ID.AddPointer(Class);
2449 static bool classof(const Type *T) {
2450 return T->getTypeClass() == MemberPointer;
2454 /// Represents an array type, per C99 6.7.5.2 - Array Declarators.
2456 class ArrayType : public Type, public llvm::FoldingSetNode {
2458 /// Capture whether this is a normal array (e.g. int X[4])
2459 /// an array with a static size (e.g. int X[static 4]), or an array
2460 /// with a star size (e.g. int X[*]).
2461 /// 'static' is only allowed on function parameters.
2462 enum ArraySizeModifier {
2463 Normal, Static, Star
2466 /// The element type of the array.
2467 QualType ElementType;
2470 // C++ [temp.dep.type]p1:
2471 // A type is dependent if it is...
2472 // - an array type constructed from any dependent type or whose
2473 // size is specified by a constant expression that is
2475 ArrayType(TypeClass tc, QualType et, QualType can,
2476 ArraySizeModifier sm, unsigned tq,
2477 bool ContainsUnexpandedParameterPack)
2478 : Type(tc, can, et->isDependentType() || tc == DependentSizedArray,
2479 et->isInstantiationDependentType() || tc == DependentSizedArray,
2480 (tc == VariableArray || et->isVariablyModifiedType()),
2481 ContainsUnexpandedParameterPack),
2483 ArrayTypeBits.IndexTypeQuals = tq;
2484 ArrayTypeBits.SizeModifier = sm;
2487 friend class ASTContext; // ASTContext creates these.
2490 QualType getElementType() const { return ElementType; }
2491 ArraySizeModifier getSizeModifier() const {
2492 return ArraySizeModifier(ArrayTypeBits.SizeModifier);
2494 Qualifiers getIndexTypeQualifiers() const {
2495 return Qualifiers::fromCVRMask(getIndexTypeCVRQualifiers());
2497 unsigned getIndexTypeCVRQualifiers() const {
2498 return ArrayTypeBits.IndexTypeQuals;
2501 static bool classof(const Type *T) {
2502 return T->getTypeClass() == ConstantArray ||
2503 T->getTypeClass() == VariableArray ||
2504 T->getTypeClass() == IncompleteArray ||
2505 T->getTypeClass() == DependentSizedArray;
2509 /// Represents the canonical version of C arrays with a specified constant size.
2510 /// For example, the canonical type for 'int A[4 + 4*100]' is a
2511 /// ConstantArrayType where the element type is 'int' and the size is 404.
2512 class ConstantArrayType : public ArrayType {
2513 llvm::APInt Size; // Allows us to unique the type.
2515 ConstantArrayType(QualType et, QualType can, const llvm::APInt &size,
2516 ArraySizeModifier sm, unsigned tq)
2517 : ArrayType(ConstantArray, et, can, sm, tq,
2518 et->containsUnexpandedParameterPack()),
2521 ConstantArrayType(TypeClass tc, QualType et, QualType can,
2522 const llvm::APInt &size, ArraySizeModifier sm, unsigned tq)
2523 : ArrayType(tc, et, can, sm, tq, et->containsUnexpandedParameterPack()),
2525 friend class ASTContext; // ASTContext creates these.
2527 const llvm::APInt &getSize() const { return Size; }
2528 bool isSugared() const { return false; }
2529 QualType desugar() const { return QualType(this, 0); }
2532 /// \brief Determine the number of bits required to address a member of
2533 // an array with the given element type and number of elements.
2534 static unsigned getNumAddressingBits(const ASTContext &Context,
2535 QualType ElementType,
2536 const llvm::APInt &NumElements);
2538 /// \brief Determine the maximum number of active bits that an array's size
2539 /// can require, which limits the maximum size of the array.
2540 static unsigned getMaxSizeBits(const ASTContext &Context);
2542 void Profile(llvm::FoldingSetNodeID &ID) {
2543 Profile(ID, getElementType(), getSize(),
2544 getSizeModifier(), getIndexTypeCVRQualifiers());
2546 static void Profile(llvm::FoldingSetNodeID &ID, QualType ET,
2547 const llvm::APInt &ArraySize, ArraySizeModifier SizeMod,
2548 unsigned TypeQuals) {
2549 ID.AddPointer(ET.getAsOpaquePtr());
2550 ID.AddInteger(ArraySize.getZExtValue());
2551 ID.AddInteger(SizeMod);
2552 ID.AddInteger(TypeQuals);
2554 static bool classof(const Type *T) {
2555 return T->getTypeClass() == ConstantArray;
2559 /// Represents a C array with an unspecified size. For example 'int A[]' has
2560 /// an IncompleteArrayType where the element type is 'int' and the size is
2562 class IncompleteArrayType : public ArrayType {
2564 IncompleteArrayType(QualType et, QualType can,
2565 ArraySizeModifier sm, unsigned tq)
2566 : ArrayType(IncompleteArray, et, can, sm, tq,
2567 et->containsUnexpandedParameterPack()) {}
2568 friend class ASTContext; // ASTContext creates these.
2570 bool isSugared() const { return false; }
2571 QualType desugar() const { return QualType(this, 0); }
2573 static bool classof(const Type *T) {
2574 return T->getTypeClass() == IncompleteArray;
2577 friend class StmtIteratorBase;
2579 void Profile(llvm::FoldingSetNodeID &ID) {
2580 Profile(ID, getElementType(), getSizeModifier(),
2581 getIndexTypeCVRQualifiers());
2584 static void Profile(llvm::FoldingSetNodeID &ID, QualType ET,
2585 ArraySizeModifier SizeMod, unsigned TypeQuals) {
2586 ID.AddPointer(ET.getAsOpaquePtr());
2587 ID.AddInteger(SizeMod);
2588 ID.AddInteger(TypeQuals);
2592 /// Represents a C array with a specified size that is not an
2593 /// integer-constant-expression. For example, 'int s[x+foo()]'.
2594 /// Since the size expression is an arbitrary expression, we store it as such.
2596 /// Note: VariableArrayType's aren't uniqued (since the expressions aren't) and
2597 /// should not be: two lexically equivalent variable array types could mean
2598 /// different things, for example, these variables do not have the same type
2601 /// void foo(int x) {
2607 class VariableArrayType : public ArrayType {
2608 /// An assignment-expression. VLA's are only permitted within
2609 /// a function block.
2611 /// The range spanned by the left and right array brackets.
2612 SourceRange Brackets;
2614 VariableArrayType(QualType et, QualType can, Expr *e,
2615 ArraySizeModifier sm, unsigned tq,
2616 SourceRange brackets)
2617 : ArrayType(VariableArray, et, can, sm, tq,
2618 et->containsUnexpandedParameterPack()),
2619 SizeExpr((Stmt*) e), Brackets(brackets) {}
2620 friend class ASTContext; // ASTContext creates these.
2623 Expr *getSizeExpr() const {
2624 // We use C-style casts instead of cast<> here because we do not wish
2625 // to have a dependency of Type.h on Stmt.h/Expr.h.
2626 return (Expr*) SizeExpr;
2628 SourceRange getBracketsRange() const { return Brackets; }
2629 SourceLocation getLBracketLoc() const { return Brackets.getBegin(); }
2630 SourceLocation getRBracketLoc() const { return Brackets.getEnd(); }
2632 bool isSugared() const { return false; }
2633 QualType desugar() const { return QualType(this, 0); }
2635 static bool classof(const Type *T) {
2636 return T->getTypeClass() == VariableArray;
2639 friend class StmtIteratorBase;
2641 void Profile(llvm::FoldingSetNodeID &ID) {
2642 llvm_unreachable("Cannot unique VariableArrayTypes.");
2646 /// Represents an array type in C++ whose size is a value-dependent expression.
2650 /// template<typename T, int Size>
2656 /// For these types, we won't actually know what the array bound is
2657 /// until template instantiation occurs, at which point this will
2658 /// become either a ConstantArrayType or a VariableArrayType.
2659 class DependentSizedArrayType : public ArrayType {
2660 const ASTContext &Context;
2662 /// \brief An assignment expression that will instantiate to the
2663 /// size of the array.
2665 /// The expression itself might be null, in which case the array
2666 /// type will have its size deduced from an initializer.
2669 /// The range spanned by the left and right array brackets.
2670 SourceRange Brackets;
2672 DependentSizedArrayType(const ASTContext &Context, QualType et, QualType can,
2673 Expr *e, ArraySizeModifier sm, unsigned tq,
2674 SourceRange brackets);
2676 friend class ASTContext; // ASTContext creates these.
2679 Expr *getSizeExpr() const {
2680 // We use C-style casts instead of cast<> here because we do not wish
2681 // to have a dependency of Type.h on Stmt.h/Expr.h.
2682 return (Expr*) SizeExpr;
2684 SourceRange getBracketsRange() const { return Brackets; }
2685 SourceLocation getLBracketLoc() const { return Brackets.getBegin(); }
2686 SourceLocation getRBracketLoc() const { return Brackets.getEnd(); }
2688 bool isSugared() const { return false; }
2689 QualType desugar() const { return QualType(this, 0); }
2691 static bool classof(const Type *T) {
2692 return T->getTypeClass() == DependentSizedArray;
2695 friend class StmtIteratorBase;
2698 void Profile(llvm::FoldingSetNodeID &ID) {
2699 Profile(ID, Context, getElementType(),
2700 getSizeModifier(), getIndexTypeCVRQualifiers(), getSizeExpr());
2703 static void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context,
2704 QualType ET, ArraySizeModifier SizeMod,
2705 unsigned TypeQuals, Expr *E);
2708 /// Represents an extended vector type where either the type or size is
2713 /// template<typename T, int Size>
2715 /// typedef T __attribute__((ext_vector_type(Size))) type;
2718 class DependentSizedExtVectorType : public Type, public llvm::FoldingSetNode {
2719 const ASTContext &Context;
2721 /// The element type of the array.
2722 QualType ElementType;
2725 DependentSizedExtVectorType(const ASTContext &Context, QualType ElementType,
2726 QualType can, Expr *SizeExpr, SourceLocation loc);
2728 friend class ASTContext;
2731 Expr *getSizeExpr() const { return SizeExpr; }
2732 QualType getElementType() const { return ElementType; }
2733 SourceLocation getAttributeLoc() const { return loc; }
2735 bool isSugared() const { return false; }
2736 QualType desugar() const { return QualType(this, 0); }
2738 static bool classof(const Type *T) {
2739 return T->getTypeClass() == DependentSizedExtVector;
2742 void Profile(llvm::FoldingSetNodeID &ID) {
2743 Profile(ID, Context, getElementType(), getSizeExpr());
2746 static void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context,
2747 QualType ElementType, Expr *SizeExpr);
2751 /// Represents a GCC generic vector type. This type is created using
2752 /// __attribute__((vector_size(n)), where "n" specifies the vector size in
2753 /// bytes; or from an Altivec __vector or vector declaration.
2754 /// Since the constructor takes the number of vector elements, the
2755 /// client is responsible for converting the size into the number of elements.
2756 class VectorType : public Type, public llvm::FoldingSetNode {
2759 GenericVector, ///< not a target-specific vector type
2760 AltiVecVector, ///< is AltiVec vector
2761 AltiVecPixel, ///< is AltiVec 'vector Pixel'
2762 AltiVecBool, ///< is AltiVec 'vector bool ...'
2763 NeonVector, ///< is ARM Neon vector
2764 NeonPolyVector ///< is ARM Neon polynomial vector
2767 /// The element type of the vector.
2768 QualType ElementType;
2770 VectorType(QualType vecType, unsigned nElements, QualType canonType,
2771 VectorKind vecKind);
2773 VectorType(TypeClass tc, QualType vecType, unsigned nElements,
2774 QualType canonType, VectorKind vecKind);
2776 friend class ASTContext; // ASTContext creates these.
2780 QualType getElementType() const { return ElementType; }
2781 unsigned getNumElements() const { return VectorTypeBits.NumElements; }
2782 static bool isVectorSizeTooLarge(unsigned NumElements) {
2783 return NumElements > VectorTypeBitfields::MaxNumElements;
2786 bool isSugared() const { return false; }
2787 QualType desugar() const { return QualType(this, 0); }
2789 VectorKind getVectorKind() const {
2790 return VectorKind(VectorTypeBits.VecKind);
2793 void Profile(llvm::FoldingSetNodeID &ID) {
2794 Profile(ID, getElementType(), getNumElements(),
2795 getTypeClass(), getVectorKind());
2797 static void Profile(llvm::FoldingSetNodeID &ID, QualType ElementType,
2798 unsigned NumElements, TypeClass TypeClass,
2799 VectorKind VecKind) {
2800 ID.AddPointer(ElementType.getAsOpaquePtr());
2801 ID.AddInteger(NumElements);
2802 ID.AddInteger(TypeClass);
2803 ID.AddInteger(VecKind);
2806 static bool classof(const Type *T) {
2807 return T->getTypeClass() == Vector || T->getTypeClass() == ExtVector;
2811 /// ExtVectorType - Extended vector type. This type is created using
2812 /// __attribute__((ext_vector_type(n)), where "n" is the number of elements.
2813 /// Unlike vector_size, ext_vector_type is only allowed on typedef's. This
2814 /// class enables syntactic extensions, like Vector Components for accessing
2815 /// points (as .xyzw), colors (as .rgba), and textures (modeled after OpenGL
2816 /// Shading Language).
2817 class ExtVectorType : public VectorType {
2818 ExtVectorType(QualType vecType, unsigned nElements, QualType canonType) :
2819 VectorType(ExtVector, vecType, nElements, canonType, GenericVector) {}
2820 friend class ASTContext; // ASTContext creates these.
2822 static int getPointAccessorIdx(char c) {
2825 case 'x': case 'r': return 0;
2826 case 'y': case 'g': return 1;
2827 case 'z': case 'b': return 2;
2828 case 'w': case 'a': return 3;
2831 static int getNumericAccessorIdx(char c) {
2845 case 'a': return 10;
2847 case 'b': return 11;
2849 case 'c': return 12;
2851 case 'd': return 13;
2853 case 'e': return 14;
2855 case 'f': return 15;
2859 static int getAccessorIdx(char c, bool isNumericAccessor) {
2860 if (isNumericAccessor)
2861 return getNumericAccessorIdx(c);
2863 return getPointAccessorIdx(c);
2866 bool isAccessorWithinNumElements(char c, bool isNumericAccessor) const {
2867 if (int idx = getAccessorIdx(c, isNumericAccessor)+1)
2868 return unsigned(idx-1) < getNumElements();
2871 bool isSugared() const { return false; }
2872 QualType desugar() const { return QualType(this, 0); }
2874 static bool classof(const Type *T) {
2875 return T->getTypeClass() == ExtVector;
2879 /// FunctionType - C99 6.7.5.3 - Function Declarators. This is the common base
2880 /// class of FunctionNoProtoType and FunctionProtoType.
2882 class FunctionType : public Type {
2883 // The type returned by the function.
2884 QualType ResultType;
2887 /// A class which abstracts out some details necessary for
2890 /// It is not actually used directly for storing this information in
2891 /// a FunctionType, although FunctionType does currently use the
2892 /// same bit-pattern.
2894 // If you add a field (say Foo), other than the obvious places (both,
2895 // constructors, compile failures), what you need to update is
2899 // * functionType. Add Foo, getFoo.
2900 // * ASTContext::getFooType
2901 // * ASTContext::mergeFunctionTypes
2902 // * FunctionNoProtoType::Profile
2903 // * FunctionProtoType::Profile
2904 // * TypePrinter::PrintFunctionProto
2905 // * AST read and write
2908 // Feel free to rearrange or add bits, but if you go over 10,
2909 // you'll need to adjust both the Bits field below and
2910 // Type::FunctionTypeBitfields.
2912 // | CC |noreturn|produces|regparm|
2913 // |0 .. 4| 5 | 6 | 7 .. 9|
2915 // regparm is either 0 (no regparm attribute) or the regparm value+1.
2916 enum { CallConvMask = 0x1F };
2917 enum { NoReturnMask = 0x20 };
2918 enum { ProducesResultMask = 0x40 };
2919 enum { RegParmMask = ~(CallConvMask | NoReturnMask | ProducesResultMask),
2920 RegParmOffset = 7 }; // Assumed to be the last field
2924 ExtInfo(unsigned Bits) : Bits(static_cast<uint16_t>(Bits)) {}
2926 friend class FunctionType;
2929 // Constructor with no defaults. Use this when you know that you
2930 // have all the elements (when reading an AST file for example).
2931 ExtInfo(bool noReturn, bool hasRegParm, unsigned regParm, CallingConv cc,
2932 bool producesResult) {
2933 assert((!hasRegParm || regParm < 7) && "Invalid regparm value");
2934 Bits = ((unsigned) cc) |
2935 (noReturn ? NoReturnMask : 0) |
2936 (producesResult ? ProducesResultMask : 0) |
2937 (hasRegParm ? ((regParm + 1) << RegParmOffset) : 0);
2940 // Constructor with all defaults. Use when for example creating a
2941 // function known to use defaults.
2942 ExtInfo() : Bits(CC_C) { }
2944 // Constructor with just the calling convention, which is an important part
2945 // of the canonical type.
2946 ExtInfo(CallingConv CC) : Bits(CC) { }
2948 bool getNoReturn() const { return Bits & NoReturnMask; }
2949 bool getProducesResult() const { return Bits & ProducesResultMask; }
2950 bool getHasRegParm() const { return (Bits >> RegParmOffset) != 0; }
2951 unsigned getRegParm() const {
2952 unsigned RegParm = Bits >> RegParmOffset;
2957 CallingConv getCC() const { return CallingConv(Bits & CallConvMask); }
2959 bool operator==(ExtInfo Other) const {
2960 return Bits == Other.Bits;
2962 bool operator!=(ExtInfo Other) const {
2963 return Bits != Other.Bits;
2966 // Note that we don't have setters. That is by design, use
2967 // the following with methods instead of mutating these objects.
2969 ExtInfo withNoReturn(bool noReturn) const {
2971 return ExtInfo(Bits | NoReturnMask);
2973 return ExtInfo(Bits & ~NoReturnMask);
2976 ExtInfo withProducesResult(bool producesResult) const {
2978 return ExtInfo(Bits | ProducesResultMask);
2980 return ExtInfo(Bits & ~ProducesResultMask);
2983 ExtInfo withRegParm(unsigned RegParm) const {
2984 assert(RegParm < 7 && "Invalid regparm value");
2985 return ExtInfo((Bits & ~RegParmMask) |
2986 ((RegParm + 1) << RegParmOffset));
2989 ExtInfo withCallingConv(CallingConv cc) const {
2990 return ExtInfo((Bits & ~CallConvMask) | (unsigned) cc);
2993 void Profile(llvm::FoldingSetNodeID &ID) const {
2994 ID.AddInteger(Bits);
2999 FunctionType(TypeClass tc, QualType res,
3000 QualType Canonical, bool Dependent,
3001 bool InstantiationDependent,
3002 bool VariablyModified, bool ContainsUnexpandedParameterPack,
3004 : Type(tc, Canonical, Dependent, InstantiationDependent, VariablyModified,
3005 ContainsUnexpandedParameterPack),
3007 FunctionTypeBits.ExtInfo = Info.Bits;
3009 unsigned getTypeQuals() const { return FunctionTypeBits.TypeQuals; }
3012 QualType getReturnType() const { return ResultType; }
3014 bool getHasRegParm() const { return getExtInfo().getHasRegParm(); }
3015 unsigned getRegParmType() const { return getExtInfo().getRegParm(); }
3016 /// Determine whether this function type includes the GNU noreturn
3017 /// attribute. The C++11 [[noreturn]] attribute does not affect the function
3019 bool getNoReturnAttr() const { return getExtInfo().getNoReturn(); }
3020 CallingConv getCallConv() const { return getExtInfo().getCC(); }
3021 ExtInfo getExtInfo() const { return ExtInfo(FunctionTypeBits.ExtInfo); }
3022 bool isConst() const { return getTypeQuals() & Qualifiers::Const; }
3023 bool isVolatile() const { return getTypeQuals() & Qualifiers::Volatile; }
3024 bool isRestrict() const { return getTypeQuals() & Qualifiers::Restrict; }
3026 /// \brief Determine the type of an expression that calls a function of
3028 QualType getCallResultType(const ASTContext &Context) const {
3029 return getReturnType().getNonLValueExprType(Context);
3032 static StringRef getNameForCallConv(CallingConv CC);
3034 static bool classof(const Type *T) {
3035 return T->getTypeClass() == FunctionNoProto ||
3036 T->getTypeClass() == FunctionProto;
3040 /// Represents a K&R-style 'int foo()' function, which has
3041 /// no information available about its arguments.
3042 class FunctionNoProtoType : public FunctionType, public llvm::FoldingSetNode {
3043 FunctionNoProtoType(QualType Result, QualType Canonical, ExtInfo Info)
3044 : FunctionType(FunctionNoProto, Result, Canonical,
3045 /*Dependent=*/false, /*InstantiationDependent=*/false,
3046 Result->isVariablyModifiedType(),
3047 /*ContainsUnexpandedParameterPack=*/false, Info) {}
3049 friend class ASTContext; // ASTContext creates these.
3052 // No additional state past what FunctionType provides.
3054 bool isSugared() const { return false; }
3055 QualType desugar() const { return QualType(this, 0); }
3057 void Profile(llvm::FoldingSetNodeID &ID) {
3058 Profile(ID, getReturnType(), getExtInfo());
3060 static void Profile(llvm::FoldingSetNodeID &ID, QualType ResultType,
3063 ID.AddPointer(ResultType.getAsOpaquePtr());
3066 static bool classof(const Type *T) {
3067 return T->getTypeClass() == FunctionNoProto;
3071 /// Represents a prototype with parameter type info, e.g.
3072 /// 'int foo(int)' or 'int foo(void)'. 'void' is represented as having no
3073 /// parameters, not as having a single void parameter. Such a type can have an
3074 /// exception specification, but this specification is not part of the canonical
3076 class FunctionProtoType : public FunctionType, public llvm::FoldingSetNode {
3078 /// Interesting information about a specific parameter that can't simply
3079 /// be reflected in parameter's type.
3081 /// It makes sense to model language features this way when there's some
3082 /// sort of parameter-specific override (such as an attribute) that
3083 /// affects how the function is called. For example, the ARC ns_consumed
3084 /// attribute changes whether a parameter is passed at +0 (the default)
3085 /// or +1 (ns_consumed). This must be reflected in the function type,
3086 /// but isn't really a change to the parameter type.
3088 /// One serious disadvantage of modelling language features this way is
3089 /// that they generally do not work with language features that attempt
3090 /// to destructure types. For example, template argument deduction will
3091 /// not be able to match a parameter declared as
3093 /// against an argument of type
3094 /// void (*)(__attribute__((ns_consumed)) id)
3095 /// because the substitution of T=void, U=id into the former will
3096 /// not produce the latter.
3097 class ExtParameterInfo {
3104 ExtParameterInfo() : Data(0) {}
3106 /// Return the ABI treatment of this parameter.
3107 ParameterABI getABI() const {
3108 return ParameterABI(Data & ABIMask);
3110 ExtParameterInfo withABI(ParameterABI kind) const {
3111 ExtParameterInfo copy = *this;
3112 copy.Data = (copy.Data & ~ABIMask) | unsigned(kind);
3116 /// Is this parameter considered "consumed" by Objective-C ARC?
3117 /// Consumed parameters must have retainable object type.
3118 bool isConsumed() const {
3119 return (Data & IsConsumed);
3121 ExtParameterInfo withIsConsumed(bool consumed) const {
3122 ExtParameterInfo copy = *this;
3124 copy.Data |= IsConsumed;
3126 copy.Data &= ~IsConsumed;
3131 unsigned char getOpaqueValue() const { return Data; }
3132 static ExtParameterInfo getFromOpaqueValue(unsigned char data) {
3133 ExtParameterInfo result;
3138 friend bool operator==(ExtParameterInfo lhs, ExtParameterInfo rhs) {
3139 return lhs.Data == rhs.Data;
3141 friend bool operator!=(ExtParameterInfo lhs, ExtParameterInfo rhs) {
3142 return lhs.Data != rhs.Data;
3146 struct ExceptionSpecInfo {
3148 : Type(EST_None), NoexceptExpr(nullptr),
3149 SourceDecl(nullptr), SourceTemplate(nullptr) {}
3151 ExceptionSpecInfo(ExceptionSpecificationType EST)
3152 : Type(EST), NoexceptExpr(nullptr), SourceDecl(nullptr),
3153 SourceTemplate(nullptr) {}
3155 /// The kind of exception specification this is.
3156 ExceptionSpecificationType Type;
3157 /// Explicitly-specified list of exception types.
3158 ArrayRef<QualType> Exceptions;
3159 /// Noexcept expression, if this is EST_ComputedNoexcept.
3161 /// The function whose exception specification this is, for
3162 /// EST_Unevaluated and EST_Uninstantiated.
3163 FunctionDecl *SourceDecl;
3164 /// The function template whose exception specification this is instantiated
3165 /// from, for EST_Uninstantiated.
3166 FunctionDecl *SourceTemplate;
3169 /// Extra information about a function prototype.
3170 struct ExtProtoInfo {
3172 : Variadic(false), HasTrailingReturn(false), TypeQuals(0),
3173 RefQualifier(RQ_None), ExtParameterInfos(nullptr) {}
3175 ExtProtoInfo(CallingConv CC)
3176 : ExtInfo(CC), Variadic(false), HasTrailingReturn(false), TypeQuals(0),
3177 RefQualifier(RQ_None), ExtParameterInfos(nullptr) {}
3179 ExtProtoInfo withExceptionSpec(const ExceptionSpecInfo &O) {
3180 ExtProtoInfo Result(*this);
3181 Result.ExceptionSpec = O;
3185 FunctionType::ExtInfo ExtInfo;
3187 bool HasTrailingReturn : 1;
3188 unsigned char TypeQuals;
3189 RefQualifierKind RefQualifier;
3190 ExceptionSpecInfo ExceptionSpec;
3191 const ExtParameterInfo *ExtParameterInfos;
3195 /// \brief Determine whether there are any argument types that
3196 /// contain an unexpanded parameter pack.
3197 static bool containsAnyUnexpandedParameterPack(const QualType *ArgArray,
3199 for (unsigned Idx = 0; Idx < numArgs; ++Idx)
3200 if (ArgArray[Idx]->containsUnexpandedParameterPack())
3206 FunctionProtoType(QualType result, ArrayRef<QualType> params,
3207 QualType canonical, const ExtProtoInfo &epi);
3209 /// The number of parameters this function has, not counting '...'.
3210 unsigned NumParams : 15;
3212 /// The number of types in the exception spec, if any.
3213 unsigned NumExceptions : 9;
3215 /// The type of exception specification this function has.
3216 unsigned ExceptionSpecType : 4;
3218 /// Whether this function has extended parameter information.
3219 unsigned HasExtParameterInfos : 1;
3221 /// Whether the function is variadic.
3222 unsigned Variadic : 1;
3224 /// Whether this function has a trailing return type.
3225 unsigned HasTrailingReturn : 1;
3227 // ParamInfo - There is an variable size array after the class in memory that
3228 // holds the parameter types.
3230 // Exceptions - There is another variable size array after ArgInfo that
3231 // holds the exception types.
3233 // NoexceptExpr - Instead of Exceptions, there may be a single Expr* pointing
3234 // to the expression in the noexcept() specifier.
3236 // ExceptionSpecDecl, ExceptionSpecTemplate - Instead of Exceptions, there may
3237 // be a pair of FunctionDecl* pointing to the function which should be used to
3238 // instantiate this function type's exception specification, and the function
3239 // from which it should be instantiated.
3241 // ExtParameterInfos - A variable size array, following the exception
3242 // specification and of length NumParams, holding an ExtParameterInfo
3243 // for each of the parameters. This only appears if HasExtParameterInfos
3246 friend class ASTContext; // ASTContext creates these.
3248 const ExtParameterInfo *getExtParameterInfosBuffer() const {
3249 assert(hasExtParameterInfos());
3251 // Find the end of the exception specification.
3252 const char *ptr = reinterpret_cast<const char *>(exception_begin());
3253 ptr += getExceptionSpecSize();
3255 return reinterpret_cast<const ExtParameterInfo *>(ptr);
3258 size_t getExceptionSpecSize() const {
3259 switch (getExceptionSpecType()) {
3260 case EST_None: return 0;
3261 case EST_DynamicNone: return 0;
3262 case EST_MSAny: return 0;
3263 case EST_BasicNoexcept: return 0;
3264 case EST_Unparsed: return 0;
3265 case EST_Dynamic: return getNumExceptions() * sizeof(QualType);
3266 case EST_ComputedNoexcept: return sizeof(Expr*);
3267 case EST_Uninstantiated: return 2 * sizeof(FunctionDecl*);
3268 case EST_Unevaluated: return sizeof(FunctionDecl*);
3270 llvm_unreachable("bad exception specification kind");
3274 unsigned getNumParams() const { return NumParams; }
3275 QualType getParamType(unsigned i) const {
3276 assert(i < NumParams && "invalid parameter index");
3277 return param_type_begin()[i];
3279 ArrayRef<QualType> getParamTypes() const {
3280 return llvm::makeArrayRef(param_type_begin(), param_type_end());
3283 ExtProtoInfo getExtProtoInfo() const {
3285 EPI.ExtInfo = getExtInfo();
3286 EPI.Variadic = isVariadic();
3287 EPI.HasTrailingReturn = hasTrailingReturn();
3288 EPI.ExceptionSpec.Type = getExceptionSpecType();
3289 EPI.TypeQuals = static_cast<unsigned char>(getTypeQuals());
3290 EPI.RefQualifier = getRefQualifier();
3291 if (EPI.ExceptionSpec.Type == EST_Dynamic) {
3292 EPI.ExceptionSpec.Exceptions = exceptions();
3293 } else if (EPI.ExceptionSpec.Type == EST_ComputedNoexcept) {
3294 EPI.ExceptionSpec.NoexceptExpr = getNoexceptExpr();
3295 } else if (EPI.ExceptionSpec.Type == EST_Uninstantiated) {
3296 EPI.ExceptionSpec.SourceDecl = getExceptionSpecDecl();
3297 EPI.ExceptionSpec.SourceTemplate = getExceptionSpecTemplate();
3298 } else if (EPI.ExceptionSpec.Type == EST_Unevaluated) {
3299 EPI.ExceptionSpec.SourceDecl = getExceptionSpecDecl();
3301 if (hasExtParameterInfos())
3302 EPI.ExtParameterInfos = getExtParameterInfosBuffer();
3306 /// Get the kind of exception specification on this function.
3307 ExceptionSpecificationType getExceptionSpecType() const {
3308 return static_cast<ExceptionSpecificationType>(ExceptionSpecType);
3310 /// Return whether this function has any kind of exception spec.
3311 bool hasExceptionSpec() const {
3312 return getExceptionSpecType() != EST_None;
3314 /// Return whether this function has a dynamic (throw) exception spec.
3315 bool hasDynamicExceptionSpec() const {
3316 return isDynamicExceptionSpec(getExceptionSpecType());
3318 /// Return whether this function has a noexcept exception spec.
3319 bool hasNoexceptExceptionSpec() const {
3320 return isNoexceptExceptionSpec(getExceptionSpecType());
3322 /// Return whether this function has a dependent exception spec.
3323 bool hasDependentExceptionSpec() const;
3324 /// Return whether this function has an instantiation-dependent exception
3326 bool hasInstantiationDependentExceptionSpec() const;
3327 /// Result type of getNoexceptSpec().
3328 enum NoexceptResult {
3329 NR_NoNoexcept, ///< There is no noexcept specifier.
3330 NR_BadNoexcept, ///< The noexcept specifier has a bad expression.
3331 NR_Dependent, ///< The noexcept specifier is dependent.
3332 NR_Throw, ///< The noexcept specifier evaluates to false.
3333 NR_Nothrow ///< The noexcept specifier evaluates to true.
3335 /// Get the meaning of the noexcept spec on this function, if any.
3336 NoexceptResult getNoexceptSpec(const ASTContext &Ctx) const;
3337 unsigned getNumExceptions() const { return NumExceptions; }
3338 QualType getExceptionType(unsigned i) const {
3339 assert(i < NumExceptions && "Invalid exception number!");
3340 return exception_begin()[i];
3342 Expr *getNoexceptExpr() const {
3343 if (getExceptionSpecType() != EST_ComputedNoexcept)
3345 // NoexceptExpr sits where the arguments end.
3346 return *reinterpret_cast<Expr *const *>(param_type_end());
3348 /// \brief If this function type has an exception specification which hasn't
3349 /// been determined yet (either because it has not been evaluated or because
3350 /// it has not been instantiated), this is the function whose exception
3351 /// specification is represented by this type.
3352 FunctionDecl *getExceptionSpecDecl() const {
3353 if (getExceptionSpecType() != EST_Uninstantiated &&
3354 getExceptionSpecType() != EST_Unevaluated)
3356 return reinterpret_cast<FunctionDecl *const *>(param_type_end())[0];
3358 /// \brief If this function type has an uninstantiated exception
3359 /// specification, this is the function whose exception specification
3360 /// should be instantiated to find the exception specification for
3362 FunctionDecl *getExceptionSpecTemplate() const {
3363 if (getExceptionSpecType() != EST_Uninstantiated)
3365 return reinterpret_cast<FunctionDecl *const *>(param_type_end())[1];
3367 /// Determine whether this function type has a non-throwing exception
3369 CanThrowResult canThrow(const ASTContext &Ctx) const;
3370 /// Determine whether this function type has a non-throwing exception
3371 /// specification. If this depends on template arguments, returns
3372 /// \c ResultIfDependent.
3373 bool isNothrow(const ASTContext &Ctx, bool ResultIfDependent = false) const {
3374 return ResultIfDependent ? canThrow(Ctx) != CT_Can
3375 : canThrow(Ctx) == CT_Cannot;
3378 bool isVariadic() const { return Variadic; }
3380 /// Determines whether this function prototype contains a
3381 /// parameter pack at the end.
3383 /// A function template whose last parameter is a parameter pack can be
3384 /// called with an arbitrary number of arguments, much like a variadic
3386 bool isTemplateVariadic() const;
3388 bool hasTrailingReturn() const { return HasTrailingReturn; }
3390 unsigned getTypeQuals() const { return FunctionType::getTypeQuals(); }
3393 /// Retrieve the ref-qualifier associated with this function type.
3394 RefQualifierKind getRefQualifier() const {
3395 return static_cast<RefQualifierKind>(FunctionTypeBits.RefQualifier);
3398 typedef const QualType *param_type_iterator;
3399 typedef llvm::iterator_range<param_type_iterator> param_type_range;
3401 param_type_range param_types() const {
3402 return param_type_range(param_type_begin(), param_type_end());
3404 param_type_iterator param_type_begin() const {
3405 return reinterpret_cast<const QualType *>(this+1);
3407 param_type_iterator param_type_end() const {
3408 return param_type_begin() + NumParams;
3411 typedef const QualType *exception_iterator;
3413 ArrayRef<QualType> exceptions() const {
3414 return llvm::makeArrayRef(exception_begin(), exception_end());
3416 exception_iterator exception_begin() const {
3417 // exceptions begin where arguments end
3418 return param_type_end();
3420 exception_iterator exception_end() const {
3421 if (getExceptionSpecType() != EST_Dynamic)
3422 return exception_begin();
3423 return exception_begin() + NumExceptions;
3426 /// Is there any interesting extra information for any of the parameters
3427 /// of this function type?
3428 bool hasExtParameterInfos() const { return HasExtParameterInfos; }
3429 ArrayRef<ExtParameterInfo> getExtParameterInfos() const {
3430 assert(hasExtParameterInfos());
3431 return ArrayRef<ExtParameterInfo>(getExtParameterInfosBuffer(),
3434 /// Return a pointer to the beginning of the array of extra parameter
3435 /// information, if present, or else null if none of the parameters
3436 /// carry it. This is equivalent to getExtProtoInfo().ExtParameterInfos.
3437 const ExtParameterInfo *getExtParameterInfosOrNull() const {
3438 if (!hasExtParameterInfos())
3440 return getExtParameterInfosBuffer();
3443 ExtParameterInfo getExtParameterInfo(unsigned I) const {
3444 assert(I < getNumParams() && "parameter index out of range");
3445 if (hasExtParameterInfos())
3446 return getExtParameterInfosBuffer()[I];
3447 return ExtParameterInfo();
3450 ParameterABI getParameterABI(unsigned I) const {
3451 assert(I < getNumParams() && "parameter index out of range");
3452 if (hasExtParameterInfos())
3453 return getExtParameterInfosBuffer()[I].getABI();
3454 return ParameterABI::Ordinary;
3457 bool isParamConsumed(unsigned I) const {
3458 assert(I < getNumParams() && "parameter index out of range");
3459 if (hasExtParameterInfos())
3460 return getExtParameterInfosBuffer()[I].isConsumed();
3464 bool isSugared() const { return false; }
3465 QualType desugar() const { return QualType(this, 0); }
3467 void printExceptionSpecification(raw_ostream &OS,
3468 const PrintingPolicy &Policy) const;
3470 static bool classof(const Type *T) {
3471 return T->getTypeClass() == FunctionProto;
3474 void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Ctx);
3475 static void Profile(llvm::FoldingSetNodeID &ID, QualType Result,
3476 param_type_iterator ArgTys, unsigned NumArgs,
3477 const ExtProtoInfo &EPI, const ASTContext &Context,
3481 /// \brief Represents the dependent type named by a dependently-scoped
3482 /// typename using declaration, e.g.
3483 /// using typename Base<T>::foo;
3485 /// Template instantiation turns these into the underlying type.
3486 class UnresolvedUsingType : public Type {
3487 UnresolvedUsingTypenameDecl *Decl;
3489 UnresolvedUsingType(const UnresolvedUsingTypenameDecl *D)
3490 : Type(UnresolvedUsing, QualType(), true, true, false,
3491 /*ContainsUnexpandedParameterPack=*/false),
3492 Decl(const_cast<UnresolvedUsingTypenameDecl*>(D)) {}
3493 friend class ASTContext; // ASTContext creates these.
3496 UnresolvedUsingTypenameDecl *getDecl() const { return Decl; }
3498 bool isSugared() const { return false; }
3499 QualType desugar() const { return QualType(this, 0); }
3501 static bool classof(const Type *T) {
3502 return T->getTypeClass() == UnresolvedUsing;
3505 void Profile(llvm::FoldingSetNodeID &ID) {
3506 return Profile(ID, Decl);
3508 static void Profile(llvm::FoldingSetNodeID &ID,
3509 UnresolvedUsingTypenameDecl *D) {
3515 class TypedefType : public Type {
3516 TypedefNameDecl *Decl;
3518 TypedefType(TypeClass tc, const TypedefNameDecl *D, QualType can)
3519 : Type(tc, can, can->isDependentType(),
3520 can->isInstantiationDependentType(),
3521 can->isVariablyModifiedType(),
3522 /*ContainsUnexpandedParameterPack=*/false),
3523 Decl(const_cast<TypedefNameDecl*>(D)) {
3524 assert(!isa<TypedefType>(can) && "Invalid canonical type");
3526 friend class ASTContext; // ASTContext creates these.
3529 TypedefNameDecl *getDecl() const { return Decl; }
3531 bool isSugared() const { return true; }
3532 QualType desugar() const;
3534 static bool classof(const Type *T) { return T->getTypeClass() == Typedef; }
3537 /// Represents a `typeof` (or __typeof__) expression (a GCC extension).
3538 class TypeOfExprType : public Type {
3542 TypeOfExprType(Expr *E, QualType can = QualType());
3543 friend class ASTContext; // ASTContext creates these.
3545 Expr *getUnderlyingExpr() const { return TOExpr; }
3547 /// \brief Remove a single level of sugar.
3548 QualType desugar() const;
3550 /// \brief Returns whether this type directly provides sugar.
3551 bool isSugared() const;
3553 static bool classof(const Type *T) { return T->getTypeClass() == TypeOfExpr; }
3556 /// \brief Internal representation of canonical, dependent
3557 /// `typeof(expr)` types.
3559 /// This class is used internally by the ASTContext to manage
3560 /// canonical, dependent types, only. Clients will only see instances
3561 /// of this class via TypeOfExprType nodes.
3562 class DependentTypeOfExprType
3563 : public TypeOfExprType, public llvm::FoldingSetNode {
3564 const ASTContext &Context;
3567 DependentTypeOfExprType(const ASTContext &Context, Expr *E)
3568 : TypeOfExprType(E), Context(Context) { }
3570 void Profile(llvm::FoldingSetNodeID &ID) {
3571 Profile(ID, Context, getUnderlyingExpr());
3574 static void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context,
3578 /// Represents `typeof(type)`, a GCC extension.
3579 class TypeOfType : public Type {
3581 TypeOfType(QualType T, QualType can)
3582 : Type(TypeOf, can, T->isDependentType(),
3583 T->isInstantiationDependentType(),
3584 T->isVariablyModifiedType(),
3585 T->containsUnexpandedParameterPack()),
3587 assert(!isa<TypedefType>(can) && "Invalid canonical type");
3589 friend class ASTContext; // ASTContext creates these.
3591 QualType getUnderlyingType() const { return TOType; }
3593 /// \brief Remove a single level of sugar.
3594 QualType desugar() const { return getUnderlyingType(); }
3596 /// \brief Returns whether this type directly provides sugar.
3597 bool isSugared() const { return true; }
3599 static bool classof(const Type *T) { return T->getTypeClass() == TypeOf; }
3602 /// Represents the type `decltype(expr)` (C++11).
3603 class DecltypeType : public Type {
3605 QualType UnderlyingType;
3608 DecltypeType(Expr *E, QualType underlyingType, QualType can = QualType());
3609 friend class ASTContext; // ASTContext creates these.
3611 Expr *getUnderlyingExpr() const { return E; }
3612 QualType getUnderlyingType() const { return UnderlyingType; }
3614 /// \brief Remove a single level of sugar.
3615 QualType desugar() const;
3617 /// \brief Returns whether this type directly provides sugar.
3618 bool isSugared() const;
3620 static bool classof(const Type *T) { return T->getTypeClass() == Decltype; }
3623 /// \brief Internal representation of canonical, dependent
3624 /// decltype(expr) types.
3626 /// This class is used internally by the ASTContext to manage
3627 /// canonical, dependent types, only. Clients will only see instances
3628 /// of this class via DecltypeType nodes.
3629 class DependentDecltypeType : public DecltypeType, public llvm::FoldingSetNode {
3630 const ASTContext &Context;
3633 DependentDecltypeType(const ASTContext &Context, Expr *E);
3635 void Profile(llvm::FoldingSetNodeID &ID) {
3636 Profile(ID, Context, getUnderlyingExpr());
3639 static void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context,
3643 /// A unary type transform, which is a type constructed from another.
3644 class UnaryTransformType : public Type {
3651 /// The untransformed type.
3653 /// The transformed type if not dependent, otherwise the same as BaseType.
3654 QualType UnderlyingType;
3658 UnaryTransformType(QualType BaseTy, QualType UnderlyingTy, UTTKind UKind,
3659 QualType CanonicalTy);
3660 friend class ASTContext;
3662 bool isSugared() const { return !isDependentType(); }
3663 QualType desugar() const { return UnderlyingType; }
3665 QualType getUnderlyingType() const { return UnderlyingType; }
3666 QualType getBaseType() const { return BaseType; }
3668 UTTKind getUTTKind() const { return UKind; }
3670 static bool classof(const Type *T) {
3671 return T->getTypeClass() == UnaryTransform;
3675 /// \brief Internal representation of canonical, dependent
3676 /// __underlying_type(type) types.
3678 /// This class is used internally by the ASTContext to manage
3679 /// canonical, dependent types, only. Clients will only see instances
3680 /// of this class via UnaryTransformType nodes.
3681 class DependentUnaryTransformType : public UnaryTransformType,
3682 public llvm::FoldingSetNode {
3684 DependentUnaryTransformType(const ASTContext &C, QualType BaseType,
3686 void Profile(llvm::FoldingSetNodeID &ID) {
3687 Profile(ID, getBaseType(), getUTTKind());
3690 static void Profile(llvm::FoldingSetNodeID &ID, QualType BaseType,
3692 ID.AddPointer(BaseType.getAsOpaquePtr());
3693 ID.AddInteger((unsigned)UKind);
3697 class TagType : public Type {
3698 /// Stores the TagDecl associated with this type. The decl may point to any
3699 /// TagDecl that declares the entity.
3702 friend class ASTReader;
3705 TagType(TypeClass TC, const TagDecl *D, QualType can);
3708 TagDecl *getDecl() const;
3710 /// Determines whether this type is in the process of being defined.
3711 bool isBeingDefined() const;
3713 static bool classof(const Type *T) {
3714 return T->getTypeClass() >= TagFirst && T->getTypeClass() <= TagLast;
3718 /// A helper class that allows the use of isa/cast/dyncast
3719 /// to detect TagType objects of structs/unions/classes.
3720 class RecordType : public TagType {
3722 explicit RecordType(const RecordDecl *D)
3723 : TagType(Record, reinterpret_cast<const TagDecl*>(D), QualType()) { }
3724 explicit RecordType(TypeClass TC, RecordDecl *D)
3725 : TagType(TC, reinterpret_cast<const TagDecl*>(D), QualType()) { }
3726 friend class ASTContext; // ASTContext creates these.
3729 RecordDecl *getDecl() const {
3730 return reinterpret_cast<RecordDecl*>(TagType::getDecl());
3733 // FIXME: This predicate is a helper to QualType/Type. It needs to
3734 // recursively check all fields for const-ness. If any field is declared
3735 // const, it needs to return false.
3736 bool hasConstFields() const { return false; }
3738 bool isSugared() const { return false; }
3739 QualType desugar() const { return QualType(this, 0); }
3741 static bool classof(const Type *T) { return T->getTypeClass() == Record; }
3744 /// A helper class that allows the use of isa/cast/dyncast
3745 /// to detect TagType objects of enums.
3746 class EnumType : public TagType {
3747 explicit EnumType(const EnumDecl *D)
3748 : TagType(Enum, reinterpret_cast<const TagDecl*>(D), QualType()) { }
3749 friend class ASTContext; // ASTContext creates these.
3752 EnumDecl *getDecl() const {
3753 return reinterpret_cast<EnumDecl*>(TagType::getDecl());
3756 bool isSugared() const { return false; }
3757 QualType desugar() const { return QualType(this, 0); }
3759 static bool classof(const Type *T) { return T->getTypeClass() == Enum; }
3762 /// An attributed type is a type to which a type attribute has been applied.
3764 /// The "modified type" is the fully-sugared type to which the attributed
3765 /// type was applied; generally it is not canonically equivalent to the
3766 /// attributed type. The "equivalent type" is the minimally-desugared type
3767 /// which the type is canonically equivalent to.
3769 /// For example, in the following attributed type:
3770 /// int32_t __attribute__((vector_size(16)))
3771 /// - the modified type is the TypedefType for int32_t
3772 /// - the equivalent type is VectorType(16, int32_t)
3773 /// - the canonical type is VectorType(16, int)
3774 class AttributedType : public Type, public llvm::FoldingSetNode {
3776 // It is really silly to have yet another attribute-kind enum, but
3777 // clang::attr::Kind doesn't currently cover the pure type attrs.
3779 // Expression operand.
3783 attr_neon_vector_type,
3784 attr_neon_polyvector_type,
3786 FirstExprOperandKind = attr_address_space,
3787 LastExprOperandKind = attr_neon_polyvector_type,
3789 // Enumerated operand (string or keyword).
3791 attr_objc_ownership,
3795 FirstEnumOperandKind = attr_objc_gc,
3796 LastEnumOperandKind = attr_pcs_vfp,
3819 attr_null_unspecified,
3821 attr_objc_inert_unsafe_unretained,
3825 QualType ModifiedType;
3826 QualType EquivalentType;
3828 friend class ASTContext; // creates these
3830 AttributedType(QualType canon, Kind attrKind,
3831 QualType modified, QualType equivalent)
3832 : Type(Attributed, canon, canon->isDependentType(),
3833 canon->isInstantiationDependentType(),
3834 canon->isVariablyModifiedType(),
3835 canon->containsUnexpandedParameterPack()),
3836 ModifiedType(modified), EquivalentType(equivalent) {
3837 AttributedTypeBits.AttrKind = attrKind;
3841 Kind getAttrKind() const {
3842 return static_cast<Kind>(AttributedTypeBits.AttrKind);
3845 QualType getModifiedType() const { return ModifiedType; }
3846 QualType getEquivalentType() const { return EquivalentType; }
3848 bool isSugared() const { return true; }
3849 QualType desugar() const { return getEquivalentType(); }
3851 /// Does this attribute behave like a type qualifier?
3853 /// A type qualifier adjusts a type to provide specialized rules for
3854 /// a specific object, like the standard const and volatile qualifiers.
3855 /// This includes attributes controlling things like nullability,
3856 /// address spaces, and ARC ownership. The value of the object is still
3857 /// largely described by the modified type.
3859 /// In contrast, many type attributes "rewrite" their modified type to
3860 /// produce a fundamentally different type, not necessarily related in any
3861 /// formalizable way to the original type. For example, calling convention
3862 /// and vector attributes are not simple type qualifiers.
3864 /// Type qualifiers are often, but not always, reflected in the canonical
3866 bool isQualifier() const;
3868 bool isMSTypeSpec() const;
3870 bool isCallingConv() const;
3872 llvm::Optional<NullabilityKind> getImmediateNullability() const;
3874 /// Retrieve the attribute kind corresponding to the given
3875 /// nullability kind.
3876 static Kind getNullabilityAttrKind(NullabilityKind kind) {
3878 case NullabilityKind::NonNull:
3879 return attr_nonnull;
3881 case NullabilityKind::Nullable:
3882 return attr_nullable;
3884 case NullabilityKind::Unspecified:
3885 return attr_null_unspecified;
3887 llvm_unreachable("Unknown nullability kind.");
3890 /// Strip off the top-level nullability annotation on the given
3891 /// type, if it's there.
3893 /// \param T The type to strip. If the type is exactly an
3894 /// AttributedType specifying nullability (without looking through
3895 /// type sugar), the nullability is returned and this type changed
3896 /// to the underlying modified type.
3898 /// \returns the top-level nullability, if present.
3899 static Optional<NullabilityKind> stripOuterNullability(QualType &T);
3901 void Profile(llvm::FoldingSetNodeID &ID) {
3902 Profile(ID, getAttrKind(), ModifiedType, EquivalentType);
3905 static void Profile(llvm::FoldingSetNodeID &ID, Kind attrKind,
3906 QualType modified, QualType equivalent) {
3907 ID.AddInteger(attrKind);
3908 ID.AddPointer(modified.getAsOpaquePtr());
3909 ID.AddPointer(equivalent.getAsOpaquePtr());
3912 static bool classof(const Type *T) {
3913 return T->getTypeClass() == Attributed;
3917 class TemplateTypeParmType : public Type, public llvm::FoldingSetNode {
3918 // Helper data collector for canonical types.
3919 struct CanonicalTTPTInfo {
3920 unsigned Depth : 15;
3921 unsigned ParameterPack : 1;
3922 unsigned Index : 16;
3926 // Info for the canonical type.
3927 CanonicalTTPTInfo CanTTPTInfo;
3928 // Info for the non-canonical type.
3929 TemplateTypeParmDecl *TTPDecl;
3932 /// Build a non-canonical type.
3933 TemplateTypeParmType(TemplateTypeParmDecl *TTPDecl, QualType Canon)
3934 : Type(TemplateTypeParm, Canon, /*Dependent=*/true,
3935 /*InstantiationDependent=*/true,
3936 /*VariablyModified=*/false,
3937 Canon->containsUnexpandedParameterPack()),
3938 TTPDecl(TTPDecl) { }
3940 /// Build the canonical type.
3941 TemplateTypeParmType(unsigned D, unsigned I, bool PP)
3942 : Type(TemplateTypeParm, QualType(this, 0),
3944 /*InstantiationDependent=*/true,
3945 /*VariablyModified=*/false, PP) {
3946 CanTTPTInfo.Depth = D;
3947 CanTTPTInfo.Index = I;
3948 CanTTPTInfo.ParameterPack = PP;
3951 friend class ASTContext; // ASTContext creates these
3953 const CanonicalTTPTInfo& getCanTTPTInfo() const {
3954 QualType Can = getCanonicalTypeInternal();
3955 return Can->castAs<TemplateTypeParmType>()->CanTTPTInfo;
3959 unsigned getDepth() const { return getCanTTPTInfo().Depth; }
3960 unsigned getIndex() const { return getCanTTPTInfo().Index; }
3961 bool isParameterPack() const { return getCanTTPTInfo().ParameterPack; }
3963 TemplateTypeParmDecl *getDecl() const {
3964 return isCanonicalUnqualified() ? nullptr : TTPDecl;
3967 IdentifierInfo *getIdentifier() const;
3969 bool isSugared() const { return false; }
3970 QualType desugar() const { return QualType(this, 0); }
3972 void Profile(llvm::FoldingSetNodeID &ID) {
3973 Profile(ID, getDepth(), getIndex(), isParameterPack(), getDecl());
3976 static void Profile(llvm::FoldingSetNodeID &ID, unsigned Depth,
3977 unsigned Index, bool ParameterPack,
3978 TemplateTypeParmDecl *TTPDecl) {
3979 ID.AddInteger(Depth);
3980 ID.AddInteger(Index);
3981 ID.AddBoolean(ParameterPack);
3982 ID.AddPointer(TTPDecl);
3985 static bool classof(const Type *T) {
3986 return T->getTypeClass() == TemplateTypeParm;
3990 /// \brief Represents the result of substituting a type for a template
3993 /// Within an instantiated template, all template type parameters have
3994 /// been replaced with these. They are used solely to record that a
3995 /// type was originally written as a template type parameter;
3996 /// therefore they are never canonical.
3997 class SubstTemplateTypeParmType : public Type, public llvm::FoldingSetNode {
3998 // The original type parameter.
3999 const TemplateTypeParmType *Replaced;
4001 SubstTemplateTypeParmType(const TemplateTypeParmType *Param, QualType Canon)
4002 : Type(SubstTemplateTypeParm, Canon, Canon->isDependentType(),
4003 Canon->isInstantiationDependentType(),
4004 Canon->isVariablyModifiedType(),
4005 Canon->containsUnexpandedParameterPack()),
4008 friend class ASTContext;
4011 /// Gets the template parameter that was substituted for.
4012 const TemplateTypeParmType *getReplacedParameter() const {
4016 /// Gets the type that was substituted for the template
4018 QualType getReplacementType() const {
4019 return getCanonicalTypeInternal();
4022 bool isSugared() const { return true; }
4023 QualType desugar() const { return getReplacementType(); }
4025 void Profile(llvm::FoldingSetNodeID &ID) {
4026 Profile(ID, getReplacedParameter(), getReplacementType());
4028 static void Profile(llvm::FoldingSetNodeID &ID,
4029 const TemplateTypeParmType *Replaced,
4030 QualType Replacement) {
4031 ID.AddPointer(Replaced);
4032 ID.AddPointer(Replacement.getAsOpaquePtr());
4035 static bool classof(const Type *T) {
4036 return T->getTypeClass() == SubstTemplateTypeParm;
4040 /// \brief Represents the result of substituting a set of types for a template
4041 /// type parameter pack.
4043 /// When a pack expansion in the source code contains multiple parameter packs
4044 /// and those parameter packs correspond to different levels of template
4045 /// parameter lists, this type node is used to represent a template type
4046 /// parameter pack from an outer level, which has already had its argument pack
4047 /// substituted but that still lives within a pack expansion that itself
4048 /// could not be instantiated. When actually performing a substitution into
4049 /// that pack expansion (e.g., when all template parameters have corresponding
4050 /// arguments), this type will be replaced with the \c SubstTemplateTypeParmType
4051 /// at the current pack substitution index.
4052 class SubstTemplateTypeParmPackType : public Type, public llvm::FoldingSetNode {
4053 /// \brief The original type parameter.
4054 const TemplateTypeParmType *Replaced;
4056 /// \brief A pointer to the set of template arguments that this
4057 /// parameter pack is instantiated with.
4058 const TemplateArgument *Arguments;
4060 /// \brief The number of template arguments in \c Arguments.
4061 unsigned NumArguments;
4063 SubstTemplateTypeParmPackType(const TemplateTypeParmType *Param,
4065 const TemplateArgument &ArgPack);
4067 friend class ASTContext;
4070 IdentifierInfo *getIdentifier() const { return Replaced->getIdentifier(); }
4072 /// Gets the template parameter that was substituted for.
4073 const TemplateTypeParmType *getReplacedParameter() const {
4077 bool isSugared() const { return false; }
4078 QualType desugar() const { return QualType(this, 0); }
4080 TemplateArgument getArgumentPack() const;
4082 void Profile(llvm::FoldingSetNodeID &ID);
4083 static void Profile(llvm::FoldingSetNodeID &ID,
4084 const TemplateTypeParmType *Replaced,
4085 const TemplateArgument &ArgPack);
4087 static bool classof(const Type *T) {
4088 return T->getTypeClass() == SubstTemplateTypeParmPack;
4092 /// \brief Represents a C++11 auto or C++14 decltype(auto) type.
4094 /// These types are usually a placeholder for a deduced type. However, before
4095 /// the initializer is attached, or (usually) if the initializer is
4096 /// type-dependent, there is no deduced type and an auto type is canonical. In
4097 /// the latter case, it is also a dependent type.
4098 class AutoType : public Type, public llvm::FoldingSetNode {
4099 AutoType(QualType DeducedType, AutoTypeKeyword Keyword, bool IsDependent)
4100 : Type(Auto, DeducedType.isNull() ? QualType(this, 0) : DeducedType,
4101 /*Dependent=*/IsDependent, /*InstantiationDependent=*/IsDependent,
4102 /*VariablyModified=*/false, /*ContainsParameterPack=*/false) {
4103 if (!DeducedType.isNull()) {
4104 if (DeducedType->isDependentType())
4106 if (DeducedType->isInstantiationDependentType())
4107 setInstantiationDependent();
4108 if (DeducedType->containsUnexpandedParameterPack())
4109 setContainsUnexpandedParameterPack();
4111 AutoTypeBits.Keyword = (unsigned)Keyword;
4114 friend class ASTContext; // ASTContext creates these
4117 bool isDecltypeAuto() const {
4118 return getKeyword() == AutoTypeKeyword::DecltypeAuto;
4120 AutoTypeKeyword getKeyword() const {
4121 return (AutoTypeKeyword)AutoTypeBits.Keyword;
4124 bool isSugared() const { return !isCanonicalUnqualified(); }
4125 QualType desugar() const { return getCanonicalTypeInternal(); }
4127 /// \brief Get the type deduced for this auto type, or null if it's either
4128 /// not been deduced or was deduced to a dependent type.
4129 QualType getDeducedType() const {
4130 return !isCanonicalUnqualified() ? getCanonicalTypeInternal() : QualType();
4132 bool isDeduced() const {
4133 return !isCanonicalUnqualified() || isDependentType();
4136 void Profile(llvm::FoldingSetNodeID &ID) {
4137 Profile(ID, getDeducedType(), getKeyword(), isDependentType());
4140 static void Profile(llvm::FoldingSetNodeID &ID, QualType Deduced,
4141 AutoTypeKeyword Keyword, bool IsDependent) {
4142 ID.AddPointer(Deduced.getAsOpaquePtr());
4143 ID.AddInteger((unsigned)Keyword);
4144 ID.AddBoolean(IsDependent);
4147 static bool classof(const Type *T) {
4148 return T->getTypeClass() == Auto;
4152 /// \brief Represents a type template specialization; the template
4153 /// must be a class template, a type alias template, or a template
4154 /// template parameter. A template which cannot be resolved to one of
4155 /// these, e.g. because it is written with a dependent scope
4156 /// specifier, is instead represented as a
4157 /// @c DependentTemplateSpecializationType.
4159 /// A non-dependent template specialization type is always "sugar",
4160 /// typically for a \c RecordType. For example, a class template
4161 /// specialization type of \c vector<int> will refer to a tag type for
4162 /// the instantiation \c std::vector<int, std::allocator<int>>
4164 /// Template specializations are dependent if either the template or
4165 /// any of the template arguments are dependent, in which case the
4166 /// type may also be canonical.
4168 /// Instances of this type are allocated with a trailing array of
4169 /// TemplateArguments, followed by a QualType representing the
4170 /// non-canonical aliased type when the template is a type alias
4172 class LLVM_ALIGNAS(/*alignof(uint64_t)*/ 8) TemplateSpecializationType
4174 public llvm::FoldingSetNode {
4175 /// The name of the template being specialized. This is
4176 /// either a TemplateName::Template (in which case it is a
4177 /// ClassTemplateDecl*, a TemplateTemplateParmDecl*, or a
4178 /// TypeAliasTemplateDecl*), a
4179 /// TemplateName::SubstTemplateTemplateParmPack, or a
4180 /// TemplateName::SubstTemplateTemplateParm (in which case the
4181 /// replacement must, recursively, be one of these).
4182 TemplateName Template;
4184 /// The number of template arguments named in this class template
4186 unsigned NumArgs : 31;
4188 /// Whether this template specialization type is a substituted type alias.
4189 unsigned TypeAlias : 1;
4191 TemplateSpecializationType(TemplateName T,
4192 ArrayRef<TemplateArgument> Args,
4196 friend class ASTContext; // ASTContext creates these
4199 /// Determine whether any of the given template arguments are dependent.
4200 static bool anyDependentTemplateArguments(ArrayRef<TemplateArgumentLoc> Args,
4201 bool &InstantiationDependent);
4203 static bool anyDependentTemplateArguments(const TemplateArgumentListInfo &,
4204 bool &InstantiationDependent);
4206 /// \brief Print a template argument list, including the '<' and '>'
4207 /// enclosing the template arguments.
4208 static void PrintTemplateArgumentList(raw_ostream &OS,
4209 ArrayRef<TemplateArgument> Args,
4210 const PrintingPolicy &Policy,
4211 bool SkipBrackets = false);
4213 static void PrintTemplateArgumentList(raw_ostream &OS,
4214 ArrayRef<TemplateArgumentLoc> Args,
4215 const PrintingPolicy &Policy);
4217 static void PrintTemplateArgumentList(raw_ostream &OS,
4218 const TemplateArgumentListInfo &,
4219 const PrintingPolicy &Policy);
4221 /// True if this template specialization type matches a current
4222 /// instantiation in the context in which it is found.
4223 bool isCurrentInstantiation() const {
4224 return isa<InjectedClassNameType>(getCanonicalTypeInternal());
4227 /// \brief Determine if this template specialization type is for a type alias
4228 /// template that has been substituted.
4230 /// Nearly every template specialization type whose template is an alias
4231 /// template will be substituted. However, this is not the case when
4232 /// the specialization contains a pack expansion but the template alias
4233 /// does not have a corresponding parameter pack, e.g.,
4236 /// template<typename T, typename U, typename V> struct S;
4237 /// template<typename T, typename U> using A = S<T, int, U>;
4238 /// template<typename... Ts> struct X {
4239 /// typedef A<Ts...> type; // not a type alias
4242 bool isTypeAlias() const { return TypeAlias; }
4244 /// Get the aliased type, if this is a specialization of a type alias
4246 QualType getAliasedType() const {
4247 assert(isTypeAlias() && "not a type alias template specialization");
4248 return *reinterpret_cast<const QualType*>(end());
4251 typedef const TemplateArgument * iterator;
4253 iterator begin() const { return getArgs(); }
4254 iterator end() const; // defined inline in TemplateBase.h
4256 /// Retrieve the name of the template that we are specializing.
4257 TemplateName getTemplateName() const { return Template; }
4259 /// Retrieve the template arguments.
4260 const TemplateArgument *getArgs() const {
4261 return reinterpret_cast<const TemplateArgument *>(this + 1);
4264 /// Retrieve the number of template arguments.
4265 unsigned getNumArgs() const { return NumArgs; }
4267 /// Retrieve a specific template argument as a type.
4268 /// \pre \c isArgType(Arg)
4269 const TemplateArgument &getArg(unsigned Idx) const; // in TemplateBase.h
4271 ArrayRef<TemplateArgument> template_arguments() const {
4272 return {getArgs(), NumArgs};
4275 bool isSugared() const {
4276 return !isDependentType() || isCurrentInstantiation() || isTypeAlias();
4278 QualType desugar() const { return getCanonicalTypeInternal(); }
4280 void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Ctx) {
4281 Profile(ID, Template, template_arguments(), Ctx);
4283 getAliasedType().Profile(ID);
4286 static void Profile(llvm::FoldingSetNodeID &ID, TemplateName T,
4287 ArrayRef<TemplateArgument> Args,
4288 const ASTContext &Context);
4290 static bool classof(const Type *T) {
4291 return T->getTypeClass() == TemplateSpecialization;
4295 /// The injected class name of a C++ class template or class
4296 /// template partial specialization. Used to record that a type was
4297 /// spelled with a bare identifier rather than as a template-id; the
4298 /// equivalent for non-templated classes is just RecordType.
4300 /// Injected class name types are always dependent. Template
4301 /// instantiation turns these into RecordTypes.
4303 /// Injected class name types are always canonical. This works
4304 /// because it is impossible to compare an injected class name type
4305 /// with the corresponding non-injected template type, for the same
4306 /// reason that it is impossible to directly compare template
4307 /// parameters from different dependent contexts: injected class name
4308 /// types can only occur within the scope of a particular templated
4309 /// declaration, and within that scope every template specialization
4310 /// will canonicalize to the injected class name (when appropriate
4311 /// according to the rules of the language).
4312 class InjectedClassNameType : public Type {
4313 CXXRecordDecl *Decl;
4315 /// The template specialization which this type represents.
4317 /// template <class T> class A { ... };
4318 /// this is A<T>, whereas in
4319 /// template <class X, class Y> class A<B<X,Y> > { ... };
4320 /// this is A<B<X,Y> >.
4322 /// It is always unqualified, always a template specialization type,
4323 /// and always dependent.
4324 QualType InjectedType;
4326 friend class ASTContext; // ASTContext creates these.
4327 friend class ASTReader; // FIXME: ASTContext::getInjectedClassNameType is not
4328 // currently suitable for AST reading, too much
4329 // interdependencies.
4330 friend class ASTNodeImporter;
4332 InjectedClassNameType(CXXRecordDecl *D, QualType TST)
4333 : Type(InjectedClassName, QualType(), /*Dependent=*/true,
4334 /*InstantiationDependent=*/true,
4335 /*VariablyModified=*/false,
4336 /*ContainsUnexpandedParameterPack=*/false),
4337 Decl(D), InjectedType(TST) {
4338 assert(isa<TemplateSpecializationType>(TST));
4339 assert(!TST.hasQualifiers());
4340 assert(TST->isDependentType());
4344 QualType getInjectedSpecializationType() const { return InjectedType; }
4345 const TemplateSpecializationType *getInjectedTST() const {
4346 return cast<TemplateSpecializationType>(InjectedType.getTypePtr());
4349 CXXRecordDecl *getDecl() const;
4351 bool isSugared() const { return false; }
4352 QualType desugar() const { return QualType(this, 0); }
4354 static bool classof(const Type *T) {
4355 return T->getTypeClass() == InjectedClassName;
4359 /// \brief The kind of a tag type.
4361 /// \brief The "struct" keyword.
4363 /// \brief The "__interface" keyword.
4365 /// \brief The "union" keyword.
4367 /// \brief The "class" keyword.
4369 /// \brief The "enum" keyword.
4373 /// \brief The elaboration keyword that precedes a qualified type name or
4374 /// introduces an elaborated-type-specifier.
4375 enum ElaboratedTypeKeyword {
4376 /// \brief The "struct" keyword introduces the elaborated-type-specifier.
4378 /// \brief The "__interface" keyword introduces the elaborated-type-specifier.
4380 /// \brief The "union" keyword introduces the elaborated-type-specifier.
4382 /// \brief The "class" keyword introduces the elaborated-type-specifier.
4384 /// \brief The "enum" keyword introduces the elaborated-type-specifier.
4386 /// \brief The "typename" keyword precedes the qualified type name, e.g.,
4387 /// \c typename T::type.
4389 /// \brief No keyword precedes the qualified type name.
4393 /// A helper class for Type nodes having an ElaboratedTypeKeyword.
4394 /// The keyword in stored in the free bits of the base class.
4395 /// Also provides a few static helpers for converting and printing
4396 /// elaborated type keyword and tag type kind enumerations.
4397 class TypeWithKeyword : public Type {
4399 TypeWithKeyword(ElaboratedTypeKeyword Keyword, TypeClass tc,
4400 QualType Canonical, bool Dependent,
4401 bool InstantiationDependent, bool VariablyModified,
4402 bool ContainsUnexpandedParameterPack)
4403 : Type(tc, Canonical, Dependent, InstantiationDependent, VariablyModified,
4404 ContainsUnexpandedParameterPack) {
4405 TypeWithKeywordBits.Keyword = Keyword;
4409 ElaboratedTypeKeyword getKeyword() const {
4410 return static_cast<ElaboratedTypeKeyword>(TypeWithKeywordBits.Keyword);
4413 /// Converts a type specifier (DeclSpec::TST) into an elaborated type keyword.
4414 static ElaboratedTypeKeyword getKeywordForTypeSpec(unsigned TypeSpec);
4416 /// Converts a type specifier (DeclSpec::TST) into a tag type kind.
4417 /// It is an error to provide a type specifier which *isn't* a tag kind here.
4418 static TagTypeKind getTagTypeKindForTypeSpec(unsigned TypeSpec);
4420 /// Converts a TagTypeKind into an elaborated type keyword.
4421 static ElaboratedTypeKeyword getKeywordForTagTypeKind(TagTypeKind Tag);
4423 /// Converts an elaborated type keyword into a TagTypeKind.
4424 /// It is an error to provide an elaborated type keyword
4425 /// which *isn't* a tag kind here.
4426 static TagTypeKind getTagTypeKindForKeyword(ElaboratedTypeKeyword Keyword);
4428 static bool KeywordIsTagTypeKind(ElaboratedTypeKeyword Keyword);
4430 static StringRef getKeywordName(ElaboratedTypeKeyword Keyword);
4432 static StringRef getTagTypeKindName(TagTypeKind Kind) {
4433 return getKeywordName(getKeywordForTagTypeKind(Kind));
4436 class CannotCastToThisType {};
4437 static CannotCastToThisType classof(const Type *);
4440 /// \brief Represents a type that was referred to using an elaborated type
4441 /// keyword, e.g., struct S, or via a qualified name, e.g., N::M::type,
4444 /// This type is used to keep track of a type name as written in the
4445 /// source code, including tag keywords and any nested-name-specifiers.
4446 /// The type itself is always "sugar", used to express what was written
4447 /// in the source code but containing no additional semantic information.
4448 class ElaboratedType : public TypeWithKeyword, public llvm::FoldingSetNode {
4450 /// The nested name specifier containing the qualifier.
4451 NestedNameSpecifier *NNS;
4453 /// The type that this qualified name refers to.
4456 ElaboratedType(ElaboratedTypeKeyword Keyword, NestedNameSpecifier *NNS,
4457 QualType NamedType, QualType CanonType)
4458 : TypeWithKeyword(Keyword, Elaborated, CanonType,
4459 NamedType->isDependentType(),
4460 NamedType->isInstantiationDependentType(),
4461 NamedType->isVariablyModifiedType(),
4462 NamedType->containsUnexpandedParameterPack()),
4463 NNS(NNS), NamedType(NamedType) {
4464 assert(!(Keyword == ETK_None && NNS == nullptr) &&
4465 "ElaboratedType cannot have elaborated type keyword "
4466 "and name qualifier both null.");
4469 friend class ASTContext; // ASTContext creates these
4474 /// Retrieve the qualification on this type.
4475 NestedNameSpecifier *getQualifier() const { return NNS; }
4477 /// Retrieve the type named by the qualified-id.
4478 QualType getNamedType() const { return NamedType; }
4480 /// Remove a single level of sugar.
4481 QualType desugar() const { return getNamedType(); }
4483 /// Returns whether this type directly provides sugar.
4484 bool isSugared() const { return true; }
4486 void Profile(llvm::FoldingSetNodeID &ID) {
4487 Profile(ID, getKeyword(), NNS, NamedType);
4490 static void Profile(llvm::FoldingSetNodeID &ID, ElaboratedTypeKeyword Keyword,
4491 NestedNameSpecifier *NNS, QualType NamedType) {
4492 ID.AddInteger(Keyword);
4494 NamedType.Profile(ID);
4497 static bool classof(const Type *T) {
4498 return T->getTypeClass() == Elaborated;
4502 /// \brief Represents a qualified type name for which the type name is
4505 /// DependentNameType represents a class of dependent types that involve a
4506 /// possibly dependent nested-name-specifier (e.g., "T::") followed by a
4507 /// name of a type. The DependentNameType may start with a "typename" (for a
4508 /// typename-specifier), "class", "struct", "union", or "enum" (for a
4509 /// dependent elaborated-type-specifier), or nothing (in contexts where we
4510 /// know that we must be referring to a type, e.g., in a base class specifier).
4511 /// Typically the nested-name-specifier is dependent, but in MSVC compatibility
4512 /// mode, this type is used with non-dependent names to delay name lookup until
4514 class DependentNameType : public TypeWithKeyword, public llvm::FoldingSetNode {
4516 /// \brief The nested name specifier containing the qualifier.
4517 NestedNameSpecifier *NNS;
4519 /// \brief The type that this typename specifier refers to.
4520 const IdentifierInfo *Name;
4522 DependentNameType(ElaboratedTypeKeyword Keyword, NestedNameSpecifier *NNS,
4523 const IdentifierInfo *Name, QualType CanonType)
4524 : TypeWithKeyword(Keyword, DependentName, CanonType, /*Dependent=*/true,
4525 /*InstantiationDependent=*/true,
4526 /*VariablyModified=*/false,
4527 NNS->containsUnexpandedParameterPack()),
4528 NNS(NNS), Name(Name) {}
4530 friend class ASTContext; // ASTContext creates these
4533 /// Retrieve the qualification on this type.
4534 NestedNameSpecifier *getQualifier() const { return NNS; }
4536 /// Retrieve the type named by the typename specifier as an identifier.
4538 /// This routine will return a non-NULL identifier pointer when the
4539 /// form of the original typename was terminated by an identifier,
4540 /// e.g., "typename T::type".
4541 const IdentifierInfo *getIdentifier() const {
4545 bool isSugared() const { return false; }
4546 QualType desugar() const { return QualType(this, 0); }
4548 void Profile(llvm::FoldingSetNodeID &ID) {
4549 Profile(ID, getKeyword(), NNS, Name);
4552 static void Profile(llvm::FoldingSetNodeID &ID, ElaboratedTypeKeyword Keyword,
4553 NestedNameSpecifier *NNS, const IdentifierInfo *Name) {
4554 ID.AddInteger(Keyword);
4556 ID.AddPointer(Name);
4559 static bool classof(const Type *T) {
4560 return T->getTypeClass() == DependentName;
4564 /// Represents a template specialization type whose template cannot be
4566 /// A<T>::template B<T>
4567 class LLVM_ALIGNAS(/*alignof(uint64_t)*/ 8) DependentTemplateSpecializationType
4568 : public TypeWithKeyword,
4569 public llvm::FoldingSetNode {
4571 /// The nested name specifier containing the qualifier.
4572 NestedNameSpecifier *NNS;
4574 /// The identifier of the template.
4575 const IdentifierInfo *Name;
4577 /// \brief The number of template arguments named in this class template
4581 const TemplateArgument *getArgBuffer() const {
4582 return reinterpret_cast<const TemplateArgument*>(this+1);
4584 TemplateArgument *getArgBuffer() {
4585 return reinterpret_cast<TemplateArgument*>(this+1);
4588 DependentTemplateSpecializationType(ElaboratedTypeKeyword Keyword,
4589 NestedNameSpecifier *NNS,
4590 const IdentifierInfo *Name,
4591 ArrayRef<TemplateArgument> Args,
4594 friend class ASTContext; // ASTContext creates these
4597 NestedNameSpecifier *getQualifier() const { return NNS; }
4598 const IdentifierInfo *getIdentifier() const { return Name; }
4600 /// \brief Retrieve the template arguments.
4601 const TemplateArgument *getArgs() const {
4602 return getArgBuffer();
4605 /// \brief Retrieve the number of template arguments.
4606 unsigned getNumArgs() const { return NumArgs; }
4608 const TemplateArgument &getArg(unsigned Idx) const; // in TemplateBase.h
4610 ArrayRef<TemplateArgument> template_arguments() const {
4611 return {getArgs(), NumArgs};
4614 typedef const TemplateArgument * iterator;
4615 iterator begin() const { return getArgs(); }
4616 iterator end() const; // inline in TemplateBase.h
4618 bool isSugared() const { return false; }
4619 QualType desugar() const { return QualType(this, 0); }
4621 void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context) {
4622 Profile(ID, Context, getKeyword(), NNS, Name, {getArgs(), NumArgs});
4625 static void Profile(llvm::FoldingSetNodeID &ID,
4626 const ASTContext &Context,
4627 ElaboratedTypeKeyword Keyword,
4628 NestedNameSpecifier *Qualifier,
4629 const IdentifierInfo *Name,
4630 ArrayRef<TemplateArgument> Args);
4632 static bool classof(const Type *T) {
4633 return T->getTypeClass() == DependentTemplateSpecialization;
4637 /// \brief Represents a pack expansion of types.
4639 /// Pack expansions are part of C++11 variadic templates. A pack
4640 /// expansion contains a pattern, which itself contains one or more
4641 /// "unexpanded" parameter packs. When instantiated, a pack expansion
4642 /// produces a series of types, each instantiated from the pattern of
4643 /// the expansion, where the Ith instantiation of the pattern uses the
4644 /// Ith arguments bound to each of the unexpanded parameter packs. The
4645 /// pack expansion is considered to "expand" these unexpanded
4646 /// parameter packs.
4649 /// template<typename ...Types> struct tuple;
4651 /// template<typename ...Types>
4652 /// struct tuple_of_references {
4653 /// typedef tuple<Types&...> type;
4657 /// Here, the pack expansion \c Types&... is represented via a
4658 /// PackExpansionType whose pattern is Types&.
4659 class PackExpansionType : public Type, public llvm::FoldingSetNode {
4660 /// \brief The pattern of the pack expansion.
4663 /// \brief The number of expansions that this pack expansion will
4664 /// generate when substituted (+1), or indicates that
4666 /// This field will only have a non-zero value when some of the parameter
4667 /// packs that occur within the pattern have been substituted but others have
4669 unsigned NumExpansions;
4671 PackExpansionType(QualType Pattern, QualType Canon,
4672 Optional<unsigned> NumExpansions)
4673 : Type(PackExpansion, Canon, /*Dependent=*/Pattern->isDependentType(),
4674 /*InstantiationDependent=*/true,
4675 /*VariablyModified=*/Pattern->isVariablyModifiedType(),
4676 /*ContainsUnexpandedParameterPack=*/false),
4678 NumExpansions(NumExpansions? *NumExpansions + 1: 0) { }
4680 friend class ASTContext; // ASTContext creates these
4683 /// \brief Retrieve the pattern of this pack expansion, which is the
4684 /// type that will be repeatedly instantiated when instantiating the
4685 /// pack expansion itself.
4686 QualType getPattern() const { return Pattern; }
4688 /// \brief Retrieve the number of expansions that this pack expansion will
4689 /// generate, if known.
4690 Optional<unsigned> getNumExpansions() const {
4692 return NumExpansions - 1;
4697 bool isSugared() const { return !Pattern->isDependentType(); }
4698 QualType desugar() const { return isSugared() ? Pattern : QualType(this, 0); }
4700 void Profile(llvm::FoldingSetNodeID &ID) {
4701 Profile(ID, getPattern(), getNumExpansions());
4704 static void Profile(llvm::FoldingSetNodeID &ID, QualType Pattern,
4705 Optional<unsigned> NumExpansions) {
4706 ID.AddPointer(Pattern.getAsOpaquePtr());
4707 ID.AddBoolean(NumExpansions.hasValue());
4709 ID.AddInteger(*NumExpansions);
4712 static bool classof(const Type *T) {
4713 return T->getTypeClass() == PackExpansion;
4717 /// This class wraps the list of protocol qualifiers. For types that can
4718 /// take ObjC protocol qualifers, they can subclass this class.
4720 class ObjCProtocolQualifiers {
4722 ObjCProtocolQualifiers() {}
4723 ObjCProtocolDecl * const *getProtocolStorage() const {
4724 return const_cast<ObjCProtocolQualifiers*>(this)->getProtocolStorage();
4727 ObjCProtocolDecl **getProtocolStorage() {
4728 return static_cast<T*>(this)->getProtocolStorageImpl();
4730 void setNumProtocols(unsigned N) {
4731 static_cast<T*>(this)->setNumProtocolsImpl(N);
4733 void initialize(ArrayRef<ObjCProtocolDecl *> protocols) {
4734 setNumProtocols(protocols.size());
4735 assert(getNumProtocols() == protocols.size() &&
4736 "bitfield overflow in protocol count");
4737 if (!protocols.empty())
4738 memcpy(getProtocolStorage(), protocols.data(),
4739 protocols.size() * sizeof(ObjCProtocolDecl*));
4743 typedef ObjCProtocolDecl * const *qual_iterator;
4744 typedef llvm::iterator_range<qual_iterator> qual_range;
4746 qual_range quals() const { return qual_range(qual_begin(), qual_end()); }
4747 qual_iterator qual_begin() const { return getProtocolStorage(); }
4748 qual_iterator qual_end() const { return qual_begin() + getNumProtocols(); }
4750 bool qual_empty() const { return getNumProtocols() == 0; }
4752 /// Return the number of qualifying protocols in this type, or 0 if
4754 unsigned getNumProtocols() const {
4755 return static_cast<const T*>(this)->getNumProtocolsImpl();
4758 /// Fetch a protocol by index.
4759 ObjCProtocolDecl *getProtocol(unsigned I) const {
4760 assert(I < getNumProtocols() && "Out-of-range protocol access");
4761 return qual_begin()[I];
4764 /// Retrieve all of the protocol qualifiers.
4765 ArrayRef<ObjCProtocolDecl *> getProtocols() const {
4766 return ArrayRef<ObjCProtocolDecl *>(qual_begin(), getNumProtocols());
4770 /// Represents a type parameter type in Objective C. It can take
4771 /// a list of protocols.
4772 class ObjCTypeParamType : public Type,
4773 public ObjCProtocolQualifiers<ObjCTypeParamType>,
4774 public llvm::FoldingSetNode {
4775 friend class ASTContext;
4776 friend class ObjCProtocolQualifiers<ObjCTypeParamType>;
4778 /// The number of protocols stored on this type.
4779 unsigned NumProtocols : 6;
4781 ObjCTypeParamDecl *OTPDecl;
4782 /// The protocols are stored after the ObjCTypeParamType node. In the
4783 /// canonical type, the list of protocols are sorted alphabetically
4785 ObjCProtocolDecl **getProtocolStorageImpl();
4786 /// Return the number of qualifying protocols in this interface type,
4787 /// or 0 if there are none.
4788 unsigned getNumProtocolsImpl() const {
4789 return NumProtocols;
4791 void setNumProtocolsImpl(unsigned N) {
4794 ObjCTypeParamType(const ObjCTypeParamDecl *D,
4796 ArrayRef<ObjCProtocolDecl *> protocols);
4798 bool isSugared() const { return true; }
4799 QualType desugar() const { return getCanonicalTypeInternal(); }
4801 static bool classof(const Type *T) {
4802 return T->getTypeClass() == ObjCTypeParam;
4805 void Profile(llvm::FoldingSetNodeID &ID);
4806 static void Profile(llvm::FoldingSetNodeID &ID,
4807 const ObjCTypeParamDecl *OTPDecl,
4808 ArrayRef<ObjCProtocolDecl *> protocols);
4810 ObjCTypeParamDecl *getDecl() const { return OTPDecl; }
4813 /// Represents a class type in Objective C.
4815 /// Every Objective C type is a combination of a base type, a set of
4816 /// type arguments (optional, for parameterized classes) and a list of
4819 /// Given the following declarations:
4825 /// 'C' is an ObjCInterfaceType C. It is sugar for an ObjCObjectType
4826 /// with base C and no protocols.
4828 /// 'C<P>' is an unspecialized ObjCObjectType with base C and protocol list [P].
4829 /// 'C<C*>' is a specialized ObjCObjectType with type arguments 'C*' and no
4831 /// 'C<C*><P>' is a specialized ObjCObjectType with base C, type arguments 'C*',
4832 /// and protocol list [P].
4834 /// 'id' is a TypedefType which is sugar for an ObjCObjectPointerType whose
4835 /// pointee is an ObjCObjectType with base BuiltinType::ObjCIdType
4836 /// and no protocols.
4838 /// 'id<P>' is an ObjCObjectPointerType whose pointee is an ObjCObjectType
4839 /// with base BuiltinType::ObjCIdType and protocol list [P]. Eventually
4840 /// this should get its own sugar class to better represent the source.
4841 class ObjCObjectType : public Type,
4842 public ObjCProtocolQualifiers<ObjCObjectType> {
4843 friend class ObjCProtocolQualifiers<ObjCObjectType>;
4844 // ObjCObjectType.NumTypeArgs - the number of type arguments stored
4845 // after the ObjCObjectPointerType node.
4846 // ObjCObjectType.NumProtocols - the number of protocols stored
4847 // after the type arguments of ObjCObjectPointerType node.
4849 // These protocols are those written directly on the type. If
4850 // protocol qualifiers ever become additive, the iterators will need
4851 // to get kindof complicated.
4853 // In the canonical object type, these are sorted alphabetically
4856 /// Either a BuiltinType or an InterfaceType or sugar for either.
4859 /// Cached superclass type.
4860 mutable llvm::PointerIntPair<const ObjCObjectType *, 1, bool>
4861 CachedSuperClassType;
4863 QualType *getTypeArgStorage();
4864 const QualType *getTypeArgStorage() const {
4865 return const_cast<ObjCObjectType *>(this)->getTypeArgStorage();
4868 ObjCProtocolDecl **getProtocolStorageImpl();
4869 /// Return the number of qualifying protocols in this interface type,
4870 /// or 0 if there are none.
4871 unsigned getNumProtocolsImpl() const {
4872 return ObjCObjectTypeBits.NumProtocols;
4874 void setNumProtocolsImpl(unsigned N) {
4875 ObjCObjectTypeBits.NumProtocols = N;
4879 ObjCObjectType(QualType Canonical, QualType Base,
4880 ArrayRef<QualType> typeArgs,
4881 ArrayRef<ObjCProtocolDecl *> protocols,
4884 enum Nonce_ObjCInterface { Nonce_ObjCInterface };
4885 ObjCObjectType(enum Nonce_ObjCInterface)
4886 : Type(ObjCInterface, QualType(), false, false, false, false),
4887 BaseType(QualType(this_(), 0)) {
4888 ObjCObjectTypeBits.NumProtocols = 0;
4889 ObjCObjectTypeBits.NumTypeArgs = 0;
4890 ObjCObjectTypeBits.IsKindOf = 0;
4893 void computeSuperClassTypeSlow() const;
4896 /// Gets the base type of this object type. This is always (possibly
4897 /// sugar for) one of:
4898 /// - the 'id' builtin type (as opposed to the 'id' type visible to the
4899 /// user, which is a typedef for an ObjCObjectPointerType)
4900 /// - the 'Class' builtin type (same caveat)
4901 /// - an ObjCObjectType (currently always an ObjCInterfaceType)
4902 QualType getBaseType() const { return BaseType; }
4904 bool isObjCId() const {
4905 return getBaseType()->isSpecificBuiltinType(BuiltinType::ObjCId);
4907 bool isObjCClass() const {
4908 return getBaseType()->isSpecificBuiltinType(BuiltinType::ObjCClass);
4910 bool isObjCUnqualifiedId() const { return qual_empty() && isObjCId(); }
4911 bool isObjCUnqualifiedClass() const { return qual_empty() && isObjCClass(); }
4912 bool isObjCUnqualifiedIdOrClass() const {
4913 if (!qual_empty()) return false;
4914 if (const BuiltinType *T = getBaseType()->getAs<BuiltinType>())
4915 return T->getKind() == BuiltinType::ObjCId ||
4916 T->getKind() == BuiltinType::ObjCClass;
4919 bool isObjCQualifiedId() const { return !qual_empty() && isObjCId(); }
4920 bool isObjCQualifiedClass() const { return !qual_empty() && isObjCClass(); }
4922 /// Gets the interface declaration for this object type, if the base type
4923 /// really is an interface.
4924 ObjCInterfaceDecl *getInterface() const;
4926 /// Determine whether this object type is "specialized", meaning
4927 /// that it has type arguments.
4928 bool isSpecialized() const;
4930 /// Determine whether this object type was written with type arguments.
4931 bool isSpecializedAsWritten() const {
4932 return ObjCObjectTypeBits.NumTypeArgs > 0;
4935 /// Determine whether this object type is "unspecialized", meaning
4936 /// that it has no type arguments.
4937 bool isUnspecialized() const { return !isSpecialized(); }
4939 /// Determine whether this object type is "unspecialized" as
4940 /// written, meaning that it has no type arguments.
4941 bool isUnspecializedAsWritten() const { return !isSpecializedAsWritten(); }
4943 /// Retrieve the type arguments of this object type (semantically).
4944 ArrayRef<QualType> getTypeArgs() const;
4946 /// Retrieve the type arguments of this object type as they were
4948 ArrayRef<QualType> getTypeArgsAsWritten() const {
4949 return llvm::makeArrayRef(getTypeArgStorage(),
4950 ObjCObjectTypeBits.NumTypeArgs);
4953 /// Whether this is a "__kindof" type as written.
4954 bool isKindOfTypeAsWritten() const { return ObjCObjectTypeBits.IsKindOf; }
4956 /// Whether this ia a "__kindof" type (semantically).
4957 bool isKindOfType() const;
4959 /// Retrieve the type of the superclass of this object type.
4961 /// This operation substitutes any type arguments into the
4962 /// superclass of the current class type, potentially producing a
4963 /// specialization of the superclass type. Produces a null type if
4964 /// there is no superclass.
4965 QualType getSuperClassType() const {
4966 if (!CachedSuperClassType.getInt())
4967 computeSuperClassTypeSlow();
4969 assert(CachedSuperClassType.getInt() && "Superclass not set?");
4970 return QualType(CachedSuperClassType.getPointer(), 0);
4973 /// Strip off the Objective-C "kindof" type and (with it) any
4974 /// protocol qualifiers.
4975 QualType stripObjCKindOfTypeAndQuals(const ASTContext &ctx) const;
4977 bool isSugared() const { return false; }
4978 QualType desugar() const { return QualType(this, 0); }
4980 static bool classof(const Type *T) {
4981 return T->getTypeClass() == ObjCObject ||
4982 T->getTypeClass() == ObjCInterface;
4986 /// A class providing a concrete implementation
4987 /// of ObjCObjectType, so as to not increase the footprint of
4988 /// ObjCInterfaceType. Code outside of ASTContext and the core type
4989 /// system should not reference this type.
4990 class ObjCObjectTypeImpl : public ObjCObjectType, public llvm::FoldingSetNode {
4991 friend class ASTContext;
4993 // If anyone adds fields here, ObjCObjectType::getProtocolStorage()
4994 // will need to be modified.
4996 ObjCObjectTypeImpl(QualType Canonical, QualType Base,
4997 ArrayRef<QualType> typeArgs,
4998 ArrayRef<ObjCProtocolDecl *> protocols,
5000 : ObjCObjectType(Canonical, Base, typeArgs, protocols, isKindOf) {}
5003 void Profile(llvm::FoldingSetNodeID &ID);
5004 static void Profile(llvm::FoldingSetNodeID &ID,
5006 ArrayRef<QualType> typeArgs,
5007 ArrayRef<ObjCProtocolDecl *> protocols,
5011 inline QualType *ObjCObjectType::getTypeArgStorage() {
5012 return reinterpret_cast<QualType *>(static_cast<ObjCObjectTypeImpl*>(this)+1);
5015 inline ObjCProtocolDecl **ObjCObjectType::getProtocolStorageImpl() {
5016 return reinterpret_cast<ObjCProtocolDecl**>(
5017 getTypeArgStorage() + ObjCObjectTypeBits.NumTypeArgs);
5020 inline ObjCProtocolDecl **ObjCTypeParamType::getProtocolStorageImpl() {
5021 return reinterpret_cast<ObjCProtocolDecl**>(
5022 static_cast<ObjCTypeParamType*>(this)+1);
5025 /// Interfaces are the core concept in Objective-C for object oriented design.
5026 /// They basically correspond to C++ classes. There are two kinds of interface
5027 /// types: normal interfaces like `NSString`, and qualified interfaces, which
5028 /// are qualified with a protocol list like `NSString<NSCopyable, NSAmazing>`.
5030 /// ObjCInterfaceType guarantees the following properties when considered
5031 /// as a subtype of its superclass, ObjCObjectType:
5032 /// - There are no protocol qualifiers. To reinforce this, code which
5033 /// tries to invoke the protocol methods via an ObjCInterfaceType will
5034 /// fail to compile.
5035 /// - It is its own base type. That is, if T is an ObjCInterfaceType*,
5036 /// T->getBaseType() == QualType(T, 0).
5037 class ObjCInterfaceType : public ObjCObjectType {
5038 mutable ObjCInterfaceDecl *Decl;
5040 ObjCInterfaceType(const ObjCInterfaceDecl *D)
5041 : ObjCObjectType(Nonce_ObjCInterface),
5042 Decl(const_cast<ObjCInterfaceDecl*>(D)) {}
5043 friend class ASTContext; // ASTContext creates these.
5044 friend class ASTReader;
5045 friend class ObjCInterfaceDecl;
5048 /// Get the declaration of this interface.
5049 ObjCInterfaceDecl *getDecl() const { return Decl; }
5051 bool isSugared() const { return false; }
5052 QualType desugar() const { return QualType(this, 0); }
5054 static bool classof(const Type *T) {
5055 return T->getTypeClass() == ObjCInterface;
5058 // Nonsense to "hide" certain members of ObjCObjectType within this
5059 // class. People asking for protocols on an ObjCInterfaceType are
5060 // not going to get what they want: ObjCInterfaceTypes are
5061 // guaranteed to have no protocols.
5071 inline ObjCInterfaceDecl *ObjCObjectType::getInterface() const {
5072 QualType baseType = getBaseType();
5073 while (const ObjCObjectType *ObjT = baseType->getAs<ObjCObjectType>()) {
5074 if (const ObjCInterfaceType *T = dyn_cast<ObjCInterfaceType>(ObjT))
5075 return T->getDecl();
5077 baseType = ObjT->getBaseType();
5083 /// Represents a pointer to an Objective C object.
5085 /// These are constructed from pointer declarators when the pointee type is
5086 /// an ObjCObjectType (or sugar for one). In addition, the 'id' and 'Class'
5087 /// types are typedefs for these, and the protocol-qualified types 'id<P>'
5088 /// and 'Class<P>' are translated into these.
5090 /// Pointers to pointers to Objective C objects are still PointerTypes;
5091 /// only the first level of pointer gets it own type implementation.
5092 class ObjCObjectPointerType : public Type, public llvm::FoldingSetNode {
5093 QualType PointeeType;
5095 ObjCObjectPointerType(QualType Canonical, QualType Pointee)
5096 : Type(ObjCObjectPointer, Canonical,
5097 Pointee->isDependentType(),
5098 Pointee->isInstantiationDependentType(),
5099 Pointee->isVariablyModifiedType(),
5100 Pointee->containsUnexpandedParameterPack()),
5101 PointeeType(Pointee) {}
5102 friend class ASTContext; // ASTContext creates these.
5105 /// Gets the type pointed to by this ObjC pointer.
5106 /// The result will always be an ObjCObjectType or sugar thereof.
5107 QualType getPointeeType() const { return PointeeType; }
5109 /// Gets the type pointed to by this ObjC pointer. Always returns non-null.
5111 /// This method is equivalent to getPointeeType() except that
5112 /// it discards any typedefs (or other sugar) between this
5113 /// type and the "outermost" object type. So for:
5115 /// \@class A; \@protocol P; \@protocol Q;
5116 /// typedef A<P> AP;
5118 /// typedef A1<P> A1P;
5119 /// typedef A1P<Q> A1PQ;
5121 /// For 'A*', getObjectType() will return 'A'.
5122 /// For 'A<P>*', getObjectType() will return 'A<P>'.
5123 /// For 'AP*', getObjectType() will return 'A<P>'.
5124 /// For 'A1*', getObjectType() will return 'A'.
5125 /// For 'A1<P>*', getObjectType() will return 'A1<P>'.
5126 /// For 'A1P*', getObjectType() will return 'A1<P>'.
5127 /// For 'A1PQ*', getObjectType() will return 'A1<Q>', because
5128 /// adding protocols to a protocol-qualified base discards the
5129 /// old qualifiers (for now). But if it didn't, getObjectType()
5130 /// would return 'A1P<Q>' (and we'd have to make iterating over
5131 /// qualifiers more complicated).
5132 const ObjCObjectType *getObjectType() const {
5133 return PointeeType->castAs<ObjCObjectType>();
5136 /// If this pointer points to an Objective C
5137 /// \@interface type, gets the type for that interface. Any protocol
5138 /// qualifiers on the interface are ignored.
5140 /// \return null if the base type for this pointer is 'id' or 'Class'
5141 const ObjCInterfaceType *getInterfaceType() const;
5143 /// If this pointer points to an Objective \@interface
5144 /// type, gets the declaration for that interface.
5146 /// \return null if the base type for this pointer is 'id' or 'Class'
5147 ObjCInterfaceDecl *getInterfaceDecl() const {
5148 return getObjectType()->getInterface();
5151 /// True if this is equivalent to the 'id' type, i.e. if
5152 /// its object type is the primitive 'id' type with no protocols.
5153 bool isObjCIdType() const {
5154 return getObjectType()->isObjCUnqualifiedId();
5157 /// True if this is equivalent to the 'Class' type,
5158 /// i.e. if its object tive is the primitive 'Class' type with no protocols.
5159 bool isObjCClassType() const {
5160 return getObjectType()->isObjCUnqualifiedClass();
5163 /// True if this is equivalent to the 'id' or 'Class' type,
5164 bool isObjCIdOrClassType() const {
5165 return getObjectType()->isObjCUnqualifiedIdOrClass();
5168 /// True if this is equivalent to 'id<P>' for some non-empty set of
5170 bool isObjCQualifiedIdType() const {
5171 return getObjectType()->isObjCQualifiedId();
5174 /// True if this is equivalent to 'Class<P>' for some non-empty set of
5176 bool isObjCQualifiedClassType() const {
5177 return getObjectType()->isObjCQualifiedClass();
5180 /// Whether this is a "__kindof" type.
5181 bool isKindOfType() const { return getObjectType()->isKindOfType(); }
5183 /// Whether this type is specialized, meaning that it has type arguments.
5184 bool isSpecialized() const { return getObjectType()->isSpecialized(); }
5186 /// Whether this type is specialized, meaning that it has type arguments.
5187 bool isSpecializedAsWritten() const {
5188 return getObjectType()->isSpecializedAsWritten();
5191 /// Whether this type is unspecialized, meaning that is has no type arguments.
5192 bool isUnspecialized() const { return getObjectType()->isUnspecialized(); }
5194 /// Determine whether this object type is "unspecialized" as
5195 /// written, meaning that it has no type arguments.
5196 bool isUnspecializedAsWritten() const { return !isSpecializedAsWritten(); }
5198 /// Retrieve the type arguments for this type.
5199 ArrayRef<QualType> getTypeArgs() const {
5200 return getObjectType()->getTypeArgs();
5203 /// Retrieve the type arguments for this type.
5204 ArrayRef<QualType> getTypeArgsAsWritten() const {
5205 return getObjectType()->getTypeArgsAsWritten();
5208 /// An iterator over the qualifiers on the object type. Provided
5209 /// for convenience. This will always iterate over the full set of
5210 /// protocols on a type, not just those provided directly.
5211 typedef ObjCObjectType::qual_iterator qual_iterator;
5212 typedef llvm::iterator_range<qual_iterator> qual_range;
5214 qual_range quals() const { return qual_range(qual_begin(), qual_end()); }
5215 qual_iterator qual_begin() const {
5216 return getObjectType()->qual_begin();
5218 qual_iterator qual_end() const {
5219 return getObjectType()->qual_end();
5221 bool qual_empty() const { return getObjectType()->qual_empty(); }
5223 /// Return the number of qualifying protocols on the object type.
5224 unsigned getNumProtocols() const {
5225 return getObjectType()->getNumProtocols();
5228 /// Retrieve a qualifying protocol by index on the object type.
5229 ObjCProtocolDecl *getProtocol(unsigned I) const {
5230 return getObjectType()->getProtocol(I);
5233 bool isSugared() const { return false; }
5234 QualType desugar() const { return QualType(this, 0); }
5236 /// Retrieve the type of the superclass of this object pointer type.
5238 /// This operation substitutes any type arguments into the
5239 /// superclass of the current class type, potentially producing a
5240 /// pointer to a specialization of the superclass type. Produces a
5241 /// null type if there is no superclass.
5242 QualType getSuperClassType() const;
5244 /// Strip off the Objective-C "kindof" type and (with it) any
5245 /// protocol qualifiers.
5246 const ObjCObjectPointerType *stripObjCKindOfTypeAndQuals(
5247 const ASTContext &ctx) const;
5249 void Profile(llvm::FoldingSetNodeID &ID) {
5250 Profile(ID, getPointeeType());
5252 static void Profile(llvm::FoldingSetNodeID &ID, QualType T) {
5253 ID.AddPointer(T.getAsOpaquePtr());
5255 static bool classof(const Type *T) {
5256 return T->getTypeClass() == ObjCObjectPointer;
5260 class AtomicType : public Type, public llvm::FoldingSetNode {
5263 AtomicType(QualType ValTy, QualType Canonical)
5264 : Type(Atomic, Canonical, ValTy->isDependentType(),
5265 ValTy->isInstantiationDependentType(),
5266 ValTy->isVariablyModifiedType(),
5267 ValTy->containsUnexpandedParameterPack()),
5269 friend class ASTContext; // ASTContext creates these.
5272 /// Gets the type contained by this atomic type, i.e.
5273 /// the type returned by performing an atomic load of this atomic type.
5274 QualType getValueType() const { return ValueType; }
5276 bool isSugared() const { return false; }
5277 QualType desugar() const { return QualType(this, 0); }
5279 void Profile(llvm::FoldingSetNodeID &ID) {
5280 Profile(ID, getValueType());
5282 static void Profile(llvm::FoldingSetNodeID &ID, QualType T) {
5283 ID.AddPointer(T.getAsOpaquePtr());
5285 static bool classof(const Type *T) {
5286 return T->getTypeClass() == Atomic;
5290 /// PipeType - OpenCL20.
5291 class PipeType : public Type, public llvm::FoldingSetNode {
5292 QualType ElementType;
5295 PipeType(QualType elemType, QualType CanonicalPtr, bool isRead) :
5296 Type(Pipe, CanonicalPtr, elemType->isDependentType(),
5297 elemType->isInstantiationDependentType(),
5298 elemType->isVariablyModifiedType(),
5299 elemType->containsUnexpandedParameterPack()),
5300 ElementType(elemType), isRead(isRead) {}
5301 friend class ASTContext; // ASTContext creates these.
5304 QualType getElementType() const { return ElementType; }
5306 bool isSugared() const { return false; }
5308 QualType desugar() const { return QualType(this, 0); }
5310 void Profile(llvm::FoldingSetNodeID &ID) {
5311 Profile(ID, getElementType(), isReadOnly());
5314 static void Profile(llvm::FoldingSetNodeID &ID, QualType T, bool isRead) {
5315 ID.AddPointer(T.getAsOpaquePtr());
5316 ID.AddBoolean(isRead);
5319 static bool classof(const Type *T) {
5320 return T->getTypeClass() == Pipe;
5323 bool isReadOnly() const { return isRead; }
5326 /// A qualifier set is used to build a set of qualifiers.
5327 class QualifierCollector : public Qualifiers {
5329 QualifierCollector(Qualifiers Qs = Qualifiers()) : Qualifiers(Qs) {}
5331 /// Collect any qualifiers on the given type and return an
5332 /// unqualified type. The qualifiers are assumed to be consistent
5333 /// with those already in the type.
5334 const Type *strip(QualType type) {
5335 addFastQualifiers(type.getLocalFastQualifiers());
5336 if (!type.hasLocalNonFastQualifiers())
5337 return type.getTypePtrUnsafe();
5339 const ExtQuals *extQuals = type.getExtQualsUnsafe();
5340 addConsistentQualifiers(extQuals->getQualifiers());
5341 return extQuals->getBaseType();
5344 /// Apply the collected qualifiers to the given type.
5345 QualType apply(const ASTContext &Context, QualType QT) const;
5347 /// Apply the collected qualifiers to the given type.
5348 QualType apply(const ASTContext &Context, const Type* T) const;
5352 // Inline function definitions.
5354 inline SplitQualType SplitQualType::getSingleStepDesugaredType() const {
5355 SplitQualType desugar =
5356 Ty->getLocallyUnqualifiedSingleStepDesugaredType().split();
5357 desugar.Quals.addConsistentQualifiers(Quals);
5361 inline const Type *QualType::getTypePtr() const {
5362 return getCommonPtr()->BaseType;
5365 inline const Type *QualType::getTypePtrOrNull() const {
5366 return (isNull() ? nullptr : getCommonPtr()->BaseType);
5369 inline SplitQualType QualType::split() const {
5370 if (!hasLocalNonFastQualifiers())
5371 return SplitQualType(getTypePtrUnsafe(),
5372 Qualifiers::fromFastMask(getLocalFastQualifiers()));
5374 const ExtQuals *eq = getExtQualsUnsafe();
5375 Qualifiers qs = eq->getQualifiers();
5376 qs.addFastQualifiers(getLocalFastQualifiers());
5377 return SplitQualType(eq->getBaseType(), qs);
5380 inline Qualifiers QualType::getLocalQualifiers() const {
5382 if (hasLocalNonFastQualifiers())
5383 Quals = getExtQualsUnsafe()->getQualifiers();
5384 Quals.addFastQualifiers(getLocalFastQualifiers());
5388 inline Qualifiers QualType::getQualifiers() const {
5389 Qualifiers quals = getCommonPtr()->CanonicalType.getLocalQualifiers();
5390 quals.addFastQualifiers(getLocalFastQualifiers());
5394 inline unsigned QualType::getCVRQualifiers() const {
5395 unsigned cvr = getCommonPtr()->CanonicalType.getLocalCVRQualifiers();
5396 cvr |= getLocalCVRQualifiers();
5400 inline QualType QualType::getCanonicalType() const {
5401 QualType canon = getCommonPtr()->CanonicalType;
5402 return canon.withFastQualifiers(getLocalFastQualifiers());
5405 inline bool QualType::isCanonical() const {
5406 return getTypePtr()->isCanonicalUnqualified();
5409 inline bool QualType::isCanonicalAsParam() const {
5410 if (!isCanonical()) return false;
5411 if (hasLocalQualifiers()) return false;
5413 const Type *T = getTypePtr();
5414 if (T->isVariablyModifiedType() && T->hasSizedVLAType())
5417 return !isa<FunctionType>(T) && !isa<ArrayType>(T);
5420 inline bool QualType::isConstQualified() const {
5421 return isLocalConstQualified() ||
5422 getCommonPtr()->CanonicalType.isLocalConstQualified();
5425 inline bool QualType::isRestrictQualified() const {
5426 return isLocalRestrictQualified() ||
5427 getCommonPtr()->CanonicalType.isLocalRestrictQualified();
5431 inline bool QualType::isVolatileQualified() const {
5432 return isLocalVolatileQualified() ||
5433 getCommonPtr()->CanonicalType.isLocalVolatileQualified();
5436 inline bool QualType::hasQualifiers() const {
5437 return hasLocalQualifiers() ||
5438 getCommonPtr()->CanonicalType.hasLocalQualifiers();
5441 inline QualType QualType::getUnqualifiedType() const {
5442 if (!getTypePtr()->getCanonicalTypeInternal().hasLocalQualifiers())
5443 return QualType(getTypePtr(), 0);
5445 return QualType(getSplitUnqualifiedTypeImpl(*this).Ty, 0);
5448 inline SplitQualType QualType::getSplitUnqualifiedType() const {
5449 if (!getTypePtr()->getCanonicalTypeInternal().hasLocalQualifiers())
5452 return getSplitUnqualifiedTypeImpl(*this);
5455 inline void QualType::removeLocalConst() {
5456 removeLocalFastQualifiers(Qualifiers::Const);
5459 inline void QualType::removeLocalRestrict() {
5460 removeLocalFastQualifiers(Qualifiers::Restrict);
5463 inline void QualType::removeLocalVolatile() {
5464 removeLocalFastQualifiers(Qualifiers::Volatile);
5467 inline void QualType::removeLocalCVRQualifiers(unsigned Mask) {
5468 assert(!(Mask & ~Qualifiers::CVRMask) && "mask has non-CVR bits");
5469 static_assert((int)Qualifiers::CVRMask == (int)Qualifiers::FastMask,
5470 "Fast bits differ from CVR bits!");
5472 // Fast path: we don't need to touch the slow qualifiers.
5473 removeLocalFastQualifiers(Mask);
5476 /// Return the address space of this type.
5477 inline unsigned QualType::getAddressSpace() const {
5478 return getQualifiers().getAddressSpace();
5481 /// Return the gc attribute of this type.
5482 inline Qualifiers::GC QualType::getObjCGCAttr() const {
5483 return getQualifiers().getObjCGCAttr();
5486 inline FunctionType::ExtInfo getFunctionExtInfo(const Type &t) {
5487 if (const PointerType *PT = t.getAs<PointerType>()) {
5488 if (const FunctionType *FT = PT->getPointeeType()->getAs<FunctionType>())
5489 return FT->getExtInfo();
5490 } else if (const FunctionType *FT = t.getAs<FunctionType>())
5491 return FT->getExtInfo();
5493 return FunctionType::ExtInfo();
5496 inline FunctionType::ExtInfo getFunctionExtInfo(QualType t) {
5497 return getFunctionExtInfo(*t);
5500 /// Determine whether this type is more
5501 /// qualified than the Other type. For example, "const volatile int"
5502 /// is more qualified than "const int", "volatile int", and
5503 /// "int". However, it is not more qualified than "const volatile
5505 inline bool QualType::isMoreQualifiedThan(QualType other) const {
5506 Qualifiers MyQuals = getQualifiers();
5507 Qualifiers OtherQuals = other.getQualifiers();
5508 return (MyQuals != OtherQuals && MyQuals.compatiblyIncludes(OtherQuals));
5511 /// Determine whether this type is at last
5512 /// as qualified as the Other type. For example, "const volatile
5513 /// int" is at least as qualified as "const int", "volatile int",
5514 /// "int", and "const volatile int".
5515 inline bool QualType::isAtLeastAsQualifiedAs(QualType other) const {
5516 Qualifiers OtherQuals = other.getQualifiers();
5518 // Ignore __unaligned qualifier if this type is a void.
5519 if (getUnqualifiedType()->isVoidType())
5520 OtherQuals.removeUnaligned();
5522 return getQualifiers().compatiblyIncludes(OtherQuals);
5525 /// If Type is a reference type (e.g., const
5526 /// int&), returns the type that the reference refers to ("const
5527 /// int"). Otherwise, returns the type itself. This routine is used
5528 /// throughout Sema to implement C++ 5p6:
5530 /// If an expression initially has the type "reference to T" (8.3.2,
5531 /// 8.5.3), the type is adjusted to "T" prior to any further
5532 /// analysis, the expression designates the object or function
5533 /// denoted by the reference, and the expression is an lvalue.
5534 inline QualType QualType::getNonReferenceType() const {
5535 if (const ReferenceType *RefType = (*this)->getAs<ReferenceType>())
5536 return RefType->getPointeeType();
5541 inline bool QualType::isCForbiddenLValueType() const {
5542 return ((getTypePtr()->isVoidType() && !hasQualifiers()) ||
5543 getTypePtr()->isFunctionType());
5546 /// Tests whether the type is categorized as a fundamental type.
5548 /// \returns True for types specified in C++0x [basic.fundamental].
5549 inline bool Type::isFundamentalType() const {
5550 return isVoidType() ||
5551 // FIXME: It's really annoying that we don't have an
5552 // 'isArithmeticType()' which agrees with the standard definition.
5553 (isArithmeticType() && !isEnumeralType());
5556 /// Tests whether the type is categorized as a compound type.
5558 /// \returns True for types specified in C++0x [basic.compound].
5559 inline bool Type::isCompoundType() const {
5560 // C++0x [basic.compound]p1:
5561 // Compound types can be constructed in the following ways:
5562 // -- arrays of objects of a given type [...];
5563 return isArrayType() ||
5564 // -- functions, which have parameters of given types [...];
5566 // -- pointers to void or objects or functions [...];
5568 // -- references to objects or functions of a given type. [...]
5569 isReferenceType() ||
5570 // -- classes containing a sequence of objects of various types, [...];
5572 // -- unions, which are classes capable of containing objects of different
5573 // types at different times;
5575 // -- enumerations, which comprise a set of named constant values. [...];
5577 // -- pointers to non-static class members, [...].
5578 isMemberPointerType();
5581 inline bool Type::isFunctionType() const {
5582 return isa<FunctionType>(CanonicalType);
5584 inline bool Type::isPointerType() const {
5585 return isa<PointerType>(CanonicalType);
5587 inline bool Type::isAnyPointerType() const {
5588 return isPointerType() || isObjCObjectPointerType();
5590 inline bool Type::isBlockPointerType() const {
5591 return isa<BlockPointerType>(CanonicalType);
5593 inline bool Type::isReferenceType() const {
5594 return isa<ReferenceType>(CanonicalType);
5596 inline bool Type::isLValueReferenceType() const {
5597 return isa<LValueReferenceType>(CanonicalType);
5599 inline bool Type::isRValueReferenceType() const {
5600 return isa<RValueReferenceType>(CanonicalType);
5602 inline bool Type::isFunctionPointerType() const {
5603 if (const PointerType *T = getAs<PointerType>())
5604 return T->getPointeeType()->isFunctionType();
5608 inline bool Type::isMemberPointerType() const {
5609 return isa<MemberPointerType>(CanonicalType);
5611 inline bool Type::isMemberFunctionPointerType() const {
5612 if (const MemberPointerType* T = getAs<MemberPointerType>())
5613 return T->isMemberFunctionPointer();
5617 inline bool Type::isMemberDataPointerType() const {
5618 if (const MemberPointerType* T = getAs<MemberPointerType>())
5619 return T->isMemberDataPointer();
5623 inline bool Type::isArrayType() const {
5624 return isa<ArrayType>(CanonicalType);
5626 inline bool Type::isConstantArrayType() const {
5627 return isa<ConstantArrayType>(CanonicalType);
5629 inline bool Type::isIncompleteArrayType() const {
5630 return isa<IncompleteArrayType>(CanonicalType);
5632 inline bool Type::isVariableArrayType() const {
5633 return isa<VariableArrayType>(CanonicalType);
5635 inline bool Type::isDependentSizedArrayType() const {
5636 return isa<DependentSizedArrayType>(CanonicalType);
5638 inline bool Type::isBuiltinType() const {
5639 return isa<BuiltinType>(CanonicalType);
5641 inline bool Type::isRecordType() const {
5642 return isa<RecordType>(CanonicalType);
5644 inline bool Type::isEnumeralType() const {
5645 return isa<EnumType>(CanonicalType);
5647 inline bool Type::isAnyComplexType() const {
5648 return isa<ComplexType>(CanonicalType);
5650 inline bool Type::isVectorType() const {
5651 return isa<VectorType>(CanonicalType);
5653 inline bool Type::isExtVectorType() const {
5654 return isa<ExtVectorType>(CanonicalType);
5656 inline bool Type::isObjCObjectPointerType() const {
5657 return isa<ObjCObjectPointerType>(CanonicalType);
5659 inline bool Type::isObjCObjectType() const {
5660 return isa<ObjCObjectType>(CanonicalType);
5662 inline bool Type::isObjCObjectOrInterfaceType() const {
5663 return isa<ObjCInterfaceType>(CanonicalType) ||
5664 isa<ObjCObjectType>(CanonicalType);
5666 inline bool Type::isAtomicType() const {
5667 return isa<AtomicType>(CanonicalType);
5670 inline bool Type::isObjCQualifiedIdType() const {
5671 if (const ObjCObjectPointerType *OPT = getAs<ObjCObjectPointerType>())
5672 return OPT->isObjCQualifiedIdType();
5675 inline bool Type::isObjCQualifiedClassType() const {
5676 if (const ObjCObjectPointerType *OPT = getAs<ObjCObjectPointerType>())
5677 return OPT->isObjCQualifiedClassType();
5680 inline bool Type::isObjCIdType() const {
5681 if (const ObjCObjectPointerType *OPT = getAs<ObjCObjectPointerType>())
5682 return OPT->isObjCIdType();
5685 inline bool Type::isObjCClassType() const {
5686 if (const ObjCObjectPointerType *OPT = getAs<ObjCObjectPointerType>())
5687 return OPT->isObjCClassType();
5690 inline bool Type::isObjCSelType() const {
5691 if (const PointerType *OPT = getAs<PointerType>())
5692 return OPT->getPointeeType()->isSpecificBuiltinType(BuiltinType::ObjCSel);
5695 inline bool Type::isObjCBuiltinType() const {
5696 return isObjCIdType() || isObjCClassType() || isObjCSelType();
5699 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
5700 inline bool Type::is##Id##Type() const { \
5701 return isSpecificBuiltinType(BuiltinType::Id); \
5703 #include "clang/Basic/OpenCLImageTypes.def"
5705 inline bool Type::isSamplerT() const {
5706 return isSpecificBuiltinType(BuiltinType::OCLSampler);
5709 inline bool Type::isEventT() const {
5710 return isSpecificBuiltinType(BuiltinType::OCLEvent);
5713 inline bool Type::isClkEventT() const {
5714 return isSpecificBuiltinType(BuiltinType::OCLClkEvent);
5717 inline bool Type::isQueueT() const {
5718 return isSpecificBuiltinType(BuiltinType::OCLQueue);
5721 inline bool Type::isNDRangeT() const {
5722 return isSpecificBuiltinType(BuiltinType::OCLNDRange);
5725 inline bool Type::isReserveIDT() const {
5726 return isSpecificBuiltinType(BuiltinType::OCLReserveID);
5729 inline bool Type::isImageType() const {
5730 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) is##Id##Type() ||
5732 #include "clang/Basic/OpenCLImageTypes.def"
5733 0; // end boolean or operation
5736 inline bool Type::isPipeType() const {
5737 return isa<PipeType>(CanonicalType);
5740 inline bool Type::isOpenCLSpecificType() const {
5741 return isSamplerT() || isEventT() || isImageType() || isClkEventT() ||
5742 isQueueT() || isNDRangeT() || isReserveIDT() || isPipeType();
5745 inline bool Type::isTemplateTypeParmType() const {
5746 return isa<TemplateTypeParmType>(CanonicalType);
5749 inline bool Type::isSpecificBuiltinType(unsigned K) const {
5750 if (const BuiltinType *BT = getAs<BuiltinType>())
5751 if (BT->getKind() == (BuiltinType::Kind) K)
5756 inline bool Type::isPlaceholderType() const {
5757 if (const BuiltinType *BT = dyn_cast<BuiltinType>(this))
5758 return BT->isPlaceholderType();
5762 inline const BuiltinType *Type::getAsPlaceholderType() const {
5763 if (const BuiltinType *BT = dyn_cast<BuiltinType>(this))
5764 if (BT->isPlaceholderType())
5769 inline bool Type::isSpecificPlaceholderType(unsigned K) const {
5770 assert(BuiltinType::isPlaceholderTypeKind((BuiltinType::Kind) K));
5771 if (const BuiltinType *BT = dyn_cast<BuiltinType>(this))
5772 return (BT->getKind() == (BuiltinType::Kind) K);
5776 inline bool Type::isNonOverloadPlaceholderType() const {
5777 if (const BuiltinType *BT = dyn_cast<BuiltinType>(this))
5778 return BT->isNonOverloadPlaceholderType();
5782 inline bool Type::isVoidType() const {
5783 if (const BuiltinType *BT = dyn_cast<BuiltinType>(CanonicalType))
5784 return BT->getKind() == BuiltinType::Void;
5788 inline bool Type::isHalfType() const {
5789 if (const BuiltinType *BT = dyn_cast<BuiltinType>(CanonicalType))
5790 return BT->getKind() == BuiltinType::Half;
5791 // FIXME: Should we allow complex __fp16? Probably not.
5795 inline bool Type::isNullPtrType() const {
5796 if (const BuiltinType *BT = getAs<BuiltinType>())
5797 return BT->getKind() == BuiltinType::NullPtr;
5801 bool IsEnumDeclComplete(EnumDecl *);
5802 bool IsEnumDeclScoped(EnumDecl *);
5804 inline bool Type::isIntegerType() const {
5805 if (const BuiltinType *BT = dyn_cast<BuiltinType>(CanonicalType))
5806 return BT->getKind() >= BuiltinType::Bool &&
5807 BT->getKind() <= BuiltinType::Int128;
5808 if (const EnumType *ET = dyn_cast<EnumType>(CanonicalType)) {
5809 // Incomplete enum types are not treated as integer types.
5810 // FIXME: In C++, enum types are never integer types.
5811 return IsEnumDeclComplete(ET->getDecl()) &&
5812 !IsEnumDeclScoped(ET->getDecl());
5817 inline bool Type::isScalarType() const {
5818 if (const BuiltinType *BT = dyn_cast<BuiltinType>(CanonicalType))
5819 return BT->getKind() > BuiltinType::Void &&
5820 BT->getKind() <= BuiltinType::NullPtr;
5821 if (const EnumType *ET = dyn_cast<EnumType>(CanonicalType))
5822 // Enums are scalar types, but only if they are defined. Incomplete enums
5823 // are not treated as scalar types.
5824 return IsEnumDeclComplete(ET->getDecl());
5825 return isa<PointerType>(CanonicalType) ||
5826 isa<BlockPointerType>(CanonicalType) ||
5827 isa<MemberPointerType>(CanonicalType) ||
5828 isa<ComplexType>(CanonicalType) ||
5829 isa<ObjCObjectPointerType>(CanonicalType);
5832 inline bool Type::isIntegralOrEnumerationType() const {
5833 if (const BuiltinType *BT = dyn_cast<BuiltinType>(CanonicalType))
5834 return BT->getKind() >= BuiltinType::Bool &&
5835 BT->getKind() <= BuiltinType::Int128;
5837 // Check for a complete enum type; incomplete enum types are not properly an
5838 // enumeration type in the sense required here.
5839 if (const EnumType *ET = dyn_cast<EnumType>(CanonicalType))
5840 return IsEnumDeclComplete(ET->getDecl());
5845 inline bool Type::isBooleanType() const {
5846 if (const BuiltinType *BT = dyn_cast<BuiltinType>(CanonicalType))
5847 return BT->getKind() == BuiltinType::Bool;
5851 inline bool Type::isUndeducedType() const {
5852 const AutoType *AT = getContainedAutoType();
5853 return AT && !AT->isDeduced();
5856 /// \brief Determines whether this is a type for which one can define
5857 /// an overloaded operator.
5858 inline bool Type::isOverloadableType() const {
5859 return isDependentType() || isRecordType() || isEnumeralType();
5862 /// \brief Determines whether this type can decay to a pointer type.
5863 inline bool Type::canDecayToPointerType() const {
5864 return isFunctionType() || isArrayType();
5867 inline bool Type::hasPointerRepresentation() const {
5868 return (isPointerType() || isReferenceType() || isBlockPointerType() ||
5869 isObjCObjectPointerType() || isNullPtrType());
5872 inline bool Type::hasObjCPointerRepresentation() const {
5873 return isObjCObjectPointerType();
5876 inline const Type *Type::getBaseElementTypeUnsafe() const {
5877 const Type *type = this;
5878 while (const ArrayType *arrayType = type->getAsArrayTypeUnsafe())
5879 type = arrayType->getElementType().getTypePtr();
5883 inline const Type *Type::getPointeeOrArrayElementType() const {
5884 const Type *type = this;
5885 if (type->isAnyPointerType())
5886 return type->getPointeeType().getTypePtr();
5887 else if (type->isArrayType())
5888 return type->getBaseElementTypeUnsafe();
5892 /// Insertion operator for diagnostics. This allows sending QualType's into a
5893 /// diagnostic with <<.
5894 inline const DiagnosticBuilder &operator<<(const DiagnosticBuilder &DB,
5896 DB.AddTaggedVal(reinterpret_cast<intptr_t>(T.getAsOpaquePtr()),
5897 DiagnosticsEngine::ak_qualtype);
5901 /// Insertion operator for partial diagnostics. This allows sending QualType's
5902 /// into a diagnostic with <<.
5903 inline const PartialDiagnostic &operator<<(const PartialDiagnostic &PD,
5905 PD.AddTaggedVal(reinterpret_cast<intptr_t>(T.getAsOpaquePtr()),
5906 DiagnosticsEngine::ak_qualtype);
5910 // Helper class template that is used by Type::getAs to ensure that one does
5911 // not try to look through a qualified type to get to an array type.
5912 template <typename T>
5913 using TypeIsArrayType =
5914 std::integral_constant<bool, std::is_same<T, ArrayType>::value ||
5915 std::is_base_of<ArrayType, T>::value>;
5917 // Member-template getAs<specific type>'.
5918 template <typename T> const T *Type::getAs() const {
5919 static_assert(!TypeIsArrayType<T>::value,
5920 "ArrayType cannot be used with getAs!");
5922 // If this is directly a T type, return it.
5923 if (const T *Ty = dyn_cast<T>(this))
5926 // If the canonical form of this type isn't the right kind, reject it.
5927 if (!isa<T>(CanonicalType))
5930 // If this is a typedef for the type, strip the typedef off without
5931 // losing all typedef information.
5932 return cast<T>(getUnqualifiedDesugaredType());
5935 inline const ArrayType *Type::getAsArrayTypeUnsafe() const {
5936 // If this is directly an array type, return it.
5937 if (const ArrayType *arr = dyn_cast<ArrayType>(this))
5940 // If the canonical form of this type isn't the right kind, reject it.
5941 if (!isa<ArrayType>(CanonicalType))
5944 // If this is a typedef for the type, strip the typedef off without
5945 // losing all typedef information.
5946 return cast<ArrayType>(getUnqualifiedDesugaredType());
5949 template <typename T> const T *Type::castAs() const {
5950 static_assert(!TypeIsArrayType<T>::value,
5951 "ArrayType cannot be used with castAs!");
5953 if (const T *ty = dyn_cast<T>(this)) return ty;
5954 assert(isa<T>(CanonicalType));
5955 return cast<T>(getUnqualifiedDesugaredType());
5958 inline const ArrayType *Type::castAsArrayTypeUnsafe() const {
5959 assert(isa<ArrayType>(CanonicalType));
5960 if (const ArrayType *arr = dyn_cast<ArrayType>(this)) return arr;
5961 return cast<ArrayType>(getUnqualifiedDesugaredType());
5964 DecayedType::DecayedType(QualType OriginalType, QualType DecayedPtr,
5965 QualType CanonicalPtr)
5966 : AdjustedType(Decayed, OriginalType, DecayedPtr, CanonicalPtr) {
5968 QualType Adjusted = getAdjustedType();
5969 (void)AttributedType::stripOuterNullability(Adjusted);
5970 assert(isa<PointerType>(Adjusted));
5974 QualType DecayedType::getPointeeType() const {
5975 QualType Decayed = getDecayedType();
5976 (void)AttributedType::stripOuterNullability(Decayed);
5977 return cast<PointerType>(Decayed)->getPointeeType();
5981 } // end namespace clang