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 TagDecl that this type refers to, either
2021 /// because the type is a TagType or because it is the injected-class-name
2022 /// type of a class template or class template partial specialization.
2023 TagDecl *getAsTagDecl() const;
2025 /// If this is a pointer or reference to a RecordType, return the
2026 /// CXXRecordDecl that the type refers to.
2028 /// If this is not a pointer or reference, or the type being pointed to does
2029 /// not refer to a CXXRecordDecl, returns NULL.
2030 const CXXRecordDecl *getPointeeCXXRecordDecl() const;
2032 /// Get the DeducedType whose type will be deduced for a variable with
2033 /// an initializer of this type. This looks through declarators like pointer
2034 /// types, but not through decltype or typedefs.
2035 DeducedType *getContainedDeducedType() const;
2037 /// Get the AutoType whose type will be deduced for a variable with
2038 /// an initializer of this type. This looks through declarators like pointer
2039 /// types, but not through decltype or typedefs.
2040 AutoType *getContainedAutoType() const {
2041 return dyn_cast_or_null<AutoType>(getContainedDeducedType());
2044 /// Determine whether this type was written with a leading 'auto'
2045 /// corresponding to a trailing return type (possibly for a nested
2046 /// function type within a pointer to function type or similar).
2047 bool hasAutoForTrailingReturnType() const;
2049 /// Member-template getAs<specific type>'. Look through sugar for
2050 /// an instance of \<specific type>. This scheme will eventually
2051 /// replace the specific getAsXXXX methods above.
2053 /// There are some specializations of this member template listed
2054 /// immediately following this class.
2055 template <typename T> const T *getAs() const;
2057 /// Member-template getAsAdjusted<specific type>. Look through specific kinds
2058 /// of sugar (parens, attributes, etc) for an instance of \<specific type>.
2059 /// This is used when you need to walk over sugar nodes that represent some
2060 /// kind of type adjustment from a type that was written as a \<specific type>
2061 /// to another type that is still canonically a \<specific type>.
2062 template <typename T> const T *getAsAdjusted() const;
2064 /// A variant of getAs<> for array types which silently discards
2065 /// qualifiers from the outermost type.
2066 const ArrayType *getAsArrayTypeUnsafe() const;
2068 /// Member-template castAs<specific type>. Look through sugar for
2069 /// the underlying instance of \<specific type>.
2071 /// This method has the same relationship to getAs<T> as cast<T> has
2072 /// to dyn_cast<T>; which is to say, the underlying type *must*
2073 /// have the intended type, and this method will never return null.
2074 template <typename T> const T *castAs() const;
2076 /// A variant of castAs<> for array type which silently discards
2077 /// qualifiers from the outermost type.
2078 const ArrayType *castAsArrayTypeUnsafe() const;
2080 /// Get the base element type of this type, potentially discarding type
2081 /// qualifiers. This should never be used when type qualifiers
2083 const Type *getBaseElementTypeUnsafe() const;
2085 /// If this is an array type, return the element type of the array,
2086 /// potentially with type qualifiers missing.
2087 /// This should never be used when type qualifiers are meaningful.
2088 const Type *getArrayElementTypeNoTypeQual() const;
2090 /// If this is a pointer type, return the pointee type.
2091 /// If this is an array type, return the array element type.
2092 /// This should never be used when type qualifiers are meaningful.
2093 const Type *getPointeeOrArrayElementType() const;
2095 /// If this is a pointer, ObjC object pointer, or block
2096 /// pointer, this returns the respective pointee.
2097 QualType getPointeeType() const;
2099 /// Return the specified type with any "sugar" removed from the type,
2100 /// removing any typedefs, typeofs, etc., as well as any qualifiers.
2101 const Type *getUnqualifiedDesugaredType() const;
2103 /// More type predicates useful for type checking/promotion
2104 bool isPromotableIntegerType() const; // C99 6.3.1.1p2
2106 /// Return true if this is an integer type that is
2107 /// signed, according to C99 6.2.5p4 [char, signed char, short, int, long..],
2108 /// or an enum decl which has a signed representation.
2109 bool isSignedIntegerType() const;
2111 /// Return true if this is an integer type that is
2112 /// unsigned, according to C99 6.2.5p6 [which returns true for _Bool],
2113 /// or an enum decl which has an unsigned representation.
2114 bool isUnsignedIntegerType() const;
2116 /// Determines whether this is an integer type that is signed or an
2117 /// enumeration types whose underlying type is a signed integer type.
2118 bool isSignedIntegerOrEnumerationType() const;
2120 /// Determines whether this is an integer type that is unsigned or an
2121 /// enumeration types whose underlying type is a unsigned integer type.
2122 bool isUnsignedIntegerOrEnumerationType() const;
2124 /// Return true if this is a fixed point type according to
2125 /// ISO/IEC JTC1 SC22 WG14 N1169.
2126 bool isFixedPointType() const;
2128 /// Return true if this is a saturated fixed point type according to
2129 /// ISO/IEC JTC1 SC22 WG14 N1169. This type can be signed or unsigned.
2130 bool isSaturatedFixedPointType() const;
2132 /// Return true if this is a saturated fixed point type according to
2133 /// ISO/IEC JTC1 SC22 WG14 N1169. This type can be signed or unsigned.
2134 bool isUnsaturatedFixedPointType() const;
2136 /// Return true if this is a fixed point type that is signed according
2137 /// to ISO/IEC JTC1 SC22 WG14 N1169. This type can also be saturated.
2138 bool isSignedFixedPointType() const;
2140 /// Return true if this is a fixed point type that is unsigned according
2141 /// to ISO/IEC JTC1 SC22 WG14 N1169. This type can also be saturated.
2142 bool isUnsignedFixedPointType() const;
2144 /// Return true if this is not a variable sized type,
2145 /// according to the rules of C99 6.7.5p3. It is not legal to call this on
2146 /// incomplete types.
2147 bool isConstantSizeType() const;
2149 /// Returns true if this type can be represented by some
2150 /// set of type specifiers.
2151 bool isSpecifierType() const;
2153 /// Determine the linkage of this type.
2154 Linkage getLinkage() const;
2156 /// Determine the visibility of this type.
2157 Visibility getVisibility() const {
2158 return getLinkageAndVisibility().getVisibility();
2161 /// Return true if the visibility was explicitly set is the code.
2162 bool isVisibilityExplicit() const {
2163 return getLinkageAndVisibility().isVisibilityExplicit();
2166 /// Determine the linkage and visibility of this type.
2167 LinkageInfo getLinkageAndVisibility() const;
2169 /// True if the computed linkage is valid. Used for consistency
2170 /// checking. Should always return true.
2171 bool isLinkageValid() const;
2173 /// Determine the nullability of the given type.
2175 /// Note that nullability is only captured as sugar within the type
2176 /// system, not as part of the canonical type, so nullability will
2177 /// be lost by canonicalization and desugaring.
2178 Optional<NullabilityKind> getNullability(const ASTContext &context) const;
2180 /// Determine whether the given type can have a nullability
2181 /// specifier applied to it, i.e., if it is any kind of pointer type.
2183 /// \param ResultIfUnknown The value to return if we don't yet know whether
2184 /// this type can have nullability because it is dependent.
2185 bool canHaveNullability(bool ResultIfUnknown = true) const;
2187 /// Retrieve the set of substitutions required when accessing a member
2188 /// of the Objective-C receiver type that is declared in the given context.
2190 /// \c *this is the type of the object we're operating on, e.g., the
2191 /// receiver for a message send or the base of a property access, and is
2192 /// expected to be of some object or object pointer type.
2194 /// \param dc The declaration context for which we are building up a
2195 /// substitution mapping, which should be an Objective-C class, extension,
2196 /// category, or method within.
2198 /// \returns an array of type arguments that can be substituted for
2199 /// the type parameters of the given declaration context in any type described
2200 /// within that context, or an empty optional to indicate that no
2201 /// substitution is required.
2202 Optional<ArrayRef<QualType>>
2203 getObjCSubstitutions(const DeclContext *dc) const;
2205 /// Determines if this is an ObjC interface type that may accept type
2207 bool acceptsObjCTypeParams() const;
2209 const char *getTypeClassName() const;
2211 QualType getCanonicalTypeInternal() const {
2212 return CanonicalType;
2215 CanQualType getCanonicalTypeUnqualified() const; // in CanonicalType.h
2217 void dump(llvm::raw_ostream &OS) const;
2220 /// This will check for a TypedefType by removing any existing sugar
2221 /// until it reaches a TypedefType or a non-sugared type.
2222 template <> const TypedefType *Type::getAs() const;
2224 /// This will check for a TemplateSpecializationType by removing any
2225 /// existing sugar until it reaches a TemplateSpecializationType or a
2226 /// non-sugared type.
2227 template <> const TemplateSpecializationType *Type::getAs() const;
2229 /// This will check for an AttributedType by removing any existing sugar
2230 /// until it reaches an AttributedType or a non-sugared type.
2231 template <> const AttributedType *Type::getAs() const;
2233 // We can do canonical leaf types faster, because we don't have to
2234 // worry about preserving child type decoration.
2235 #define TYPE(Class, Base)
2236 #define LEAF_TYPE(Class) \
2237 template <> inline const Class##Type *Type::getAs() const { \
2238 return dyn_cast<Class##Type>(CanonicalType); \
2240 template <> inline const Class##Type *Type::castAs() const { \
2241 return cast<Class##Type>(CanonicalType); \
2243 #include "clang/AST/TypeNodes.def"
2245 /// This class is used for builtin types like 'int'. Builtin
2246 /// types are always canonical and have a literal name field.
2247 class BuiltinType : public Type {
2250 // OpenCL image types
2251 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) Id,
2252 #include "clang/Basic/OpenCLImageTypes.def"
2253 // All other builtin types
2254 #define BUILTIN_TYPE(Id, SingletonId) Id,
2255 #define LAST_BUILTIN_TYPE(Id) LastKind = Id
2256 #include "clang/AST/BuiltinTypes.def"
2260 friend class ASTContext; // ASTContext creates these.
2263 : Type(Builtin, QualType(), /*Dependent=*/(K == Dependent),
2264 /*InstantiationDependent=*/(K == Dependent),
2265 /*VariablyModified=*/false,
2266 /*Unexpanded parameter pack=*/false) {
2267 BuiltinTypeBits.Kind = K;
2271 Kind getKind() const { return static_cast<Kind>(BuiltinTypeBits.Kind); }
2272 StringRef getName(const PrintingPolicy &Policy) const;
2274 const char *getNameAsCString(const PrintingPolicy &Policy) const {
2275 // The StringRef is null-terminated.
2276 StringRef str = getName(Policy);
2277 assert(!str.empty() && str.data()[str.size()] == '\0');
2281 bool isSugared() const { return false; }
2282 QualType desugar() const { return QualType(this, 0); }
2284 bool isInteger() const {
2285 return getKind() >= Bool && getKind() <= Int128;
2288 bool isSignedInteger() const {
2289 return getKind() >= Char_S && getKind() <= Int128;
2292 bool isUnsignedInteger() const {
2293 return getKind() >= Bool && getKind() <= UInt128;
2296 bool isFloatingPoint() const {
2297 return getKind() >= Half && getKind() <= Float128;
2300 /// Determines whether the given kind corresponds to a placeholder type.
2301 static bool isPlaceholderTypeKind(Kind K) {
2302 return K >= Overload;
2305 /// Determines whether this type is a placeholder type, i.e. a type
2306 /// which cannot appear in arbitrary positions in a fully-formed
2308 bool isPlaceholderType() const {
2309 return isPlaceholderTypeKind(getKind());
2312 /// Determines whether this type is a placeholder type other than
2313 /// Overload. Most placeholder types require only syntactic
2314 /// information about their context in order to be resolved (e.g.
2315 /// whether it is a call expression), which means they can (and
2316 /// should) be resolved in an earlier "phase" of analysis.
2317 /// Overload expressions sometimes pick up further information
2318 /// from their context, like whether the context expects a
2319 /// specific function-pointer type, and so frequently need
2320 /// special treatment.
2321 bool isNonOverloadPlaceholderType() const {
2322 return getKind() > Overload;
2325 static bool classof(const Type *T) { return T->getTypeClass() == Builtin; }
2328 /// Complex values, per C99 6.2.5p11. This supports the C99 complex
2329 /// types (_Complex float etc) as well as the GCC integer complex extensions.
2330 class ComplexType : public Type, public llvm::FoldingSetNode {
2331 friend class ASTContext; // ASTContext creates these.
2333 QualType ElementType;
2335 ComplexType(QualType Element, QualType CanonicalPtr)
2336 : Type(Complex, CanonicalPtr, Element->isDependentType(),
2337 Element->isInstantiationDependentType(),
2338 Element->isVariablyModifiedType(),
2339 Element->containsUnexpandedParameterPack()),
2340 ElementType(Element) {}
2343 QualType getElementType() const { return ElementType; }
2345 bool isSugared() const { return false; }
2346 QualType desugar() const { return QualType(this, 0); }
2348 void Profile(llvm::FoldingSetNodeID &ID) {
2349 Profile(ID, getElementType());
2352 static void Profile(llvm::FoldingSetNodeID &ID, QualType Element) {
2353 ID.AddPointer(Element.getAsOpaquePtr());
2356 static bool classof(const Type *T) { return T->getTypeClass() == Complex; }
2359 /// Sugar for parentheses used when specifying types.
2360 class ParenType : public Type, public llvm::FoldingSetNode {
2361 friend class ASTContext; // ASTContext creates these.
2365 ParenType(QualType InnerType, QualType CanonType)
2366 : Type(Paren, CanonType, InnerType->isDependentType(),
2367 InnerType->isInstantiationDependentType(),
2368 InnerType->isVariablyModifiedType(),
2369 InnerType->containsUnexpandedParameterPack()),
2373 QualType getInnerType() const { return Inner; }
2375 bool isSugared() const { return true; }
2376 QualType desugar() const { return getInnerType(); }
2378 void Profile(llvm::FoldingSetNodeID &ID) {
2379 Profile(ID, getInnerType());
2382 static void Profile(llvm::FoldingSetNodeID &ID, QualType Inner) {
2386 static bool classof(const Type *T) { return T->getTypeClass() == Paren; }
2389 /// PointerType - C99 6.7.5.1 - Pointer Declarators.
2390 class PointerType : public Type, public llvm::FoldingSetNode {
2391 friend class ASTContext; // ASTContext creates these.
2393 QualType PointeeType;
2395 PointerType(QualType Pointee, QualType CanonicalPtr)
2396 : Type(Pointer, CanonicalPtr, Pointee->isDependentType(),
2397 Pointee->isInstantiationDependentType(),
2398 Pointee->isVariablyModifiedType(),
2399 Pointee->containsUnexpandedParameterPack()),
2400 PointeeType(Pointee) {}
2403 QualType getPointeeType() const { return PointeeType; }
2405 /// Returns true if address spaces of pointers overlap.
2406 /// OpenCL v2.0 defines conversion rules for pointers to different
2407 /// address spaces (OpenCLC v2.0 s6.5.5) and notion of overlapping
2410 /// address spaces overlap iff they are they same.
2412 /// __generic overlaps with any address space except for __constant.
2413 bool isAddressSpaceOverlapping(const PointerType &other) const {
2414 Qualifiers thisQuals = PointeeType.getQualifiers();
2415 Qualifiers otherQuals = other.getPointeeType().getQualifiers();
2416 // Address spaces overlap if at least one of them is a superset of another
2417 return thisQuals.isAddressSpaceSupersetOf(otherQuals) ||
2418 otherQuals.isAddressSpaceSupersetOf(thisQuals);
2421 bool isSugared() const { return false; }
2422 QualType desugar() const { return QualType(this, 0); }
2424 void Profile(llvm::FoldingSetNodeID &ID) {
2425 Profile(ID, getPointeeType());
2428 static void Profile(llvm::FoldingSetNodeID &ID, QualType Pointee) {
2429 ID.AddPointer(Pointee.getAsOpaquePtr());
2432 static bool classof(const Type *T) { return T->getTypeClass() == Pointer; }
2435 /// Represents a type which was implicitly adjusted by the semantic
2436 /// engine for arbitrary reasons. For example, array and function types can
2437 /// decay, and function types can have their calling conventions adjusted.
2438 class AdjustedType : public Type, public llvm::FoldingSetNode {
2439 QualType OriginalTy;
2440 QualType AdjustedTy;
2443 friend class ASTContext; // ASTContext creates these.
2445 AdjustedType(TypeClass TC, QualType OriginalTy, QualType AdjustedTy,
2446 QualType CanonicalPtr)
2447 : Type(TC, CanonicalPtr, OriginalTy->isDependentType(),
2448 OriginalTy->isInstantiationDependentType(),
2449 OriginalTy->isVariablyModifiedType(),
2450 OriginalTy->containsUnexpandedParameterPack()),
2451 OriginalTy(OriginalTy), AdjustedTy(AdjustedTy) {}
2454 QualType getOriginalType() const { return OriginalTy; }
2455 QualType getAdjustedType() const { return AdjustedTy; }
2457 bool isSugared() const { return true; }
2458 QualType desugar() const { return AdjustedTy; }
2460 void Profile(llvm::FoldingSetNodeID &ID) {
2461 Profile(ID, OriginalTy, AdjustedTy);
2464 static void Profile(llvm::FoldingSetNodeID &ID, QualType Orig, QualType New) {
2465 ID.AddPointer(Orig.getAsOpaquePtr());
2466 ID.AddPointer(New.getAsOpaquePtr());
2469 static bool classof(const Type *T) {
2470 return T->getTypeClass() == Adjusted || T->getTypeClass() == Decayed;
2474 /// Represents a pointer type decayed from an array or function type.
2475 class DecayedType : public AdjustedType {
2476 friend class ASTContext; // ASTContext creates these.
2479 DecayedType(QualType OriginalType, QualType Decayed, QualType Canonical);
2482 QualType getDecayedType() const { return getAdjustedType(); }
2484 inline QualType getPointeeType() const;
2486 static bool classof(const Type *T) { return T->getTypeClass() == Decayed; }
2489 /// Pointer to a block type.
2490 /// This type is to represent types syntactically represented as
2491 /// "void (^)(int)", etc. Pointee is required to always be a function type.
2492 class BlockPointerType : public Type, public llvm::FoldingSetNode {
2493 friend class ASTContext; // ASTContext creates these.
2495 // Block is some kind of pointer type
2496 QualType PointeeType;
2498 BlockPointerType(QualType Pointee, QualType CanonicalCls)
2499 : Type(BlockPointer, CanonicalCls, Pointee->isDependentType(),
2500 Pointee->isInstantiationDependentType(),
2501 Pointee->isVariablyModifiedType(),
2502 Pointee->containsUnexpandedParameterPack()),
2503 PointeeType(Pointee) {}
2506 // Get the pointee type. Pointee is required to always be a function type.
2507 QualType getPointeeType() const { return PointeeType; }
2509 bool isSugared() const { return false; }
2510 QualType desugar() const { return QualType(this, 0); }
2512 void Profile(llvm::FoldingSetNodeID &ID) {
2513 Profile(ID, getPointeeType());
2516 static void Profile(llvm::FoldingSetNodeID &ID, QualType Pointee) {
2517 ID.AddPointer(Pointee.getAsOpaquePtr());
2520 static bool classof(const Type *T) {
2521 return T->getTypeClass() == BlockPointer;
2525 /// Base for LValueReferenceType and RValueReferenceType
2526 class ReferenceType : public Type, public llvm::FoldingSetNode {
2527 QualType PointeeType;
2530 ReferenceType(TypeClass tc, QualType Referencee, QualType CanonicalRef,
2531 bool SpelledAsLValue)
2532 : Type(tc, CanonicalRef, Referencee->isDependentType(),
2533 Referencee->isInstantiationDependentType(),
2534 Referencee->isVariablyModifiedType(),
2535 Referencee->containsUnexpandedParameterPack()),
2536 PointeeType(Referencee) {
2537 ReferenceTypeBits.SpelledAsLValue = SpelledAsLValue;
2538 ReferenceTypeBits.InnerRef = Referencee->isReferenceType();
2542 bool isSpelledAsLValue() const { return ReferenceTypeBits.SpelledAsLValue; }
2543 bool isInnerRef() const { return ReferenceTypeBits.InnerRef; }
2545 QualType getPointeeTypeAsWritten() const { return PointeeType; }
2547 QualType getPointeeType() const {
2548 // FIXME: this might strip inner qualifiers; okay?
2549 const ReferenceType *T = this;
2550 while (T->isInnerRef())
2551 T = T->PointeeType->castAs<ReferenceType>();
2552 return T->PointeeType;
2555 void Profile(llvm::FoldingSetNodeID &ID) {
2556 Profile(ID, PointeeType, isSpelledAsLValue());
2559 static void Profile(llvm::FoldingSetNodeID &ID,
2560 QualType Referencee,
2561 bool SpelledAsLValue) {
2562 ID.AddPointer(Referencee.getAsOpaquePtr());
2563 ID.AddBoolean(SpelledAsLValue);
2566 static bool classof(const Type *T) {
2567 return T->getTypeClass() == LValueReference ||
2568 T->getTypeClass() == RValueReference;
2572 /// An lvalue reference type, per C++11 [dcl.ref].
2573 class LValueReferenceType : public ReferenceType {
2574 friend class ASTContext; // ASTContext creates these
2576 LValueReferenceType(QualType Referencee, QualType CanonicalRef,
2577 bool SpelledAsLValue)
2578 : ReferenceType(LValueReference, Referencee, CanonicalRef,
2582 bool isSugared() const { return false; }
2583 QualType desugar() const { return QualType(this, 0); }
2585 static bool classof(const Type *T) {
2586 return T->getTypeClass() == LValueReference;
2590 /// An rvalue reference type, per C++11 [dcl.ref].
2591 class RValueReferenceType : public ReferenceType {
2592 friend class ASTContext; // ASTContext creates these
2594 RValueReferenceType(QualType Referencee, QualType CanonicalRef)
2595 : ReferenceType(RValueReference, Referencee, CanonicalRef, false) {}
2598 bool isSugared() const { return false; }
2599 QualType desugar() const { return QualType(this, 0); }
2601 static bool classof(const Type *T) {
2602 return T->getTypeClass() == RValueReference;
2606 /// A pointer to member type per C++ 8.3.3 - Pointers to members.
2608 /// This includes both pointers to data members and pointer to member functions.
2609 class MemberPointerType : public Type, public llvm::FoldingSetNode {
2610 friend class ASTContext; // ASTContext creates these.
2612 QualType PointeeType;
2614 /// The class of which the pointee is a member. Must ultimately be a
2615 /// RecordType, but could be a typedef or a template parameter too.
2618 MemberPointerType(QualType Pointee, const Type *Cls, QualType CanonicalPtr)
2619 : Type(MemberPointer, CanonicalPtr,
2620 Cls->isDependentType() || Pointee->isDependentType(),
2621 (Cls->isInstantiationDependentType() ||
2622 Pointee->isInstantiationDependentType()),
2623 Pointee->isVariablyModifiedType(),
2624 (Cls->containsUnexpandedParameterPack() ||
2625 Pointee->containsUnexpandedParameterPack())),
2626 PointeeType(Pointee), Class(Cls) {}
2629 QualType getPointeeType() const { return PointeeType; }
2631 /// Returns true if the member type (i.e. the pointee type) is a
2632 /// function type rather than a data-member type.
2633 bool isMemberFunctionPointer() const {
2634 return PointeeType->isFunctionProtoType();
2637 /// Returns true if the member type (i.e. the pointee type) is a
2638 /// data type rather than a function type.
2639 bool isMemberDataPointer() const {
2640 return !PointeeType->isFunctionProtoType();
2643 const Type *getClass() const { return Class; }
2644 CXXRecordDecl *getMostRecentCXXRecordDecl() const;
2646 bool isSugared() const { return false; }
2647 QualType desugar() const { return QualType(this, 0); }
2649 void Profile(llvm::FoldingSetNodeID &ID) {
2650 Profile(ID, getPointeeType(), getClass());
2653 static void Profile(llvm::FoldingSetNodeID &ID, QualType Pointee,
2654 const Type *Class) {
2655 ID.AddPointer(Pointee.getAsOpaquePtr());
2656 ID.AddPointer(Class);
2659 static bool classof(const Type *T) {
2660 return T->getTypeClass() == MemberPointer;
2664 /// Represents an array type, per C99 6.7.5.2 - Array Declarators.
2665 class ArrayType : public Type, public llvm::FoldingSetNode {
2667 /// Capture whether this is a normal array (e.g. int X[4])
2668 /// an array with a static size (e.g. int X[static 4]), or an array
2669 /// with a star size (e.g. int X[*]).
2670 /// 'static' is only allowed on function parameters.
2671 enum ArraySizeModifier {
2672 Normal, Static, Star
2676 /// The element type of the array.
2677 QualType ElementType;
2680 friend class ASTContext; // ASTContext creates these.
2682 // C++ [temp.dep.type]p1:
2683 // A type is dependent if it is...
2684 // - an array type constructed from any dependent type or whose
2685 // size is specified by a constant expression that is
2687 ArrayType(TypeClass tc, QualType et, QualType can,
2688 ArraySizeModifier sm, unsigned tq,
2689 bool ContainsUnexpandedParameterPack)
2690 : Type(tc, can, et->isDependentType() || tc == DependentSizedArray,
2691 et->isInstantiationDependentType() || tc == DependentSizedArray,
2692 (tc == VariableArray || et->isVariablyModifiedType()),
2693 ContainsUnexpandedParameterPack),
2695 ArrayTypeBits.IndexTypeQuals = tq;
2696 ArrayTypeBits.SizeModifier = sm;
2700 QualType getElementType() const { return ElementType; }
2702 ArraySizeModifier getSizeModifier() const {
2703 return ArraySizeModifier(ArrayTypeBits.SizeModifier);
2706 Qualifiers getIndexTypeQualifiers() const {
2707 return Qualifiers::fromCVRMask(getIndexTypeCVRQualifiers());
2710 unsigned getIndexTypeCVRQualifiers() const {
2711 return ArrayTypeBits.IndexTypeQuals;
2714 static bool classof(const Type *T) {
2715 return T->getTypeClass() == ConstantArray ||
2716 T->getTypeClass() == VariableArray ||
2717 T->getTypeClass() == IncompleteArray ||
2718 T->getTypeClass() == DependentSizedArray;
2722 /// Represents the canonical version of C arrays with a specified constant size.
2723 /// For example, the canonical type for 'int A[4 + 4*100]' is a
2724 /// ConstantArrayType where the element type is 'int' and the size is 404.
2725 class ConstantArrayType : public ArrayType {
2726 llvm::APInt Size; // Allows us to unique the type.
2728 ConstantArrayType(QualType et, QualType can, const llvm::APInt &size,
2729 ArraySizeModifier sm, unsigned tq)
2730 : ArrayType(ConstantArray, et, can, sm, tq,
2731 et->containsUnexpandedParameterPack()),
2735 friend class ASTContext; // ASTContext creates these.
2737 ConstantArrayType(TypeClass tc, QualType et, QualType can,
2738 const llvm::APInt &size, ArraySizeModifier sm, unsigned tq)
2739 : ArrayType(tc, et, can, sm, tq, et->containsUnexpandedParameterPack()),
2743 const llvm::APInt &getSize() const { return Size; }
2744 bool isSugared() const { return false; }
2745 QualType desugar() const { return QualType(this, 0); }
2747 /// Determine the number of bits required to address a member of
2748 // an array with the given element type and number of elements.
2749 static unsigned getNumAddressingBits(const ASTContext &Context,
2750 QualType ElementType,
2751 const llvm::APInt &NumElements);
2753 /// Determine the maximum number of active bits that an array's size
2754 /// can require, which limits the maximum size of the array.
2755 static unsigned getMaxSizeBits(const ASTContext &Context);
2757 void Profile(llvm::FoldingSetNodeID &ID) {
2758 Profile(ID, getElementType(), getSize(),
2759 getSizeModifier(), getIndexTypeCVRQualifiers());
2762 static void Profile(llvm::FoldingSetNodeID &ID, QualType ET,
2763 const llvm::APInt &ArraySize, ArraySizeModifier SizeMod,
2764 unsigned TypeQuals) {
2765 ID.AddPointer(ET.getAsOpaquePtr());
2766 ID.AddInteger(ArraySize.getZExtValue());
2767 ID.AddInteger(SizeMod);
2768 ID.AddInteger(TypeQuals);
2771 static bool classof(const Type *T) {
2772 return T->getTypeClass() == ConstantArray;
2776 /// Represents a C array with an unspecified size. For example 'int A[]' has
2777 /// an IncompleteArrayType where the element type is 'int' and the size is
2779 class IncompleteArrayType : public ArrayType {
2780 friend class ASTContext; // ASTContext creates these.
2782 IncompleteArrayType(QualType et, QualType can,
2783 ArraySizeModifier sm, unsigned tq)
2784 : ArrayType(IncompleteArray, et, can, sm, tq,
2785 et->containsUnexpandedParameterPack()) {}
2788 friend class StmtIteratorBase;
2790 bool isSugared() const { return false; }
2791 QualType desugar() const { return QualType(this, 0); }
2793 static bool classof(const Type *T) {
2794 return T->getTypeClass() == IncompleteArray;
2797 void Profile(llvm::FoldingSetNodeID &ID) {
2798 Profile(ID, getElementType(), getSizeModifier(),
2799 getIndexTypeCVRQualifiers());
2802 static void Profile(llvm::FoldingSetNodeID &ID, QualType ET,
2803 ArraySizeModifier SizeMod, unsigned TypeQuals) {
2804 ID.AddPointer(ET.getAsOpaquePtr());
2805 ID.AddInteger(SizeMod);
2806 ID.AddInteger(TypeQuals);
2810 /// Represents a C array with a specified size that is not an
2811 /// integer-constant-expression. For example, 'int s[x+foo()]'.
2812 /// Since the size expression is an arbitrary expression, we store it as such.
2814 /// Note: VariableArrayType's aren't uniqued (since the expressions aren't) and
2815 /// should not be: two lexically equivalent variable array types could mean
2816 /// different things, for example, these variables do not have the same type
2819 /// void foo(int x) {
2824 class VariableArrayType : public ArrayType {
2825 friend class ASTContext; // ASTContext creates these.
2827 /// An assignment-expression. VLA's are only permitted within
2828 /// a function block.
2831 /// The range spanned by the left and right array brackets.
2832 SourceRange Brackets;
2834 VariableArrayType(QualType et, QualType can, Expr *e,
2835 ArraySizeModifier sm, unsigned tq,
2836 SourceRange brackets)
2837 : ArrayType(VariableArray, et, can, sm, tq,
2838 et->containsUnexpandedParameterPack()),
2839 SizeExpr((Stmt*) e), Brackets(brackets) {}
2842 friend class StmtIteratorBase;
2844 Expr *getSizeExpr() const {
2845 // We use C-style casts instead of cast<> here because we do not wish
2846 // to have a dependency of Type.h on Stmt.h/Expr.h.
2847 return (Expr*) SizeExpr;
2850 SourceRange getBracketsRange() const { return Brackets; }
2851 SourceLocation getLBracketLoc() const { return Brackets.getBegin(); }
2852 SourceLocation getRBracketLoc() const { return Brackets.getEnd(); }
2854 bool isSugared() const { return false; }
2855 QualType desugar() const { return QualType(this, 0); }
2857 static bool classof(const Type *T) {
2858 return T->getTypeClass() == VariableArray;
2861 void Profile(llvm::FoldingSetNodeID &ID) {
2862 llvm_unreachable("Cannot unique VariableArrayTypes.");
2866 /// Represents an array type in C++ whose size is a value-dependent expression.
2870 /// template<typename T, int Size>
2876 /// For these types, we won't actually know what the array bound is
2877 /// until template instantiation occurs, at which point this will
2878 /// become either a ConstantArrayType or a VariableArrayType.
2879 class DependentSizedArrayType : public ArrayType {
2880 friend class ASTContext; // ASTContext creates these.
2882 const ASTContext &Context;
2884 /// An assignment expression that will instantiate to the
2885 /// size of the array.
2887 /// The expression itself might be null, in which case the array
2888 /// type will have its size deduced from an initializer.
2891 /// The range spanned by the left and right array brackets.
2892 SourceRange Brackets;
2894 DependentSizedArrayType(const ASTContext &Context, QualType et, QualType can,
2895 Expr *e, ArraySizeModifier sm, unsigned tq,
2896 SourceRange brackets);
2899 friend class StmtIteratorBase;
2901 Expr *getSizeExpr() const {
2902 // We use C-style casts instead of cast<> here because we do not wish
2903 // to have a dependency of Type.h on Stmt.h/Expr.h.
2904 return (Expr*) SizeExpr;
2907 SourceRange getBracketsRange() const { return Brackets; }
2908 SourceLocation getLBracketLoc() const { return Brackets.getBegin(); }
2909 SourceLocation getRBracketLoc() const { return Brackets.getEnd(); }
2911 bool isSugared() const { return false; }
2912 QualType desugar() const { return QualType(this, 0); }
2914 static bool classof(const Type *T) {
2915 return T->getTypeClass() == DependentSizedArray;
2918 void Profile(llvm::FoldingSetNodeID &ID) {
2919 Profile(ID, Context, getElementType(),
2920 getSizeModifier(), getIndexTypeCVRQualifiers(), getSizeExpr());
2923 static void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context,
2924 QualType ET, ArraySizeModifier SizeMod,
2925 unsigned TypeQuals, Expr *E);
2928 /// Represents an extended address space qualifier where the input address space
2929 /// value is dependent. Non-dependent address spaces are not represented with a
2930 /// special Type subclass; they are stored on an ExtQuals node as part of a QualType.
2934 /// template<typename T, int AddrSpace>
2935 /// class AddressSpace {
2936 /// typedef T __attribute__((address_space(AddrSpace))) type;
2939 class DependentAddressSpaceType : public Type, public llvm::FoldingSetNode {
2940 friend class ASTContext;
2942 const ASTContext &Context;
2943 Expr *AddrSpaceExpr;
2944 QualType PointeeType;
2947 DependentAddressSpaceType(const ASTContext &Context, QualType PointeeType,
2948 QualType can, Expr *AddrSpaceExpr,
2949 SourceLocation loc);
2952 Expr *getAddrSpaceExpr() const { return AddrSpaceExpr; }
2953 QualType getPointeeType() const { return PointeeType; }
2954 SourceLocation getAttributeLoc() const { return loc; }
2956 bool isSugared() const { return false; }
2957 QualType desugar() const { return QualType(this, 0); }
2959 static bool classof(const Type *T) {
2960 return T->getTypeClass() == DependentAddressSpace;
2963 void Profile(llvm::FoldingSetNodeID &ID) {
2964 Profile(ID, Context, getPointeeType(), getAddrSpaceExpr());
2967 static void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context,
2968 QualType PointeeType, Expr *AddrSpaceExpr);
2971 /// Represents an extended vector type where either the type or size is
2976 /// template<typename T, int Size>
2978 /// typedef T __attribute__((ext_vector_type(Size))) type;
2981 class DependentSizedExtVectorType : public Type, public llvm::FoldingSetNode {
2982 friend class ASTContext;
2984 const ASTContext &Context;
2987 /// The element type of the array.
2988 QualType ElementType;
2992 DependentSizedExtVectorType(const ASTContext &Context, QualType ElementType,
2993 QualType can, Expr *SizeExpr, SourceLocation loc);
2996 Expr *getSizeExpr() const { return SizeExpr; }
2997 QualType getElementType() const { return ElementType; }
2998 SourceLocation getAttributeLoc() const { return loc; }
3000 bool isSugared() const { return false; }
3001 QualType desugar() const { return QualType(this, 0); }
3003 static bool classof(const Type *T) {
3004 return T->getTypeClass() == DependentSizedExtVector;
3007 void Profile(llvm::FoldingSetNodeID &ID) {
3008 Profile(ID, Context, getElementType(), getSizeExpr());
3011 static void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context,
3012 QualType ElementType, Expr *SizeExpr);
3016 /// Represents a GCC generic vector type. This type is created using
3017 /// __attribute__((vector_size(n)), where "n" specifies the vector size in
3018 /// bytes; or from an Altivec __vector or vector declaration.
3019 /// Since the constructor takes the number of vector elements, the
3020 /// client is responsible for converting the size into the number of elements.
3021 class VectorType : public Type, public llvm::FoldingSetNode {
3024 /// not a target-specific vector type
3027 /// is AltiVec vector
3030 /// is AltiVec 'vector Pixel'
3033 /// is AltiVec 'vector bool ...'
3036 /// is ARM Neon vector
3039 /// is ARM Neon polynomial vector
3044 friend class ASTContext; // ASTContext creates these.
3046 /// The element type of the vector.
3047 QualType ElementType;
3049 VectorType(QualType vecType, unsigned nElements, QualType canonType,
3050 VectorKind vecKind);
3052 VectorType(TypeClass tc, QualType vecType, unsigned nElements,
3053 QualType canonType, VectorKind vecKind);
3056 QualType getElementType() const { return ElementType; }
3057 unsigned getNumElements() const { return VectorTypeBits.NumElements; }
3059 static bool isVectorSizeTooLarge(unsigned NumElements) {
3060 return NumElements > VectorTypeBitfields::MaxNumElements;
3063 bool isSugared() const { return false; }
3064 QualType desugar() const { return QualType(this, 0); }
3066 VectorKind getVectorKind() const {
3067 return VectorKind(VectorTypeBits.VecKind);
3070 void Profile(llvm::FoldingSetNodeID &ID) {
3071 Profile(ID, getElementType(), getNumElements(),
3072 getTypeClass(), getVectorKind());
3075 static void Profile(llvm::FoldingSetNodeID &ID, QualType ElementType,
3076 unsigned NumElements, TypeClass TypeClass,
3077 VectorKind VecKind) {
3078 ID.AddPointer(ElementType.getAsOpaquePtr());
3079 ID.AddInteger(NumElements);
3080 ID.AddInteger(TypeClass);
3081 ID.AddInteger(VecKind);
3084 static bool classof(const Type *T) {
3085 return T->getTypeClass() == Vector || T->getTypeClass() == ExtVector;
3089 /// Represents a vector type where either the type or size is dependent.
3093 /// template<typename T, int Size>
3095 /// typedef T __attribute__((vector_size(Size))) type;
3098 class DependentVectorType : public Type, public llvm::FoldingSetNode {
3099 friend class ASTContext;
3101 const ASTContext &Context;
3102 QualType ElementType;
3106 DependentVectorType(const ASTContext &Context, QualType ElementType,
3107 QualType CanonType, Expr *SizeExpr,
3108 SourceLocation Loc, VectorType::VectorKind vecKind);
3111 Expr *getSizeExpr() const { return SizeExpr; }
3112 QualType getElementType() const { return ElementType; }
3113 SourceLocation getAttributeLoc() const { return Loc; }
3114 VectorType::VectorKind getVectorKind() const {
3115 return VectorType::VectorKind(VectorTypeBits.VecKind);
3118 bool isSugared() const { return false; }
3119 QualType desugar() const { return QualType(this, 0); }
3121 static bool classof(const Type *T) {
3122 return T->getTypeClass() == DependentVector;
3125 void Profile(llvm::FoldingSetNodeID &ID) {
3126 Profile(ID, Context, getElementType(), getSizeExpr(), getVectorKind());
3129 static void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context,
3130 QualType ElementType, const Expr *SizeExpr,
3131 VectorType::VectorKind VecKind);
3134 /// ExtVectorType - Extended vector type. This type is created using
3135 /// __attribute__((ext_vector_type(n)), where "n" is the number of elements.
3136 /// Unlike vector_size, ext_vector_type is only allowed on typedef's. This
3137 /// class enables syntactic extensions, like Vector Components for accessing
3138 /// points (as .xyzw), colors (as .rgba), and textures (modeled after OpenGL
3139 /// Shading Language).
3140 class ExtVectorType : public VectorType {
3141 friend class ASTContext; // ASTContext creates these.
3143 ExtVectorType(QualType vecType, unsigned nElements, QualType canonType)
3144 : VectorType(ExtVector, vecType, nElements, canonType, GenericVector) {}
3147 static int getPointAccessorIdx(char c) {
3150 case 'x': case 'r': return 0;
3151 case 'y': case 'g': return 1;
3152 case 'z': case 'b': return 2;
3153 case 'w': case 'a': return 3;
3157 static int getNumericAccessorIdx(char c) {
3171 case 'a': return 10;
3173 case 'b': return 11;
3175 case 'c': return 12;
3177 case 'd': return 13;
3179 case 'e': return 14;
3181 case 'f': return 15;
3185 static int getAccessorIdx(char c, bool isNumericAccessor) {
3186 if (isNumericAccessor)
3187 return getNumericAccessorIdx(c);
3189 return getPointAccessorIdx(c);
3192 bool isAccessorWithinNumElements(char c, bool isNumericAccessor) const {
3193 if (int idx = getAccessorIdx(c, isNumericAccessor)+1)
3194 return unsigned(idx-1) < getNumElements();
3198 bool isSugared() const { return false; }
3199 QualType desugar() const { return QualType(this, 0); }
3201 static bool classof(const Type *T) {
3202 return T->getTypeClass() == ExtVector;
3206 /// FunctionType - C99 6.7.5.3 - Function Declarators. This is the common base
3207 /// class of FunctionNoProtoType and FunctionProtoType.
3208 class FunctionType : public Type {
3209 // The type returned by the function.
3210 QualType ResultType;
3213 /// A class which abstracts out some details necessary for
3216 /// It is not actually used directly for storing this information in
3217 /// a FunctionType, although FunctionType does currently use the
3218 /// same bit-pattern.
3220 // If you add a field (say Foo), other than the obvious places (both,
3221 // constructors, compile failures), what you need to update is
3225 // * functionType. Add Foo, getFoo.
3226 // * ASTContext::getFooType
3227 // * ASTContext::mergeFunctionTypes
3228 // * FunctionNoProtoType::Profile
3229 // * FunctionProtoType::Profile
3230 // * TypePrinter::PrintFunctionProto
3231 // * AST read and write
3234 friend class FunctionType;
3236 // Feel free to rearrange or add bits, but if you go over 12,
3237 // you'll need to adjust both the Bits field below and
3238 // Type::FunctionTypeBitfields.
3240 // | CC |noreturn|produces|nocallersavedregs|regparm|nocfcheck|
3241 // |0 .. 4| 5 | 6 | 7 |8 .. 10| 11 |
3243 // regparm is either 0 (no regparm attribute) or the regparm value+1.
3244 enum { CallConvMask = 0x1F };
3245 enum { NoReturnMask = 0x20 };
3246 enum { ProducesResultMask = 0x40 };
3247 enum { NoCallerSavedRegsMask = 0x80 };
3248 enum { NoCfCheckMask = 0x800 };
3250 RegParmMask = ~(CallConvMask | NoReturnMask | ProducesResultMask |
3251 NoCallerSavedRegsMask | NoCfCheckMask),
3253 }; // Assumed to be the last field
3254 uint16_t Bits = CC_C;
3256 ExtInfo(unsigned Bits) : Bits(static_cast<uint16_t>(Bits)) {}
3259 // Constructor with no defaults. Use this when you know that you
3260 // have all the elements (when reading an AST file for example).
3261 ExtInfo(bool noReturn, bool hasRegParm, unsigned regParm, CallingConv cc,
3262 bool producesResult, bool noCallerSavedRegs, bool NoCfCheck) {
3263 assert((!hasRegParm || regParm < 7) && "Invalid regparm value");
3264 Bits = ((unsigned)cc) | (noReturn ? NoReturnMask : 0) |
3265 (producesResult ? ProducesResultMask : 0) |
3266 (noCallerSavedRegs ? NoCallerSavedRegsMask : 0) |
3267 (hasRegParm ? ((regParm + 1) << RegParmOffset) : 0) |
3268 (NoCfCheck ? NoCfCheckMask : 0);
3271 // Constructor with all defaults. Use when for example creating a
3272 // function known to use defaults.
3273 ExtInfo() = default;
3275 // Constructor with just the calling convention, which is an important part
3276 // of the canonical type.
3277 ExtInfo(CallingConv CC) : Bits(CC) {}
3279 bool getNoReturn() const { return Bits & NoReturnMask; }
3280 bool getProducesResult() const { return Bits & ProducesResultMask; }
3281 bool getNoCallerSavedRegs() const { return Bits & NoCallerSavedRegsMask; }
3282 bool getNoCfCheck() const { return Bits & NoCfCheckMask; }
3283 bool getHasRegParm() const { return (Bits >> RegParmOffset) != 0; }
3285 unsigned getRegParm() const {
3286 unsigned RegParm = (Bits & RegParmMask) >> RegParmOffset;
3292 CallingConv getCC() const { return CallingConv(Bits & CallConvMask); }
3294 bool operator==(ExtInfo Other) const {
3295 return Bits == Other.Bits;
3297 bool operator!=(ExtInfo Other) const {
3298 return Bits != Other.Bits;
3301 // Note that we don't have setters. That is by design, use
3302 // the following with methods instead of mutating these objects.
3304 ExtInfo withNoReturn(bool noReturn) const {
3306 return ExtInfo(Bits | NoReturnMask);
3308 return ExtInfo(Bits & ~NoReturnMask);
3311 ExtInfo withProducesResult(bool producesResult) const {
3313 return ExtInfo(Bits | ProducesResultMask);
3315 return ExtInfo(Bits & ~ProducesResultMask);
3318 ExtInfo withNoCallerSavedRegs(bool noCallerSavedRegs) const {
3319 if (noCallerSavedRegs)
3320 return ExtInfo(Bits | NoCallerSavedRegsMask);
3322 return ExtInfo(Bits & ~NoCallerSavedRegsMask);
3325 ExtInfo withNoCfCheck(bool noCfCheck) const {
3327 return ExtInfo(Bits | NoCfCheckMask);
3329 return ExtInfo(Bits & ~NoCfCheckMask);
3332 ExtInfo withRegParm(unsigned RegParm) const {
3333 assert(RegParm < 7 && "Invalid regparm value");
3334 return ExtInfo((Bits & ~RegParmMask) |
3335 ((RegParm + 1) << RegParmOffset));
3338 ExtInfo withCallingConv(CallingConv cc) const {
3339 return ExtInfo((Bits & ~CallConvMask) | (unsigned) cc);
3342 void Profile(llvm::FoldingSetNodeID &ID) const {
3343 ID.AddInteger(Bits);
3348 FunctionType(TypeClass tc, QualType res,
3349 QualType Canonical, bool Dependent,
3350 bool InstantiationDependent,
3351 bool VariablyModified, bool ContainsUnexpandedParameterPack,
3353 : Type(tc, Canonical, Dependent, InstantiationDependent, VariablyModified,
3354 ContainsUnexpandedParameterPack),
3356 FunctionTypeBits.ExtInfo = Info.Bits;
3359 unsigned getTypeQuals() const { return FunctionTypeBits.TypeQuals; }
3362 QualType getReturnType() const { return ResultType; }
3364 bool getHasRegParm() const { return getExtInfo().getHasRegParm(); }
3365 unsigned getRegParmType() const { return getExtInfo().getRegParm(); }
3367 /// Determine whether this function type includes the GNU noreturn
3368 /// attribute. The C++11 [[noreturn]] attribute does not affect the function
3370 bool getNoReturnAttr() const { return getExtInfo().getNoReturn(); }
3372 CallingConv getCallConv() const { return getExtInfo().getCC(); }
3373 ExtInfo getExtInfo() const { return ExtInfo(FunctionTypeBits.ExtInfo); }
3374 bool isConst() const { return getTypeQuals() & Qualifiers::Const; }
3375 bool isVolatile() const { return getTypeQuals() & Qualifiers::Volatile; }
3376 bool isRestrict() const { return getTypeQuals() & Qualifiers::Restrict; }
3378 /// Determine the type of an expression that calls a function of
3380 QualType getCallResultType(const ASTContext &Context) const {
3381 return getReturnType().getNonLValueExprType(Context);
3384 static StringRef getNameForCallConv(CallingConv CC);
3386 static bool classof(const Type *T) {
3387 return T->getTypeClass() == FunctionNoProto ||
3388 T->getTypeClass() == FunctionProto;
3392 /// Represents a K&R-style 'int foo()' function, which has
3393 /// no information available about its arguments.
3394 class FunctionNoProtoType : public FunctionType, public llvm::FoldingSetNode {
3395 friend class ASTContext; // ASTContext creates these.
3397 FunctionNoProtoType(QualType Result, QualType Canonical, ExtInfo Info)
3398 : FunctionType(FunctionNoProto, Result, Canonical,
3399 /*Dependent=*/false, /*InstantiationDependent=*/false,
3400 Result->isVariablyModifiedType(),
3401 /*ContainsUnexpandedParameterPack=*/false, Info) {}
3404 // No additional state past what FunctionType provides.
3406 bool isSugared() const { return false; }
3407 QualType desugar() const { return QualType(this, 0); }
3409 void Profile(llvm::FoldingSetNodeID &ID) {
3410 Profile(ID, getReturnType(), getExtInfo());
3413 static void Profile(llvm::FoldingSetNodeID &ID, QualType ResultType,
3416 ID.AddPointer(ResultType.getAsOpaquePtr());
3419 static bool classof(const Type *T) {
3420 return T->getTypeClass() == FunctionNoProto;
3424 /// Represents a prototype with parameter type info, e.g.
3425 /// 'int foo(int)' or 'int foo(void)'. 'void' is represented as having no
3426 /// parameters, not as having a single void parameter. Such a type can have an
3427 /// exception specification, but this specification is not part of the canonical
3429 class FunctionProtoType : public FunctionType, public llvm::FoldingSetNode {
3431 /// Interesting information about a specific parameter that can't simply
3432 /// be reflected in parameter's type.
3434 /// It makes sense to model language features this way when there's some
3435 /// sort of parameter-specific override (such as an attribute) that
3436 /// affects how the function is called. For example, the ARC ns_consumed
3437 /// attribute changes whether a parameter is passed at +0 (the default)
3438 /// or +1 (ns_consumed). This must be reflected in the function type,
3439 /// but isn't really a change to the parameter type.
3441 /// One serious disadvantage of modelling language features this way is
3442 /// that they generally do not work with language features that attempt
3443 /// to destructure types. For example, template argument deduction will
3444 /// not be able to match a parameter declared as
3446 /// against an argument of type
3447 /// void (*)(__attribute__((ns_consumed)) id)
3448 /// because the substitution of T=void, U=id into the former will
3449 /// not produce the latter.
3450 class ExtParameterInfo {
3454 HasPassObjSize = 0x20,
3457 unsigned char Data = 0;
3460 ExtParameterInfo() = default;
3462 /// Return the ABI treatment of this parameter.
3463 ParameterABI getABI() const {
3464 return ParameterABI(Data & ABIMask);
3466 ExtParameterInfo withABI(ParameterABI kind) const {
3467 ExtParameterInfo copy = *this;
3468 copy.Data = (copy.Data & ~ABIMask) | unsigned(kind);
3472 /// Is this parameter considered "consumed" by Objective-C ARC?
3473 /// Consumed parameters must have retainable object type.
3474 bool isConsumed() const {
3475 return (Data & IsConsumed);
3477 ExtParameterInfo withIsConsumed(bool consumed) const {
3478 ExtParameterInfo copy = *this;
3480 copy.Data |= IsConsumed;
3482 copy.Data &= ~IsConsumed;
3487 bool hasPassObjectSize() const {
3488 return Data & HasPassObjSize;
3490 ExtParameterInfo withHasPassObjectSize() const {
3491 ExtParameterInfo Copy = *this;
3492 Copy.Data |= HasPassObjSize;
3496 bool isNoEscape() const {
3497 return Data & IsNoEscape;
3500 ExtParameterInfo withIsNoEscape(bool NoEscape) const {
3501 ExtParameterInfo Copy = *this;
3503 Copy.Data |= IsNoEscape;
3505 Copy.Data &= ~IsNoEscape;
3509 unsigned char getOpaqueValue() const { return Data; }
3510 static ExtParameterInfo getFromOpaqueValue(unsigned char data) {
3511 ExtParameterInfo result;
3516 friend bool operator==(ExtParameterInfo lhs, ExtParameterInfo rhs) {
3517 return lhs.Data == rhs.Data;
3519 friend bool operator!=(ExtParameterInfo lhs, ExtParameterInfo rhs) {
3520 return lhs.Data != rhs.Data;
3524 struct ExceptionSpecInfo {
3525 /// The kind of exception specification this is.
3526 ExceptionSpecificationType Type = EST_None;
3528 /// Explicitly-specified list of exception types.
3529 ArrayRef<QualType> Exceptions;
3531 /// Noexcept expression, if this is a computed noexcept specification.
3532 Expr *NoexceptExpr = nullptr;
3534 /// The function whose exception specification this is, for
3535 /// EST_Unevaluated and EST_Uninstantiated.
3536 FunctionDecl *SourceDecl = nullptr;
3538 /// The function template whose exception specification this is instantiated
3539 /// from, for EST_Uninstantiated.
3540 FunctionDecl *SourceTemplate = nullptr;
3542 ExceptionSpecInfo() = default;
3544 ExceptionSpecInfo(ExceptionSpecificationType EST) : Type(EST) {}
3547 /// Extra information about a function prototype.
3548 struct ExtProtoInfo {
3549 FunctionType::ExtInfo ExtInfo;
3551 bool HasTrailingReturn : 1;
3552 unsigned char TypeQuals = 0;
3553 RefQualifierKind RefQualifier = RQ_None;
3554 ExceptionSpecInfo ExceptionSpec;
3555 const ExtParameterInfo *ExtParameterInfos = nullptr;
3558 : Variadic(false), HasTrailingReturn(false) {}
3560 ExtProtoInfo(CallingConv CC)
3561 : ExtInfo(CC), Variadic(false), HasTrailingReturn(false) {}
3563 ExtProtoInfo withExceptionSpec(const ExceptionSpecInfo &O) {
3564 ExtProtoInfo Result(*this);
3565 Result.ExceptionSpec = O;
3571 friend class ASTContext; // ASTContext creates these.
3573 /// Determine whether there are any argument types that
3574 /// contain an unexpanded parameter pack.
3575 static bool containsAnyUnexpandedParameterPack(const QualType *ArgArray,
3577 for (unsigned Idx = 0; Idx < numArgs; ++Idx)
3578 if (ArgArray[Idx]->containsUnexpandedParameterPack())
3584 FunctionProtoType(QualType result, ArrayRef<QualType> params,
3585 QualType canonical, const ExtProtoInfo &epi);
3587 /// The number of parameters this function has, not counting '...'.
3588 unsigned NumParams : 15;
3590 /// The number of types in the exception spec, if any.
3591 unsigned NumExceptions : 9;
3593 /// The type of exception specification this function has.
3594 unsigned ExceptionSpecType : 4;
3596 /// Whether this function has extended parameter information.
3597 unsigned HasExtParameterInfos : 1;
3599 /// Whether the function is variadic.
3600 unsigned Variadic : 1;
3602 /// Whether this function has a trailing return type.
3603 unsigned HasTrailingReturn : 1;
3605 // ParamInfo - There is an variable size array after the class in memory that
3606 // holds the parameter types.
3608 // Exceptions - There is another variable size array after ArgInfo that
3609 // holds the exception types.
3611 // NoexceptExpr - Instead of Exceptions, there may be a single Expr* pointing
3612 // to the expression in the noexcept() specifier.
3614 // ExceptionSpecDecl, ExceptionSpecTemplate - Instead of Exceptions, there may
3615 // be a pair of FunctionDecl* pointing to the function which should be used to
3616 // instantiate this function type's exception specification, and the function
3617 // from which it should be instantiated.
3619 // ExtParameterInfos - A variable size array, following the exception
3620 // specification and of length NumParams, holding an ExtParameterInfo
3621 // for each of the parameters. This only appears if HasExtParameterInfos
3624 const ExtParameterInfo *getExtParameterInfosBuffer() const {
3625 assert(hasExtParameterInfos());
3627 // Find the end of the exception specification.
3628 const auto *ptr = reinterpret_cast<const char *>(exception_begin());
3629 ptr += getExceptionSpecSize();
3631 return reinterpret_cast<const ExtParameterInfo *>(ptr);
3634 static size_t getExceptionSpecSize(ExceptionSpecificationType EST,
3635 unsigned NumExceptions) {
3638 case EST_DynamicNone:
3640 case EST_BasicNoexcept:
3645 return NumExceptions * sizeof(QualType);
3647 case EST_DependentNoexcept:
3648 case EST_NoexceptFalse:
3649 case EST_NoexceptTrue:
3650 return sizeof(Expr *);
3652 case EST_Uninstantiated:
3653 return 2 * sizeof(FunctionDecl *);
3655 case EST_Unevaluated:
3656 return sizeof(FunctionDecl *);
3658 llvm_unreachable("bad exception specification kind");
3660 size_t getExceptionSpecSize() const {
3661 return getExceptionSpecSize(getExceptionSpecType(), getNumExceptions());
3665 unsigned getNumParams() const { return NumParams; }
3667 QualType getParamType(unsigned i) const {
3668 assert(i < NumParams && "invalid parameter index");
3669 return param_type_begin()[i];
3672 ArrayRef<QualType> getParamTypes() const {
3673 return llvm::makeArrayRef(param_type_begin(), param_type_end());
3676 ExtProtoInfo getExtProtoInfo() const {
3678 EPI.ExtInfo = getExtInfo();
3679 EPI.Variadic = isVariadic();
3680 EPI.HasTrailingReturn = hasTrailingReturn();
3681 EPI.ExceptionSpec.Type = getExceptionSpecType();
3682 EPI.TypeQuals = static_cast<unsigned char>(getTypeQuals());
3683 EPI.RefQualifier = getRefQualifier();
3684 if (EPI.ExceptionSpec.Type == EST_Dynamic) {
3685 EPI.ExceptionSpec.Exceptions = exceptions();
3686 } else if (isComputedNoexcept(EPI.ExceptionSpec.Type)) {
3687 EPI.ExceptionSpec.NoexceptExpr = getNoexceptExpr();
3688 } else if (EPI.ExceptionSpec.Type == EST_Uninstantiated) {
3689 EPI.ExceptionSpec.SourceDecl = getExceptionSpecDecl();
3690 EPI.ExceptionSpec.SourceTemplate = getExceptionSpecTemplate();
3691 } else if (EPI.ExceptionSpec.Type == EST_Unevaluated) {
3692 EPI.ExceptionSpec.SourceDecl = getExceptionSpecDecl();
3694 if (hasExtParameterInfos())
3695 EPI.ExtParameterInfos = getExtParameterInfosBuffer();
3699 /// Get the kind of exception specification on this function.
3700 ExceptionSpecificationType getExceptionSpecType() const {
3701 return static_cast<ExceptionSpecificationType>(ExceptionSpecType);
3704 /// Return whether this function has any kind of exception spec.
3705 bool hasExceptionSpec() const {
3706 return getExceptionSpecType() != EST_None;
3709 /// Return whether this function has a dynamic (throw) exception spec.
3710 bool hasDynamicExceptionSpec() const {
3711 return isDynamicExceptionSpec(getExceptionSpecType());
3714 /// Return whether this function has a noexcept exception spec.
3715 bool hasNoexceptExceptionSpec() const {
3716 return isNoexceptExceptionSpec(getExceptionSpecType());
3719 /// Return whether this function has a dependent exception spec.
3720 bool hasDependentExceptionSpec() const;
3722 /// Return whether this function has an instantiation-dependent exception
3724 bool hasInstantiationDependentExceptionSpec() const;
3726 unsigned getNumExceptions() const { return NumExceptions; }
3727 QualType getExceptionType(unsigned i) const {
3728 assert(i < NumExceptions && "Invalid exception number!");
3729 return exception_begin()[i];
3731 Expr *getNoexceptExpr() const {
3732 if (!isComputedNoexcept(getExceptionSpecType()))
3734 // NoexceptExpr sits where the arguments end.
3735 return *reinterpret_cast<Expr *const *>(param_type_end());
3738 /// If this function type has an exception specification which hasn't
3739 /// been determined yet (either because it has not been evaluated or because
3740 /// it has not been instantiated), this is the function whose exception
3741 /// specification is represented by this type.
3742 FunctionDecl *getExceptionSpecDecl() const {
3743 if (getExceptionSpecType() != EST_Uninstantiated &&
3744 getExceptionSpecType() != EST_Unevaluated)
3746 return reinterpret_cast<FunctionDecl *const *>(param_type_end())[0];
3749 /// If this function type has an uninstantiated exception
3750 /// specification, this is the function whose exception specification
3751 /// should be instantiated to find the exception specification for
3753 FunctionDecl *getExceptionSpecTemplate() const {
3754 if (getExceptionSpecType() != EST_Uninstantiated)
3756 return reinterpret_cast<FunctionDecl *const *>(param_type_end())[1];
3759 /// Determine whether this function type has a non-throwing exception
3761 CanThrowResult canThrow() const;
3763 /// Determine whether this function type has a non-throwing exception
3764 /// specification. If this depends on template arguments, returns
3765 /// \c ResultIfDependent.
3766 bool isNothrow(bool ResultIfDependent = false) const {
3767 return ResultIfDependent ? canThrow() != CT_Can
3768 : canThrow() == CT_Cannot;
3771 bool isVariadic() const { return Variadic; }
3773 /// Determines whether this function prototype contains a
3774 /// parameter pack at the end.
3776 /// A function template whose last parameter is a parameter pack can be
3777 /// called with an arbitrary number of arguments, much like a variadic
3779 bool isTemplateVariadic() const;
3781 bool hasTrailingReturn() const { return HasTrailingReturn; }
3783 unsigned getTypeQuals() const { return FunctionType::getTypeQuals(); }
3785 /// Retrieve the ref-qualifier associated with this function type.
3786 RefQualifierKind getRefQualifier() const {
3787 return static_cast<RefQualifierKind>(FunctionTypeBits.RefQualifier);
3790 using param_type_iterator = const QualType *;
3791 using param_type_range = llvm::iterator_range<param_type_iterator>;
3793 param_type_range param_types() const {
3794 return param_type_range(param_type_begin(), param_type_end());
3797 param_type_iterator param_type_begin() const {
3798 return reinterpret_cast<const QualType *>(this+1);
3801 param_type_iterator param_type_end() const {
3802 return param_type_begin() + NumParams;
3805 using exception_iterator = const QualType *;
3807 ArrayRef<QualType> exceptions() const {
3808 return llvm::makeArrayRef(exception_begin(), exception_end());
3811 exception_iterator exception_begin() const {
3812 // exceptions begin where arguments end
3813 return param_type_end();
3816 exception_iterator exception_end() const {
3817 if (getExceptionSpecType() != EST_Dynamic)
3818 return exception_begin();
3819 return exception_begin() + NumExceptions;
3822 /// Is there any interesting extra information for any of the parameters
3823 /// of this function type?
3824 bool hasExtParameterInfos() const { return HasExtParameterInfos; }
3825 ArrayRef<ExtParameterInfo> getExtParameterInfos() const {
3826 assert(hasExtParameterInfos());
3827 return ArrayRef<ExtParameterInfo>(getExtParameterInfosBuffer(),
3831 /// Return a pointer to the beginning of the array of extra parameter
3832 /// information, if present, or else null if none of the parameters
3833 /// carry it. This is equivalent to getExtProtoInfo().ExtParameterInfos.
3834 const ExtParameterInfo *getExtParameterInfosOrNull() const {
3835 if (!hasExtParameterInfos())
3837 return getExtParameterInfosBuffer();
3840 ExtParameterInfo getExtParameterInfo(unsigned I) const {
3841 assert(I < getNumParams() && "parameter index out of range");
3842 if (hasExtParameterInfos())
3843 return getExtParameterInfosBuffer()[I];
3844 return ExtParameterInfo();
3847 ParameterABI getParameterABI(unsigned I) const {
3848 assert(I < getNumParams() && "parameter index out of range");
3849 if (hasExtParameterInfos())
3850 return getExtParameterInfosBuffer()[I].getABI();
3851 return ParameterABI::Ordinary;
3854 bool isParamConsumed(unsigned I) const {
3855 assert(I < getNumParams() && "parameter index out of range");
3856 if (hasExtParameterInfos())
3857 return getExtParameterInfosBuffer()[I].isConsumed();
3861 bool isSugared() const { return false; }
3862 QualType desugar() const { return QualType(this, 0); }
3864 void printExceptionSpecification(raw_ostream &OS,
3865 const PrintingPolicy &Policy) const;
3867 static bool classof(const Type *T) {
3868 return T->getTypeClass() == FunctionProto;
3871 void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Ctx);
3872 static void Profile(llvm::FoldingSetNodeID &ID, QualType Result,
3873 param_type_iterator ArgTys, unsigned NumArgs,
3874 const ExtProtoInfo &EPI, const ASTContext &Context,
3878 /// Represents the dependent type named by a dependently-scoped
3879 /// typename using declaration, e.g.
3880 /// using typename Base<T>::foo;
3882 /// Template instantiation turns these into the underlying type.
3883 class UnresolvedUsingType : public Type {
3884 friend class ASTContext; // ASTContext creates these.
3886 UnresolvedUsingTypenameDecl *Decl;
3888 UnresolvedUsingType(const UnresolvedUsingTypenameDecl *D)
3889 : Type(UnresolvedUsing, QualType(), true, true, false,
3890 /*ContainsUnexpandedParameterPack=*/false),
3891 Decl(const_cast<UnresolvedUsingTypenameDecl*>(D)) {}
3894 UnresolvedUsingTypenameDecl *getDecl() const { return Decl; }
3896 bool isSugared() const { return false; }
3897 QualType desugar() const { return QualType(this, 0); }
3899 static bool classof(const Type *T) {
3900 return T->getTypeClass() == UnresolvedUsing;
3903 void Profile(llvm::FoldingSetNodeID &ID) {
3904 return Profile(ID, Decl);
3907 static void Profile(llvm::FoldingSetNodeID &ID,
3908 UnresolvedUsingTypenameDecl *D) {
3913 class TypedefType : public Type {
3914 TypedefNameDecl *Decl;
3917 friend class ASTContext; // ASTContext creates these.
3919 TypedefType(TypeClass tc, const TypedefNameDecl *D, QualType can)
3920 : Type(tc, can, can->isDependentType(),
3921 can->isInstantiationDependentType(),
3922 can->isVariablyModifiedType(),
3923 /*ContainsUnexpandedParameterPack=*/false),
3924 Decl(const_cast<TypedefNameDecl*>(D)) {
3925 assert(!isa<TypedefType>(can) && "Invalid canonical type");
3929 TypedefNameDecl *getDecl() const { return Decl; }
3931 bool isSugared() const { return true; }
3932 QualType desugar() const;
3934 static bool classof(const Type *T) { return T->getTypeClass() == Typedef; }
3937 /// Represents a `typeof` (or __typeof__) expression (a GCC extension).
3938 class TypeOfExprType : public Type {
3942 friend class ASTContext; // ASTContext creates these.
3944 TypeOfExprType(Expr *E, QualType can = QualType());
3947 Expr *getUnderlyingExpr() const { return TOExpr; }
3949 /// Remove a single level of sugar.
3950 QualType desugar() const;
3952 /// Returns whether this type directly provides sugar.
3953 bool isSugared() const;
3955 static bool classof(const Type *T) { return T->getTypeClass() == TypeOfExpr; }
3958 /// Internal representation of canonical, dependent
3959 /// `typeof(expr)` types.
3961 /// This class is used internally by the ASTContext to manage
3962 /// canonical, dependent types, only. Clients will only see instances
3963 /// of this class via TypeOfExprType nodes.
3964 class DependentTypeOfExprType
3965 : public TypeOfExprType, public llvm::FoldingSetNode {
3966 const ASTContext &Context;
3969 DependentTypeOfExprType(const ASTContext &Context, Expr *E)
3970 : TypeOfExprType(E), Context(Context) {}
3972 void Profile(llvm::FoldingSetNodeID &ID) {
3973 Profile(ID, Context, getUnderlyingExpr());
3976 static void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context,
3980 /// Represents `typeof(type)`, a GCC extension.
3981 class TypeOfType : public Type {
3982 friend class ASTContext; // ASTContext creates these.
3986 TypeOfType(QualType T, QualType can)
3987 : Type(TypeOf, can, T->isDependentType(),
3988 T->isInstantiationDependentType(),
3989 T->isVariablyModifiedType(),
3990 T->containsUnexpandedParameterPack()),
3992 assert(!isa<TypedefType>(can) && "Invalid canonical type");
3996 QualType getUnderlyingType() const { return TOType; }
3998 /// Remove a single level of sugar.
3999 QualType desugar() const { return getUnderlyingType(); }
4001 /// Returns whether this type directly provides sugar.
4002 bool isSugared() const { return true; }
4004 static bool classof(const Type *T) { return T->getTypeClass() == TypeOf; }
4007 /// Represents the type `decltype(expr)` (C++11).
4008 class DecltypeType : public Type {
4010 QualType UnderlyingType;
4013 friend class ASTContext; // ASTContext creates these.
4015 DecltypeType(Expr *E, QualType underlyingType, QualType can = QualType());
4018 Expr *getUnderlyingExpr() const { return E; }
4019 QualType getUnderlyingType() const { return UnderlyingType; }
4021 /// Remove a single level of sugar.
4022 QualType desugar() const;
4024 /// Returns whether this type directly provides sugar.
4025 bool isSugared() const;
4027 static bool classof(const Type *T) { return T->getTypeClass() == Decltype; }
4030 /// Internal representation of canonical, dependent
4031 /// decltype(expr) types.
4033 /// This class is used internally by the ASTContext to manage
4034 /// canonical, dependent types, only. Clients will only see instances
4035 /// of this class via DecltypeType nodes.
4036 class DependentDecltypeType : public DecltypeType, public llvm::FoldingSetNode {
4037 const ASTContext &Context;
4040 DependentDecltypeType(const ASTContext &Context, Expr *E);
4042 void Profile(llvm::FoldingSetNodeID &ID) {
4043 Profile(ID, Context, getUnderlyingExpr());
4046 static void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context,
4050 /// A unary type transform, which is a type constructed from another.
4051 class UnaryTransformType : public Type {
4058 /// The untransformed type.
4061 /// The transformed type if not dependent, otherwise the same as BaseType.
4062 QualType UnderlyingType;
4067 friend class ASTContext;
4069 UnaryTransformType(QualType BaseTy, QualType UnderlyingTy, UTTKind UKind,
4070 QualType CanonicalTy);
4073 bool isSugared() const { return !isDependentType(); }
4074 QualType desugar() const { return UnderlyingType; }
4076 QualType getUnderlyingType() const { return UnderlyingType; }
4077 QualType getBaseType() const { return BaseType; }
4079 UTTKind getUTTKind() const { return UKind; }
4081 static bool classof(const Type *T) {
4082 return T->getTypeClass() == UnaryTransform;
4086 /// Internal representation of canonical, dependent
4087 /// __underlying_type(type) types.
4089 /// This class is used internally by the ASTContext to manage
4090 /// canonical, dependent types, only. Clients will only see instances
4091 /// of this class via UnaryTransformType nodes.
4092 class DependentUnaryTransformType : public UnaryTransformType,
4093 public llvm::FoldingSetNode {
4095 DependentUnaryTransformType(const ASTContext &C, QualType BaseType,
4098 void Profile(llvm::FoldingSetNodeID &ID) {
4099 Profile(ID, getBaseType(), getUTTKind());
4102 static void Profile(llvm::FoldingSetNodeID &ID, QualType BaseType,
4104 ID.AddPointer(BaseType.getAsOpaquePtr());
4105 ID.AddInteger((unsigned)UKind);
4109 class TagType : public Type {
4110 friend class ASTReader;
4112 /// Stores the TagDecl associated with this type. The decl may point to any
4113 /// TagDecl that declares the entity.
4117 TagType(TypeClass TC, const TagDecl *D, QualType can);
4120 TagDecl *getDecl() const;
4122 /// Determines whether this type is in the process of being defined.
4123 bool isBeingDefined() const;
4125 static bool classof(const Type *T) {
4126 return T->getTypeClass() >= TagFirst && T->getTypeClass() <= TagLast;
4130 /// A helper class that allows the use of isa/cast/dyncast
4131 /// to detect TagType objects of structs/unions/classes.
4132 class RecordType : public TagType {
4134 friend class ASTContext; // ASTContext creates these.
4136 explicit RecordType(const RecordDecl *D)
4137 : TagType(Record, reinterpret_cast<const TagDecl*>(D), QualType()) {}
4138 explicit RecordType(TypeClass TC, RecordDecl *D)
4139 : TagType(TC, reinterpret_cast<const TagDecl*>(D), QualType()) {}
4142 RecordDecl *getDecl() const {
4143 return reinterpret_cast<RecordDecl*>(TagType::getDecl());
4146 /// Recursively check all fields in the record for const-ness. If any field
4147 /// is declared const, return true. Otherwise, return false.
4148 bool hasConstFields() const;
4150 bool isSugared() const { return false; }
4151 QualType desugar() const { return QualType(this, 0); }
4153 static bool classof(const Type *T) { return T->getTypeClass() == Record; }
4156 /// A helper class that allows the use of isa/cast/dyncast
4157 /// to detect TagType objects of enums.
4158 class EnumType : public TagType {
4159 friend class ASTContext; // ASTContext creates these.
4161 explicit EnumType(const EnumDecl *D)
4162 : TagType(Enum, reinterpret_cast<const TagDecl*>(D), QualType()) {}
4165 EnumDecl *getDecl() const {
4166 return reinterpret_cast<EnumDecl*>(TagType::getDecl());
4169 bool isSugared() const { return false; }
4170 QualType desugar() const { return QualType(this, 0); }
4172 static bool classof(const Type *T) { return T->getTypeClass() == Enum; }
4175 /// An attributed type is a type to which a type attribute has been applied.
4177 /// The "modified type" is the fully-sugared type to which the attributed
4178 /// type was applied; generally it is not canonically equivalent to the
4179 /// attributed type. The "equivalent type" is the minimally-desugared type
4180 /// which the type is canonically equivalent to.
4182 /// For example, in the following attributed type:
4183 /// int32_t __attribute__((vector_size(16)))
4184 /// - the modified type is the TypedefType for int32_t
4185 /// - the equivalent type is VectorType(16, int32_t)
4186 /// - the canonical type is VectorType(16, int)
4187 class AttributedType : public Type, public llvm::FoldingSetNode {
4189 // It is really silly to have yet another attribute-kind enum, but
4190 // clang::attr::Kind doesn't currently cover the pure type attrs.
4192 // Expression operand.
4196 attr_neon_vector_type,
4197 attr_neon_polyvector_type,
4199 FirstExprOperandKind = attr_address_space,
4200 LastExprOperandKind = attr_neon_polyvector_type,
4202 // Enumerated operand (string or keyword).
4204 attr_objc_ownership,
4208 FirstEnumOperandKind = attr_objc_gc,
4209 LastEnumOperandKind = attr_pcs_vfp,
4232 attr_ns_returns_retained,
4234 attr_null_unspecified,
4236 attr_objc_inert_unsafe_unretained,
4240 friend class ASTContext; // ASTContext creates these
4242 QualType ModifiedType;
4243 QualType EquivalentType;
4245 AttributedType(QualType canon, Kind attrKind, QualType modified,
4246 QualType equivalent)
4247 : Type(Attributed, canon, equivalent->isDependentType(),
4248 equivalent->isInstantiationDependentType(),
4249 equivalent->isVariablyModifiedType(),
4250 equivalent->containsUnexpandedParameterPack()),
4251 ModifiedType(modified), EquivalentType(equivalent) {
4252 AttributedTypeBits.AttrKind = attrKind;
4256 Kind getAttrKind() const {
4257 return static_cast<Kind>(AttributedTypeBits.AttrKind);
4260 QualType getModifiedType() const { return ModifiedType; }
4261 QualType getEquivalentType() const { return EquivalentType; }
4263 bool isSugared() const { return true; }
4264 QualType desugar() const { return getEquivalentType(); }
4266 /// Does this attribute behave like a type qualifier?
4268 /// A type qualifier adjusts a type to provide specialized rules for
4269 /// a specific object, like the standard const and volatile qualifiers.
4270 /// This includes attributes controlling things like nullability,
4271 /// address spaces, and ARC ownership. The value of the object is still
4272 /// largely described by the modified type.
4274 /// In contrast, many type attributes "rewrite" their modified type to
4275 /// produce a fundamentally different type, not necessarily related in any
4276 /// formalizable way to the original type. For example, calling convention
4277 /// and vector attributes are not simple type qualifiers.
4279 /// Type qualifiers are often, but not always, reflected in the canonical
4281 bool isQualifier() const;
4283 bool isMSTypeSpec() const;
4285 bool isCallingConv() const;
4287 llvm::Optional<NullabilityKind> getImmediateNullability() const;
4289 /// Retrieve the attribute kind corresponding to the given
4290 /// nullability kind.
4291 static Kind getNullabilityAttrKind(NullabilityKind kind) {
4293 case NullabilityKind::NonNull:
4294 return attr_nonnull;
4296 case NullabilityKind::Nullable:
4297 return attr_nullable;
4299 case NullabilityKind::Unspecified:
4300 return attr_null_unspecified;
4302 llvm_unreachable("Unknown nullability kind.");
4305 /// Strip off the top-level nullability annotation on the given
4306 /// type, if it's there.
4308 /// \param T The type to strip. If the type is exactly an
4309 /// AttributedType specifying nullability (without looking through
4310 /// type sugar), the nullability is returned and this type changed
4311 /// to the underlying modified type.
4313 /// \returns the top-level nullability, if present.
4314 static Optional<NullabilityKind> stripOuterNullability(QualType &T);
4316 void Profile(llvm::FoldingSetNodeID &ID) {
4317 Profile(ID, getAttrKind(), ModifiedType, EquivalentType);
4320 static void Profile(llvm::FoldingSetNodeID &ID, Kind attrKind,
4321 QualType modified, QualType equivalent) {
4322 ID.AddInteger(attrKind);
4323 ID.AddPointer(modified.getAsOpaquePtr());
4324 ID.AddPointer(equivalent.getAsOpaquePtr());
4327 static bool classof(const Type *T) {
4328 return T->getTypeClass() == Attributed;
4332 class TemplateTypeParmType : public Type, public llvm::FoldingSetNode {
4333 friend class ASTContext; // ASTContext creates these
4335 // Helper data collector for canonical types.
4336 struct CanonicalTTPTInfo {
4337 unsigned Depth : 15;
4338 unsigned ParameterPack : 1;
4339 unsigned Index : 16;
4343 // Info for the canonical type.
4344 CanonicalTTPTInfo CanTTPTInfo;
4346 // Info for the non-canonical type.
4347 TemplateTypeParmDecl *TTPDecl;
4350 /// Build a non-canonical type.
4351 TemplateTypeParmType(TemplateTypeParmDecl *TTPDecl, QualType Canon)
4352 : Type(TemplateTypeParm, Canon, /*Dependent=*/true,
4353 /*InstantiationDependent=*/true,
4354 /*VariablyModified=*/false,
4355 Canon->containsUnexpandedParameterPack()),
4358 /// Build the canonical type.
4359 TemplateTypeParmType(unsigned D, unsigned I, bool PP)
4360 : Type(TemplateTypeParm, QualType(this, 0),
4362 /*InstantiationDependent=*/true,
4363 /*VariablyModified=*/false, PP) {
4364 CanTTPTInfo.Depth = D;
4365 CanTTPTInfo.Index = I;
4366 CanTTPTInfo.ParameterPack = PP;
4369 const CanonicalTTPTInfo& getCanTTPTInfo() const {
4370 QualType Can = getCanonicalTypeInternal();
4371 return Can->castAs<TemplateTypeParmType>()->CanTTPTInfo;
4375 unsigned getDepth() const { return getCanTTPTInfo().Depth; }
4376 unsigned getIndex() const { return getCanTTPTInfo().Index; }
4377 bool isParameterPack() const { return getCanTTPTInfo().ParameterPack; }
4379 TemplateTypeParmDecl *getDecl() const {
4380 return isCanonicalUnqualified() ? nullptr : TTPDecl;
4383 IdentifierInfo *getIdentifier() const;
4385 bool isSugared() const { return false; }
4386 QualType desugar() const { return QualType(this, 0); }
4388 void Profile(llvm::FoldingSetNodeID &ID) {
4389 Profile(ID, getDepth(), getIndex(), isParameterPack(), getDecl());
4392 static void Profile(llvm::FoldingSetNodeID &ID, unsigned Depth,
4393 unsigned Index, bool ParameterPack,
4394 TemplateTypeParmDecl *TTPDecl) {
4395 ID.AddInteger(Depth);
4396 ID.AddInteger(Index);
4397 ID.AddBoolean(ParameterPack);
4398 ID.AddPointer(TTPDecl);
4401 static bool classof(const Type *T) {
4402 return T->getTypeClass() == TemplateTypeParm;
4406 /// Represents the result of substituting a type for a template
4409 /// Within an instantiated template, all template type parameters have
4410 /// been replaced with these. They are used solely to record that a
4411 /// type was originally written as a template type parameter;
4412 /// therefore they are never canonical.
4413 class SubstTemplateTypeParmType : public Type, public llvm::FoldingSetNode {
4414 friend class ASTContext;
4416 // The original type parameter.
4417 const TemplateTypeParmType *Replaced;
4419 SubstTemplateTypeParmType(const TemplateTypeParmType *Param, QualType Canon)
4420 : Type(SubstTemplateTypeParm, Canon, Canon->isDependentType(),
4421 Canon->isInstantiationDependentType(),
4422 Canon->isVariablyModifiedType(),
4423 Canon->containsUnexpandedParameterPack()),
4427 /// Gets the template parameter that was substituted for.
4428 const TemplateTypeParmType *getReplacedParameter() const {
4432 /// Gets the type that was substituted for the template
4434 QualType getReplacementType() const {
4435 return getCanonicalTypeInternal();
4438 bool isSugared() const { return true; }
4439 QualType desugar() const { return getReplacementType(); }
4441 void Profile(llvm::FoldingSetNodeID &ID) {
4442 Profile(ID, getReplacedParameter(), getReplacementType());
4445 static void Profile(llvm::FoldingSetNodeID &ID,
4446 const TemplateTypeParmType *Replaced,
4447 QualType Replacement) {
4448 ID.AddPointer(Replaced);
4449 ID.AddPointer(Replacement.getAsOpaquePtr());
4452 static bool classof(const Type *T) {
4453 return T->getTypeClass() == SubstTemplateTypeParm;
4457 /// Represents the result of substituting a set of types for a template
4458 /// type parameter pack.
4460 /// When a pack expansion in the source code contains multiple parameter packs
4461 /// and those parameter packs correspond to different levels of template
4462 /// parameter lists, this type node is used to represent a template type
4463 /// parameter pack from an outer level, which has already had its argument pack
4464 /// substituted but that still lives within a pack expansion that itself
4465 /// could not be instantiated. When actually performing a substitution into
4466 /// that pack expansion (e.g., when all template parameters have corresponding
4467 /// arguments), this type will be replaced with the \c SubstTemplateTypeParmType
4468 /// at the current pack substitution index.
4469 class SubstTemplateTypeParmPackType : public Type, public llvm::FoldingSetNode {
4470 friend class ASTContext;
4472 /// The original type parameter.
4473 const TemplateTypeParmType *Replaced;
4475 /// A pointer to the set of template arguments that this
4476 /// parameter pack is instantiated with.
4477 const TemplateArgument *Arguments;
4479 /// The number of template arguments in \c Arguments.
4480 unsigned NumArguments;
4482 SubstTemplateTypeParmPackType(const TemplateTypeParmType *Param,
4484 const TemplateArgument &ArgPack);
4487 IdentifierInfo *getIdentifier() const { return Replaced->getIdentifier(); }
4489 /// Gets the template parameter that was substituted for.
4490 const TemplateTypeParmType *getReplacedParameter() const {
4494 bool isSugared() const { return false; }
4495 QualType desugar() const { return QualType(this, 0); }
4497 TemplateArgument getArgumentPack() const;
4499 void Profile(llvm::FoldingSetNodeID &ID);
4500 static void Profile(llvm::FoldingSetNodeID &ID,
4501 const TemplateTypeParmType *Replaced,
4502 const TemplateArgument &ArgPack);
4504 static bool classof(const Type *T) {
4505 return T->getTypeClass() == SubstTemplateTypeParmPack;
4509 /// Common base class for placeholders for types that get replaced by
4510 /// placeholder type deduction: C++11 auto, C++14 decltype(auto), C++17 deduced
4511 /// class template types, and (eventually) constrained type names from the C++
4514 /// These types are usually a placeholder for a deduced type. However, before
4515 /// the initializer is attached, or (usually) if the initializer is
4516 /// type-dependent, there is no deduced type and the type is canonical. In
4517 /// the latter case, it is also a dependent type.
4518 class DeducedType : public Type {
4520 DeducedType(TypeClass TC, QualType DeducedAsType, bool IsDependent,
4521 bool IsInstantiationDependent, bool ContainsParameterPack)
4523 // FIXME: Retain the sugared deduced type?
4524 DeducedAsType.isNull() ? QualType(this, 0)
4525 : DeducedAsType.getCanonicalType(),
4526 IsDependent, IsInstantiationDependent,
4527 /*VariablyModified=*/false, ContainsParameterPack) {
4528 if (!DeducedAsType.isNull()) {
4529 if (DeducedAsType->isDependentType())
4531 if (DeducedAsType->isInstantiationDependentType())
4532 setInstantiationDependent();
4533 if (DeducedAsType->containsUnexpandedParameterPack())
4534 setContainsUnexpandedParameterPack();
4539 bool isSugared() const { return !isCanonicalUnqualified(); }
4540 QualType desugar() const { return getCanonicalTypeInternal(); }
4542 /// Get the type deduced for this placeholder type, or null if it's
4543 /// either not been deduced or was deduced to a dependent type.
4544 QualType getDeducedType() const {
4545 return !isCanonicalUnqualified() ? getCanonicalTypeInternal() : QualType();
4547 bool isDeduced() const {
4548 return !isCanonicalUnqualified() || isDependentType();
4551 static bool classof(const Type *T) {
4552 return T->getTypeClass() == Auto ||
4553 T->getTypeClass() == DeducedTemplateSpecialization;
4557 /// Represents a C++11 auto or C++14 decltype(auto) type.
4558 class AutoType : public DeducedType, public llvm::FoldingSetNode {
4559 friend class ASTContext; // ASTContext creates these
4561 AutoType(QualType DeducedAsType, AutoTypeKeyword Keyword,
4562 bool IsDeducedAsDependent)
4563 : DeducedType(Auto, DeducedAsType, IsDeducedAsDependent,
4564 IsDeducedAsDependent, /*ContainsPack=*/false) {
4565 AutoTypeBits.Keyword = (unsigned)Keyword;
4569 bool isDecltypeAuto() const {
4570 return getKeyword() == AutoTypeKeyword::DecltypeAuto;
4573 AutoTypeKeyword getKeyword() const {
4574 return (AutoTypeKeyword)AutoTypeBits.Keyword;
4577 void Profile(llvm::FoldingSetNodeID &ID) {
4578 Profile(ID, getDeducedType(), getKeyword(), isDependentType());
4581 static void Profile(llvm::FoldingSetNodeID &ID, QualType Deduced,
4582 AutoTypeKeyword Keyword, bool IsDependent) {
4583 ID.AddPointer(Deduced.getAsOpaquePtr());
4584 ID.AddInteger((unsigned)Keyword);
4585 ID.AddBoolean(IsDependent);
4588 static bool classof(const Type *T) {
4589 return T->getTypeClass() == Auto;
4593 /// Represents a C++17 deduced template specialization type.
4594 class DeducedTemplateSpecializationType : public DeducedType,
4595 public llvm::FoldingSetNode {
4596 friend class ASTContext; // ASTContext creates these
4598 /// The name of the template whose arguments will be deduced.
4599 TemplateName Template;
4601 DeducedTemplateSpecializationType(TemplateName Template,
4602 QualType DeducedAsType,
4603 bool IsDeducedAsDependent)
4604 : DeducedType(DeducedTemplateSpecialization, DeducedAsType,
4605 IsDeducedAsDependent || Template.isDependent(),
4606 IsDeducedAsDependent || Template.isInstantiationDependent(),
4607 Template.containsUnexpandedParameterPack()),
4608 Template(Template) {}
4611 /// Retrieve the name of the template that we are deducing.
4612 TemplateName getTemplateName() const { return Template;}
4614 void Profile(llvm::FoldingSetNodeID &ID) {
4615 Profile(ID, getTemplateName(), getDeducedType(), isDependentType());
4618 static void Profile(llvm::FoldingSetNodeID &ID, TemplateName Template,
4619 QualType Deduced, bool IsDependent) {
4620 Template.Profile(ID);
4621 ID.AddPointer(Deduced.getAsOpaquePtr());
4622 ID.AddBoolean(IsDependent);
4625 static bool classof(const Type *T) {
4626 return T->getTypeClass() == DeducedTemplateSpecialization;
4630 /// Represents a type template specialization; the template
4631 /// must be a class template, a type alias template, or a template
4632 /// template parameter. A template which cannot be resolved to one of
4633 /// these, e.g. because it is written with a dependent scope
4634 /// specifier, is instead represented as a
4635 /// @c DependentTemplateSpecializationType.
4637 /// A non-dependent template specialization type is always "sugar",
4638 /// typically for a \c RecordType. For example, a class template
4639 /// specialization type of \c vector<int> will refer to a tag type for
4640 /// the instantiation \c std::vector<int, std::allocator<int>>
4642 /// Template specializations are dependent if either the template or
4643 /// any of the template arguments are dependent, in which case the
4644 /// type may also be canonical.
4646 /// Instances of this type are allocated with a trailing array of
4647 /// TemplateArguments, followed by a QualType representing the
4648 /// non-canonical aliased type when the template is a type alias
4650 class alignas(8) TemplateSpecializationType
4652 public llvm::FoldingSetNode {
4653 friend class ASTContext; // ASTContext creates these
4655 /// The name of the template being specialized. This is
4656 /// either a TemplateName::Template (in which case it is a
4657 /// ClassTemplateDecl*, a TemplateTemplateParmDecl*, or a
4658 /// TypeAliasTemplateDecl*), a
4659 /// TemplateName::SubstTemplateTemplateParmPack, or a
4660 /// TemplateName::SubstTemplateTemplateParm (in which case the
4661 /// replacement must, recursively, be one of these).
4662 TemplateName Template;
4664 /// The number of template arguments named in this class template
4666 unsigned NumArgs : 31;
4668 /// Whether this template specialization type is a substituted type alias.
4669 unsigned TypeAlias : 1;
4671 TemplateSpecializationType(TemplateName T,
4672 ArrayRef<TemplateArgument> Args,
4677 /// Determine whether any of the given template arguments are dependent.
4678 static bool anyDependentTemplateArguments(ArrayRef<TemplateArgumentLoc> Args,
4679 bool &InstantiationDependent);
4681 static bool anyDependentTemplateArguments(const TemplateArgumentListInfo &,
4682 bool &InstantiationDependent);
4684 /// True if this template specialization type matches a current
4685 /// instantiation in the context in which it is found.
4686 bool isCurrentInstantiation() const {
4687 return isa<InjectedClassNameType>(getCanonicalTypeInternal());
4690 /// Determine if this template specialization type is for a type alias
4691 /// template that has been substituted.
4693 /// Nearly every template specialization type whose template is an alias
4694 /// template will be substituted. However, this is not the case when
4695 /// the specialization contains a pack expansion but the template alias
4696 /// does not have a corresponding parameter pack, e.g.,
4699 /// template<typename T, typename U, typename V> struct S;
4700 /// template<typename T, typename U> using A = S<T, int, U>;
4701 /// template<typename... Ts> struct X {
4702 /// typedef A<Ts...> type; // not a type alias
4705 bool isTypeAlias() const { return TypeAlias; }
4707 /// Get the aliased type, if this is a specialization of a type alias
4709 QualType getAliasedType() const {
4710 assert(isTypeAlias() && "not a type alias template specialization");
4711 return *reinterpret_cast<const QualType*>(end());
4714 using iterator = const TemplateArgument *;
4716 iterator begin() const { return getArgs(); }
4717 iterator end() const; // defined inline in TemplateBase.h
4719 /// Retrieve the name of the template that we are specializing.
4720 TemplateName getTemplateName() const { return Template; }
4722 /// Retrieve the template arguments.
4723 const TemplateArgument *getArgs() const {
4724 return reinterpret_cast<const TemplateArgument *>(this + 1);
4727 /// Retrieve the number of template arguments.
4728 unsigned getNumArgs() const { return NumArgs; }
4730 /// Retrieve a specific template argument as a type.
4731 /// \pre \c isArgType(Arg)
4732 const TemplateArgument &getArg(unsigned Idx) const; // in TemplateBase.h
4734 ArrayRef<TemplateArgument> template_arguments() const {
4735 return {getArgs(), NumArgs};
4738 bool isSugared() const {
4739 return !isDependentType() || isCurrentInstantiation() || isTypeAlias();
4742 QualType desugar() const { return getCanonicalTypeInternal(); }
4744 void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Ctx) {
4745 Profile(ID, Template, template_arguments(), Ctx);
4747 getAliasedType().Profile(ID);
4750 static void Profile(llvm::FoldingSetNodeID &ID, TemplateName T,
4751 ArrayRef<TemplateArgument> Args,
4752 const ASTContext &Context);
4754 static bool classof(const Type *T) {
4755 return T->getTypeClass() == TemplateSpecialization;
4759 /// Print a template argument list, including the '<' and '>'
4760 /// enclosing the template arguments.
4761 void printTemplateArgumentList(raw_ostream &OS,
4762 ArrayRef<TemplateArgument> Args,
4763 const PrintingPolicy &Policy);
4765 void printTemplateArgumentList(raw_ostream &OS,
4766 ArrayRef<TemplateArgumentLoc> Args,
4767 const PrintingPolicy &Policy);
4769 void printTemplateArgumentList(raw_ostream &OS,
4770 const TemplateArgumentListInfo &Args,
4771 const PrintingPolicy &Policy);
4773 /// The injected class name of a C++ class template or class
4774 /// template partial specialization. Used to record that a type was
4775 /// spelled with a bare identifier rather than as a template-id; the
4776 /// equivalent for non-templated classes is just RecordType.
4778 /// Injected class name types are always dependent. Template
4779 /// instantiation turns these into RecordTypes.
4781 /// Injected class name types are always canonical. This works
4782 /// because it is impossible to compare an injected class name type
4783 /// with the corresponding non-injected template type, for the same
4784 /// reason that it is impossible to directly compare template
4785 /// parameters from different dependent contexts: injected class name
4786 /// types can only occur within the scope of a particular templated
4787 /// declaration, and within that scope every template specialization
4788 /// will canonicalize to the injected class name (when appropriate
4789 /// according to the rules of the language).
4790 class InjectedClassNameType : public Type {
4791 friend class ASTContext; // ASTContext creates these.
4792 friend class ASTNodeImporter;
4793 friend class ASTReader; // FIXME: ASTContext::getInjectedClassNameType is not
4794 // currently suitable for AST reading, too much
4795 // interdependencies.
4797 CXXRecordDecl *Decl;
4799 /// The template specialization which this type represents.
4801 /// template <class T> class A { ... };
4802 /// this is A<T>, whereas in
4803 /// template <class X, class Y> class A<B<X,Y> > { ... };
4804 /// this is A<B<X,Y> >.
4806 /// It is always unqualified, always a template specialization type,
4807 /// and always dependent.
4808 QualType InjectedType;
4810 InjectedClassNameType(CXXRecordDecl *D, QualType TST)
4811 : Type(InjectedClassName, QualType(), /*Dependent=*/true,
4812 /*InstantiationDependent=*/true,
4813 /*VariablyModified=*/false,
4814 /*ContainsUnexpandedParameterPack=*/false),
4815 Decl(D), InjectedType(TST) {
4816 assert(isa<TemplateSpecializationType>(TST));
4817 assert(!TST.hasQualifiers());
4818 assert(TST->isDependentType());
4822 QualType getInjectedSpecializationType() const { return InjectedType; }
4824 const TemplateSpecializationType *getInjectedTST() const {
4825 return cast<TemplateSpecializationType>(InjectedType.getTypePtr());
4828 TemplateName getTemplateName() const {
4829 return getInjectedTST()->getTemplateName();
4832 CXXRecordDecl *getDecl() const;
4834 bool isSugared() const { return false; }
4835 QualType desugar() const { return QualType(this, 0); }
4837 static bool classof(const Type *T) {
4838 return T->getTypeClass() == InjectedClassName;
4842 /// The kind of a tag type.
4844 /// The "struct" keyword.
4847 /// The "__interface" keyword.
4850 /// The "union" keyword.
4853 /// The "class" keyword.
4856 /// The "enum" keyword.
4860 /// The elaboration keyword that precedes a qualified type name or
4861 /// introduces an elaborated-type-specifier.
4862 enum ElaboratedTypeKeyword {
4863 /// The "struct" keyword introduces the elaborated-type-specifier.
4866 /// The "__interface" keyword introduces the elaborated-type-specifier.
4869 /// The "union" keyword introduces the elaborated-type-specifier.
4872 /// The "class" keyword introduces the elaborated-type-specifier.
4875 /// The "enum" keyword introduces the elaborated-type-specifier.
4878 /// The "typename" keyword precedes the qualified type name, e.g.,
4879 /// \c typename T::type.
4882 /// No keyword precedes the qualified type name.
4886 /// A helper class for Type nodes having an ElaboratedTypeKeyword.
4887 /// The keyword in stored in the free bits of the base class.
4888 /// Also provides a few static helpers for converting and printing
4889 /// elaborated type keyword and tag type kind enumerations.
4890 class TypeWithKeyword : public Type {
4892 TypeWithKeyword(ElaboratedTypeKeyword Keyword, TypeClass tc,
4893 QualType Canonical, bool Dependent,
4894 bool InstantiationDependent, bool VariablyModified,
4895 bool ContainsUnexpandedParameterPack)
4896 : Type(tc, Canonical, Dependent, InstantiationDependent, VariablyModified,
4897 ContainsUnexpandedParameterPack) {
4898 TypeWithKeywordBits.Keyword = Keyword;
4902 ElaboratedTypeKeyword getKeyword() const {
4903 return static_cast<ElaboratedTypeKeyword>(TypeWithKeywordBits.Keyword);
4906 /// Converts a type specifier (DeclSpec::TST) into an elaborated type keyword.
4907 static ElaboratedTypeKeyword getKeywordForTypeSpec(unsigned TypeSpec);
4909 /// Converts a type specifier (DeclSpec::TST) into a tag type kind.
4910 /// It is an error to provide a type specifier which *isn't* a tag kind here.
4911 static TagTypeKind getTagTypeKindForTypeSpec(unsigned TypeSpec);
4913 /// Converts a TagTypeKind into an elaborated type keyword.
4914 static ElaboratedTypeKeyword getKeywordForTagTypeKind(TagTypeKind Tag);
4916 /// Converts an elaborated type keyword into a TagTypeKind.
4917 /// It is an error to provide an elaborated type keyword
4918 /// which *isn't* a tag kind here.
4919 static TagTypeKind getTagTypeKindForKeyword(ElaboratedTypeKeyword Keyword);
4921 static bool KeywordIsTagTypeKind(ElaboratedTypeKeyword Keyword);
4923 static StringRef getKeywordName(ElaboratedTypeKeyword Keyword);
4925 static StringRef getTagTypeKindName(TagTypeKind Kind) {
4926 return getKeywordName(getKeywordForTagTypeKind(Kind));
4929 class CannotCastToThisType {};
4930 static CannotCastToThisType classof(const Type *);
4933 /// Represents a type that was referred to using an elaborated type
4934 /// keyword, e.g., struct S, or via a qualified name, e.g., N::M::type,
4937 /// This type is used to keep track of a type name as written in the
4938 /// source code, including tag keywords and any nested-name-specifiers.
4939 /// The type itself is always "sugar", used to express what was written
4940 /// in the source code but containing no additional semantic information.
4941 class ElaboratedType : public TypeWithKeyword, public llvm::FoldingSetNode {
4942 friend class ASTContext; // ASTContext creates these
4944 /// The nested name specifier containing the qualifier.
4945 NestedNameSpecifier *NNS;
4947 /// The type that this qualified name refers to.
4950 /// The (re)declaration of this tag type owned by this occurrence, or nullptr
4952 TagDecl *OwnedTagDecl;
4954 ElaboratedType(ElaboratedTypeKeyword Keyword, NestedNameSpecifier *NNS,
4955 QualType NamedType, QualType CanonType, TagDecl *OwnedTagDecl)
4956 : TypeWithKeyword(Keyword, Elaborated, CanonType,
4957 NamedType->isDependentType(),
4958 NamedType->isInstantiationDependentType(),
4959 NamedType->isVariablyModifiedType(),
4960 NamedType->containsUnexpandedParameterPack()),
4961 NNS(NNS), NamedType(NamedType), OwnedTagDecl(OwnedTagDecl) {
4962 assert(!(Keyword == ETK_None && NNS == nullptr) &&
4963 "ElaboratedType cannot have elaborated type keyword "
4964 "and name qualifier both null.");
4970 /// Retrieve the qualification on this type.
4971 NestedNameSpecifier *getQualifier() const { return NNS; }
4973 /// Retrieve the type named by the qualified-id.
4974 QualType getNamedType() const { return NamedType; }
4976 /// Remove a single level of sugar.
4977 QualType desugar() const { return getNamedType(); }
4979 /// Returns whether this type directly provides sugar.
4980 bool isSugared() const { return true; }
4982 /// Return the (re)declaration of this type owned by this occurrence of this
4983 /// type, or nullptr if none.
4984 TagDecl *getOwnedTagDecl() const { return OwnedTagDecl; }
4986 void Profile(llvm::FoldingSetNodeID &ID) {
4987 Profile(ID, getKeyword(), NNS, NamedType, OwnedTagDecl);
4990 static void Profile(llvm::FoldingSetNodeID &ID, ElaboratedTypeKeyword Keyword,
4991 NestedNameSpecifier *NNS, QualType NamedType,
4992 TagDecl *OwnedTagDecl) {
4993 ID.AddInteger(Keyword);
4995 NamedType.Profile(ID);
4996 ID.AddPointer(OwnedTagDecl);
4999 static bool classof(const Type *T) {
5000 return T->getTypeClass() == Elaborated;
5004 /// Represents a qualified type name for which the type name is
5007 /// DependentNameType represents a class of dependent types that involve a
5008 /// possibly dependent nested-name-specifier (e.g., "T::") followed by a
5009 /// name of a type. The DependentNameType may start with a "typename" (for a
5010 /// typename-specifier), "class", "struct", "union", or "enum" (for a
5011 /// dependent elaborated-type-specifier), or nothing (in contexts where we
5012 /// know that we must be referring to a type, e.g., in a base class specifier).
5013 /// Typically the nested-name-specifier is dependent, but in MSVC compatibility
5014 /// mode, this type is used with non-dependent names to delay name lookup until
5016 class DependentNameType : public TypeWithKeyword, public llvm::FoldingSetNode {
5017 friend class ASTContext; // ASTContext creates these
5019 /// The nested name specifier containing the qualifier.
5020 NestedNameSpecifier *NNS;
5022 /// The type that this typename specifier refers to.
5023 const IdentifierInfo *Name;
5025 DependentNameType(ElaboratedTypeKeyword Keyword, NestedNameSpecifier *NNS,
5026 const IdentifierInfo *Name, QualType CanonType)
5027 : TypeWithKeyword(Keyword, DependentName, CanonType, /*Dependent=*/true,
5028 /*InstantiationDependent=*/true,
5029 /*VariablyModified=*/false,
5030 NNS->containsUnexpandedParameterPack()),
5031 NNS(NNS), Name(Name) {}
5034 /// Retrieve the qualification on this type.
5035 NestedNameSpecifier *getQualifier() const { return NNS; }
5037 /// Retrieve the type named by the typename specifier as an identifier.
5039 /// This routine will return a non-NULL identifier pointer when the
5040 /// form of the original typename was terminated by an identifier,
5041 /// e.g., "typename T::type".
5042 const IdentifierInfo *getIdentifier() const {
5046 bool isSugared() const { return false; }
5047 QualType desugar() const { return QualType(this, 0); }
5049 void Profile(llvm::FoldingSetNodeID &ID) {
5050 Profile(ID, getKeyword(), NNS, Name);
5053 static void Profile(llvm::FoldingSetNodeID &ID, ElaboratedTypeKeyword Keyword,
5054 NestedNameSpecifier *NNS, const IdentifierInfo *Name) {
5055 ID.AddInteger(Keyword);
5057 ID.AddPointer(Name);
5060 static bool classof(const Type *T) {
5061 return T->getTypeClass() == DependentName;
5065 /// Represents a template specialization type whose template cannot be
5067 /// A<T>::template B<T>
5068 class alignas(8) DependentTemplateSpecializationType
5069 : public TypeWithKeyword,
5070 public llvm::FoldingSetNode {
5071 friend class ASTContext; // ASTContext creates these
5073 /// The nested name specifier containing the qualifier.
5074 NestedNameSpecifier *NNS;
5076 /// The identifier of the template.
5077 const IdentifierInfo *Name;
5079 /// The number of template arguments named in this class template
5083 DependentTemplateSpecializationType(ElaboratedTypeKeyword Keyword,
5084 NestedNameSpecifier *NNS,
5085 const IdentifierInfo *Name,
5086 ArrayRef<TemplateArgument> Args,
5089 const TemplateArgument *getArgBuffer() const {
5090 return reinterpret_cast<const TemplateArgument*>(this+1);
5093 TemplateArgument *getArgBuffer() {
5094 return reinterpret_cast<TemplateArgument*>(this+1);
5098 NestedNameSpecifier *getQualifier() const { return NNS; }
5099 const IdentifierInfo *getIdentifier() const { return Name; }
5101 /// Retrieve the template arguments.
5102 const TemplateArgument *getArgs() const {
5103 return getArgBuffer();
5106 /// Retrieve the number of template arguments.
5107 unsigned getNumArgs() const { return NumArgs; }
5109 const TemplateArgument &getArg(unsigned Idx) const; // in TemplateBase.h
5111 ArrayRef<TemplateArgument> template_arguments() const {
5112 return {getArgs(), NumArgs};
5115 using iterator = const TemplateArgument *;
5117 iterator begin() const { return getArgs(); }
5118 iterator end() const; // inline in TemplateBase.h
5120 bool isSugared() const { return false; }
5121 QualType desugar() const { return QualType(this, 0); }
5123 void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context) {
5124 Profile(ID, Context, getKeyword(), NNS, Name, {getArgs(), NumArgs});
5127 static void Profile(llvm::FoldingSetNodeID &ID,
5128 const ASTContext &Context,
5129 ElaboratedTypeKeyword Keyword,
5130 NestedNameSpecifier *Qualifier,
5131 const IdentifierInfo *Name,
5132 ArrayRef<TemplateArgument> Args);
5134 static bool classof(const Type *T) {
5135 return T->getTypeClass() == DependentTemplateSpecialization;
5139 /// Represents a pack expansion of types.
5141 /// Pack expansions are part of C++11 variadic templates. A pack
5142 /// expansion contains a pattern, which itself contains one or more
5143 /// "unexpanded" parameter packs. When instantiated, a pack expansion
5144 /// produces a series of types, each instantiated from the pattern of
5145 /// the expansion, where the Ith instantiation of the pattern uses the
5146 /// Ith arguments bound to each of the unexpanded parameter packs. The
5147 /// pack expansion is considered to "expand" these unexpanded
5148 /// parameter packs.
5151 /// template<typename ...Types> struct tuple;
5153 /// template<typename ...Types>
5154 /// struct tuple_of_references {
5155 /// typedef tuple<Types&...> type;
5159 /// Here, the pack expansion \c Types&... is represented via a
5160 /// PackExpansionType whose pattern is Types&.
5161 class PackExpansionType : public Type, public llvm::FoldingSetNode {
5162 friend class ASTContext; // ASTContext creates these
5164 /// The pattern of the pack expansion.
5167 /// The number of expansions that this pack expansion will
5168 /// generate when substituted (+1), or indicates that
5170 /// This field will only have a non-zero value when some of the parameter
5171 /// packs that occur within the pattern have been substituted but others have
5173 unsigned NumExpansions;
5175 PackExpansionType(QualType Pattern, QualType Canon,
5176 Optional<unsigned> NumExpansions)
5177 : Type(PackExpansion, Canon, /*Dependent=*/Pattern->isDependentType(),
5178 /*InstantiationDependent=*/true,
5179 /*VariablyModified=*/Pattern->isVariablyModifiedType(),
5180 /*ContainsUnexpandedParameterPack=*/false),
5182 NumExpansions(NumExpansions ? *NumExpansions + 1 : 0) {}
5185 /// Retrieve the pattern of this pack expansion, which is the
5186 /// type that will be repeatedly instantiated when instantiating the
5187 /// pack expansion itself.
5188 QualType getPattern() const { return Pattern; }
5190 /// Retrieve the number of expansions that this pack expansion will
5191 /// generate, if known.
5192 Optional<unsigned> getNumExpansions() const {
5194 return NumExpansions - 1;
5199 bool isSugared() const { return !Pattern->isDependentType(); }
5200 QualType desugar() const { return isSugared() ? Pattern : QualType(this, 0); }
5202 void Profile(llvm::FoldingSetNodeID &ID) {
5203 Profile(ID, getPattern(), getNumExpansions());
5206 static void Profile(llvm::FoldingSetNodeID &ID, QualType Pattern,
5207 Optional<unsigned> NumExpansions) {
5208 ID.AddPointer(Pattern.getAsOpaquePtr());
5209 ID.AddBoolean(NumExpansions.hasValue());
5211 ID.AddInteger(*NumExpansions);
5214 static bool classof(const Type *T) {
5215 return T->getTypeClass() == PackExpansion;
5219 /// This class wraps the list of protocol qualifiers. For types that can
5220 /// take ObjC protocol qualifers, they can subclass this class.
5222 class ObjCProtocolQualifiers {
5224 ObjCProtocolQualifiers() = default;
5226 ObjCProtocolDecl * const *getProtocolStorage() const {
5227 return const_cast<ObjCProtocolQualifiers*>(this)->getProtocolStorage();
5230 ObjCProtocolDecl **getProtocolStorage() {
5231 return static_cast<T*>(this)->getProtocolStorageImpl();
5234 void setNumProtocols(unsigned N) {
5235 static_cast<T*>(this)->setNumProtocolsImpl(N);
5238 void initialize(ArrayRef<ObjCProtocolDecl *> protocols) {
5239 setNumProtocols(protocols.size());
5240 assert(getNumProtocols() == protocols.size() &&
5241 "bitfield overflow in protocol count");
5242 if (!protocols.empty())
5243 memcpy(getProtocolStorage(), protocols.data(),
5244 protocols.size() * sizeof(ObjCProtocolDecl*));
5248 using qual_iterator = ObjCProtocolDecl * const *;
5249 using qual_range = llvm::iterator_range<qual_iterator>;
5251 qual_range quals() const { return qual_range(qual_begin(), qual_end()); }
5252 qual_iterator qual_begin() const { return getProtocolStorage(); }
5253 qual_iterator qual_end() const { return qual_begin() + getNumProtocols(); }
5255 bool qual_empty() const { return getNumProtocols() == 0; }
5257 /// Return the number of qualifying protocols in this type, or 0 if
5259 unsigned getNumProtocols() const {
5260 return static_cast<const T*>(this)->getNumProtocolsImpl();
5263 /// Fetch a protocol by index.
5264 ObjCProtocolDecl *getProtocol(unsigned I) const {
5265 assert(I < getNumProtocols() && "Out-of-range protocol access");
5266 return qual_begin()[I];
5269 /// Retrieve all of the protocol qualifiers.
5270 ArrayRef<ObjCProtocolDecl *> getProtocols() const {
5271 return ArrayRef<ObjCProtocolDecl *>(qual_begin(), getNumProtocols());
5275 /// Represents a type parameter type in Objective C. It can take
5276 /// a list of protocols.
5277 class ObjCTypeParamType : public Type,
5278 public ObjCProtocolQualifiers<ObjCTypeParamType>,
5279 public llvm::FoldingSetNode {
5280 friend class ASTContext;
5281 friend class ObjCProtocolQualifiers<ObjCTypeParamType>;
5283 /// The number of protocols stored on this type.
5284 unsigned NumProtocols : 6;
5286 ObjCTypeParamDecl *OTPDecl;
5288 /// The protocols are stored after the ObjCTypeParamType node. In the
5289 /// canonical type, the list of protocols are sorted alphabetically
5291 ObjCProtocolDecl **getProtocolStorageImpl();
5293 /// Return the number of qualifying protocols in this interface type,
5294 /// or 0 if there are none.
5295 unsigned getNumProtocolsImpl() const {
5296 return NumProtocols;
5299 void setNumProtocolsImpl(unsigned N) {
5303 ObjCTypeParamType(const ObjCTypeParamDecl *D,
5305 ArrayRef<ObjCProtocolDecl *> protocols);
5308 bool isSugared() const { return true; }
5309 QualType desugar() const { return getCanonicalTypeInternal(); }
5311 static bool classof(const Type *T) {
5312 return T->getTypeClass() == ObjCTypeParam;
5315 void Profile(llvm::FoldingSetNodeID &ID);
5316 static void Profile(llvm::FoldingSetNodeID &ID,
5317 const ObjCTypeParamDecl *OTPDecl,
5318 ArrayRef<ObjCProtocolDecl *> protocols);
5320 ObjCTypeParamDecl *getDecl() const { return OTPDecl; }
5323 /// Represents a class type in Objective C.
5325 /// Every Objective C type is a combination of a base type, a set of
5326 /// type arguments (optional, for parameterized classes) and a list of
5329 /// Given the following declarations:
5335 /// 'C' is an ObjCInterfaceType C. It is sugar for an ObjCObjectType
5336 /// with base C and no protocols.
5338 /// 'C<P>' is an unspecialized ObjCObjectType with base C and protocol list [P].
5339 /// 'C<C*>' is a specialized ObjCObjectType with type arguments 'C*' and no
5341 /// 'C<C*><P>' is a specialized ObjCObjectType with base C, type arguments 'C*',
5342 /// and protocol list [P].
5344 /// 'id' is a TypedefType which is sugar for an ObjCObjectPointerType whose
5345 /// pointee is an ObjCObjectType with base BuiltinType::ObjCIdType
5346 /// and no protocols.
5348 /// 'id<P>' is an ObjCObjectPointerType whose pointee is an ObjCObjectType
5349 /// with base BuiltinType::ObjCIdType and protocol list [P]. Eventually
5350 /// this should get its own sugar class to better represent the source.
5351 class ObjCObjectType : public Type,
5352 public ObjCProtocolQualifiers<ObjCObjectType> {
5353 friend class ObjCProtocolQualifiers<ObjCObjectType>;
5355 // ObjCObjectType.NumTypeArgs - the number of type arguments stored
5356 // after the ObjCObjectPointerType node.
5357 // ObjCObjectType.NumProtocols - the number of protocols stored
5358 // after the type arguments of ObjCObjectPointerType node.
5360 // These protocols are those written directly on the type. If
5361 // protocol qualifiers ever become additive, the iterators will need
5362 // to get kindof complicated.
5364 // In the canonical object type, these are sorted alphabetically
5367 /// Either a BuiltinType or an InterfaceType or sugar for either.
5370 /// Cached superclass type.
5371 mutable llvm::PointerIntPair<const ObjCObjectType *, 1, bool>
5372 CachedSuperClassType;
5374 QualType *getTypeArgStorage();
5375 const QualType *getTypeArgStorage() const {
5376 return const_cast<ObjCObjectType *>(this)->getTypeArgStorage();
5379 ObjCProtocolDecl **getProtocolStorageImpl();
5380 /// Return the number of qualifying protocols in this interface type,
5381 /// or 0 if there are none.
5382 unsigned getNumProtocolsImpl() const {
5383 return ObjCObjectTypeBits.NumProtocols;
5385 void setNumProtocolsImpl(unsigned N) {
5386 ObjCObjectTypeBits.NumProtocols = N;
5390 enum Nonce_ObjCInterface { Nonce_ObjCInterface };
5392 ObjCObjectType(QualType Canonical, QualType Base,
5393 ArrayRef<QualType> typeArgs,
5394 ArrayRef<ObjCProtocolDecl *> protocols,
5397 ObjCObjectType(enum Nonce_ObjCInterface)
5398 : Type(ObjCInterface, QualType(), false, false, false, false),
5399 BaseType(QualType(this_(), 0)) {
5400 ObjCObjectTypeBits.NumProtocols = 0;
5401 ObjCObjectTypeBits.NumTypeArgs = 0;
5402 ObjCObjectTypeBits.IsKindOf = 0;
5405 void computeSuperClassTypeSlow() const;
5408 /// Gets the base type of this object type. This is always (possibly
5409 /// sugar for) one of:
5410 /// - the 'id' builtin type (as opposed to the 'id' type visible to the
5411 /// user, which is a typedef for an ObjCObjectPointerType)
5412 /// - the 'Class' builtin type (same caveat)
5413 /// - an ObjCObjectType (currently always an ObjCInterfaceType)
5414 QualType getBaseType() const { return BaseType; }
5416 bool isObjCId() const {
5417 return getBaseType()->isSpecificBuiltinType(BuiltinType::ObjCId);
5420 bool isObjCClass() const {
5421 return getBaseType()->isSpecificBuiltinType(BuiltinType::ObjCClass);
5424 bool isObjCUnqualifiedId() const { return qual_empty() && isObjCId(); }
5425 bool isObjCUnqualifiedClass() const { return qual_empty() && isObjCClass(); }
5426 bool isObjCUnqualifiedIdOrClass() const {
5427 if (!qual_empty()) return false;
5428 if (const BuiltinType *T = getBaseType()->getAs<BuiltinType>())
5429 return T->getKind() == BuiltinType::ObjCId ||
5430 T->getKind() == BuiltinType::ObjCClass;
5433 bool isObjCQualifiedId() const { return !qual_empty() && isObjCId(); }
5434 bool isObjCQualifiedClass() const { return !qual_empty() && isObjCClass(); }
5436 /// Gets the interface declaration for this object type, if the base type
5437 /// really is an interface.
5438 ObjCInterfaceDecl *getInterface() const;
5440 /// Determine whether this object type is "specialized", meaning
5441 /// that it has type arguments.
5442 bool isSpecialized() const;
5444 /// Determine whether this object type was written with type arguments.
5445 bool isSpecializedAsWritten() const {
5446 return ObjCObjectTypeBits.NumTypeArgs > 0;
5449 /// Determine whether this object type is "unspecialized", meaning
5450 /// that it has no type arguments.
5451 bool isUnspecialized() const { return !isSpecialized(); }
5453 /// Determine whether this object type is "unspecialized" as
5454 /// written, meaning that it has no type arguments.
5455 bool isUnspecializedAsWritten() const { return !isSpecializedAsWritten(); }
5457 /// Retrieve the type arguments of this object type (semantically).
5458 ArrayRef<QualType> getTypeArgs() const;
5460 /// Retrieve the type arguments of this object type as they were
5462 ArrayRef<QualType> getTypeArgsAsWritten() const {
5463 return llvm::makeArrayRef(getTypeArgStorage(),
5464 ObjCObjectTypeBits.NumTypeArgs);
5467 /// Whether this is a "__kindof" type as written.
5468 bool isKindOfTypeAsWritten() const { return ObjCObjectTypeBits.IsKindOf; }
5470 /// Whether this ia a "__kindof" type (semantically).
5471 bool isKindOfType() const;
5473 /// Retrieve the type of the superclass of this object type.
5475 /// This operation substitutes any type arguments into the
5476 /// superclass of the current class type, potentially producing a
5477 /// specialization of the superclass type. Produces a null type if
5478 /// there is no superclass.
5479 QualType getSuperClassType() const {
5480 if (!CachedSuperClassType.getInt())
5481 computeSuperClassTypeSlow();
5483 assert(CachedSuperClassType.getInt() && "Superclass not set?");
5484 return QualType(CachedSuperClassType.getPointer(), 0);
5487 /// Strip off the Objective-C "kindof" type and (with it) any
5488 /// protocol qualifiers.
5489 QualType stripObjCKindOfTypeAndQuals(const ASTContext &ctx) const;
5491 bool isSugared() const { return false; }
5492 QualType desugar() const { return QualType(this, 0); }
5494 static bool classof(const Type *T) {
5495 return T->getTypeClass() == ObjCObject ||
5496 T->getTypeClass() == ObjCInterface;
5500 /// A class providing a concrete implementation
5501 /// of ObjCObjectType, so as to not increase the footprint of
5502 /// ObjCInterfaceType. Code outside of ASTContext and the core type
5503 /// system should not reference this type.
5504 class ObjCObjectTypeImpl : public ObjCObjectType, public llvm::FoldingSetNode {
5505 friend class ASTContext;
5507 // If anyone adds fields here, ObjCObjectType::getProtocolStorage()
5508 // will need to be modified.
5510 ObjCObjectTypeImpl(QualType Canonical, QualType Base,
5511 ArrayRef<QualType> typeArgs,
5512 ArrayRef<ObjCProtocolDecl *> protocols,
5514 : ObjCObjectType(Canonical, Base, typeArgs, protocols, isKindOf) {}
5517 void Profile(llvm::FoldingSetNodeID &ID);
5518 static void Profile(llvm::FoldingSetNodeID &ID,
5520 ArrayRef<QualType> typeArgs,
5521 ArrayRef<ObjCProtocolDecl *> protocols,
5525 inline QualType *ObjCObjectType::getTypeArgStorage() {
5526 return reinterpret_cast<QualType *>(static_cast<ObjCObjectTypeImpl*>(this)+1);
5529 inline ObjCProtocolDecl **ObjCObjectType::getProtocolStorageImpl() {
5530 return reinterpret_cast<ObjCProtocolDecl**>(
5531 getTypeArgStorage() + ObjCObjectTypeBits.NumTypeArgs);
5534 inline ObjCProtocolDecl **ObjCTypeParamType::getProtocolStorageImpl() {
5535 return reinterpret_cast<ObjCProtocolDecl**>(
5536 static_cast<ObjCTypeParamType*>(this)+1);
5539 /// Interfaces are the core concept in Objective-C for object oriented design.
5540 /// They basically correspond to C++ classes. There are two kinds of interface
5541 /// types: normal interfaces like `NSString`, and qualified interfaces, which
5542 /// are qualified with a protocol list like `NSString<NSCopyable, NSAmazing>`.
5544 /// ObjCInterfaceType guarantees the following properties when considered
5545 /// as a subtype of its superclass, ObjCObjectType:
5546 /// - There are no protocol qualifiers. To reinforce this, code which
5547 /// tries to invoke the protocol methods via an ObjCInterfaceType will
5548 /// fail to compile.
5549 /// - It is its own base type. That is, if T is an ObjCInterfaceType*,
5550 /// T->getBaseType() == QualType(T, 0).
5551 class ObjCInterfaceType : public ObjCObjectType {
5552 friend class ASTContext; // ASTContext creates these.
5553 friend class ASTReader;
5554 friend class ObjCInterfaceDecl;
5556 mutable ObjCInterfaceDecl *Decl;
5558 ObjCInterfaceType(const ObjCInterfaceDecl *D)
5559 : ObjCObjectType(Nonce_ObjCInterface),
5560 Decl(const_cast<ObjCInterfaceDecl*>(D)) {}
5563 /// Get the declaration of this interface.
5564 ObjCInterfaceDecl *getDecl() const { return Decl; }
5566 bool isSugared() const { return false; }
5567 QualType desugar() const { return QualType(this, 0); }
5569 static bool classof(const Type *T) {
5570 return T->getTypeClass() == ObjCInterface;
5573 // Nonsense to "hide" certain members of ObjCObjectType within this
5574 // class. People asking for protocols on an ObjCInterfaceType are
5575 // not going to get what they want: ObjCInterfaceTypes are
5576 // guaranteed to have no protocols.
5586 inline ObjCInterfaceDecl *ObjCObjectType::getInterface() const {
5587 QualType baseType = getBaseType();
5588 while (const auto *ObjT = baseType->getAs<ObjCObjectType>()) {
5589 if (const auto *T = dyn_cast<ObjCInterfaceType>(ObjT))
5590 return T->getDecl();
5592 baseType = ObjT->getBaseType();
5598 /// Represents a pointer to an Objective C object.
5600 /// These are constructed from pointer declarators when the pointee type is
5601 /// an ObjCObjectType (or sugar for one). In addition, the 'id' and 'Class'
5602 /// types are typedefs for these, and the protocol-qualified types 'id<P>'
5603 /// and 'Class<P>' are translated into these.
5605 /// Pointers to pointers to Objective C objects are still PointerTypes;
5606 /// only the first level of pointer gets it own type implementation.
5607 class ObjCObjectPointerType : public Type, public llvm::FoldingSetNode {
5608 friend class ASTContext; // ASTContext creates these.
5610 QualType PointeeType;
5612 ObjCObjectPointerType(QualType Canonical, QualType Pointee)
5613 : Type(ObjCObjectPointer, Canonical,
5614 Pointee->isDependentType(),
5615 Pointee->isInstantiationDependentType(),
5616 Pointee->isVariablyModifiedType(),
5617 Pointee->containsUnexpandedParameterPack()),
5618 PointeeType(Pointee) {}
5621 /// Gets the type pointed to by this ObjC pointer.
5622 /// The result will always be an ObjCObjectType or sugar thereof.
5623 QualType getPointeeType() const { return PointeeType; }
5625 /// Gets the type pointed to by this ObjC pointer. Always returns non-null.
5627 /// This method is equivalent to getPointeeType() except that
5628 /// it discards any typedefs (or other sugar) between this
5629 /// type and the "outermost" object type. So for:
5631 /// \@class A; \@protocol P; \@protocol Q;
5632 /// typedef A<P> AP;
5634 /// typedef A1<P> A1P;
5635 /// typedef A1P<Q> A1PQ;
5637 /// For 'A*', getObjectType() will return 'A'.
5638 /// For 'A<P>*', getObjectType() will return 'A<P>'.
5639 /// For 'AP*', getObjectType() will return 'A<P>'.
5640 /// For 'A1*', getObjectType() will return 'A'.
5641 /// For 'A1<P>*', getObjectType() will return 'A1<P>'.
5642 /// For 'A1P*', getObjectType() will return 'A1<P>'.
5643 /// For 'A1PQ*', getObjectType() will return 'A1<Q>', because
5644 /// adding protocols to a protocol-qualified base discards the
5645 /// old qualifiers (for now). But if it didn't, getObjectType()
5646 /// would return 'A1P<Q>' (and we'd have to make iterating over
5647 /// qualifiers more complicated).
5648 const ObjCObjectType *getObjectType() const {
5649 return PointeeType->castAs<ObjCObjectType>();
5652 /// If this pointer points to an Objective C
5653 /// \@interface type, gets the type for that interface. Any protocol
5654 /// qualifiers on the interface are ignored.
5656 /// \return null if the base type for this pointer is 'id' or 'Class'
5657 const ObjCInterfaceType *getInterfaceType() const;
5659 /// If this pointer points to an Objective \@interface
5660 /// type, gets the declaration for that interface.
5662 /// \return null if the base type for this pointer is 'id' or 'Class'
5663 ObjCInterfaceDecl *getInterfaceDecl() const {
5664 return getObjectType()->getInterface();
5667 /// True if this is equivalent to the 'id' type, i.e. if
5668 /// its object type is the primitive 'id' type with no protocols.
5669 bool isObjCIdType() const {
5670 return getObjectType()->isObjCUnqualifiedId();
5673 /// True if this is equivalent to the 'Class' type,
5674 /// i.e. if its object tive is the primitive 'Class' type with no protocols.
5675 bool isObjCClassType() const {
5676 return getObjectType()->isObjCUnqualifiedClass();
5679 /// True if this is equivalent to the 'id' or 'Class' type,
5680 bool isObjCIdOrClassType() const {
5681 return getObjectType()->isObjCUnqualifiedIdOrClass();
5684 /// True if this is equivalent to 'id<P>' for some non-empty set of
5686 bool isObjCQualifiedIdType() const {
5687 return getObjectType()->isObjCQualifiedId();
5690 /// True if this is equivalent to 'Class<P>' for some non-empty set of
5692 bool isObjCQualifiedClassType() const {
5693 return getObjectType()->isObjCQualifiedClass();
5696 /// Whether this is a "__kindof" type.
5697 bool isKindOfType() const { return getObjectType()->isKindOfType(); }
5699 /// Whether this type is specialized, meaning that it has type arguments.
5700 bool isSpecialized() const { return getObjectType()->isSpecialized(); }
5702 /// Whether this type is specialized, meaning that it has type arguments.
5703 bool isSpecializedAsWritten() const {
5704 return getObjectType()->isSpecializedAsWritten();
5707 /// Whether this type is unspecialized, meaning that is has no type arguments.
5708 bool isUnspecialized() const { return getObjectType()->isUnspecialized(); }
5710 /// Determine whether this object type is "unspecialized" as
5711 /// written, meaning that it has no type arguments.
5712 bool isUnspecializedAsWritten() const { return !isSpecializedAsWritten(); }
5714 /// Retrieve the type arguments for this type.
5715 ArrayRef<QualType> getTypeArgs() const {
5716 return getObjectType()->getTypeArgs();
5719 /// Retrieve the type arguments for this type.
5720 ArrayRef<QualType> getTypeArgsAsWritten() const {
5721 return getObjectType()->getTypeArgsAsWritten();
5724 /// An iterator over the qualifiers on the object type. Provided
5725 /// for convenience. This will always iterate over the full set of
5726 /// protocols on a type, not just those provided directly.
5727 using qual_iterator = ObjCObjectType::qual_iterator;
5728 using qual_range = llvm::iterator_range<qual_iterator>;
5730 qual_range quals() const { return qual_range(qual_begin(), qual_end()); }
5732 qual_iterator qual_begin() const {
5733 return getObjectType()->qual_begin();
5736 qual_iterator qual_end() const {
5737 return getObjectType()->qual_end();
5740 bool qual_empty() const { return getObjectType()->qual_empty(); }
5742 /// Return the number of qualifying protocols on the object type.
5743 unsigned getNumProtocols() const {
5744 return getObjectType()->getNumProtocols();
5747 /// Retrieve a qualifying protocol by index on the object type.
5748 ObjCProtocolDecl *getProtocol(unsigned I) const {
5749 return getObjectType()->getProtocol(I);
5752 bool isSugared() const { return false; }
5753 QualType desugar() const { return QualType(this, 0); }
5755 /// Retrieve the type of the superclass of this object pointer type.
5757 /// This operation substitutes any type arguments into the
5758 /// superclass of the current class type, potentially producing a
5759 /// pointer to a specialization of the superclass type. Produces a
5760 /// null type if there is no superclass.
5761 QualType getSuperClassType() const;
5763 /// Strip off the Objective-C "kindof" type and (with it) any
5764 /// protocol qualifiers.
5765 const ObjCObjectPointerType *stripObjCKindOfTypeAndQuals(
5766 const ASTContext &ctx) const;
5768 void Profile(llvm::FoldingSetNodeID &ID) {
5769 Profile(ID, getPointeeType());
5772 static void Profile(llvm::FoldingSetNodeID &ID, QualType T) {
5773 ID.AddPointer(T.getAsOpaquePtr());
5776 static bool classof(const Type *T) {
5777 return T->getTypeClass() == ObjCObjectPointer;
5781 class AtomicType : public Type, public llvm::FoldingSetNode {
5782 friend class ASTContext; // ASTContext creates these.
5786 AtomicType(QualType ValTy, QualType Canonical)
5787 : Type(Atomic, Canonical, ValTy->isDependentType(),
5788 ValTy->isInstantiationDependentType(),
5789 ValTy->isVariablyModifiedType(),
5790 ValTy->containsUnexpandedParameterPack()),
5794 /// Gets the type contained by this atomic type, i.e.
5795 /// the type returned by performing an atomic load of this atomic type.
5796 QualType getValueType() const { return ValueType; }
5798 bool isSugared() const { return false; }
5799 QualType desugar() const { return QualType(this, 0); }
5801 void Profile(llvm::FoldingSetNodeID &ID) {
5802 Profile(ID, getValueType());
5805 static void Profile(llvm::FoldingSetNodeID &ID, QualType T) {
5806 ID.AddPointer(T.getAsOpaquePtr());
5809 static bool classof(const Type *T) {
5810 return T->getTypeClass() == Atomic;
5814 /// PipeType - OpenCL20.
5815 class PipeType : public Type, public llvm::FoldingSetNode {
5816 friend class ASTContext; // ASTContext creates these.
5818 QualType ElementType;
5821 PipeType(QualType elemType, QualType CanonicalPtr, bool isRead)
5822 : Type(Pipe, CanonicalPtr, elemType->isDependentType(),
5823 elemType->isInstantiationDependentType(),
5824 elemType->isVariablyModifiedType(),
5825 elemType->containsUnexpandedParameterPack()),
5826 ElementType(elemType), isRead(isRead) {}
5829 QualType getElementType() const { return ElementType; }
5831 bool isSugared() const { return false; }
5833 QualType desugar() const { return QualType(this, 0); }
5835 void Profile(llvm::FoldingSetNodeID &ID) {
5836 Profile(ID, getElementType(), isReadOnly());
5839 static void Profile(llvm::FoldingSetNodeID &ID, QualType T, bool isRead) {
5840 ID.AddPointer(T.getAsOpaquePtr());
5841 ID.AddBoolean(isRead);
5844 static bool classof(const Type *T) {
5845 return T->getTypeClass() == Pipe;
5848 bool isReadOnly() const { return isRead; }
5851 /// A qualifier set is used to build a set of qualifiers.
5852 class QualifierCollector : public Qualifiers {
5854 QualifierCollector(Qualifiers Qs = Qualifiers()) : Qualifiers(Qs) {}
5856 /// Collect any qualifiers on the given type and return an
5857 /// unqualified type. The qualifiers are assumed to be consistent
5858 /// with those already in the type.
5859 const Type *strip(QualType type) {
5860 addFastQualifiers(type.getLocalFastQualifiers());
5861 if (!type.hasLocalNonFastQualifiers())
5862 return type.getTypePtrUnsafe();
5864 const ExtQuals *extQuals = type.getExtQualsUnsafe();
5865 addConsistentQualifiers(extQuals->getQualifiers());
5866 return extQuals->getBaseType();
5869 /// Apply the collected qualifiers to the given type.
5870 QualType apply(const ASTContext &Context, QualType QT) const;
5872 /// Apply the collected qualifiers to the given type.
5873 QualType apply(const ASTContext &Context, const Type* T) const;
5876 // Inline function definitions.
5878 inline SplitQualType SplitQualType::getSingleStepDesugaredType() const {
5879 SplitQualType desugar =
5880 Ty->getLocallyUnqualifiedSingleStepDesugaredType().split();
5881 desugar.Quals.addConsistentQualifiers(Quals);
5885 inline const Type *QualType::getTypePtr() const {
5886 return getCommonPtr()->BaseType;
5889 inline const Type *QualType::getTypePtrOrNull() const {
5890 return (isNull() ? nullptr : getCommonPtr()->BaseType);
5893 inline SplitQualType QualType::split() const {
5894 if (!hasLocalNonFastQualifiers())
5895 return SplitQualType(getTypePtrUnsafe(),
5896 Qualifiers::fromFastMask(getLocalFastQualifiers()));
5898 const ExtQuals *eq = getExtQualsUnsafe();
5899 Qualifiers qs = eq->getQualifiers();
5900 qs.addFastQualifiers(getLocalFastQualifiers());
5901 return SplitQualType(eq->getBaseType(), qs);
5904 inline Qualifiers QualType::getLocalQualifiers() const {
5906 if (hasLocalNonFastQualifiers())
5907 Quals = getExtQualsUnsafe()->getQualifiers();
5908 Quals.addFastQualifiers(getLocalFastQualifiers());
5912 inline Qualifiers QualType::getQualifiers() const {
5913 Qualifiers quals = getCommonPtr()->CanonicalType.getLocalQualifiers();
5914 quals.addFastQualifiers(getLocalFastQualifiers());
5918 inline unsigned QualType::getCVRQualifiers() const {
5919 unsigned cvr = getCommonPtr()->CanonicalType.getLocalCVRQualifiers();
5920 cvr |= getLocalCVRQualifiers();
5924 inline QualType QualType::getCanonicalType() const {
5925 QualType canon = getCommonPtr()->CanonicalType;
5926 return canon.withFastQualifiers(getLocalFastQualifiers());
5929 inline bool QualType::isCanonical() const {
5930 return getTypePtr()->isCanonicalUnqualified();
5933 inline bool QualType::isCanonicalAsParam() const {
5934 if (!isCanonical()) return false;
5935 if (hasLocalQualifiers()) return false;
5937 const Type *T = getTypePtr();
5938 if (T->isVariablyModifiedType() && T->hasSizedVLAType())
5941 return !isa<FunctionType>(T) && !isa<ArrayType>(T);
5944 inline bool QualType::isConstQualified() const {
5945 return isLocalConstQualified() ||
5946 getCommonPtr()->CanonicalType.isLocalConstQualified();
5949 inline bool QualType::isRestrictQualified() const {
5950 return isLocalRestrictQualified() ||
5951 getCommonPtr()->CanonicalType.isLocalRestrictQualified();
5955 inline bool QualType::isVolatileQualified() const {
5956 return isLocalVolatileQualified() ||
5957 getCommonPtr()->CanonicalType.isLocalVolatileQualified();
5960 inline bool QualType::hasQualifiers() const {
5961 return hasLocalQualifiers() ||
5962 getCommonPtr()->CanonicalType.hasLocalQualifiers();
5965 inline QualType QualType::getUnqualifiedType() const {
5966 if (!getTypePtr()->getCanonicalTypeInternal().hasLocalQualifiers())
5967 return QualType(getTypePtr(), 0);
5969 return QualType(getSplitUnqualifiedTypeImpl(*this).Ty, 0);
5972 inline SplitQualType QualType::getSplitUnqualifiedType() const {
5973 if (!getTypePtr()->getCanonicalTypeInternal().hasLocalQualifiers())
5976 return getSplitUnqualifiedTypeImpl(*this);
5979 inline void QualType::removeLocalConst() {
5980 removeLocalFastQualifiers(Qualifiers::Const);
5983 inline void QualType::removeLocalRestrict() {
5984 removeLocalFastQualifiers(Qualifiers::Restrict);
5987 inline void QualType::removeLocalVolatile() {
5988 removeLocalFastQualifiers(Qualifiers::Volatile);
5991 inline void QualType::removeLocalCVRQualifiers(unsigned Mask) {
5992 assert(!(Mask & ~Qualifiers::CVRMask) && "mask has non-CVR bits");
5993 static_assert((int)Qualifiers::CVRMask == (int)Qualifiers::FastMask,
5994 "Fast bits differ from CVR bits!");
5996 // Fast path: we don't need to touch the slow qualifiers.
5997 removeLocalFastQualifiers(Mask);
6000 /// Return the address space of this type.
6001 inline LangAS QualType::getAddressSpace() const {
6002 return getQualifiers().getAddressSpace();
6005 /// Return the gc attribute of this type.
6006 inline Qualifiers::GC QualType::getObjCGCAttr() const {
6007 return getQualifiers().getObjCGCAttr();
6010 inline FunctionType::ExtInfo getFunctionExtInfo(const Type &t) {
6011 if (const auto *PT = t.getAs<PointerType>()) {
6012 if (const auto *FT = PT->getPointeeType()->getAs<FunctionType>())
6013 return FT->getExtInfo();
6014 } else if (const auto *FT = t.getAs<FunctionType>())
6015 return FT->getExtInfo();
6017 return FunctionType::ExtInfo();
6020 inline FunctionType::ExtInfo getFunctionExtInfo(QualType t) {
6021 return getFunctionExtInfo(*t);
6024 /// Determine whether this type is more
6025 /// qualified than the Other type. For example, "const volatile int"
6026 /// is more qualified than "const int", "volatile int", and
6027 /// "int". However, it is not more qualified than "const volatile
6029 inline bool QualType::isMoreQualifiedThan(QualType other) const {
6030 Qualifiers MyQuals = getQualifiers();
6031 Qualifiers OtherQuals = other.getQualifiers();
6032 return (MyQuals != OtherQuals && MyQuals.compatiblyIncludes(OtherQuals));
6035 /// Determine whether this type is at last
6036 /// as qualified as the Other type. For example, "const volatile
6037 /// int" is at least as qualified as "const int", "volatile int",
6038 /// "int", and "const volatile int".
6039 inline bool QualType::isAtLeastAsQualifiedAs(QualType other) const {
6040 Qualifiers OtherQuals = other.getQualifiers();
6042 // Ignore __unaligned qualifier if this type is a void.
6043 if (getUnqualifiedType()->isVoidType())
6044 OtherQuals.removeUnaligned();
6046 return getQualifiers().compatiblyIncludes(OtherQuals);
6049 /// If Type is a reference type (e.g., const
6050 /// int&), returns the type that the reference refers to ("const
6051 /// int"). Otherwise, returns the type itself. This routine is used
6052 /// throughout Sema to implement C++ 5p6:
6054 /// If an expression initially has the type "reference to T" (8.3.2,
6055 /// 8.5.3), the type is adjusted to "T" prior to any further
6056 /// analysis, the expression designates the object or function
6057 /// denoted by the reference, and the expression is an lvalue.
6058 inline QualType QualType::getNonReferenceType() const {
6059 if (const auto *RefType = (*this)->getAs<ReferenceType>())
6060 return RefType->getPointeeType();
6065 inline bool QualType::isCForbiddenLValueType() const {
6066 return ((getTypePtr()->isVoidType() && !hasQualifiers()) ||
6067 getTypePtr()->isFunctionType());
6070 /// Tests whether the type is categorized as a fundamental type.
6072 /// \returns True for types specified in C++0x [basic.fundamental].
6073 inline bool Type::isFundamentalType() const {
6074 return isVoidType() ||
6075 // FIXME: It's really annoying that we don't have an
6076 // 'isArithmeticType()' which agrees with the standard definition.
6077 (isArithmeticType() && !isEnumeralType());
6080 /// Tests whether the type is categorized as a compound type.
6082 /// \returns True for types specified in C++0x [basic.compound].
6083 inline bool Type::isCompoundType() const {
6084 // C++0x [basic.compound]p1:
6085 // Compound types can be constructed in the following ways:
6086 // -- arrays of objects of a given type [...];
6087 return isArrayType() ||
6088 // -- functions, which have parameters of given types [...];
6090 // -- pointers to void or objects or functions [...];
6092 // -- references to objects or functions of a given type. [...]
6093 isReferenceType() ||
6094 // -- classes containing a sequence of objects of various types, [...];
6096 // -- unions, which are classes capable of containing objects of different
6097 // types at different times;
6099 // -- enumerations, which comprise a set of named constant values. [...];
6101 // -- pointers to non-static class members, [...].
6102 isMemberPointerType();
6105 inline bool Type::isFunctionType() const {
6106 return isa<FunctionType>(CanonicalType);
6109 inline bool Type::isPointerType() const {
6110 return isa<PointerType>(CanonicalType);
6113 inline bool Type::isAnyPointerType() const {
6114 return isPointerType() || isObjCObjectPointerType();
6117 inline bool Type::isBlockPointerType() const {
6118 return isa<BlockPointerType>(CanonicalType);
6121 inline bool Type::isReferenceType() const {
6122 return isa<ReferenceType>(CanonicalType);
6125 inline bool Type::isLValueReferenceType() const {
6126 return isa<LValueReferenceType>(CanonicalType);
6129 inline bool Type::isRValueReferenceType() const {
6130 return isa<RValueReferenceType>(CanonicalType);
6133 inline bool Type::isFunctionPointerType() const {
6134 if (const auto *T = getAs<PointerType>())
6135 return T->getPointeeType()->isFunctionType();
6140 inline bool Type::isMemberPointerType() const {
6141 return isa<MemberPointerType>(CanonicalType);
6144 inline bool Type::isMemberFunctionPointerType() const {
6145 if (const auto *T = getAs<MemberPointerType>())
6146 return T->isMemberFunctionPointer();
6151 inline bool Type::isMemberDataPointerType() const {
6152 if (const auto *T = getAs<MemberPointerType>())
6153 return T->isMemberDataPointer();
6158 inline bool Type::isArrayType() const {
6159 return isa<ArrayType>(CanonicalType);
6162 inline bool Type::isConstantArrayType() const {
6163 return isa<ConstantArrayType>(CanonicalType);
6166 inline bool Type::isIncompleteArrayType() const {
6167 return isa<IncompleteArrayType>(CanonicalType);
6170 inline bool Type::isVariableArrayType() const {
6171 return isa<VariableArrayType>(CanonicalType);
6174 inline bool Type::isDependentSizedArrayType() const {
6175 return isa<DependentSizedArrayType>(CanonicalType);
6178 inline bool Type::isBuiltinType() const {
6179 return isa<BuiltinType>(CanonicalType);
6182 inline bool Type::isRecordType() const {
6183 return isa<RecordType>(CanonicalType);
6186 inline bool Type::isEnumeralType() const {
6187 return isa<EnumType>(CanonicalType);
6190 inline bool Type::isAnyComplexType() const {
6191 return isa<ComplexType>(CanonicalType);
6194 inline bool Type::isVectorType() const {
6195 return isa<VectorType>(CanonicalType);
6198 inline bool Type::isExtVectorType() const {
6199 return isa<ExtVectorType>(CanonicalType);
6202 inline bool Type::isDependentAddressSpaceType() const {
6203 return isa<DependentAddressSpaceType>(CanonicalType);
6206 inline bool Type::isObjCObjectPointerType() const {
6207 return isa<ObjCObjectPointerType>(CanonicalType);
6210 inline bool Type::isObjCObjectType() const {
6211 return isa<ObjCObjectType>(CanonicalType);
6214 inline bool Type::isObjCObjectOrInterfaceType() const {
6215 return isa<ObjCInterfaceType>(CanonicalType) ||
6216 isa<ObjCObjectType>(CanonicalType);
6219 inline bool Type::isAtomicType() const {
6220 return isa<AtomicType>(CanonicalType);
6223 inline bool Type::isObjCQualifiedIdType() const {
6224 if (const auto *OPT = getAs<ObjCObjectPointerType>())
6225 return OPT->isObjCQualifiedIdType();
6229 inline bool Type::isObjCQualifiedClassType() const {
6230 if (const auto *OPT = getAs<ObjCObjectPointerType>())
6231 return OPT->isObjCQualifiedClassType();
6235 inline bool Type::isObjCIdType() const {
6236 if (const auto *OPT = getAs<ObjCObjectPointerType>())
6237 return OPT->isObjCIdType();
6241 inline bool Type::isObjCClassType() const {
6242 if (const auto *OPT = getAs<ObjCObjectPointerType>())
6243 return OPT->isObjCClassType();
6247 inline bool Type::isObjCSelType() const {
6248 if (const auto *OPT = getAs<PointerType>())
6249 return OPT->getPointeeType()->isSpecificBuiltinType(BuiltinType::ObjCSel);
6253 inline bool Type::isObjCBuiltinType() const {
6254 return isObjCIdType() || isObjCClassType() || isObjCSelType();
6257 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
6258 inline bool Type::is##Id##Type() const { \
6259 return isSpecificBuiltinType(BuiltinType::Id); \
6261 #include "clang/Basic/OpenCLImageTypes.def"
6263 inline bool Type::isSamplerT() const {
6264 return isSpecificBuiltinType(BuiltinType::OCLSampler);
6267 inline bool Type::isEventT() const {
6268 return isSpecificBuiltinType(BuiltinType::OCLEvent);
6271 inline bool Type::isClkEventT() const {
6272 return isSpecificBuiltinType(BuiltinType::OCLClkEvent);
6275 inline bool Type::isQueueT() const {
6276 return isSpecificBuiltinType(BuiltinType::OCLQueue);
6279 inline bool Type::isReserveIDT() const {
6280 return isSpecificBuiltinType(BuiltinType::OCLReserveID);
6283 inline bool Type::isImageType() const {
6284 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) is##Id##Type() ||
6286 #include "clang/Basic/OpenCLImageTypes.def"
6287 false; // end boolean or operation
6290 inline bool Type::isPipeType() const {
6291 return isa<PipeType>(CanonicalType);
6294 inline bool Type::isOpenCLSpecificType() const {
6295 return isSamplerT() || isEventT() || isImageType() || isClkEventT() ||
6296 isQueueT() || isReserveIDT() || isPipeType();
6299 inline bool Type::isTemplateTypeParmType() const {
6300 return isa<TemplateTypeParmType>(CanonicalType);
6303 inline bool Type::isSpecificBuiltinType(unsigned K) const {
6304 if (const BuiltinType *BT = getAs<BuiltinType>())
6305 if (BT->getKind() == (BuiltinType::Kind) K)
6310 inline bool Type::isPlaceholderType() const {
6311 if (const auto *BT = dyn_cast<BuiltinType>(this))
6312 return BT->isPlaceholderType();
6316 inline const BuiltinType *Type::getAsPlaceholderType() const {
6317 if (const auto *BT = dyn_cast<BuiltinType>(this))
6318 if (BT->isPlaceholderType())
6323 inline bool Type::isSpecificPlaceholderType(unsigned K) const {
6324 assert(BuiltinType::isPlaceholderTypeKind((BuiltinType::Kind) K));
6325 if (const auto *BT = dyn_cast<BuiltinType>(this))
6326 return (BT->getKind() == (BuiltinType::Kind) K);
6330 inline bool Type::isNonOverloadPlaceholderType() const {
6331 if (const auto *BT = dyn_cast<BuiltinType>(this))
6332 return BT->isNonOverloadPlaceholderType();
6336 inline bool Type::isVoidType() const {
6337 if (const auto *BT = dyn_cast<BuiltinType>(CanonicalType))
6338 return BT->getKind() == BuiltinType::Void;
6342 inline bool Type::isHalfType() const {
6343 if (const auto *BT = dyn_cast<BuiltinType>(CanonicalType))
6344 return BT->getKind() == BuiltinType::Half;
6345 // FIXME: Should we allow complex __fp16? Probably not.
6349 inline bool Type::isFloat16Type() const {
6350 if (const auto *BT = dyn_cast<BuiltinType>(CanonicalType))
6351 return BT->getKind() == BuiltinType::Float16;
6355 inline bool Type::isFloat128Type() const {
6356 if (const auto *BT = dyn_cast<BuiltinType>(CanonicalType))
6357 return BT->getKind() == BuiltinType::Float128;
6361 inline bool Type::isNullPtrType() const {
6362 if (const auto *BT = getAs<BuiltinType>())
6363 return BT->getKind() == BuiltinType::NullPtr;
6367 bool IsEnumDeclComplete(EnumDecl *);
6368 bool IsEnumDeclScoped(EnumDecl *);
6370 inline bool Type::isIntegerType() const {
6371 if (const auto *BT = dyn_cast<BuiltinType>(CanonicalType))
6372 return BT->getKind() >= BuiltinType::Bool &&
6373 BT->getKind() <= BuiltinType::Int128;
6374 if (const EnumType *ET = dyn_cast<EnumType>(CanonicalType)) {
6375 // Incomplete enum types are not treated as integer types.
6376 // FIXME: In C++, enum types are never integer types.
6377 return IsEnumDeclComplete(ET->getDecl()) &&
6378 !IsEnumDeclScoped(ET->getDecl());
6383 inline bool Type::isFixedPointType() const {
6384 if (const auto *BT = dyn_cast<BuiltinType>(CanonicalType)) {
6385 return BT->getKind() >= BuiltinType::ShortAccum &&
6386 BT->getKind() <= BuiltinType::SatULongFract;
6391 inline bool Type::isSaturatedFixedPointType() const {
6392 if (const auto *BT = dyn_cast<BuiltinType>(CanonicalType)) {
6393 return BT->getKind() >= BuiltinType::SatShortAccum &&
6394 BT->getKind() <= BuiltinType::SatULongFract;
6399 inline bool Type::isUnsaturatedFixedPointType() const {
6400 return isFixedPointType() && !isSaturatedFixedPointType();
6403 inline bool Type::isSignedFixedPointType() const {
6404 if (const auto *BT = dyn_cast<BuiltinType>(CanonicalType)) {
6405 return ((BT->getKind() >= BuiltinType::ShortAccum &&
6406 BT->getKind() <= BuiltinType::LongAccum) ||
6407 (BT->getKind() >= BuiltinType::ShortFract &&
6408 BT->getKind() <= BuiltinType::LongFract) ||
6409 (BT->getKind() >= BuiltinType::SatShortAccum &&
6410 BT->getKind() <= BuiltinType::SatLongAccum) ||
6411 (BT->getKind() >= BuiltinType::SatShortFract &&
6412 BT->getKind() <= BuiltinType::SatLongFract));
6417 inline bool Type::isUnsignedFixedPointType() const {
6418 return isFixedPointType() && !isSignedFixedPointType();
6421 inline bool Type::isScalarType() const {
6422 if (const auto *BT = dyn_cast<BuiltinType>(CanonicalType))
6423 return BT->getKind() > BuiltinType::Void &&
6424 BT->getKind() <= BuiltinType::NullPtr;
6425 if (const EnumType *ET = dyn_cast<EnumType>(CanonicalType))
6426 // Enums are scalar types, but only if they are defined. Incomplete enums
6427 // are not treated as scalar types.
6428 return IsEnumDeclComplete(ET->getDecl());
6429 return isa<PointerType>(CanonicalType) ||
6430 isa<BlockPointerType>(CanonicalType) ||
6431 isa<MemberPointerType>(CanonicalType) ||
6432 isa<ComplexType>(CanonicalType) ||
6433 isa<ObjCObjectPointerType>(CanonicalType);
6436 inline bool Type::isIntegralOrEnumerationType() const {
6437 if (const auto *BT = dyn_cast<BuiltinType>(CanonicalType))
6438 return BT->getKind() >= BuiltinType::Bool &&
6439 BT->getKind() <= BuiltinType::Int128;
6441 // Check for a complete enum type; incomplete enum types are not properly an
6442 // enumeration type in the sense required here.
6443 if (const auto *ET = dyn_cast<EnumType>(CanonicalType))
6444 return IsEnumDeclComplete(ET->getDecl());
6449 inline bool Type::isBooleanType() const {
6450 if (const auto *BT = dyn_cast<BuiltinType>(CanonicalType))
6451 return BT->getKind() == BuiltinType::Bool;
6455 inline bool Type::isUndeducedType() const {
6456 auto *DT = getContainedDeducedType();
6457 return DT && !DT->isDeduced();
6460 /// Determines whether this is a type for which one can define
6461 /// an overloaded operator.
6462 inline bool Type::isOverloadableType() const {
6463 return isDependentType() || isRecordType() || isEnumeralType();
6466 /// Determines whether this type can decay to a pointer type.
6467 inline bool Type::canDecayToPointerType() const {
6468 return isFunctionType() || isArrayType();
6471 inline bool Type::hasPointerRepresentation() const {
6472 return (isPointerType() || isReferenceType() || isBlockPointerType() ||
6473 isObjCObjectPointerType() || isNullPtrType());
6476 inline bool Type::hasObjCPointerRepresentation() const {
6477 return isObjCObjectPointerType();
6480 inline const Type *Type::getBaseElementTypeUnsafe() const {
6481 const Type *type = this;
6482 while (const ArrayType *arrayType = type->getAsArrayTypeUnsafe())
6483 type = arrayType->getElementType().getTypePtr();
6487 inline const Type *Type::getPointeeOrArrayElementType() const {
6488 const Type *type = this;
6489 if (type->isAnyPointerType())
6490 return type->getPointeeType().getTypePtr();
6491 else if (type->isArrayType())
6492 return type->getBaseElementTypeUnsafe();
6496 /// Insertion operator for diagnostics. This allows sending QualType's into a
6497 /// diagnostic with <<.
6498 inline const DiagnosticBuilder &operator<<(const DiagnosticBuilder &DB,
6500 DB.AddTaggedVal(reinterpret_cast<intptr_t>(T.getAsOpaquePtr()),
6501 DiagnosticsEngine::ak_qualtype);
6505 /// Insertion operator for partial diagnostics. This allows sending QualType's
6506 /// into a diagnostic with <<.
6507 inline const PartialDiagnostic &operator<<(const PartialDiagnostic &PD,
6509 PD.AddTaggedVal(reinterpret_cast<intptr_t>(T.getAsOpaquePtr()),
6510 DiagnosticsEngine::ak_qualtype);
6514 // Helper class template that is used by Type::getAs to ensure that one does
6515 // not try to look through a qualified type to get to an array type.
6516 template <typename T>
6517 using TypeIsArrayType =
6518 std::integral_constant<bool, std::is_same<T, ArrayType>::value ||
6519 std::is_base_of<ArrayType, T>::value>;
6521 // Member-template getAs<specific type>'.
6522 template <typename T> const T *Type::getAs() const {
6523 static_assert(!TypeIsArrayType<T>::value,
6524 "ArrayType cannot be used with getAs!");
6526 // If this is directly a T type, return it.
6527 if (const auto *Ty = dyn_cast<T>(this))
6530 // If the canonical form of this type isn't the right kind, reject it.
6531 if (!isa<T>(CanonicalType))
6534 // If this is a typedef for the type, strip the typedef off without
6535 // losing all typedef information.
6536 return cast<T>(getUnqualifiedDesugaredType());
6539 template <typename T> const T *Type::getAsAdjusted() const {
6540 static_assert(!TypeIsArrayType<T>::value, "ArrayType cannot be used with getAsAdjusted!");
6542 // If this is directly a T type, return it.
6543 if (const auto *Ty = dyn_cast<T>(this))
6546 // If the canonical form of this type isn't the right kind, reject it.
6547 if (!isa<T>(CanonicalType))
6550 // Strip off type adjustments that do not modify the underlying nature of the
6552 const Type *Ty = this;
6554 if (const auto *A = dyn_cast<AttributedType>(Ty))
6555 Ty = A->getModifiedType().getTypePtr();
6556 else if (const auto *E = dyn_cast<ElaboratedType>(Ty))
6557 Ty = E->desugar().getTypePtr();
6558 else if (const auto *P = dyn_cast<ParenType>(Ty))
6559 Ty = P->desugar().getTypePtr();
6560 else if (const auto *A = dyn_cast<AdjustedType>(Ty))
6561 Ty = A->desugar().getTypePtr();
6566 // Just because the canonical type is correct does not mean we can use cast<>,
6567 // since we may not have stripped off all the sugar down to the base type.
6568 return dyn_cast<T>(Ty);
6571 inline const ArrayType *Type::getAsArrayTypeUnsafe() const {
6572 // If this is directly an array type, return it.
6573 if (const auto *arr = dyn_cast<ArrayType>(this))
6576 // If the canonical form of this type isn't the right kind, reject it.
6577 if (!isa<ArrayType>(CanonicalType))
6580 // If this is a typedef for the type, strip the typedef off without
6581 // losing all typedef information.
6582 return cast<ArrayType>(getUnqualifiedDesugaredType());
6585 template <typename T> const T *Type::castAs() const {
6586 static_assert(!TypeIsArrayType<T>::value,
6587 "ArrayType cannot be used with castAs!");
6589 if (const auto *ty = dyn_cast<T>(this)) return ty;
6590 assert(isa<T>(CanonicalType));
6591 return cast<T>(getUnqualifiedDesugaredType());
6594 inline const ArrayType *Type::castAsArrayTypeUnsafe() const {
6595 assert(isa<ArrayType>(CanonicalType));
6596 if (const auto *arr = dyn_cast<ArrayType>(this)) return arr;
6597 return cast<ArrayType>(getUnqualifiedDesugaredType());
6600 DecayedType::DecayedType(QualType OriginalType, QualType DecayedPtr,
6601 QualType CanonicalPtr)
6602 : AdjustedType(Decayed, OriginalType, DecayedPtr, CanonicalPtr) {
6604 QualType Adjusted = getAdjustedType();
6605 (void)AttributedType::stripOuterNullability(Adjusted);
6606 assert(isa<PointerType>(Adjusted));
6610 QualType DecayedType::getPointeeType() const {
6611 QualType Decayed = getDecayedType();
6612 (void)AttributedType::stripOuterNullability(Decayed);
6613 return cast<PointerType>(Decayed)->getPointeeType();
6616 // Get the decimal string representation of a fixed point type, represented
6617 // as a scaled integer.
6618 void FixedPointValueToString(SmallVectorImpl<char> &Str,
6619 const llvm::APSInt &Val,
6620 unsigned Scale, unsigned Radix);
6622 } // namespace clang
6624 #endif // LLVM_CLANG_AST_TYPE_H