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 //===----------------------------------------------------------------------===//
11 /// C Language Family Type Representation
13 /// This file defines the clang::Type interface and subclasses, used to
14 /// represent types for languages in the C family.
16 //===----------------------------------------------------------------------===//
18 #ifndef LLVM_CLANG_AST_TYPE_H
19 #define LLVM_CLANG_AST_TYPE_H
21 #include "clang/AST/NestedNameSpecifier.h"
22 #include "clang/AST/TemplateName.h"
23 #include "clang/Basic/AddressSpaces.h"
24 #include "clang/Basic/Diagnostic.h"
25 #include "clang/Basic/ExceptionSpecificationType.h"
26 #include "clang/Basic/LLVM.h"
27 #include "clang/Basic/Linkage.h"
28 #include "clang/Basic/PartialDiagnostic.h"
29 #include "clang/Basic/SourceLocation.h"
30 #include "clang/Basic/Specifiers.h"
31 #include "clang/Basic/Visibility.h"
32 #include "llvm/ADT/APInt.h"
33 #include "llvm/ADT/APSInt.h"
34 #include "llvm/ADT/ArrayRef.h"
35 #include "llvm/ADT/FoldingSet.h"
36 #include "llvm/ADT/None.h"
37 #include "llvm/ADT/Optional.h"
38 #include "llvm/ADT/PointerIntPair.h"
39 #include "llvm/ADT/PointerUnion.h"
40 #include "llvm/ADT/StringRef.h"
41 #include "llvm/ADT/Twine.h"
42 #include "llvm/ADT/iterator_range.h"
43 #include "llvm/Support/Casting.h"
44 #include "llvm/Support/Compiler.h"
45 #include "llvm/Support/ErrorHandling.h"
46 #include "llvm/Support/PointerLikeTypeTraits.h"
47 #include "llvm/Support/type_traits.h"
53 #include <type_traits>
64 TypeAlignmentInBits = 4,
65 TypeAlignment = 1 << TypeAlignmentInBits
73 struct PointerLikeTypeTraits;
75 struct PointerLikeTypeTraits< ::clang::Type*> {
76 static inline void *getAsVoidPointer(::clang::Type *P) { return P; }
78 static inline ::clang::Type *getFromVoidPointer(void *P) {
79 return static_cast< ::clang::Type*>(P);
82 enum { NumLowBitsAvailable = clang::TypeAlignmentInBits };
86 struct PointerLikeTypeTraits< ::clang::ExtQuals*> {
87 static inline void *getAsVoidPointer(::clang::ExtQuals *P) { return P; }
89 static inline ::clang::ExtQuals *getFromVoidPointer(void *P) {
90 return static_cast< ::clang::ExtQuals*>(P);
93 enum { NumLowBitsAvailable = clang::TypeAlignmentInBits };
97 struct isPodLike<clang::QualType> { static const bool value = true; };
105 class AttributedType;
108 template <typename> class CanQual;
115 class ExtQualsTypeCommonBase;
117 class FunctionNoProtoType;
118 class FunctionProtoType;
119 class IdentifierInfo;
120 class InjectedClassNameType;
122 class ObjCInterfaceDecl;
123 class ObjCObjectPointerType;
124 class ObjCObjectType;
125 class ObjCProtocolDecl;
126 class ObjCTypeParamDecl;
128 struct PrintingPolicy;
133 class TemplateArgument;
134 class TemplateArgumentListInfo;
135 class TemplateArgumentLoc;
136 class TemplateSpecializationType;
137 class TemplateTypeParmDecl;
138 class TypedefNameDecl;
140 class UnresolvedUsingTypenameDecl;
142 using CanQualType = CanQual<Type>;
144 // Provide forward declarations for all of the *Type classes
145 #define TYPE(Class, Base) class Class##Type;
146 #include "clang/AST/TypeNodes.def"
148 /// The collection of all-type qualifiers we support.
149 /// Clang supports five independent qualifiers:
150 /// * C99: const, volatile, and restrict
151 /// * MS: __unaligned
152 /// * Embedded C (TR18037): address spaces
153 /// * Objective C: the GC attributes (none, weak, or strong)
156 enum TQ { // NOTE: These flags must be kept in sync with DeclSpec::TQ.
160 CVRMask = Const | Volatile | Restrict
170 /// There is no lifetime qualification on this type.
173 /// This object can be modified without requiring retains or
177 /// Assigning into this object requires the old value to be
178 /// released and the new value to be retained. The timing of the
179 /// release of the old value is inexact: it may be moved to
180 /// immediately after the last known point where the value is
184 /// Reading or writing from this object requires a barrier call.
187 /// Assigning into this object requires a lifetime extension.
192 /// The maximum supported address space number.
193 /// 23 bits should be enough for anyone.
194 MaxAddressSpace = 0x7fffffu,
196 /// The width of the "fast" qualifier mask.
199 /// The fast qualifier mask.
200 FastMask = (1 << FastWidth) - 1
203 /// Returns the common set of qualifiers while removing them from
205 static Qualifiers removeCommonQualifiers(Qualifiers &L, Qualifiers &R) {
206 // If both are only CVR-qualified, bit operations are sufficient.
207 if (!(L.Mask & ~CVRMask) && !(R.Mask & ~CVRMask)) {
209 Q.Mask = L.Mask & R.Mask;
216 unsigned CommonCRV = L.getCVRQualifiers() & R.getCVRQualifiers();
217 Q.addCVRQualifiers(CommonCRV);
218 L.removeCVRQualifiers(CommonCRV);
219 R.removeCVRQualifiers(CommonCRV);
221 if (L.getObjCGCAttr() == R.getObjCGCAttr()) {
222 Q.setObjCGCAttr(L.getObjCGCAttr());
223 L.removeObjCGCAttr();
224 R.removeObjCGCAttr();
227 if (L.getObjCLifetime() == R.getObjCLifetime()) {
228 Q.setObjCLifetime(L.getObjCLifetime());
229 L.removeObjCLifetime();
230 R.removeObjCLifetime();
233 if (L.getAddressSpace() == R.getAddressSpace()) {
234 Q.setAddressSpace(L.getAddressSpace());
235 L.removeAddressSpace();
236 R.removeAddressSpace();
241 static Qualifiers fromFastMask(unsigned Mask) {
243 Qs.addFastQualifiers(Mask);
247 static Qualifiers fromCVRMask(unsigned CVR) {
249 Qs.addCVRQualifiers(CVR);
253 static Qualifiers fromCVRUMask(unsigned CVRU) {
255 Qs.addCVRUQualifiers(CVRU);
259 // Deserialize qualifiers from an opaque representation.
260 static Qualifiers fromOpaqueValue(unsigned opaque) {
266 // Serialize these qualifiers into an opaque representation.
267 unsigned getAsOpaqueValue() const {
271 bool hasConst() const { return Mask & Const; }
272 void setConst(bool flag) {
273 Mask = (Mask & ~Const) | (flag ? Const : 0);
275 void removeConst() { Mask &= ~Const; }
276 void addConst() { Mask |= Const; }
278 bool hasVolatile() const { return Mask & Volatile; }
279 void setVolatile(bool flag) {
280 Mask = (Mask & ~Volatile) | (flag ? Volatile : 0);
282 void removeVolatile() { Mask &= ~Volatile; }
283 void addVolatile() { Mask |= Volatile; }
285 bool hasRestrict() const { return Mask & Restrict; }
286 void setRestrict(bool flag) {
287 Mask = (Mask & ~Restrict) | (flag ? Restrict : 0);
289 void removeRestrict() { Mask &= ~Restrict; }
290 void addRestrict() { Mask |= Restrict; }
292 bool hasCVRQualifiers() const { return getCVRQualifiers(); }
293 unsigned getCVRQualifiers() const { return Mask & CVRMask; }
294 void setCVRQualifiers(unsigned mask) {
295 assert(!(mask & ~CVRMask) && "bitmask contains non-CVR bits");
296 Mask = (Mask & ~CVRMask) | mask;
298 void removeCVRQualifiers(unsigned mask) {
299 assert(!(mask & ~CVRMask) && "bitmask contains non-CVR bits");
302 void removeCVRQualifiers() {
303 removeCVRQualifiers(CVRMask);
305 void addCVRQualifiers(unsigned mask) {
306 assert(!(mask & ~CVRMask) && "bitmask contains non-CVR bits");
309 void addCVRUQualifiers(unsigned mask) {
310 assert(!(mask & ~CVRMask & ~UMask) && "bitmask contains non-CVRU bits");
314 bool hasUnaligned() const { return Mask & UMask; }
315 void setUnaligned(bool flag) {
316 Mask = (Mask & ~UMask) | (flag ? UMask : 0);
318 void removeUnaligned() { Mask &= ~UMask; }
319 void addUnaligned() { Mask |= UMask; }
321 bool hasObjCGCAttr() const { return Mask & GCAttrMask; }
322 GC getObjCGCAttr() const { return GC((Mask & GCAttrMask) >> GCAttrShift); }
323 void setObjCGCAttr(GC type) {
324 Mask = (Mask & ~GCAttrMask) | (type << GCAttrShift);
326 void removeObjCGCAttr() { setObjCGCAttr(GCNone); }
327 void addObjCGCAttr(GC type) {
331 Qualifiers withoutObjCGCAttr() const {
332 Qualifiers qs = *this;
333 qs.removeObjCGCAttr();
336 Qualifiers withoutObjCLifetime() const {
337 Qualifiers qs = *this;
338 qs.removeObjCLifetime();
342 bool hasObjCLifetime() const { return Mask & LifetimeMask; }
343 ObjCLifetime getObjCLifetime() const {
344 return ObjCLifetime((Mask & LifetimeMask) >> LifetimeShift);
346 void setObjCLifetime(ObjCLifetime type) {
347 Mask = (Mask & ~LifetimeMask) | (type << LifetimeShift);
349 void removeObjCLifetime() { setObjCLifetime(OCL_None); }
350 void addObjCLifetime(ObjCLifetime type) {
352 assert(!hasObjCLifetime());
353 Mask |= (type << LifetimeShift);
356 /// True if the lifetime is neither None or ExplicitNone.
357 bool hasNonTrivialObjCLifetime() const {
358 ObjCLifetime lifetime = getObjCLifetime();
359 return (lifetime > OCL_ExplicitNone);
362 /// True if the lifetime is either strong or weak.
363 bool hasStrongOrWeakObjCLifetime() const {
364 ObjCLifetime lifetime = getObjCLifetime();
365 return (lifetime == OCL_Strong || lifetime == OCL_Weak);
368 bool hasAddressSpace() const { return Mask & AddressSpaceMask; }
369 LangAS getAddressSpace() const {
370 return static_cast<LangAS>(Mask >> AddressSpaceShift);
372 bool hasTargetSpecificAddressSpace() const {
373 return isTargetAddressSpace(getAddressSpace());
375 /// Get the address space attribute value to be printed by diagnostics.
376 unsigned getAddressSpaceAttributePrintValue() const {
377 auto Addr = getAddressSpace();
378 // This function is not supposed to be used with language specific
379 // address spaces. If that happens, the diagnostic message should consider
380 // printing the QualType instead of the address space value.
381 assert(Addr == LangAS::Default || hasTargetSpecificAddressSpace());
382 if (Addr != LangAS::Default)
383 return toTargetAddressSpace(Addr);
384 // TODO: The diagnostic messages where Addr may be 0 should be fixed
385 // since it cannot differentiate the situation where 0 denotes the default
386 // address space or user specified __attribute__((address_space(0))).
389 void setAddressSpace(LangAS space) {
390 assert((unsigned)space <= MaxAddressSpace);
391 Mask = (Mask & ~AddressSpaceMask)
392 | (((uint32_t) space) << AddressSpaceShift);
394 void removeAddressSpace() { setAddressSpace(LangAS::Default); }
395 void addAddressSpace(LangAS space) {
396 assert(space != LangAS::Default);
397 setAddressSpace(space);
400 // Fast qualifiers are those that can be allocated directly
401 // on a QualType object.
402 bool hasFastQualifiers() const { return getFastQualifiers(); }
403 unsigned getFastQualifiers() const { return Mask & FastMask; }
404 void setFastQualifiers(unsigned mask) {
405 assert(!(mask & ~FastMask) && "bitmask contains non-fast qualifier bits");
406 Mask = (Mask & ~FastMask) | mask;
408 void removeFastQualifiers(unsigned mask) {
409 assert(!(mask & ~FastMask) && "bitmask contains non-fast qualifier bits");
412 void removeFastQualifiers() {
413 removeFastQualifiers(FastMask);
415 void addFastQualifiers(unsigned mask) {
416 assert(!(mask & ~FastMask) && "bitmask contains non-fast qualifier bits");
420 /// Return true if the set contains any qualifiers which require an ExtQuals
421 /// node to be allocated.
422 bool hasNonFastQualifiers() const { return Mask & ~FastMask; }
423 Qualifiers getNonFastQualifiers() const {
424 Qualifiers Quals = *this;
425 Quals.setFastQualifiers(0);
429 /// Return true if the set contains any qualifiers.
430 bool hasQualifiers() const { return Mask; }
431 bool empty() const { return !Mask; }
433 /// Add the qualifiers from the given set to this set.
434 void addQualifiers(Qualifiers Q) {
435 // If the other set doesn't have any non-boolean qualifiers, just
437 if (!(Q.Mask & ~CVRMask))
440 Mask |= (Q.Mask & CVRMask);
441 if (Q.hasAddressSpace())
442 addAddressSpace(Q.getAddressSpace());
443 if (Q.hasObjCGCAttr())
444 addObjCGCAttr(Q.getObjCGCAttr());
445 if (Q.hasObjCLifetime())
446 addObjCLifetime(Q.getObjCLifetime());
450 /// Remove the qualifiers from the given set from this set.
451 void removeQualifiers(Qualifiers Q) {
452 // If the other set doesn't have any non-boolean qualifiers, just
453 // bit-and the inverse in.
454 if (!(Q.Mask & ~CVRMask))
457 Mask &= ~(Q.Mask & CVRMask);
458 if (getObjCGCAttr() == Q.getObjCGCAttr())
460 if (getObjCLifetime() == Q.getObjCLifetime())
461 removeObjCLifetime();
462 if (getAddressSpace() == Q.getAddressSpace())
463 removeAddressSpace();
467 /// Add the qualifiers from the given set to this set, given that
468 /// they don't conflict.
469 void addConsistentQualifiers(Qualifiers qs) {
470 assert(getAddressSpace() == qs.getAddressSpace() ||
471 !hasAddressSpace() || !qs.hasAddressSpace());
472 assert(getObjCGCAttr() == qs.getObjCGCAttr() ||
473 !hasObjCGCAttr() || !qs.hasObjCGCAttr());
474 assert(getObjCLifetime() == qs.getObjCLifetime() ||
475 !hasObjCLifetime() || !qs.hasObjCLifetime());
479 /// Returns true if this address space is a superset of the other one.
480 /// OpenCL v2.0 defines conversion rules (OpenCLC v2.0 s6.5.5) and notion of
481 /// overlapping address spaces.
483 /// every address space is a superset of itself.
485 /// __generic is a superset of any address space except for __constant.
486 bool isAddressSpaceSupersetOf(Qualifiers other) const {
488 // Address spaces must match exactly.
489 getAddressSpace() == other.getAddressSpace() ||
490 // Otherwise in OpenCLC v2.0 s6.5.5: every address space except
491 // for __constant can be used as __generic.
492 (getAddressSpace() == LangAS::opencl_generic &&
493 other.getAddressSpace() != LangAS::opencl_constant);
496 /// Determines if these qualifiers compatibly include another set.
497 /// Generally this answers the question of whether an object with the other
498 /// qualifiers can be safely used as an object with these qualifiers.
499 bool compatiblyIncludes(Qualifiers other) const {
500 return isAddressSpaceSupersetOf(other) &&
501 // ObjC GC qualifiers can match, be added, or be removed, but can't
503 (getObjCGCAttr() == other.getObjCGCAttr() || !hasObjCGCAttr() ||
504 !other.hasObjCGCAttr()) &&
505 // ObjC lifetime qualifiers must match exactly.
506 getObjCLifetime() == other.getObjCLifetime() &&
507 // CVR qualifiers may subset.
508 (((Mask & CVRMask) | (other.Mask & CVRMask)) == (Mask & CVRMask)) &&
509 // U qualifier may superset.
510 (!other.hasUnaligned() || hasUnaligned());
513 /// Determines if these qualifiers compatibly include another set of
514 /// qualifiers from the narrow perspective of Objective-C ARC lifetime.
516 /// One set of Objective-C lifetime qualifiers compatibly includes the other
517 /// if the lifetime qualifiers match, or if both are non-__weak and the
518 /// including set also contains the 'const' qualifier, or both are non-__weak
519 /// and one is None (which can only happen in non-ARC modes).
520 bool compatiblyIncludesObjCLifetime(Qualifiers other) const {
521 if (getObjCLifetime() == other.getObjCLifetime())
524 if (getObjCLifetime() == OCL_Weak || other.getObjCLifetime() == OCL_Weak)
527 if (getObjCLifetime() == OCL_None || other.getObjCLifetime() == OCL_None)
533 /// Determine whether this set of qualifiers is a strict superset of
534 /// another set of qualifiers, not considering qualifier compatibility.
535 bool isStrictSupersetOf(Qualifiers Other) const;
537 bool operator==(Qualifiers Other) const { return Mask == Other.Mask; }
538 bool operator!=(Qualifiers Other) const { return Mask != Other.Mask; }
540 explicit operator bool() const { return hasQualifiers(); }
542 Qualifiers &operator+=(Qualifiers R) {
547 // Union two qualifier sets. If an enumerated qualifier appears
548 // in both sets, use the one from the right.
549 friend Qualifiers operator+(Qualifiers L, Qualifiers R) {
554 Qualifiers &operator-=(Qualifiers R) {
559 /// Compute the difference between two qualifier sets.
560 friend Qualifiers operator-(Qualifiers L, Qualifiers R) {
565 std::string getAsString() const;
566 std::string getAsString(const PrintingPolicy &Policy) const;
568 bool isEmptyWhenPrinted(const PrintingPolicy &Policy) const;
569 void print(raw_ostream &OS, const PrintingPolicy &Policy,
570 bool appendSpaceIfNonEmpty = false) const;
572 void Profile(llvm::FoldingSetNodeID &ID) const {
577 // bits: |0 1 2|3|4 .. 5|6 .. 8|9 ... 31|
578 // |C R V|U|GCAttr|Lifetime|AddressSpace|
581 static const uint32_t UMask = 0x8;
582 static const uint32_t UShift = 3;
583 static const uint32_t GCAttrMask = 0x30;
584 static const uint32_t GCAttrShift = 4;
585 static const uint32_t LifetimeMask = 0x1C0;
586 static const uint32_t LifetimeShift = 6;
587 static const uint32_t AddressSpaceMask =
588 ~(CVRMask | UMask | GCAttrMask | LifetimeMask);
589 static const uint32_t AddressSpaceShift = 9;
592 /// A std::pair-like structure for storing a qualified type split
593 /// into its local qualifiers and its locally-unqualified type.
594 struct SplitQualType {
595 /// The locally-unqualified type.
596 const Type *Ty = nullptr;
598 /// The local qualifiers.
601 SplitQualType() = default;
602 SplitQualType(const Type *ty, Qualifiers qs) : Ty(ty), Quals(qs) {}
604 SplitQualType getSingleStepDesugaredType() const; // end of this file
606 // Make std::tie work.
607 std::pair<const Type *,Qualifiers> asPair() const {
608 return std::pair<const Type *, Qualifiers>(Ty, Quals);
611 friend bool operator==(SplitQualType a, SplitQualType b) {
612 return a.Ty == b.Ty && a.Quals == b.Quals;
614 friend bool operator!=(SplitQualType a, SplitQualType b) {
615 return a.Ty != b.Ty || a.Quals != b.Quals;
619 /// The kind of type we are substituting Objective-C type arguments into.
621 /// The kind of substitution affects the replacement of type parameters when
622 /// no concrete type information is provided, e.g., when dealing with an
623 /// unspecialized type.
624 enum class ObjCSubstitutionContext {
625 /// An ordinary type.
628 /// The result type of a method or function.
631 /// The parameter type of a method or function.
634 /// The type of a property.
637 /// The superclass of a type.
641 /// A (possibly-)qualified type.
643 /// For efficiency, we don't store CV-qualified types as nodes on their
644 /// own: instead each reference to a type stores the qualifiers. This
645 /// greatly reduces the number of nodes we need to allocate for types (for
646 /// example we only need one for 'int', 'const int', 'volatile int',
647 /// 'const volatile int', etc).
649 /// As an added efficiency bonus, instead of making this a pair, we
650 /// just store the two bits we care about in the low bits of the
651 /// pointer. To handle the packing/unpacking, we make QualType be a
652 /// simple wrapper class that acts like a smart pointer. A third bit
653 /// indicates whether there are extended qualifiers present, in which
654 /// case the pointer points to a special structure.
656 friend class QualifierCollector;
658 // Thankfully, these are efficiently composable.
659 llvm::PointerIntPair<llvm::PointerUnion<const Type *, const ExtQuals *>,
660 Qualifiers::FastWidth> Value;
662 const ExtQuals *getExtQualsUnsafe() const {
663 return Value.getPointer().get<const ExtQuals*>();
666 const Type *getTypePtrUnsafe() const {
667 return Value.getPointer().get<const Type*>();
670 const ExtQualsTypeCommonBase *getCommonPtr() const {
671 assert(!isNull() && "Cannot retrieve a NULL type pointer");
672 auto CommonPtrVal = reinterpret_cast<uintptr_t>(Value.getOpaqueValue());
673 CommonPtrVal &= ~(uintptr_t)((1 << TypeAlignmentInBits) - 1);
674 return reinterpret_cast<ExtQualsTypeCommonBase*>(CommonPtrVal);
678 QualType() = default;
679 QualType(const Type *Ptr, unsigned Quals) : Value(Ptr, Quals) {}
680 QualType(const ExtQuals *Ptr, unsigned Quals) : Value(Ptr, Quals) {}
682 unsigned getLocalFastQualifiers() const { return Value.getInt(); }
683 void setLocalFastQualifiers(unsigned Quals) { Value.setInt(Quals); }
685 /// Retrieves a pointer to the underlying (unqualified) type.
687 /// This function requires that the type not be NULL. If the type might be
688 /// NULL, use the (slightly less efficient) \c getTypePtrOrNull().
689 const Type *getTypePtr() const;
691 const Type *getTypePtrOrNull() const;
693 /// Retrieves a pointer to the name of the base type.
694 const IdentifierInfo *getBaseTypeIdentifier() const;
696 /// Divides a QualType into its unqualified type and a set of local
698 SplitQualType split() const;
700 void *getAsOpaquePtr() const { return Value.getOpaqueValue(); }
702 static QualType getFromOpaquePtr(const void *Ptr) {
704 T.Value.setFromOpaqueValue(const_cast<void*>(Ptr));
708 const Type &operator*() const {
709 return *getTypePtr();
712 const Type *operator->() const {
716 bool isCanonical() const;
717 bool isCanonicalAsParam() const;
719 /// Return true if this QualType doesn't point to a type yet.
720 bool isNull() const {
721 return Value.getPointer().isNull();
724 /// Determine whether this particular QualType instance has the
725 /// "const" qualifier set, without looking through typedefs that may have
726 /// added "const" at a different level.
727 bool isLocalConstQualified() const {
728 return (getLocalFastQualifiers() & Qualifiers::Const);
731 /// Determine whether this type is const-qualified.
732 bool isConstQualified() const;
734 /// Determine whether this particular QualType instance has the
735 /// "restrict" qualifier set, without looking through typedefs that may have
736 /// added "restrict" at a different level.
737 bool isLocalRestrictQualified() const {
738 return (getLocalFastQualifiers() & Qualifiers::Restrict);
741 /// Determine whether this type is restrict-qualified.
742 bool isRestrictQualified() const;
744 /// Determine whether this particular QualType instance has the
745 /// "volatile" qualifier set, without looking through typedefs that may have
746 /// added "volatile" at a different level.
747 bool isLocalVolatileQualified() const {
748 return (getLocalFastQualifiers() & Qualifiers::Volatile);
751 /// Determine whether this type is volatile-qualified.
752 bool isVolatileQualified() const;
754 /// Determine whether this particular QualType instance has any
755 /// qualifiers, without looking through any typedefs that might add
756 /// qualifiers at a different level.
757 bool hasLocalQualifiers() const {
758 return getLocalFastQualifiers() || hasLocalNonFastQualifiers();
761 /// Determine whether this type has any qualifiers.
762 bool hasQualifiers() const;
764 /// Determine whether this particular QualType instance has any
765 /// "non-fast" qualifiers, e.g., those that are stored in an ExtQualType
767 bool hasLocalNonFastQualifiers() const {
768 return Value.getPointer().is<const ExtQuals*>();
771 /// Retrieve the set of qualifiers local to this particular QualType
772 /// instance, not including any qualifiers acquired through typedefs or
774 Qualifiers getLocalQualifiers() const;
776 /// Retrieve the set of qualifiers applied to this type.
777 Qualifiers getQualifiers() const;
779 /// Retrieve the set of CVR (const-volatile-restrict) qualifiers
780 /// local to this particular QualType instance, not including any qualifiers
781 /// acquired through typedefs or other sugar.
782 unsigned getLocalCVRQualifiers() const {
783 return getLocalFastQualifiers();
786 /// Retrieve the set of CVR (const-volatile-restrict) qualifiers
787 /// applied to this type.
788 unsigned getCVRQualifiers() const;
790 bool isConstant(const ASTContext& Ctx) const {
791 return QualType::isConstant(*this, Ctx);
794 /// Determine whether this is a Plain Old Data (POD) type (C++ 3.9p10).
795 bool isPODType(const ASTContext &Context) const;
797 /// Return true if this is a POD type according to the rules of the C++98
798 /// standard, regardless of the current compilation's language.
799 bool isCXX98PODType(const ASTContext &Context) const;
801 /// Return true if this is a POD type according to the more relaxed rules
802 /// of the C++11 standard, regardless of the current compilation's language.
803 /// (C++0x [basic.types]p9). Note that, unlike
804 /// CXXRecordDecl::isCXX11StandardLayout, this takes DRs into account.
805 bool isCXX11PODType(const ASTContext &Context) const;
807 /// Return true if this is a trivial type per (C++0x [basic.types]p9)
808 bool isTrivialType(const ASTContext &Context) const;
810 /// Return true if this is a trivially copyable type (C++0x [basic.types]p9)
811 bool isTriviallyCopyableType(const ASTContext &Context) const;
814 /// Returns true if it is a class and it might be dynamic.
815 bool mayBeDynamicClass() const;
817 /// Returns true if it is not a class or if the class might not be dynamic.
818 bool mayBeNotDynamicClass() const;
820 // Don't promise in the API that anything besides 'const' can be
823 /// Add the `const` type qualifier to this QualType.
825 addFastQualifiers(Qualifiers::Const);
827 QualType withConst() const {
828 return withFastQualifiers(Qualifiers::Const);
831 /// Add the `volatile` type qualifier to this QualType.
833 addFastQualifiers(Qualifiers::Volatile);
835 QualType withVolatile() const {
836 return withFastQualifiers(Qualifiers::Volatile);
839 /// Add the `restrict` qualifier to this QualType.
841 addFastQualifiers(Qualifiers::Restrict);
843 QualType withRestrict() const {
844 return withFastQualifiers(Qualifiers::Restrict);
847 QualType withCVRQualifiers(unsigned CVR) const {
848 return withFastQualifiers(CVR);
851 void addFastQualifiers(unsigned TQs) {
852 assert(!(TQs & ~Qualifiers::FastMask)
853 && "non-fast qualifier bits set in mask!");
854 Value.setInt(Value.getInt() | TQs);
857 void removeLocalConst();
858 void removeLocalVolatile();
859 void removeLocalRestrict();
860 void removeLocalCVRQualifiers(unsigned Mask);
862 void removeLocalFastQualifiers() { Value.setInt(0); }
863 void removeLocalFastQualifiers(unsigned Mask) {
864 assert(!(Mask & ~Qualifiers::FastMask) && "mask has non-fast qualifiers");
865 Value.setInt(Value.getInt() & ~Mask);
868 // Creates a type with the given qualifiers in addition to any
869 // qualifiers already on this type.
870 QualType withFastQualifiers(unsigned TQs) const {
872 T.addFastQualifiers(TQs);
876 // Creates a type with exactly the given fast qualifiers, removing
877 // any existing fast qualifiers.
878 QualType withExactLocalFastQualifiers(unsigned TQs) const {
879 return withoutLocalFastQualifiers().withFastQualifiers(TQs);
882 // Removes fast qualifiers, but leaves any extended qualifiers in place.
883 QualType withoutLocalFastQualifiers() const {
885 T.removeLocalFastQualifiers();
889 QualType getCanonicalType() const;
891 /// Return this type with all of the instance-specific qualifiers
892 /// removed, but without removing any qualifiers that may have been applied
893 /// through typedefs.
894 QualType getLocalUnqualifiedType() const { return QualType(getTypePtr(), 0); }
896 /// Retrieve the unqualified variant of the given type,
897 /// removing as little sugar as possible.
899 /// This routine looks through various kinds of sugar to find the
900 /// least-desugared type that is unqualified. For example, given:
903 /// typedef int Integer;
904 /// typedef const Integer CInteger;
905 /// typedef CInteger DifferenceType;
908 /// Executing \c getUnqualifiedType() on the type \c DifferenceType will
909 /// desugar until we hit the type \c Integer, which has no qualifiers on it.
911 /// The resulting type might still be qualified if it's sugar for an array
912 /// type. To strip qualifiers even from within a sugared array type, use
913 /// ASTContext::getUnqualifiedArrayType.
914 inline QualType getUnqualifiedType() const;
916 /// Retrieve the unqualified variant of the given type, removing as little
917 /// sugar as possible.
919 /// Like getUnqualifiedType(), but also returns the set of
920 /// qualifiers that were built up.
922 /// The resulting type might still be qualified if it's sugar for an array
923 /// type. To strip qualifiers even from within a sugared array type, use
924 /// ASTContext::getUnqualifiedArrayType.
925 inline SplitQualType getSplitUnqualifiedType() const;
927 /// Determine whether this type is more qualified than the other
928 /// given type, requiring exact equality for non-CVR qualifiers.
929 bool isMoreQualifiedThan(QualType Other) const;
931 /// Determine whether this type is at least as qualified as the other
932 /// given type, requiring exact equality for non-CVR qualifiers.
933 bool isAtLeastAsQualifiedAs(QualType Other) const;
935 QualType getNonReferenceType() const;
937 /// Determine the type of a (typically non-lvalue) expression with the
938 /// specified result type.
940 /// This routine should be used for expressions for which the return type is
941 /// explicitly specified (e.g., in a cast or call) and isn't necessarily
942 /// an lvalue. It removes a top-level reference (since there are no
943 /// expressions of reference type) and deletes top-level cvr-qualifiers
944 /// from non-class types (in C++) or all types (in C).
945 QualType getNonLValueExprType(const ASTContext &Context) const;
947 /// Return the specified type with any "sugar" removed from
948 /// the type. This takes off typedefs, typeof's etc. If the outer level of
949 /// the type is already concrete, it returns it unmodified. This is similar
950 /// to getting the canonical type, but it doesn't remove *all* typedefs. For
951 /// example, it returns "T*" as "T*", (not as "int*"), because the pointer is
954 /// Qualifiers are left in place.
955 QualType getDesugaredType(const ASTContext &Context) const {
956 return getDesugaredType(*this, Context);
959 SplitQualType getSplitDesugaredType() const {
960 return getSplitDesugaredType(*this);
963 /// Return the specified type with one level of "sugar" removed from
966 /// This routine takes off the first typedef, typeof, etc. If the outer level
967 /// of the type is already concrete, it returns it unmodified.
968 QualType getSingleStepDesugaredType(const ASTContext &Context) const {
969 return getSingleStepDesugaredTypeImpl(*this, Context);
972 /// Returns the specified type after dropping any
973 /// outer-level parentheses.
974 QualType IgnoreParens() const {
975 if (isa<ParenType>(*this))
976 return QualType::IgnoreParens(*this);
980 /// Indicate whether the specified types and qualifiers are identical.
981 friend bool operator==(const QualType &LHS, const QualType &RHS) {
982 return LHS.Value == RHS.Value;
984 friend bool operator!=(const QualType &LHS, const QualType &RHS) {
985 return LHS.Value != RHS.Value;
988 static std::string getAsString(SplitQualType split,
989 const PrintingPolicy &Policy) {
990 return getAsString(split.Ty, split.Quals, Policy);
992 static std::string getAsString(const Type *ty, Qualifiers qs,
993 const PrintingPolicy &Policy);
995 std::string getAsString() const;
996 std::string getAsString(const PrintingPolicy &Policy) const;
998 void print(raw_ostream &OS, const PrintingPolicy &Policy,
999 const Twine &PlaceHolder = Twine(),
1000 unsigned Indentation = 0) const {
1001 print(split(), OS, Policy, PlaceHolder, Indentation);
1004 static void print(SplitQualType split, raw_ostream &OS,
1005 const PrintingPolicy &policy, const Twine &PlaceHolder,
1006 unsigned Indentation = 0) {
1007 return print(split.Ty, split.Quals, OS, policy, PlaceHolder, Indentation);
1010 static void print(const Type *ty, Qualifiers qs,
1011 raw_ostream &OS, const PrintingPolicy &policy,
1012 const Twine &PlaceHolder,
1013 unsigned Indentation = 0);
1015 void getAsStringInternal(std::string &Str,
1016 const PrintingPolicy &Policy) const {
1017 return getAsStringInternal(split(), Str, Policy);
1020 static void getAsStringInternal(SplitQualType split, std::string &out,
1021 const PrintingPolicy &policy) {
1022 return getAsStringInternal(split.Ty, split.Quals, out, policy);
1025 static void getAsStringInternal(const Type *ty, Qualifiers qs,
1027 const PrintingPolicy &policy);
1029 class StreamedQualTypeHelper {
1031 const PrintingPolicy &Policy;
1032 const Twine &PlaceHolder;
1033 unsigned Indentation;
1036 StreamedQualTypeHelper(const QualType &T, const PrintingPolicy &Policy,
1037 const Twine &PlaceHolder, unsigned Indentation)
1038 : T(T), Policy(Policy), PlaceHolder(PlaceHolder),
1039 Indentation(Indentation) {}
1041 friend raw_ostream &operator<<(raw_ostream &OS,
1042 const StreamedQualTypeHelper &SQT) {
1043 SQT.T.print(OS, SQT.Policy, SQT.PlaceHolder, SQT.Indentation);
1048 StreamedQualTypeHelper stream(const PrintingPolicy &Policy,
1049 const Twine &PlaceHolder = Twine(),
1050 unsigned Indentation = 0) const {
1051 return StreamedQualTypeHelper(*this, Policy, PlaceHolder, Indentation);
1054 void dump(const char *s) const;
1056 void dump(llvm::raw_ostream &OS) const;
1058 void Profile(llvm::FoldingSetNodeID &ID) const {
1059 ID.AddPointer(getAsOpaquePtr());
1062 /// Return the address space of this type.
1063 inline LangAS getAddressSpace() const;
1065 /// Returns gc attribute of this type.
1066 inline Qualifiers::GC getObjCGCAttr() const;
1068 /// true when Type is objc's weak.
1069 bool isObjCGCWeak() const {
1070 return getObjCGCAttr() == Qualifiers::Weak;
1073 /// true when Type is objc's strong.
1074 bool isObjCGCStrong() const {
1075 return getObjCGCAttr() == Qualifiers::Strong;
1078 /// Returns lifetime attribute of this type.
1079 Qualifiers::ObjCLifetime getObjCLifetime() const {
1080 return getQualifiers().getObjCLifetime();
1083 bool hasNonTrivialObjCLifetime() const {
1084 return getQualifiers().hasNonTrivialObjCLifetime();
1087 bool hasStrongOrWeakObjCLifetime() const {
1088 return getQualifiers().hasStrongOrWeakObjCLifetime();
1091 // true when Type is objc's weak and weak is enabled but ARC isn't.
1092 bool isNonWeakInMRRWithObjCWeak(const ASTContext &Context) const;
1094 enum PrimitiveDefaultInitializeKind {
1095 /// The type does not fall into any of the following categories. Note that
1096 /// this case is zero-valued so that values of this enum can be used as a
1097 /// boolean condition for non-triviality.
1100 /// The type is an Objective-C retainable pointer type that is qualified
1101 /// with the ARC __strong qualifier.
1104 /// The type is an Objective-C retainable pointer type that is qualified
1105 /// with the ARC __weak qualifier.
1108 /// The type is a struct containing a field whose type is not PCK_Trivial.
1112 /// Functions to query basic properties of non-trivial C struct types.
1114 /// Check if this is a non-trivial type that would cause a C struct
1115 /// transitively containing this type to be non-trivial to default initialize
1116 /// and return the kind.
1117 PrimitiveDefaultInitializeKind
1118 isNonTrivialToPrimitiveDefaultInitialize() const;
1120 enum PrimitiveCopyKind {
1121 /// The type does not fall into any of the following categories. Note that
1122 /// this case is zero-valued so that values of this enum can be used as a
1123 /// boolean condition for non-triviality.
1126 /// The type would be trivial except that it is volatile-qualified. Types
1127 /// that fall into one of the other non-trivial cases may additionally be
1128 /// volatile-qualified.
1129 PCK_VolatileTrivial,
1131 /// The type is an Objective-C retainable pointer type that is qualified
1132 /// with the ARC __strong qualifier.
1135 /// The type is an Objective-C retainable pointer type that is qualified
1136 /// with the ARC __weak qualifier.
1139 /// The type is a struct containing a field whose type is neither
1140 /// PCK_Trivial nor PCK_VolatileTrivial.
1141 /// Note that a C++ struct type does not necessarily match this; C++ copying
1142 /// semantics are too complex to express here, in part because they depend
1143 /// on the exact constructor or assignment operator that is chosen by
1144 /// overload resolution to do the copy.
1148 /// Check if this is a non-trivial type that would cause a C struct
1149 /// transitively containing this type to be non-trivial to copy and return the
1151 PrimitiveCopyKind isNonTrivialToPrimitiveCopy() const;
1153 /// Check if this is a non-trivial type that would cause a C struct
1154 /// transitively containing this type to be non-trivial to destructively
1155 /// move and return the kind. Destructive move in this context is a C++-style
1156 /// move in which the source object is placed in a valid but unspecified state
1157 /// after it is moved, as opposed to a truly destructive move in which the
1158 /// source object is placed in an uninitialized state.
1159 PrimitiveCopyKind isNonTrivialToPrimitiveDestructiveMove() const;
1161 enum DestructionKind {
1164 DK_objc_strong_lifetime,
1165 DK_objc_weak_lifetime,
1166 DK_nontrivial_c_struct
1169 /// Returns a nonzero value if objects of this type require
1170 /// non-trivial work to clean up after. Non-zero because it's
1171 /// conceivable that qualifiers (objc_gc(weak)?) could make
1172 /// something require destruction.
1173 DestructionKind isDestructedType() const {
1174 return isDestructedTypeImpl(*this);
1177 /// Determine whether expressions of the given type are forbidden
1178 /// from being lvalues in C.
1180 /// The expression types that are forbidden to be lvalues are:
1181 /// - 'void', but not qualified void
1182 /// - function types
1184 /// The exact rule here is C99 6.3.2.1:
1185 /// An lvalue is an expression with an object type or an incomplete
1186 /// type other than void.
1187 bool isCForbiddenLValueType() const;
1189 /// Substitute type arguments for the Objective-C type parameters used in the
1192 /// \param ctx ASTContext in which the type exists.
1194 /// \param typeArgs The type arguments that will be substituted for the
1195 /// Objective-C type parameters in the subject type, which are generally
1196 /// computed via \c Type::getObjCSubstitutions. If empty, the type
1197 /// parameters will be replaced with their bounds or id/Class, as appropriate
1198 /// for the context.
1200 /// \param context The context in which the subject type was written.
1202 /// \returns the resulting type.
1203 QualType substObjCTypeArgs(ASTContext &ctx,
1204 ArrayRef<QualType> typeArgs,
1205 ObjCSubstitutionContext context) const;
1207 /// Substitute type arguments from an object type for the Objective-C type
1208 /// parameters used in the subject type.
1210 /// This operation combines the computation of type arguments for
1211 /// substitution (\c Type::getObjCSubstitutions) with the actual process of
1212 /// substitution (\c QualType::substObjCTypeArgs) for the convenience of
1213 /// callers that need to perform a single substitution in isolation.
1215 /// \param objectType The type of the object whose member type we're
1216 /// substituting into. For example, this might be the receiver of a message
1217 /// or the base of a property access.
1219 /// \param dc The declaration context from which the subject type was
1220 /// retrieved, which indicates (for example) which type parameters should
1223 /// \param context The context in which the subject type was written.
1225 /// \returns the subject type after replacing all of the Objective-C type
1226 /// parameters with their corresponding arguments.
1227 QualType substObjCMemberType(QualType objectType,
1228 const DeclContext *dc,
1229 ObjCSubstitutionContext context) const;
1231 /// Strip Objective-C "__kindof" types from the given type.
1232 QualType stripObjCKindOfType(const ASTContext &ctx) const;
1234 /// Remove all qualifiers including _Atomic.
1235 QualType getAtomicUnqualifiedType() const;
1238 // These methods are implemented in a separate translation unit;
1239 // "static"-ize them to avoid creating temporary QualTypes in the
1241 static bool isConstant(QualType T, const ASTContext& Ctx);
1242 static QualType getDesugaredType(QualType T, const ASTContext &Context);
1243 static SplitQualType getSplitDesugaredType(QualType T);
1244 static SplitQualType getSplitUnqualifiedTypeImpl(QualType type);
1245 static QualType getSingleStepDesugaredTypeImpl(QualType type,
1246 const ASTContext &C);
1247 static QualType IgnoreParens(QualType T);
1248 static DestructionKind isDestructedTypeImpl(QualType type);
1251 } // namespace clang
1255 /// Implement simplify_type for QualType, so that we can dyn_cast from QualType
1256 /// to a specific Type class.
1257 template<> struct simplify_type< ::clang::QualType> {
1258 using SimpleType = const ::clang::Type *;
1260 static SimpleType getSimplifiedValue(::clang::QualType Val) {
1261 return Val.getTypePtr();
1265 // Teach SmallPtrSet that QualType is "basically a pointer".
1267 struct PointerLikeTypeTraits<clang::QualType> {
1268 static inline void *getAsVoidPointer(clang::QualType P) {
1269 return P.getAsOpaquePtr();
1272 static inline clang::QualType getFromVoidPointer(void *P) {
1273 return clang::QualType::getFromOpaquePtr(P);
1276 // Various qualifiers go in low bits.
1277 enum { NumLowBitsAvailable = 0 };
1284 /// Base class that is common to both the \c ExtQuals and \c Type
1285 /// classes, which allows \c QualType to access the common fields between the
1287 class ExtQualsTypeCommonBase {
1288 friend class ExtQuals;
1289 friend class QualType;
1292 /// The "base" type of an extended qualifiers type (\c ExtQuals) or
1293 /// a self-referential pointer (for \c Type).
1295 /// This pointer allows an efficient mapping from a QualType to its
1296 /// underlying type pointer.
1297 const Type *const BaseType;
1299 /// The canonical type of this type. A QualType.
1300 QualType CanonicalType;
1302 ExtQualsTypeCommonBase(const Type *baseType, QualType canon)
1303 : BaseType(baseType), CanonicalType(canon) {}
1306 /// We can encode up to four bits in the low bits of a
1307 /// type pointer, but there are many more type qualifiers that we want
1308 /// to be able to apply to an arbitrary type. Therefore we have this
1309 /// struct, intended to be heap-allocated and used by QualType to
1310 /// store qualifiers.
1312 /// The current design tags the 'const', 'restrict', and 'volatile' qualifiers
1313 /// in three low bits on the QualType pointer; a fourth bit records whether
1314 /// the pointer is an ExtQuals node. The extended qualifiers (address spaces,
1315 /// Objective-C GC attributes) are much more rare.
1316 class ExtQuals : public ExtQualsTypeCommonBase, public llvm::FoldingSetNode {
1317 // NOTE: changing the fast qualifiers should be straightforward as
1318 // long as you don't make 'const' non-fast.
1320 // a) Modify the bitmasks (Qualifiers::TQ and DeclSpec::TQ).
1321 // Fast qualifiers must occupy the low-order bits.
1322 // b) Update Qualifiers::FastWidth and FastMask.
1324 // a) Update is{Volatile,Restrict}Qualified(), defined inline.
1325 // b) Update remove{Volatile,Restrict}, defined near the end of
1328 // a) Update get{Volatile,Restrict}Type.
1330 /// The immutable set of qualifiers applied by this node. Always contains
1331 /// extended qualifiers.
1334 ExtQuals *this_() { return this; }
1337 ExtQuals(const Type *baseType, QualType canon, Qualifiers quals)
1338 : ExtQualsTypeCommonBase(baseType,
1339 canon.isNull() ? QualType(this_(), 0) : canon),
1341 assert(Quals.hasNonFastQualifiers()
1342 && "ExtQuals created with no fast qualifiers");
1343 assert(!Quals.hasFastQualifiers()
1344 && "ExtQuals created with fast qualifiers");
1347 Qualifiers getQualifiers() const { return Quals; }
1349 bool hasObjCGCAttr() const { return Quals.hasObjCGCAttr(); }
1350 Qualifiers::GC getObjCGCAttr() const { return Quals.getObjCGCAttr(); }
1352 bool hasObjCLifetime() const { return Quals.hasObjCLifetime(); }
1353 Qualifiers::ObjCLifetime getObjCLifetime() const {
1354 return Quals.getObjCLifetime();
1357 bool hasAddressSpace() const { return Quals.hasAddressSpace(); }
1358 LangAS getAddressSpace() const { return Quals.getAddressSpace(); }
1360 const Type *getBaseType() const { return BaseType; }
1363 void Profile(llvm::FoldingSetNodeID &ID) const {
1364 Profile(ID, getBaseType(), Quals);
1367 static void Profile(llvm::FoldingSetNodeID &ID,
1368 const Type *BaseType,
1370 assert(!Quals.hasFastQualifiers() && "fast qualifiers in ExtQuals hash!");
1371 ID.AddPointer(BaseType);
1376 /// The kind of C++11 ref-qualifier associated with a function type.
1377 /// This determines whether a member function's "this" object can be an
1378 /// lvalue, rvalue, or neither.
1379 enum RefQualifierKind {
1380 /// No ref-qualifier was provided.
1383 /// An lvalue ref-qualifier was provided (\c &).
1386 /// An rvalue ref-qualifier was provided (\c &&).
1390 /// Which keyword(s) were used to create an AutoType.
1391 enum class AutoTypeKeyword {
1398 /// __auto_type (GNU extension)
1402 /// The base class of the type hierarchy.
1404 /// A central concept with types is that each type always has a canonical
1405 /// type. A canonical type is the type with any typedef names stripped out
1406 /// of it or the types it references. For example, consider:
1408 /// typedef int foo;
1409 /// typedef foo* bar;
1410 /// 'int *' 'foo *' 'bar'
1412 /// There will be a Type object created for 'int'. Since int is canonical, its
1413 /// CanonicalType pointer points to itself. There is also a Type for 'foo' (a
1414 /// TypedefType). Its CanonicalType pointer points to the 'int' Type. Next
1415 /// there is a PointerType that represents 'int*', which, like 'int', is
1416 /// canonical. Finally, there is a PointerType type for 'foo*' whose canonical
1417 /// type is 'int*', and there is a TypedefType for 'bar', whose canonical type
1420 /// Non-canonical types are useful for emitting diagnostics, without losing
1421 /// information about typedefs being used. Canonical types are useful for type
1422 /// comparisons (they allow by-pointer equality tests) and useful for reasoning
1423 /// about whether something has a particular form (e.g. is a function type),
1424 /// because they implicitly, recursively, strip all typedefs out of a type.
1426 /// Types, once created, are immutable.
1428 class Type : public ExtQualsTypeCommonBase {
1431 #define TYPE(Class, Base) Class,
1432 #define LAST_TYPE(Class) TypeLast = Class,
1433 #define ABSTRACT_TYPE(Class, Base)
1434 #include "clang/AST/TypeNodes.def"
1435 TagFirst = Record, TagLast = Enum
1439 /// Bitfields required by the Type class.
1440 class TypeBitfields {
1442 template <class T> friend class TypePropertyCache;
1444 /// TypeClass bitfield - Enum that specifies what subclass this belongs to.
1447 /// Whether this type is a dependent type (C++ [temp.dep.type]).
1448 unsigned Dependent : 1;
1450 /// Whether this type somehow involves a template parameter, even
1451 /// if the resolution of the type does not depend on a template parameter.
1452 unsigned InstantiationDependent : 1;
1454 /// Whether this type is a variably-modified type (C99 6.7.5).
1455 unsigned VariablyModified : 1;
1457 /// Whether this type contains an unexpanded parameter pack
1458 /// (for C++11 variadic templates).
1459 unsigned ContainsUnexpandedParameterPack : 1;
1461 /// True if the cache (i.e. the bitfields here starting with
1462 /// 'Cache') is valid.
1463 mutable unsigned CacheValid : 1;
1465 /// Linkage of this type.
1466 mutable unsigned CachedLinkage : 3;
1468 /// Whether this type involves and local or unnamed types.
1469 mutable unsigned CachedLocalOrUnnamed : 1;
1471 /// Whether this type comes from an AST file.
1472 mutable unsigned FromAST : 1;
1474 bool isCacheValid() const {
1478 Linkage getLinkage() const {
1479 assert(isCacheValid() && "getting linkage from invalid cache");
1480 return static_cast<Linkage>(CachedLinkage);
1483 bool hasLocalOrUnnamedType() const {
1484 assert(isCacheValid() && "getting linkage from invalid cache");
1485 return CachedLocalOrUnnamed;
1488 enum { NumTypeBits = 18 };
1491 // These classes allow subclasses to somewhat cleanly pack bitfields
1494 class ArrayTypeBitfields {
1495 friend class ArrayType;
1497 unsigned : NumTypeBits;
1499 /// CVR qualifiers from declarations like
1500 /// 'int X[static restrict 4]'. For function parameters only.
1501 unsigned IndexTypeQuals : 3;
1503 /// Storage class qualifiers from declarations like
1504 /// 'int X[static restrict 4]'. For function parameters only.
1505 /// Actually an ArrayType::ArraySizeModifier.
1506 unsigned SizeModifier : 3;
1509 class BuiltinTypeBitfields {
1510 friend class BuiltinType;
1512 unsigned : NumTypeBits;
1514 /// The kind (BuiltinType::Kind) of builtin type this is.
1518 class FunctionTypeBitfields {
1519 friend class FunctionProtoType;
1520 friend class FunctionType;
1522 unsigned : NumTypeBits;
1524 /// Extra information which affects how the function is called, like
1525 /// regparm and the calling convention.
1526 unsigned ExtInfo : 12;
1528 /// Used only by FunctionProtoType, put here to pack with the
1529 /// other bitfields.
1530 /// The qualifiers are part of FunctionProtoType because...
1532 /// C++ 8.3.5p4: The return type, the parameter type list and the
1533 /// cv-qualifier-seq, [...], are part of the function type.
1534 unsigned TypeQuals : 4;
1536 /// The ref-qualifier associated with a \c FunctionProtoType.
1538 /// This is a value of type \c RefQualifierKind.
1539 unsigned RefQualifier : 2;
1542 class ObjCObjectTypeBitfields {
1543 friend class ObjCObjectType;
1545 unsigned : NumTypeBits;
1547 /// The number of type arguments stored directly on this object type.
1548 unsigned NumTypeArgs : 7;
1550 /// The number of protocols stored directly on this object type.
1551 unsigned NumProtocols : 6;
1553 /// Whether this is a "kindof" type.
1554 unsigned IsKindOf : 1;
1557 static_assert(NumTypeBits + 7 + 6 + 1 <= 32, "Does not fit in an unsigned");
1559 class ReferenceTypeBitfields {
1560 friend class ReferenceType;
1562 unsigned : NumTypeBits;
1564 /// True if the type was originally spelled with an lvalue sigil.
1565 /// This is never true of rvalue references but can also be false
1566 /// on lvalue references because of C++0x [dcl.typedef]p9,
1569 /// typedef int &ref; // lvalue, spelled lvalue
1570 /// typedef int &&rvref; // rvalue
1571 /// ref &a; // lvalue, inner ref, spelled lvalue
1572 /// ref &&a; // lvalue, inner ref
1573 /// rvref &a; // lvalue, inner ref, spelled lvalue
1574 /// rvref &&a; // rvalue, inner ref
1575 unsigned SpelledAsLValue : 1;
1577 /// True if the inner type is a reference type. This only happens
1578 /// in non-canonical forms.
1579 unsigned InnerRef : 1;
1582 class TypeWithKeywordBitfields {
1583 friend class TypeWithKeyword;
1585 unsigned : NumTypeBits;
1587 /// An ElaboratedTypeKeyword. 8 bits for efficient access.
1588 unsigned Keyword : 8;
1591 class VectorTypeBitfields {
1592 friend class VectorType;
1593 friend class DependentVectorType;
1595 unsigned : NumTypeBits;
1597 /// The kind of vector, either a generic vector type or some
1598 /// target-specific vector type such as for AltiVec or Neon.
1599 unsigned VecKind : 3;
1601 /// The number of elements in the vector.
1602 unsigned NumElements : 29 - NumTypeBits;
1604 enum { MaxNumElements = (1 << (29 - NumTypeBits)) - 1 };
1607 class AttributedTypeBitfields {
1608 friend class AttributedType;
1610 unsigned : NumTypeBits;
1612 /// An AttributedType::Kind
1613 unsigned AttrKind : 32 - NumTypeBits;
1616 class AutoTypeBitfields {
1617 friend class AutoType;
1619 unsigned : NumTypeBits;
1621 /// Was this placeholder type spelled as 'auto', 'decltype(auto)',
1622 /// or '__auto_type'? AutoTypeKeyword value.
1623 unsigned Keyword : 2;
1627 TypeBitfields TypeBits;
1628 ArrayTypeBitfields ArrayTypeBits;
1629 AttributedTypeBitfields AttributedTypeBits;
1630 AutoTypeBitfields AutoTypeBits;
1631 BuiltinTypeBitfields BuiltinTypeBits;
1632 FunctionTypeBitfields FunctionTypeBits;
1633 ObjCObjectTypeBitfields ObjCObjectTypeBits;
1634 ReferenceTypeBitfields ReferenceTypeBits;
1635 TypeWithKeywordBitfields TypeWithKeywordBits;
1636 VectorTypeBitfields VectorTypeBits;
1640 template <class T> friend class TypePropertyCache;
1642 /// Set whether this type comes from an AST file.
1643 void setFromAST(bool V = true) const {
1644 TypeBits.FromAST = V;
1648 friend class ASTContext;
1650 Type(TypeClass tc, QualType canon, bool Dependent,
1651 bool InstantiationDependent, bool VariablyModified,
1652 bool ContainsUnexpandedParameterPack)
1653 : ExtQualsTypeCommonBase(this,
1654 canon.isNull() ? QualType(this_(), 0) : canon) {
1656 TypeBits.Dependent = Dependent;
1657 TypeBits.InstantiationDependent = Dependent || InstantiationDependent;
1658 TypeBits.VariablyModified = VariablyModified;
1659 TypeBits.ContainsUnexpandedParameterPack = ContainsUnexpandedParameterPack;
1660 TypeBits.CacheValid = false;
1661 TypeBits.CachedLocalOrUnnamed = false;
1662 TypeBits.CachedLinkage = NoLinkage;
1663 TypeBits.FromAST = false;
1666 // silence VC++ warning C4355: 'this' : used in base member initializer list
1667 Type *this_() { return this; }
1669 void setDependent(bool D = true) {
1670 TypeBits.Dependent = D;
1672 TypeBits.InstantiationDependent = true;
1675 void setInstantiationDependent(bool D = true) {
1676 TypeBits.InstantiationDependent = D; }
1678 void setVariablyModified(bool VM = true) { TypeBits.VariablyModified = VM; }
1680 void setContainsUnexpandedParameterPack(bool PP = true) {
1681 TypeBits.ContainsUnexpandedParameterPack = PP;
1685 friend class ASTReader;
1686 friend class ASTWriter;
1688 Type(const Type &) = delete;
1689 Type &operator=(const Type &) = delete;
1691 TypeClass getTypeClass() const { return static_cast<TypeClass>(TypeBits.TC); }
1693 /// Whether this type comes from an AST file.
1694 bool isFromAST() const { return TypeBits.FromAST; }
1696 /// Whether this type is or contains an unexpanded parameter
1697 /// pack, used to support C++0x variadic templates.
1699 /// A type that contains a parameter pack shall be expanded by the
1700 /// ellipsis operator at some point. For example, the typedef in the
1701 /// following example contains an unexpanded parameter pack 'T':
1704 /// template<typename ...T>
1706 /// typedef T* pointer_types; // ill-formed; T is a parameter pack.
1710 /// Note that this routine does not specify which
1711 bool containsUnexpandedParameterPack() const {
1712 return TypeBits.ContainsUnexpandedParameterPack;
1715 /// Determines if this type would be canonical if it had no further
1717 bool isCanonicalUnqualified() const {
1718 return CanonicalType == QualType(this, 0);
1721 /// Pull a single level of sugar off of this locally-unqualified type.
1722 /// Users should generally prefer SplitQualType::getSingleStepDesugaredType()
1723 /// or QualType::getSingleStepDesugaredType(const ASTContext&).
1724 QualType getLocallyUnqualifiedSingleStepDesugaredType() const;
1726 /// Types are partitioned into 3 broad categories (C99 6.2.5p1):
1727 /// object types, function types, and incomplete types.
1729 /// Return true if this is an incomplete type.
1730 /// A type that can describe objects, but which lacks information needed to
1731 /// determine its size (e.g. void, or a fwd declared struct). Clients of this
1732 /// routine will need to determine if the size is actually required.
1734 /// Def If non-null, and the type refers to some kind of declaration
1735 /// that can be completed (such as a C struct, C++ class, or Objective-C
1736 /// class), will be set to the declaration.
1737 bool isIncompleteType(NamedDecl **Def = nullptr) const;
1739 /// Return true if this is an incomplete or object
1740 /// type, in other words, not a function type.
1741 bool isIncompleteOrObjectType() const {
1742 return !isFunctionType();
1745 /// Determine whether this type is an object type.
1746 bool isObjectType() const {
1747 // C++ [basic.types]p8:
1748 // An object type is a (possibly cv-qualified) type that is not a
1749 // function type, not a reference type, and not a void type.
1750 return !isReferenceType() && !isFunctionType() && !isVoidType();
1753 /// Return true if this is a literal type
1754 /// (C++11 [basic.types]p10)
1755 bool isLiteralType(const ASTContext &Ctx) const;
1757 /// Test if this type is a standard-layout type.
1758 /// (C++0x [basic.type]p9)
1759 bool isStandardLayoutType() const;
1761 /// Helper methods to distinguish type categories. All type predicates
1762 /// operate on the canonical type, ignoring typedefs and qualifiers.
1764 /// Returns true if the type is a builtin type.
1765 bool isBuiltinType() const;
1767 /// Test for a particular builtin type.
1768 bool isSpecificBuiltinType(unsigned K) const;
1770 /// Test for a type which does not represent an actual type-system type but
1771 /// is instead used as a placeholder for various convenient purposes within
1772 /// Clang. All such types are BuiltinTypes.
1773 bool isPlaceholderType() const;
1774 const BuiltinType *getAsPlaceholderType() const;
1776 /// Test for a specific placeholder type.
1777 bool isSpecificPlaceholderType(unsigned K) const;
1779 /// Test for a placeholder type other than Overload; see
1780 /// BuiltinType::isNonOverloadPlaceholderType.
1781 bool isNonOverloadPlaceholderType() const;
1783 /// isIntegerType() does *not* include complex integers (a GCC extension).
1784 /// isComplexIntegerType() can be used to test for complex integers.
1785 bool isIntegerType() const; // C99 6.2.5p17 (int, char, bool, enum)
1786 bool isEnumeralType() const;
1788 /// Determine whether this type is a scoped enumeration type.
1789 bool isScopedEnumeralType() const;
1790 bool isBooleanType() const;
1791 bool isCharType() const;
1792 bool isWideCharType() const;
1793 bool isChar8Type() const;
1794 bool isChar16Type() const;
1795 bool isChar32Type() const;
1796 bool isAnyCharacterType() const;
1797 bool isIntegralType(const ASTContext &Ctx) const;
1799 /// Determine whether this type is an integral or enumeration type.
1800 bool isIntegralOrEnumerationType() const;
1802 /// Determine whether this type is an integral or unscoped enumeration type.
1803 bool isIntegralOrUnscopedEnumerationType() const;
1805 /// Floating point categories.
1806 bool isRealFloatingType() const; // C99 6.2.5p10 (float, double, long double)
1807 /// isComplexType() does *not* include complex integers (a GCC extension).
1808 /// isComplexIntegerType() can be used to test for complex integers.
1809 bool isComplexType() const; // C99 6.2.5p11 (complex)
1810 bool isAnyComplexType() const; // C99 6.2.5p11 (complex) + Complex Int.
1811 bool isFloatingType() const; // C99 6.2.5p11 (real floating + complex)
1812 bool isHalfType() const; // OpenCL 6.1.1.1, NEON (IEEE 754-2008 half)
1813 bool isFloat16Type() const; // C11 extension ISO/IEC TS 18661
1814 bool isFloat128Type() const;
1815 bool isRealType() const; // C99 6.2.5p17 (real floating + integer)
1816 bool isArithmeticType() const; // C99 6.2.5p18 (integer + floating)
1817 bool isVoidType() const; // C99 6.2.5p19
1818 bool isScalarType() const; // C99 6.2.5p21 (arithmetic + pointers)
1819 bool isAggregateType() const;
1820 bool isFundamentalType() const;
1821 bool isCompoundType() const;
1823 // Type Predicates: Check to see if this type is structurally the specified
1824 // type, ignoring typedefs and qualifiers.
1825 bool isFunctionType() const;
1826 bool isFunctionNoProtoType() const { return getAs<FunctionNoProtoType>(); }
1827 bool isFunctionProtoType() const { return getAs<FunctionProtoType>(); }
1828 bool isPointerType() const;
1829 bool isAnyPointerType() const; // Any C pointer or ObjC object pointer
1830 bool isBlockPointerType() const;
1831 bool isVoidPointerType() const;
1832 bool isReferenceType() const;
1833 bool isLValueReferenceType() const;
1834 bool isRValueReferenceType() const;
1835 bool isFunctionPointerType() const;
1836 bool isMemberPointerType() const;
1837 bool isMemberFunctionPointerType() const;
1838 bool isMemberDataPointerType() const;
1839 bool isArrayType() const;
1840 bool isConstantArrayType() const;
1841 bool isIncompleteArrayType() const;
1842 bool isVariableArrayType() const;
1843 bool isDependentSizedArrayType() const;
1844 bool isRecordType() const;
1845 bool isClassType() const;
1846 bool isStructureType() const;
1847 bool isObjCBoxableRecordType() const;
1848 bool isInterfaceType() const;
1849 bool isStructureOrClassType() const;
1850 bool isUnionType() const;
1851 bool isComplexIntegerType() const; // GCC _Complex integer type.
1852 bool isVectorType() const; // GCC vector type.
1853 bool isExtVectorType() const; // Extended vector type.
1854 bool isDependentAddressSpaceType() const; // value-dependent address space qualifier
1855 bool isObjCObjectPointerType() const; // pointer to ObjC object
1856 bool isObjCRetainableType() const; // ObjC object or block pointer
1857 bool isObjCLifetimeType() const; // (array of)* retainable type
1858 bool isObjCIndirectLifetimeType() const; // (pointer to)* lifetime type
1859 bool isObjCNSObjectType() const; // __attribute__((NSObject))
1860 bool isObjCIndependentClassType() const; // __attribute__((objc_independent_class))
1861 // FIXME: change this to 'raw' interface type, so we can used 'interface' type
1862 // for the common case.
1863 bool isObjCObjectType() const; // NSString or typeof(*(id)0)
1864 bool isObjCQualifiedInterfaceType() const; // NSString<foo>
1865 bool isObjCQualifiedIdType() const; // id<foo>
1866 bool isObjCQualifiedClassType() const; // Class<foo>
1867 bool isObjCObjectOrInterfaceType() const;
1868 bool isObjCIdType() const; // id
1869 bool isObjCInertUnsafeUnretainedType() const;
1871 /// Whether the type is Objective-C 'id' or a __kindof type of an
1872 /// object type, e.g., __kindof NSView * or __kindof id
1875 /// \param bound Will be set to the bound on non-id subtype types,
1876 /// which will be (possibly specialized) Objective-C class type, or
1878 bool isObjCIdOrObjectKindOfType(const ASTContext &ctx,
1879 const ObjCObjectType *&bound) const;
1881 bool isObjCClassType() const; // Class
1883 /// Whether the type is Objective-C 'Class' or a __kindof type of an
1884 /// Class type, e.g., __kindof Class <NSCopying>.
1886 /// Unlike \c isObjCIdOrObjectKindOfType, there is no relevant bound
1887 /// here because Objective-C's type system cannot express "a class
1888 /// object for a subclass of NSFoo".
1889 bool isObjCClassOrClassKindOfType() const;
1891 bool isBlockCompatibleObjCPointerType(ASTContext &ctx) const;
1892 bool isObjCSelType() const; // Class
1893 bool isObjCBuiltinType() const; // 'id' or 'Class'
1894 bool isObjCARCBridgableType() const;
1895 bool isCARCBridgableType() const;
1896 bool isTemplateTypeParmType() const; // C++ template type parameter
1897 bool isNullPtrType() const; // C++11 std::nullptr_t
1898 bool isAlignValT() const; // C++17 std::align_val_t
1899 bool isStdByteType() const; // C++17 std::byte
1900 bool isAtomicType() const; // C11 _Atomic()
1902 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
1903 bool is##Id##Type() const;
1904 #include "clang/Basic/OpenCLImageTypes.def"
1906 bool isImageType() const; // Any OpenCL image type
1908 bool isSamplerT() const; // OpenCL sampler_t
1909 bool isEventT() const; // OpenCL event_t
1910 bool isClkEventT() const; // OpenCL clk_event_t
1911 bool isQueueT() const; // OpenCL queue_t
1912 bool isReserveIDT() const; // OpenCL reserve_id_t
1914 bool isPipeType() const; // OpenCL pipe type
1915 bool isOpenCLSpecificType() const; // Any OpenCL specific type
1917 /// Determines if this type, which must satisfy
1918 /// isObjCLifetimeType(), is implicitly __unsafe_unretained rather
1919 /// than implicitly __strong.
1920 bool isObjCARCImplicitlyUnretainedType() const;
1922 /// Return the implicit lifetime for this type, which must not be dependent.
1923 Qualifiers::ObjCLifetime getObjCARCImplicitLifetime() const;
1925 enum ScalarTypeKind {
1928 STK_ObjCObjectPointer,
1933 STK_IntegralComplex,
1937 /// Given that this is a scalar type, classify it.
1938 ScalarTypeKind getScalarTypeKind() const;
1940 /// Whether this type is a dependent type, meaning that its definition
1941 /// somehow depends on a template parameter (C++ [temp.dep.type]).
1942 bool isDependentType() const { return TypeBits.Dependent; }
1944 /// Determine whether this type is an instantiation-dependent type,
1945 /// meaning that the type involves a template parameter (even if the
1946 /// definition does not actually depend on the type substituted for that
1947 /// template parameter).
1948 bool isInstantiationDependentType() const {
1949 return TypeBits.InstantiationDependent;
1952 /// Determine whether this type is an undeduced type, meaning that
1953 /// it somehow involves a C++11 'auto' type or similar which has not yet been
1955 bool isUndeducedType() const;
1957 /// Whether this type is a variably-modified type (C99 6.7.5).
1958 bool isVariablyModifiedType() const { return TypeBits.VariablyModified; }
1960 /// Whether this type involves a variable-length array type
1961 /// with a definite size.
1962 bool hasSizedVLAType() const;
1964 /// Whether this type is or contains a local or unnamed type.
1965 bool hasUnnamedOrLocalType() const;
1967 bool isOverloadableType() const;
1969 /// Determine wither this type is a C++ elaborated-type-specifier.
1970 bool isElaboratedTypeSpecifier() const;
1972 bool canDecayToPointerType() const;
1974 /// Whether this type is represented natively as a pointer. This includes
1975 /// pointers, references, block pointers, and Objective-C interface,
1976 /// qualified id, and qualified interface types, as well as nullptr_t.
1977 bool hasPointerRepresentation() const;
1979 /// Whether this type can represent an objective pointer type for the
1980 /// purpose of GC'ability
1981 bool hasObjCPointerRepresentation() const;
1983 /// Determine whether this type has an integer representation
1984 /// of some sort, e.g., it is an integer type or a vector.
1985 bool hasIntegerRepresentation() const;
1987 /// Determine whether this type has an signed integer representation
1988 /// of some sort, e.g., it is an signed integer type or a vector.
1989 bool hasSignedIntegerRepresentation() const;
1991 /// Determine whether this type has an unsigned integer representation
1992 /// of some sort, e.g., it is an unsigned integer type or a vector.
1993 bool hasUnsignedIntegerRepresentation() const;
1995 /// Determine whether this type has a floating-point representation
1996 /// of some sort, e.g., it is a floating-point type or a vector thereof.
1997 bool hasFloatingRepresentation() const;
1999 // Type Checking Functions: Check to see if this type is structurally the
2000 // specified type, ignoring typedefs and qualifiers, and return a pointer to
2001 // the best type we can.
2002 const RecordType *getAsStructureType() const;
2003 /// NOTE: getAs*ArrayType are methods on ASTContext.
2004 const RecordType *getAsUnionType() const;
2005 const ComplexType *getAsComplexIntegerType() const; // GCC complex int type.
2006 const ObjCObjectType *getAsObjCInterfaceType() const;
2008 // The following is a convenience method that returns an ObjCObjectPointerType
2009 // for object declared using an interface.
2010 const ObjCObjectPointerType *getAsObjCInterfacePointerType() const;
2011 const ObjCObjectPointerType *getAsObjCQualifiedIdType() const;
2012 const ObjCObjectPointerType *getAsObjCQualifiedClassType() const;
2013 const ObjCObjectType *getAsObjCQualifiedInterfaceType() const;
2015 /// Retrieves the CXXRecordDecl that this type refers to, either
2016 /// because the type is a RecordType or because it is the injected-class-name
2017 /// type of a class template or class template partial specialization.
2018 CXXRecordDecl *getAsCXXRecordDecl() const;
2020 /// Retrieves the RecordDecl this type refers to.
2021 RecordDecl *getAsRecordDecl() const;
2023 /// Retrieves the TagDecl that this type refers to, either
2024 /// because the type is a TagType or because it is the injected-class-name
2025 /// type of a class template or class template partial specialization.
2026 TagDecl *getAsTagDecl() const;
2028 /// If this is a pointer or reference to a RecordType, return the
2029 /// CXXRecordDecl that the type refers to.
2031 /// If this is not a pointer or reference, or the type being pointed to does
2032 /// not refer to a CXXRecordDecl, returns NULL.
2033 const CXXRecordDecl *getPointeeCXXRecordDecl() const;
2035 /// Get the DeducedType whose type will be deduced for a variable with
2036 /// an initializer of this type. This looks through declarators like pointer
2037 /// types, but not through decltype or typedefs.
2038 DeducedType *getContainedDeducedType() const;
2040 /// Get the AutoType whose type will be deduced for a variable with
2041 /// an initializer of this type. This looks through declarators like pointer
2042 /// types, but not through decltype or typedefs.
2043 AutoType *getContainedAutoType() const {
2044 return dyn_cast_or_null<AutoType>(getContainedDeducedType());
2047 /// Determine whether this type was written with a leading 'auto'
2048 /// corresponding to a trailing return type (possibly for a nested
2049 /// function type within a pointer to function type or similar).
2050 bool hasAutoForTrailingReturnType() const;
2052 /// Member-template getAs<specific type>'. Look through sugar for
2053 /// an instance of \<specific type>. This scheme will eventually
2054 /// replace the specific getAsXXXX methods above.
2056 /// There are some specializations of this member template listed
2057 /// immediately following this class.
2058 template <typename T> const T *getAs() const;
2060 /// Member-template getAsAdjusted<specific type>. Look through specific kinds
2061 /// of sugar (parens, attributes, etc) for an instance of \<specific type>.
2062 /// This is used when you need to walk over sugar nodes that represent some
2063 /// kind of type adjustment from a type that was written as a \<specific type>
2064 /// to another type that is still canonically a \<specific type>.
2065 template <typename T> const T *getAsAdjusted() const;
2067 /// A variant of getAs<> for array types which silently discards
2068 /// qualifiers from the outermost type.
2069 const ArrayType *getAsArrayTypeUnsafe() const;
2071 /// Member-template castAs<specific type>. Look through sugar for
2072 /// the underlying instance of \<specific type>.
2074 /// This method has the same relationship to getAs<T> as cast<T> has
2075 /// to dyn_cast<T>; which is to say, the underlying type *must*
2076 /// have the intended type, and this method will never return null.
2077 template <typename T> const T *castAs() const;
2079 /// A variant of castAs<> for array type which silently discards
2080 /// qualifiers from the outermost type.
2081 const ArrayType *castAsArrayTypeUnsafe() const;
2083 /// Get the base element type of this type, potentially discarding type
2084 /// qualifiers. This should never be used when type qualifiers
2086 const Type *getBaseElementTypeUnsafe() const;
2088 /// If this is an array type, return the element type of the array,
2089 /// potentially with type qualifiers missing.
2090 /// This should never be used when type qualifiers are meaningful.
2091 const Type *getArrayElementTypeNoTypeQual() const;
2093 /// If this is a pointer type, return the pointee type.
2094 /// If this is an array type, return the array element type.
2095 /// This should never be used when type qualifiers are meaningful.
2096 const Type *getPointeeOrArrayElementType() const;
2098 /// If this is a pointer, ObjC object pointer, or block
2099 /// pointer, this returns the respective pointee.
2100 QualType getPointeeType() const;
2102 /// Return the specified type with any "sugar" removed from the type,
2103 /// removing any typedefs, typeofs, etc., as well as any qualifiers.
2104 const Type *getUnqualifiedDesugaredType() const;
2106 /// More type predicates useful for type checking/promotion
2107 bool isPromotableIntegerType() const; // C99 6.3.1.1p2
2109 /// Return true if this is an integer type that is
2110 /// signed, according to C99 6.2.5p4 [char, signed char, short, int, long..],
2111 /// or an enum decl which has a signed representation.
2112 bool isSignedIntegerType() const;
2114 /// Return true if this is an integer type that is
2115 /// unsigned, according to C99 6.2.5p6 [which returns true for _Bool],
2116 /// or an enum decl which has an unsigned representation.
2117 bool isUnsignedIntegerType() const;
2119 /// Determines whether this is an integer type that is signed or an
2120 /// enumeration types whose underlying type is a signed integer type.
2121 bool isSignedIntegerOrEnumerationType() const;
2123 /// Determines whether this is an integer type that is unsigned or an
2124 /// enumeration types whose underlying type is a unsigned integer type.
2125 bool isUnsignedIntegerOrEnumerationType() const;
2127 /// Return true if this is a fixed point type according to
2128 /// ISO/IEC JTC1 SC22 WG14 N1169.
2129 bool isFixedPointType() const;
2131 /// Return true if this is a saturated fixed point type according to
2132 /// ISO/IEC JTC1 SC22 WG14 N1169. This type can be signed or unsigned.
2133 bool isSaturatedFixedPointType() const;
2135 /// Return true if this is a saturated fixed point type according to
2136 /// ISO/IEC JTC1 SC22 WG14 N1169. This type can be signed or unsigned.
2137 bool isUnsaturatedFixedPointType() const;
2139 /// Return true if this is a fixed point type that is signed according
2140 /// to ISO/IEC JTC1 SC22 WG14 N1169. This type can also be saturated.
2141 bool isSignedFixedPointType() const;
2143 /// Return true if this is a fixed point type that is unsigned according
2144 /// to ISO/IEC JTC1 SC22 WG14 N1169. This type can also be saturated.
2145 bool isUnsignedFixedPointType() const;
2147 /// Return true if this is not a variable sized type,
2148 /// according to the rules of C99 6.7.5p3. It is not legal to call this on
2149 /// incomplete types.
2150 bool isConstantSizeType() const;
2152 /// Returns true if this type can be represented by some
2153 /// set of type specifiers.
2154 bool isSpecifierType() const;
2156 /// Determine the linkage of this type.
2157 Linkage getLinkage() const;
2159 /// Determine the visibility of this type.
2160 Visibility getVisibility() const {
2161 return getLinkageAndVisibility().getVisibility();
2164 /// Return true if the visibility was explicitly set is the code.
2165 bool isVisibilityExplicit() const {
2166 return getLinkageAndVisibility().isVisibilityExplicit();
2169 /// Determine the linkage and visibility of this type.
2170 LinkageInfo getLinkageAndVisibility() const;
2172 /// True if the computed linkage is valid. Used for consistency
2173 /// checking. Should always return true.
2174 bool isLinkageValid() const;
2176 /// Determine the nullability of the given type.
2178 /// Note that nullability is only captured as sugar within the type
2179 /// system, not as part of the canonical type, so nullability will
2180 /// be lost by canonicalization and desugaring.
2181 Optional<NullabilityKind> getNullability(const ASTContext &context) const;
2183 /// Determine whether the given type can have a nullability
2184 /// specifier applied to it, i.e., if it is any kind of pointer type.
2186 /// \param ResultIfUnknown The value to return if we don't yet know whether
2187 /// this type can have nullability because it is dependent.
2188 bool canHaveNullability(bool ResultIfUnknown = true) const;
2190 /// Retrieve the set of substitutions required when accessing a member
2191 /// of the Objective-C receiver type that is declared in the given context.
2193 /// \c *this is the type of the object we're operating on, e.g., the
2194 /// receiver for a message send or the base of a property access, and is
2195 /// expected to be of some object or object pointer type.
2197 /// \param dc The declaration context for which we are building up a
2198 /// substitution mapping, which should be an Objective-C class, extension,
2199 /// category, or method within.
2201 /// \returns an array of type arguments that can be substituted for
2202 /// the type parameters of the given declaration context in any type described
2203 /// within that context, or an empty optional to indicate that no
2204 /// substitution is required.
2205 Optional<ArrayRef<QualType>>
2206 getObjCSubstitutions(const DeclContext *dc) const;
2208 /// Determines if this is an ObjC interface type that may accept type
2210 bool acceptsObjCTypeParams() const;
2212 const char *getTypeClassName() const;
2214 QualType getCanonicalTypeInternal() const {
2215 return CanonicalType;
2218 CanQualType getCanonicalTypeUnqualified() const; // in CanonicalType.h
2220 void dump(llvm::raw_ostream &OS) const;
2223 /// This will check for a TypedefType by removing any existing sugar
2224 /// until it reaches a TypedefType or a non-sugared type.
2225 template <> const TypedefType *Type::getAs() const;
2227 /// This will check for a TemplateSpecializationType by removing any
2228 /// existing sugar until it reaches a TemplateSpecializationType or a
2229 /// non-sugared type.
2230 template <> const TemplateSpecializationType *Type::getAs() const;
2232 /// This will check for an AttributedType by removing any existing sugar
2233 /// until it reaches an AttributedType or a non-sugared type.
2234 template <> const AttributedType *Type::getAs() const;
2236 // We can do canonical leaf types faster, because we don't have to
2237 // worry about preserving child type decoration.
2238 #define TYPE(Class, Base)
2239 #define LEAF_TYPE(Class) \
2240 template <> inline const Class##Type *Type::getAs() const { \
2241 return dyn_cast<Class##Type>(CanonicalType); \
2243 template <> inline const Class##Type *Type::castAs() const { \
2244 return cast<Class##Type>(CanonicalType); \
2246 #include "clang/AST/TypeNodes.def"
2248 /// This class is used for builtin types like 'int'. Builtin
2249 /// types are always canonical and have a literal name field.
2250 class BuiltinType : public Type {
2253 // OpenCL image types
2254 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) Id,
2255 #include "clang/Basic/OpenCLImageTypes.def"
2256 // All other builtin types
2257 #define BUILTIN_TYPE(Id, SingletonId) Id,
2258 #define LAST_BUILTIN_TYPE(Id) LastKind = Id
2259 #include "clang/AST/BuiltinTypes.def"
2263 friend class ASTContext; // ASTContext creates these.
2266 : Type(Builtin, QualType(), /*Dependent=*/(K == Dependent),
2267 /*InstantiationDependent=*/(K == Dependent),
2268 /*VariablyModified=*/false,
2269 /*Unexpanded parameter pack=*/false) {
2270 BuiltinTypeBits.Kind = K;
2274 Kind getKind() const { return static_cast<Kind>(BuiltinTypeBits.Kind); }
2275 StringRef getName(const PrintingPolicy &Policy) const;
2277 const char *getNameAsCString(const PrintingPolicy &Policy) const {
2278 // The StringRef is null-terminated.
2279 StringRef str = getName(Policy);
2280 assert(!str.empty() && str.data()[str.size()] == '\0');
2284 bool isSugared() const { return false; }
2285 QualType desugar() const { return QualType(this, 0); }
2287 bool isInteger() const {
2288 return getKind() >= Bool && getKind() <= Int128;
2291 bool isSignedInteger() const {
2292 return getKind() >= Char_S && getKind() <= Int128;
2295 bool isUnsignedInteger() const {
2296 return getKind() >= Bool && getKind() <= UInt128;
2299 bool isFloatingPoint() const {
2300 return getKind() >= Half && getKind() <= Float128;
2303 /// Determines whether the given kind corresponds to a placeholder type.
2304 static bool isPlaceholderTypeKind(Kind K) {
2305 return K >= Overload;
2308 /// Determines whether this type is a placeholder type, i.e. a type
2309 /// which cannot appear in arbitrary positions in a fully-formed
2311 bool isPlaceholderType() const {
2312 return isPlaceholderTypeKind(getKind());
2315 /// Determines whether this type is a placeholder type other than
2316 /// Overload. Most placeholder types require only syntactic
2317 /// information about their context in order to be resolved (e.g.
2318 /// whether it is a call expression), which means they can (and
2319 /// should) be resolved in an earlier "phase" of analysis.
2320 /// Overload expressions sometimes pick up further information
2321 /// from their context, like whether the context expects a
2322 /// specific function-pointer type, and so frequently need
2323 /// special treatment.
2324 bool isNonOverloadPlaceholderType() const {
2325 return getKind() > Overload;
2328 static bool classof(const Type *T) { return T->getTypeClass() == Builtin; }
2331 /// Complex values, per C99 6.2.5p11. This supports the C99 complex
2332 /// types (_Complex float etc) as well as the GCC integer complex extensions.
2333 class ComplexType : public Type, public llvm::FoldingSetNode {
2334 friend class ASTContext; // ASTContext creates these.
2336 QualType ElementType;
2338 ComplexType(QualType Element, QualType CanonicalPtr)
2339 : Type(Complex, CanonicalPtr, Element->isDependentType(),
2340 Element->isInstantiationDependentType(),
2341 Element->isVariablyModifiedType(),
2342 Element->containsUnexpandedParameterPack()),
2343 ElementType(Element) {}
2346 QualType getElementType() const { return ElementType; }
2348 bool isSugared() const { return false; }
2349 QualType desugar() const { return QualType(this, 0); }
2351 void Profile(llvm::FoldingSetNodeID &ID) {
2352 Profile(ID, getElementType());
2355 static void Profile(llvm::FoldingSetNodeID &ID, QualType Element) {
2356 ID.AddPointer(Element.getAsOpaquePtr());
2359 static bool classof(const Type *T) { return T->getTypeClass() == Complex; }
2362 /// Sugar for parentheses used when specifying types.
2363 class ParenType : public Type, public llvm::FoldingSetNode {
2364 friend class ASTContext; // ASTContext creates these.
2368 ParenType(QualType InnerType, QualType CanonType)
2369 : Type(Paren, CanonType, InnerType->isDependentType(),
2370 InnerType->isInstantiationDependentType(),
2371 InnerType->isVariablyModifiedType(),
2372 InnerType->containsUnexpandedParameterPack()),
2376 QualType getInnerType() const { return Inner; }
2378 bool isSugared() const { return true; }
2379 QualType desugar() const { return getInnerType(); }
2381 void Profile(llvm::FoldingSetNodeID &ID) {
2382 Profile(ID, getInnerType());
2385 static void Profile(llvm::FoldingSetNodeID &ID, QualType Inner) {
2389 static bool classof(const Type *T) { return T->getTypeClass() == Paren; }
2392 /// PointerType - C99 6.7.5.1 - Pointer Declarators.
2393 class PointerType : public Type, public llvm::FoldingSetNode {
2394 friend class ASTContext; // ASTContext creates these.
2396 QualType PointeeType;
2398 PointerType(QualType Pointee, QualType CanonicalPtr)
2399 : Type(Pointer, CanonicalPtr, Pointee->isDependentType(),
2400 Pointee->isInstantiationDependentType(),
2401 Pointee->isVariablyModifiedType(),
2402 Pointee->containsUnexpandedParameterPack()),
2403 PointeeType(Pointee) {}
2406 QualType getPointeeType() const { return PointeeType; }
2408 /// Returns true if address spaces of pointers overlap.
2409 /// OpenCL v2.0 defines conversion rules for pointers to different
2410 /// address spaces (OpenCLC v2.0 s6.5.5) and notion of overlapping
2413 /// address spaces overlap iff they are they same.
2415 /// __generic overlaps with any address space except for __constant.
2416 bool isAddressSpaceOverlapping(const PointerType &other) const {
2417 Qualifiers thisQuals = PointeeType.getQualifiers();
2418 Qualifiers otherQuals = other.getPointeeType().getQualifiers();
2419 // Address spaces overlap if at least one of them is a superset of another
2420 return thisQuals.isAddressSpaceSupersetOf(otherQuals) ||
2421 otherQuals.isAddressSpaceSupersetOf(thisQuals);
2424 bool isSugared() const { return false; }
2425 QualType desugar() const { return QualType(this, 0); }
2427 void Profile(llvm::FoldingSetNodeID &ID) {
2428 Profile(ID, getPointeeType());
2431 static void Profile(llvm::FoldingSetNodeID &ID, QualType Pointee) {
2432 ID.AddPointer(Pointee.getAsOpaquePtr());
2435 static bool classof(const Type *T) { return T->getTypeClass() == Pointer; }
2438 /// Represents a type which was implicitly adjusted by the semantic
2439 /// engine for arbitrary reasons. For example, array and function types can
2440 /// decay, and function types can have their calling conventions adjusted.
2441 class AdjustedType : public Type, public llvm::FoldingSetNode {
2442 QualType OriginalTy;
2443 QualType AdjustedTy;
2446 friend class ASTContext; // ASTContext creates these.
2448 AdjustedType(TypeClass TC, QualType OriginalTy, QualType AdjustedTy,
2449 QualType CanonicalPtr)
2450 : Type(TC, CanonicalPtr, OriginalTy->isDependentType(),
2451 OriginalTy->isInstantiationDependentType(),
2452 OriginalTy->isVariablyModifiedType(),
2453 OriginalTy->containsUnexpandedParameterPack()),
2454 OriginalTy(OriginalTy), AdjustedTy(AdjustedTy) {}
2457 QualType getOriginalType() const { return OriginalTy; }
2458 QualType getAdjustedType() const { return AdjustedTy; }
2460 bool isSugared() const { return true; }
2461 QualType desugar() const { return AdjustedTy; }
2463 void Profile(llvm::FoldingSetNodeID &ID) {
2464 Profile(ID, OriginalTy, AdjustedTy);
2467 static void Profile(llvm::FoldingSetNodeID &ID, QualType Orig, QualType New) {
2468 ID.AddPointer(Orig.getAsOpaquePtr());
2469 ID.AddPointer(New.getAsOpaquePtr());
2472 static bool classof(const Type *T) {
2473 return T->getTypeClass() == Adjusted || T->getTypeClass() == Decayed;
2477 /// Represents a pointer type decayed from an array or function type.
2478 class DecayedType : public AdjustedType {
2479 friend class ASTContext; // ASTContext creates these.
2482 DecayedType(QualType OriginalType, QualType Decayed, QualType Canonical);
2485 QualType getDecayedType() const { return getAdjustedType(); }
2487 inline QualType getPointeeType() const;
2489 static bool classof(const Type *T) { return T->getTypeClass() == Decayed; }
2492 /// Pointer to a block type.
2493 /// This type is to represent types syntactically represented as
2494 /// "void (^)(int)", etc. Pointee is required to always be a function type.
2495 class BlockPointerType : public Type, public llvm::FoldingSetNode {
2496 friend class ASTContext; // ASTContext creates these.
2498 // Block is some kind of pointer type
2499 QualType PointeeType;
2501 BlockPointerType(QualType Pointee, QualType CanonicalCls)
2502 : Type(BlockPointer, CanonicalCls, Pointee->isDependentType(),
2503 Pointee->isInstantiationDependentType(),
2504 Pointee->isVariablyModifiedType(),
2505 Pointee->containsUnexpandedParameterPack()),
2506 PointeeType(Pointee) {}
2509 // Get the pointee type. Pointee is required to always be a function type.
2510 QualType getPointeeType() const { return PointeeType; }
2512 bool isSugared() const { return false; }
2513 QualType desugar() const { return QualType(this, 0); }
2515 void Profile(llvm::FoldingSetNodeID &ID) {
2516 Profile(ID, getPointeeType());
2519 static void Profile(llvm::FoldingSetNodeID &ID, QualType Pointee) {
2520 ID.AddPointer(Pointee.getAsOpaquePtr());
2523 static bool classof(const Type *T) {
2524 return T->getTypeClass() == BlockPointer;
2528 /// Base for LValueReferenceType and RValueReferenceType
2529 class ReferenceType : public Type, public llvm::FoldingSetNode {
2530 QualType PointeeType;
2533 ReferenceType(TypeClass tc, QualType Referencee, QualType CanonicalRef,
2534 bool SpelledAsLValue)
2535 : Type(tc, CanonicalRef, Referencee->isDependentType(),
2536 Referencee->isInstantiationDependentType(),
2537 Referencee->isVariablyModifiedType(),
2538 Referencee->containsUnexpandedParameterPack()),
2539 PointeeType(Referencee) {
2540 ReferenceTypeBits.SpelledAsLValue = SpelledAsLValue;
2541 ReferenceTypeBits.InnerRef = Referencee->isReferenceType();
2545 bool isSpelledAsLValue() const { return ReferenceTypeBits.SpelledAsLValue; }
2546 bool isInnerRef() const { return ReferenceTypeBits.InnerRef; }
2548 QualType getPointeeTypeAsWritten() const { return PointeeType; }
2550 QualType getPointeeType() const {
2551 // FIXME: this might strip inner qualifiers; okay?
2552 const ReferenceType *T = this;
2553 while (T->isInnerRef())
2554 T = T->PointeeType->castAs<ReferenceType>();
2555 return T->PointeeType;
2558 void Profile(llvm::FoldingSetNodeID &ID) {
2559 Profile(ID, PointeeType, isSpelledAsLValue());
2562 static void Profile(llvm::FoldingSetNodeID &ID,
2563 QualType Referencee,
2564 bool SpelledAsLValue) {
2565 ID.AddPointer(Referencee.getAsOpaquePtr());
2566 ID.AddBoolean(SpelledAsLValue);
2569 static bool classof(const Type *T) {
2570 return T->getTypeClass() == LValueReference ||
2571 T->getTypeClass() == RValueReference;
2575 /// An lvalue reference type, per C++11 [dcl.ref].
2576 class LValueReferenceType : public ReferenceType {
2577 friend class ASTContext; // ASTContext creates these
2579 LValueReferenceType(QualType Referencee, QualType CanonicalRef,
2580 bool SpelledAsLValue)
2581 : ReferenceType(LValueReference, Referencee, CanonicalRef,
2585 bool isSugared() const { return false; }
2586 QualType desugar() const { return QualType(this, 0); }
2588 static bool classof(const Type *T) {
2589 return T->getTypeClass() == LValueReference;
2593 /// An rvalue reference type, per C++11 [dcl.ref].
2594 class RValueReferenceType : public ReferenceType {
2595 friend class ASTContext; // ASTContext creates these
2597 RValueReferenceType(QualType Referencee, QualType CanonicalRef)
2598 : ReferenceType(RValueReference, Referencee, CanonicalRef, false) {}
2601 bool isSugared() const { return false; }
2602 QualType desugar() const { return QualType(this, 0); }
2604 static bool classof(const Type *T) {
2605 return T->getTypeClass() == RValueReference;
2609 /// A pointer to member type per C++ 8.3.3 - Pointers to members.
2611 /// This includes both pointers to data members and pointer to member functions.
2612 class MemberPointerType : public Type, public llvm::FoldingSetNode {
2613 friend class ASTContext; // ASTContext creates these.
2615 QualType PointeeType;
2617 /// The class of which the pointee is a member. Must ultimately be a
2618 /// RecordType, but could be a typedef or a template parameter too.
2621 MemberPointerType(QualType Pointee, const Type *Cls, QualType CanonicalPtr)
2622 : Type(MemberPointer, CanonicalPtr,
2623 Cls->isDependentType() || Pointee->isDependentType(),
2624 (Cls->isInstantiationDependentType() ||
2625 Pointee->isInstantiationDependentType()),
2626 Pointee->isVariablyModifiedType(),
2627 (Cls->containsUnexpandedParameterPack() ||
2628 Pointee->containsUnexpandedParameterPack())),
2629 PointeeType(Pointee), Class(Cls) {}
2632 QualType getPointeeType() const { return PointeeType; }
2634 /// Returns true if the member type (i.e. the pointee type) is a
2635 /// function type rather than a data-member type.
2636 bool isMemberFunctionPointer() const {
2637 return PointeeType->isFunctionProtoType();
2640 /// Returns true if the member type (i.e. the pointee type) is a
2641 /// data type rather than a function type.
2642 bool isMemberDataPointer() const {
2643 return !PointeeType->isFunctionProtoType();
2646 const Type *getClass() const { return Class; }
2647 CXXRecordDecl *getMostRecentCXXRecordDecl() const;
2649 bool isSugared() const { return false; }
2650 QualType desugar() const { return QualType(this, 0); }
2652 void Profile(llvm::FoldingSetNodeID &ID) {
2653 Profile(ID, getPointeeType(), getClass());
2656 static void Profile(llvm::FoldingSetNodeID &ID, QualType Pointee,
2657 const Type *Class) {
2658 ID.AddPointer(Pointee.getAsOpaquePtr());
2659 ID.AddPointer(Class);
2662 static bool classof(const Type *T) {
2663 return T->getTypeClass() == MemberPointer;
2667 /// Represents an array type, per C99 6.7.5.2 - Array Declarators.
2668 class ArrayType : public Type, public llvm::FoldingSetNode {
2670 /// Capture whether this is a normal array (e.g. int X[4])
2671 /// an array with a static size (e.g. int X[static 4]), or an array
2672 /// with a star size (e.g. int X[*]).
2673 /// 'static' is only allowed on function parameters.
2674 enum ArraySizeModifier {
2675 Normal, Static, Star
2679 /// The element type of the array.
2680 QualType ElementType;
2683 friend class ASTContext; // ASTContext creates these.
2685 // C++ [temp.dep.type]p1:
2686 // A type is dependent if it is...
2687 // - an array type constructed from any dependent type or whose
2688 // size is specified by a constant expression that is
2690 ArrayType(TypeClass tc, QualType et, QualType can,
2691 ArraySizeModifier sm, unsigned tq,
2692 bool ContainsUnexpandedParameterPack)
2693 : Type(tc, can, et->isDependentType() || tc == DependentSizedArray,
2694 et->isInstantiationDependentType() || tc == DependentSizedArray,
2695 (tc == VariableArray || et->isVariablyModifiedType()),
2696 ContainsUnexpandedParameterPack),
2698 ArrayTypeBits.IndexTypeQuals = tq;
2699 ArrayTypeBits.SizeModifier = sm;
2703 QualType getElementType() const { return ElementType; }
2705 ArraySizeModifier getSizeModifier() const {
2706 return ArraySizeModifier(ArrayTypeBits.SizeModifier);
2709 Qualifiers getIndexTypeQualifiers() const {
2710 return Qualifiers::fromCVRMask(getIndexTypeCVRQualifiers());
2713 unsigned getIndexTypeCVRQualifiers() const {
2714 return ArrayTypeBits.IndexTypeQuals;
2717 static bool classof(const Type *T) {
2718 return T->getTypeClass() == ConstantArray ||
2719 T->getTypeClass() == VariableArray ||
2720 T->getTypeClass() == IncompleteArray ||
2721 T->getTypeClass() == DependentSizedArray;
2725 /// Represents the canonical version of C arrays with a specified constant size.
2726 /// For example, the canonical type for 'int A[4 + 4*100]' is a
2727 /// ConstantArrayType where the element type is 'int' and the size is 404.
2728 class ConstantArrayType : public ArrayType {
2729 llvm::APInt Size; // Allows us to unique the type.
2731 ConstantArrayType(QualType et, QualType can, const llvm::APInt &size,
2732 ArraySizeModifier sm, unsigned tq)
2733 : ArrayType(ConstantArray, et, can, sm, tq,
2734 et->containsUnexpandedParameterPack()),
2738 friend class ASTContext; // ASTContext creates these.
2740 ConstantArrayType(TypeClass tc, QualType et, QualType can,
2741 const llvm::APInt &size, ArraySizeModifier sm, unsigned tq)
2742 : ArrayType(tc, et, can, sm, tq, et->containsUnexpandedParameterPack()),
2746 const llvm::APInt &getSize() const { return Size; }
2747 bool isSugared() const { return false; }
2748 QualType desugar() const { return QualType(this, 0); }
2750 /// Determine the number of bits required to address a member of
2751 // an array with the given element type and number of elements.
2752 static unsigned getNumAddressingBits(const ASTContext &Context,
2753 QualType ElementType,
2754 const llvm::APInt &NumElements);
2756 /// Determine the maximum number of active bits that an array's size
2757 /// can require, which limits the maximum size of the array.
2758 static unsigned getMaxSizeBits(const ASTContext &Context);
2760 void Profile(llvm::FoldingSetNodeID &ID) {
2761 Profile(ID, getElementType(), getSize(),
2762 getSizeModifier(), getIndexTypeCVRQualifiers());
2765 static void Profile(llvm::FoldingSetNodeID &ID, QualType ET,
2766 const llvm::APInt &ArraySize, ArraySizeModifier SizeMod,
2767 unsigned TypeQuals) {
2768 ID.AddPointer(ET.getAsOpaquePtr());
2769 ID.AddInteger(ArraySize.getZExtValue());
2770 ID.AddInteger(SizeMod);
2771 ID.AddInteger(TypeQuals);
2774 static bool classof(const Type *T) {
2775 return T->getTypeClass() == ConstantArray;
2779 /// Represents a C array with an unspecified size. For example 'int A[]' has
2780 /// an IncompleteArrayType where the element type is 'int' and the size is
2782 class IncompleteArrayType : public ArrayType {
2783 friend class ASTContext; // ASTContext creates these.
2785 IncompleteArrayType(QualType et, QualType can,
2786 ArraySizeModifier sm, unsigned tq)
2787 : ArrayType(IncompleteArray, et, can, sm, tq,
2788 et->containsUnexpandedParameterPack()) {}
2791 friend class StmtIteratorBase;
2793 bool isSugared() const { return false; }
2794 QualType desugar() const { return QualType(this, 0); }
2796 static bool classof(const Type *T) {
2797 return T->getTypeClass() == IncompleteArray;
2800 void Profile(llvm::FoldingSetNodeID &ID) {
2801 Profile(ID, getElementType(), getSizeModifier(),
2802 getIndexTypeCVRQualifiers());
2805 static void Profile(llvm::FoldingSetNodeID &ID, QualType ET,
2806 ArraySizeModifier SizeMod, unsigned TypeQuals) {
2807 ID.AddPointer(ET.getAsOpaquePtr());
2808 ID.AddInteger(SizeMod);
2809 ID.AddInteger(TypeQuals);
2813 /// Represents a C array with a specified size that is not an
2814 /// integer-constant-expression. For example, 'int s[x+foo()]'.
2815 /// Since the size expression is an arbitrary expression, we store it as such.
2817 /// Note: VariableArrayType's aren't uniqued (since the expressions aren't) and
2818 /// should not be: two lexically equivalent variable array types could mean
2819 /// different things, for example, these variables do not have the same type
2822 /// void foo(int x) {
2827 class VariableArrayType : public ArrayType {
2828 friend class ASTContext; // ASTContext creates these.
2830 /// An assignment-expression. VLA's are only permitted within
2831 /// a function block.
2834 /// The range spanned by the left and right array brackets.
2835 SourceRange Brackets;
2837 VariableArrayType(QualType et, QualType can, Expr *e,
2838 ArraySizeModifier sm, unsigned tq,
2839 SourceRange brackets)
2840 : ArrayType(VariableArray, et, can, sm, tq,
2841 et->containsUnexpandedParameterPack()),
2842 SizeExpr((Stmt*) e), Brackets(brackets) {}
2845 friend class StmtIteratorBase;
2847 Expr *getSizeExpr() const {
2848 // We use C-style casts instead of cast<> here because we do not wish
2849 // to have a dependency of Type.h on Stmt.h/Expr.h.
2850 return (Expr*) SizeExpr;
2853 SourceRange getBracketsRange() const { return Brackets; }
2854 SourceLocation getLBracketLoc() const { return Brackets.getBegin(); }
2855 SourceLocation getRBracketLoc() const { return Brackets.getEnd(); }
2857 bool isSugared() const { return false; }
2858 QualType desugar() const { return QualType(this, 0); }
2860 static bool classof(const Type *T) {
2861 return T->getTypeClass() == VariableArray;
2864 void Profile(llvm::FoldingSetNodeID &ID) {
2865 llvm_unreachable("Cannot unique VariableArrayTypes.");
2869 /// Represents an array type in C++ whose size is a value-dependent expression.
2873 /// template<typename T, int Size>
2879 /// For these types, we won't actually know what the array bound is
2880 /// until template instantiation occurs, at which point this will
2881 /// become either a ConstantArrayType or a VariableArrayType.
2882 class DependentSizedArrayType : public ArrayType {
2883 friend class ASTContext; // ASTContext creates these.
2885 const ASTContext &Context;
2887 /// An assignment expression that will instantiate to the
2888 /// size of the array.
2890 /// The expression itself might be null, in which case the array
2891 /// type will have its size deduced from an initializer.
2894 /// The range spanned by the left and right array brackets.
2895 SourceRange Brackets;
2897 DependentSizedArrayType(const ASTContext &Context, QualType et, QualType can,
2898 Expr *e, ArraySizeModifier sm, unsigned tq,
2899 SourceRange brackets);
2902 friend class StmtIteratorBase;
2904 Expr *getSizeExpr() const {
2905 // We use C-style casts instead of cast<> here because we do not wish
2906 // to have a dependency of Type.h on Stmt.h/Expr.h.
2907 return (Expr*) SizeExpr;
2910 SourceRange getBracketsRange() const { return Brackets; }
2911 SourceLocation getLBracketLoc() const { return Brackets.getBegin(); }
2912 SourceLocation getRBracketLoc() const { return Brackets.getEnd(); }
2914 bool isSugared() const { return false; }
2915 QualType desugar() const { return QualType(this, 0); }
2917 static bool classof(const Type *T) {
2918 return T->getTypeClass() == DependentSizedArray;
2921 void Profile(llvm::FoldingSetNodeID &ID) {
2922 Profile(ID, Context, getElementType(),
2923 getSizeModifier(), getIndexTypeCVRQualifiers(), getSizeExpr());
2926 static void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context,
2927 QualType ET, ArraySizeModifier SizeMod,
2928 unsigned TypeQuals, Expr *E);
2931 /// Represents an extended address space qualifier where the input address space
2932 /// value is dependent. Non-dependent address spaces are not represented with a
2933 /// special Type subclass; they are stored on an ExtQuals node as part of a QualType.
2937 /// template<typename T, int AddrSpace>
2938 /// class AddressSpace {
2939 /// typedef T __attribute__((address_space(AddrSpace))) type;
2942 class DependentAddressSpaceType : public Type, public llvm::FoldingSetNode {
2943 friend class ASTContext;
2945 const ASTContext &Context;
2946 Expr *AddrSpaceExpr;
2947 QualType PointeeType;
2950 DependentAddressSpaceType(const ASTContext &Context, QualType PointeeType,
2951 QualType can, Expr *AddrSpaceExpr,
2952 SourceLocation loc);
2955 Expr *getAddrSpaceExpr() const { return AddrSpaceExpr; }
2956 QualType getPointeeType() const { return PointeeType; }
2957 SourceLocation getAttributeLoc() const { return loc; }
2959 bool isSugared() const { return false; }
2960 QualType desugar() const { return QualType(this, 0); }
2962 static bool classof(const Type *T) {
2963 return T->getTypeClass() == DependentAddressSpace;
2966 void Profile(llvm::FoldingSetNodeID &ID) {
2967 Profile(ID, Context, getPointeeType(), getAddrSpaceExpr());
2970 static void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context,
2971 QualType PointeeType, Expr *AddrSpaceExpr);
2974 /// Represents an extended vector type where either the type or size is
2979 /// template<typename T, int Size>
2981 /// typedef T __attribute__((ext_vector_type(Size))) type;
2984 class DependentSizedExtVectorType : public Type, public llvm::FoldingSetNode {
2985 friend class ASTContext;
2987 const ASTContext &Context;
2990 /// The element type of the array.
2991 QualType ElementType;
2995 DependentSizedExtVectorType(const ASTContext &Context, QualType ElementType,
2996 QualType can, Expr *SizeExpr, SourceLocation loc);
2999 Expr *getSizeExpr() const { return SizeExpr; }
3000 QualType getElementType() const { return ElementType; }
3001 SourceLocation getAttributeLoc() const { return loc; }
3003 bool isSugared() const { return false; }
3004 QualType desugar() const { return QualType(this, 0); }
3006 static bool classof(const Type *T) {
3007 return T->getTypeClass() == DependentSizedExtVector;
3010 void Profile(llvm::FoldingSetNodeID &ID) {
3011 Profile(ID, Context, getElementType(), getSizeExpr());
3014 static void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context,
3015 QualType ElementType, Expr *SizeExpr);
3019 /// Represents a GCC generic vector type. This type is created using
3020 /// __attribute__((vector_size(n)), where "n" specifies the vector size in
3021 /// bytes; or from an Altivec __vector or vector declaration.
3022 /// Since the constructor takes the number of vector elements, the
3023 /// client is responsible for converting the size into the number of elements.
3024 class VectorType : public Type, public llvm::FoldingSetNode {
3027 /// not a target-specific vector type
3030 /// is AltiVec vector
3033 /// is AltiVec 'vector Pixel'
3036 /// is AltiVec 'vector bool ...'
3039 /// is ARM Neon vector
3042 /// is ARM Neon polynomial vector
3047 friend class ASTContext; // ASTContext creates these.
3049 /// The element type of the vector.
3050 QualType ElementType;
3052 VectorType(QualType vecType, unsigned nElements, QualType canonType,
3053 VectorKind vecKind);
3055 VectorType(TypeClass tc, QualType vecType, unsigned nElements,
3056 QualType canonType, VectorKind vecKind);
3059 QualType getElementType() const { return ElementType; }
3060 unsigned getNumElements() const { return VectorTypeBits.NumElements; }
3062 static bool isVectorSizeTooLarge(unsigned NumElements) {
3063 return NumElements > VectorTypeBitfields::MaxNumElements;
3066 bool isSugared() const { return false; }
3067 QualType desugar() const { return QualType(this, 0); }
3069 VectorKind getVectorKind() const {
3070 return VectorKind(VectorTypeBits.VecKind);
3073 void Profile(llvm::FoldingSetNodeID &ID) {
3074 Profile(ID, getElementType(), getNumElements(),
3075 getTypeClass(), getVectorKind());
3078 static void Profile(llvm::FoldingSetNodeID &ID, QualType ElementType,
3079 unsigned NumElements, TypeClass TypeClass,
3080 VectorKind VecKind) {
3081 ID.AddPointer(ElementType.getAsOpaquePtr());
3082 ID.AddInteger(NumElements);
3083 ID.AddInteger(TypeClass);
3084 ID.AddInteger(VecKind);
3087 static bool classof(const Type *T) {
3088 return T->getTypeClass() == Vector || T->getTypeClass() == ExtVector;
3092 /// Represents a vector type where either the type or size is dependent.
3096 /// template<typename T, int Size>
3098 /// typedef T __attribute__((vector_size(Size))) type;
3101 class DependentVectorType : public Type, public llvm::FoldingSetNode {
3102 friend class ASTContext;
3104 const ASTContext &Context;
3105 QualType ElementType;
3109 DependentVectorType(const ASTContext &Context, QualType ElementType,
3110 QualType CanonType, Expr *SizeExpr,
3111 SourceLocation Loc, VectorType::VectorKind vecKind);
3114 Expr *getSizeExpr() const { return SizeExpr; }
3115 QualType getElementType() const { return ElementType; }
3116 SourceLocation getAttributeLoc() const { return Loc; }
3117 VectorType::VectorKind getVectorKind() const {
3118 return VectorType::VectorKind(VectorTypeBits.VecKind);
3121 bool isSugared() const { return false; }
3122 QualType desugar() const { return QualType(this, 0); }
3124 static bool classof(const Type *T) {
3125 return T->getTypeClass() == DependentVector;
3128 void Profile(llvm::FoldingSetNodeID &ID) {
3129 Profile(ID, Context, getElementType(), getSizeExpr(), getVectorKind());
3132 static void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context,
3133 QualType ElementType, const Expr *SizeExpr,
3134 VectorType::VectorKind VecKind);
3137 /// ExtVectorType - Extended vector type. This type is created using
3138 /// __attribute__((ext_vector_type(n)), where "n" is the number of elements.
3139 /// Unlike vector_size, ext_vector_type is only allowed on typedef's. This
3140 /// class enables syntactic extensions, like Vector Components for accessing
3141 /// points (as .xyzw), colors (as .rgba), and textures (modeled after OpenGL
3142 /// Shading Language).
3143 class ExtVectorType : public VectorType {
3144 friend class ASTContext; // ASTContext creates these.
3146 ExtVectorType(QualType vecType, unsigned nElements, QualType canonType)
3147 : VectorType(ExtVector, vecType, nElements, canonType, GenericVector) {}
3150 static int getPointAccessorIdx(char c) {
3153 case 'x': case 'r': return 0;
3154 case 'y': case 'g': return 1;
3155 case 'z': case 'b': return 2;
3156 case 'w': case 'a': return 3;
3160 static int getNumericAccessorIdx(char c) {
3174 case 'a': return 10;
3176 case 'b': return 11;
3178 case 'c': return 12;
3180 case 'd': return 13;
3182 case 'e': return 14;
3184 case 'f': return 15;
3188 static int getAccessorIdx(char c, bool isNumericAccessor) {
3189 if (isNumericAccessor)
3190 return getNumericAccessorIdx(c);
3192 return getPointAccessorIdx(c);
3195 bool isAccessorWithinNumElements(char c, bool isNumericAccessor) const {
3196 if (int idx = getAccessorIdx(c, isNumericAccessor)+1)
3197 return unsigned(idx-1) < getNumElements();
3201 bool isSugared() const { return false; }
3202 QualType desugar() const { return QualType(this, 0); }
3204 static bool classof(const Type *T) {
3205 return T->getTypeClass() == ExtVector;
3209 /// FunctionType - C99 6.7.5.3 - Function Declarators. This is the common base
3210 /// class of FunctionNoProtoType and FunctionProtoType.
3211 class FunctionType : public Type {
3212 // The type returned by the function.
3213 QualType ResultType;
3216 /// A class which abstracts out some details necessary for
3219 /// It is not actually used directly for storing this information in
3220 /// a FunctionType, although FunctionType does currently use the
3221 /// same bit-pattern.
3223 // If you add a field (say Foo), other than the obvious places (both,
3224 // constructors, compile failures), what you need to update is
3228 // * functionType. Add Foo, getFoo.
3229 // * ASTContext::getFooType
3230 // * ASTContext::mergeFunctionTypes
3231 // * FunctionNoProtoType::Profile
3232 // * FunctionProtoType::Profile
3233 // * TypePrinter::PrintFunctionProto
3234 // * AST read and write
3237 friend class FunctionType;
3239 // Feel free to rearrange or add bits, but if you go over 12,
3240 // you'll need to adjust both the Bits field below and
3241 // Type::FunctionTypeBitfields.
3243 // | CC |noreturn|produces|nocallersavedregs|regparm|nocfcheck|
3244 // |0 .. 4| 5 | 6 | 7 |8 .. 10| 11 |
3246 // regparm is either 0 (no regparm attribute) or the regparm value+1.
3247 enum { CallConvMask = 0x1F };
3248 enum { NoReturnMask = 0x20 };
3249 enum { ProducesResultMask = 0x40 };
3250 enum { NoCallerSavedRegsMask = 0x80 };
3251 enum { NoCfCheckMask = 0x800 };
3253 RegParmMask = ~(CallConvMask | NoReturnMask | ProducesResultMask |
3254 NoCallerSavedRegsMask | NoCfCheckMask),
3256 }; // Assumed to be the last field
3257 uint16_t Bits = CC_C;
3259 ExtInfo(unsigned Bits) : Bits(static_cast<uint16_t>(Bits)) {}
3262 // Constructor with no defaults. Use this when you know that you
3263 // have all the elements (when reading an AST file for example).
3264 ExtInfo(bool noReturn, bool hasRegParm, unsigned regParm, CallingConv cc,
3265 bool producesResult, bool noCallerSavedRegs, bool NoCfCheck) {
3266 assert((!hasRegParm || regParm < 7) && "Invalid regparm value");
3267 Bits = ((unsigned)cc) | (noReturn ? NoReturnMask : 0) |
3268 (producesResult ? ProducesResultMask : 0) |
3269 (noCallerSavedRegs ? NoCallerSavedRegsMask : 0) |
3270 (hasRegParm ? ((regParm + 1) << RegParmOffset) : 0) |
3271 (NoCfCheck ? NoCfCheckMask : 0);
3274 // Constructor with all defaults. Use when for example creating a
3275 // function known to use defaults.
3276 ExtInfo() = default;
3278 // Constructor with just the calling convention, which is an important part
3279 // of the canonical type.
3280 ExtInfo(CallingConv CC) : Bits(CC) {}
3282 bool getNoReturn() const { return Bits & NoReturnMask; }
3283 bool getProducesResult() const { return Bits & ProducesResultMask; }
3284 bool getNoCallerSavedRegs() const { return Bits & NoCallerSavedRegsMask; }
3285 bool getNoCfCheck() const { return Bits & NoCfCheckMask; }
3286 bool getHasRegParm() const { return (Bits >> RegParmOffset) != 0; }
3288 unsigned getRegParm() const {
3289 unsigned RegParm = (Bits & RegParmMask) >> RegParmOffset;
3295 CallingConv getCC() const { return CallingConv(Bits & CallConvMask); }
3297 bool operator==(ExtInfo Other) const {
3298 return Bits == Other.Bits;
3300 bool operator!=(ExtInfo Other) const {
3301 return Bits != Other.Bits;
3304 // Note that we don't have setters. That is by design, use
3305 // the following with methods instead of mutating these objects.
3307 ExtInfo withNoReturn(bool noReturn) const {
3309 return ExtInfo(Bits | NoReturnMask);
3311 return ExtInfo(Bits & ~NoReturnMask);
3314 ExtInfo withProducesResult(bool producesResult) const {
3316 return ExtInfo(Bits | ProducesResultMask);
3318 return ExtInfo(Bits & ~ProducesResultMask);
3321 ExtInfo withNoCallerSavedRegs(bool noCallerSavedRegs) const {
3322 if (noCallerSavedRegs)
3323 return ExtInfo(Bits | NoCallerSavedRegsMask);
3325 return ExtInfo(Bits & ~NoCallerSavedRegsMask);
3328 ExtInfo withNoCfCheck(bool noCfCheck) const {
3330 return ExtInfo(Bits | NoCfCheckMask);
3332 return ExtInfo(Bits & ~NoCfCheckMask);
3335 ExtInfo withRegParm(unsigned RegParm) const {
3336 assert(RegParm < 7 && "Invalid regparm value");
3337 return ExtInfo((Bits & ~RegParmMask) |
3338 ((RegParm + 1) << RegParmOffset));
3341 ExtInfo withCallingConv(CallingConv cc) const {
3342 return ExtInfo((Bits & ~CallConvMask) | (unsigned) cc);
3345 void Profile(llvm::FoldingSetNodeID &ID) const {
3346 ID.AddInteger(Bits);
3351 FunctionType(TypeClass tc, QualType res,
3352 QualType Canonical, bool Dependent,
3353 bool InstantiationDependent,
3354 bool VariablyModified, bool ContainsUnexpandedParameterPack,
3356 : Type(tc, Canonical, Dependent, InstantiationDependent, VariablyModified,
3357 ContainsUnexpandedParameterPack),
3359 FunctionTypeBits.ExtInfo = Info.Bits;
3362 unsigned getTypeQuals() const { return FunctionTypeBits.TypeQuals; }
3365 QualType getReturnType() const { return ResultType; }
3367 bool getHasRegParm() const { return getExtInfo().getHasRegParm(); }
3368 unsigned getRegParmType() const { return getExtInfo().getRegParm(); }
3370 /// Determine whether this function type includes the GNU noreturn
3371 /// attribute. The C++11 [[noreturn]] attribute does not affect the function
3373 bool getNoReturnAttr() const { return getExtInfo().getNoReturn(); }
3375 CallingConv getCallConv() const { return getExtInfo().getCC(); }
3376 ExtInfo getExtInfo() const { return ExtInfo(FunctionTypeBits.ExtInfo); }
3377 bool isConst() const { return getTypeQuals() & Qualifiers::Const; }
3378 bool isVolatile() const { return getTypeQuals() & Qualifiers::Volatile; }
3379 bool isRestrict() const { return getTypeQuals() & Qualifiers::Restrict; }
3381 /// Determine the type of an expression that calls a function of
3383 QualType getCallResultType(const ASTContext &Context) const {
3384 return getReturnType().getNonLValueExprType(Context);
3387 static StringRef getNameForCallConv(CallingConv CC);
3389 static bool classof(const Type *T) {
3390 return T->getTypeClass() == FunctionNoProto ||
3391 T->getTypeClass() == FunctionProto;
3395 /// Represents a K&R-style 'int foo()' function, which has
3396 /// no information available about its arguments.
3397 class FunctionNoProtoType : public FunctionType, public llvm::FoldingSetNode {
3398 friend class ASTContext; // ASTContext creates these.
3400 FunctionNoProtoType(QualType Result, QualType Canonical, ExtInfo Info)
3401 : FunctionType(FunctionNoProto, Result, Canonical,
3402 /*Dependent=*/false, /*InstantiationDependent=*/false,
3403 Result->isVariablyModifiedType(),
3404 /*ContainsUnexpandedParameterPack=*/false, Info) {}
3407 // No additional state past what FunctionType provides.
3409 bool isSugared() const { return false; }
3410 QualType desugar() const { return QualType(this, 0); }
3412 void Profile(llvm::FoldingSetNodeID &ID) {
3413 Profile(ID, getReturnType(), getExtInfo());
3416 static void Profile(llvm::FoldingSetNodeID &ID, QualType ResultType,
3419 ID.AddPointer(ResultType.getAsOpaquePtr());
3422 static bool classof(const Type *T) {
3423 return T->getTypeClass() == FunctionNoProto;
3427 /// Represents a prototype with parameter type info, e.g.
3428 /// 'int foo(int)' or 'int foo(void)'. 'void' is represented as having no
3429 /// parameters, not as having a single void parameter. Such a type can have an
3430 /// exception specification, but this specification is not part of the canonical
3432 class FunctionProtoType : public FunctionType, public llvm::FoldingSetNode {
3434 /// Interesting information about a specific parameter that can't simply
3435 /// be reflected in parameter's type.
3437 /// It makes sense to model language features this way when there's some
3438 /// sort of parameter-specific override (such as an attribute) that
3439 /// affects how the function is called. For example, the ARC ns_consumed
3440 /// attribute changes whether a parameter is passed at +0 (the default)
3441 /// or +1 (ns_consumed). This must be reflected in the function type,
3442 /// but isn't really a change to the parameter type.
3444 /// One serious disadvantage of modelling language features this way is
3445 /// that they generally do not work with language features that attempt
3446 /// to destructure types. For example, template argument deduction will
3447 /// not be able to match a parameter declared as
3449 /// against an argument of type
3450 /// void (*)(__attribute__((ns_consumed)) id)
3451 /// because the substitution of T=void, U=id into the former will
3452 /// not produce the latter.
3453 class ExtParameterInfo {
3457 HasPassObjSize = 0x20,
3460 unsigned char Data = 0;
3463 ExtParameterInfo() = default;
3465 /// Return the ABI treatment of this parameter.
3466 ParameterABI getABI() const {
3467 return ParameterABI(Data & ABIMask);
3469 ExtParameterInfo withABI(ParameterABI kind) const {
3470 ExtParameterInfo copy = *this;
3471 copy.Data = (copy.Data & ~ABIMask) | unsigned(kind);
3475 /// Is this parameter considered "consumed" by Objective-C ARC?
3476 /// Consumed parameters must have retainable object type.
3477 bool isConsumed() const {
3478 return (Data & IsConsumed);
3480 ExtParameterInfo withIsConsumed(bool consumed) const {
3481 ExtParameterInfo copy = *this;
3483 copy.Data |= IsConsumed;
3485 copy.Data &= ~IsConsumed;
3490 bool hasPassObjectSize() const {
3491 return Data & HasPassObjSize;
3493 ExtParameterInfo withHasPassObjectSize() const {
3494 ExtParameterInfo Copy = *this;
3495 Copy.Data |= HasPassObjSize;
3499 bool isNoEscape() const {
3500 return Data & IsNoEscape;
3503 ExtParameterInfo withIsNoEscape(bool NoEscape) const {
3504 ExtParameterInfo Copy = *this;
3506 Copy.Data |= IsNoEscape;
3508 Copy.Data &= ~IsNoEscape;
3512 unsigned char getOpaqueValue() const { return Data; }
3513 static ExtParameterInfo getFromOpaqueValue(unsigned char data) {
3514 ExtParameterInfo result;
3519 friend bool operator==(ExtParameterInfo lhs, ExtParameterInfo rhs) {
3520 return lhs.Data == rhs.Data;
3522 friend bool operator!=(ExtParameterInfo lhs, ExtParameterInfo rhs) {
3523 return lhs.Data != rhs.Data;
3527 struct ExceptionSpecInfo {
3528 /// The kind of exception specification this is.
3529 ExceptionSpecificationType Type = EST_None;
3531 /// Explicitly-specified list of exception types.
3532 ArrayRef<QualType> Exceptions;
3534 /// Noexcept expression, if this is a computed noexcept specification.
3535 Expr *NoexceptExpr = nullptr;
3537 /// The function whose exception specification this is, for
3538 /// EST_Unevaluated and EST_Uninstantiated.
3539 FunctionDecl *SourceDecl = nullptr;
3541 /// The function template whose exception specification this is instantiated
3542 /// from, for EST_Uninstantiated.
3543 FunctionDecl *SourceTemplate = nullptr;
3545 ExceptionSpecInfo() = default;
3547 ExceptionSpecInfo(ExceptionSpecificationType EST) : Type(EST) {}
3550 /// Extra information about a function prototype.
3551 struct ExtProtoInfo {
3552 FunctionType::ExtInfo ExtInfo;
3554 bool HasTrailingReturn : 1;
3555 unsigned char TypeQuals = 0;
3556 RefQualifierKind RefQualifier = RQ_None;
3557 ExceptionSpecInfo ExceptionSpec;
3558 const ExtParameterInfo *ExtParameterInfos = nullptr;
3561 : Variadic(false), HasTrailingReturn(false) {}
3563 ExtProtoInfo(CallingConv CC)
3564 : ExtInfo(CC), Variadic(false), HasTrailingReturn(false) {}
3566 ExtProtoInfo withExceptionSpec(const ExceptionSpecInfo &O) {
3567 ExtProtoInfo Result(*this);
3568 Result.ExceptionSpec = O;
3574 friend class ASTContext; // ASTContext creates these.
3576 /// Determine whether there are any argument types that
3577 /// contain an unexpanded parameter pack.
3578 static bool containsAnyUnexpandedParameterPack(const QualType *ArgArray,
3580 for (unsigned Idx = 0; Idx < numArgs; ++Idx)
3581 if (ArgArray[Idx]->containsUnexpandedParameterPack())
3587 FunctionProtoType(QualType result, ArrayRef<QualType> params,
3588 QualType canonical, const ExtProtoInfo &epi);
3590 /// The number of parameters this function has, not counting '...'.
3591 unsigned NumParams : 15;
3593 /// The number of types in the exception spec, if any.
3594 unsigned NumExceptions : 9;
3596 /// The type of exception specification this function has.
3597 unsigned ExceptionSpecType : 4;
3599 /// Whether this function has extended parameter information.
3600 unsigned HasExtParameterInfos : 1;
3602 /// Whether the function is variadic.
3603 unsigned Variadic : 1;
3605 /// Whether this function has a trailing return type.
3606 unsigned HasTrailingReturn : 1;
3608 // ParamInfo - There is an variable size array after the class in memory that
3609 // holds the parameter types.
3611 // Exceptions - There is another variable size array after ArgInfo that
3612 // holds the exception types.
3614 // NoexceptExpr - Instead of Exceptions, there may be a single Expr* pointing
3615 // to the expression in the noexcept() specifier.
3617 // ExceptionSpecDecl, ExceptionSpecTemplate - Instead of Exceptions, there may
3618 // be a pair of FunctionDecl* pointing to the function which should be used to
3619 // instantiate this function type's exception specification, and the function
3620 // from which it should be instantiated.
3622 // ExtParameterInfos - A variable size array, following the exception
3623 // specification and of length NumParams, holding an ExtParameterInfo
3624 // for each of the parameters. This only appears if HasExtParameterInfos
3627 const ExtParameterInfo *getExtParameterInfosBuffer() const {
3628 assert(hasExtParameterInfos());
3630 // Find the end of the exception specification.
3631 const auto *ptr = reinterpret_cast<const char *>(exception_begin());
3632 ptr += getExceptionSpecSize();
3634 return reinterpret_cast<const ExtParameterInfo *>(ptr);
3637 static size_t getExceptionSpecSize(ExceptionSpecificationType EST,
3638 unsigned NumExceptions) {
3641 case EST_DynamicNone:
3643 case EST_BasicNoexcept:
3648 return NumExceptions * sizeof(QualType);
3650 case EST_DependentNoexcept:
3651 case EST_NoexceptFalse:
3652 case EST_NoexceptTrue:
3653 return sizeof(Expr *);
3655 case EST_Uninstantiated:
3656 return 2 * sizeof(FunctionDecl *);
3658 case EST_Unevaluated:
3659 return sizeof(FunctionDecl *);
3661 llvm_unreachable("bad exception specification kind");
3663 size_t getExceptionSpecSize() const {
3664 return getExceptionSpecSize(getExceptionSpecType(), getNumExceptions());
3668 unsigned getNumParams() const { return NumParams; }
3670 QualType getParamType(unsigned i) const {
3671 assert(i < NumParams && "invalid parameter index");
3672 return param_type_begin()[i];
3675 ArrayRef<QualType> getParamTypes() const {
3676 return llvm::makeArrayRef(param_type_begin(), param_type_end());
3679 ExtProtoInfo getExtProtoInfo() const {
3681 EPI.ExtInfo = getExtInfo();
3682 EPI.Variadic = isVariadic();
3683 EPI.HasTrailingReturn = hasTrailingReturn();
3684 EPI.ExceptionSpec.Type = getExceptionSpecType();
3685 EPI.TypeQuals = static_cast<unsigned char>(getTypeQuals());
3686 EPI.RefQualifier = getRefQualifier();
3687 if (EPI.ExceptionSpec.Type == EST_Dynamic) {
3688 EPI.ExceptionSpec.Exceptions = exceptions();
3689 } else if (isComputedNoexcept(EPI.ExceptionSpec.Type)) {
3690 EPI.ExceptionSpec.NoexceptExpr = getNoexceptExpr();
3691 } else if (EPI.ExceptionSpec.Type == EST_Uninstantiated) {
3692 EPI.ExceptionSpec.SourceDecl = getExceptionSpecDecl();
3693 EPI.ExceptionSpec.SourceTemplate = getExceptionSpecTemplate();
3694 } else if (EPI.ExceptionSpec.Type == EST_Unevaluated) {
3695 EPI.ExceptionSpec.SourceDecl = getExceptionSpecDecl();
3697 if (hasExtParameterInfos())
3698 EPI.ExtParameterInfos = getExtParameterInfosBuffer();
3702 /// Get the kind of exception specification on this function.
3703 ExceptionSpecificationType getExceptionSpecType() const {
3704 return static_cast<ExceptionSpecificationType>(ExceptionSpecType);
3707 /// Return whether this function has any kind of exception spec.
3708 bool hasExceptionSpec() const {
3709 return getExceptionSpecType() != EST_None;
3712 /// Return whether this function has a dynamic (throw) exception spec.
3713 bool hasDynamicExceptionSpec() const {
3714 return isDynamicExceptionSpec(getExceptionSpecType());
3717 /// Return whether this function has a noexcept exception spec.
3718 bool hasNoexceptExceptionSpec() const {
3719 return isNoexceptExceptionSpec(getExceptionSpecType());
3722 /// Return whether this function has a dependent exception spec.
3723 bool hasDependentExceptionSpec() const;
3725 /// Return whether this function has an instantiation-dependent exception
3727 bool hasInstantiationDependentExceptionSpec() const;
3729 unsigned getNumExceptions() const { return NumExceptions; }
3730 QualType getExceptionType(unsigned i) const {
3731 assert(i < NumExceptions && "Invalid exception number!");
3732 return exception_begin()[i];
3734 Expr *getNoexceptExpr() const {
3735 if (!isComputedNoexcept(getExceptionSpecType()))
3737 // NoexceptExpr sits where the arguments end.
3738 return *reinterpret_cast<Expr *const *>(param_type_end());
3741 /// If this function type has an exception specification which hasn't
3742 /// been determined yet (either because it has not been evaluated or because
3743 /// it has not been instantiated), this is the function whose exception
3744 /// specification is represented by this type.
3745 FunctionDecl *getExceptionSpecDecl() const {
3746 if (getExceptionSpecType() != EST_Uninstantiated &&
3747 getExceptionSpecType() != EST_Unevaluated)
3749 return reinterpret_cast<FunctionDecl *const *>(param_type_end())[0];
3752 /// If this function type has an uninstantiated exception
3753 /// specification, this is the function whose exception specification
3754 /// should be instantiated to find the exception specification for
3756 FunctionDecl *getExceptionSpecTemplate() const {
3757 if (getExceptionSpecType() != EST_Uninstantiated)
3759 return reinterpret_cast<FunctionDecl *const *>(param_type_end())[1];
3762 /// Determine whether this function type has a non-throwing exception
3764 CanThrowResult canThrow() const;
3766 /// Determine whether this function type has a non-throwing exception
3767 /// specification. If this depends on template arguments, returns
3768 /// \c ResultIfDependent.
3769 bool isNothrow(bool ResultIfDependent = false) const {
3770 return ResultIfDependent ? canThrow() != CT_Can
3771 : canThrow() == CT_Cannot;
3774 bool isVariadic() const { return Variadic; }
3776 /// Determines whether this function prototype contains a
3777 /// parameter pack at the end.
3779 /// A function template whose last parameter is a parameter pack can be
3780 /// called with an arbitrary number of arguments, much like a variadic
3782 bool isTemplateVariadic() const;
3784 bool hasTrailingReturn() const { return HasTrailingReturn; }
3786 unsigned getTypeQuals() const { return FunctionType::getTypeQuals(); }
3788 /// Retrieve the ref-qualifier associated with this function type.
3789 RefQualifierKind getRefQualifier() const {
3790 return static_cast<RefQualifierKind>(FunctionTypeBits.RefQualifier);
3793 using param_type_iterator = const QualType *;
3794 using param_type_range = llvm::iterator_range<param_type_iterator>;
3796 param_type_range param_types() const {
3797 return param_type_range(param_type_begin(), param_type_end());
3800 param_type_iterator param_type_begin() const {
3801 return reinterpret_cast<const QualType *>(this+1);
3804 param_type_iterator param_type_end() const {
3805 return param_type_begin() + NumParams;
3808 using exception_iterator = const QualType *;
3810 ArrayRef<QualType> exceptions() const {
3811 return llvm::makeArrayRef(exception_begin(), exception_end());
3814 exception_iterator exception_begin() const {
3815 // exceptions begin where arguments end
3816 return param_type_end();
3819 exception_iterator exception_end() const {
3820 if (getExceptionSpecType() != EST_Dynamic)
3821 return exception_begin();
3822 return exception_begin() + NumExceptions;
3825 /// Is there any interesting extra information for any of the parameters
3826 /// of this function type?
3827 bool hasExtParameterInfos() const { return HasExtParameterInfos; }
3828 ArrayRef<ExtParameterInfo> getExtParameterInfos() const {
3829 assert(hasExtParameterInfos());
3830 return ArrayRef<ExtParameterInfo>(getExtParameterInfosBuffer(),
3834 /// Return a pointer to the beginning of the array of extra parameter
3835 /// information, if present, or else null if none of the parameters
3836 /// carry it. This is equivalent to getExtProtoInfo().ExtParameterInfos.
3837 const ExtParameterInfo *getExtParameterInfosOrNull() const {
3838 if (!hasExtParameterInfos())
3840 return getExtParameterInfosBuffer();
3843 ExtParameterInfo getExtParameterInfo(unsigned I) const {
3844 assert(I < getNumParams() && "parameter index out of range");
3845 if (hasExtParameterInfos())
3846 return getExtParameterInfosBuffer()[I];
3847 return ExtParameterInfo();
3850 ParameterABI getParameterABI(unsigned I) const {
3851 assert(I < getNumParams() && "parameter index out of range");
3852 if (hasExtParameterInfos())
3853 return getExtParameterInfosBuffer()[I].getABI();
3854 return ParameterABI::Ordinary;
3857 bool isParamConsumed(unsigned I) const {
3858 assert(I < getNumParams() && "parameter index out of range");
3859 if (hasExtParameterInfos())
3860 return getExtParameterInfosBuffer()[I].isConsumed();
3864 bool isSugared() const { return false; }
3865 QualType desugar() const { return QualType(this, 0); }
3867 void printExceptionSpecification(raw_ostream &OS,
3868 const PrintingPolicy &Policy) const;
3870 static bool classof(const Type *T) {
3871 return T->getTypeClass() == FunctionProto;
3874 void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Ctx);
3875 static void Profile(llvm::FoldingSetNodeID &ID, QualType Result,
3876 param_type_iterator ArgTys, unsigned NumArgs,
3877 const ExtProtoInfo &EPI, const ASTContext &Context,
3881 /// Represents the dependent type named by a dependently-scoped
3882 /// typename using declaration, e.g.
3883 /// using typename Base<T>::foo;
3885 /// Template instantiation turns these into the underlying type.
3886 class UnresolvedUsingType : public Type {
3887 friend class ASTContext; // ASTContext creates these.
3889 UnresolvedUsingTypenameDecl *Decl;
3891 UnresolvedUsingType(const UnresolvedUsingTypenameDecl *D)
3892 : Type(UnresolvedUsing, QualType(), true, true, false,
3893 /*ContainsUnexpandedParameterPack=*/false),
3894 Decl(const_cast<UnresolvedUsingTypenameDecl*>(D)) {}
3897 UnresolvedUsingTypenameDecl *getDecl() const { return Decl; }
3899 bool isSugared() const { return false; }
3900 QualType desugar() const { return QualType(this, 0); }
3902 static bool classof(const Type *T) {
3903 return T->getTypeClass() == UnresolvedUsing;
3906 void Profile(llvm::FoldingSetNodeID &ID) {
3907 return Profile(ID, Decl);
3910 static void Profile(llvm::FoldingSetNodeID &ID,
3911 UnresolvedUsingTypenameDecl *D) {
3916 class TypedefType : public Type {
3917 TypedefNameDecl *Decl;
3920 friend class ASTContext; // ASTContext creates these.
3922 TypedefType(TypeClass tc, const TypedefNameDecl *D, QualType can)
3923 : Type(tc, can, can->isDependentType(),
3924 can->isInstantiationDependentType(),
3925 can->isVariablyModifiedType(),
3926 /*ContainsUnexpandedParameterPack=*/false),
3927 Decl(const_cast<TypedefNameDecl*>(D)) {
3928 assert(!isa<TypedefType>(can) && "Invalid canonical type");
3932 TypedefNameDecl *getDecl() const { return Decl; }
3934 bool isSugared() const { return true; }
3935 QualType desugar() const;
3937 static bool classof(const Type *T) { return T->getTypeClass() == Typedef; }
3940 /// Represents a `typeof` (or __typeof__) expression (a GCC extension).
3941 class TypeOfExprType : public Type {
3945 friend class ASTContext; // ASTContext creates these.
3947 TypeOfExprType(Expr *E, QualType can = QualType());
3950 Expr *getUnderlyingExpr() const { return TOExpr; }
3952 /// Remove a single level of sugar.
3953 QualType desugar() const;
3955 /// Returns whether this type directly provides sugar.
3956 bool isSugared() const;
3958 static bool classof(const Type *T) { return T->getTypeClass() == TypeOfExpr; }
3961 /// Internal representation of canonical, dependent
3962 /// `typeof(expr)` types.
3964 /// This class is used internally by the ASTContext to manage
3965 /// canonical, dependent types, only. Clients will only see instances
3966 /// of this class via TypeOfExprType nodes.
3967 class DependentTypeOfExprType
3968 : public TypeOfExprType, public llvm::FoldingSetNode {
3969 const ASTContext &Context;
3972 DependentTypeOfExprType(const ASTContext &Context, Expr *E)
3973 : TypeOfExprType(E), Context(Context) {}
3975 void Profile(llvm::FoldingSetNodeID &ID) {
3976 Profile(ID, Context, getUnderlyingExpr());
3979 static void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context,
3983 /// Represents `typeof(type)`, a GCC extension.
3984 class TypeOfType : public Type {
3985 friend class ASTContext; // ASTContext creates these.
3989 TypeOfType(QualType T, QualType can)
3990 : Type(TypeOf, can, T->isDependentType(),
3991 T->isInstantiationDependentType(),
3992 T->isVariablyModifiedType(),
3993 T->containsUnexpandedParameterPack()),
3995 assert(!isa<TypedefType>(can) && "Invalid canonical type");
3999 QualType getUnderlyingType() const { return TOType; }
4001 /// Remove a single level of sugar.
4002 QualType desugar() const { return getUnderlyingType(); }
4004 /// Returns whether this type directly provides sugar.
4005 bool isSugared() const { return true; }
4007 static bool classof(const Type *T) { return T->getTypeClass() == TypeOf; }
4010 /// Represents the type `decltype(expr)` (C++11).
4011 class DecltypeType : public Type {
4013 QualType UnderlyingType;
4016 friend class ASTContext; // ASTContext creates these.
4018 DecltypeType(Expr *E, QualType underlyingType, QualType can = QualType());
4021 Expr *getUnderlyingExpr() const { return E; }
4022 QualType getUnderlyingType() const { return UnderlyingType; }
4024 /// Remove a single level of sugar.
4025 QualType desugar() const;
4027 /// Returns whether this type directly provides sugar.
4028 bool isSugared() const;
4030 static bool classof(const Type *T) { return T->getTypeClass() == Decltype; }
4033 /// Internal representation of canonical, dependent
4034 /// decltype(expr) types.
4036 /// This class is used internally by the ASTContext to manage
4037 /// canonical, dependent types, only. Clients will only see instances
4038 /// of this class via DecltypeType nodes.
4039 class DependentDecltypeType : public DecltypeType, public llvm::FoldingSetNode {
4040 const ASTContext &Context;
4043 DependentDecltypeType(const ASTContext &Context, Expr *E);
4045 void Profile(llvm::FoldingSetNodeID &ID) {
4046 Profile(ID, Context, getUnderlyingExpr());
4049 static void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context,
4053 /// A unary type transform, which is a type constructed from another.
4054 class UnaryTransformType : public Type {
4061 /// The untransformed type.
4064 /// The transformed type if not dependent, otherwise the same as BaseType.
4065 QualType UnderlyingType;
4070 friend class ASTContext;
4072 UnaryTransformType(QualType BaseTy, QualType UnderlyingTy, UTTKind UKind,
4073 QualType CanonicalTy);
4076 bool isSugared() const { return !isDependentType(); }
4077 QualType desugar() const { return UnderlyingType; }
4079 QualType getUnderlyingType() const { return UnderlyingType; }
4080 QualType getBaseType() const { return BaseType; }
4082 UTTKind getUTTKind() const { return UKind; }
4084 static bool classof(const Type *T) {
4085 return T->getTypeClass() == UnaryTransform;
4089 /// Internal representation of canonical, dependent
4090 /// __underlying_type(type) types.
4092 /// This class is used internally by the ASTContext to manage
4093 /// canonical, dependent types, only. Clients will only see instances
4094 /// of this class via UnaryTransformType nodes.
4095 class DependentUnaryTransformType : public UnaryTransformType,
4096 public llvm::FoldingSetNode {
4098 DependentUnaryTransformType(const ASTContext &C, QualType BaseType,
4101 void Profile(llvm::FoldingSetNodeID &ID) {
4102 Profile(ID, getBaseType(), getUTTKind());
4105 static void Profile(llvm::FoldingSetNodeID &ID, QualType BaseType,
4107 ID.AddPointer(BaseType.getAsOpaquePtr());
4108 ID.AddInteger((unsigned)UKind);
4112 class TagType : public Type {
4113 friend class ASTReader;
4115 /// Stores the TagDecl associated with this type. The decl may point to any
4116 /// TagDecl that declares the entity.
4120 TagType(TypeClass TC, const TagDecl *D, QualType can);
4123 TagDecl *getDecl() const;
4125 /// Determines whether this type is in the process of being defined.
4126 bool isBeingDefined() const;
4128 static bool classof(const Type *T) {
4129 return T->getTypeClass() >= TagFirst && T->getTypeClass() <= TagLast;
4133 /// A helper class that allows the use of isa/cast/dyncast
4134 /// to detect TagType objects of structs/unions/classes.
4135 class RecordType : public TagType {
4137 friend class ASTContext; // ASTContext creates these.
4139 explicit RecordType(const RecordDecl *D)
4140 : TagType(Record, reinterpret_cast<const TagDecl*>(D), QualType()) {}
4141 explicit RecordType(TypeClass TC, RecordDecl *D)
4142 : TagType(TC, reinterpret_cast<const TagDecl*>(D), QualType()) {}
4145 RecordDecl *getDecl() const {
4146 return reinterpret_cast<RecordDecl*>(TagType::getDecl());
4149 /// Recursively check all fields in the record for const-ness. If any field
4150 /// is declared const, return true. Otherwise, return false.
4151 bool hasConstFields() const;
4153 bool isSugared() const { return false; }
4154 QualType desugar() const { return QualType(this, 0); }
4156 static bool classof(const Type *T) { return T->getTypeClass() == Record; }
4159 /// A helper class that allows the use of isa/cast/dyncast
4160 /// to detect TagType objects of enums.
4161 class EnumType : public TagType {
4162 friend class ASTContext; // ASTContext creates these.
4164 explicit EnumType(const EnumDecl *D)
4165 : TagType(Enum, reinterpret_cast<const TagDecl*>(D), QualType()) {}
4168 EnumDecl *getDecl() const {
4169 return reinterpret_cast<EnumDecl*>(TagType::getDecl());
4172 bool isSugared() const { return false; }
4173 QualType desugar() const { return QualType(this, 0); }
4175 static bool classof(const Type *T) { return T->getTypeClass() == Enum; }
4178 /// An attributed type is a type to which a type attribute has been applied.
4180 /// The "modified type" is the fully-sugared type to which the attributed
4181 /// type was applied; generally it is not canonically equivalent to the
4182 /// attributed type. The "equivalent type" is the minimally-desugared type
4183 /// which the type is canonically equivalent to.
4185 /// For example, in the following attributed type:
4186 /// int32_t __attribute__((vector_size(16)))
4187 /// - the modified type is the TypedefType for int32_t
4188 /// - the equivalent type is VectorType(16, int32_t)
4189 /// - the canonical type is VectorType(16, int)
4190 class AttributedType : public Type, public llvm::FoldingSetNode {
4192 // It is really silly to have yet another attribute-kind enum, but
4193 // clang::attr::Kind doesn't currently cover the pure type attrs.
4195 // Expression operand.
4199 attr_neon_vector_type,
4200 attr_neon_polyvector_type,
4202 FirstExprOperandKind = attr_address_space,
4203 LastExprOperandKind = attr_neon_polyvector_type,
4205 // Enumerated operand (string or keyword).
4207 attr_objc_ownership,
4211 FirstEnumOperandKind = attr_objc_gc,
4212 LastEnumOperandKind = attr_pcs_vfp,
4235 attr_ns_returns_retained,
4237 attr_null_unspecified,
4239 attr_objc_inert_unsafe_unretained,
4244 friend class ASTContext; // ASTContext creates these
4246 QualType ModifiedType;
4247 QualType EquivalentType;
4249 AttributedType(QualType canon, Kind attrKind, QualType modified,
4250 QualType equivalent)
4251 : Type(Attributed, canon, equivalent->isDependentType(),
4252 equivalent->isInstantiationDependentType(),
4253 equivalent->isVariablyModifiedType(),
4254 equivalent->containsUnexpandedParameterPack()),
4255 ModifiedType(modified), EquivalentType(equivalent) {
4256 AttributedTypeBits.AttrKind = attrKind;
4260 Kind getAttrKind() const {
4261 return static_cast<Kind>(AttributedTypeBits.AttrKind);
4264 QualType getModifiedType() const { return ModifiedType; }
4265 QualType getEquivalentType() const { return EquivalentType; }
4267 bool isSugared() const { return true; }
4268 QualType desugar() const { return getEquivalentType(); }
4270 /// Does this attribute behave like a type qualifier?
4272 /// A type qualifier adjusts a type to provide specialized rules for
4273 /// a specific object, like the standard const and volatile qualifiers.
4274 /// This includes attributes controlling things like nullability,
4275 /// address spaces, and ARC ownership. The value of the object is still
4276 /// largely described by the modified type.
4278 /// In contrast, many type attributes "rewrite" their modified type to
4279 /// produce a fundamentally different type, not necessarily related in any
4280 /// formalizable way to the original type. For example, calling convention
4281 /// and vector attributes are not simple type qualifiers.
4283 /// Type qualifiers are often, but not always, reflected in the canonical
4285 bool isQualifier() const;
4287 bool isMSTypeSpec() const;
4289 bool isCallingConv() const;
4291 llvm::Optional<NullabilityKind> getImmediateNullability() const;
4293 /// Retrieve the attribute kind corresponding to the given
4294 /// nullability kind.
4295 static Kind getNullabilityAttrKind(NullabilityKind kind) {
4297 case NullabilityKind::NonNull:
4298 return attr_nonnull;
4300 case NullabilityKind::Nullable:
4301 return attr_nullable;
4303 case NullabilityKind::Unspecified:
4304 return attr_null_unspecified;
4306 llvm_unreachable("Unknown nullability kind.");
4309 /// Strip off the top-level nullability annotation on the given
4310 /// type, if it's there.
4312 /// \param T The type to strip. If the type is exactly an
4313 /// AttributedType specifying nullability (without looking through
4314 /// type sugar), the nullability is returned and this type changed
4315 /// to the underlying modified type.
4317 /// \returns the top-level nullability, if present.
4318 static Optional<NullabilityKind> stripOuterNullability(QualType &T);
4320 void Profile(llvm::FoldingSetNodeID &ID) {
4321 Profile(ID, getAttrKind(), ModifiedType, EquivalentType);
4324 static void Profile(llvm::FoldingSetNodeID &ID, Kind attrKind,
4325 QualType modified, QualType equivalent) {
4326 ID.AddInteger(attrKind);
4327 ID.AddPointer(modified.getAsOpaquePtr());
4328 ID.AddPointer(equivalent.getAsOpaquePtr());
4331 static bool classof(const Type *T) {
4332 return T->getTypeClass() == Attributed;
4336 class TemplateTypeParmType : public Type, public llvm::FoldingSetNode {
4337 friend class ASTContext; // ASTContext creates these
4339 // Helper data collector for canonical types.
4340 struct CanonicalTTPTInfo {
4341 unsigned Depth : 15;
4342 unsigned ParameterPack : 1;
4343 unsigned Index : 16;
4347 // Info for the canonical type.
4348 CanonicalTTPTInfo CanTTPTInfo;
4350 // Info for the non-canonical type.
4351 TemplateTypeParmDecl *TTPDecl;
4354 /// Build a non-canonical type.
4355 TemplateTypeParmType(TemplateTypeParmDecl *TTPDecl, QualType Canon)
4356 : Type(TemplateTypeParm, Canon, /*Dependent=*/true,
4357 /*InstantiationDependent=*/true,
4358 /*VariablyModified=*/false,
4359 Canon->containsUnexpandedParameterPack()),
4362 /// Build the canonical type.
4363 TemplateTypeParmType(unsigned D, unsigned I, bool PP)
4364 : Type(TemplateTypeParm, QualType(this, 0),
4366 /*InstantiationDependent=*/true,
4367 /*VariablyModified=*/false, PP) {
4368 CanTTPTInfo.Depth = D;
4369 CanTTPTInfo.Index = I;
4370 CanTTPTInfo.ParameterPack = PP;
4373 const CanonicalTTPTInfo& getCanTTPTInfo() const {
4374 QualType Can = getCanonicalTypeInternal();
4375 return Can->castAs<TemplateTypeParmType>()->CanTTPTInfo;
4379 unsigned getDepth() const { return getCanTTPTInfo().Depth; }
4380 unsigned getIndex() const { return getCanTTPTInfo().Index; }
4381 bool isParameterPack() const { return getCanTTPTInfo().ParameterPack; }
4383 TemplateTypeParmDecl *getDecl() const {
4384 return isCanonicalUnqualified() ? nullptr : TTPDecl;
4387 IdentifierInfo *getIdentifier() const;
4389 bool isSugared() const { return false; }
4390 QualType desugar() const { return QualType(this, 0); }
4392 void Profile(llvm::FoldingSetNodeID &ID) {
4393 Profile(ID, getDepth(), getIndex(), isParameterPack(), getDecl());
4396 static void Profile(llvm::FoldingSetNodeID &ID, unsigned Depth,
4397 unsigned Index, bool ParameterPack,
4398 TemplateTypeParmDecl *TTPDecl) {
4399 ID.AddInteger(Depth);
4400 ID.AddInteger(Index);
4401 ID.AddBoolean(ParameterPack);
4402 ID.AddPointer(TTPDecl);
4405 static bool classof(const Type *T) {
4406 return T->getTypeClass() == TemplateTypeParm;
4410 /// Represents the result of substituting a type for a template
4413 /// Within an instantiated template, all template type parameters have
4414 /// been replaced with these. They are used solely to record that a
4415 /// type was originally written as a template type parameter;
4416 /// therefore they are never canonical.
4417 class SubstTemplateTypeParmType : public Type, public llvm::FoldingSetNode {
4418 friend class ASTContext;
4420 // The original type parameter.
4421 const TemplateTypeParmType *Replaced;
4423 SubstTemplateTypeParmType(const TemplateTypeParmType *Param, QualType Canon)
4424 : Type(SubstTemplateTypeParm, Canon, Canon->isDependentType(),
4425 Canon->isInstantiationDependentType(),
4426 Canon->isVariablyModifiedType(),
4427 Canon->containsUnexpandedParameterPack()),
4431 /// Gets the template parameter that was substituted for.
4432 const TemplateTypeParmType *getReplacedParameter() const {
4436 /// Gets the type that was substituted for the template
4438 QualType getReplacementType() const {
4439 return getCanonicalTypeInternal();
4442 bool isSugared() const { return true; }
4443 QualType desugar() const { return getReplacementType(); }
4445 void Profile(llvm::FoldingSetNodeID &ID) {
4446 Profile(ID, getReplacedParameter(), getReplacementType());
4449 static void Profile(llvm::FoldingSetNodeID &ID,
4450 const TemplateTypeParmType *Replaced,
4451 QualType Replacement) {
4452 ID.AddPointer(Replaced);
4453 ID.AddPointer(Replacement.getAsOpaquePtr());
4456 static bool classof(const Type *T) {
4457 return T->getTypeClass() == SubstTemplateTypeParm;
4461 /// Represents the result of substituting a set of types for a template
4462 /// type parameter pack.
4464 /// When a pack expansion in the source code contains multiple parameter packs
4465 /// and those parameter packs correspond to different levels of template
4466 /// parameter lists, this type node is used to represent a template type
4467 /// parameter pack from an outer level, which has already had its argument pack
4468 /// substituted but that still lives within a pack expansion that itself
4469 /// could not be instantiated. When actually performing a substitution into
4470 /// that pack expansion (e.g., when all template parameters have corresponding
4471 /// arguments), this type will be replaced with the \c SubstTemplateTypeParmType
4472 /// at the current pack substitution index.
4473 class SubstTemplateTypeParmPackType : public Type, public llvm::FoldingSetNode {
4474 friend class ASTContext;
4476 /// The original type parameter.
4477 const TemplateTypeParmType *Replaced;
4479 /// A pointer to the set of template arguments that this
4480 /// parameter pack is instantiated with.
4481 const TemplateArgument *Arguments;
4483 /// The number of template arguments in \c Arguments.
4484 unsigned NumArguments;
4486 SubstTemplateTypeParmPackType(const TemplateTypeParmType *Param,
4488 const TemplateArgument &ArgPack);
4491 IdentifierInfo *getIdentifier() const { return Replaced->getIdentifier(); }
4493 /// Gets the template parameter that was substituted for.
4494 const TemplateTypeParmType *getReplacedParameter() const {
4498 bool isSugared() const { return false; }
4499 QualType desugar() const { return QualType(this, 0); }
4501 TemplateArgument getArgumentPack() const;
4503 void Profile(llvm::FoldingSetNodeID &ID);
4504 static void Profile(llvm::FoldingSetNodeID &ID,
4505 const TemplateTypeParmType *Replaced,
4506 const TemplateArgument &ArgPack);
4508 static bool classof(const Type *T) {
4509 return T->getTypeClass() == SubstTemplateTypeParmPack;
4513 /// Common base class for placeholders for types that get replaced by
4514 /// placeholder type deduction: C++11 auto, C++14 decltype(auto), C++17 deduced
4515 /// class template types, and (eventually) constrained type names from the C++
4518 /// These types are usually a placeholder for a deduced type. However, before
4519 /// the initializer is attached, or (usually) if the initializer is
4520 /// type-dependent, there is no deduced type and the type is canonical. In
4521 /// the latter case, it is also a dependent type.
4522 class DeducedType : public Type {
4524 DeducedType(TypeClass TC, QualType DeducedAsType, bool IsDependent,
4525 bool IsInstantiationDependent, bool ContainsParameterPack)
4527 // FIXME: Retain the sugared deduced type?
4528 DeducedAsType.isNull() ? QualType(this, 0)
4529 : DeducedAsType.getCanonicalType(),
4530 IsDependent, IsInstantiationDependent,
4531 /*VariablyModified=*/false, ContainsParameterPack) {
4532 if (!DeducedAsType.isNull()) {
4533 if (DeducedAsType->isDependentType())
4535 if (DeducedAsType->isInstantiationDependentType())
4536 setInstantiationDependent();
4537 if (DeducedAsType->containsUnexpandedParameterPack())
4538 setContainsUnexpandedParameterPack();
4543 bool isSugared() const { return !isCanonicalUnqualified(); }
4544 QualType desugar() const { return getCanonicalTypeInternal(); }
4546 /// Get the type deduced for this placeholder type, or null if it's
4547 /// either not been deduced or was deduced to a dependent type.
4548 QualType getDeducedType() const {
4549 return !isCanonicalUnqualified() ? getCanonicalTypeInternal() : QualType();
4551 bool isDeduced() const {
4552 return !isCanonicalUnqualified() || isDependentType();
4555 static bool classof(const Type *T) {
4556 return T->getTypeClass() == Auto ||
4557 T->getTypeClass() == DeducedTemplateSpecialization;
4561 /// Represents a C++11 auto or C++14 decltype(auto) type.
4562 class AutoType : public DeducedType, public llvm::FoldingSetNode {
4563 friend class ASTContext; // ASTContext creates these
4565 AutoType(QualType DeducedAsType, AutoTypeKeyword Keyword,
4566 bool IsDeducedAsDependent)
4567 : DeducedType(Auto, DeducedAsType, IsDeducedAsDependent,
4568 IsDeducedAsDependent, /*ContainsPack=*/false) {
4569 AutoTypeBits.Keyword = (unsigned)Keyword;
4573 bool isDecltypeAuto() const {
4574 return getKeyword() == AutoTypeKeyword::DecltypeAuto;
4577 AutoTypeKeyword getKeyword() const {
4578 return (AutoTypeKeyword)AutoTypeBits.Keyword;
4581 void Profile(llvm::FoldingSetNodeID &ID) {
4582 Profile(ID, getDeducedType(), getKeyword(), isDependentType());
4585 static void Profile(llvm::FoldingSetNodeID &ID, QualType Deduced,
4586 AutoTypeKeyword Keyword, bool IsDependent) {
4587 ID.AddPointer(Deduced.getAsOpaquePtr());
4588 ID.AddInteger((unsigned)Keyword);
4589 ID.AddBoolean(IsDependent);
4592 static bool classof(const Type *T) {
4593 return T->getTypeClass() == Auto;
4597 /// Represents a C++17 deduced template specialization type.
4598 class DeducedTemplateSpecializationType : public DeducedType,
4599 public llvm::FoldingSetNode {
4600 friend class ASTContext; // ASTContext creates these
4602 /// The name of the template whose arguments will be deduced.
4603 TemplateName Template;
4605 DeducedTemplateSpecializationType(TemplateName Template,
4606 QualType DeducedAsType,
4607 bool IsDeducedAsDependent)
4608 : DeducedType(DeducedTemplateSpecialization, DeducedAsType,
4609 IsDeducedAsDependent || Template.isDependent(),
4610 IsDeducedAsDependent || Template.isInstantiationDependent(),
4611 Template.containsUnexpandedParameterPack()),
4612 Template(Template) {}
4615 /// Retrieve the name of the template that we are deducing.
4616 TemplateName getTemplateName() const { return Template;}
4618 void Profile(llvm::FoldingSetNodeID &ID) {
4619 Profile(ID, getTemplateName(), getDeducedType(), isDependentType());
4622 static void Profile(llvm::FoldingSetNodeID &ID, TemplateName Template,
4623 QualType Deduced, bool IsDependent) {
4624 Template.Profile(ID);
4625 ID.AddPointer(Deduced.getAsOpaquePtr());
4626 ID.AddBoolean(IsDependent);
4629 static bool classof(const Type *T) {
4630 return T->getTypeClass() == DeducedTemplateSpecialization;
4634 /// Represents a type template specialization; the template
4635 /// must be a class template, a type alias template, or a template
4636 /// template parameter. A template which cannot be resolved to one of
4637 /// these, e.g. because it is written with a dependent scope
4638 /// specifier, is instead represented as a
4639 /// @c DependentTemplateSpecializationType.
4641 /// A non-dependent template specialization type is always "sugar",
4642 /// typically for a \c RecordType. For example, a class template
4643 /// specialization type of \c vector<int> will refer to a tag type for
4644 /// the instantiation \c std::vector<int, std::allocator<int>>
4646 /// Template specializations are dependent if either the template or
4647 /// any of the template arguments are dependent, in which case the
4648 /// type may also be canonical.
4650 /// Instances of this type are allocated with a trailing array of
4651 /// TemplateArguments, followed by a QualType representing the
4652 /// non-canonical aliased type when the template is a type alias
4654 class alignas(8) TemplateSpecializationType
4656 public llvm::FoldingSetNode {
4657 friend class ASTContext; // ASTContext creates these
4659 /// The name of the template being specialized. This is
4660 /// either a TemplateName::Template (in which case it is a
4661 /// ClassTemplateDecl*, a TemplateTemplateParmDecl*, or a
4662 /// TypeAliasTemplateDecl*), a
4663 /// TemplateName::SubstTemplateTemplateParmPack, or a
4664 /// TemplateName::SubstTemplateTemplateParm (in which case the
4665 /// replacement must, recursively, be one of these).
4666 TemplateName Template;
4668 /// The number of template arguments named in this class template
4670 unsigned NumArgs : 31;
4672 /// Whether this template specialization type is a substituted type alias.
4673 unsigned TypeAlias : 1;
4675 TemplateSpecializationType(TemplateName T,
4676 ArrayRef<TemplateArgument> Args,
4681 /// Determine whether any of the given template arguments are dependent.
4682 static bool anyDependentTemplateArguments(ArrayRef<TemplateArgumentLoc> Args,
4683 bool &InstantiationDependent);
4685 static bool anyDependentTemplateArguments(const TemplateArgumentListInfo &,
4686 bool &InstantiationDependent);
4688 /// True if this template specialization type matches a current
4689 /// instantiation in the context in which it is found.
4690 bool isCurrentInstantiation() const {
4691 return isa<InjectedClassNameType>(getCanonicalTypeInternal());
4694 /// Determine if this template specialization type is for a type alias
4695 /// template that has been substituted.
4697 /// Nearly every template specialization type whose template is an alias
4698 /// template will be substituted. However, this is not the case when
4699 /// the specialization contains a pack expansion but the template alias
4700 /// does not have a corresponding parameter pack, e.g.,
4703 /// template<typename T, typename U, typename V> struct S;
4704 /// template<typename T, typename U> using A = S<T, int, U>;
4705 /// template<typename... Ts> struct X {
4706 /// typedef A<Ts...> type; // not a type alias
4709 bool isTypeAlias() const { return TypeAlias; }
4711 /// Get the aliased type, if this is a specialization of a type alias
4713 QualType getAliasedType() const {
4714 assert(isTypeAlias() && "not a type alias template specialization");
4715 return *reinterpret_cast<const QualType*>(end());
4718 using iterator = const TemplateArgument *;
4720 iterator begin() const { return getArgs(); }
4721 iterator end() const; // defined inline in TemplateBase.h
4723 /// Retrieve the name of the template that we are specializing.
4724 TemplateName getTemplateName() const { return Template; }
4726 /// Retrieve the template arguments.
4727 const TemplateArgument *getArgs() const {
4728 return reinterpret_cast<const TemplateArgument *>(this + 1);
4731 /// Retrieve the number of template arguments.
4732 unsigned getNumArgs() const { return NumArgs; }
4734 /// Retrieve a specific template argument as a type.
4735 /// \pre \c isArgType(Arg)
4736 const TemplateArgument &getArg(unsigned Idx) const; // in TemplateBase.h
4738 ArrayRef<TemplateArgument> template_arguments() const {
4739 return {getArgs(), NumArgs};
4742 bool isSugared() const {
4743 return !isDependentType() || isCurrentInstantiation() || isTypeAlias();
4746 QualType desugar() const { return getCanonicalTypeInternal(); }
4748 void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Ctx) {
4749 Profile(ID, Template, template_arguments(), Ctx);
4751 getAliasedType().Profile(ID);
4754 static void Profile(llvm::FoldingSetNodeID &ID, TemplateName T,
4755 ArrayRef<TemplateArgument> Args,
4756 const ASTContext &Context);
4758 static bool classof(const Type *T) {
4759 return T->getTypeClass() == TemplateSpecialization;
4763 /// Print a template argument list, including the '<' and '>'
4764 /// enclosing the template arguments.
4765 void printTemplateArgumentList(raw_ostream &OS,
4766 ArrayRef<TemplateArgument> Args,
4767 const PrintingPolicy &Policy);
4769 void printTemplateArgumentList(raw_ostream &OS,
4770 ArrayRef<TemplateArgumentLoc> Args,
4771 const PrintingPolicy &Policy);
4773 void printTemplateArgumentList(raw_ostream &OS,
4774 const TemplateArgumentListInfo &Args,
4775 const PrintingPolicy &Policy);
4777 /// The injected class name of a C++ class template or class
4778 /// template partial specialization. Used to record that a type was
4779 /// spelled with a bare identifier rather than as a template-id; the
4780 /// equivalent for non-templated classes is just RecordType.
4782 /// Injected class name types are always dependent. Template
4783 /// instantiation turns these into RecordTypes.
4785 /// Injected class name types are always canonical. This works
4786 /// because it is impossible to compare an injected class name type
4787 /// with the corresponding non-injected template type, for the same
4788 /// reason that it is impossible to directly compare template
4789 /// parameters from different dependent contexts: injected class name
4790 /// types can only occur within the scope of a particular templated
4791 /// declaration, and within that scope every template specialization
4792 /// will canonicalize to the injected class name (when appropriate
4793 /// according to the rules of the language).
4794 class InjectedClassNameType : public Type {
4795 friend class ASTContext; // ASTContext creates these.
4796 friend class ASTNodeImporter;
4797 friend class ASTReader; // FIXME: ASTContext::getInjectedClassNameType is not
4798 // currently suitable for AST reading, too much
4799 // interdependencies.
4801 CXXRecordDecl *Decl;
4803 /// The template specialization which this type represents.
4805 /// template <class T> class A { ... };
4806 /// this is A<T>, whereas in
4807 /// template <class X, class Y> class A<B<X,Y> > { ... };
4808 /// this is A<B<X,Y> >.
4810 /// It is always unqualified, always a template specialization type,
4811 /// and always dependent.
4812 QualType InjectedType;
4814 InjectedClassNameType(CXXRecordDecl *D, QualType TST)
4815 : Type(InjectedClassName, QualType(), /*Dependent=*/true,
4816 /*InstantiationDependent=*/true,
4817 /*VariablyModified=*/false,
4818 /*ContainsUnexpandedParameterPack=*/false),
4819 Decl(D), InjectedType(TST) {
4820 assert(isa<TemplateSpecializationType>(TST));
4821 assert(!TST.hasQualifiers());
4822 assert(TST->isDependentType());
4826 QualType getInjectedSpecializationType() const { return InjectedType; }
4828 const TemplateSpecializationType *getInjectedTST() const {
4829 return cast<TemplateSpecializationType>(InjectedType.getTypePtr());
4832 TemplateName getTemplateName() const {
4833 return getInjectedTST()->getTemplateName();
4836 CXXRecordDecl *getDecl() const;
4838 bool isSugared() const { return false; }
4839 QualType desugar() const { return QualType(this, 0); }
4841 static bool classof(const Type *T) {
4842 return T->getTypeClass() == InjectedClassName;
4846 /// The kind of a tag type.
4848 /// The "struct" keyword.
4851 /// The "__interface" keyword.
4854 /// The "union" keyword.
4857 /// The "class" keyword.
4860 /// The "enum" keyword.
4864 /// The elaboration keyword that precedes a qualified type name or
4865 /// introduces an elaborated-type-specifier.
4866 enum ElaboratedTypeKeyword {
4867 /// The "struct" keyword introduces the elaborated-type-specifier.
4870 /// The "__interface" keyword introduces the elaborated-type-specifier.
4873 /// The "union" keyword introduces the elaborated-type-specifier.
4876 /// The "class" keyword introduces the elaborated-type-specifier.
4879 /// The "enum" keyword introduces the elaborated-type-specifier.
4882 /// The "typename" keyword precedes the qualified type name, e.g.,
4883 /// \c typename T::type.
4886 /// No keyword precedes the qualified type name.
4890 /// A helper class for Type nodes having an ElaboratedTypeKeyword.
4891 /// The keyword in stored in the free bits of the base class.
4892 /// Also provides a few static helpers for converting and printing
4893 /// elaborated type keyword and tag type kind enumerations.
4894 class TypeWithKeyword : public Type {
4896 TypeWithKeyword(ElaboratedTypeKeyword Keyword, TypeClass tc,
4897 QualType Canonical, bool Dependent,
4898 bool InstantiationDependent, bool VariablyModified,
4899 bool ContainsUnexpandedParameterPack)
4900 : Type(tc, Canonical, Dependent, InstantiationDependent, VariablyModified,
4901 ContainsUnexpandedParameterPack) {
4902 TypeWithKeywordBits.Keyword = Keyword;
4906 ElaboratedTypeKeyword getKeyword() const {
4907 return static_cast<ElaboratedTypeKeyword>(TypeWithKeywordBits.Keyword);
4910 /// Converts a type specifier (DeclSpec::TST) into an elaborated type keyword.
4911 static ElaboratedTypeKeyword getKeywordForTypeSpec(unsigned TypeSpec);
4913 /// Converts a type specifier (DeclSpec::TST) into a tag type kind.
4914 /// It is an error to provide a type specifier which *isn't* a tag kind here.
4915 static TagTypeKind getTagTypeKindForTypeSpec(unsigned TypeSpec);
4917 /// Converts a TagTypeKind into an elaborated type keyword.
4918 static ElaboratedTypeKeyword getKeywordForTagTypeKind(TagTypeKind Tag);
4920 /// Converts an elaborated type keyword into a TagTypeKind.
4921 /// It is an error to provide an elaborated type keyword
4922 /// which *isn't* a tag kind here.
4923 static TagTypeKind getTagTypeKindForKeyword(ElaboratedTypeKeyword Keyword);
4925 static bool KeywordIsTagTypeKind(ElaboratedTypeKeyword Keyword);
4927 static StringRef getKeywordName(ElaboratedTypeKeyword Keyword);
4929 static StringRef getTagTypeKindName(TagTypeKind Kind) {
4930 return getKeywordName(getKeywordForTagTypeKind(Kind));
4933 class CannotCastToThisType {};
4934 static CannotCastToThisType classof(const Type *);
4937 /// Represents a type that was referred to using an elaborated type
4938 /// keyword, e.g., struct S, or via a qualified name, e.g., N::M::type,
4941 /// This type is used to keep track of a type name as written in the
4942 /// source code, including tag keywords and any nested-name-specifiers.
4943 /// The type itself is always "sugar", used to express what was written
4944 /// in the source code but containing no additional semantic information.
4945 class ElaboratedType : public TypeWithKeyword, public llvm::FoldingSetNode {
4946 friend class ASTContext; // ASTContext creates these
4948 /// The nested name specifier containing the qualifier.
4949 NestedNameSpecifier *NNS;
4951 /// The type that this qualified name refers to.
4954 /// The (re)declaration of this tag type owned by this occurrence, or nullptr
4956 TagDecl *OwnedTagDecl;
4958 ElaboratedType(ElaboratedTypeKeyword Keyword, NestedNameSpecifier *NNS,
4959 QualType NamedType, QualType CanonType, TagDecl *OwnedTagDecl)
4960 : TypeWithKeyword(Keyword, Elaborated, CanonType,
4961 NamedType->isDependentType(),
4962 NamedType->isInstantiationDependentType(),
4963 NamedType->isVariablyModifiedType(),
4964 NamedType->containsUnexpandedParameterPack()),
4965 NNS(NNS), NamedType(NamedType), OwnedTagDecl(OwnedTagDecl) {
4966 assert(!(Keyword == ETK_None && NNS == nullptr) &&
4967 "ElaboratedType cannot have elaborated type keyword "
4968 "and name qualifier both null.");
4974 /// Retrieve the qualification on this type.
4975 NestedNameSpecifier *getQualifier() const { return NNS; }
4977 /// Retrieve the type named by the qualified-id.
4978 QualType getNamedType() const { return NamedType; }
4980 /// Remove a single level of sugar.
4981 QualType desugar() const { return getNamedType(); }
4983 /// Returns whether this type directly provides sugar.
4984 bool isSugared() const { return true; }
4986 /// Return the (re)declaration of this type owned by this occurrence of this
4987 /// type, or nullptr if none.
4988 TagDecl *getOwnedTagDecl() const { return OwnedTagDecl; }
4990 void Profile(llvm::FoldingSetNodeID &ID) {
4991 Profile(ID, getKeyword(), NNS, NamedType, OwnedTagDecl);
4994 static void Profile(llvm::FoldingSetNodeID &ID, ElaboratedTypeKeyword Keyword,
4995 NestedNameSpecifier *NNS, QualType NamedType,
4996 TagDecl *OwnedTagDecl) {
4997 ID.AddInteger(Keyword);
4999 NamedType.Profile(ID);
5000 ID.AddPointer(OwnedTagDecl);
5003 static bool classof(const Type *T) {
5004 return T->getTypeClass() == Elaborated;
5008 /// Represents a qualified type name for which the type name is
5011 /// DependentNameType represents a class of dependent types that involve a
5012 /// possibly dependent nested-name-specifier (e.g., "T::") followed by a
5013 /// name of a type. The DependentNameType may start with a "typename" (for a
5014 /// typename-specifier), "class", "struct", "union", or "enum" (for a
5015 /// dependent elaborated-type-specifier), or nothing (in contexts where we
5016 /// know that we must be referring to a type, e.g., in a base class specifier).
5017 /// Typically the nested-name-specifier is dependent, but in MSVC compatibility
5018 /// mode, this type is used with non-dependent names to delay name lookup until
5020 class DependentNameType : public TypeWithKeyword, public llvm::FoldingSetNode {
5021 friend class ASTContext; // ASTContext creates these
5023 /// The nested name specifier containing the qualifier.
5024 NestedNameSpecifier *NNS;
5026 /// The type that this typename specifier refers to.
5027 const IdentifierInfo *Name;
5029 DependentNameType(ElaboratedTypeKeyword Keyword, NestedNameSpecifier *NNS,
5030 const IdentifierInfo *Name, QualType CanonType)
5031 : TypeWithKeyword(Keyword, DependentName, CanonType, /*Dependent=*/true,
5032 /*InstantiationDependent=*/true,
5033 /*VariablyModified=*/false,
5034 NNS->containsUnexpandedParameterPack()),
5035 NNS(NNS), Name(Name) {}
5038 /// Retrieve the qualification on this type.
5039 NestedNameSpecifier *getQualifier() const { return NNS; }
5041 /// Retrieve the type named by the typename specifier as an identifier.
5043 /// This routine will return a non-NULL identifier pointer when the
5044 /// form of the original typename was terminated by an identifier,
5045 /// e.g., "typename T::type".
5046 const IdentifierInfo *getIdentifier() const {
5050 bool isSugared() const { return false; }
5051 QualType desugar() const { return QualType(this, 0); }
5053 void Profile(llvm::FoldingSetNodeID &ID) {
5054 Profile(ID, getKeyword(), NNS, Name);
5057 static void Profile(llvm::FoldingSetNodeID &ID, ElaboratedTypeKeyword Keyword,
5058 NestedNameSpecifier *NNS, const IdentifierInfo *Name) {
5059 ID.AddInteger(Keyword);
5061 ID.AddPointer(Name);
5064 static bool classof(const Type *T) {
5065 return T->getTypeClass() == DependentName;
5069 /// Represents a template specialization type whose template cannot be
5071 /// A<T>::template B<T>
5072 class alignas(8) DependentTemplateSpecializationType
5073 : public TypeWithKeyword,
5074 public llvm::FoldingSetNode {
5075 friend class ASTContext; // ASTContext creates these
5077 /// The nested name specifier containing the qualifier.
5078 NestedNameSpecifier *NNS;
5080 /// The identifier of the template.
5081 const IdentifierInfo *Name;
5083 /// The number of template arguments named in this class template
5087 DependentTemplateSpecializationType(ElaboratedTypeKeyword Keyword,
5088 NestedNameSpecifier *NNS,
5089 const IdentifierInfo *Name,
5090 ArrayRef<TemplateArgument> Args,
5093 const TemplateArgument *getArgBuffer() const {
5094 return reinterpret_cast<const TemplateArgument*>(this+1);
5097 TemplateArgument *getArgBuffer() {
5098 return reinterpret_cast<TemplateArgument*>(this+1);
5102 NestedNameSpecifier *getQualifier() const { return NNS; }
5103 const IdentifierInfo *getIdentifier() const { return Name; }
5105 /// Retrieve the template arguments.
5106 const TemplateArgument *getArgs() const {
5107 return getArgBuffer();
5110 /// Retrieve the number of template arguments.
5111 unsigned getNumArgs() const { return NumArgs; }
5113 const TemplateArgument &getArg(unsigned Idx) const; // in TemplateBase.h
5115 ArrayRef<TemplateArgument> template_arguments() const {
5116 return {getArgs(), NumArgs};
5119 using iterator = const TemplateArgument *;
5121 iterator begin() const { return getArgs(); }
5122 iterator end() const; // inline in TemplateBase.h
5124 bool isSugared() const { return false; }
5125 QualType desugar() const { return QualType(this, 0); }
5127 void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context) {
5128 Profile(ID, Context, getKeyword(), NNS, Name, {getArgs(), NumArgs});
5131 static void Profile(llvm::FoldingSetNodeID &ID,
5132 const ASTContext &Context,
5133 ElaboratedTypeKeyword Keyword,
5134 NestedNameSpecifier *Qualifier,
5135 const IdentifierInfo *Name,
5136 ArrayRef<TemplateArgument> Args);
5138 static bool classof(const Type *T) {
5139 return T->getTypeClass() == DependentTemplateSpecialization;
5143 /// Represents a pack expansion of types.
5145 /// Pack expansions are part of C++11 variadic templates. A pack
5146 /// expansion contains a pattern, which itself contains one or more
5147 /// "unexpanded" parameter packs. When instantiated, a pack expansion
5148 /// produces a series of types, each instantiated from the pattern of
5149 /// the expansion, where the Ith instantiation of the pattern uses the
5150 /// Ith arguments bound to each of the unexpanded parameter packs. The
5151 /// pack expansion is considered to "expand" these unexpanded
5152 /// parameter packs.
5155 /// template<typename ...Types> struct tuple;
5157 /// template<typename ...Types>
5158 /// struct tuple_of_references {
5159 /// typedef tuple<Types&...> type;
5163 /// Here, the pack expansion \c Types&... is represented via a
5164 /// PackExpansionType whose pattern is Types&.
5165 class PackExpansionType : public Type, public llvm::FoldingSetNode {
5166 friend class ASTContext; // ASTContext creates these
5168 /// The pattern of the pack expansion.
5171 /// The number of expansions that this pack expansion will
5172 /// generate when substituted (+1), or indicates that
5174 /// This field will only have a non-zero value when some of the parameter
5175 /// packs that occur within the pattern have been substituted but others have
5177 unsigned NumExpansions;
5179 PackExpansionType(QualType Pattern, QualType Canon,
5180 Optional<unsigned> NumExpansions)
5181 : Type(PackExpansion, Canon, /*Dependent=*/Pattern->isDependentType(),
5182 /*InstantiationDependent=*/true,
5183 /*VariablyModified=*/Pattern->isVariablyModifiedType(),
5184 /*ContainsUnexpandedParameterPack=*/false),
5186 NumExpansions(NumExpansions ? *NumExpansions + 1 : 0) {}
5189 /// Retrieve the pattern of this pack expansion, which is the
5190 /// type that will be repeatedly instantiated when instantiating the
5191 /// pack expansion itself.
5192 QualType getPattern() const { return Pattern; }
5194 /// Retrieve the number of expansions that this pack expansion will
5195 /// generate, if known.
5196 Optional<unsigned> getNumExpansions() const {
5198 return NumExpansions - 1;
5203 bool isSugared() const { return !Pattern->isDependentType(); }
5204 QualType desugar() const { return isSugared() ? Pattern : QualType(this, 0); }
5206 void Profile(llvm::FoldingSetNodeID &ID) {
5207 Profile(ID, getPattern(), getNumExpansions());
5210 static void Profile(llvm::FoldingSetNodeID &ID, QualType Pattern,
5211 Optional<unsigned> NumExpansions) {
5212 ID.AddPointer(Pattern.getAsOpaquePtr());
5213 ID.AddBoolean(NumExpansions.hasValue());
5215 ID.AddInteger(*NumExpansions);
5218 static bool classof(const Type *T) {
5219 return T->getTypeClass() == PackExpansion;
5223 /// This class wraps the list of protocol qualifiers. For types that can
5224 /// take ObjC protocol qualifers, they can subclass this class.
5226 class ObjCProtocolQualifiers {
5228 ObjCProtocolQualifiers() = default;
5230 ObjCProtocolDecl * const *getProtocolStorage() const {
5231 return const_cast<ObjCProtocolQualifiers*>(this)->getProtocolStorage();
5234 ObjCProtocolDecl **getProtocolStorage() {
5235 return static_cast<T*>(this)->getProtocolStorageImpl();
5238 void setNumProtocols(unsigned N) {
5239 static_cast<T*>(this)->setNumProtocolsImpl(N);
5242 void initialize(ArrayRef<ObjCProtocolDecl *> protocols) {
5243 setNumProtocols(protocols.size());
5244 assert(getNumProtocols() == protocols.size() &&
5245 "bitfield overflow in protocol count");
5246 if (!protocols.empty())
5247 memcpy(getProtocolStorage(), protocols.data(),
5248 protocols.size() * sizeof(ObjCProtocolDecl*));
5252 using qual_iterator = ObjCProtocolDecl * const *;
5253 using qual_range = llvm::iterator_range<qual_iterator>;
5255 qual_range quals() const { return qual_range(qual_begin(), qual_end()); }
5256 qual_iterator qual_begin() const { return getProtocolStorage(); }
5257 qual_iterator qual_end() const { return qual_begin() + getNumProtocols(); }
5259 bool qual_empty() const { return getNumProtocols() == 0; }
5261 /// Return the number of qualifying protocols in this type, or 0 if
5263 unsigned getNumProtocols() const {
5264 return static_cast<const T*>(this)->getNumProtocolsImpl();
5267 /// Fetch a protocol by index.
5268 ObjCProtocolDecl *getProtocol(unsigned I) const {
5269 assert(I < getNumProtocols() && "Out-of-range protocol access");
5270 return qual_begin()[I];
5273 /// Retrieve all of the protocol qualifiers.
5274 ArrayRef<ObjCProtocolDecl *> getProtocols() const {
5275 return ArrayRef<ObjCProtocolDecl *>(qual_begin(), getNumProtocols());
5279 /// Represents a type parameter type in Objective C. It can take
5280 /// a list of protocols.
5281 class ObjCTypeParamType : public Type,
5282 public ObjCProtocolQualifiers<ObjCTypeParamType>,
5283 public llvm::FoldingSetNode {
5284 friend class ASTContext;
5285 friend class ObjCProtocolQualifiers<ObjCTypeParamType>;
5287 /// The number of protocols stored on this type.
5288 unsigned NumProtocols : 6;
5290 ObjCTypeParamDecl *OTPDecl;
5292 /// The protocols are stored after the ObjCTypeParamType node. In the
5293 /// canonical type, the list of protocols are sorted alphabetically
5295 ObjCProtocolDecl **getProtocolStorageImpl();
5297 /// Return the number of qualifying protocols in this interface type,
5298 /// or 0 if there are none.
5299 unsigned getNumProtocolsImpl() const {
5300 return NumProtocols;
5303 void setNumProtocolsImpl(unsigned N) {
5307 ObjCTypeParamType(const ObjCTypeParamDecl *D,
5309 ArrayRef<ObjCProtocolDecl *> protocols);
5312 bool isSugared() const { return true; }
5313 QualType desugar() const { return getCanonicalTypeInternal(); }
5315 static bool classof(const Type *T) {
5316 return T->getTypeClass() == ObjCTypeParam;
5319 void Profile(llvm::FoldingSetNodeID &ID);
5320 static void Profile(llvm::FoldingSetNodeID &ID,
5321 const ObjCTypeParamDecl *OTPDecl,
5322 ArrayRef<ObjCProtocolDecl *> protocols);
5324 ObjCTypeParamDecl *getDecl() const { return OTPDecl; }
5327 /// Represents a class type in Objective C.
5329 /// Every Objective C type is a combination of a base type, a set of
5330 /// type arguments (optional, for parameterized classes) and a list of
5333 /// Given the following declarations:
5339 /// 'C' is an ObjCInterfaceType C. It is sugar for an ObjCObjectType
5340 /// with base C and no protocols.
5342 /// 'C<P>' is an unspecialized ObjCObjectType with base C and protocol list [P].
5343 /// 'C<C*>' is a specialized ObjCObjectType with type arguments 'C*' and no
5345 /// 'C<C*><P>' is a specialized ObjCObjectType with base C, type arguments 'C*',
5346 /// and protocol list [P].
5348 /// 'id' is a TypedefType which is sugar for an ObjCObjectPointerType whose
5349 /// pointee is an ObjCObjectType with base BuiltinType::ObjCIdType
5350 /// and no protocols.
5352 /// 'id<P>' is an ObjCObjectPointerType whose pointee is an ObjCObjectType
5353 /// with base BuiltinType::ObjCIdType and protocol list [P]. Eventually
5354 /// this should get its own sugar class to better represent the source.
5355 class ObjCObjectType : public Type,
5356 public ObjCProtocolQualifiers<ObjCObjectType> {
5357 friend class ObjCProtocolQualifiers<ObjCObjectType>;
5359 // ObjCObjectType.NumTypeArgs - the number of type arguments stored
5360 // after the ObjCObjectPointerType node.
5361 // ObjCObjectType.NumProtocols - the number of protocols stored
5362 // after the type arguments of ObjCObjectPointerType node.
5364 // These protocols are those written directly on the type. If
5365 // protocol qualifiers ever become additive, the iterators will need
5366 // to get kindof complicated.
5368 // In the canonical object type, these are sorted alphabetically
5371 /// Either a BuiltinType or an InterfaceType or sugar for either.
5374 /// Cached superclass type.
5375 mutable llvm::PointerIntPair<const ObjCObjectType *, 1, bool>
5376 CachedSuperClassType;
5378 QualType *getTypeArgStorage();
5379 const QualType *getTypeArgStorage() const {
5380 return const_cast<ObjCObjectType *>(this)->getTypeArgStorage();
5383 ObjCProtocolDecl **getProtocolStorageImpl();
5384 /// Return the number of qualifying protocols in this interface type,
5385 /// or 0 if there are none.
5386 unsigned getNumProtocolsImpl() const {
5387 return ObjCObjectTypeBits.NumProtocols;
5389 void setNumProtocolsImpl(unsigned N) {
5390 ObjCObjectTypeBits.NumProtocols = N;
5394 enum Nonce_ObjCInterface { Nonce_ObjCInterface };
5396 ObjCObjectType(QualType Canonical, QualType Base,
5397 ArrayRef<QualType> typeArgs,
5398 ArrayRef<ObjCProtocolDecl *> protocols,
5401 ObjCObjectType(enum Nonce_ObjCInterface)
5402 : Type(ObjCInterface, QualType(), false, false, false, false),
5403 BaseType(QualType(this_(), 0)) {
5404 ObjCObjectTypeBits.NumProtocols = 0;
5405 ObjCObjectTypeBits.NumTypeArgs = 0;
5406 ObjCObjectTypeBits.IsKindOf = 0;
5409 void computeSuperClassTypeSlow() const;
5412 /// Gets the base type of this object type. This is always (possibly
5413 /// sugar for) one of:
5414 /// - the 'id' builtin type (as opposed to the 'id' type visible to the
5415 /// user, which is a typedef for an ObjCObjectPointerType)
5416 /// - the 'Class' builtin type (same caveat)
5417 /// - an ObjCObjectType (currently always an ObjCInterfaceType)
5418 QualType getBaseType() const { return BaseType; }
5420 bool isObjCId() const {
5421 return getBaseType()->isSpecificBuiltinType(BuiltinType::ObjCId);
5424 bool isObjCClass() const {
5425 return getBaseType()->isSpecificBuiltinType(BuiltinType::ObjCClass);
5428 bool isObjCUnqualifiedId() const { return qual_empty() && isObjCId(); }
5429 bool isObjCUnqualifiedClass() const { return qual_empty() && isObjCClass(); }
5430 bool isObjCUnqualifiedIdOrClass() const {
5431 if (!qual_empty()) return false;
5432 if (const BuiltinType *T = getBaseType()->getAs<BuiltinType>())
5433 return T->getKind() == BuiltinType::ObjCId ||
5434 T->getKind() == BuiltinType::ObjCClass;
5437 bool isObjCQualifiedId() const { return !qual_empty() && isObjCId(); }
5438 bool isObjCQualifiedClass() const { return !qual_empty() && isObjCClass(); }
5440 /// Gets the interface declaration for this object type, if the base type
5441 /// really is an interface.
5442 ObjCInterfaceDecl *getInterface() const;
5444 /// Determine whether this object type is "specialized", meaning
5445 /// that it has type arguments.
5446 bool isSpecialized() const;
5448 /// Determine whether this object type was written with type arguments.
5449 bool isSpecializedAsWritten() const {
5450 return ObjCObjectTypeBits.NumTypeArgs > 0;
5453 /// Determine whether this object type is "unspecialized", meaning
5454 /// that it has no type arguments.
5455 bool isUnspecialized() const { return !isSpecialized(); }
5457 /// Determine whether this object type is "unspecialized" as
5458 /// written, meaning that it has no type arguments.
5459 bool isUnspecializedAsWritten() const { return !isSpecializedAsWritten(); }
5461 /// Retrieve the type arguments of this object type (semantically).
5462 ArrayRef<QualType> getTypeArgs() const;
5464 /// Retrieve the type arguments of this object type as they were
5466 ArrayRef<QualType> getTypeArgsAsWritten() const {
5467 return llvm::makeArrayRef(getTypeArgStorage(),
5468 ObjCObjectTypeBits.NumTypeArgs);
5471 /// Whether this is a "__kindof" type as written.
5472 bool isKindOfTypeAsWritten() const { return ObjCObjectTypeBits.IsKindOf; }
5474 /// Whether this ia a "__kindof" type (semantically).
5475 bool isKindOfType() const;
5477 /// Retrieve the type of the superclass of this object type.
5479 /// This operation substitutes any type arguments into the
5480 /// superclass of the current class type, potentially producing a
5481 /// specialization of the superclass type. Produces a null type if
5482 /// there is no superclass.
5483 QualType getSuperClassType() const {
5484 if (!CachedSuperClassType.getInt())
5485 computeSuperClassTypeSlow();
5487 assert(CachedSuperClassType.getInt() && "Superclass not set?");
5488 return QualType(CachedSuperClassType.getPointer(), 0);
5491 /// Strip off the Objective-C "kindof" type and (with it) any
5492 /// protocol qualifiers.
5493 QualType stripObjCKindOfTypeAndQuals(const ASTContext &ctx) const;
5495 bool isSugared() const { return false; }
5496 QualType desugar() const { return QualType(this, 0); }
5498 static bool classof(const Type *T) {
5499 return T->getTypeClass() == ObjCObject ||
5500 T->getTypeClass() == ObjCInterface;
5504 /// A class providing a concrete implementation
5505 /// of ObjCObjectType, so as to not increase the footprint of
5506 /// ObjCInterfaceType. Code outside of ASTContext and the core type
5507 /// system should not reference this type.
5508 class ObjCObjectTypeImpl : public ObjCObjectType, public llvm::FoldingSetNode {
5509 friend class ASTContext;
5511 // If anyone adds fields here, ObjCObjectType::getProtocolStorage()
5512 // will need to be modified.
5514 ObjCObjectTypeImpl(QualType Canonical, QualType Base,
5515 ArrayRef<QualType> typeArgs,
5516 ArrayRef<ObjCProtocolDecl *> protocols,
5518 : ObjCObjectType(Canonical, Base, typeArgs, protocols, isKindOf) {}
5521 void Profile(llvm::FoldingSetNodeID &ID);
5522 static void Profile(llvm::FoldingSetNodeID &ID,
5524 ArrayRef<QualType> typeArgs,
5525 ArrayRef<ObjCProtocolDecl *> protocols,
5529 inline QualType *ObjCObjectType::getTypeArgStorage() {
5530 return reinterpret_cast<QualType *>(static_cast<ObjCObjectTypeImpl*>(this)+1);
5533 inline ObjCProtocolDecl **ObjCObjectType::getProtocolStorageImpl() {
5534 return reinterpret_cast<ObjCProtocolDecl**>(
5535 getTypeArgStorage() + ObjCObjectTypeBits.NumTypeArgs);
5538 inline ObjCProtocolDecl **ObjCTypeParamType::getProtocolStorageImpl() {
5539 return reinterpret_cast<ObjCProtocolDecl**>(
5540 static_cast<ObjCTypeParamType*>(this)+1);
5543 /// Interfaces are the core concept in Objective-C for object oriented design.
5544 /// They basically correspond to C++ classes. There are two kinds of interface
5545 /// types: normal interfaces like `NSString`, and qualified interfaces, which
5546 /// are qualified with a protocol list like `NSString<NSCopyable, NSAmazing>`.
5548 /// ObjCInterfaceType guarantees the following properties when considered
5549 /// as a subtype of its superclass, ObjCObjectType:
5550 /// - There are no protocol qualifiers. To reinforce this, code which
5551 /// tries to invoke the protocol methods via an ObjCInterfaceType will
5552 /// fail to compile.
5553 /// - It is its own base type. That is, if T is an ObjCInterfaceType*,
5554 /// T->getBaseType() == QualType(T, 0).
5555 class ObjCInterfaceType : public ObjCObjectType {
5556 friend class ASTContext; // ASTContext creates these.
5557 friend class ASTReader;
5558 friend class ObjCInterfaceDecl;
5560 mutable ObjCInterfaceDecl *Decl;
5562 ObjCInterfaceType(const ObjCInterfaceDecl *D)
5563 : ObjCObjectType(Nonce_ObjCInterface),
5564 Decl(const_cast<ObjCInterfaceDecl*>(D)) {}
5567 /// Get the declaration of this interface.
5568 ObjCInterfaceDecl *getDecl() const { return Decl; }
5570 bool isSugared() const { return false; }
5571 QualType desugar() const { return QualType(this, 0); }
5573 static bool classof(const Type *T) {
5574 return T->getTypeClass() == ObjCInterface;
5577 // Nonsense to "hide" certain members of ObjCObjectType within this
5578 // class. People asking for protocols on an ObjCInterfaceType are
5579 // not going to get what they want: ObjCInterfaceTypes are
5580 // guaranteed to have no protocols.
5590 inline ObjCInterfaceDecl *ObjCObjectType::getInterface() const {
5591 QualType baseType = getBaseType();
5592 while (const auto *ObjT = baseType->getAs<ObjCObjectType>()) {
5593 if (const auto *T = dyn_cast<ObjCInterfaceType>(ObjT))
5594 return T->getDecl();
5596 baseType = ObjT->getBaseType();
5602 /// Represents a pointer to an Objective C object.
5604 /// These are constructed from pointer declarators when the pointee type is
5605 /// an ObjCObjectType (or sugar for one). In addition, the 'id' and 'Class'
5606 /// types are typedefs for these, and the protocol-qualified types 'id<P>'
5607 /// and 'Class<P>' are translated into these.
5609 /// Pointers to pointers to Objective C objects are still PointerTypes;
5610 /// only the first level of pointer gets it own type implementation.
5611 class ObjCObjectPointerType : public Type, public llvm::FoldingSetNode {
5612 friend class ASTContext; // ASTContext creates these.
5614 QualType PointeeType;
5616 ObjCObjectPointerType(QualType Canonical, QualType Pointee)
5617 : Type(ObjCObjectPointer, Canonical,
5618 Pointee->isDependentType(),
5619 Pointee->isInstantiationDependentType(),
5620 Pointee->isVariablyModifiedType(),
5621 Pointee->containsUnexpandedParameterPack()),
5622 PointeeType(Pointee) {}
5625 /// Gets the type pointed to by this ObjC pointer.
5626 /// The result will always be an ObjCObjectType or sugar thereof.
5627 QualType getPointeeType() const { return PointeeType; }
5629 /// Gets the type pointed to by this ObjC pointer. Always returns non-null.
5631 /// This method is equivalent to getPointeeType() except that
5632 /// it discards any typedefs (or other sugar) between this
5633 /// type and the "outermost" object type. So for:
5635 /// \@class A; \@protocol P; \@protocol Q;
5636 /// typedef A<P> AP;
5638 /// typedef A1<P> A1P;
5639 /// typedef A1P<Q> A1PQ;
5641 /// For 'A*', getObjectType() will return 'A'.
5642 /// For 'A<P>*', getObjectType() will return 'A<P>'.
5643 /// For 'AP*', getObjectType() will return 'A<P>'.
5644 /// For 'A1*', getObjectType() will return 'A'.
5645 /// For 'A1<P>*', getObjectType() will return 'A1<P>'.
5646 /// For 'A1P*', getObjectType() will return 'A1<P>'.
5647 /// For 'A1PQ*', getObjectType() will return 'A1<Q>', because
5648 /// adding protocols to a protocol-qualified base discards the
5649 /// old qualifiers (for now). But if it didn't, getObjectType()
5650 /// would return 'A1P<Q>' (and we'd have to make iterating over
5651 /// qualifiers more complicated).
5652 const ObjCObjectType *getObjectType() const {
5653 return PointeeType->castAs<ObjCObjectType>();
5656 /// If this pointer points to an Objective C
5657 /// \@interface type, gets the type for that interface. Any protocol
5658 /// qualifiers on the interface are ignored.
5660 /// \return null if the base type for this pointer is 'id' or 'Class'
5661 const ObjCInterfaceType *getInterfaceType() const;
5663 /// If this pointer points to an Objective \@interface
5664 /// type, gets the declaration for that interface.
5666 /// \return null if the base type for this pointer is 'id' or 'Class'
5667 ObjCInterfaceDecl *getInterfaceDecl() const {
5668 return getObjectType()->getInterface();
5671 /// True if this is equivalent to the 'id' type, i.e. if
5672 /// its object type is the primitive 'id' type with no protocols.
5673 bool isObjCIdType() const {
5674 return getObjectType()->isObjCUnqualifiedId();
5677 /// True if this is equivalent to the 'Class' type,
5678 /// i.e. if its object tive is the primitive 'Class' type with no protocols.
5679 bool isObjCClassType() const {
5680 return getObjectType()->isObjCUnqualifiedClass();
5683 /// True if this is equivalent to the 'id' or 'Class' type,
5684 bool isObjCIdOrClassType() const {
5685 return getObjectType()->isObjCUnqualifiedIdOrClass();
5688 /// True if this is equivalent to 'id<P>' for some non-empty set of
5690 bool isObjCQualifiedIdType() const {
5691 return getObjectType()->isObjCQualifiedId();
5694 /// True if this is equivalent to 'Class<P>' for some non-empty set of
5696 bool isObjCQualifiedClassType() const {
5697 return getObjectType()->isObjCQualifiedClass();
5700 /// Whether this is a "__kindof" type.
5701 bool isKindOfType() const { return getObjectType()->isKindOfType(); }
5703 /// Whether this type is specialized, meaning that it has type arguments.
5704 bool isSpecialized() const { return getObjectType()->isSpecialized(); }
5706 /// Whether this type is specialized, meaning that it has type arguments.
5707 bool isSpecializedAsWritten() const {
5708 return getObjectType()->isSpecializedAsWritten();
5711 /// Whether this type is unspecialized, meaning that is has no type arguments.
5712 bool isUnspecialized() const { return getObjectType()->isUnspecialized(); }
5714 /// Determine whether this object type is "unspecialized" as
5715 /// written, meaning that it has no type arguments.
5716 bool isUnspecializedAsWritten() const { return !isSpecializedAsWritten(); }
5718 /// Retrieve the type arguments for this type.
5719 ArrayRef<QualType> getTypeArgs() const {
5720 return getObjectType()->getTypeArgs();
5723 /// Retrieve the type arguments for this type.
5724 ArrayRef<QualType> getTypeArgsAsWritten() const {
5725 return getObjectType()->getTypeArgsAsWritten();
5728 /// An iterator over the qualifiers on the object type. Provided
5729 /// for convenience. This will always iterate over the full set of
5730 /// protocols on a type, not just those provided directly.
5731 using qual_iterator = ObjCObjectType::qual_iterator;
5732 using qual_range = llvm::iterator_range<qual_iterator>;
5734 qual_range quals() const { return qual_range(qual_begin(), qual_end()); }
5736 qual_iterator qual_begin() const {
5737 return getObjectType()->qual_begin();
5740 qual_iterator qual_end() const {
5741 return getObjectType()->qual_end();
5744 bool qual_empty() const { return getObjectType()->qual_empty(); }
5746 /// Return the number of qualifying protocols on the object type.
5747 unsigned getNumProtocols() const {
5748 return getObjectType()->getNumProtocols();
5751 /// Retrieve a qualifying protocol by index on the object type.
5752 ObjCProtocolDecl *getProtocol(unsigned I) const {
5753 return getObjectType()->getProtocol(I);
5756 bool isSugared() const { return false; }
5757 QualType desugar() const { return QualType(this, 0); }
5759 /// Retrieve the type of the superclass of this object pointer type.
5761 /// This operation substitutes any type arguments into the
5762 /// superclass of the current class type, potentially producing a
5763 /// pointer to a specialization of the superclass type. Produces a
5764 /// null type if there is no superclass.
5765 QualType getSuperClassType() const;
5767 /// Strip off the Objective-C "kindof" type and (with it) any
5768 /// protocol qualifiers.
5769 const ObjCObjectPointerType *stripObjCKindOfTypeAndQuals(
5770 const ASTContext &ctx) const;
5772 void Profile(llvm::FoldingSetNodeID &ID) {
5773 Profile(ID, getPointeeType());
5776 static void Profile(llvm::FoldingSetNodeID &ID, QualType T) {
5777 ID.AddPointer(T.getAsOpaquePtr());
5780 static bool classof(const Type *T) {
5781 return T->getTypeClass() == ObjCObjectPointer;
5785 class AtomicType : public Type, public llvm::FoldingSetNode {
5786 friend class ASTContext; // ASTContext creates these.
5790 AtomicType(QualType ValTy, QualType Canonical)
5791 : Type(Atomic, Canonical, ValTy->isDependentType(),
5792 ValTy->isInstantiationDependentType(),
5793 ValTy->isVariablyModifiedType(),
5794 ValTy->containsUnexpandedParameterPack()),
5798 /// Gets the type contained by this atomic type, i.e.
5799 /// the type returned by performing an atomic load of this atomic type.
5800 QualType getValueType() const { return ValueType; }
5802 bool isSugared() const { return false; }
5803 QualType desugar() const { return QualType(this, 0); }
5805 void Profile(llvm::FoldingSetNodeID &ID) {
5806 Profile(ID, getValueType());
5809 static void Profile(llvm::FoldingSetNodeID &ID, QualType T) {
5810 ID.AddPointer(T.getAsOpaquePtr());
5813 static bool classof(const Type *T) {
5814 return T->getTypeClass() == Atomic;
5818 /// PipeType - OpenCL20.
5819 class PipeType : public Type, public llvm::FoldingSetNode {
5820 friend class ASTContext; // ASTContext creates these.
5822 QualType ElementType;
5825 PipeType(QualType elemType, QualType CanonicalPtr, bool isRead)
5826 : Type(Pipe, CanonicalPtr, elemType->isDependentType(),
5827 elemType->isInstantiationDependentType(),
5828 elemType->isVariablyModifiedType(),
5829 elemType->containsUnexpandedParameterPack()),
5830 ElementType(elemType), isRead(isRead) {}
5833 QualType getElementType() const { return ElementType; }
5835 bool isSugared() const { return false; }
5837 QualType desugar() const { return QualType(this, 0); }
5839 void Profile(llvm::FoldingSetNodeID &ID) {
5840 Profile(ID, getElementType(), isReadOnly());
5843 static void Profile(llvm::FoldingSetNodeID &ID, QualType T, bool isRead) {
5844 ID.AddPointer(T.getAsOpaquePtr());
5845 ID.AddBoolean(isRead);
5848 static bool classof(const Type *T) {
5849 return T->getTypeClass() == Pipe;
5852 bool isReadOnly() const { return isRead; }
5855 /// A qualifier set is used to build a set of qualifiers.
5856 class QualifierCollector : public Qualifiers {
5858 QualifierCollector(Qualifiers Qs = Qualifiers()) : Qualifiers(Qs) {}
5860 /// Collect any qualifiers on the given type and return an
5861 /// unqualified type. The qualifiers are assumed to be consistent
5862 /// with those already in the type.
5863 const Type *strip(QualType type) {
5864 addFastQualifiers(type.getLocalFastQualifiers());
5865 if (!type.hasLocalNonFastQualifiers())
5866 return type.getTypePtrUnsafe();
5868 const ExtQuals *extQuals = type.getExtQualsUnsafe();
5869 addConsistentQualifiers(extQuals->getQualifiers());
5870 return extQuals->getBaseType();
5873 /// Apply the collected qualifiers to the given type.
5874 QualType apply(const ASTContext &Context, QualType QT) const;
5876 /// Apply the collected qualifiers to the given type.
5877 QualType apply(const ASTContext &Context, const Type* T) const;
5880 // Inline function definitions.
5882 inline SplitQualType SplitQualType::getSingleStepDesugaredType() const {
5883 SplitQualType desugar =
5884 Ty->getLocallyUnqualifiedSingleStepDesugaredType().split();
5885 desugar.Quals.addConsistentQualifiers(Quals);
5889 inline const Type *QualType::getTypePtr() const {
5890 return getCommonPtr()->BaseType;
5893 inline const Type *QualType::getTypePtrOrNull() const {
5894 return (isNull() ? nullptr : getCommonPtr()->BaseType);
5897 inline SplitQualType QualType::split() const {
5898 if (!hasLocalNonFastQualifiers())
5899 return SplitQualType(getTypePtrUnsafe(),
5900 Qualifiers::fromFastMask(getLocalFastQualifiers()));
5902 const ExtQuals *eq = getExtQualsUnsafe();
5903 Qualifiers qs = eq->getQualifiers();
5904 qs.addFastQualifiers(getLocalFastQualifiers());
5905 return SplitQualType(eq->getBaseType(), qs);
5908 inline Qualifiers QualType::getLocalQualifiers() const {
5910 if (hasLocalNonFastQualifiers())
5911 Quals = getExtQualsUnsafe()->getQualifiers();
5912 Quals.addFastQualifiers(getLocalFastQualifiers());
5916 inline Qualifiers QualType::getQualifiers() const {
5917 Qualifiers quals = getCommonPtr()->CanonicalType.getLocalQualifiers();
5918 quals.addFastQualifiers(getLocalFastQualifiers());
5922 inline unsigned QualType::getCVRQualifiers() const {
5923 unsigned cvr = getCommonPtr()->CanonicalType.getLocalCVRQualifiers();
5924 cvr |= getLocalCVRQualifiers();
5928 inline QualType QualType::getCanonicalType() const {
5929 QualType canon = getCommonPtr()->CanonicalType;
5930 return canon.withFastQualifiers(getLocalFastQualifiers());
5933 inline bool QualType::isCanonical() const {
5934 return getTypePtr()->isCanonicalUnqualified();
5937 inline bool QualType::isCanonicalAsParam() const {
5938 if (!isCanonical()) return false;
5939 if (hasLocalQualifiers()) return false;
5941 const Type *T = getTypePtr();
5942 if (T->isVariablyModifiedType() && T->hasSizedVLAType())
5945 return !isa<FunctionType>(T) && !isa<ArrayType>(T);
5948 inline bool QualType::isConstQualified() const {
5949 return isLocalConstQualified() ||
5950 getCommonPtr()->CanonicalType.isLocalConstQualified();
5953 inline bool QualType::isRestrictQualified() const {
5954 return isLocalRestrictQualified() ||
5955 getCommonPtr()->CanonicalType.isLocalRestrictQualified();
5959 inline bool QualType::isVolatileQualified() const {
5960 return isLocalVolatileQualified() ||
5961 getCommonPtr()->CanonicalType.isLocalVolatileQualified();
5964 inline bool QualType::hasQualifiers() const {
5965 return hasLocalQualifiers() ||
5966 getCommonPtr()->CanonicalType.hasLocalQualifiers();
5969 inline QualType QualType::getUnqualifiedType() const {
5970 if (!getTypePtr()->getCanonicalTypeInternal().hasLocalQualifiers())
5971 return QualType(getTypePtr(), 0);
5973 return QualType(getSplitUnqualifiedTypeImpl(*this).Ty, 0);
5976 inline SplitQualType QualType::getSplitUnqualifiedType() const {
5977 if (!getTypePtr()->getCanonicalTypeInternal().hasLocalQualifiers())
5980 return getSplitUnqualifiedTypeImpl(*this);
5983 inline void QualType::removeLocalConst() {
5984 removeLocalFastQualifiers(Qualifiers::Const);
5987 inline void QualType::removeLocalRestrict() {
5988 removeLocalFastQualifiers(Qualifiers::Restrict);
5991 inline void QualType::removeLocalVolatile() {
5992 removeLocalFastQualifiers(Qualifiers::Volatile);
5995 inline void QualType::removeLocalCVRQualifiers(unsigned Mask) {
5996 assert(!(Mask & ~Qualifiers::CVRMask) && "mask has non-CVR bits");
5997 static_assert((int)Qualifiers::CVRMask == (int)Qualifiers::FastMask,
5998 "Fast bits differ from CVR bits!");
6000 // Fast path: we don't need to touch the slow qualifiers.
6001 removeLocalFastQualifiers(Mask);
6004 /// Return the address space of this type.
6005 inline LangAS QualType::getAddressSpace() const {
6006 return getQualifiers().getAddressSpace();
6009 /// Return the gc attribute of this type.
6010 inline Qualifiers::GC QualType::getObjCGCAttr() const {
6011 return getQualifiers().getObjCGCAttr();
6014 inline FunctionType::ExtInfo getFunctionExtInfo(const Type &t) {
6015 if (const auto *PT = t.getAs<PointerType>()) {
6016 if (const auto *FT = PT->getPointeeType()->getAs<FunctionType>())
6017 return FT->getExtInfo();
6018 } else if (const auto *FT = t.getAs<FunctionType>())
6019 return FT->getExtInfo();
6021 return FunctionType::ExtInfo();
6024 inline FunctionType::ExtInfo getFunctionExtInfo(QualType t) {
6025 return getFunctionExtInfo(*t);
6028 /// Determine whether this type is more
6029 /// qualified than the Other type. For example, "const volatile int"
6030 /// is more qualified than "const int", "volatile int", and
6031 /// "int". However, it is not more qualified than "const volatile
6033 inline bool QualType::isMoreQualifiedThan(QualType other) const {
6034 Qualifiers MyQuals = getQualifiers();
6035 Qualifiers OtherQuals = other.getQualifiers();
6036 return (MyQuals != OtherQuals && MyQuals.compatiblyIncludes(OtherQuals));
6039 /// Determine whether this type is at last
6040 /// as qualified as the Other type. For example, "const volatile
6041 /// int" is at least as qualified as "const int", "volatile int",
6042 /// "int", and "const volatile int".
6043 inline bool QualType::isAtLeastAsQualifiedAs(QualType other) const {
6044 Qualifiers OtherQuals = other.getQualifiers();
6046 // Ignore __unaligned qualifier if this type is a void.
6047 if (getUnqualifiedType()->isVoidType())
6048 OtherQuals.removeUnaligned();
6050 return getQualifiers().compatiblyIncludes(OtherQuals);
6053 /// If Type is a reference type (e.g., const
6054 /// int&), returns the type that the reference refers to ("const
6055 /// int"). Otherwise, returns the type itself. This routine is used
6056 /// throughout Sema to implement C++ 5p6:
6058 /// If an expression initially has the type "reference to T" (8.3.2,
6059 /// 8.5.3), the type is adjusted to "T" prior to any further
6060 /// analysis, the expression designates the object or function
6061 /// denoted by the reference, and the expression is an lvalue.
6062 inline QualType QualType::getNonReferenceType() const {
6063 if (const auto *RefType = (*this)->getAs<ReferenceType>())
6064 return RefType->getPointeeType();
6069 inline bool QualType::isCForbiddenLValueType() const {
6070 return ((getTypePtr()->isVoidType() && !hasQualifiers()) ||
6071 getTypePtr()->isFunctionType());
6074 /// Tests whether the type is categorized as a fundamental type.
6076 /// \returns True for types specified in C++0x [basic.fundamental].
6077 inline bool Type::isFundamentalType() const {
6078 return isVoidType() ||
6079 // FIXME: It's really annoying that we don't have an
6080 // 'isArithmeticType()' which agrees with the standard definition.
6081 (isArithmeticType() && !isEnumeralType());
6084 /// Tests whether the type is categorized as a compound type.
6086 /// \returns True for types specified in C++0x [basic.compound].
6087 inline bool Type::isCompoundType() const {
6088 // C++0x [basic.compound]p1:
6089 // Compound types can be constructed in the following ways:
6090 // -- arrays of objects of a given type [...];
6091 return isArrayType() ||
6092 // -- functions, which have parameters of given types [...];
6094 // -- pointers to void or objects or functions [...];
6096 // -- references to objects or functions of a given type. [...]
6097 isReferenceType() ||
6098 // -- classes containing a sequence of objects of various types, [...];
6100 // -- unions, which are classes capable of containing objects of different
6101 // types at different times;
6103 // -- enumerations, which comprise a set of named constant values. [...];
6105 // -- pointers to non-static class members, [...].
6106 isMemberPointerType();
6109 inline bool Type::isFunctionType() const {
6110 return isa<FunctionType>(CanonicalType);
6113 inline bool Type::isPointerType() const {
6114 return isa<PointerType>(CanonicalType);
6117 inline bool Type::isAnyPointerType() const {
6118 return isPointerType() || isObjCObjectPointerType();
6121 inline bool Type::isBlockPointerType() const {
6122 return isa<BlockPointerType>(CanonicalType);
6125 inline bool Type::isReferenceType() const {
6126 return isa<ReferenceType>(CanonicalType);
6129 inline bool Type::isLValueReferenceType() const {
6130 return isa<LValueReferenceType>(CanonicalType);
6133 inline bool Type::isRValueReferenceType() const {
6134 return isa<RValueReferenceType>(CanonicalType);
6137 inline bool Type::isFunctionPointerType() const {
6138 if (const auto *T = getAs<PointerType>())
6139 return T->getPointeeType()->isFunctionType();
6144 inline bool Type::isMemberPointerType() const {
6145 return isa<MemberPointerType>(CanonicalType);
6148 inline bool Type::isMemberFunctionPointerType() const {
6149 if (const auto *T = getAs<MemberPointerType>())
6150 return T->isMemberFunctionPointer();
6155 inline bool Type::isMemberDataPointerType() const {
6156 if (const auto *T = getAs<MemberPointerType>())
6157 return T->isMemberDataPointer();
6162 inline bool Type::isArrayType() const {
6163 return isa<ArrayType>(CanonicalType);
6166 inline bool Type::isConstantArrayType() const {
6167 return isa<ConstantArrayType>(CanonicalType);
6170 inline bool Type::isIncompleteArrayType() const {
6171 return isa<IncompleteArrayType>(CanonicalType);
6174 inline bool Type::isVariableArrayType() const {
6175 return isa<VariableArrayType>(CanonicalType);
6178 inline bool Type::isDependentSizedArrayType() const {
6179 return isa<DependentSizedArrayType>(CanonicalType);
6182 inline bool Type::isBuiltinType() const {
6183 return isa<BuiltinType>(CanonicalType);
6186 inline bool Type::isRecordType() const {
6187 return isa<RecordType>(CanonicalType);
6190 inline bool Type::isEnumeralType() const {
6191 return isa<EnumType>(CanonicalType);
6194 inline bool Type::isAnyComplexType() const {
6195 return isa<ComplexType>(CanonicalType);
6198 inline bool Type::isVectorType() const {
6199 return isa<VectorType>(CanonicalType);
6202 inline bool Type::isExtVectorType() const {
6203 return isa<ExtVectorType>(CanonicalType);
6206 inline bool Type::isDependentAddressSpaceType() const {
6207 return isa<DependentAddressSpaceType>(CanonicalType);
6210 inline bool Type::isObjCObjectPointerType() const {
6211 return isa<ObjCObjectPointerType>(CanonicalType);
6214 inline bool Type::isObjCObjectType() const {
6215 return isa<ObjCObjectType>(CanonicalType);
6218 inline bool Type::isObjCObjectOrInterfaceType() const {
6219 return isa<ObjCInterfaceType>(CanonicalType) ||
6220 isa<ObjCObjectType>(CanonicalType);
6223 inline bool Type::isAtomicType() const {
6224 return isa<AtomicType>(CanonicalType);
6227 inline bool Type::isObjCQualifiedIdType() const {
6228 if (const auto *OPT = getAs<ObjCObjectPointerType>())
6229 return OPT->isObjCQualifiedIdType();
6233 inline bool Type::isObjCQualifiedClassType() const {
6234 if (const auto *OPT = getAs<ObjCObjectPointerType>())
6235 return OPT->isObjCQualifiedClassType();
6239 inline bool Type::isObjCIdType() const {
6240 if (const auto *OPT = getAs<ObjCObjectPointerType>())
6241 return OPT->isObjCIdType();
6245 inline bool Type::isObjCClassType() const {
6246 if (const auto *OPT = getAs<ObjCObjectPointerType>())
6247 return OPT->isObjCClassType();
6251 inline bool Type::isObjCSelType() const {
6252 if (const auto *OPT = getAs<PointerType>())
6253 return OPT->getPointeeType()->isSpecificBuiltinType(BuiltinType::ObjCSel);
6257 inline bool Type::isObjCBuiltinType() const {
6258 return isObjCIdType() || isObjCClassType() || isObjCSelType();
6261 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
6262 inline bool Type::is##Id##Type() const { \
6263 return isSpecificBuiltinType(BuiltinType::Id); \
6265 #include "clang/Basic/OpenCLImageTypes.def"
6267 inline bool Type::isSamplerT() const {
6268 return isSpecificBuiltinType(BuiltinType::OCLSampler);
6271 inline bool Type::isEventT() const {
6272 return isSpecificBuiltinType(BuiltinType::OCLEvent);
6275 inline bool Type::isClkEventT() const {
6276 return isSpecificBuiltinType(BuiltinType::OCLClkEvent);
6279 inline bool Type::isQueueT() const {
6280 return isSpecificBuiltinType(BuiltinType::OCLQueue);
6283 inline bool Type::isReserveIDT() const {
6284 return isSpecificBuiltinType(BuiltinType::OCLReserveID);
6287 inline bool Type::isImageType() const {
6288 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) is##Id##Type() ||
6290 #include "clang/Basic/OpenCLImageTypes.def"
6291 false; // end boolean or operation
6294 inline bool Type::isPipeType() const {
6295 return isa<PipeType>(CanonicalType);
6298 inline bool Type::isOpenCLSpecificType() const {
6299 return isSamplerT() || isEventT() || isImageType() || isClkEventT() ||
6300 isQueueT() || isReserveIDT() || isPipeType();
6303 inline bool Type::isTemplateTypeParmType() const {
6304 return isa<TemplateTypeParmType>(CanonicalType);
6307 inline bool Type::isSpecificBuiltinType(unsigned K) const {
6308 if (const BuiltinType *BT = getAs<BuiltinType>())
6309 if (BT->getKind() == (BuiltinType::Kind) K)
6314 inline bool Type::isPlaceholderType() const {
6315 if (const auto *BT = dyn_cast<BuiltinType>(this))
6316 return BT->isPlaceholderType();
6320 inline const BuiltinType *Type::getAsPlaceholderType() const {
6321 if (const auto *BT = dyn_cast<BuiltinType>(this))
6322 if (BT->isPlaceholderType())
6327 inline bool Type::isSpecificPlaceholderType(unsigned K) const {
6328 assert(BuiltinType::isPlaceholderTypeKind((BuiltinType::Kind) K));
6329 if (const auto *BT = dyn_cast<BuiltinType>(this))
6330 return (BT->getKind() == (BuiltinType::Kind) K);
6334 inline bool Type::isNonOverloadPlaceholderType() const {
6335 if (const auto *BT = dyn_cast<BuiltinType>(this))
6336 return BT->isNonOverloadPlaceholderType();
6340 inline bool Type::isVoidType() const {
6341 if (const auto *BT = dyn_cast<BuiltinType>(CanonicalType))
6342 return BT->getKind() == BuiltinType::Void;
6346 inline bool Type::isHalfType() const {
6347 if (const auto *BT = dyn_cast<BuiltinType>(CanonicalType))
6348 return BT->getKind() == BuiltinType::Half;
6349 // FIXME: Should we allow complex __fp16? Probably not.
6353 inline bool Type::isFloat16Type() const {
6354 if (const auto *BT = dyn_cast<BuiltinType>(CanonicalType))
6355 return BT->getKind() == BuiltinType::Float16;
6359 inline bool Type::isFloat128Type() const {
6360 if (const auto *BT = dyn_cast<BuiltinType>(CanonicalType))
6361 return BT->getKind() == BuiltinType::Float128;
6365 inline bool Type::isNullPtrType() const {
6366 if (const auto *BT = getAs<BuiltinType>())
6367 return BT->getKind() == BuiltinType::NullPtr;
6371 bool IsEnumDeclComplete(EnumDecl *);
6372 bool IsEnumDeclScoped(EnumDecl *);
6374 inline bool Type::isIntegerType() const {
6375 if (const auto *BT = dyn_cast<BuiltinType>(CanonicalType))
6376 return BT->getKind() >= BuiltinType::Bool &&
6377 BT->getKind() <= BuiltinType::Int128;
6378 if (const EnumType *ET = dyn_cast<EnumType>(CanonicalType)) {
6379 // Incomplete enum types are not treated as integer types.
6380 // FIXME: In C++, enum types are never integer types.
6381 return IsEnumDeclComplete(ET->getDecl()) &&
6382 !IsEnumDeclScoped(ET->getDecl());
6387 inline bool Type::isFixedPointType() const {
6388 if (const auto *BT = dyn_cast<BuiltinType>(CanonicalType)) {
6389 return BT->getKind() >= BuiltinType::ShortAccum &&
6390 BT->getKind() <= BuiltinType::SatULongFract;
6395 inline bool Type::isSaturatedFixedPointType() const {
6396 if (const auto *BT = dyn_cast<BuiltinType>(CanonicalType)) {
6397 return BT->getKind() >= BuiltinType::SatShortAccum &&
6398 BT->getKind() <= BuiltinType::SatULongFract;
6403 inline bool Type::isUnsaturatedFixedPointType() const {
6404 return isFixedPointType() && !isSaturatedFixedPointType();
6407 inline bool Type::isSignedFixedPointType() const {
6408 if (const auto *BT = dyn_cast<BuiltinType>(CanonicalType)) {
6409 return ((BT->getKind() >= BuiltinType::ShortAccum &&
6410 BT->getKind() <= BuiltinType::LongAccum) ||
6411 (BT->getKind() >= BuiltinType::ShortFract &&
6412 BT->getKind() <= BuiltinType::LongFract) ||
6413 (BT->getKind() >= BuiltinType::SatShortAccum &&
6414 BT->getKind() <= BuiltinType::SatLongAccum) ||
6415 (BT->getKind() >= BuiltinType::SatShortFract &&
6416 BT->getKind() <= BuiltinType::SatLongFract));
6421 inline bool Type::isUnsignedFixedPointType() const {
6422 return isFixedPointType() && !isSignedFixedPointType();
6425 inline bool Type::isScalarType() const {
6426 if (const auto *BT = dyn_cast<BuiltinType>(CanonicalType))
6427 return BT->getKind() > BuiltinType::Void &&
6428 BT->getKind() <= BuiltinType::NullPtr;
6429 if (const EnumType *ET = dyn_cast<EnumType>(CanonicalType))
6430 // Enums are scalar types, but only if they are defined. Incomplete enums
6431 // are not treated as scalar types.
6432 return IsEnumDeclComplete(ET->getDecl());
6433 return isa<PointerType>(CanonicalType) ||
6434 isa<BlockPointerType>(CanonicalType) ||
6435 isa<MemberPointerType>(CanonicalType) ||
6436 isa<ComplexType>(CanonicalType) ||
6437 isa<ObjCObjectPointerType>(CanonicalType);
6440 inline bool Type::isIntegralOrEnumerationType() const {
6441 if (const auto *BT = dyn_cast<BuiltinType>(CanonicalType))
6442 return BT->getKind() >= BuiltinType::Bool &&
6443 BT->getKind() <= BuiltinType::Int128;
6445 // Check for a complete enum type; incomplete enum types are not properly an
6446 // enumeration type in the sense required here.
6447 if (const auto *ET = dyn_cast<EnumType>(CanonicalType))
6448 return IsEnumDeclComplete(ET->getDecl());
6453 inline bool Type::isBooleanType() const {
6454 if (const auto *BT = dyn_cast<BuiltinType>(CanonicalType))
6455 return BT->getKind() == BuiltinType::Bool;
6459 inline bool Type::isUndeducedType() const {
6460 auto *DT = getContainedDeducedType();
6461 return DT && !DT->isDeduced();
6464 /// Determines whether this is a type for which one can define
6465 /// an overloaded operator.
6466 inline bool Type::isOverloadableType() const {
6467 return isDependentType() || isRecordType() || isEnumeralType();
6470 /// Determines whether this type can decay to a pointer type.
6471 inline bool Type::canDecayToPointerType() const {
6472 return isFunctionType() || isArrayType();
6475 inline bool Type::hasPointerRepresentation() const {
6476 return (isPointerType() || isReferenceType() || isBlockPointerType() ||
6477 isObjCObjectPointerType() || isNullPtrType());
6480 inline bool Type::hasObjCPointerRepresentation() const {
6481 return isObjCObjectPointerType();
6484 inline const Type *Type::getBaseElementTypeUnsafe() const {
6485 const Type *type = this;
6486 while (const ArrayType *arrayType = type->getAsArrayTypeUnsafe())
6487 type = arrayType->getElementType().getTypePtr();
6491 inline const Type *Type::getPointeeOrArrayElementType() const {
6492 const Type *type = this;
6493 if (type->isAnyPointerType())
6494 return type->getPointeeType().getTypePtr();
6495 else if (type->isArrayType())
6496 return type->getBaseElementTypeUnsafe();
6500 /// Insertion operator for diagnostics. This allows sending QualType's into a
6501 /// diagnostic with <<.
6502 inline const DiagnosticBuilder &operator<<(const DiagnosticBuilder &DB,
6504 DB.AddTaggedVal(reinterpret_cast<intptr_t>(T.getAsOpaquePtr()),
6505 DiagnosticsEngine::ak_qualtype);
6509 /// Insertion operator for partial diagnostics. This allows sending QualType's
6510 /// into a diagnostic with <<.
6511 inline const PartialDiagnostic &operator<<(const PartialDiagnostic &PD,
6513 PD.AddTaggedVal(reinterpret_cast<intptr_t>(T.getAsOpaquePtr()),
6514 DiagnosticsEngine::ak_qualtype);
6518 // Helper class template that is used by Type::getAs to ensure that one does
6519 // not try to look through a qualified type to get to an array type.
6520 template <typename T>
6521 using TypeIsArrayType =
6522 std::integral_constant<bool, std::is_same<T, ArrayType>::value ||
6523 std::is_base_of<ArrayType, T>::value>;
6525 // Member-template getAs<specific type>'.
6526 template <typename T> const T *Type::getAs() const {
6527 static_assert(!TypeIsArrayType<T>::value,
6528 "ArrayType cannot be used with getAs!");
6530 // If this is directly a T type, return it.
6531 if (const auto *Ty = dyn_cast<T>(this))
6534 // If the canonical form of this type isn't the right kind, reject it.
6535 if (!isa<T>(CanonicalType))
6538 // If this is a typedef for the type, strip the typedef off without
6539 // losing all typedef information.
6540 return cast<T>(getUnqualifiedDesugaredType());
6543 template <typename T> const T *Type::getAsAdjusted() const {
6544 static_assert(!TypeIsArrayType<T>::value, "ArrayType cannot be used with getAsAdjusted!");
6546 // If this is directly a T type, return it.
6547 if (const auto *Ty = dyn_cast<T>(this))
6550 // If the canonical form of this type isn't the right kind, reject it.
6551 if (!isa<T>(CanonicalType))
6554 // Strip off type adjustments that do not modify the underlying nature of the
6556 const Type *Ty = this;
6558 if (const auto *A = dyn_cast<AttributedType>(Ty))
6559 Ty = A->getModifiedType().getTypePtr();
6560 else if (const auto *E = dyn_cast<ElaboratedType>(Ty))
6561 Ty = E->desugar().getTypePtr();
6562 else if (const auto *P = dyn_cast<ParenType>(Ty))
6563 Ty = P->desugar().getTypePtr();
6564 else if (const auto *A = dyn_cast<AdjustedType>(Ty))
6565 Ty = A->desugar().getTypePtr();
6570 // Just because the canonical type is correct does not mean we can use cast<>,
6571 // since we may not have stripped off all the sugar down to the base type.
6572 return dyn_cast<T>(Ty);
6575 inline const ArrayType *Type::getAsArrayTypeUnsafe() const {
6576 // If this is directly an array type, return it.
6577 if (const auto *arr = dyn_cast<ArrayType>(this))
6580 // If the canonical form of this type isn't the right kind, reject it.
6581 if (!isa<ArrayType>(CanonicalType))
6584 // If this is a typedef for the type, strip the typedef off without
6585 // losing all typedef information.
6586 return cast<ArrayType>(getUnqualifiedDesugaredType());
6589 template <typename T> const T *Type::castAs() const {
6590 static_assert(!TypeIsArrayType<T>::value,
6591 "ArrayType cannot be used with castAs!");
6593 if (const auto *ty = dyn_cast<T>(this)) return ty;
6594 assert(isa<T>(CanonicalType));
6595 return cast<T>(getUnqualifiedDesugaredType());
6598 inline const ArrayType *Type::castAsArrayTypeUnsafe() const {
6599 assert(isa<ArrayType>(CanonicalType));
6600 if (const auto *arr = dyn_cast<ArrayType>(this)) return arr;
6601 return cast<ArrayType>(getUnqualifiedDesugaredType());
6604 DecayedType::DecayedType(QualType OriginalType, QualType DecayedPtr,
6605 QualType CanonicalPtr)
6606 : AdjustedType(Decayed, OriginalType, DecayedPtr, CanonicalPtr) {
6608 QualType Adjusted = getAdjustedType();
6609 (void)AttributedType::stripOuterNullability(Adjusted);
6610 assert(isa<PointerType>(Adjusted));
6614 QualType DecayedType::getPointeeType() const {
6615 QualType Decayed = getDecayedType();
6616 (void)AttributedType::stripOuterNullability(Decayed);
6617 return cast<PointerType>(Decayed)->getPointeeType();
6620 // Get the decimal string representation of a fixed point type, represented
6621 // as a scaled integer.
6622 void FixedPointValueToString(SmallVectorImpl<char> &Str,
6623 const llvm::APSInt &Val,
6624 unsigned Scale, unsigned Radix);
6626 } // namespace clang
6628 #endif // LLVM_CLANG_AST_TYPE_H