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 /// \brief 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/ArrayRef.h"
34 #include "llvm/ADT/FoldingSet.h"
35 #include "llvm/ADT/None.h"
36 #include "llvm/ADT/Optional.h"
37 #include "llvm/ADT/PointerIntPair.h"
38 #include "llvm/ADT/PointerUnion.h"
39 #include "llvm/ADT/StringRef.h"
40 #include "llvm/ADT/Twine.h"
41 #include "llvm/ADT/iterator_range.h"
42 #include "llvm/Support/Casting.h"
43 #include "llvm/Support/Compiler.h"
44 #include "llvm/Support/ErrorHandling.h"
45 #include "llvm/Support/PointerLikeTypeTraits.h"
46 #include "llvm/Support/type_traits.h"
52 #include <type_traits>
62 TypeAlignmentInBits = 4,
63 TypeAlignment = 1 << TypeAlignmentInBits
71 struct PointerLikeTypeTraits;
73 struct PointerLikeTypeTraits< ::clang::Type*> {
74 static inline void *getAsVoidPointer(::clang::Type *P) { return P; }
76 static inline ::clang::Type *getFromVoidPointer(void *P) {
77 return static_cast< ::clang::Type*>(P);
80 enum { NumLowBitsAvailable = clang::TypeAlignmentInBits };
84 struct PointerLikeTypeTraits< ::clang::ExtQuals*> {
85 static inline void *getAsVoidPointer(::clang::ExtQuals *P) { return P; }
87 static inline ::clang::ExtQuals *getFromVoidPointer(void *P) {
88 return static_cast< ::clang::ExtQuals*>(P);
91 enum { NumLowBitsAvailable = clang::TypeAlignmentInBits };
95 struct isPodLike<clang::QualType> { static const bool value = true; };
103 class AttributedType;
106 template <typename> class CanQual;
113 class ExtQualsTypeCommonBase;
115 class FunctionNoProtoType;
116 class FunctionProtoType;
117 class IdentifierInfo;
118 class InjectedClassNameType;
120 class ObjCInterfaceDecl;
121 class ObjCObjectPointerType;
122 class ObjCObjectType;
123 class ObjCProtocolDecl;
124 class ObjCTypeParamDecl;
126 struct PrintingPolicy;
131 class TemplateArgument;
132 class TemplateArgumentListInfo;
133 class TemplateArgumentLoc;
134 class TemplateSpecializationType;
135 class TemplateTypeParmDecl;
136 class TypedefNameDecl;
138 class UnresolvedUsingTypenameDecl;
140 using CanQualType = CanQual<Type>;
142 // Provide forward declarations for all of the *Type classes
143 #define TYPE(Class, Base) class Class##Type;
144 #include "clang/AST/TypeNodes.def"
146 /// The collection of all-type qualifiers we support.
147 /// Clang supports five independent qualifiers:
148 /// * C99: const, volatile, and restrict
149 /// * MS: __unaligned
150 /// * Embedded C (TR18037): address spaces
151 /// * Objective C: the GC attributes (none, weak, or strong)
154 enum TQ { // NOTE: These flags must be kept in sync with DeclSpec::TQ.
158 CVRMask = Const | Volatile | Restrict
168 /// There is no lifetime qualification on this type.
171 /// This object can be modified without requiring retains or
175 /// Assigning into this object requires the old value to be
176 /// released and the new value to be retained. The timing of the
177 /// release of the old value is inexact: it may be moved to
178 /// immediately after the last known point where the value is
182 /// Reading or writing from this object requires a barrier call.
185 /// Assigning into this object requires a lifetime extension.
190 /// The maximum supported address space number.
191 /// 23 bits should be enough for anyone.
192 MaxAddressSpace = 0x7fffffu,
194 /// The width of the "fast" qualifier mask.
197 /// The fast qualifier mask.
198 FastMask = (1 << FastWidth) - 1
201 /// Returns the common set of qualifiers while removing them from
203 static Qualifiers removeCommonQualifiers(Qualifiers &L, Qualifiers &R) {
204 // If both are only CVR-qualified, bit operations are sufficient.
205 if (!(L.Mask & ~CVRMask) && !(R.Mask & ~CVRMask)) {
207 Q.Mask = L.Mask & R.Mask;
214 unsigned CommonCRV = L.getCVRQualifiers() & R.getCVRQualifiers();
215 Q.addCVRQualifiers(CommonCRV);
216 L.removeCVRQualifiers(CommonCRV);
217 R.removeCVRQualifiers(CommonCRV);
219 if (L.getObjCGCAttr() == R.getObjCGCAttr()) {
220 Q.setObjCGCAttr(L.getObjCGCAttr());
221 L.removeObjCGCAttr();
222 R.removeObjCGCAttr();
225 if (L.getObjCLifetime() == R.getObjCLifetime()) {
226 Q.setObjCLifetime(L.getObjCLifetime());
227 L.removeObjCLifetime();
228 R.removeObjCLifetime();
231 if (L.getAddressSpace() == R.getAddressSpace()) {
232 Q.setAddressSpace(L.getAddressSpace());
233 L.removeAddressSpace();
234 R.removeAddressSpace();
239 static Qualifiers fromFastMask(unsigned Mask) {
241 Qs.addFastQualifiers(Mask);
245 static Qualifiers fromCVRMask(unsigned CVR) {
247 Qs.addCVRQualifiers(CVR);
251 static Qualifiers fromCVRUMask(unsigned CVRU) {
253 Qs.addCVRUQualifiers(CVRU);
257 // Deserialize qualifiers from an opaque representation.
258 static Qualifiers fromOpaqueValue(unsigned opaque) {
264 // Serialize these qualifiers into an opaque representation.
265 unsigned getAsOpaqueValue() const {
269 bool hasConst() const { return Mask & Const; }
270 void setConst(bool flag) {
271 Mask = (Mask & ~Const) | (flag ? Const : 0);
273 void removeConst() { Mask &= ~Const; }
274 void addConst() { Mask |= Const; }
276 bool hasVolatile() const { return Mask & Volatile; }
277 void setVolatile(bool flag) {
278 Mask = (Mask & ~Volatile) | (flag ? Volatile : 0);
280 void removeVolatile() { Mask &= ~Volatile; }
281 void addVolatile() { Mask |= Volatile; }
283 bool hasRestrict() const { return Mask & Restrict; }
284 void setRestrict(bool flag) {
285 Mask = (Mask & ~Restrict) | (flag ? Restrict : 0);
287 void removeRestrict() { Mask &= ~Restrict; }
288 void addRestrict() { Mask |= Restrict; }
290 bool hasCVRQualifiers() const { return getCVRQualifiers(); }
291 unsigned getCVRQualifiers() const { return Mask & CVRMask; }
292 void setCVRQualifiers(unsigned mask) {
293 assert(!(mask & ~CVRMask) && "bitmask contains non-CVR bits");
294 Mask = (Mask & ~CVRMask) | mask;
296 void removeCVRQualifiers(unsigned mask) {
297 assert(!(mask & ~CVRMask) && "bitmask contains non-CVR bits");
300 void removeCVRQualifiers() {
301 removeCVRQualifiers(CVRMask);
303 void addCVRQualifiers(unsigned mask) {
304 assert(!(mask & ~CVRMask) && "bitmask contains non-CVR bits");
307 void addCVRUQualifiers(unsigned mask) {
308 assert(!(mask & ~CVRMask & ~UMask) && "bitmask contains non-CVRU bits");
312 bool hasUnaligned() const { return Mask & UMask; }
313 void setUnaligned(bool flag) {
314 Mask = (Mask & ~UMask) | (flag ? UMask : 0);
316 void removeUnaligned() { Mask &= ~UMask; }
317 void addUnaligned() { Mask |= UMask; }
319 bool hasObjCGCAttr() const { return Mask & GCAttrMask; }
320 GC getObjCGCAttr() const { return GC((Mask & GCAttrMask) >> GCAttrShift); }
321 void setObjCGCAttr(GC type) {
322 Mask = (Mask & ~GCAttrMask) | (type << GCAttrShift);
324 void removeObjCGCAttr() { setObjCGCAttr(GCNone); }
325 void addObjCGCAttr(GC type) {
329 Qualifiers withoutObjCGCAttr() const {
330 Qualifiers qs = *this;
331 qs.removeObjCGCAttr();
334 Qualifiers withoutObjCLifetime() const {
335 Qualifiers qs = *this;
336 qs.removeObjCLifetime();
340 bool hasObjCLifetime() const { return Mask & LifetimeMask; }
341 ObjCLifetime getObjCLifetime() const {
342 return ObjCLifetime((Mask & LifetimeMask) >> LifetimeShift);
344 void setObjCLifetime(ObjCLifetime type) {
345 Mask = (Mask & ~LifetimeMask) | (type << LifetimeShift);
347 void removeObjCLifetime() { setObjCLifetime(OCL_None); }
348 void addObjCLifetime(ObjCLifetime type) {
350 assert(!hasObjCLifetime());
351 Mask |= (type << LifetimeShift);
354 /// True if the lifetime is neither None or ExplicitNone.
355 bool hasNonTrivialObjCLifetime() const {
356 ObjCLifetime lifetime = getObjCLifetime();
357 return (lifetime > OCL_ExplicitNone);
360 /// True if the lifetime is either strong or weak.
361 bool hasStrongOrWeakObjCLifetime() const {
362 ObjCLifetime lifetime = getObjCLifetime();
363 return (lifetime == OCL_Strong || lifetime == OCL_Weak);
366 bool hasAddressSpace() const { return Mask & AddressSpaceMask; }
367 LangAS getAddressSpace() const {
368 return static_cast<LangAS>(Mask >> AddressSpaceShift);
370 bool hasTargetSpecificAddressSpace() const {
371 return isTargetAddressSpace(getAddressSpace());
373 /// Get the address space attribute value to be printed by diagnostics.
374 unsigned getAddressSpaceAttributePrintValue() const {
375 auto Addr = getAddressSpace();
376 // This function is not supposed to be used with language specific
377 // address spaces. If that happens, the diagnostic message should consider
378 // printing the QualType instead of the address space value.
379 assert(Addr == LangAS::Default || hasTargetSpecificAddressSpace());
380 if (Addr != LangAS::Default)
381 return toTargetAddressSpace(Addr);
382 // TODO: The diagnostic messages where Addr may be 0 should be fixed
383 // since it cannot differentiate the situation where 0 denotes the default
384 // address space or user specified __attribute__((address_space(0))).
387 void setAddressSpace(LangAS space) {
388 assert((unsigned)space <= MaxAddressSpace);
389 Mask = (Mask & ~AddressSpaceMask)
390 | (((uint32_t) space) << AddressSpaceShift);
392 void removeAddressSpace() { setAddressSpace(LangAS::Default); }
393 void addAddressSpace(LangAS space) {
394 assert(space != LangAS::Default);
395 setAddressSpace(space);
398 // Fast qualifiers are those that can be allocated directly
399 // on a QualType object.
400 bool hasFastQualifiers() const { return getFastQualifiers(); }
401 unsigned getFastQualifiers() const { return Mask & FastMask; }
402 void setFastQualifiers(unsigned mask) {
403 assert(!(mask & ~FastMask) && "bitmask contains non-fast qualifier bits");
404 Mask = (Mask & ~FastMask) | mask;
406 void removeFastQualifiers(unsigned mask) {
407 assert(!(mask & ~FastMask) && "bitmask contains non-fast qualifier bits");
410 void removeFastQualifiers() {
411 removeFastQualifiers(FastMask);
413 void addFastQualifiers(unsigned mask) {
414 assert(!(mask & ~FastMask) && "bitmask contains non-fast qualifier bits");
418 /// Return true if the set contains any qualifiers which require an ExtQuals
419 /// node to be allocated.
420 bool hasNonFastQualifiers() const { return Mask & ~FastMask; }
421 Qualifiers getNonFastQualifiers() const {
422 Qualifiers Quals = *this;
423 Quals.setFastQualifiers(0);
427 /// Return true if the set contains any qualifiers.
428 bool hasQualifiers() const { return Mask; }
429 bool empty() const { return !Mask; }
431 /// Add the qualifiers from the given set to this set.
432 void addQualifiers(Qualifiers Q) {
433 // If the other set doesn't have any non-boolean qualifiers, just
435 if (!(Q.Mask & ~CVRMask))
438 Mask |= (Q.Mask & CVRMask);
439 if (Q.hasAddressSpace())
440 addAddressSpace(Q.getAddressSpace());
441 if (Q.hasObjCGCAttr())
442 addObjCGCAttr(Q.getObjCGCAttr());
443 if (Q.hasObjCLifetime())
444 addObjCLifetime(Q.getObjCLifetime());
448 /// \brief Remove the qualifiers from the given set from this set.
449 void removeQualifiers(Qualifiers Q) {
450 // If the other set doesn't have any non-boolean qualifiers, just
451 // bit-and the inverse in.
452 if (!(Q.Mask & ~CVRMask))
455 Mask &= ~(Q.Mask & CVRMask);
456 if (getObjCGCAttr() == Q.getObjCGCAttr())
458 if (getObjCLifetime() == Q.getObjCLifetime())
459 removeObjCLifetime();
460 if (getAddressSpace() == Q.getAddressSpace())
461 removeAddressSpace();
465 /// Add the qualifiers from the given set to this set, given that
466 /// they don't conflict.
467 void addConsistentQualifiers(Qualifiers qs) {
468 assert(getAddressSpace() == qs.getAddressSpace() ||
469 !hasAddressSpace() || !qs.hasAddressSpace());
470 assert(getObjCGCAttr() == qs.getObjCGCAttr() ||
471 !hasObjCGCAttr() || !qs.hasObjCGCAttr());
472 assert(getObjCLifetime() == qs.getObjCLifetime() ||
473 !hasObjCLifetime() || !qs.hasObjCLifetime());
477 /// Returns true if this address space is a superset of the other one.
478 /// OpenCL v2.0 defines conversion rules (OpenCLC v2.0 s6.5.5) and notion of
479 /// overlapping address spaces.
481 /// every address space is a superset of itself.
483 /// __generic is a superset of any address space except for __constant.
484 bool isAddressSpaceSupersetOf(Qualifiers other) const {
486 // Address spaces must match exactly.
487 getAddressSpace() == other.getAddressSpace() ||
488 // Otherwise in OpenCLC v2.0 s6.5.5: every address space except
489 // for __constant can be used as __generic.
490 (getAddressSpace() == LangAS::opencl_generic &&
491 other.getAddressSpace() != LangAS::opencl_constant);
494 /// Determines if these qualifiers compatibly include another set.
495 /// Generally this answers the question of whether an object with the other
496 /// qualifiers can be safely used as an object with these qualifiers.
497 bool compatiblyIncludes(Qualifiers other) const {
498 return isAddressSpaceSupersetOf(other) &&
499 // ObjC GC qualifiers can match, be added, or be removed, but can't
501 (getObjCGCAttr() == other.getObjCGCAttr() || !hasObjCGCAttr() ||
502 !other.hasObjCGCAttr()) &&
503 // ObjC lifetime qualifiers must match exactly.
504 getObjCLifetime() == other.getObjCLifetime() &&
505 // CVR qualifiers may subset.
506 (((Mask & CVRMask) | (other.Mask & CVRMask)) == (Mask & CVRMask)) &&
507 // U qualifier may superset.
508 (!other.hasUnaligned() || hasUnaligned());
511 /// \brief Determines if these qualifiers compatibly include another set of
512 /// qualifiers from the narrow perspective of Objective-C ARC lifetime.
514 /// One set of Objective-C lifetime qualifiers compatibly includes the other
515 /// if the lifetime qualifiers match, or if both are non-__weak and the
516 /// including set also contains the 'const' qualifier, or both are non-__weak
517 /// and one is None (which can only happen in non-ARC modes).
518 bool compatiblyIncludesObjCLifetime(Qualifiers other) const {
519 if (getObjCLifetime() == other.getObjCLifetime())
522 if (getObjCLifetime() == OCL_Weak || other.getObjCLifetime() == OCL_Weak)
525 if (getObjCLifetime() == OCL_None || other.getObjCLifetime() == OCL_None)
531 /// \brief Determine whether this set of qualifiers is a strict superset of
532 /// another set of qualifiers, not considering qualifier compatibility.
533 bool isStrictSupersetOf(Qualifiers Other) const;
535 bool operator==(Qualifiers Other) const { return Mask == Other.Mask; }
536 bool operator!=(Qualifiers Other) const { return Mask != Other.Mask; }
538 explicit operator bool() const { return hasQualifiers(); }
540 Qualifiers &operator+=(Qualifiers R) {
545 // Union two qualifier sets. If an enumerated qualifier appears
546 // in both sets, use the one from the right.
547 friend Qualifiers operator+(Qualifiers L, Qualifiers R) {
552 Qualifiers &operator-=(Qualifiers R) {
557 /// \brief Compute the difference between two qualifier sets.
558 friend Qualifiers operator-(Qualifiers L, Qualifiers R) {
563 std::string getAsString() const;
564 std::string getAsString(const PrintingPolicy &Policy) const;
566 bool isEmptyWhenPrinted(const PrintingPolicy &Policy) const;
567 void print(raw_ostream &OS, const PrintingPolicy &Policy,
568 bool appendSpaceIfNonEmpty = false) const;
570 void Profile(llvm::FoldingSetNodeID &ID) const {
575 // bits: |0 1 2|3|4 .. 5|6 .. 8|9 ... 31|
576 // |C R V|U|GCAttr|Lifetime|AddressSpace|
579 static const uint32_t UMask = 0x8;
580 static const uint32_t UShift = 3;
581 static const uint32_t GCAttrMask = 0x30;
582 static const uint32_t GCAttrShift = 4;
583 static const uint32_t LifetimeMask = 0x1C0;
584 static const uint32_t LifetimeShift = 6;
585 static const uint32_t AddressSpaceMask =
586 ~(CVRMask | UMask | GCAttrMask | LifetimeMask);
587 static const uint32_t AddressSpaceShift = 9;
590 /// A std::pair-like structure for storing a qualified type split
591 /// into its local qualifiers and its locally-unqualified type.
592 struct SplitQualType {
593 /// The locally-unqualified type.
594 const Type *Ty = nullptr;
596 /// The local qualifiers.
599 SplitQualType() = default;
600 SplitQualType(const Type *ty, Qualifiers qs) : Ty(ty), Quals(qs) {}
602 SplitQualType getSingleStepDesugaredType() const; // end of this file
604 // Make std::tie work.
605 std::pair<const Type *,Qualifiers> asPair() const {
606 return std::pair<const Type *, Qualifiers>(Ty, Quals);
609 friend bool operator==(SplitQualType a, SplitQualType b) {
610 return a.Ty == b.Ty && a.Quals == b.Quals;
612 friend bool operator!=(SplitQualType a, SplitQualType b) {
613 return a.Ty != b.Ty || a.Quals != b.Quals;
617 /// The kind of type we are substituting Objective-C type arguments into.
619 /// The kind of substitution affects the replacement of type parameters when
620 /// no concrete type information is provided, e.g., when dealing with an
621 /// unspecialized type.
622 enum class ObjCSubstitutionContext {
623 /// An ordinary type.
626 /// The result type of a method or function.
629 /// The parameter type of a method or function.
632 /// The type of a property.
635 /// The superclass of a type.
639 /// A (possibly-)qualified type.
641 /// For efficiency, we don't store CV-qualified types as nodes on their
642 /// own: instead each reference to a type stores the qualifiers. This
643 /// greatly reduces the number of nodes we need to allocate for types (for
644 /// example we only need one for 'int', 'const int', 'volatile int',
645 /// 'const volatile int', etc).
647 /// As an added efficiency bonus, instead of making this a pair, we
648 /// just store the two bits we care about in the low bits of the
649 /// pointer. To handle the packing/unpacking, we make QualType be a
650 /// simple wrapper class that acts like a smart pointer. A third bit
651 /// indicates whether there are extended qualifiers present, in which
652 /// case the pointer points to a special structure.
654 friend class QualifierCollector;
656 // Thankfully, these are efficiently composable.
657 llvm::PointerIntPair<llvm::PointerUnion<const Type *, const ExtQuals *>,
658 Qualifiers::FastWidth> Value;
660 const ExtQuals *getExtQualsUnsafe() const {
661 return Value.getPointer().get<const ExtQuals*>();
664 const Type *getTypePtrUnsafe() const {
665 return Value.getPointer().get<const Type*>();
668 const ExtQualsTypeCommonBase *getCommonPtr() const {
669 assert(!isNull() && "Cannot retrieve a NULL type pointer");
670 uintptr_t CommonPtrVal
671 = reinterpret_cast<uintptr_t>(Value.getOpaqueValue());
672 CommonPtrVal &= ~(uintptr_t)((1 << TypeAlignmentInBits) - 1);
673 return reinterpret_cast<ExtQualsTypeCommonBase*>(CommonPtrVal);
677 QualType() = default;
678 QualType(const Type *Ptr, unsigned Quals) : Value(Ptr, Quals) {}
679 QualType(const ExtQuals *Ptr, unsigned Quals) : Value(Ptr, Quals) {}
681 unsigned getLocalFastQualifiers() const { return Value.getInt(); }
682 void setLocalFastQualifiers(unsigned Quals) { Value.setInt(Quals); }
684 /// Retrieves a pointer to the underlying (unqualified) type.
686 /// This function requires that the type not be NULL. If the type might be
687 /// NULL, use the (slightly less efficient) \c getTypePtrOrNull().
688 const Type *getTypePtr() const;
690 const Type *getTypePtrOrNull() const;
692 /// Retrieves a pointer to the name of the base type.
693 const IdentifierInfo *getBaseTypeIdentifier() const;
695 /// Divides a QualType into its unqualified type and a set of local
697 SplitQualType split() const;
699 void *getAsOpaquePtr() const { return Value.getOpaqueValue(); }
701 static QualType getFromOpaquePtr(const void *Ptr) {
703 T.Value.setFromOpaqueValue(const_cast<void*>(Ptr));
707 const Type &operator*() const {
708 return *getTypePtr();
711 const Type *operator->() const {
715 bool isCanonical() const;
716 bool isCanonicalAsParam() const;
718 /// Return true if this QualType doesn't point to a type yet.
719 bool isNull() const {
720 return Value.getPointer().isNull();
723 /// \brief Determine whether this particular QualType instance has the
724 /// "const" qualifier set, without looking through typedefs that may have
725 /// added "const" at a different level.
726 bool isLocalConstQualified() const {
727 return (getLocalFastQualifiers() & Qualifiers::Const);
730 /// \brief Determine whether this type is const-qualified.
731 bool isConstQualified() const;
733 /// \brief Determine whether this particular QualType instance has the
734 /// "restrict" qualifier set, without looking through typedefs that may have
735 /// added "restrict" at a different level.
736 bool isLocalRestrictQualified() const {
737 return (getLocalFastQualifiers() & Qualifiers::Restrict);
740 /// \brief Determine whether this type is restrict-qualified.
741 bool isRestrictQualified() const;
743 /// \brief Determine whether this particular QualType instance has the
744 /// "volatile" qualifier set, without looking through typedefs that may have
745 /// added "volatile" at a different level.
746 bool isLocalVolatileQualified() const {
747 return (getLocalFastQualifiers() & Qualifiers::Volatile);
750 /// \brief Determine whether this type is volatile-qualified.
751 bool isVolatileQualified() const;
753 /// \brief Determine whether this particular QualType instance has any
754 /// qualifiers, without looking through any typedefs that might add
755 /// qualifiers at a different level.
756 bool hasLocalQualifiers() const {
757 return getLocalFastQualifiers() || hasLocalNonFastQualifiers();
760 /// \brief Determine whether this type has any qualifiers.
761 bool hasQualifiers() const;
763 /// \brief Determine whether this particular QualType instance has any
764 /// "non-fast" qualifiers, e.g., those that are stored in an ExtQualType
766 bool hasLocalNonFastQualifiers() const {
767 return Value.getPointer().is<const ExtQuals*>();
770 /// \brief Retrieve the set of qualifiers local to this particular QualType
771 /// instance, not including any qualifiers acquired through typedefs or
773 Qualifiers getLocalQualifiers() const;
775 /// \brief Retrieve the set of qualifiers applied to this type.
776 Qualifiers getQualifiers() const;
778 /// \brief Retrieve the set of CVR (const-volatile-restrict) qualifiers
779 /// local to this particular QualType instance, not including any qualifiers
780 /// acquired through typedefs or other sugar.
781 unsigned getLocalCVRQualifiers() const {
782 return getLocalFastQualifiers();
785 /// \brief Retrieve the set of CVR (const-volatile-restrict) qualifiers
786 /// applied to this type.
787 unsigned getCVRQualifiers() const;
789 bool isConstant(const ASTContext& Ctx) const {
790 return QualType::isConstant(*this, Ctx);
793 /// \brief Determine whether this is a Plain Old Data (POD) type (C++ 3.9p10).
794 bool isPODType(const ASTContext &Context) const;
796 /// Return true if this is a POD type according to the rules of the C++98
797 /// standard, regardless of the current compilation's language.
798 bool isCXX98PODType(const ASTContext &Context) const;
800 /// Return true if this is a POD type according to the more relaxed rules
801 /// of the C++11 standard, regardless of the current compilation's language.
802 /// (C++0x [basic.types]p9)
803 bool isCXX11PODType(const ASTContext &Context) const;
805 /// Return true if this is a trivial type per (C++0x [basic.types]p9)
806 bool isTrivialType(const ASTContext &Context) const;
808 /// Return true if this is a trivially copyable type (C++0x [basic.types]p9)
809 bool isTriviallyCopyableType(const ASTContext &Context) const;
811 // Don't promise in the API that anything besides 'const' can be
814 /// Add the `const` type qualifier to this QualType.
816 addFastQualifiers(Qualifiers::Const);
818 QualType withConst() const {
819 return withFastQualifiers(Qualifiers::Const);
822 /// Add the `volatile` type qualifier to this QualType.
824 addFastQualifiers(Qualifiers::Volatile);
826 QualType withVolatile() const {
827 return withFastQualifiers(Qualifiers::Volatile);
830 /// Add the `restrict` qualifier to this QualType.
832 addFastQualifiers(Qualifiers::Restrict);
834 QualType withRestrict() const {
835 return withFastQualifiers(Qualifiers::Restrict);
838 QualType withCVRQualifiers(unsigned CVR) const {
839 return withFastQualifiers(CVR);
842 void addFastQualifiers(unsigned TQs) {
843 assert(!(TQs & ~Qualifiers::FastMask)
844 && "non-fast qualifier bits set in mask!");
845 Value.setInt(Value.getInt() | TQs);
848 void removeLocalConst();
849 void removeLocalVolatile();
850 void removeLocalRestrict();
851 void removeLocalCVRQualifiers(unsigned Mask);
853 void removeLocalFastQualifiers() { Value.setInt(0); }
854 void removeLocalFastQualifiers(unsigned Mask) {
855 assert(!(Mask & ~Qualifiers::FastMask) && "mask has non-fast qualifiers");
856 Value.setInt(Value.getInt() & ~Mask);
859 // Creates a type with the given qualifiers in addition to any
860 // qualifiers already on this type.
861 QualType withFastQualifiers(unsigned TQs) const {
863 T.addFastQualifiers(TQs);
867 // Creates a type with exactly the given fast qualifiers, removing
868 // any existing fast qualifiers.
869 QualType withExactLocalFastQualifiers(unsigned TQs) const {
870 return withoutLocalFastQualifiers().withFastQualifiers(TQs);
873 // Removes fast qualifiers, but leaves any extended qualifiers in place.
874 QualType withoutLocalFastQualifiers() const {
876 T.removeLocalFastQualifiers();
880 QualType getCanonicalType() const;
882 /// \brief Return this type with all of the instance-specific qualifiers
883 /// removed, but without removing any qualifiers that may have been applied
884 /// through typedefs.
885 QualType getLocalUnqualifiedType() const { return QualType(getTypePtr(), 0); }
887 /// \brief Retrieve the unqualified variant of the given type,
888 /// removing as little sugar as possible.
890 /// This routine looks through various kinds of sugar to find the
891 /// least-desugared type that is unqualified. For example, given:
894 /// typedef int Integer;
895 /// typedef const Integer CInteger;
896 /// typedef CInteger DifferenceType;
899 /// Executing \c getUnqualifiedType() on the type \c DifferenceType will
900 /// desugar until we hit the type \c Integer, which has no qualifiers on it.
902 /// The resulting type might still be qualified if it's sugar for an array
903 /// type. To strip qualifiers even from within a sugared array type, use
904 /// ASTContext::getUnqualifiedArrayType.
905 inline QualType getUnqualifiedType() const;
907 /// Retrieve the unqualified variant of the given type, removing as little
908 /// sugar as possible.
910 /// Like getUnqualifiedType(), but also returns the set of
911 /// qualifiers that were built up.
913 /// The resulting type might still be qualified if it's sugar for an array
914 /// type. To strip qualifiers even from within a sugared array type, use
915 /// ASTContext::getUnqualifiedArrayType.
916 inline SplitQualType getSplitUnqualifiedType() const;
918 /// \brief Determine whether this type is more qualified than the other
919 /// given type, requiring exact equality for non-CVR qualifiers.
920 bool isMoreQualifiedThan(QualType Other) const;
922 /// \brief Determine whether this type is at least as qualified as the other
923 /// given type, requiring exact equality for non-CVR qualifiers.
924 bool isAtLeastAsQualifiedAs(QualType Other) const;
926 QualType getNonReferenceType() const;
928 /// \brief Determine the type of a (typically non-lvalue) expression with the
929 /// specified result type.
931 /// This routine should be used for expressions for which the return type is
932 /// explicitly specified (e.g., in a cast or call) and isn't necessarily
933 /// an lvalue. It removes a top-level reference (since there are no
934 /// expressions of reference type) and deletes top-level cvr-qualifiers
935 /// from non-class types (in C++) or all types (in C).
936 QualType getNonLValueExprType(const ASTContext &Context) const;
938 /// Return the specified type with any "sugar" removed from
939 /// the type. This takes off typedefs, typeof's etc. If the outer level of
940 /// the type is already concrete, it returns it unmodified. This is similar
941 /// to getting the canonical type, but it doesn't remove *all* typedefs. For
942 /// example, it returns "T*" as "T*", (not as "int*"), because the pointer is
945 /// Qualifiers are left in place.
946 QualType getDesugaredType(const ASTContext &Context) const {
947 return getDesugaredType(*this, Context);
950 SplitQualType getSplitDesugaredType() const {
951 return getSplitDesugaredType(*this);
954 /// \brief Return the specified type with one level of "sugar" removed from
957 /// This routine takes off the first typedef, typeof, etc. If the outer level
958 /// of the type is already concrete, it returns it unmodified.
959 QualType getSingleStepDesugaredType(const ASTContext &Context) const {
960 return getSingleStepDesugaredTypeImpl(*this, Context);
963 /// Returns the specified type after dropping any
964 /// outer-level parentheses.
965 QualType IgnoreParens() const {
966 if (isa<ParenType>(*this))
967 return QualType::IgnoreParens(*this);
971 /// Indicate whether the specified types and qualifiers are identical.
972 friend bool operator==(const QualType &LHS, const QualType &RHS) {
973 return LHS.Value == RHS.Value;
975 friend bool operator!=(const QualType &LHS, const QualType &RHS) {
976 return LHS.Value != RHS.Value;
979 static std::string getAsString(SplitQualType split,
980 const PrintingPolicy &Policy) {
981 return getAsString(split.Ty, split.Quals, Policy);
983 static std::string getAsString(const Type *ty, Qualifiers qs,
984 const PrintingPolicy &Policy);
986 std::string getAsString() const;
987 std::string getAsString(const PrintingPolicy &Policy) const;
989 void print(raw_ostream &OS, const PrintingPolicy &Policy,
990 const Twine &PlaceHolder = Twine(),
991 unsigned Indentation = 0) const {
992 print(split(), OS, Policy, PlaceHolder, Indentation);
995 static void print(SplitQualType split, raw_ostream &OS,
996 const PrintingPolicy &policy, const Twine &PlaceHolder,
997 unsigned Indentation = 0) {
998 return print(split.Ty, split.Quals, OS, policy, PlaceHolder, Indentation);
1001 static void print(const Type *ty, Qualifiers qs,
1002 raw_ostream &OS, const PrintingPolicy &policy,
1003 const Twine &PlaceHolder,
1004 unsigned Indentation = 0);
1006 void getAsStringInternal(std::string &Str,
1007 const PrintingPolicy &Policy) const {
1008 return getAsStringInternal(split(), Str, Policy);
1011 static void getAsStringInternal(SplitQualType split, std::string &out,
1012 const PrintingPolicy &policy) {
1013 return getAsStringInternal(split.Ty, split.Quals, out, policy);
1016 static void getAsStringInternal(const Type *ty, Qualifiers qs,
1018 const PrintingPolicy &policy);
1020 class StreamedQualTypeHelper {
1022 const PrintingPolicy &Policy;
1023 const Twine &PlaceHolder;
1024 unsigned Indentation;
1027 StreamedQualTypeHelper(const QualType &T, const PrintingPolicy &Policy,
1028 const Twine &PlaceHolder, unsigned Indentation)
1029 : T(T), Policy(Policy), PlaceHolder(PlaceHolder),
1030 Indentation(Indentation) {}
1032 friend raw_ostream &operator<<(raw_ostream &OS,
1033 const StreamedQualTypeHelper &SQT) {
1034 SQT.T.print(OS, SQT.Policy, SQT.PlaceHolder, SQT.Indentation);
1039 StreamedQualTypeHelper stream(const PrintingPolicy &Policy,
1040 const Twine &PlaceHolder = Twine(),
1041 unsigned Indentation = 0) const {
1042 return StreamedQualTypeHelper(*this, Policy, PlaceHolder, Indentation);
1045 void dump(const char *s) const;
1047 void dump(llvm::raw_ostream &OS) const;
1049 void Profile(llvm::FoldingSetNodeID &ID) const {
1050 ID.AddPointer(getAsOpaquePtr());
1053 /// Return the address space of this type.
1054 inline LangAS getAddressSpace() const;
1056 /// Returns gc attribute of this type.
1057 inline Qualifiers::GC getObjCGCAttr() const;
1059 /// true when Type is objc's weak.
1060 bool isObjCGCWeak() const {
1061 return getObjCGCAttr() == Qualifiers::Weak;
1064 /// true when Type is objc's strong.
1065 bool isObjCGCStrong() const {
1066 return getObjCGCAttr() == Qualifiers::Strong;
1069 /// Returns lifetime attribute of this type.
1070 Qualifiers::ObjCLifetime getObjCLifetime() const {
1071 return getQualifiers().getObjCLifetime();
1074 bool hasNonTrivialObjCLifetime() const {
1075 return getQualifiers().hasNonTrivialObjCLifetime();
1078 bool hasStrongOrWeakObjCLifetime() const {
1079 return getQualifiers().hasStrongOrWeakObjCLifetime();
1082 // true when Type is objc's weak and weak is enabled but ARC isn't.
1083 bool isNonWeakInMRRWithObjCWeak(const ASTContext &Context) const;
1085 enum DestructionKind {
1088 DK_objc_strong_lifetime,
1089 DK_objc_weak_lifetime
1092 /// Returns a nonzero value if objects of this type require
1093 /// non-trivial work to clean up after. Non-zero because it's
1094 /// conceivable that qualifiers (objc_gc(weak)?) could make
1095 /// something require destruction.
1096 DestructionKind isDestructedType() const {
1097 return isDestructedTypeImpl(*this);
1100 /// Determine whether expressions of the given type are forbidden
1101 /// from being lvalues in C.
1103 /// The expression types that are forbidden to be lvalues are:
1104 /// - 'void', but not qualified void
1105 /// - function types
1107 /// The exact rule here is C99 6.3.2.1:
1108 /// An lvalue is an expression with an object type or an incomplete
1109 /// type other than void.
1110 bool isCForbiddenLValueType() const;
1112 /// Substitute type arguments for the Objective-C type parameters used in the
1115 /// \param ctx ASTContext in which the type exists.
1117 /// \param typeArgs The type arguments that will be substituted for the
1118 /// Objective-C type parameters in the subject type, which are generally
1119 /// computed via \c Type::getObjCSubstitutions. If empty, the type
1120 /// parameters will be replaced with their bounds or id/Class, as appropriate
1121 /// for the context.
1123 /// \param context The context in which the subject type was written.
1125 /// \returns the resulting type.
1126 QualType substObjCTypeArgs(ASTContext &ctx,
1127 ArrayRef<QualType> typeArgs,
1128 ObjCSubstitutionContext context) const;
1130 /// Substitute type arguments from an object type for the Objective-C type
1131 /// parameters used in the subject type.
1133 /// This operation combines the computation of type arguments for
1134 /// substitution (\c Type::getObjCSubstitutions) with the actual process of
1135 /// substitution (\c QualType::substObjCTypeArgs) for the convenience of
1136 /// callers that need to perform a single substitution in isolation.
1138 /// \param objectType The type of the object whose member type we're
1139 /// substituting into. For example, this might be the receiver of a message
1140 /// or the base of a property access.
1142 /// \param dc The declaration context from which the subject type was
1143 /// retrieved, which indicates (for example) which type parameters should
1146 /// \param context The context in which the subject type was written.
1148 /// \returns the subject type after replacing all of the Objective-C type
1149 /// parameters with their corresponding arguments.
1150 QualType substObjCMemberType(QualType objectType,
1151 const DeclContext *dc,
1152 ObjCSubstitutionContext context) const;
1154 /// Strip Objective-C "__kindof" types from the given type.
1155 QualType stripObjCKindOfType(const ASTContext &ctx) const;
1157 /// Remove all qualifiers including _Atomic.
1158 QualType getAtomicUnqualifiedType() const;
1161 // These methods are implemented in a separate translation unit;
1162 // "static"-ize them to avoid creating temporary QualTypes in the
1164 static bool isConstant(QualType T, const ASTContext& Ctx);
1165 static QualType getDesugaredType(QualType T, const ASTContext &Context);
1166 static SplitQualType getSplitDesugaredType(QualType T);
1167 static SplitQualType getSplitUnqualifiedTypeImpl(QualType type);
1168 static QualType getSingleStepDesugaredTypeImpl(QualType type,
1169 const ASTContext &C);
1170 static QualType IgnoreParens(QualType T);
1171 static DestructionKind isDestructedTypeImpl(QualType type);
1174 } // namespace clang
1178 /// Implement simplify_type for QualType, so that we can dyn_cast from QualType
1179 /// to a specific Type class.
1180 template<> struct simplify_type< ::clang::QualType> {
1181 using SimpleType = const ::clang::Type *;
1183 static SimpleType getSimplifiedValue(::clang::QualType Val) {
1184 return Val.getTypePtr();
1188 // Teach SmallPtrSet that QualType is "basically a pointer".
1190 struct PointerLikeTypeTraits<clang::QualType> {
1191 static inline void *getAsVoidPointer(clang::QualType P) {
1192 return P.getAsOpaquePtr();
1195 static inline clang::QualType getFromVoidPointer(void *P) {
1196 return clang::QualType::getFromOpaquePtr(P);
1199 // Various qualifiers go in low bits.
1200 enum { NumLowBitsAvailable = 0 };
1207 /// \brief Base class that is common to both the \c ExtQuals and \c Type
1208 /// classes, which allows \c QualType to access the common fields between the
1210 class ExtQualsTypeCommonBase {
1211 friend class ExtQuals;
1212 friend class QualType;
1215 /// \brief The "base" type of an extended qualifiers type (\c ExtQuals) or
1216 /// a self-referential pointer (for \c Type).
1218 /// This pointer allows an efficient mapping from a QualType to its
1219 /// underlying type pointer.
1220 const Type *const BaseType;
1222 /// \brief The canonical type of this type. A QualType.
1223 QualType CanonicalType;
1225 ExtQualsTypeCommonBase(const Type *baseType, QualType canon)
1226 : BaseType(baseType), CanonicalType(canon) {}
1229 /// We can encode up to four bits in the low bits of a
1230 /// type pointer, but there are many more type qualifiers that we want
1231 /// to be able to apply to an arbitrary type. Therefore we have this
1232 /// struct, intended to be heap-allocated and used by QualType to
1233 /// store qualifiers.
1235 /// The current design tags the 'const', 'restrict', and 'volatile' qualifiers
1236 /// in three low bits on the QualType pointer; a fourth bit records whether
1237 /// the pointer is an ExtQuals node. The extended qualifiers (address spaces,
1238 /// Objective-C GC attributes) are much more rare.
1239 class ExtQuals : public ExtQualsTypeCommonBase, public llvm::FoldingSetNode {
1240 // NOTE: changing the fast qualifiers should be straightforward as
1241 // long as you don't make 'const' non-fast.
1243 // a) Modify the bitmasks (Qualifiers::TQ and DeclSpec::TQ).
1244 // Fast qualifiers must occupy the low-order bits.
1245 // b) Update Qualifiers::FastWidth and FastMask.
1247 // a) Update is{Volatile,Restrict}Qualified(), defined inline.
1248 // b) Update remove{Volatile,Restrict}, defined near the end of
1251 // a) Update get{Volatile,Restrict}Type.
1253 /// The immutable set of qualifiers applied by this node. Always contains
1254 /// extended qualifiers.
1257 ExtQuals *this_() { return this; }
1260 ExtQuals(const Type *baseType, QualType canon, Qualifiers quals)
1261 : ExtQualsTypeCommonBase(baseType,
1262 canon.isNull() ? QualType(this_(), 0) : canon),
1264 assert(Quals.hasNonFastQualifiers()
1265 && "ExtQuals created with no fast qualifiers");
1266 assert(!Quals.hasFastQualifiers()
1267 && "ExtQuals created with fast qualifiers");
1270 Qualifiers getQualifiers() const { return Quals; }
1272 bool hasObjCGCAttr() const { return Quals.hasObjCGCAttr(); }
1273 Qualifiers::GC getObjCGCAttr() const { return Quals.getObjCGCAttr(); }
1275 bool hasObjCLifetime() const { return Quals.hasObjCLifetime(); }
1276 Qualifiers::ObjCLifetime getObjCLifetime() const {
1277 return Quals.getObjCLifetime();
1280 bool hasAddressSpace() const { return Quals.hasAddressSpace(); }
1281 LangAS getAddressSpace() const { return Quals.getAddressSpace(); }
1283 const Type *getBaseType() const { return BaseType; }
1286 void Profile(llvm::FoldingSetNodeID &ID) const {
1287 Profile(ID, getBaseType(), Quals);
1290 static void Profile(llvm::FoldingSetNodeID &ID,
1291 const Type *BaseType,
1293 assert(!Quals.hasFastQualifiers() && "fast qualifiers in ExtQuals hash!");
1294 ID.AddPointer(BaseType);
1299 /// The kind of C++11 ref-qualifier associated with a function type.
1300 /// This determines whether a member function's "this" object can be an
1301 /// lvalue, rvalue, or neither.
1302 enum RefQualifierKind {
1303 /// \brief No ref-qualifier was provided.
1306 /// \brief An lvalue ref-qualifier was provided (\c &).
1309 /// \brief An rvalue ref-qualifier was provided (\c &&).
1313 /// Which keyword(s) were used to create an AutoType.
1314 enum class AutoTypeKeyword {
1318 /// \brief decltype(auto)
1321 /// \brief __auto_type (GNU extension)
1325 /// The base class of the type hierarchy.
1327 /// A central concept with types is that each type always has a canonical
1328 /// type. A canonical type is the type with any typedef names stripped out
1329 /// of it or the types it references. For example, consider:
1331 /// typedef int foo;
1332 /// typedef foo* bar;
1333 /// 'int *' 'foo *' 'bar'
1335 /// There will be a Type object created for 'int'. Since int is canonical, its
1336 /// CanonicalType pointer points to itself. There is also a Type for 'foo' (a
1337 /// TypedefType). Its CanonicalType pointer points to the 'int' Type. Next
1338 /// there is a PointerType that represents 'int*', which, like 'int', is
1339 /// canonical. Finally, there is a PointerType type for 'foo*' whose canonical
1340 /// type is 'int*', and there is a TypedefType for 'bar', whose canonical type
1343 /// Non-canonical types are useful for emitting diagnostics, without losing
1344 /// information about typedefs being used. Canonical types are useful for type
1345 /// comparisons (they allow by-pointer equality tests) and useful for reasoning
1346 /// about whether something has a particular form (e.g. is a function type),
1347 /// because they implicitly, recursively, strip all typedefs out of a type.
1349 /// Types, once created, are immutable.
1351 class Type : public ExtQualsTypeCommonBase {
1354 #define TYPE(Class, Base) Class,
1355 #define LAST_TYPE(Class) TypeLast = Class,
1356 #define ABSTRACT_TYPE(Class, Base)
1357 #include "clang/AST/TypeNodes.def"
1358 TagFirst = Record, TagLast = Enum
1362 /// Bitfields required by the Type class.
1363 class TypeBitfields {
1365 template <class T> friend class TypePropertyCache;
1367 /// TypeClass bitfield - Enum that specifies what subclass this belongs to.
1370 /// Whether this type is a dependent type (C++ [temp.dep.type]).
1371 unsigned Dependent : 1;
1373 /// Whether this type somehow involves a template parameter, even
1374 /// if the resolution of the type does not depend on a template parameter.
1375 unsigned InstantiationDependent : 1;
1377 /// Whether this type is a variably-modified type (C99 6.7.5).
1378 unsigned VariablyModified : 1;
1380 /// \brief Whether this type contains an unexpanded parameter pack
1381 /// (for C++11 variadic templates).
1382 unsigned ContainsUnexpandedParameterPack : 1;
1384 /// \brief True if the cache (i.e. the bitfields here starting with
1385 /// 'Cache') is valid.
1386 mutable unsigned CacheValid : 1;
1388 /// \brief Linkage of this type.
1389 mutable unsigned CachedLinkage : 3;
1391 /// \brief Whether this type involves and local or unnamed types.
1392 mutable unsigned CachedLocalOrUnnamed : 1;
1394 /// \brief Whether this type comes from an AST file.
1395 mutable unsigned FromAST : 1;
1397 bool isCacheValid() const {
1401 Linkage getLinkage() const {
1402 assert(isCacheValid() && "getting linkage from invalid cache");
1403 return static_cast<Linkage>(CachedLinkage);
1406 bool hasLocalOrUnnamedType() const {
1407 assert(isCacheValid() && "getting linkage from invalid cache");
1408 return CachedLocalOrUnnamed;
1411 enum { NumTypeBits = 18 };
1414 // These classes allow subclasses to somewhat cleanly pack bitfields
1417 class ArrayTypeBitfields {
1418 friend class ArrayType;
1420 unsigned : NumTypeBits;
1422 /// CVR qualifiers from declarations like
1423 /// 'int X[static restrict 4]'. For function parameters only.
1424 unsigned IndexTypeQuals : 3;
1426 /// Storage class qualifiers from declarations like
1427 /// 'int X[static restrict 4]'. For function parameters only.
1428 /// Actually an ArrayType::ArraySizeModifier.
1429 unsigned SizeModifier : 3;
1432 class BuiltinTypeBitfields {
1433 friend class BuiltinType;
1435 unsigned : NumTypeBits;
1437 /// The kind (BuiltinType::Kind) of builtin type this is.
1441 class FunctionTypeBitfields {
1442 friend class FunctionProtoType;
1443 friend class FunctionType;
1445 unsigned : NumTypeBits;
1447 /// Extra information which affects how the function is called, like
1448 /// regparm and the calling convention.
1449 unsigned ExtInfo : 11;
1451 /// Used only by FunctionProtoType, put here to pack with the
1452 /// other bitfields.
1453 /// The qualifiers are part of FunctionProtoType because...
1455 /// C++ 8.3.5p4: The return type, the parameter type list and the
1456 /// cv-qualifier-seq, [...], are part of the function type.
1457 unsigned TypeQuals : 4;
1459 /// \brief The ref-qualifier associated with a \c FunctionProtoType.
1461 /// This is a value of type \c RefQualifierKind.
1462 unsigned RefQualifier : 2;
1465 class ObjCObjectTypeBitfields {
1466 friend class ObjCObjectType;
1468 unsigned : NumTypeBits;
1470 /// The number of type arguments stored directly on this object type.
1471 unsigned NumTypeArgs : 7;
1473 /// The number of protocols stored directly on this object type.
1474 unsigned NumProtocols : 6;
1476 /// Whether this is a "kindof" type.
1477 unsigned IsKindOf : 1;
1480 static_assert(NumTypeBits + 7 + 6 + 1 <= 32, "Does not fit in an unsigned");
1482 class ReferenceTypeBitfields {
1483 friend class ReferenceType;
1485 unsigned : NumTypeBits;
1487 /// True if the type was originally spelled with an lvalue sigil.
1488 /// This is never true of rvalue references but can also be false
1489 /// on lvalue references because of C++0x [dcl.typedef]p9,
1492 /// typedef int &ref; // lvalue, spelled lvalue
1493 /// typedef int &&rvref; // rvalue
1494 /// ref &a; // lvalue, inner ref, spelled lvalue
1495 /// ref &&a; // lvalue, inner ref
1496 /// rvref &a; // lvalue, inner ref, spelled lvalue
1497 /// rvref &&a; // rvalue, inner ref
1498 unsigned SpelledAsLValue : 1;
1500 /// True if the inner type is a reference type. This only happens
1501 /// in non-canonical forms.
1502 unsigned InnerRef : 1;
1505 class TypeWithKeywordBitfields {
1506 friend class TypeWithKeyword;
1508 unsigned : NumTypeBits;
1510 /// An ElaboratedTypeKeyword. 8 bits for efficient access.
1511 unsigned Keyword : 8;
1514 class VectorTypeBitfields {
1515 friend class VectorType;
1517 unsigned : NumTypeBits;
1519 /// The kind of vector, either a generic vector type or some
1520 /// target-specific vector type such as for AltiVec or Neon.
1521 unsigned VecKind : 3;
1523 /// The number of elements in the vector.
1524 unsigned NumElements : 29 - NumTypeBits;
1526 enum { MaxNumElements = (1 << (29 - NumTypeBits)) - 1 };
1529 class AttributedTypeBitfields {
1530 friend class AttributedType;
1532 unsigned : NumTypeBits;
1534 /// An AttributedType::Kind
1535 unsigned AttrKind : 32 - NumTypeBits;
1538 class AutoTypeBitfields {
1539 friend class AutoType;
1541 unsigned : NumTypeBits;
1543 /// Was this placeholder type spelled as 'auto', 'decltype(auto)',
1544 /// or '__auto_type'? AutoTypeKeyword value.
1545 unsigned Keyword : 2;
1549 TypeBitfields TypeBits;
1550 ArrayTypeBitfields ArrayTypeBits;
1551 AttributedTypeBitfields AttributedTypeBits;
1552 AutoTypeBitfields AutoTypeBits;
1553 BuiltinTypeBitfields BuiltinTypeBits;
1554 FunctionTypeBitfields FunctionTypeBits;
1555 ObjCObjectTypeBitfields ObjCObjectTypeBits;
1556 ReferenceTypeBitfields ReferenceTypeBits;
1557 TypeWithKeywordBitfields TypeWithKeywordBits;
1558 VectorTypeBitfields VectorTypeBits;
1562 template <class T> friend class TypePropertyCache;
1564 /// \brief Set whether this type comes from an AST file.
1565 void setFromAST(bool V = true) const {
1566 TypeBits.FromAST = V;
1570 friend class ASTContext;
1572 Type(TypeClass tc, QualType canon, bool Dependent,
1573 bool InstantiationDependent, bool VariablyModified,
1574 bool ContainsUnexpandedParameterPack)
1575 : ExtQualsTypeCommonBase(this,
1576 canon.isNull() ? QualType(this_(), 0) : canon) {
1578 TypeBits.Dependent = Dependent;
1579 TypeBits.InstantiationDependent = Dependent || InstantiationDependent;
1580 TypeBits.VariablyModified = VariablyModified;
1581 TypeBits.ContainsUnexpandedParameterPack = ContainsUnexpandedParameterPack;
1582 TypeBits.CacheValid = false;
1583 TypeBits.CachedLocalOrUnnamed = false;
1584 TypeBits.CachedLinkage = NoLinkage;
1585 TypeBits.FromAST = false;
1588 // silence VC++ warning C4355: 'this' : used in base member initializer list
1589 Type *this_() { return this; }
1591 void setDependent(bool D = true) {
1592 TypeBits.Dependent = D;
1594 TypeBits.InstantiationDependent = true;
1597 void setInstantiationDependent(bool D = true) {
1598 TypeBits.InstantiationDependent = D; }
1600 void setVariablyModified(bool VM = true) { TypeBits.VariablyModified = VM; }
1602 void setContainsUnexpandedParameterPack(bool PP = true) {
1603 TypeBits.ContainsUnexpandedParameterPack = PP;
1607 friend class ASTReader;
1608 friend class ASTWriter;
1610 Type(const Type &) = delete;
1611 Type &operator=(const Type &) = delete;
1613 TypeClass getTypeClass() const { return static_cast<TypeClass>(TypeBits.TC); }
1615 /// \brief Whether this type comes from an AST file.
1616 bool isFromAST() const { return TypeBits.FromAST; }
1618 /// \brief Whether this type is or contains an unexpanded parameter
1619 /// pack, used to support C++0x variadic templates.
1621 /// A type that contains a parameter pack shall be expanded by the
1622 /// ellipsis operator at some point. For example, the typedef in the
1623 /// following example contains an unexpanded parameter pack 'T':
1626 /// template<typename ...T>
1628 /// typedef T* pointer_types; // ill-formed; T is a parameter pack.
1632 /// Note that this routine does not specify which
1633 bool containsUnexpandedParameterPack() const {
1634 return TypeBits.ContainsUnexpandedParameterPack;
1637 /// Determines if this type would be canonical if it had no further
1639 bool isCanonicalUnqualified() const {
1640 return CanonicalType == QualType(this, 0);
1643 /// Pull a single level of sugar off of this locally-unqualified type.
1644 /// Users should generally prefer SplitQualType::getSingleStepDesugaredType()
1645 /// or QualType::getSingleStepDesugaredType(const ASTContext&).
1646 QualType getLocallyUnqualifiedSingleStepDesugaredType() const;
1648 /// Types are partitioned into 3 broad categories (C99 6.2.5p1):
1649 /// object types, function types, and incomplete types.
1651 /// Return true if this is an incomplete type.
1652 /// A type that can describe objects, but which lacks information needed to
1653 /// determine its size (e.g. void, or a fwd declared struct). Clients of this
1654 /// routine will need to determine if the size is actually required.
1656 /// \brief Def If non-null, and the type refers to some kind of declaration
1657 /// that can be completed (such as a C struct, C++ class, or Objective-C
1658 /// class), will be set to the declaration.
1659 bool isIncompleteType(NamedDecl **Def = nullptr) const;
1661 /// Return true if this is an incomplete or object
1662 /// type, in other words, not a function type.
1663 bool isIncompleteOrObjectType() const {
1664 return !isFunctionType();
1667 /// \brief Determine whether this type is an object type.
1668 bool isObjectType() const {
1669 // C++ [basic.types]p8:
1670 // An object type is a (possibly cv-qualified) type that is not a
1671 // function type, not a reference type, and not a void type.
1672 return !isReferenceType() && !isFunctionType() && !isVoidType();
1675 /// Return true if this is a literal type
1676 /// (C++11 [basic.types]p10)
1677 bool isLiteralType(const ASTContext &Ctx) const;
1679 /// Test if this type is a standard-layout type.
1680 /// (C++0x [basic.type]p9)
1681 bool isStandardLayoutType() const;
1683 /// Helper methods to distinguish type categories. All type predicates
1684 /// operate on the canonical type, ignoring typedefs and qualifiers.
1686 /// Returns true if the type is a builtin type.
1687 bool isBuiltinType() const;
1689 /// Test for a particular builtin type.
1690 bool isSpecificBuiltinType(unsigned K) const;
1692 /// Test for a type which does not represent an actual type-system type but
1693 /// is instead used as a placeholder for various convenient purposes within
1694 /// Clang. All such types are BuiltinTypes.
1695 bool isPlaceholderType() const;
1696 const BuiltinType *getAsPlaceholderType() const;
1698 /// Test for a specific placeholder type.
1699 bool isSpecificPlaceholderType(unsigned K) const;
1701 /// Test for a placeholder type other than Overload; see
1702 /// BuiltinType::isNonOverloadPlaceholderType.
1703 bool isNonOverloadPlaceholderType() const;
1705 /// isIntegerType() does *not* include complex integers (a GCC extension).
1706 /// isComplexIntegerType() can be used to test for complex integers.
1707 bool isIntegerType() const; // C99 6.2.5p17 (int, char, bool, enum)
1708 bool isEnumeralType() const;
1709 bool isBooleanType() const;
1710 bool isCharType() const;
1711 bool isWideCharType() const;
1712 bool isChar16Type() const;
1713 bool isChar32Type() const;
1714 bool isAnyCharacterType() const;
1715 bool isIntegralType(const ASTContext &Ctx) const;
1717 /// Determine whether this type is an integral or enumeration type.
1718 bool isIntegralOrEnumerationType() const;
1720 /// Determine whether this type is an integral or unscoped enumeration type.
1721 bool isIntegralOrUnscopedEnumerationType() const;
1723 /// Floating point categories.
1724 bool isRealFloatingType() const; // C99 6.2.5p10 (float, double, long double)
1725 /// isComplexType() does *not* include complex integers (a GCC extension).
1726 /// isComplexIntegerType() can be used to test for complex integers.
1727 bool isComplexType() const; // C99 6.2.5p11 (complex)
1728 bool isAnyComplexType() const; // C99 6.2.5p11 (complex) + Complex Int.
1729 bool isFloatingType() const; // C99 6.2.5p11 (real floating + complex)
1730 bool isHalfType() const; // OpenCL 6.1.1.1, NEON (IEEE 754-2008 half)
1731 bool isRealType() const; // C99 6.2.5p17 (real floating + integer)
1732 bool isArithmeticType() const; // C99 6.2.5p18 (integer + floating)
1733 bool isVoidType() const; // C99 6.2.5p19
1734 bool isScalarType() const; // C99 6.2.5p21 (arithmetic + pointers)
1735 bool isAggregateType() const;
1736 bool isFundamentalType() const;
1737 bool isCompoundType() const;
1739 // Type Predicates: Check to see if this type is structurally the specified
1740 // type, ignoring typedefs and qualifiers.
1741 bool isFunctionType() const;
1742 bool isFunctionNoProtoType() const { return getAs<FunctionNoProtoType>(); }
1743 bool isFunctionProtoType() const { return getAs<FunctionProtoType>(); }
1744 bool isPointerType() const;
1745 bool isAnyPointerType() const; // Any C pointer or ObjC object pointer
1746 bool isBlockPointerType() const;
1747 bool isVoidPointerType() const;
1748 bool isReferenceType() const;
1749 bool isLValueReferenceType() const;
1750 bool isRValueReferenceType() const;
1751 bool isFunctionPointerType() const;
1752 bool isMemberPointerType() const;
1753 bool isMemberFunctionPointerType() const;
1754 bool isMemberDataPointerType() const;
1755 bool isArrayType() const;
1756 bool isConstantArrayType() const;
1757 bool isIncompleteArrayType() const;
1758 bool isVariableArrayType() const;
1759 bool isDependentSizedArrayType() const;
1760 bool isRecordType() const;
1761 bool isClassType() const;
1762 bool isStructureType() const;
1763 bool isObjCBoxableRecordType() const;
1764 bool isInterfaceType() const;
1765 bool isStructureOrClassType() const;
1766 bool isUnionType() const;
1767 bool isComplexIntegerType() const; // GCC _Complex integer type.
1768 bool isVectorType() const; // GCC vector type.
1769 bool isExtVectorType() const; // Extended vector type.
1770 bool isDependentAddressSpaceType() const; // value-dependent address space qualifier
1771 bool isObjCObjectPointerType() const; // pointer to ObjC object
1772 bool isObjCRetainableType() const; // ObjC object or block pointer
1773 bool isObjCLifetimeType() const; // (array of)* retainable type
1774 bool isObjCIndirectLifetimeType() const; // (pointer to)* lifetime type
1775 bool isObjCNSObjectType() const; // __attribute__((NSObject))
1776 bool isObjCIndependentClassType() const; // __attribute__((objc_independent_class))
1777 // FIXME: change this to 'raw' interface type, so we can used 'interface' type
1778 // for the common case.
1779 bool isObjCObjectType() const; // NSString or typeof(*(id)0)
1780 bool isObjCQualifiedInterfaceType() const; // NSString<foo>
1781 bool isObjCQualifiedIdType() const; // id<foo>
1782 bool isObjCQualifiedClassType() const; // Class<foo>
1783 bool isObjCObjectOrInterfaceType() const;
1784 bool isObjCIdType() const; // id
1785 bool isObjCInertUnsafeUnretainedType() const;
1787 /// Whether the type is Objective-C 'id' or a __kindof type of an
1788 /// object type, e.g., __kindof NSView * or __kindof id
1791 /// \param bound Will be set to the bound on non-id subtype types,
1792 /// which will be (possibly specialized) Objective-C class type, or
1794 bool isObjCIdOrObjectKindOfType(const ASTContext &ctx,
1795 const ObjCObjectType *&bound) const;
1797 bool isObjCClassType() const; // Class
1799 /// Whether the type is Objective-C 'Class' or a __kindof type of an
1800 /// Class type, e.g., __kindof Class <NSCopying>.
1802 /// Unlike \c isObjCIdOrObjectKindOfType, there is no relevant bound
1803 /// here because Objective-C's type system cannot express "a class
1804 /// object for a subclass of NSFoo".
1805 bool isObjCClassOrClassKindOfType() const;
1807 bool isBlockCompatibleObjCPointerType(ASTContext &ctx) const;
1808 bool isObjCSelType() const; // Class
1809 bool isObjCBuiltinType() const; // 'id' or 'Class'
1810 bool isObjCARCBridgableType() const;
1811 bool isCARCBridgableType() const;
1812 bool isTemplateTypeParmType() const; // C++ template type parameter
1813 bool isNullPtrType() const; // C++11 std::nullptr_t
1814 bool isAlignValT() const; // C++17 std::align_val_t
1815 bool isStdByteType() const; // C++17 std::byte
1816 bool isAtomicType() const; // C11 _Atomic()
1818 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
1819 bool is##Id##Type() const;
1820 #include "clang/Basic/OpenCLImageTypes.def"
1822 bool isImageType() const; // Any OpenCL image type
1824 bool isSamplerT() const; // OpenCL sampler_t
1825 bool isEventT() const; // OpenCL event_t
1826 bool isClkEventT() const; // OpenCL clk_event_t
1827 bool isQueueT() const; // OpenCL queue_t
1828 bool isReserveIDT() const; // OpenCL reserve_id_t
1830 bool isPipeType() const; // OpenCL pipe type
1831 bool isOpenCLSpecificType() const; // Any OpenCL specific type
1833 /// Determines if this type, which must satisfy
1834 /// isObjCLifetimeType(), is implicitly __unsafe_unretained rather
1835 /// than implicitly __strong.
1836 bool isObjCARCImplicitlyUnretainedType() const;
1838 /// Return the implicit lifetime for this type, which must not be dependent.
1839 Qualifiers::ObjCLifetime getObjCARCImplicitLifetime() const;
1841 enum ScalarTypeKind {
1844 STK_ObjCObjectPointer,
1849 STK_IntegralComplex,
1853 /// Given that this is a scalar type, classify it.
1854 ScalarTypeKind getScalarTypeKind() const;
1856 /// Whether this type is a dependent type, meaning that its definition
1857 /// somehow depends on a template parameter (C++ [temp.dep.type]).
1858 bool isDependentType() const { return TypeBits.Dependent; }
1860 /// \brief Determine whether this type is an instantiation-dependent type,
1861 /// meaning that the type involves a template parameter (even if the
1862 /// definition does not actually depend on the type substituted for that
1863 /// template parameter).
1864 bool isInstantiationDependentType() const {
1865 return TypeBits.InstantiationDependent;
1868 /// \brief Determine whether this type is an undeduced type, meaning that
1869 /// it somehow involves a C++11 'auto' type or similar which has not yet been
1871 bool isUndeducedType() const;
1873 /// \brief Whether this type is a variably-modified type (C99 6.7.5).
1874 bool isVariablyModifiedType() const { return TypeBits.VariablyModified; }
1876 /// \brief Whether this type involves a variable-length array type
1877 /// with a definite size.
1878 bool hasSizedVLAType() const;
1880 /// \brief Whether this type is or contains a local or unnamed type.
1881 bool hasUnnamedOrLocalType() const;
1883 bool isOverloadableType() const;
1885 /// \brief Determine wither this type is a C++ elaborated-type-specifier.
1886 bool isElaboratedTypeSpecifier() const;
1888 bool canDecayToPointerType() const;
1890 /// Whether this type is represented natively as a pointer. This includes
1891 /// pointers, references, block pointers, and Objective-C interface,
1892 /// qualified id, and qualified interface types, as well as nullptr_t.
1893 bool hasPointerRepresentation() const;
1895 /// Whether this type can represent an objective pointer type for the
1896 /// purpose of GC'ability
1897 bool hasObjCPointerRepresentation() const;
1899 /// \brief Determine whether this type has an integer representation
1900 /// of some sort, e.g., it is an integer type or a vector.
1901 bool hasIntegerRepresentation() const;
1903 /// \brief Determine whether this type has an signed integer representation
1904 /// of some sort, e.g., it is an signed integer type or a vector.
1905 bool hasSignedIntegerRepresentation() const;
1907 /// \brief Determine whether this type has an unsigned integer representation
1908 /// of some sort, e.g., it is an unsigned integer type or a vector.
1909 bool hasUnsignedIntegerRepresentation() const;
1911 /// \brief Determine whether this type has a floating-point representation
1912 /// of some sort, e.g., it is a floating-point type or a vector thereof.
1913 bool hasFloatingRepresentation() const;
1915 // Type Checking Functions: Check to see if this type is structurally the
1916 // specified type, ignoring typedefs and qualifiers, and return a pointer to
1917 // the best type we can.
1918 const RecordType *getAsStructureType() const;
1919 /// NOTE: getAs*ArrayType are methods on ASTContext.
1920 const RecordType *getAsUnionType() const;
1921 const ComplexType *getAsComplexIntegerType() const; // GCC complex int type.
1922 const ObjCObjectType *getAsObjCInterfaceType() const;
1924 // The following is a convenience method that returns an ObjCObjectPointerType
1925 // for object declared using an interface.
1926 const ObjCObjectPointerType *getAsObjCInterfacePointerType() const;
1927 const ObjCObjectPointerType *getAsObjCQualifiedIdType() const;
1928 const ObjCObjectPointerType *getAsObjCQualifiedClassType() const;
1929 const ObjCObjectType *getAsObjCQualifiedInterfaceType() const;
1931 /// \brief Retrieves the CXXRecordDecl that this type refers to, either
1932 /// because the type is a RecordType or because it is the injected-class-name
1933 /// type of a class template or class template partial specialization.
1934 CXXRecordDecl *getAsCXXRecordDecl() const;
1936 /// \brief Retrieves the TagDecl that this type refers to, either
1937 /// because the type is a TagType or because it is the injected-class-name
1938 /// type of a class template or class template partial specialization.
1939 TagDecl *getAsTagDecl() const;
1941 /// If this is a pointer or reference to a RecordType, return the
1942 /// CXXRecordDecl that that type refers to.
1944 /// If this is not a pointer or reference, or the type being pointed to does
1945 /// not refer to a CXXRecordDecl, returns NULL.
1946 const CXXRecordDecl *getPointeeCXXRecordDecl() const;
1948 /// Get the DeducedType whose type will be deduced for a variable with
1949 /// an initializer of this type. This looks through declarators like pointer
1950 /// types, but not through decltype or typedefs.
1951 DeducedType *getContainedDeducedType() const;
1953 /// Get the AutoType whose type will be deduced for a variable with
1954 /// an initializer of this type. This looks through declarators like pointer
1955 /// types, but not through decltype or typedefs.
1956 AutoType *getContainedAutoType() const {
1957 return dyn_cast_or_null<AutoType>(getContainedDeducedType());
1960 /// Determine whether this type was written with a leading 'auto'
1961 /// corresponding to a trailing return type (possibly for a nested
1962 /// function type within a pointer to function type or similar).
1963 bool hasAutoForTrailingReturnType() const;
1965 /// Member-template getAs<specific type>'. Look through sugar for
1966 /// an instance of \<specific type>. This scheme will eventually
1967 /// replace the specific getAsXXXX methods above.
1969 /// There are some specializations of this member template listed
1970 /// immediately following this class.
1971 template <typename T> const T *getAs() const;
1973 /// Member-template getAsAdjusted<specific type>. Look through specific kinds
1974 /// of sugar (parens, attributes, etc) for an instance of \<specific type>.
1975 /// This is used when you need to walk over sugar nodes that represent some
1976 /// kind of type adjustment from a type that was written as a \<specific type>
1977 /// to another type that is still canonically a \<specific type>.
1978 template <typename T> const T *getAsAdjusted() const;
1980 /// A variant of getAs<> for array types which silently discards
1981 /// qualifiers from the outermost type.
1982 const ArrayType *getAsArrayTypeUnsafe() const;
1984 /// Member-template castAs<specific type>. Look through sugar for
1985 /// the underlying instance of \<specific type>.
1987 /// This method has the same relationship to getAs<T> as cast<T> has
1988 /// to dyn_cast<T>; which is to say, the underlying type *must*
1989 /// have the intended type, and this method will never return null.
1990 template <typename T> const T *castAs() const;
1992 /// A variant of castAs<> for array type which silently discards
1993 /// qualifiers from the outermost type.
1994 const ArrayType *castAsArrayTypeUnsafe() const;
1996 /// Get the base element type of this type, potentially discarding type
1997 /// qualifiers. This should never be used when type qualifiers
1999 const Type *getBaseElementTypeUnsafe() const;
2001 /// If this is an array type, return the element type of the array,
2002 /// potentially with type qualifiers missing.
2003 /// This should never be used when type qualifiers are meaningful.
2004 const Type *getArrayElementTypeNoTypeQual() const;
2006 /// If this is a pointer type, return the pointee type.
2007 /// If this is an array type, return the array element type.
2008 /// This should never be used when type qualifiers are meaningful.
2009 const Type *getPointeeOrArrayElementType() const;
2011 /// If this is a pointer, ObjC object pointer, or block
2012 /// pointer, this returns the respective pointee.
2013 QualType getPointeeType() const;
2015 /// Return the specified type with any "sugar" removed from the type,
2016 /// removing any typedefs, typeofs, etc., as well as any qualifiers.
2017 const Type *getUnqualifiedDesugaredType() const;
2019 /// More type predicates useful for type checking/promotion
2020 bool isPromotableIntegerType() const; // C99 6.3.1.1p2
2022 /// Return true if this is an integer type that is
2023 /// signed, according to C99 6.2.5p4 [char, signed char, short, int, long..],
2024 /// or an enum decl which has a signed representation.
2025 bool isSignedIntegerType() const;
2027 /// Return true if this is an integer type that is
2028 /// unsigned, according to C99 6.2.5p6 [which returns true for _Bool],
2029 /// or an enum decl which has an unsigned representation.
2030 bool isUnsignedIntegerType() const;
2032 /// Determines whether this is an integer type that is signed or an
2033 /// enumeration types whose underlying type is a signed integer type.
2034 bool isSignedIntegerOrEnumerationType() const;
2036 /// Determines whether this is an integer type that is unsigned or an
2037 /// enumeration types whose underlying type is a unsigned integer type.
2038 bool isUnsignedIntegerOrEnumerationType() const;
2040 /// Return true if this is not a variable sized type,
2041 /// according to the rules of C99 6.7.5p3. It is not legal to call this on
2042 /// incomplete types.
2043 bool isConstantSizeType() const;
2045 /// Returns true if this type can be represented by some
2046 /// set of type specifiers.
2047 bool isSpecifierType() const;
2049 /// Determine the linkage of this type.
2050 Linkage getLinkage() const;
2052 /// Determine the visibility of this type.
2053 Visibility getVisibility() const {
2054 return getLinkageAndVisibility().getVisibility();
2057 /// Return true if the visibility was explicitly set is the code.
2058 bool isVisibilityExplicit() const {
2059 return getLinkageAndVisibility().isVisibilityExplicit();
2062 /// Determine the linkage and visibility of this type.
2063 LinkageInfo getLinkageAndVisibility() const;
2065 /// True if the computed linkage is valid. Used for consistency
2066 /// checking. Should always return true.
2067 bool isLinkageValid() const;
2069 /// Determine the nullability of the given type.
2071 /// Note that nullability is only captured as sugar within the type
2072 /// system, not as part of the canonical type, so nullability will
2073 /// be lost by canonicalization and desugaring.
2074 Optional<NullabilityKind> getNullability(const ASTContext &context) const;
2076 /// Determine whether the given type can have a nullability
2077 /// specifier applied to it, i.e., if it is any kind of pointer type.
2079 /// \param ResultIfUnknown The value to return if we don't yet know whether
2080 /// this type can have nullability because it is dependent.
2081 bool canHaveNullability(bool ResultIfUnknown = true) const;
2083 /// Retrieve the set of substitutions required when accessing a member
2084 /// of the Objective-C receiver type that is declared in the given context.
2086 /// \c *this is the type of the object we're operating on, e.g., the
2087 /// receiver for a message send or the base of a property access, and is
2088 /// expected to be of some object or object pointer type.
2090 /// \param dc The declaration context for which we are building up a
2091 /// substitution mapping, which should be an Objective-C class, extension,
2092 /// category, or method within.
2094 /// \returns an array of type arguments that can be substituted for
2095 /// the type parameters of the given declaration context in any type described
2096 /// within that context, or an empty optional to indicate that no
2097 /// substitution is required.
2098 Optional<ArrayRef<QualType>>
2099 getObjCSubstitutions(const DeclContext *dc) const;
2101 /// Determines if this is an ObjC interface type that may accept type
2103 bool acceptsObjCTypeParams() const;
2105 const char *getTypeClassName() const;
2107 QualType getCanonicalTypeInternal() const {
2108 return CanonicalType;
2111 CanQualType getCanonicalTypeUnqualified() const; // in CanonicalType.h
2113 void dump(llvm::raw_ostream &OS) const;
2116 /// \brief This will check for a TypedefType by removing any existing sugar
2117 /// until it reaches a TypedefType or a non-sugared type.
2118 template <> const TypedefType *Type::getAs() const;
2120 /// \brief This will check for a TemplateSpecializationType by removing any
2121 /// existing sugar until it reaches a TemplateSpecializationType or a
2122 /// non-sugared type.
2123 template <> const TemplateSpecializationType *Type::getAs() const;
2125 /// \brief This will check for an AttributedType by removing any existing sugar
2126 /// until it reaches an AttributedType or a non-sugared type.
2127 template <> const AttributedType *Type::getAs() const;
2129 // We can do canonical leaf types faster, because we don't have to
2130 // worry about preserving child type decoration.
2131 #define TYPE(Class, Base)
2132 #define LEAF_TYPE(Class) \
2133 template <> inline const Class##Type *Type::getAs() const { \
2134 return dyn_cast<Class##Type>(CanonicalType); \
2136 template <> inline const Class##Type *Type::castAs() const { \
2137 return cast<Class##Type>(CanonicalType); \
2139 #include "clang/AST/TypeNodes.def"
2141 /// This class is used for builtin types like 'int'. Builtin
2142 /// types are always canonical and have a literal name field.
2143 class BuiltinType : public Type {
2146 // OpenCL image types
2147 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) Id,
2148 #include "clang/Basic/OpenCLImageTypes.def"
2149 // All other builtin types
2150 #define BUILTIN_TYPE(Id, SingletonId) Id,
2151 #define LAST_BUILTIN_TYPE(Id) LastKind = Id
2152 #include "clang/AST/BuiltinTypes.def"
2157 : Type(Builtin, QualType(), /*Dependent=*/(K == Dependent),
2158 /*InstantiationDependent=*/(K == Dependent),
2159 /*VariablyModified=*/false,
2160 /*Unexpanded parameter pack=*/false) {
2161 BuiltinTypeBits.Kind = K;
2164 Kind getKind() const { return static_cast<Kind>(BuiltinTypeBits.Kind); }
2165 StringRef getName(const PrintingPolicy &Policy) const;
2167 const char *getNameAsCString(const PrintingPolicy &Policy) const {
2168 // The StringRef is null-terminated.
2169 StringRef str = getName(Policy);
2170 assert(!str.empty() && str.data()[str.size()] == '\0');
2174 bool isSugared() const { return false; }
2175 QualType desugar() const { return QualType(this, 0); }
2177 bool isInteger() const {
2178 return getKind() >= Bool && getKind() <= Int128;
2181 bool isSignedInteger() const {
2182 return getKind() >= Char_S && getKind() <= Int128;
2185 bool isUnsignedInteger() const {
2186 return getKind() >= Bool && getKind() <= UInt128;
2189 bool isFloatingPoint() const {
2190 return getKind() >= Half && getKind() <= Float128;
2193 /// Determines whether the given kind corresponds to a placeholder type.
2194 static bool isPlaceholderTypeKind(Kind K) {
2195 return K >= Overload;
2198 /// Determines whether this type is a placeholder type, i.e. a type
2199 /// which cannot appear in arbitrary positions in a fully-formed
2201 bool isPlaceholderType() const {
2202 return isPlaceholderTypeKind(getKind());
2205 /// Determines whether this type is a placeholder type other than
2206 /// Overload. Most placeholder types require only syntactic
2207 /// information about their context in order to be resolved (e.g.
2208 /// whether it is a call expression), which means they can (and
2209 /// should) be resolved in an earlier "phase" of analysis.
2210 /// Overload expressions sometimes pick up further information
2211 /// from their context, like whether the context expects a
2212 /// specific function-pointer type, and so frequently need
2213 /// special treatment.
2214 bool isNonOverloadPlaceholderType() const {
2215 return getKind() > Overload;
2218 static bool classof(const Type *T) { return T->getTypeClass() == Builtin; }
2221 /// Complex values, per C99 6.2.5p11. This supports the C99 complex
2222 /// types (_Complex float etc) as well as the GCC integer complex extensions.
2223 class ComplexType : public Type, public llvm::FoldingSetNode {
2224 friend class ASTContext; // ASTContext creates these.
2226 QualType ElementType;
2228 ComplexType(QualType Element, QualType CanonicalPtr)
2229 : Type(Complex, CanonicalPtr, Element->isDependentType(),
2230 Element->isInstantiationDependentType(),
2231 Element->isVariablyModifiedType(),
2232 Element->containsUnexpandedParameterPack()),
2233 ElementType(Element) {}
2236 QualType getElementType() const { return ElementType; }
2238 bool isSugared() const { return false; }
2239 QualType desugar() const { return QualType(this, 0); }
2241 void Profile(llvm::FoldingSetNodeID &ID) {
2242 Profile(ID, getElementType());
2245 static void Profile(llvm::FoldingSetNodeID &ID, QualType Element) {
2246 ID.AddPointer(Element.getAsOpaquePtr());
2249 static bool classof(const Type *T) { return T->getTypeClass() == Complex; }
2252 /// Sugar for parentheses used when specifying types.
2253 class ParenType : public Type, public llvm::FoldingSetNode {
2254 friend class ASTContext; // ASTContext creates these.
2258 ParenType(QualType InnerType, QualType CanonType)
2259 : Type(Paren, CanonType, InnerType->isDependentType(),
2260 InnerType->isInstantiationDependentType(),
2261 InnerType->isVariablyModifiedType(),
2262 InnerType->containsUnexpandedParameterPack()),
2266 QualType getInnerType() const { return Inner; }
2268 bool isSugared() const { return true; }
2269 QualType desugar() const { return getInnerType(); }
2271 void Profile(llvm::FoldingSetNodeID &ID) {
2272 Profile(ID, getInnerType());
2275 static void Profile(llvm::FoldingSetNodeID &ID, QualType Inner) {
2279 static bool classof(const Type *T) { return T->getTypeClass() == Paren; }
2282 /// PointerType - C99 6.7.5.1 - Pointer Declarators.
2283 class PointerType : public Type, public llvm::FoldingSetNode {
2284 friend class ASTContext; // ASTContext creates these.
2286 QualType PointeeType;
2288 PointerType(QualType Pointee, QualType CanonicalPtr)
2289 : Type(Pointer, CanonicalPtr, Pointee->isDependentType(),
2290 Pointee->isInstantiationDependentType(),
2291 Pointee->isVariablyModifiedType(),
2292 Pointee->containsUnexpandedParameterPack()),
2293 PointeeType(Pointee) {}
2296 QualType getPointeeType() const { return PointeeType; }
2298 /// Returns true if address spaces of pointers overlap.
2299 /// OpenCL v2.0 defines conversion rules for pointers to different
2300 /// address spaces (OpenCLC v2.0 s6.5.5) and notion of overlapping
2303 /// address spaces overlap iff they are they same.
2305 /// __generic overlaps with any address space except for __constant.
2306 bool isAddressSpaceOverlapping(const PointerType &other) const {
2307 Qualifiers thisQuals = PointeeType.getQualifiers();
2308 Qualifiers otherQuals = other.getPointeeType().getQualifiers();
2309 // Address spaces overlap if at least one of them is a superset of another
2310 return thisQuals.isAddressSpaceSupersetOf(otherQuals) ||
2311 otherQuals.isAddressSpaceSupersetOf(thisQuals);
2314 bool isSugared() const { return false; }
2315 QualType desugar() const { return QualType(this, 0); }
2317 void Profile(llvm::FoldingSetNodeID &ID) {
2318 Profile(ID, getPointeeType());
2321 static void Profile(llvm::FoldingSetNodeID &ID, QualType Pointee) {
2322 ID.AddPointer(Pointee.getAsOpaquePtr());
2325 static bool classof(const Type *T) { return T->getTypeClass() == Pointer; }
2328 /// Represents a type which was implicitly adjusted by the semantic
2329 /// engine for arbitrary reasons. For example, array and function types can
2330 /// decay, and function types can have their calling conventions adjusted.
2331 class AdjustedType : public Type, public llvm::FoldingSetNode {
2332 QualType OriginalTy;
2333 QualType AdjustedTy;
2336 friend class ASTContext; // ASTContext creates these.
2338 AdjustedType(TypeClass TC, QualType OriginalTy, QualType AdjustedTy,
2339 QualType CanonicalPtr)
2340 : Type(TC, CanonicalPtr, OriginalTy->isDependentType(),
2341 OriginalTy->isInstantiationDependentType(),
2342 OriginalTy->isVariablyModifiedType(),
2343 OriginalTy->containsUnexpandedParameterPack()),
2344 OriginalTy(OriginalTy), AdjustedTy(AdjustedTy) {}
2347 QualType getOriginalType() const { return OriginalTy; }
2348 QualType getAdjustedType() const { return AdjustedTy; }
2350 bool isSugared() const { return true; }
2351 QualType desugar() const { return AdjustedTy; }
2353 void Profile(llvm::FoldingSetNodeID &ID) {
2354 Profile(ID, OriginalTy, AdjustedTy);
2357 static void Profile(llvm::FoldingSetNodeID &ID, QualType Orig, QualType New) {
2358 ID.AddPointer(Orig.getAsOpaquePtr());
2359 ID.AddPointer(New.getAsOpaquePtr());
2362 static bool classof(const Type *T) {
2363 return T->getTypeClass() == Adjusted || T->getTypeClass() == Decayed;
2367 /// Represents a pointer type decayed from an array or function type.
2368 class DecayedType : public AdjustedType {
2369 friend class ASTContext; // ASTContext creates these.
2372 DecayedType(QualType OriginalType, QualType Decayed, QualType Canonical);
2375 QualType getDecayedType() const { return getAdjustedType(); }
2377 inline QualType getPointeeType() const;
2379 static bool classof(const Type *T) { return T->getTypeClass() == Decayed; }
2382 /// Pointer to a block type.
2383 /// This type is to represent types syntactically represented as
2384 /// "void (^)(int)", etc. Pointee is required to always be a function type.
2385 class BlockPointerType : public Type, public llvm::FoldingSetNode {
2386 friend class ASTContext; // ASTContext creates these.
2388 // Block is some kind of pointer type
2389 QualType PointeeType;
2391 BlockPointerType(QualType Pointee, QualType CanonicalCls)
2392 : Type(BlockPointer, CanonicalCls, Pointee->isDependentType(),
2393 Pointee->isInstantiationDependentType(),
2394 Pointee->isVariablyModifiedType(),
2395 Pointee->containsUnexpandedParameterPack()),
2396 PointeeType(Pointee) {}
2399 // Get the pointee type. Pointee is required to always be a function type.
2400 QualType getPointeeType() const { return PointeeType; }
2402 bool isSugared() const { return false; }
2403 QualType desugar() const { return QualType(this, 0); }
2405 void Profile(llvm::FoldingSetNodeID &ID) {
2406 Profile(ID, getPointeeType());
2409 static void Profile(llvm::FoldingSetNodeID &ID, QualType Pointee) {
2410 ID.AddPointer(Pointee.getAsOpaquePtr());
2413 static bool classof(const Type *T) {
2414 return T->getTypeClass() == BlockPointer;
2418 /// Base for LValueReferenceType and RValueReferenceType
2419 class ReferenceType : public Type, public llvm::FoldingSetNode {
2420 QualType PointeeType;
2423 ReferenceType(TypeClass tc, QualType Referencee, QualType CanonicalRef,
2424 bool SpelledAsLValue)
2425 : Type(tc, CanonicalRef, Referencee->isDependentType(),
2426 Referencee->isInstantiationDependentType(),
2427 Referencee->isVariablyModifiedType(),
2428 Referencee->containsUnexpandedParameterPack()),
2429 PointeeType(Referencee) {
2430 ReferenceTypeBits.SpelledAsLValue = SpelledAsLValue;
2431 ReferenceTypeBits.InnerRef = Referencee->isReferenceType();
2435 bool isSpelledAsLValue() const { return ReferenceTypeBits.SpelledAsLValue; }
2436 bool isInnerRef() const { return ReferenceTypeBits.InnerRef; }
2438 QualType getPointeeTypeAsWritten() const { return PointeeType; }
2440 QualType getPointeeType() const {
2441 // FIXME: this might strip inner qualifiers; okay?
2442 const ReferenceType *T = this;
2443 while (T->isInnerRef())
2444 T = T->PointeeType->castAs<ReferenceType>();
2445 return T->PointeeType;
2448 void Profile(llvm::FoldingSetNodeID &ID) {
2449 Profile(ID, PointeeType, isSpelledAsLValue());
2452 static void Profile(llvm::FoldingSetNodeID &ID,
2453 QualType Referencee,
2454 bool SpelledAsLValue) {
2455 ID.AddPointer(Referencee.getAsOpaquePtr());
2456 ID.AddBoolean(SpelledAsLValue);
2459 static bool classof(const Type *T) {
2460 return T->getTypeClass() == LValueReference ||
2461 T->getTypeClass() == RValueReference;
2465 /// An lvalue reference type, per C++11 [dcl.ref].
2466 class LValueReferenceType : public ReferenceType {
2467 friend class ASTContext; // ASTContext creates these
2469 LValueReferenceType(QualType Referencee, QualType CanonicalRef,
2470 bool SpelledAsLValue)
2471 : ReferenceType(LValueReference, Referencee, CanonicalRef,
2475 bool isSugared() const { return false; }
2476 QualType desugar() const { return QualType(this, 0); }
2478 static bool classof(const Type *T) {
2479 return T->getTypeClass() == LValueReference;
2483 /// An rvalue reference type, per C++11 [dcl.ref].
2484 class RValueReferenceType : public ReferenceType {
2485 friend class ASTContext; // ASTContext creates these
2487 RValueReferenceType(QualType Referencee, QualType CanonicalRef)
2488 : ReferenceType(RValueReference, Referencee, CanonicalRef, false) {}
2491 bool isSugared() const { return false; }
2492 QualType desugar() const { return QualType(this, 0); }
2494 static bool classof(const Type *T) {
2495 return T->getTypeClass() == RValueReference;
2499 /// A pointer to member type per C++ 8.3.3 - Pointers to members.
2501 /// This includes both pointers to data members and pointer to member functions.
2502 class MemberPointerType : public Type, public llvm::FoldingSetNode {
2503 friend class ASTContext; // ASTContext creates these.
2505 QualType PointeeType;
2507 /// The class of which the pointee is a member. Must ultimately be a
2508 /// RecordType, but could be a typedef or a template parameter too.
2511 MemberPointerType(QualType Pointee, const Type *Cls, QualType CanonicalPtr)
2512 : Type(MemberPointer, CanonicalPtr,
2513 Cls->isDependentType() || Pointee->isDependentType(),
2514 (Cls->isInstantiationDependentType() ||
2515 Pointee->isInstantiationDependentType()),
2516 Pointee->isVariablyModifiedType(),
2517 (Cls->containsUnexpandedParameterPack() ||
2518 Pointee->containsUnexpandedParameterPack())),
2519 PointeeType(Pointee), Class(Cls) {}
2522 QualType getPointeeType() const { return PointeeType; }
2524 /// Returns true if the member type (i.e. the pointee type) is a
2525 /// function type rather than a data-member type.
2526 bool isMemberFunctionPointer() const {
2527 return PointeeType->isFunctionProtoType();
2530 /// Returns true if the member type (i.e. the pointee type) is a
2531 /// data type rather than a function type.
2532 bool isMemberDataPointer() const {
2533 return !PointeeType->isFunctionProtoType();
2536 const Type *getClass() const { return Class; }
2537 CXXRecordDecl *getMostRecentCXXRecordDecl() const;
2539 bool isSugared() const { return false; }
2540 QualType desugar() const { return QualType(this, 0); }
2542 void Profile(llvm::FoldingSetNodeID &ID) {
2543 Profile(ID, getPointeeType(), getClass());
2546 static void Profile(llvm::FoldingSetNodeID &ID, QualType Pointee,
2547 const Type *Class) {
2548 ID.AddPointer(Pointee.getAsOpaquePtr());
2549 ID.AddPointer(Class);
2552 static bool classof(const Type *T) {
2553 return T->getTypeClass() == MemberPointer;
2557 /// Represents an array type, per C99 6.7.5.2 - Array Declarators.
2558 class ArrayType : public Type, public llvm::FoldingSetNode {
2560 /// Capture whether this is a normal array (e.g. int X[4])
2561 /// an array with a static size (e.g. int X[static 4]), or an array
2562 /// with a star size (e.g. int X[*]).
2563 /// 'static' is only allowed on function parameters.
2564 enum ArraySizeModifier {
2565 Normal, Static, Star
2569 /// The element type of the array.
2570 QualType ElementType;
2573 friend class ASTContext; // ASTContext creates these.
2575 // C++ [temp.dep.type]p1:
2576 // A type is dependent if it is...
2577 // - an array type constructed from any dependent type or whose
2578 // size is specified by a constant expression that is
2580 ArrayType(TypeClass tc, QualType et, QualType can,
2581 ArraySizeModifier sm, unsigned tq,
2582 bool ContainsUnexpandedParameterPack)
2583 : Type(tc, can, et->isDependentType() || tc == DependentSizedArray,
2584 et->isInstantiationDependentType() || tc == DependentSizedArray,
2585 (tc == VariableArray || et->isVariablyModifiedType()),
2586 ContainsUnexpandedParameterPack),
2588 ArrayTypeBits.IndexTypeQuals = tq;
2589 ArrayTypeBits.SizeModifier = sm;
2593 QualType getElementType() const { return ElementType; }
2595 ArraySizeModifier getSizeModifier() const {
2596 return ArraySizeModifier(ArrayTypeBits.SizeModifier);
2599 Qualifiers getIndexTypeQualifiers() const {
2600 return Qualifiers::fromCVRMask(getIndexTypeCVRQualifiers());
2603 unsigned getIndexTypeCVRQualifiers() const {
2604 return ArrayTypeBits.IndexTypeQuals;
2607 static bool classof(const Type *T) {
2608 return T->getTypeClass() == ConstantArray ||
2609 T->getTypeClass() == VariableArray ||
2610 T->getTypeClass() == IncompleteArray ||
2611 T->getTypeClass() == DependentSizedArray;
2615 /// Represents the canonical version of C arrays with a specified constant size.
2616 /// For example, the canonical type for 'int A[4 + 4*100]' is a
2617 /// ConstantArrayType where the element type is 'int' and the size is 404.
2618 class ConstantArrayType : public ArrayType {
2619 llvm::APInt Size; // Allows us to unique the type.
2621 ConstantArrayType(QualType et, QualType can, const llvm::APInt &size,
2622 ArraySizeModifier sm, unsigned tq)
2623 : ArrayType(ConstantArray, et, can, sm, tq,
2624 et->containsUnexpandedParameterPack()),
2628 friend class ASTContext; // ASTContext creates these.
2630 ConstantArrayType(TypeClass tc, QualType et, QualType can,
2631 const llvm::APInt &size, ArraySizeModifier sm, unsigned tq)
2632 : ArrayType(tc, et, can, sm, tq, et->containsUnexpandedParameterPack()),
2636 const llvm::APInt &getSize() const { return Size; }
2637 bool isSugared() const { return false; }
2638 QualType desugar() const { return QualType(this, 0); }
2640 /// \brief Determine the number of bits required to address a member of
2641 // an array with the given element type and number of elements.
2642 static unsigned getNumAddressingBits(const ASTContext &Context,
2643 QualType ElementType,
2644 const llvm::APInt &NumElements);
2646 /// \brief Determine the maximum number of active bits that an array's size
2647 /// can require, which limits the maximum size of the array.
2648 static unsigned getMaxSizeBits(const ASTContext &Context);
2650 void Profile(llvm::FoldingSetNodeID &ID) {
2651 Profile(ID, getElementType(), getSize(),
2652 getSizeModifier(), getIndexTypeCVRQualifiers());
2655 static void Profile(llvm::FoldingSetNodeID &ID, QualType ET,
2656 const llvm::APInt &ArraySize, ArraySizeModifier SizeMod,
2657 unsigned TypeQuals) {
2658 ID.AddPointer(ET.getAsOpaquePtr());
2659 ID.AddInteger(ArraySize.getZExtValue());
2660 ID.AddInteger(SizeMod);
2661 ID.AddInteger(TypeQuals);
2664 static bool classof(const Type *T) {
2665 return T->getTypeClass() == ConstantArray;
2669 /// Represents a C array with an unspecified size. For example 'int A[]' has
2670 /// an IncompleteArrayType where the element type is 'int' and the size is
2672 class IncompleteArrayType : public ArrayType {
2673 friend class ASTContext; // ASTContext creates these.
2675 IncompleteArrayType(QualType et, QualType can,
2676 ArraySizeModifier sm, unsigned tq)
2677 : ArrayType(IncompleteArray, et, can, sm, tq,
2678 et->containsUnexpandedParameterPack()) {}
2681 friend class StmtIteratorBase;
2683 bool isSugared() const { return false; }
2684 QualType desugar() const { return QualType(this, 0); }
2686 static bool classof(const Type *T) {
2687 return T->getTypeClass() == IncompleteArray;
2690 void Profile(llvm::FoldingSetNodeID &ID) {
2691 Profile(ID, getElementType(), getSizeModifier(),
2692 getIndexTypeCVRQualifiers());
2695 static void Profile(llvm::FoldingSetNodeID &ID, QualType ET,
2696 ArraySizeModifier SizeMod, unsigned TypeQuals) {
2697 ID.AddPointer(ET.getAsOpaquePtr());
2698 ID.AddInteger(SizeMod);
2699 ID.AddInteger(TypeQuals);
2703 /// Represents a C array with a specified size that is not an
2704 /// integer-constant-expression. For example, 'int s[x+foo()]'.
2705 /// Since the size expression is an arbitrary expression, we store it as such.
2707 /// Note: VariableArrayType's aren't uniqued (since the expressions aren't) and
2708 /// should not be: two lexically equivalent variable array types could mean
2709 /// different things, for example, these variables do not have the same type
2712 /// void foo(int x) {
2717 class VariableArrayType : public ArrayType {
2718 friend class ASTContext; // ASTContext creates these.
2720 /// An assignment-expression. VLA's are only permitted within
2721 /// a function block.
2724 /// The range spanned by the left and right array brackets.
2725 SourceRange Brackets;
2727 VariableArrayType(QualType et, QualType can, Expr *e,
2728 ArraySizeModifier sm, unsigned tq,
2729 SourceRange brackets)
2730 : ArrayType(VariableArray, et, can, sm, tq,
2731 et->containsUnexpandedParameterPack()),
2732 SizeExpr((Stmt*) e), Brackets(brackets) {}
2735 friend class StmtIteratorBase;
2737 Expr *getSizeExpr() const {
2738 // We use C-style casts instead of cast<> here because we do not wish
2739 // to have a dependency of Type.h on Stmt.h/Expr.h.
2740 return (Expr*) SizeExpr;
2743 SourceRange getBracketsRange() const { return Brackets; }
2744 SourceLocation getLBracketLoc() const { return Brackets.getBegin(); }
2745 SourceLocation getRBracketLoc() const { return Brackets.getEnd(); }
2747 bool isSugared() const { return false; }
2748 QualType desugar() const { return QualType(this, 0); }
2750 static bool classof(const Type *T) {
2751 return T->getTypeClass() == VariableArray;
2754 void Profile(llvm::FoldingSetNodeID &ID) {
2755 llvm_unreachable("Cannot unique VariableArrayTypes.");
2759 /// Represents an array type in C++ whose size is a value-dependent expression.
2763 /// template<typename T, int Size>
2769 /// For these types, we won't actually know what the array bound is
2770 /// until template instantiation occurs, at which point this will
2771 /// become either a ConstantArrayType or a VariableArrayType.
2772 class DependentSizedArrayType : public ArrayType {
2773 friend class ASTContext; // ASTContext creates these.
2775 const ASTContext &Context;
2777 /// \brief An assignment expression that will instantiate to the
2778 /// size of the array.
2780 /// The expression itself might be null, in which case the array
2781 /// type will have its size deduced from an initializer.
2784 /// The range spanned by the left and right array brackets.
2785 SourceRange Brackets;
2787 DependentSizedArrayType(const ASTContext &Context, QualType et, QualType can,
2788 Expr *e, ArraySizeModifier sm, unsigned tq,
2789 SourceRange brackets);
2792 friend class StmtIteratorBase;
2794 Expr *getSizeExpr() const {
2795 // We use C-style casts instead of cast<> here because we do not wish
2796 // to have a dependency of Type.h on Stmt.h/Expr.h.
2797 return (Expr*) SizeExpr;
2800 SourceRange getBracketsRange() const { return Brackets; }
2801 SourceLocation getLBracketLoc() const { return Brackets.getBegin(); }
2802 SourceLocation getRBracketLoc() const { return Brackets.getEnd(); }
2804 bool isSugared() const { return false; }
2805 QualType desugar() const { return QualType(this, 0); }
2807 static bool classof(const Type *T) {
2808 return T->getTypeClass() == DependentSizedArray;
2811 void Profile(llvm::FoldingSetNodeID &ID) {
2812 Profile(ID, Context, getElementType(),
2813 getSizeModifier(), getIndexTypeCVRQualifiers(), getSizeExpr());
2816 static void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context,
2817 QualType ET, ArraySizeModifier SizeMod,
2818 unsigned TypeQuals, Expr *E);
2821 /// Represents an extended address space qualifier where the input address space
2822 /// value is dependent. Non-dependent address spaces are not represented with a
2823 /// special Type subclass; they are stored on an ExtQuals node as part of a QualType.
2827 /// template<typename T, int AddrSpace>
2828 /// class AddressSpace {
2829 /// typedef T __attribute__((address_space(AddrSpace))) type;
2832 class DependentAddressSpaceType : public Type, public llvm::FoldingSetNode {
2833 friend class ASTContext;
2835 const ASTContext &Context;
2836 Expr *AddrSpaceExpr;
2837 QualType PointeeType;
2840 DependentAddressSpaceType(const ASTContext &Context, QualType PointeeType,
2841 QualType can, Expr *AddrSpaceExpr,
2842 SourceLocation loc);
2845 Expr *getAddrSpaceExpr() const { return AddrSpaceExpr; }
2846 QualType getPointeeType() const { return PointeeType; }
2847 SourceLocation getAttributeLoc() const { return loc; }
2849 bool isSugared() const { return false; }
2850 QualType desugar() const { return QualType(this, 0); }
2852 static bool classof(const Type *T) {
2853 return T->getTypeClass() == DependentAddressSpace;
2856 void Profile(llvm::FoldingSetNodeID &ID) {
2857 Profile(ID, Context, getPointeeType(), getAddrSpaceExpr());
2860 static void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context,
2861 QualType PointeeType, Expr *AddrSpaceExpr);
2864 /// Represents an extended vector type where either the type or size is
2869 /// template<typename T, int Size>
2871 /// typedef T __attribute__((ext_vector_type(Size))) type;
2874 class DependentSizedExtVectorType : public Type, public llvm::FoldingSetNode {
2875 friend class ASTContext;
2877 const ASTContext &Context;
2880 /// The element type of the array.
2881 QualType ElementType;
2885 DependentSizedExtVectorType(const ASTContext &Context, QualType ElementType,
2886 QualType can, Expr *SizeExpr, SourceLocation loc);
2889 Expr *getSizeExpr() const { return SizeExpr; }
2890 QualType getElementType() const { return ElementType; }
2891 SourceLocation getAttributeLoc() const { return loc; }
2893 bool isSugared() const { return false; }
2894 QualType desugar() const { return QualType(this, 0); }
2896 static bool classof(const Type *T) {
2897 return T->getTypeClass() == DependentSizedExtVector;
2900 void Profile(llvm::FoldingSetNodeID &ID) {
2901 Profile(ID, Context, getElementType(), getSizeExpr());
2904 static void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context,
2905 QualType ElementType, Expr *SizeExpr);
2909 /// Represents a GCC generic vector type. This type is created using
2910 /// __attribute__((vector_size(n)), where "n" specifies the vector size in
2911 /// bytes; or from an Altivec __vector or vector declaration.
2912 /// Since the constructor takes the number of vector elements, the
2913 /// client is responsible for converting the size into the number of elements.
2914 class VectorType : public Type, public llvm::FoldingSetNode {
2917 /// not a target-specific vector type
2920 /// is AltiVec vector
2923 /// is AltiVec 'vector Pixel'
2926 /// is AltiVec 'vector bool ...'
2929 /// is ARM Neon vector
2932 /// is ARM Neon polynomial vector
2937 friend class ASTContext; // ASTContext creates these.
2939 /// The element type of the vector.
2940 QualType ElementType;
2942 VectorType(QualType vecType, unsigned nElements, QualType canonType,
2943 VectorKind vecKind);
2945 VectorType(TypeClass tc, QualType vecType, unsigned nElements,
2946 QualType canonType, VectorKind vecKind);
2949 QualType getElementType() const { return ElementType; }
2950 unsigned getNumElements() const { return VectorTypeBits.NumElements; }
2952 static bool isVectorSizeTooLarge(unsigned NumElements) {
2953 return NumElements > VectorTypeBitfields::MaxNumElements;
2956 bool isSugared() const { return false; }
2957 QualType desugar() const { return QualType(this, 0); }
2959 VectorKind getVectorKind() const {
2960 return VectorKind(VectorTypeBits.VecKind);
2963 void Profile(llvm::FoldingSetNodeID &ID) {
2964 Profile(ID, getElementType(), getNumElements(),
2965 getTypeClass(), getVectorKind());
2968 static void Profile(llvm::FoldingSetNodeID &ID, QualType ElementType,
2969 unsigned NumElements, TypeClass TypeClass,
2970 VectorKind VecKind) {
2971 ID.AddPointer(ElementType.getAsOpaquePtr());
2972 ID.AddInteger(NumElements);
2973 ID.AddInteger(TypeClass);
2974 ID.AddInteger(VecKind);
2977 static bool classof(const Type *T) {
2978 return T->getTypeClass() == Vector || T->getTypeClass() == ExtVector;
2982 /// ExtVectorType - Extended vector type. This type is created using
2983 /// __attribute__((ext_vector_type(n)), where "n" is the number of elements.
2984 /// Unlike vector_size, ext_vector_type is only allowed on typedef's. This
2985 /// class enables syntactic extensions, like Vector Components for accessing
2986 /// points (as .xyzw), colors (as .rgba), and textures (modeled after OpenGL
2987 /// Shading Language).
2988 class ExtVectorType : public VectorType {
2989 friend class ASTContext; // ASTContext creates these.
2991 ExtVectorType(QualType vecType, unsigned nElements, QualType canonType)
2992 : VectorType(ExtVector, vecType, nElements, canonType, GenericVector) {}
2995 static int getPointAccessorIdx(char c) {
2998 case 'x': case 'r': return 0;
2999 case 'y': case 'g': return 1;
3000 case 'z': case 'b': return 2;
3001 case 'w': case 'a': return 3;
3005 static int getNumericAccessorIdx(char c) {
3019 case 'a': return 10;
3021 case 'b': return 11;
3023 case 'c': return 12;
3025 case 'd': return 13;
3027 case 'e': return 14;
3029 case 'f': return 15;
3033 static int getAccessorIdx(char c, bool isNumericAccessor) {
3034 if (isNumericAccessor)
3035 return getNumericAccessorIdx(c);
3037 return getPointAccessorIdx(c);
3040 bool isAccessorWithinNumElements(char c, bool isNumericAccessor) const {
3041 if (int idx = getAccessorIdx(c, isNumericAccessor)+1)
3042 return unsigned(idx-1) < getNumElements();
3046 bool isSugared() const { return false; }
3047 QualType desugar() const { return QualType(this, 0); }
3049 static bool classof(const Type *T) {
3050 return T->getTypeClass() == ExtVector;
3054 /// FunctionType - C99 6.7.5.3 - Function Declarators. This is the common base
3055 /// class of FunctionNoProtoType and FunctionProtoType.
3056 class FunctionType : public Type {
3057 // The type returned by the function.
3058 QualType ResultType;
3061 /// A class which abstracts out some details necessary for
3064 /// It is not actually used directly for storing this information in
3065 /// a FunctionType, although FunctionType does currently use the
3066 /// same bit-pattern.
3068 // If you add a field (say Foo), other than the obvious places (both,
3069 // constructors, compile failures), what you need to update is
3073 // * functionType. Add Foo, getFoo.
3074 // * ASTContext::getFooType
3075 // * ASTContext::mergeFunctionTypes
3076 // * FunctionNoProtoType::Profile
3077 // * FunctionProtoType::Profile
3078 // * TypePrinter::PrintFunctionProto
3079 // * AST read and write
3082 friend class FunctionType;
3084 // Feel free to rearrange or add bits, but if you go over 11,
3085 // you'll need to adjust both the Bits field below and
3086 // Type::FunctionTypeBitfields.
3088 // | CC |noreturn|produces|nocallersavedregs|regparm|
3089 // |0 .. 4| 5 | 6 | 7 |8 .. 10|
3091 // regparm is either 0 (no regparm attribute) or the regparm value+1.
3092 enum { CallConvMask = 0x1F };
3093 enum { NoReturnMask = 0x20 };
3094 enum { ProducesResultMask = 0x40 };
3095 enum { NoCallerSavedRegsMask = 0x80 };
3097 RegParmMask = ~(CallConvMask | NoReturnMask | ProducesResultMask |
3098 NoCallerSavedRegsMask),
3100 }; // Assumed to be the last field
3102 uint16_t Bits = CC_C;
3104 ExtInfo(unsigned Bits) : Bits(static_cast<uint16_t>(Bits)) {}
3107 // Constructor with no defaults. Use this when you know that you
3108 // have all the elements (when reading an AST file for example).
3109 ExtInfo(bool noReturn, bool hasRegParm, unsigned regParm, CallingConv cc,
3110 bool producesResult, bool noCallerSavedRegs) {
3111 assert((!hasRegParm || regParm < 7) && "Invalid regparm value");
3112 Bits = ((unsigned)cc) | (noReturn ? NoReturnMask : 0) |
3113 (producesResult ? ProducesResultMask : 0) |
3114 (noCallerSavedRegs ? NoCallerSavedRegsMask : 0) |
3115 (hasRegParm ? ((regParm + 1) << RegParmOffset) : 0);
3118 // Constructor with all defaults. Use when for example creating a
3119 // function known to use defaults.
3120 ExtInfo() = default;
3122 // Constructor with just the calling convention, which is an important part
3123 // of the canonical type.
3124 ExtInfo(CallingConv CC) : Bits(CC) {}
3126 bool getNoReturn() const { return Bits & NoReturnMask; }
3127 bool getProducesResult() const { return Bits & ProducesResultMask; }
3128 bool getNoCallerSavedRegs() const { return Bits & NoCallerSavedRegsMask; }
3129 bool getHasRegParm() const { return (Bits >> RegParmOffset) != 0; }
3131 unsigned getRegParm() const {
3132 unsigned RegParm = Bits >> RegParmOffset;
3138 CallingConv getCC() const { return CallingConv(Bits & CallConvMask); }
3140 bool operator==(ExtInfo Other) const {
3141 return Bits == Other.Bits;
3143 bool operator!=(ExtInfo Other) const {
3144 return Bits != Other.Bits;
3147 // Note that we don't have setters. That is by design, use
3148 // the following with methods instead of mutating these objects.
3150 ExtInfo withNoReturn(bool noReturn) const {
3152 return ExtInfo(Bits | NoReturnMask);
3154 return ExtInfo(Bits & ~NoReturnMask);
3157 ExtInfo withProducesResult(bool producesResult) const {
3159 return ExtInfo(Bits | ProducesResultMask);
3161 return ExtInfo(Bits & ~ProducesResultMask);
3164 ExtInfo withNoCallerSavedRegs(bool noCallerSavedRegs) const {
3165 if (noCallerSavedRegs)
3166 return ExtInfo(Bits | NoCallerSavedRegsMask);
3168 return ExtInfo(Bits & ~NoCallerSavedRegsMask);
3171 ExtInfo withRegParm(unsigned RegParm) const {
3172 assert(RegParm < 7 && "Invalid regparm value");
3173 return ExtInfo((Bits & ~RegParmMask) |
3174 ((RegParm + 1) << RegParmOffset));
3177 ExtInfo withCallingConv(CallingConv cc) const {
3178 return ExtInfo((Bits & ~CallConvMask) | (unsigned) cc);
3181 void Profile(llvm::FoldingSetNodeID &ID) const {
3182 ID.AddInteger(Bits);
3187 FunctionType(TypeClass tc, QualType res,
3188 QualType Canonical, bool Dependent,
3189 bool InstantiationDependent,
3190 bool VariablyModified, bool ContainsUnexpandedParameterPack,
3192 : Type(tc, Canonical, Dependent, InstantiationDependent, VariablyModified,
3193 ContainsUnexpandedParameterPack),
3195 FunctionTypeBits.ExtInfo = Info.Bits;
3198 unsigned getTypeQuals() const { return FunctionTypeBits.TypeQuals; }
3201 QualType getReturnType() const { return ResultType; }
3203 bool getHasRegParm() const { return getExtInfo().getHasRegParm(); }
3204 unsigned getRegParmType() const { return getExtInfo().getRegParm(); }
3206 /// Determine whether this function type includes the GNU noreturn
3207 /// attribute. The C++11 [[noreturn]] attribute does not affect the function
3209 bool getNoReturnAttr() const { return getExtInfo().getNoReturn(); }
3211 CallingConv getCallConv() const { return getExtInfo().getCC(); }
3212 ExtInfo getExtInfo() const { return ExtInfo(FunctionTypeBits.ExtInfo); }
3213 bool isConst() const { return getTypeQuals() & Qualifiers::Const; }
3214 bool isVolatile() const { return getTypeQuals() & Qualifiers::Volatile; }
3215 bool isRestrict() const { return getTypeQuals() & Qualifiers::Restrict; }
3217 /// \brief Determine the type of an expression that calls a function of
3219 QualType getCallResultType(const ASTContext &Context) const {
3220 return getReturnType().getNonLValueExprType(Context);
3223 static StringRef getNameForCallConv(CallingConv CC);
3225 static bool classof(const Type *T) {
3226 return T->getTypeClass() == FunctionNoProto ||
3227 T->getTypeClass() == FunctionProto;
3231 /// Represents a K&R-style 'int foo()' function, which has
3232 /// no information available about its arguments.
3233 class FunctionNoProtoType : public FunctionType, public llvm::FoldingSetNode {
3234 friend class ASTContext; // ASTContext creates these.
3236 FunctionNoProtoType(QualType Result, QualType Canonical, ExtInfo Info)
3237 : FunctionType(FunctionNoProto, Result, Canonical,
3238 /*Dependent=*/false, /*InstantiationDependent=*/false,
3239 Result->isVariablyModifiedType(),
3240 /*ContainsUnexpandedParameterPack=*/false, Info) {}
3243 // No additional state past what FunctionType provides.
3245 bool isSugared() const { return false; }
3246 QualType desugar() const { return QualType(this, 0); }
3248 void Profile(llvm::FoldingSetNodeID &ID) {
3249 Profile(ID, getReturnType(), getExtInfo());
3252 static void Profile(llvm::FoldingSetNodeID &ID, QualType ResultType,
3255 ID.AddPointer(ResultType.getAsOpaquePtr());
3258 static bool classof(const Type *T) {
3259 return T->getTypeClass() == FunctionNoProto;
3263 /// Represents a prototype with parameter type info, e.g.
3264 /// 'int foo(int)' or 'int foo(void)'. 'void' is represented as having no
3265 /// parameters, not as having a single void parameter. Such a type can have an
3266 /// exception specification, but this specification is not part of the canonical
3268 class FunctionProtoType : public FunctionType, public llvm::FoldingSetNode {
3270 /// Interesting information about a specific parameter that can't simply
3271 /// be reflected in parameter's type.
3273 /// It makes sense to model language features this way when there's some
3274 /// sort of parameter-specific override (such as an attribute) that
3275 /// affects how the function is called. For example, the ARC ns_consumed
3276 /// attribute changes whether a parameter is passed at +0 (the default)
3277 /// or +1 (ns_consumed). This must be reflected in the function type,
3278 /// but isn't really a change to the parameter type.
3280 /// One serious disadvantage of modelling language features this way is
3281 /// that they generally do not work with language features that attempt
3282 /// to destructure types. For example, template argument deduction will
3283 /// not be able to match a parameter declared as
3285 /// against an argument of type
3286 /// void (*)(__attribute__((ns_consumed)) id)
3287 /// because the substitution of T=void, U=id into the former will
3288 /// not produce the latter.
3289 class ExtParameterInfo {
3293 HasPassObjSize = 0x20,
3296 unsigned char Data = 0;
3299 ExtParameterInfo() = default;
3301 /// Return the ABI treatment of this parameter.
3302 ParameterABI getABI() const {
3303 return ParameterABI(Data & ABIMask);
3305 ExtParameterInfo withABI(ParameterABI kind) const {
3306 ExtParameterInfo copy = *this;
3307 copy.Data = (copy.Data & ~ABIMask) | unsigned(kind);
3311 /// Is this parameter considered "consumed" by Objective-C ARC?
3312 /// Consumed parameters must have retainable object type.
3313 bool isConsumed() const {
3314 return (Data & IsConsumed);
3316 ExtParameterInfo withIsConsumed(bool consumed) const {
3317 ExtParameterInfo copy = *this;
3319 copy.Data |= IsConsumed;
3321 copy.Data &= ~IsConsumed;
3326 bool hasPassObjectSize() const {
3327 return Data & HasPassObjSize;
3329 ExtParameterInfo withHasPassObjectSize() const {
3330 ExtParameterInfo Copy = *this;
3331 Copy.Data |= HasPassObjSize;
3335 bool isNoEscape() const {
3336 return Data & IsNoEscape;
3339 ExtParameterInfo withIsNoEscape(bool NoEscape) const {
3340 ExtParameterInfo Copy = *this;
3342 Copy.Data |= IsNoEscape;
3344 Copy.Data &= ~IsNoEscape;
3348 unsigned char getOpaqueValue() const { return Data; }
3349 static ExtParameterInfo getFromOpaqueValue(unsigned char data) {
3350 ExtParameterInfo result;
3355 friend bool operator==(ExtParameterInfo lhs, ExtParameterInfo rhs) {
3356 return lhs.Data == rhs.Data;
3358 friend bool operator!=(ExtParameterInfo lhs, ExtParameterInfo rhs) {
3359 return lhs.Data != rhs.Data;
3363 struct ExceptionSpecInfo {
3364 /// The kind of exception specification this is.
3365 ExceptionSpecificationType Type = EST_None;
3367 /// Explicitly-specified list of exception types.
3368 ArrayRef<QualType> Exceptions;
3370 /// Noexcept expression, if this is EST_ComputedNoexcept.
3371 Expr *NoexceptExpr = nullptr;
3373 /// The function whose exception specification this is, for
3374 /// EST_Unevaluated and EST_Uninstantiated.
3375 FunctionDecl *SourceDecl = nullptr;
3377 /// The function template whose exception specification this is instantiated
3378 /// from, for EST_Uninstantiated.
3379 FunctionDecl *SourceTemplate = nullptr;
3381 ExceptionSpecInfo() = default;
3383 ExceptionSpecInfo(ExceptionSpecificationType EST) : Type(EST) {}
3386 /// Extra information about a function prototype.
3387 struct ExtProtoInfo {
3388 FunctionType::ExtInfo ExtInfo;
3390 bool HasTrailingReturn : 1;
3391 unsigned char TypeQuals = 0;
3392 RefQualifierKind RefQualifier = RQ_None;
3393 ExceptionSpecInfo ExceptionSpec;
3394 const ExtParameterInfo *ExtParameterInfos = nullptr;
3397 : Variadic(false), HasTrailingReturn(false) {}
3399 ExtProtoInfo(CallingConv CC)
3400 : ExtInfo(CC), Variadic(false), HasTrailingReturn(false) {}
3402 ExtProtoInfo withExceptionSpec(const ExceptionSpecInfo &O) {
3403 ExtProtoInfo Result(*this);
3404 Result.ExceptionSpec = O;
3410 friend class ASTContext; // ASTContext creates these.
3412 /// \brief Determine whether there are any argument types that
3413 /// contain an unexpanded parameter pack.
3414 static bool containsAnyUnexpandedParameterPack(const QualType *ArgArray,
3416 for (unsigned Idx = 0; Idx < numArgs; ++Idx)
3417 if (ArgArray[Idx]->containsUnexpandedParameterPack())
3423 FunctionProtoType(QualType result, ArrayRef<QualType> params,
3424 QualType canonical, const ExtProtoInfo &epi);
3426 /// The number of parameters this function has, not counting '...'.
3427 unsigned NumParams : 15;
3429 /// The number of types in the exception spec, if any.
3430 unsigned NumExceptions : 9;
3432 /// The type of exception specification this function has.
3433 unsigned ExceptionSpecType : 4;
3435 /// Whether this function has extended parameter information.
3436 unsigned HasExtParameterInfos : 1;
3438 /// Whether the function is variadic.
3439 unsigned Variadic : 1;
3441 /// Whether this function has a trailing return type.
3442 unsigned HasTrailingReturn : 1;
3444 // ParamInfo - There is an variable size array after the class in memory that
3445 // holds the parameter types.
3447 // Exceptions - There is another variable size array after ArgInfo that
3448 // holds the exception types.
3450 // NoexceptExpr - Instead of Exceptions, there may be a single Expr* pointing
3451 // to the expression in the noexcept() specifier.
3453 // ExceptionSpecDecl, ExceptionSpecTemplate - Instead of Exceptions, there may
3454 // be a pair of FunctionDecl* pointing to the function which should be used to
3455 // instantiate this function type's exception specification, and the function
3456 // from which it should be instantiated.
3458 // ExtParameterInfos - A variable size array, following the exception
3459 // specification and of length NumParams, holding an ExtParameterInfo
3460 // for each of the parameters. This only appears if HasExtParameterInfos
3463 const ExtParameterInfo *getExtParameterInfosBuffer() const {
3464 assert(hasExtParameterInfos());
3466 // Find the end of the exception specification.
3467 const char *ptr = reinterpret_cast<const char *>(exception_begin());
3468 ptr += getExceptionSpecSize();
3470 return reinterpret_cast<const ExtParameterInfo *>(ptr);
3473 size_t getExceptionSpecSize() const {
3474 switch (getExceptionSpecType()) {
3475 case EST_None: return 0;
3476 case EST_DynamicNone: return 0;
3477 case EST_MSAny: return 0;
3478 case EST_BasicNoexcept: return 0;
3479 case EST_Unparsed: return 0;
3480 case EST_Dynamic: return getNumExceptions() * sizeof(QualType);
3481 case EST_ComputedNoexcept: return sizeof(Expr*);
3482 case EST_Uninstantiated: return 2 * sizeof(FunctionDecl*);
3483 case EST_Unevaluated: return sizeof(FunctionDecl*);
3485 llvm_unreachable("bad exception specification kind");
3489 unsigned getNumParams() const { return NumParams; }
3491 QualType getParamType(unsigned i) const {
3492 assert(i < NumParams && "invalid parameter index");
3493 return param_type_begin()[i];
3496 ArrayRef<QualType> getParamTypes() const {
3497 return llvm::makeArrayRef(param_type_begin(), param_type_end());
3500 ExtProtoInfo getExtProtoInfo() const {
3502 EPI.ExtInfo = getExtInfo();
3503 EPI.Variadic = isVariadic();
3504 EPI.HasTrailingReturn = hasTrailingReturn();
3505 EPI.ExceptionSpec.Type = getExceptionSpecType();
3506 EPI.TypeQuals = static_cast<unsigned char>(getTypeQuals());
3507 EPI.RefQualifier = getRefQualifier();
3508 if (EPI.ExceptionSpec.Type == EST_Dynamic) {
3509 EPI.ExceptionSpec.Exceptions = exceptions();
3510 } else if (EPI.ExceptionSpec.Type == EST_ComputedNoexcept) {
3511 EPI.ExceptionSpec.NoexceptExpr = getNoexceptExpr();
3512 } else if (EPI.ExceptionSpec.Type == EST_Uninstantiated) {
3513 EPI.ExceptionSpec.SourceDecl = getExceptionSpecDecl();
3514 EPI.ExceptionSpec.SourceTemplate = getExceptionSpecTemplate();
3515 } else if (EPI.ExceptionSpec.Type == EST_Unevaluated) {
3516 EPI.ExceptionSpec.SourceDecl = getExceptionSpecDecl();
3518 if (hasExtParameterInfos())
3519 EPI.ExtParameterInfos = getExtParameterInfosBuffer();
3523 /// Get the kind of exception specification on this function.
3524 ExceptionSpecificationType getExceptionSpecType() const {
3525 return static_cast<ExceptionSpecificationType>(ExceptionSpecType);
3528 /// Return whether this function has any kind of exception spec.
3529 bool hasExceptionSpec() const {
3530 return getExceptionSpecType() != EST_None;
3533 /// Return whether this function has a dynamic (throw) exception spec.
3534 bool hasDynamicExceptionSpec() const {
3535 return isDynamicExceptionSpec(getExceptionSpecType());
3538 /// Return whether this function has a noexcept exception spec.
3539 bool hasNoexceptExceptionSpec() const {
3540 return isNoexceptExceptionSpec(getExceptionSpecType());
3543 /// Return whether this function has a dependent exception spec.
3544 bool hasDependentExceptionSpec() const;
3546 /// Return whether this function has an instantiation-dependent exception
3548 bool hasInstantiationDependentExceptionSpec() const;
3550 /// Result type of getNoexceptSpec().
3551 enum NoexceptResult {
3552 /// There is no noexcept specifier.
3555 /// The noexcept specifier has a bad expression.
3558 /// The noexcept specifier is dependent.
3561 /// The noexcept specifier evaluates to false.
3564 /// The noexcept specifier evaluates to true.
3568 /// Get the meaning of the noexcept spec on this function, if any.
3569 NoexceptResult getNoexceptSpec(const ASTContext &Ctx) const;
3570 unsigned getNumExceptions() const { return NumExceptions; }
3571 QualType getExceptionType(unsigned i) const {
3572 assert(i < NumExceptions && "Invalid exception number!");
3573 return exception_begin()[i];
3575 Expr *getNoexceptExpr() const {
3576 if (getExceptionSpecType() != EST_ComputedNoexcept)
3578 // NoexceptExpr sits where the arguments end.
3579 return *reinterpret_cast<Expr *const *>(param_type_end());
3582 /// \brief If this function type has an exception specification which hasn't
3583 /// been determined yet (either because it has not been evaluated or because
3584 /// it has not been instantiated), this is the function whose exception
3585 /// specification is represented by this type.
3586 FunctionDecl *getExceptionSpecDecl() const {
3587 if (getExceptionSpecType() != EST_Uninstantiated &&
3588 getExceptionSpecType() != EST_Unevaluated)
3590 return reinterpret_cast<FunctionDecl *const *>(param_type_end())[0];
3593 /// \brief If this function type has an uninstantiated exception
3594 /// specification, this is the function whose exception specification
3595 /// should be instantiated to find the exception specification for
3597 FunctionDecl *getExceptionSpecTemplate() const {
3598 if (getExceptionSpecType() != EST_Uninstantiated)
3600 return reinterpret_cast<FunctionDecl *const *>(param_type_end())[1];
3603 /// Determine whether this function type has a non-throwing exception
3605 CanThrowResult canThrow(const ASTContext &Ctx) const;
3607 /// Determine whether this function type has a non-throwing exception
3608 /// specification. If this depends on template arguments, returns
3609 /// \c ResultIfDependent.
3610 bool isNothrow(const ASTContext &Ctx, bool ResultIfDependent = false) const {
3611 return ResultIfDependent ? canThrow(Ctx) != CT_Can
3612 : canThrow(Ctx) == CT_Cannot;
3615 bool isVariadic() const { return Variadic; }
3617 /// Determines whether this function prototype contains a
3618 /// parameter pack at the end.
3620 /// A function template whose last parameter is a parameter pack can be
3621 /// called with an arbitrary number of arguments, much like a variadic
3623 bool isTemplateVariadic() const;
3625 bool hasTrailingReturn() const { return HasTrailingReturn; }
3627 unsigned getTypeQuals() const { return FunctionType::getTypeQuals(); }
3629 /// Retrieve the ref-qualifier associated with this function type.
3630 RefQualifierKind getRefQualifier() const {
3631 return static_cast<RefQualifierKind>(FunctionTypeBits.RefQualifier);
3634 using param_type_iterator = const QualType *;
3635 using param_type_range = llvm::iterator_range<param_type_iterator>;
3637 param_type_range param_types() const {
3638 return param_type_range(param_type_begin(), param_type_end());
3641 param_type_iterator param_type_begin() const {
3642 return reinterpret_cast<const QualType *>(this+1);
3645 param_type_iterator param_type_end() const {
3646 return param_type_begin() + NumParams;
3649 using exception_iterator = const QualType *;
3651 ArrayRef<QualType> exceptions() const {
3652 return llvm::makeArrayRef(exception_begin(), exception_end());
3655 exception_iterator exception_begin() const {
3656 // exceptions begin where arguments end
3657 return param_type_end();
3660 exception_iterator exception_end() const {
3661 if (getExceptionSpecType() != EST_Dynamic)
3662 return exception_begin();
3663 return exception_begin() + NumExceptions;
3666 /// Is there any interesting extra information for any of the parameters
3667 /// of this function type?
3668 bool hasExtParameterInfos() const { return HasExtParameterInfos; }
3669 ArrayRef<ExtParameterInfo> getExtParameterInfos() const {
3670 assert(hasExtParameterInfos());
3671 return ArrayRef<ExtParameterInfo>(getExtParameterInfosBuffer(),
3675 /// Return a pointer to the beginning of the array of extra parameter
3676 /// information, if present, or else null if none of the parameters
3677 /// carry it. This is equivalent to getExtProtoInfo().ExtParameterInfos.
3678 const ExtParameterInfo *getExtParameterInfosOrNull() const {
3679 if (!hasExtParameterInfos())
3681 return getExtParameterInfosBuffer();
3684 ExtParameterInfo getExtParameterInfo(unsigned I) const {
3685 assert(I < getNumParams() && "parameter index out of range");
3686 if (hasExtParameterInfos())
3687 return getExtParameterInfosBuffer()[I];
3688 return ExtParameterInfo();
3691 ParameterABI getParameterABI(unsigned I) const {
3692 assert(I < getNumParams() && "parameter index out of range");
3693 if (hasExtParameterInfos())
3694 return getExtParameterInfosBuffer()[I].getABI();
3695 return ParameterABI::Ordinary;
3698 bool isParamConsumed(unsigned I) const {
3699 assert(I < getNumParams() && "parameter index out of range");
3700 if (hasExtParameterInfos())
3701 return getExtParameterInfosBuffer()[I].isConsumed();
3705 bool isSugared() const { return false; }
3706 QualType desugar() const { return QualType(this, 0); }
3708 void printExceptionSpecification(raw_ostream &OS,
3709 const PrintingPolicy &Policy) const;
3711 static bool classof(const Type *T) {
3712 return T->getTypeClass() == FunctionProto;
3715 void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Ctx);
3716 static void Profile(llvm::FoldingSetNodeID &ID, QualType Result,
3717 param_type_iterator ArgTys, unsigned NumArgs,
3718 const ExtProtoInfo &EPI, const ASTContext &Context,
3722 /// \brief Represents the dependent type named by a dependently-scoped
3723 /// typename using declaration, e.g.
3724 /// using typename Base<T>::foo;
3726 /// Template instantiation turns these into the underlying type.
3727 class UnresolvedUsingType : public Type {
3728 friend class ASTContext; // ASTContext creates these.
3730 UnresolvedUsingTypenameDecl *Decl;
3732 UnresolvedUsingType(const UnresolvedUsingTypenameDecl *D)
3733 : Type(UnresolvedUsing, QualType(), true, true, false,
3734 /*ContainsUnexpandedParameterPack=*/false),
3735 Decl(const_cast<UnresolvedUsingTypenameDecl*>(D)) {}
3738 UnresolvedUsingTypenameDecl *getDecl() const { return Decl; }
3740 bool isSugared() const { return false; }
3741 QualType desugar() const { return QualType(this, 0); }
3743 static bool classof(const Type *T) {
3744 return T->getTypeClass() == UnresolvedUsing;
3747 void Profile(llvm::FoldingSetNodeID &ID) {
3748 return Profile(ID, Decl);
3751 static void Profile(llvm::FoldingSetNodeID &ID,
3752 UnresolvedUsingTypenameDecl *D) {
3757 class TypedefType : public Type {
3758 TypedefNameDecl *Decl;
3761 friend class ASTContext; // ASTContext creates these.
3763 TypedefType(TypeClass tc, const TypedefNameDecl *D, QualType can)
3764 : Type(tc, can, can->isDependentType(),
3765 can->isInstantiationDependentType(),
3766 can->isVariablyModifiedType(),
3767 /*ContainsUnexpandedParameterPack=*/false),
3768 Decl(const_cast<TypedefNameDecl*>(D)) {
3769 assert(!isa<TypedefType>(can) && "Invalid canonical type");
3773 TypedefNameDecl *getDecl() const { return Decl; }
3775 bool isSugared() const { return true; }
3776 QualType desugar() const;
3778 static bool classof(const Type *T) { return T->getTypeClass() == Typedef; }
3781 /// Represents a `typeof` (or __typeof__) expression (a GCC extension).
3782 class TypeOfExprType : public Type {
3786 friend class ASTContext; // ASTContext creates these.
3788 TypeOfExprType(Expr *E, QualType can = QualType());
3791 Expr *getUnderlyingExpr() const { return TOExpr; }
3793 /// \brief Remove a single level of sugar.
3794 QualType desugar() const;
3796 /// \brief Returns whether this type directly provides sugar.
3797 bool isSugared() const;
3799 static bool classof(const Type *T) { return T->getTypeClass() == TypeOfExpr; }
3802 /// \brief Internal representation of canonical, dependent
3803 /// `typeof(expr)` types.
3805 /// This class is used internally by the ASTContext to manage
3806 /// canonical, dependent types, only. Clients will only see instances
3807 /// of this class via TypeOfExprType nodes.
3808 class DependentTypeOfExprType
3809 : public TypeOfExprType, public llvm::FoldingSetNode {
3810 const ASTContext &Context;
3813 DependentTypeOfExprType(const ASTContext &Context, Expr *E)
3814 : TypeOfExprType(E), Context(Context) {}
3816 void Profile(llvm::FoldingSetNodeID &ID) {
3817 Profile(ID, Context, getUnderlyingExpr());
3820 static void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context,
3824 /// Represents `typeof(type)`, a GCC extension.
3825 class TypeOfType : public Type {
3826 friend class ASTContext; // ASTContext creates these.
3830 TypeOfType(QualType T, QualType can)
3831 : Type(TypeOf, can, T->isDependentType(),
3832 T->isInstantiationDependentType(),
3833 T->isVariablyModifiedType(),
3834 T->containsUnexpandedParameterPack()),
3836 assert(!isa<TypedefType>(can) && "Invalid canonical type");
3840 QualType getUnderlyingType() const { return TOType; }
3842 /// \brief Remove a single level of sugar.
3843 QualType desugar() const { return getUnderlyingType(); }
3845 /// \brief Returns whether this type directly provides sugar.
3846 bool isSugared() const { return true; }
3848 static bool classof(const Type *T) { return T->getTypeClass() == TypeOf; }
3851 /// Represents the type `decltype(expr)` (C++11).
3852 class DecltypeType : public Type {
3854 QualType UnderlyingType;
3857 friend class ASTContext; // ASTContext creates these.
3859 DecltypeType(Expr *E, QualType underlyingType, QualType can = QualType());
3862 Expr *getUnderlyingExpr() const { return E; }
3863 QualType getUnderlyingType() const { return UnderlyingType; }
3865 /// \brief Remove a single level of sugar.
3866 QualType desugar() const;
3868 /// \brief Returns whether this type directly provides sugar.
3869 bool isSugared() const;
3871 static bool classof(const Type *T) { return T->getTypeClass() == Decltype; }
3874 /// \brief Internal representation of canonical, dependent
3875 /// decltype(expr) types.
3877 /// This class is used internally by the ASTContext to manage
3878 /// canonical, dependent types, only. Clients will only see instances
3879 /// of this class via DecltypeType nodes.
3880 class DependentDecltypeType : public DecltypeType, public llvm::FoldingSetNode {
3881 const ASTContext &Context;
3884 DependentDecltypeType(const ASTContext &Context, Expr *E);
3886 void Profile(llvm::FoldingSetNodeID &ID) {
3887 Profile(ID, Context, getUnderlyingExpr());
3890 static void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context,
3894 /// A unary type transform, which is a type constructed from another.
3895 class UnaryTransformType : public Type {
3902 /// The untransformed type.
3905 /// The transformed type if not dependent, otherwise the same as BaseType.
3906 QualType UnderlyingType;
3911 friend class ASTContext;
3913 UnaryTransformType(QualType BaseTy, QualType UnderlyingTy, UTTKind UKind,
3914 QualType CanonicalTy);
3917 bool isSugared() const { return !isDependentType(); }
3918 QualType desugar() const { return UnderlyingType; }
3920 QualType getUnderlyingType() const { return UnderlyingType; }
3921 QualType getBaseType() const { return BaseType; }
3923 UTTKind getUTTKind() const { return UKind; }
3925 static bool classof(const Type *T) {
3926 return T->getTypeClass() == UnaryTransform;
3930 /// \brief Internal representation of canonical, dependent
3931 /// __underlying_type(type) types.
3933 /// This class is used internally by the ASTContext to manage
3934 /// canonical, dependent types, only. Clients will only see instances
3935 /// of this class via UnaryTransformType nodes.
3936 class DependentUnaryTransformType : public UnaryTransformType,
3937 public llvm::FoldingSetNode {
3939 DependentUnaryTransformType(const ASTContext &C, QualType BaseType,
3942 void Profile(llvm::FoldingSetNodeID &ID) {
3943 Profile(ID, getBaseType(), getUTTKind());
3946 static void Profile(llvm::FoldingSetNodeID &ID, QualType BaseType,
3948 ID.AddPointer(BaseType.getAsOpaquePtr());
3949 ID.AddInteger((unsigned)UKind);
3953 class TagType : public Type {
3954 friend class ASTReader;
3956 /// Stores the TagDecl associated with this type. The decl may point to any
3957 /// TagDecl that declares the entity.
3961 TagType(TypeClass TC, const TagDecl *D, QualType can);
3964 TagDecl *getDecl() const;
3966 /// Determines whether this type is in the process of being defined.
3967 bool isBeingDefined() const;
3969 static bool classof(const Type *T) {
3970 return T->getTypeClass() >= TagFirst && T->getTypeClass() <= TagLast;
3974 /// A helper class that allows the use of isa/cast/dyncast
3975 /// to detect TagType objects of structs/unions/classes.
3976 class RecordType : public TagType {
3978 friend class ASTContext; // ASTContext creates these.
3980 explicit RecordType(const RecordDecl *D)
3981 : TagType(Record, reinterpret_cast<const TagDecl*>(D), QualType()) {}
3982 explicit RecordType(TypeClass TC, RecordDecl *D)
3983 : TagType(TC, reinterpret_cast<const TagDecl*>(D), QualType()) {}
3986 RecordDecl *getDecl() const {
3987 return reinterpret_cast<RecordDecl*>(TagType::getDecl());
3990 /// Recursively check all fields in the record for const-ness. If any field
3991 /// is declared const, return true. Otherwise, return false.
3992 bool hasConstFields() const;
3994 bool isSugared() const { return false; }
3995 QualType desugar() const { return QualType(this, 0); }
3997 static bool classof(const Type *T) { return T->getTypeClass() == Record; }
4000 /// A helper class that allows the use of isa/cast/dyncast
4001 /// to detect TagType objects of enums.
4002 class EnumType : public TagType {
4003 friend class ASTContext; // ASTContext creates these.
4005 explicit EnumType(const EnumDecl *D)
4006 : TagType(Enum, reinterpret_cast<const TagDecl*>(D), QualType()) {}
4009 EnumDecl *getDecl() const {
4010 return reinterpret_cast<EnumDecl*>(TagType::getDecl());
4013 bool isSugared() const { return false; }
4014 QualType desugar() const { return QualType(this, 0); }
4016 static bool classof(const Type *T) { return T->getTypeClass() == Enum; }
4019 /// An attributed type is a type to which a type attribute has been applied.
4021 /// The "modified type" is the fully-sugared type to which the attributed
4022 /// type was applied; generally it is not canonically equivalent to the
4023 /// attributed type. The "equivalent type" is the minimally-desugared type
4024 /// which the type is canonically equivalent to.
4026 /// For example, in the following attributed type:
4027 /// int32_t __attribute__((vector_size(16)))
4028 /// - the modified type is the TypedefType for int32_t
4029 /// - the equivalent type is VectorType(16, int32_t)
4030 /// - the canonical type is VectorType(16, int)
4031 class AttributedType : public Type, public llvm::FoldingSetNode {
4033 // It is really silly to have yet another attribute-kind enum, but
4034 // clang::attr::Kind doesn't currently cover the pure type attrs.
4036 // Expression operand.
4040 attr_neon_vector_type,
4041 attr_neon_polyvector_type,
4043 FirstExprOperandKind = attr_address_space,
4044 LastExprOperandKind = attr_neon_polyvector_type,
4046 // Enumerated operand (string or keyword).
4048 attr_objc_ownership,
4052 FirstEnumOperandKind = attr_objc_gc,
4053 LastEnumOperandKind = attr_pcs_vfp,
4075 attr_ns_returns_retained,
4077 attr_null_unspecified,
4079 attr_objc_inert_unsafe_unretained,
4083 friend class ASTContext; // ASTContext creates these
4085 QualType ModifiedType;
4086 QualType EquivalentType;
4088 AttributedType(QualType canon, Kind attrKind, QualType modified,
4089 QualType equivalent)
4090 : Type(Attributed, canon, equivalent->isDependentType(),
4091 equivalent->isInstantiationDependentType(),
4092 equivalent->isVariablyModifiedType(),
4093 equivalent->containsUnexpandedParameterPack()),
4094 ModifiedType(modified), EquivalentType(equivalent) {
4095 AttributedTypeBits.AttrKind = attrKind;
4099 Kind getAttrKind() const {
4100 return static_cast<Kind>(AttributedTypeBits.AttrKind);
4103 QualType getModifiedType() const { return ModifiedType; }
4104 QualType getEquivalentType() const { return EquivalentType; }
4106 bool isSugared() const { return true; }
4107 QualType desugar() const { return getEquivalentType(); }
4109 /// Does this attribute behave like a type qualifier?
4111 /// A type qualifier adjusts a type to provide specialized rules for
4112 /// a specific object, like the standard const and volatile qualifiers.
4113 /// This includes attributes controlling things like nullability,
4114 /// address spaces, and ARC ownership. The value of the object is still
4115 /// largely described by the modified type.
4117 /// In contrast, many type attributes "rewrite" their modified type to
4118 /// produce a fundamentally different type, not necessarily related in any
4119 /// formalizable way to the original type. For example, calling convention
4120 /// and vector attributes are not simple type qualifiers.
4122 /// Type qualifiers are often, but not always, reflected in the canonical
4124 bool isQualifier() const;
4126 bool isMSTypeSpec() const;
4128 bool isCallingConv() const;
4130 llvm::Optional<NullabilityKind> getImmediateNullability() const;
4132 /// Retrieve the attribute kind corresponding to the given
4133 /// nullability kind.
4134 static Kind getNullabilityAttrKind(NullabilityKind kind) {
4136 case NullabilityKind::NonNull:
4137 return attr_nonnull;
4139 case NullabilityKind::Nullable:
4140 return attr_nullable;
4142 case NullabilityKind::Unspecified:
4143 return attr_null_unspecified;
4145 llvm_unreachable("Unknown nullability kind.");
4148 /// Strip off the top-level nullability annotation on the given
4149 /// type, if it's there.
4151 /// \param T The type to strip. If the type is exactly an
4152 /// AttributedType specifying nullability (without looking through
4153 /// type sugar), the nullability is returned and this type changed
4154 /// to the underlying modified type.
4156 /// \returns the top-level nullability, if present.
4157 static Optional<NullabilityKind> stripOuterNullability(QualType &T);
4159 void Profile(llvm::FoldingSetNodeID &ID) {
4160 Profile(ID, getAttrKind(), ModifiedType, EquivalentType);
4163 static void Profile(llvm::FoldingSetNodeID &ID, Kind attrKind,
4164 QualType modified, QualType equivalent) {
4165 ID.AddInteger(attrKind);
4166 ID.AddPointer(modified.getAsOpaquePtr());
4167 ID.AddPointer(equivalent.getAsOpaquePtr());
4170 static bool classof(const Type *T) {
4171 return T->getTypeClass() == Attributed;
4175 class TemplateTypeParmType : public Type, public llvm::FoldingSetNode {
4176 friend class ASTContext; // ASTContext creates these
4178 // Helper data collector for canonical types.
4179 struct CanonicalTTPTInfo {
4180 unsigned Depth : 15;
4181 unsigned ParameterPack : 1;
4182 unsigned Index : 16;
4186 // Info for the canonical type.
4187 CanonicalTTPTInfo CanTTPTInfo;
4189 // Info for the non-canonical type.
4190 TemplateTypeParmDecl *TTPDecl;
4193 /// Build a non-canonical type.
4194 TemplateTypeParmType(TemplateTypeParmDecl *TTPDecl, QualType Canon)
4195 : Type(TemplateTypeParm, Canon, /*Dependent=*/true,
4196 /*InstantiationDependent=*/true,
4197 /*VariablyModified=*/false,
4198 Canon->containsUnexpandedParameterPack()),
4201 /// Build the canonical type.
4202 TemplateTypeParmType(unsigned D, unsigned I, bool PP)
4203 : Type(TemplateTypeParm, QualType(this, 0),
4205 /*InstantiationDependent=*/true,
4206 /*VariablyModified=*/false, PP) {
4207 CanTTPTInfo.Depth = D;
4208 CanTTPTInfo.Index = I;
4209 CanTTPTInfo.ParameterPack = PP;
4212 const CanonicalTTPTInfo& getCanTTPTInfo() const {
4213 QualType Can = getCanonicalTypeInternal();
4214 return Can->castAs<TemplateTypeParmType>()->CanTTPTInfo;
4218 unsigned getDepth() const { return getCanTTPTInfo().Depth; }
4219 unsigned getIndex() const { return getCanTTPTInfo().Index; }
4220 bool isParameterPack() const { return getCanTTPTInfo().ParameterPack; }
4222 TemplateTypeParmDecl *getDecl() const {
4223 return isCanonicalUnqualified() ? nullptr : TTPDecl;
4226 IdentifierInfo *getIdentifier() const;
4228 bool isSugared() const { return false; }
4229 QualType desugar() const { return QualType(this, 0); }
4231 void Profile(llvm::FoldingSetNodeID &ID) {
4232 Profile(ID, getDepth(), getIndex(), isParameterPack(), getDecl());
4235 static void Profile(llvm::FoldingSetNodeID &ID, unsigned Depth,
4236 unsigned Index, bool ParameterPack,
4237 TemplateTypeParmDecl *TTPDecl) {
4238 ID.AddInteger(Depth);
4239 ID.AddInteger(Index);
4240 ID.AddBoolean(ParameterPack);
4241 ID.AddPointer(TTPDecl);
4244 static bool classof(const Type *T) {
4245 return T->getTypeClass() == TemplateTypeParm;
4249 /// \brief Represents the result of substituting a type for a template
4252 /// Within an instantiated template, all template type parameters have
4253 /// been replaced with these. They are used solely to record that a
4254 /// type was originally written as a template type parameter;
4255 /// therefore they are never canonical.
4256 class SubstTemplateTypeParmType : public Type, public llvm::FoldingSetNode {
4257 friend class ASTContext;
4259 // The original type parameter.
4260 const TemplateTypeParmType *Replaced;
4262 SubstTemplateTypeParmType(const TemplateTypeParmType *Param, QualType Canon)
4263 : Type(SubstTemplateTypeParm, Canon, Canon->isDependentType(),
4264 Canon->isInstantiationDependentType(),
4265 Canon->isVariablyModifiedType(),
4266 Canon->containsUnexpandedParameterPack()),
4270 /// Gets the template parameter that was substituted for.
4271 const TemplateTypeParmType *getReplacedParameter() const {
4275 /// Gets the type that was substituted for the template
4277 QualType getReplacementType() const {
4278 return getCanonicalTypeInternal();
4281 bool isSugared() const { return true; }
4282 QualType desugar() const { return getReplacementType(); }
4284 void Profile(llvm::FoldingSetNodeID &ID) {
4285 Profile(ID, getReplacedParameter(), getReplacementType());
4288 static void Profile(llvm::FoldingSetNodeID &ID,
4289 const TemplateTypeParmType *Replaced,
4290 QualType Replacement) {
4291 ID.AddPointer(Replaced);
4292 ID.AddPointer(Replacement.getAsOpaquePtr());
4295 static bool classof(const Type *T) {
4296 return T->getTypeClass() == SubstTemplateTypeParm;
4300 /// \brief Represents the result of substituting a set of types for a template
4301 /// type parameter pack.
4303 /// When a pack expansion in the source code contains multiple parameter packs
4304 /// and those parameter packs correspond to different levels of template
4305 /// parameter lists, this type node is used to represent a template type
4306 /// parameter pack from an outer level, which has already had its argument pack
4307 /// substituted but that still lives within a pack expansion that itself
4308 /// could not be instantiated. When actually performing a substitution into
4309 /// that pack expansion (e.g., when all template parameters have corresponding
4310 /// arguments), this type will be replaced with the \c SubstTemplateTypeParmType
4311 /// at the current pack substitution index.
4312 class SubstTemplateTypeParmPackType : public Type, public llvm::FoldingSetNode {
4313 friend class ASTContext;
4315 /// \brief The original type parameter.
4316 const TemplateTypeParmType *Replaced;
4318 /// \brief A pointer to the set of template arguments that this
4319 /// parameter pack is instantiated with.
4320 const TemplateArgument *Arguments;
4322 /// \brief The number of template arguments in \c Arguments.
4323 unsigned NumArguments;
4325 SubstTemplateTypeParmPackType(const TemplateTypeParmType *Param,
4327 const TemplateArgument &ArgPack);
4330 IdentifierInfo *getIdentifier() const { return Replaced->getIdentifier(); }
4332 /// Gets the template parameter that was substituted for.
4333 const TemplateTypeParmType *getReplacedParameter() const {
4337 bool isSugared() const { return false; }
4338 QualType desugar() const { return QualType(this, 0); }
4340 TemplateArgument getArgumentPack() const;
4342 void Profile(llvm::FoldingSetNodeID &ID);
4343 static void Profile(llvm::FoldingSetNodeID &ID,
4344 const TemplateTypeParmType *Replaced,
4345 const TemplateArgument &ArgPack);
4347 static bool classof(const Type *T) {
4348 return T->getTypeClass() == SubstTemplateTypeParmPack;
4352 /// \brief Common base class for placeholders for types that get replaced by
4353 /// placeholder type deduction: C++11 auto, C++14 decltype(auto), C++17 deduced
4354 /// class template types, and (eventually) constrained type names from the C++
4357 /// These types are usually a placeholder for a deduced type. However, before
4358 /// the initializer is attached, or (usually) if the initializer is
4359 /// type-dependent, there is no deduced type and the type is canonical. In
4360 /// the latter case, it is also a dependent type.
4361 class DeducedType : public Type {
4363 DeducedType(TypeClass TC, QualType DeducedAsType, bool IsDependent,
4364 bool IsInstantiationDependent, bool ContainsParameterPack)
4366 // FIXME: Retain the sugared deduced type?
4367 DeducedAsType.isNull() ? QualType(this, 0)
4368 : DeducedAsType.getCanonicalType(),
4369 IsDependent, IsInstantiationDependent,
4370 /*VariablyModified=*/false, ContainsParameterPack) {
4371 if (!DeducedAsType.isNull()) {
4372 if (DeducedAsType->isDependentType())
4374 if (DeducedAsType->isInstantiationDependentType())
4375 setInstantiationDependent();
4376 if (DeducedAsType->containsUnexpandedParameterPack())
4377 setContainsUnexpandedParameterPack();
4382 bool isSugared() const { return !isCanonicalUnqualified(); }
4383 QualType desugar() const { return getCanonicalTypeInternal(); }
4385 /// \brief Get the type deduced for this placeholder type, or null if it's
4386 /// either not been deduced or was deduced to a dependent type.
4387 QualType getDeducedType() const {
4388 return !isCanonicalUnqualified() ? getCanonicalTypeInternal() : QualType();
4390 bool isDeduced() const {
4391 return !isCanonicalUnqualified() || isDependentType();
4394 static bool classof(const Type *T) {
4395 return T->getTypeClass() == Auto ||
4396 T->getTypeClass() == DeducedTemplateSpecialization;
4400 /// \brief Represents a C++11 auto or C++14 decltype(auto) type.
4401 class AutoType : public DeducedType, public llvm::FoldingSetNode {
4402 friend class ASTContext; // ASTContext creates these
4404 AutoType(QualType DeducedAsType, AutoTypeKeyword Keyword,
4405 bool IsDeducedAsDependent)
4406 : DeducedType(Auto, DeducedAsType, IsDeducedAsDependent,
4407 IsDeducedAsDependent, /*ContainsPack=*/false) {
4408 AutoTypeBits.Keyword = (unsigned)Keyword;
4412 bool isDecltypeAuto() const {
4413 return getKeyword() == AutoTypeKeyword::DecltypeAuto;
4416 AutoTypeKeyword getKeyword() const {
4417 return (AutoTypeKeyword)AutoTypeBits.Keyword;
4420 void Profile(llvm::FoldingSetNodeID &ID) {
4421 Profile(ID, getDeducedType(), getKeyword(), isDependentType());
4424 static void Profile(llvm::FoldingSetNodeID &ID, QualType Deduced,
4425 AutoTypeKeyword Keyword, bool IsDependent) {
4426 ID.AddPointer(Deduced.getAsOpaquePtr());
4427 ID.AddInteger((unsigned)Keyword);
4428 ID.AddBoolean(IsDependent);
4431 static bool classof(const Type *T) {
4432 return T->getTypeClass() == Auto;
4436 /// \brief Represents a C++17 deduced template specialization type.
4437 class DeducedTemplateSpecializationType : public DeducedType,
4438 public llvm::FoldingSetNode {
4439 friend class ASTContext; // ASTContext creates these
4441 /// The name of the template whose arguments will be deduced.
4442 TemplateName Template;
4444 DeducedTemplateSpecializationType(TemplateName Template,
4445 QualType DeducedAsType,
4446 bool IsDeducedAsDependent)
4447 : DeducedType(DeducedTemplateSpecialization, DeducedAsType,
4448 IsDeducedAsDependent || Template.isDependent(),
4449 IsDeducedAsDependent || Template.isInstantiationDependent(),
4450 Template.containsUnexpandedParameterPack()),
4451 Template(Template) {}
4454 /// Retrieve the name of the template that we are deducing.
4455 TemplateName getTemplateName() const { return Template;}
4457 void Profile(llvm::FoldingSetNodeID &ID) {
4458 Profile(ID, getTemplateName(), getDeducedType(), isDependentType());
4461 static void Profile(llvm::FoldingSetNodeID &ID, TemplateName Template,
4462 QualType Deduced, bool IsDependent) {
4463 Template.Profile(ID);
4464 ID.AddPointer(Deduced.getAsOpaquePtr());
4465 ID.AddBoolean(IsDependent);
4468 static bool classof(const Type *T) {
4469 return T->getTypeClass() == DeducedTemplateSpecialization;
4473 /// \brief Represents a type template specialization; the template
4474 /// must be a class template, a type alias template, or a template
4475 /// template parameter. A template which cannot be resolved to one of
4476 /// these, e.g. because it is written with a dependent scope
4477 /// specifier, is instead represented as a
4478 /// @c DependentTemplateSpecializationType.
4480 /// A non-dependent template specialization type is always "sugar",
4481 /// typically for a \c RecordType. For example, a class template
4482 /// specialization type of \c vector<int> will refer to a tag type for
4483 /// the instantiation \c std::vector<int, std::allocator<int>>
4485 /// Template specializations are dependent if either the template or
4486 /// any of the template arguments are dependent, in which case the
4487 /// type may also be canonical.
4489 /// Instances of this type are allocated with a trailing array of
4490 /// TemplateArguments, followed by a QualType representing the
4491 /// non-canonical aliased type when the template is a type alias
4493 class LLVM_ALIGNAS(/*alignof(uint64_t)*/ 8) TemplateSpecializationType
4495 public llvm::FoldingSetNode {
4496 friend class ASTContext; // ASTContext creates these
4498 /// The name of the template being specialized. This is
4499 /// either a TemplateName::Template (in which case it is a
4500 /// ClassTemplateDecl*, a TemplateTemplateParmDecl*, or a
4501 /// TypeAliasTemplateDecl*), a
4502 /// TemplateName::SubstTemplateTemplateParmPack, or a
4503 /// TemplateName::SubstTemplateTemplateParm (in which case the
4504 /// replacement must, recursively, be one of these).
4505 TemplateName Template;
4507 /// The number of template arguments named in this class template
4509 unsigned NumArgs : 31;
4511 /// Whether this template specialization type is a substituted type alias.
4512 unsigned TypeAlias : 1;
4514 TemplateSpecializationType(TemplateName T,
4515 ArrayRef<TemplateArgument> Args,
4520 /// Determine whether any of the given template arguments are dependent.
4521 static bool anyDependentTemplateArguments(ArrayRef<TemplateArgumentLoc> Args,
4522 bool &InstantiationDependent);
4524 static bool anyDependentTemplateArguments(const TemplateArgumentListInfo &,
4525 bool &InstantiationDependent);
4527 /// True if this template specialization type matches a current
4528 /// instantiation in the context in which it is found.
4529 bool isCurrentInstantiation() const {
4530 return isa<InjectedClassNameType>(getCanonicalTypeInternal());
4533 /// \brief Determine if this template specialization type is for a type alias
4534 /// template that has been substituted.
4536 /// Nearly every template specialization type whose template is an alias
4537 /// template will be substituted. However, this is not the case when
4538 /// the specialization contains a pack expansion but the template alias
4539 /// does not have a corresponding parameter pack, e.g.,
4542 /// template<typename T, typename U, typename V> struct S;
4543 /// template<typename T, typename U> using A = S<T, int, U>;
4544 /// template<typename... Ts> struct X {
4545 /// typedef A<Ts...> type; // not a type alias
4548 bool isTypeAlias() const { return TypeAlias; }
4550 /// Get the aliased type, if this is a specialization of a type alias
4552 QualType getAliasedType() const {
4553 assert(isTypeAlias() && "not a type alias template specialization");
4554 return *reinterpret_cast<const QualType*>(end());
4557 using iterator = const TemplateArgument *;
4559 iterator begin() const { return getArgs(); }
4560 iterator end() const; // defined inline in TemplateBase.h
4562 /// Retrieve the name of the template that we are specializing.
4563 TemplateName getTemplateName() const { return Template; }
4565 /// Retrieve the template arguments.
4566 const TemplateArgument *getArgs() const {
4567 return reinterpret_cast<const TemplateArgument *>(this + 1);
4570 /// Retrieve the number of template arguments.
4571 unsigned getNumArgs() const { return NumArgs; }
4573 /// Retrieve a specific template argument as a type.
4574 /// \pre \c isArgType(Arg)
4575 const TemplateArgument &getArg(unsigned Idx) const; // in TemplateBase.h
4577 ArrayRef<TemplateArgument> template_arguments() const {
4578 return {getArgs(), NumArgs};
4581 bool isSugared() const {
4582 return !isDependentType() || isCurrentInstantiation() || isTypeAlias();
4585 QualType desugar() const { return getCanonicalTypeInternal(); }
4587 void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Ctx) {
4588 Profile(ID, Template, template_arguments(), Ctx);
4590 getAliasedType().Profile(ID);
4593 static void Profile(llvm::FoldingSetNodeID &ID, TemplateName T,
4594 ArrayRef<TemplateArgument> Args,
4595 const ASTContext &Context);
4597 static bool classof(const Type *T) {
4598 return T->getTypeClass() == TemplateSpecialization;
4602 /// \brief Print a template argument list, including the '<' and '>'
4603 /// enclosing the template arguments.
4604 void printTemplateArgumentList(raw_ostream &OS,
4605 ArrayRef<TemplateArgument> Args,
4606 const PrintingPolicy &Policy);
4608 void printTemplateArgumentList(raw_ostream &OS,
4609 ArrayRef<TemplateArgumentLoc> Args,
4610 const PrintingPolicy &Policy);
4612 void printTemplateArgumentList(raw_ostream &OS,
4613 const TemplateArgumentListInfo &Args,
4614 const PrintingPolicy &Policy);
4616 /// The injected class name of a C++ class template or class
4617 /// template partial specialization. Used to record that a type was
4618 /// spelled with a bare identifier rather than as a template-id; the
4619 /// equivalent for non-templated classes is just RecordType.
4621 /// Injected class name types are always dependent. Template
4622 /// instantiation turns these into RecordTypes.
4624 /// Injected class name types are always canonical. This works
4625 /// because it is impossible to compare an injected class name type
4626 /// with the corresponding non-injected template type, for the same
4627 /// reason that it is impossible to directly compare template
4628 /// parameters from different dependent contexts: injected class name
4629 /// types can only occur within the scope of a particular templated
4630 /// declaration, and within that scope every template specialization
4631 /// will canonicalize to the injected class name (when appropriate
4632 /// according to the rules of the language).
4633 class InjectedClassNameType : public Type {
4634 friend class ASTContext; // ASTContext creates these.
4635 friend class ASTNodeImporter;
4636 friend class ASTReader; // FIXME: ASTContext::getInjectedClassNameType is not
4637 // currently suitable for AST reading, too much
4638 // interdependencies.
4640 CXXRecordDecl *Decl;
4642 /// The template specialization which this type represents.
4644 /// template <class T> class A { ... };
4645 /// this is A<T>, whereas in
4646 /// template <class X, class Y> class A<B<X,Y> > { ... };
4647 /// this is A<B<X,Y> >.
4649 /// It is always unqualified, always a template specialization type,
4650 /// and always dependent.
4651 QualType InjectedType;
4653 InjectedClassNameType(CXXRecordDecl *D, QualType TST)
4654 : Type(InjectedClassName, QualType(), /*Dependent=*/true,
4655 /*InstantiationDependent=*/true,
4656 /*VariablyModified=*/false,
4657 /*ContainsUnexpandedParameterPack=*/false),
4658 Decl(D), InjectedType(TST) {
4659 assert(isa<TemplateSpecializationType>(TST));
4660 assert(!TST.hasQualifiers());
4661 assert(TST->isDependentType());
4665 QualType getInjectedSpecializationType() const { return InjectedType; }
4667 const TemplateSpecializationType *getInjectedTST() const {
4668 return cast<TemplateSpecializationType>(InjectedType.getTypePtr());
4671 TemplateName getTemplateName() const {
4672 return getInjectedTST()->getTemplateName();
4675 CXXRecordDecl *getDecl() const;
4677 bool isSugared() const { return false; }
4678 QualType desugar() const { return QualType(this, 0); }
4680 static bool classof(const Type *T) {
4681 return T->getTypeClass() == InjectedClassName;
4685 /// \brief The kind of a tag type.
4687 /// \brief The "struct" keyword.
4690 /// \brief The "__interface" keyword.
4693 /// \brief The "union" keyword.
4696 /// \brief The "class" keyword.
4699 /// \brief The "enum" keyword.
4703 /// \brief The elaboration keyword that precedes a qualified type name or
4704 /// introduces an elaborated-type-specifier.
4705 enum ElaboratedTypeKeyword {
4706 /// \brief The "struct" keyword introduces the elaborated-type-specifier.
4709 /// \brief The "__interface" keyword introduces the elaborated-type-specifier.
4712 /// \brief The "union" keyword introduces the elaborated-type-specifier.
4715 /// \brief The "class" keyword introduces the elaborated-type-specifier.
4718 /// \brief The "enum" keyword introduces the elaborated-type-specifier.
4721 /// \brief The "typename" keyword precedes the qualified type name, e.g.,
4722 /// \c typename T::type.
4725 /// \brief No keyword precedes the qualified type name.
4729 /// A helper class for Type nodes having an ElaboratedTypeKeyword.
4730 /// The keyword in stored in the free bits of the base class.
4731 /// Also provides a few static helpers for converting and printing
4732 /// elaborated type keyword and tag type kind enumerations.
4733 class TypeWithKeyword : public Type {
4735 TypeWithKeyword(ElaboratedTypeKeyword Keyword, TypeClass tc,
4736 QualType Canonical, bool Dependent,
4737 bool InstantiationDependent, bool VariablyModified,
4738 bool ContainsUnexpandedParameterPack)
4739 : Type(tc, Canonical, Dependent, InstantiationDependent, VariablyModified,
4740 ContainsUnexpandedParameterPack) {
4741 TypeWithKeywordBits.Keyword = Keyword;
4745 ElaboratedTypeKeyword getKeyword() const {
4746 return static_cast<ElaboratedTypeKeyword>(TypeWithKeywordBits.Keyword);
4749 /// Converts a type specifier (DeclSpec::TST) into an elaborated type keyword.
4750 static ElaboratedTypeKeyword getKeywordForTypeSpec(unsigned TypeSpec);
4752 /// Converts a type specifier (DeclSpec::TST) into a tag type kind.
4753 /// It is an error to provide a type specifier which *isn't* a tag kind here.
4754 static TagTypeKind getTagTypeKindForTypeSpec(unsigned TypeSpec);
4756 /// Converts a TagTypeKind into an elaborated type keyword.
4757 static ElaboratedTypeKeyword getKeywordForTagTypeKind(TagTypeKind Tag);
4759 /// Converts an elaborated type keyword into a TagTypeKind.
4760 /// It is an error to provide an elaborated type keyword
4761 /// which *isn't* a tag kind here.
4762 static TagTypeKind getTagTypeKindForKeyword(ElaboratedTypeKeyword Keyword);
4764 static bool KeywordIsTagTypeKind(ElaboratedTypeKeyword Keyword);
4766 static StringRef getKeywordName(ElaboratedTypeKeyword Keyword);
4768 static StringRef getTagTypeKindName(TagTypeKind Kind) {
4769 return getKeywordName(getKeywordForTagTypeKind(Kind));
4772 class CannotCastToThisType {};
4773 static CannotCastToThisType classof(const Type *);
4776 /// \brief Represents a type that was referred to using an elaborated type
4777 /// keyword, e.g., struct S, or via a qualified name, e.g., N::M::type,
4780 /// This type is used to keep track of a type name as written in the
4781 /// source code, including tag keywords and any nested-name-specifiers.
4782 /// The type itself is always "sugar", used to express what was written
4783 /// in the source code but containing no additional semantic information.
4784 class ElaboratedType : public TypeWithKeyword, public llvm::FoldingSetNode {
4785 friend class ASTContext; // ASTContext creates these
4787 /// The nested name specifier containing the qualifier.
4788 NestedNameSpecifier *NNS;
4790 /// The type that this qualified name refers to.
4793 ElaboratedType(ElaboratedTypeKeyword Keyword, NestedNameSpecifier *NNS,
4794 QualType NamedType, QualType CanonType)
4795 : TypeWithKeyword(Keyword, Elaborated, CanonType,
4796 NamedType->isDependentType(),
4797 NamedType->isInstantiationDependentType(),
4798 NamedType->isVariablyModifiedType(),
4799 NamedType->containsUnexpandedParameterPack()),
4800 NNS(NNS), NamedType(NamedType) {
4801 assert(!(Keyword == ETK_None && NNS == nullptr) &&
4802 "ElaboratedType cannot have elaborated type keyword "
4803 "and name qualifier both null.");
4809 /// Retrieve the qualification on this type.
4810 NestedNameSpecifier *getQualifier() const { return NNS; }
4812 /// Retrieve the type named by the qualified-id.
4813 QualType getNamedType() const { return NamedType; }
4815 /// Remove a single level of sugar.
4816 QualType desugar() const { return getNamedType(); }
4818 /// Returns whether this type directly provides sugar.
4819 bool isSugared() const { return true; }
4821 void Profile(llvm::FoldingSetNodeID &ID) {
4822 Profile(ID, getKeyword(), NNS, NamedType);
4825 static void Profile(llvm::FoldingSetNodeID &ID, ElaboratedTypeKeyword Keyword,
4826 NestedNameSpecifier *NNS, QualType NamedType) {
4827 ID.AddInteger(Keyword);
4829 NamedType.Profile(ID);
4832 static bool classof(const Type *T) {
4833 return T->getTypeClass() == Elaborated;
4837 /// \brief Represents a qualified type name for which the type name is
4840 /// DependentNameType represents a class of dependent types that involve a
4841 /// possibly dependent nested-name-specifier (e.g., "T::") followed by a
4842 /// name of a type. The DependentNameType may start with a "typename" (for a
4843 /// typename-specifier), "class", "struct", "union", or "enum" (for a
4844 /// dependent elaborated-type-specifier), or nothing (in contexts where we
4845 /// know that we must be referring to a type, e.g., in a base class specifier).
4846 /// Typically the nested-name-specifier is dependent, but in MSVC compatibility
4847 /// mode, this type is used with non-dependent names to delay name lookup until
4849 class DependentNameType : public TypeWithKeyword, public llvm::FoldingSetNode {
4850 friend class ASTContext; // ASTContext creates these
4852 /// \brief The nested name specifier containing the qualifier.
4853 NestedNameSpecifier *NNS;
4855 /// \brief The type that this typename specifier refers to.
4856 const IdentifierInfo *Name;
4858 DependentNameType(ElaboratedTypeKeyword Keyword, NestedNameSpecifier *NNS,
4859 const IdentifierInfo *Name, QualType CanonType)
4860 : TypeWithKeyword(Keyword, DependentName, CanonType, /*Dependent=*/true,
4861 /*InstantiationDependent=*/true,
4862 /*VariablyModified=*/false,
4863 NNS->containsUnexpandedParameterPack()),
4864 NNS(NNS), Name(Name) {}
4867 /// Retrieve the qualification on this type.
4868 NestedNameSpecifier *getQualifier() const { return NNS; }
4870 /// Retrieve the type named by the typename specifier as an identifier.
4872 /// This routine will return a non-NULL identifier pointer when the
4873 /// form of the original typename was terminated by an identifier,
4874 /// e.g., "typename T::type".
4875 const IdentifierInfo *getIdentifier() const {
4879 bool isSugared() const { return false; }
4880 QualType desugar() const { return QualType(this, 0); }
4882 void Profile(llvm::FoldingSetNodeID &ID) {
4883 Profile(ID, getKeyword(), NNS, Name);
4886 static void Profile(llvm::FoldingSetNodeID &ID, ElaboratedTypeKeyword Keyword,
4887 NestedNameSpecifier *NNS, const IdentifierInfo *Name) {
4888 ID.AddInteger(Keyword);
4890 ID.AddPointer(Name);
4893 static bool classof(const Type *T) {
4894 return T->getTypeClass() == DependentName;
4898 /// Represents a template specialization type whose template cannot be
4900 /// A<T>::template B<T>
4901 class LLVM_ALIGNAS(/*alignof(uint64_t)*/ 8) DependentTemplateSpecializationType
4902 : public TypeWithKeyword,
4903 public llvm::FoldingSetNode {
4904 friend class ASTContext; // ASTContext creates these
4906 /// The nested name specifier containing the qualifier.
4907 NestedNameSpecifier *NNS;
4909 /// The identifier of the template.
4910 const IdentifierInfo *Name;
4912 /// \brief The number of template arguments named in this class template
4916 DependentTemplateSpecializationType(ElaboratedTypeKeyword Keyword,
4917 NestedNameSpecifier *NNS,
4918 const IdentifierInfo *Name,
4919 ArrayRef<TemplateArgument> Args,
4922 const TemplateArgument *getArgBuffer() const {
4923 return reinterpret_cast<const TemplateArgument*>(this+1);
4926 TemplateArgument *getArgBuffer() {
4927 return reinterpret_cast<TemplateArgument*>(this+1);
4931 NestedNameSpecifier *getQualifier() const { return NNS; }
4932 const IdentifierInfo *getIdentifier() const { return Name; }
4934 /// \brief Retrieve the template arguments.
4935 const TemplateArgument *getArgs() const {
4936 return getArgBuffer();
4939 /// \brief Retrieve the number of template arguments.
4940 unsigned getNumArgs() const { return NumArgs; }
4942 const TemplateArgument &getArg(unsigned Idx) const; // in TemplateBase.h
4944 ArrayRef<TemplateArgument> template_arguments() const {
4945 return {getArgs(), NumArgs};
4948 using iterator = const TemplateArgument *;
4950 iterator begin() const { return getArgs(); }
4951 iterator end() const; // inline in TemplateBase.h
4953 bool isSugared() const { return false; }
4954 QualType desugar() const { return QualType(this, 0); }
4956 void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context) {
4957 Profile(ID, Context, getKeyword(), NNS, Name, {getArgs(), NumArgs});
4960 static void Profile(llvm::FoldingSetNodeID &ID,
4961 const ASTContext &Context,
4962 ElaboratedTypeKeyword Keyword,
4963 NestedNameSpecifier *Qualifier,
4964 const IdentifierInfo *Name,
4965 ArrayRef<TemplateArgument> Args);
4967 static bool classof(const Type *T) {
4968 return T->getTypeClass() == DependentTemplateSpecialization;
4972 /// \brief Represents a pack expansion of types.
4974 /// Pack expansions are part of C++11 variadic templates. A pack
4975 /// expansion contains a pattern, which itself contains one or more
4976 /// "unexpanded" parameter packs. When instantiated, a pack expansion
4977 /// produces a series of types, each instantiated from the pattern of
4978 /// the expansion, where the Ith instantiation of the pattern uses the
4979 /// Ith arguments bound to each of the unexpanded parameter packs. The
4980 /// pack expansion is considered to "expand" these unexpanded
4981 /// parameter packs.
4984 /// template<typename ...Types> struct tuple;
4986 /// template<typename ...Types>
4987 /// struct tuple_of_references {
4988 /// typedef tuple<Types&...> type;
4992 /// Here, the pack expansion \c Types&... is represented via a
4993 /// PackExpansionType whose pattern is Types&.
4994 class PackExpansionType : public Type, public llvm::FoldingSetNode {
4995 friend class ASTContext; // ASTContext creates these
4997 /// \brief The pattern of the pack expansion.
5000 /// \brief The number of expansions that this pack expansion will
5001 /// generate when substituted (+1), or indicates that
5003 /// This field will only have a non-zero value when some of the parameter
5004 /// packs that occur within the pattern have been substituted but others have
5006 unsigned NumExpansions;
5008 PackExpansionType(QualType Pattern, QualType Canon,
5009 Optional<unsigned> NumExpansions)
5010 : Type(PackExpansion, Canon, /*Dependent=*/Pattern->isDependentType(),
5011 /*InstantiationDependent=*/true,
5012 /*VariablyModified=*/Pattern->isVariablyModifiedType(),
5013 /*ContainsUnexpandedParameterPack=*/false),
5015 NumExpansions(NumExpansions ? *NumExpansions + 1 : 0) {}
5018 /// \brief Retrieve the pattern of this pack expansion, which is the
5019 /// type that will be repeatedly instantiated when instantiating the
5020 /// pack expansion itself.
5021 QualType getPattern() const { return Pattern; }
5023 /// \brief Retrieve the number of expansions that this pack expansion will
5024 /// generate, if known.
5025 Optional<unsigned> getNumExpansions() const {
5027 return NumExpansions - 1;
5032 bool isSugared() const { return !Pattern->isDependentType(); }
5033 QualType desugar() const { return isSugared() ? Pattern : QualType(this, 0); }
5035 void Profile(llvm::FoldingSetNodeID &ID) {
5036 Profile(ID, getPattern(), getNumExpansions());
5039 static void Profile(llvm::FoldingSetNodeID &ID, QualType Pattern,
5040 Optional<unsigned> NumExpansions) {
5041 ID.AddPointer(Pattern.getAsOpaquePtr());
5042 ID.AddBoolean(NumExpansions.hasValue());
5044 ID.AddInteger(*NumExpansions);
5047 static bool classof(const Type *T) {
5048 return T->getTypeClass() == PackExpansion;
5052 /// This class wraps the list of protocol qualifiers. For types that can
5053 /// take ObjC protocol qualifers, they can subclass this class.
5055 class ObjCProtocolQualifiers {
5057 ObjCProtocolQualifiers() = default;
5059 ObjCProtocolDecl * const *getProtocolStorage() const {
5060 return const_cast<ObjCProtocolQualifiers*>(this)->getProtocolStorage();
5063 ObjCProtocolDecl **getProtocolStorage() {
5064 return static_cast<T*>(this)->getProtocolStorageImpl();
5067 void setNumProtocols(unsigned N) {
5068 static_cast<T*>(this)->setNumProtocolsImpl(N);
5071 void initialize(ArrayRef<ObjCProtocolDecl *> protocols) {
5072 setNumProtocols(protocols.size());
5073 assert(getNumProtocols() == protocols.size() &&
5074 "bitfield overflow in protocol count");
5075 if (!protocols.empty())
5076 memcpy(getProtocolStorage(), protocols.data(),
5077 protocols.size() * sizeof(ObjCProtocolDecl*));
5081 using qual_iterator = ObjCProtocolDecl * const *;
5082 using qual_range = llvm::iterator_range<qual_iterator>;
5084 qual_range quals() const { return qual_range(qual_begin(), qual_end()); }
5085 qual_iterator qual_begin() const { return getProtocolStorage(); }
5086 qual_iterator qual_end() const { return qual_begin() + getNumProtocols(); }
5088 bool qual_empty() const { return getNumProtocols() == 0; }
5090 /// Return the number of qualifying protocols in this type, or 0 if
5092 unsigned getNumProtocols() const {
5093 return static_cast<const T*>(this)->getNumProtocolsImpl();
5096 /// Fetch a protocol by index.
5097 ObjCProtocolDecl *getProtocol(unsigned I) const {
5098 assert(I < getNumProtocols() && "Out-of-range protocol access");
5099 return qual_begin()[I];
5102 /// Retrieve all of the protocol qualifiers.
5103 ArrayRef<ObjCProtocolDecl *> getProtocols() const {
5104 return ArrayRef<ObjCProtocolDecl *>(qual_begin(), getNumProtocols());
5108 /// Represents a type parameter type in Objective C. It can take
5109 /// a list of protocols.
5110 class ObjCTypeParamType : public Type,
5111 public ObjCProtocolQualifiers<ObjCTypeParamType>,
5112 public llvm::FoldingSetNode {
5113 friend class ASTContext;
5114 friend class ObjCProtocolQualifiers<ObjCTypeParamType>;
5116 /// The number of protocols stored on this type.
5117 unsigned NumProtocols : 6;
5119 ObjCTypeParamDecl *OTPDecl;
5121 /// The protocols are stored after the ObjCTypeParamType node. In the
5122 /// canonical type, the list of protocols are sorted alphabetically
5124 ObjCProtocolDecl **getProtocolStorageImpl();
5126 /// Return the number of qualifying protocols in this interface type,
5127 /// or 0 if there are none.
5128 unsigned getNumProtocolsImpl() const {
5129 return NumProtocols;
5132 void setNumProtocolsImpl(unsigned N) {
5136 ObjCTypeParamType(const ObjCTypeParamDecl *D,
5138 ArrayRef<ObjCProtocolDecl *> protocols);
5141 bool isSugared() const { return true; }
5142 QualType desugar() const { return getCanonicalTypeInternal(); }
5144 static bool classof(const Type *T) {
5145 return T->getTypeClass() == ObjCTypeParam;
5148 void Profile(llvm::FoldingSetNodeID &ID);
5149 static void Profile(llvm::FoldingSetNodeID &ID,
5150 const ObjCTypeParamDecl *OTPDecl,
5151 ArrayRef<ObjCProtocolDecl *> protocols);
5153 ObjCTypeParamDecl *getDecl() const { return OTPDecl; }
5156 /// Represents a class type in Objective C.
5158 /// Every Objective C type is a combination of a base type, a set of
5159 /// type arguments (optional, for parameterized classes) and a list of
5162 /// Given the following declarations:
5168 /// 'C' is an ObjCInterfaceType C. It is sugar for an ObjCObjectType
5169 /// with base C and no protocols.
5171 /// 'C<P>' is an unspecialized ObjCObjectType with base C and protocol list [P].
5172 /// 'C<C*>' is a specialized ObjCObjectType with type arguments 'C*' and no
5174 /// 'C<C*><P>' is a specialized ObjCObjectType with base C, type arguments 'C*',
5175 /// and protocol list [P].
5177 /// 'id' is a TypedefType which is sugar for an ObjCObjectPointerType whose
5178 /// pointee is an ObjCObjectType with base BuiltinType::ObjCIdType
5179 /// and no protocols.
5181 /// 'id<P>' is an ObjCObjectPointerType whose pointee is an ObjCObjectType
5182 /// with base BuiltinType::ObjCIdType and protocol list [P]. Eventually
5183 /// this should get its own sugar class to better represent the source.
5184 class ObjCObjectType : public Type,
5185 public ObjCProtocolQualifiers<ObjCObjectType> {
5186 friend class ObjCProtocolQualifiers<ObjCObjectType>;
5188 // ObjCObjectType.NumTypeArgs - the number of type arguments stored
5189 // after the ObjCObjectPointerType node.
5190 // ObjCObjectType.NumProtocols - the number of protocols stored
5191 // after the type arguments of ObjCObjectPointerType node.
5193 // These protocols are those written directly on the type. If
5194 // protocol qualifiers ever become additive, the iterators will need
5195 // to get kindof complicated.
5197 // In the canonical object type, these are sorted alphabetically
5200 /// Either a BuiltinType or an InterfaceType or sugar for either.
5203 /// Cached superclass type.
5204 mutable llvm::PointerIntPair<const ObjCObjectType *, 1, bool>
5205 CachedSuperClassType;
5207 QualType *getTypeArgStorage();
5208 const QualType *getTypeArgStorage() const {
5209 return const_cast<ObjCObjectType *>(this)->getTypeArgStorage();
5212 ObjCProtocolDecl **getProtocolStorageImpl();
5213 /// Return the number of qualifying protocols in this interface type,
5214 /// or 0 if there are none.
5215 unsigned getNumProtocolsImpl() const {
5216 return ObjCObjectTypeBits.NumProtocols;
5218 void setNumProtocolsImpl(unsigned N) {
5219 ObjCObjectTypeBits.NumProtocols = N;
5223 enum Nonce_ObjCInterface { Nonce_ObjCInterface };
5225 ObjCObjectType(QualType Canonical, QualType Base,
5226 ArrayRef<QualType> typeArgs,
5227 ArrayRef<ObjCProtocolDecl *> protocols,
5230 ObjCObjectType(enum Nonce_ObjCInterface)
5231 : Type(ObjCInterface, QualType(), false, false, false, false),
5232 BaseType(QualType(this_(), 0)) {
5233 ObjCObjectTypeBits.NumProtocols = 0;
5234 ObjCObjectTypeBits.NumTypeArgs = 0;
5235 ObjCObjectTypeBits.IsKindOf = 0;
5238 void computeSuperClassTypeSlow() const;
5241 /// Gets the base type of this object type. This is always (possibly
5242 /// sugar for) one of:
5243 /// - the 'id' builtin type (as opposed to the 'id' type visible to the
5244 /// user, which is a typedef for an ObjCObjectPointerType)
5245 /// - the 'Class' builtin type (same caveat)
5246 /// - an ObjCObjectType (currently always an ObjCInterfaceType)
5247 QualType getBaseType() const { return BaseType; }
5249 bool isObjCId() const {
5250 return getBaseType()->isSpecificBuiltinType(BuiltinType::ObjCId);
5253 bool isObjCClass() const {
5254 return getBaseType()->isSpecificBuiltinType(BuiltinType::ObjCClass);
5257 bool isObjCUnqualifiedId() const { return qual_empty() && isObjCId(); }
5258 bool isObjCUnqualifiedClass() const { return qual_empty() && isObjCClass(); }
5259 bool isObjCUnqualifiedIdOrClass() const {
5260 if (!qual_empty()) return false;
5261 if (const BuiltinType *T = getBaseType()->getAs<BuiltinType>())
5262 return T->getKind() == BuiltinType::ObjCId ||
5263 T->getKind() == BuiltinType::ObjCClass;
5266 bool isObjCQualifiedId() const { return !qual_empty() && isObjCId(); }
5267 bool isObjCQualifiedClass() const { return !qual_empty() && isObjCClass(); }
5269 /// Gets the interface declaration for this object type, if the base type
5270 /// really is an interface.
5271 ObjCInterfaceDecl *getInterface() const;
5273 /// Determine whether this object type is "specialized", meaning
5274 /// that it has type arguments.
5275 bool isSpecialized() const;
5277 /// Determine whether this object type was written with type arguments.
5278 bool isSpecializedAsWritten() const {
5279 return ObjCObjectTypeBits.NumTypeArgs > 0;
5282 /// Determine whether this object type is "unspecialized", meaning
5283 /// that it has no type arguments.
5284 bool isUnspecialized() const { return !isSpecialized(); }
5286 /// Determine whether this object type is "unspecialized" as
5287 /// written, meaning that it has no type arguments.
5288 bool isUnspecializedAsWritten() const { return !isSpecializedAsWritten(); }
5290 /// Retrieve the type arguments of this object type (semantically).
5291 ArrayRef<QualType> getTypeArgs() const;
5293 /// Retrieve the type arguments of this object type as they were
5295 ArrayRef<QualType> getTypeArgsAsWritten() const {
5296 return llvm::makeArrayRef(getTypeArgStorage(),
5297 ObjCObjectTypeBits.NumTypeArgs);
5300 /// Whether this is a "__kindof" type as written.
5301 bool isKindOfTypeAsWritten() const { return ObjCObjectTypeBits.IsKindOf; }
5303 /// Whether this ia a "__kindof" type (semantically).
5304 bool isKindOfType() const;
5306 /// Retrieve the type of the superclass of this object type.
5308 /// This operation substitutes any type arguments into the
5309 /// superclass of the current class type, potentially producing a
5310 /// specialization of the superclass type. Produces a null type if
5311 /// there is no superclass.
5312 QualType getSuperClassType() const {
5313 if (!CachedSuperClassType.getInt())
5314 computeSuperClassTypeSlow();
5316 assert(CachedSuperClassType.getInt() && "Superclass not set?");
5317 return QualType(CachedSuperClassType.getPointer(), 0);
5320 /// Strip off the Objective-C "kindof" type and (with it) any
5321 /// protocol qualifiers.
5322 QualType stripObjCKindOfTypeAndQuals(const ASTContext &ctx) const;
5324 bool isSugared() const { return false; }
5325 QualType desugar() const { return QualType(this, 0); }
5327 static bool classof(const Type *T) {
5328 return T->getTypeClass() == ObjCObject ||
5329 T->getTypeClass() == ObjCInterface;
5333 /// A class providing a concrete implementation
5334 /// of ObjCObjectType, so as to not increase the footprint of
5335 /// ObjCInterfaceType. Code outside of ASTContext and the core type
5336 /// system should not reference this type.
5337 class ObjCObjectTypeImpl : public ObjCObjectType, public llvm::FoldingSetNode {
5338 friend class ASTContext;
5340 // If anyone adds fields here, ObjCObjectType::getProtocolStorage()
5341 // will need to be modified.
5343 ObjCObjectTypeImpl(QualType Canonical, QualType Base,
5344 ArrayRef<QualType> typeArgs,
5345 ArrayRef<ObjCProtocolDecl *> protocols,
5347 : ObjCObjectType(Canonical, Base, typeArgs, protocols, isKindOf) {}
5350 void Profile(llvm::FoldingSetNodeID &ID);
5351 static void Profile(llvm::FoldingSetNodeID &ID,
5353 ArrayRef<QualType> typeArgs,
5354 ArrayRef<ObjCProtocolDecl *> protocols,
5358 inline QualType *ObjCObjectType::getTypeArgStorage() {
5359 return reinterpret_cast<QualType *>(static_cast<ObjCObjectTypeImpl*>(this)+1);
5362 inline ObjCProtocolDecl **ObjCObjectType::getProtocolStorageImpl() {
5363 return reinterpret_cast<ObjCProtocolDecl**>(
5364 getTypeArgStorage() + ObjCObjectTypeBits.NumTypeArgs);
5367 inline ObjCProtocolDecl **ObjCTypeParamType::getProtocolStorageImpl() {
5368 return reinterpret_cast<ObjCProtocolDecl**>(
5369 static_cast<ObjCTypeParamType*>(this)+1);
5372 /// Interfaces are the core concept in Objective-C for object oriented design.
5373 /// They basically correspond to C++ classes. There are two kinds of interface
5374 /// types: normal interfaces like `NSString`, and qualified interfaces, which
5375 /// are qualified with a protocol list like `NSString<NSCopyable, NSAmazing>`.
5377 /// ObjCInterfaceType guarantees the following properties when considered
5378 /// as a subtype of its superclass, ObjCObjectType:
5379 /// - There are no protocol qualifiers. To reinforce this, code which
5380 /// tries to invoke the protocol methods via an ObjCInterfaceType will
5381 /// fail to compile.
5382 /// - It is its own base type. That is, if T is an ObjCInterfaceType*,
5383 /// T->getBaseType() == QualType(T, 0).
5384 class ObjCInterfaceType : public ObjCObjectType {
5385 friend class ASTContext; // ASTContext creates these.
5386 friend class ASTReader;
5387 friend class ObjCInterfaceDecl;
5389 mutable ObjCInterfaceDecl *Decl;
5391 ObjCInterfaceType(const ObjCInterfaceDecl *D)
5392 : ObjCObjectType(Nonce_ObjCInterface),
5393 Decl(const_cast<ObjCInterfaceDecl*>(D)) {}
5396 /// Get the declaration of this interface.
5397 ObjCInterfaceDecl *getDecl() const { return Decl; }
5399 bool isSugared() const { return false; }
5400 QualType desugar() const { return QualType(this, 0); }
5402 static bool classof(const Type *T) {
5403 return T->getTypeClass() == ObjCInterface;
5406 // Nonsense to "hide" certain members of ObjCObjectType within this
5407 // class. People asking for protocols on an ObjCInterfaceType are
5408 // not going to get what they want: ObjCInterfaceTypes are
5409 // guaranteed to have no protocols.
5419 inline ObjCInterfaceDecl *ObjCObjectType::getInterface() const {
5420 QualType baseType = getBaseType();
5421 while (const ObjCObjectType *ObjT = baseType->getAs<ObjCObjectType>()) {
5422 if (const ObjCInterfaceType *T = dyn_cast<ObjCInterfaceType>(ObjT))
5423 return T->getDecl();
5425 baseType = ObjT->getBaseType();
5431 /// Represents a pointer to an Objective C object.
5433 /// These are constructed from pointer declarators when the pointee type is
5434 /// an ObjCObjectType (or sugar for one). In addition, the 'id' and 'Class'
5435 /// types are typedefs for these, and the protocol-qualified types 'id<P>'
5436 /// and 'Class<P>' are translated into these.
5438 /// Pointers to pointers to Objective C objects are still PointerTypes;
5439 /// only the first level of pointer gets it own type implementation.
5440 class ObjCObjectPointerType : public Type, public llvm::FoldingSetNode {
5441 friend class ASTContext; // ASTContext creates these.
5443 QualType PointeeType;
5445 ObjCObjectPointerType(QualType Canonical, QualType Pointee)
5446 : Type(ObjCObjectPointer, Canonical,
5447 Pointee->isDependentType(),
5448 Pointee->isInstantiationDependentType(),
5449 Pointee->isVariablyModifiedType(),
5450 Pointee->containsUnexpandedParameterPack()),
5451 PointeeType(Pointee) {}
5454 /// Gets the type pointed to by this ObjC pointer.
5455 /// The result will always be an ObjCObjectType or sugar thereof.
5456 QualType getPointeeType() const { return PointeeType; }
5458 /// Gets the type pointed to by this ObjC pointer. Always returns non-null.
5460 /// This method is equivalent to getPointeeType() except that
5461 /// it discards any typedefs (or other sugar) between this
5462 /// type and the "outermost" object type. So for:
5464 /// \@class A; \@protocol P; \@protocol Q;
5465 /// typedef A<P> AP;
5467 /// typedef A1<P> A1P;
5468 /// typedef A1P<Q> A1PQ;
5470 /// For 'A*', getObjectType() will return 'A'.
5471 /// For 'A<P>*', getObjectType() will return 'A<P>'.
5472 /// For 'AP*', getObjectType() will return 'A<P>'.
5473 /// For 'A1*', getObjectType() will return 'A'.
5474 /// For 'A1<P>*', getObjectType() will return 'A1<P>'.
5475 /// For 'A1P*', getObjectType() will return 'A1<P>'.
5476 /// For 'A1PQ*', getObjectType() will return 'A1<Q>', because
5477 /// adding protocols to a protocol-qualified base discards the
5478 /// old qualifiers (for now). But if it didn't, getObjectType()
5479 /// would return 'A1P<Q>' (and we'd have to make iterating over
5480 /// qualifiers more complicated).
5481 const ObjCObjectType *getObjectType() const {
5482 return PointeeType->castAs<ObjCObjectType>();
5485 /// If this pointer points to an Objective C
5486 /// \@interface type, gets the type for that interface. Any protocol
5487 /// qualifiers on the interface are ignored.
5489 /// \return null if the base type for this pointer is 'id' or 'Class'
5490 const ObjCInterfaceType *getInterfaceType() const;
5492 /// If this pointer points to an Objective \@interface
5493 /// type, gets the declaration for that interface.
5495 /// \return null if the base type for this pointer is 'id' or 'Class'
5496 ObjCInterfaceDecl *getInterfaceDecl() const {
5497 return getObjectType()->getInterface();
5500 /// True if this is equivalent to the 'id' type, i.e. if
5501 /// its object type is the primitive 'id' type with no protocols.
5502 bool isObjCIdType() const {
5503 return getObjectType()->isObjCUnqualifiedId();
5506 /// True if this is equivalent to the 'Class' type,
5507 /// i.e. if its object tive is the primitive 'Class' type with no protocols.
5508 bool isObjCClassType() const {
5509 return getObjectType()->isObjCUnqualifiedClass();
5512 /// True if this is equivalent to the 'id' or 'Class' type,
5513 bool isObjCIdOrClassType() const {
5514 return getObjectType()->isObjCUnqualifiedIdOrClass();
5517 /// True if this is equivalent to 'id<P>' for some non-empty set of
5519 bool isObjCQualifiedIdType() const {
5520 return getObjectType()->isObjCQualifiedId();
5523 /// True if this is equivalent to 'Class<P>' for some non-empty set of
5525 bool isObjCQualifiedClassType() const {
5526 return getObjectType()->isObjCQualifiedClass();
5529 /// Whether this is a "__kindof" type.
5530 bool isKindOfType() const { return getObjectType()->isKindOfType(); }
5532 /// Whether this type is specialized, meaning that it has type arguments.
5533 bool isSpecialized() const { return getObjectType()->isSpecialized(); }
5535 /// Whether this type is specialized, meaning that it has type arguments.
5536 bool isSpecializedAsWritten() const {
5537 return getObjectType()->isSpecializedAsWritten();
5540 /// Whether this type is unspecialized, meaning that is has no type arguments.
5541 bool isUnspecialized() const { return getObjectType()->isUnspecialized(); }
5543 /// Determine whether this object type is "unspecialized" as
5544 /// written, meaning that it has no type arguments.
5545 bool isUnspecializedAsWritten() const { return !isSpecializedAsWritten(); }
5547 /// Retrieve the type arguments for this type.
5548 ArrayRef<QualType> getTypeArgs() const {
5549 return getObjectType()->getTypeArgs();
5552 /// Retrieve the type arguments for this type.
5553 ArrayRef<QualType> getTypeArgsAsWritten() const {
5554 return getObjectType()->getTypeArgsAsWritten();
5557 /// An iterator over the qualifiers on the object type. Provided
5558 /// for convenience. This will always iterate over the full set of
5559 /// protocols on a type, not just those provided directly.
5560 using qual_iterator = ObjCObjectType::qual_iterator;
5561 using qual_range = llvm::iterator_range<qual_iterator>;
5563 qual_range quals() const { return qual_range(qual_begin(), qual_end()); }
5565 qual_iterator qual_begin() const {
5566 return getObjectType()->qual_begin();
5569 qual_iterator qual_end() const {
5570 return getObjectType()->qual_end();
5573 bool qual_empty() const { return getObjectType()->qual_empty(); }
5575 /// Return the number of qualifying protocols on the object type.
5576 unsigned getNumProtocols() const {
5577 return getObjectType()->getNumProtocols();
5580 /// Retrieve a qualifying protocol by index on the object type.
5581 ObjCProtocolDecl *getProtocol(unsigned I) const {
5582 return getObjectType()->getProtocol(I);
5585 bool isSugared() const { return false; }
5586 QualType desugar() const { return QualType(this, 0); }
5588 /// Retrieve the type of the superclass of this object pointer type.
5590 /// This operation substitutes any type arguments into the
5591 /// superclass of the current class type, potentially producing a
5592 /// pointer to a specialization of the superclass type. Produces a
5593 /// null type if there is no superclass.
5594 QualType getSuperClassType() const;
5596 /// Strip off the Objective-C "kindof" type and (with it) any
5597 /// protocol qualifiers.
5598 const ObjCObjectPointerType *stripObjCKindOfTypeAndQuals(
5599 const ASTContext &ctx) const;
5601 void Profile(llvm::FoldingSetNodeID &ID) {
5602 Profile(ID, getPointeeType());
5605 static void Profile(llvm::FoldingSetNodeID &ID, QualType T) {
5606 ID.AddPointer(T.getAsOpaquePtr());
5609 static bool classof(const Type *T) {
5610 return T->getTypeClass() == ObjCObjectPointer;
5614 class AtomicType : public Type, public llvm::FoldingSetNode {
5615 friend class ASTContext; // ASTContext creates these.
5619 AtomicType(QualType ValTy, QualType Canonical)
5620 : Type(Atomic, Canonical, ValTy->isDependentType(),
5621 ValTy->isInstantiationDependentType(),
5622 ValTy->isVariablyModifiedType(),
5623 ValTy->containsUnexpandedParameterPack()),
5627 /// Gets the type contained by this atomic type, i.e.
5628 /// the type returned by performing an atomic load of this atomic type.
5629 QualType getValueType() const { return ValueType; }
5631 bool isSugared() const { return false; }
5632 QualType desugar() const { return QualType(this, 0); }
5634 void Profile(llvm::FoldingSetNodeID &ID) {
5635 Profile(ID, getValueType());
5638 static void Profile(llvm::FoldingSetNodeID &ID, QualType T) {
5639 ID.AddPointer(T.getAsOpaquePtr());
5642 static bool classof(const Type *T) {
5643 return T->getTypeClass() == Atomic;
5647 /// PipeType - OpenCL20.
5648 class PipeType : public Type, public llvm::FoldingSetNode {
5649 friend class ASTContext; // ASTContext creates these.
5651 QualType ElementType;
5654 PipeType(QualType elemType, QualType CanonicalPtr, bool isRead)
5655 : Type(Pipe, CanonicalPtr, elemType->isDependentType(),
5656 elemType->isInstantiationDependentType(),
5657 elemType->isVariablyModifiedType(),
5658 elemType->containsUnexpandedParameterPack()),
5659 ElementType(elemType), isRead(isRead) {}
5662 QualType getElementType() const { return ElementType; }
5664 bool isSugared() const { return false; }
5666 QualType desugar() const { return QualType(this, 0); }
5668 void Profile(llvm::FoldingSetNodeID &ID) {
5669 Profile(ID, getElementType(), isReadOnly());
5672 static void Profile(llvm::FoldingSetNodeID &ID, QualType T, bool isRead) {
5673 ID.AddPointer(T.getAsOpaquePtr());
5674 ID.AddBoolean(isRead);
5677 static bool classof(const Type *T) {
5678 return T->getTypeClass() == Pipe;
5681 bool isReadOnly() const { return isRead; }
5684 /// A qualifier set is used to build a set of qualifiers.
5685 class QualifierCollector : public Qualifiers {
5687 QualifierCollector(Qualifiers Qs = Qualifiers()) : Qualifiers(Qs) {}
5689 /// Collect any qualifiers on the given type and return an
5690 /// unqualified type. The qualifiers are assumed to be consistent
5691 /// with those already in the type.
5692 const Type *strip(QualType type) {
5693 addFastQualifiers(type.getLocalFastQualifiers());
5694 if (!type.hasLocalNonFastQualifiers())
5695 return type.getTypePtrUnsafe();
5697 const ExtQuals *extQuals = type.getExtQualsUnsafe();
5698 addConsistentQualifiers(extQuals->getQualifiers());
5699 return extQuals->getBaseType();
5702 /// Apply the collected qualifiers to the given type.
5703 QualType apply(const ASTContext &Context, QualType QT) const;
5705 /// Apply the collected qualifiers to the given type.
5706 QualType apply(const ASTContext &Context, const Type* T) const;
5709 // Inline function definitions.
5711 inline SplitQualType SplitQualType::getSingleStepDesugaredType() const {
5712 SplitQualType desugar =
5713 Ty->getLocallyUnqualifiedSingleStepDesugaredType().split();
5714 desugar.Quals.addConsistentQualifiers(Quals);
5718 inline const Type *QualType::getTypePtr() const {
5719 return getCommonPtr()->BaseType;
5722 inline const Type *QualType::getTypePtrOrNull() const {
5723 return (isNull() ? nullptr : getCommonPtr()->BaseType);
5726 inline SplitQualType QualType::split() const {
5727 if (!hasLocalNonFastQualifiers())
5728 return SplitQualType(getTypePtrUnsafe(),
5729 Qualifiers::fromFastMask(getLocalFastQualifiers()));
5731 const ExtQuals *eq = getExtQualsUnsafe();
5732 Qualifiers qs = eq->getQualifiers();
5733 qs.addFastQualifiers(getLocalFastQualifiers());
5734 return SplitQualType(eq->getBaseType(), qs);
5737 inline Qualifiers QualType::getLocalQualifiers() const {
5739 if (hasLocalNonFastQualifiers())
5740 Quals = getExtQualsUnsafe()->getQualifiers();
5741 Quals.addFastQualifiers(getLocalFastQualifiers());
5745 inline Qualifiers QualType::getQualifiers() const {
5746 Qualifiers quals = getCommonPtr()->CanonicalType.getLocalQualifiers();
5747 quals.addFastQualifiers(getLocalFastQualifiers());
5751 inline unsigned QualType::getCVRQualifiers() const {
5752 unsigned cvr = getCommonPtr()->CanonicalType.getLocalCVRQualifiers();
5753 cvr |= getLocalCVRQualifiers();
5757 inline QualType QualType::getCanonicalType() const {
5758 QualType canon = getCommonPtr()->CanonicalType;
5759 return canon.withFastQualifiers(getLocalFastQualifiers());
5762 inline bool QualType::isCanonical() const {
5763 return getTypePtr()->isCanonicalUnqualified();
5766 inline bool QualType::isCanonicalAsParam() const {
5767 if (!isCanonical()) return false;
5768 if (hasLocalQualifiers()) return false;
5770 const Type *T = getTypePtr();
5771 if (T->isVariablyModifiedType() && T->hasSizedVLAType())
5774 return !isa<FunctionType>(T) && !isa<ArrayType>(T);
5777 inline bool QualType::isConstQualified() const {
5778 return isLocalConstQualified() ||
5779 getCommonPtr()->CanonicalType.isLocalConstQualified();
5782 inline bool QualType::isRestrictQualified() const {
5783 return isLocalRestrictQualified() ||
5784 getCommonPtr()->CanonicalType.isLocalRestrictQualified();
5788 inline bool QualType::isVolatileQualified() const {
5789 return isLocalVolatileQualified() ||
5790 getCommonPtr()->CanonicalType.isLocalVolatileQualified();
5793 inline bool QualType::hasQualifiers() const {
5794 return hasLocalQualifiers() ||
5795 getCommonPtr()->CanonicalType.hasLocalQualifiers();
5798 inline QualType QualType::getUnqualifiedType() const {
5799 if (!getTypePtr()->getCanonicalTypeInternal().hasLocalQualifiers())
5800 return QualType(getTypePtr(), 0);
5802 return QualType(getSplitUnqualifiedTypeImpl(*this).Ty, 0);
5805 inline SplitQualType QualType::getSplitUnqualifiedType() const {
5806 if (!getTypePtr()->getCanonicalTypeInternal().hasLocalQualifiers())
5809 return getSplitUnqualifiedTypeImpl(*this);
5812 inline void QualType::removeLocalConst() {
5813 removeLocalFastQualifiers(Qualifiers::Const);
5816 inline void QualType::removeLocalRestrict() {
5817 removeLocalFastQualifiers(Qualifiers::Restrict);
5820 inline void QualType::removeLocalVolatile() {
5821 removeLocalFastQualifiers(Qualifiers::Volatile);
5824 inline void QualType::removeLocalCVRQualifiers(unsigned Mask) {
5825 assert(!(Mask & ~Qualifiers::CVRMask) && "mask has non-CVR bits");
5826 static_assert((int)Qualifiers::CVRMask == (int)Qualifiers::FastMask,
5827 "Fast bits differ from CVR bits!");
5829 // Fast path: we don't need to touch the slow qualifiers.
5830 removeLocalFastQualifiers(Mask);
5833 /// Return the address space of this type.
5834 inline LangAS QualType::getAddressSpace() const {
5835 return getQualifiers().getAddressSpace();
5838 /// Return the gc attribute of this type.
5839 inline Qualifiers::GC QualType::getObjCGCAttr() const {
5840 return getQualifiers().getObjCGCAttr();
5843 inline FunctionType::ExtInfo getFunctionExtInfo(const Type &t) {
5844 if (const PointerType *PT = t.getAs<PointerType>()) {
5845 if (const FunctionType *FT = PT->getPointeeType()->getAs<FunctionType>())
5846 return FT->getExtInfo();
5847 } else if (const FunctionType *FT = t.getAs<FunctionType>())
5848 return FT->getExtInfo();
5850 return FunctionType::ExtInfo();
5853 inline FunctionType::ExtInfo getFunctionExtInfo(QualType t) {
5854 return getFunctionExtInfo(*t);
5857 /// Determine whether this type is more
5858 /// qualified than the Other type. For example, "const volatile int"
5859 /// is more qualified than "const int", "volatile int", and
5860 /// "int". However, it is not more qualified than "const volatile
5862 inline bool QualType::isMoreQualifiedThan(QualType other) const {
5863 Qualifiers MyQuals = getQualifiers();
5864 Qualifiers OtherQuals = other.getQualifiers();
5865 return (MyQuals != OtherQuals && MyQuals.compatiblyIncludes(OtherQuals));
5868 /// Determine whether this type is at last
5869 /// as qualified as the Other type. For example, "const volatile
5870 /// int" is at least as qualified as "const int", "volatile int",
5871 /// "int", and "const volatile int".
5872 inline bool QualType::isAtLeastAsQualifiedAs(QualType other) const {
5873 Qualifiers OtherQuals = other.getQualifiers();
5875 // Ignore __unaligned qualifier if this type is a void.
5876 if (getUnqualifiedType()->isVoidType())
5877 OtherQuals.removeUnaligned();
5879 return getQualifiers().compatiblyIncludes(OtherQuals);
5882 /// If Type is a reference type (e.g., const
5883 /// int&), returns the type that the reference refers to ("const
5884 /// int"). Otherwise, returns the type itself. This routine is used
5885 /// throughout Sema to implement C++ 5p6:
5887 /// If an expression initially has the type "reference to T" (8.3.2,
5888 /// 8.5.3), the type is adjusted to "T" prior to any further
5889 /// analysis, the expression designates the object or function
5890 /// denoted by the reference, and the expression is an lvalue.
5891 inline QualType QualType::getNonReferenceType() const {
5892 if (const ReferenceType *RefType = (*this)->getAs<ReferenceType>())
5893 return RefType->getPointeeType();
5898 inline bool QualType::isCForbiddenLValueType() const {
5899 return ((getTypePtr()->isVoidType() && !hasQualifiers()) ||
5900 getTypePtr()->isFunctionType());
5903 /// Tests whether the type is categorized as a fundamental type.
5905 /// \returns True for types specified in C++0x [basic.fundamental].
5906 inline bool Type::isFundamentalType() const {
5907 return isVoidType() ||
5908 // FIXME: It's really annoying that we don't have an
5909 // 'isArithmeticType()' which agrees with the standard definition.
5910 (isArithmeticType() && !isEnumeralType());
5913 /// Tests whether the type is categorized as a compound type.
5915 /// \returns True for types specified in C++0x [basic.compound].
5916 inline bool Type::isCompoundType() const {
5917 // C++0x [basic.compound]p1:
5918 // Compound types can be constructed in the following ways:
5919 // -- arrays of objects of a given type [...];
5920 return isArrayType() ||
5921 // -- functions, which have parameters of given types [...];
5923 // -- pointers to void or objects or functions [...];
5925 // -- references to objects or functions of a given type. [...]
5926 isReferenceType() ||
5927 // -- classes containing a sequence of objects of various types, [...];
5929 // -- unions, which are classes capable of containing objects of different
5930 // types at different times;
5932 // -- enumerations, which comprise a set of named constant values. [...];
5934 // -- pointers to non-static class members, [...].
5935 isMemberPointerType();
5938 inline bool Type::isFunctionType() const {
5939 return isa<FunctionType>(CanonicalType);
5942 inline bool Type::isPointerType() const {
5943 return isa<PointerType>(CanonicalType);
5946 inline bool Type::isAnyPointerType() const {
5947 return isPointerType() || isObjCObjectPointerType();
5950 inline bool Type::isBlockPointerType() const {
5951 return isa<BlockPointerType>(CanonicalType);
5954 inline bool Type::isReferenceType() const {
5955 return isa<ReferenceType>(CanonicalType);
5958 inline bool Type::isLValueReferenceType() const {
5959 return isa<LValueReferenceType>(CanonicalType);
5962 inline bool Type::isRValueReferenceType() const {
5963 return isa<RValueReferenceType>(CanonicalType);
5966 inline bool Type::isFunctionPointerType() const {
5967 if (const PointerType *T = getAs<PointerType>())
5968 return T->getPointeeType()->isFunctionType();
5973 inline bool Type::isMemberPointerType() const {
5974 return isa<MemberPointerType>(CanonicalType);
5977 inline bool Type::isMemberFunctionPointerType() const {
5978 if (const MemberPointerType* T = getAs<MemberPointerType>())
5979 return T->isMemberFunctionPointer();
5984 inline bool Type::isMemberDataPointerType() const {
5985 if (const MemberPointerType* T = getAs<MemberPointerType>())
5986 return T->isMemberDataPointer();
5991 inline bool Type::isArrayType() const {
5992 return isa<ArrayType>(CanonicalType);
5995 inline bool Type::isConstantArrayType() const {
5996 return isa<ConstantArrayType>(CanonicalType);
5999 inline bool Type::isIncompleteArrayType() const {
6000 return isa<IncompleteArrayType>(CanonicalType);
6003 inline bool Type::isVariableArrayType() const {
6004 return isa<VariableArrayType>(CanonicalType);
6007 inline bool Type::isDependentSizedArrayType() const {
6008 return isa<DependentSizedArrayType>(CanonicalType);
6011 inline bool Type::isBuiltinType() const {
6012 return isa<BuiltinType>(CanonicalType);
6015 inline bool Type::isRecordType() const {
6016 return isa<RecordType>(CanonicalType);
6019 inline bool Type::isEnumeralType() const {
6020 return isa<EnumType>(CanonicalType);
6023 inline bool Type::isAnyComplexType() const {
6024 return isa<ComplexType>(CanonicalType);
6027 inline bool Type::isVectorType() const {
6028 return isa<VectorType>(CanonicalType);
6031 inline bool Type::isExtVectorType() const {
6032 return isa<ExtVectorType>(CanonicalType);
6035 inline bool Type::isDependentAddressSpaceType() const {
6036 return isa<DependentAddressSpaceType>(CanonicalType);
6039 inline bool Type::isObjCObjectPointerType() const {
6040 return isa<ObjCObjectPointerType>(CanonicalType);
6043 inline bool Type::isObjCObjectType() const {
6044 return isa<ObjCObjectType>(CanonicalType);
6047 inline bool Type::isObjCObjectOrInterfaceType() const {
6048 return isa<ObjCInterfaceType>(CanonicalType) ||
6049 isa<ObjCObjectType>(CanonicalType);
6052 inline bool Type::isAtomicType() const {
6053 return isa<AtomicType>(CanonicalType);
6056 inline bool Type::isObjCQualifiedIdType() const {
6057 if (const ObjCObjectPointerType *OPT = getAs<ObjCObjectPointerType>())
6058 return OPT->isObjCQualifiedIdType();
6062 inline bool Type::isObjCQualifiedClassType() const {
6063 if (const ObjCObjectPointerType *OPT = getAs<ObjCObjectPointerType>())
6064 return OPT->isObjCQualifiedClassType();
6068 inline bool Type::isObjCIdType() const {
6069 if (const ObjCObjectPointerType *OPT = getAs<ObjCObjectPointerType>())
6070 return OPT->isObjCIdType();
6074 inline bool Type::isObjCClassType() const {
6075 if (const ObjCObjectPointerType *OPT = getAs<ObjCObjectPointerType>())
6076 return OPT->isObjCClassType();
6080 inline bool Type::isObjCSelType() const {
6081 if (const PointerType *OPT = getAs<PointerType>())
6082 return OPT->getPointeeType()->isSpecificBuiltinType(BuiltinType::ObjCSel);
6086 inline bool Type::isObjCBuiltinType() const {
6087 return isObjCIdType() || isObjCClassType() || isObjCSelType();
6090 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
6091 inline bool Type::is##Id##Type() const { \
6092 return isSpecificBuiltinType(BuiltinType::Id); \
6094 #include "clang/Basic/OpenCLImageTypes.def"
6096 inline bool Type::isSamplerT() const {
6097 return isSpecificBuiltinType(BuiltinType::OCLSampler);
6100 inline bool Type::isEventT() const {
6101 return isSpecificBuiltinType(BuiltinType::OCLEvent);
6104 inline bool Type::isClkEventT() const {
6105 return isSpecificBuiltinType(BuiltinType::OCLClkEvent);
6108 inline bool Type::isQueueT() const {
6109 return isSpecificBuiltinType(BuiltinType::OCLQueue);
6112 inline bool Type::isReserveIDT() const {
6113 return isSpecificBuiltinType(BuiltinType::OCLReserveID);
6116 inline bool Type::isImageType() const {
6117 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) is##Id##Type() ||
6119 #include "clang/Basic/OpenCLImageTypes.def"
6120 false; // end boolean or operation
6123 inline bool Type::isPipeType() const {
6124 return isa<PipeType>(CanonicalType);
6127 inline bool Type::isOpenCLSpecificType() const {
6128 return isSamplerT() || isEventT() || isImageType() || isClkEventT() ||
6129 isQueueT() || isReserveIDT() || isPipeType();
6132 inline bool Type::isTemplateTypeParmType() const {
6133 return isa<TemplateTypeParmType>(CanonicalType);
6136 inline bool Type::isSpecificBuiltinType(unsigned K) const {
6137 if (const BuiltinType *BT = getAs<BuiltinType>())
6138 if (BT->getKind() == (BuiltinType::Kind) K)
6143 inline bool Type::isPlaceholderType() const {
6144 if (const BuiltinType *BT = dyn_cast<BuiltinType>(this))
6145 return BT->isPlaceholderType();
6149 inline const BuiltinType *Type::getAsPlaceholderType() const {
6150 if (const BuiltinType *BT = dyn_cast<BuiltinType>(this))
6151 if (BT->isPlaceholderType())
6156 inline bool Type::isSpecificPlaceholderType(unsigned K) const {
6157 assert(BuiltinType::isPlaceholderTypeKind((BuiltinType::Kind) K));
6158 if (const BuiltinType *BT = dyn_cast<BuiltinType>(this))
6159 return (BT->getKind() == (BuiltinType::Kind) K);
6163 inline bool Type::isNonOverloadPlaceholderType() const {
6164 if (const BuiltinType *BT = dyn_cast<BuiltinType>(this))
6165 return BT->isNonOverloadPlaceholderType();
6169 inline bool Type::isVoidType() const {
6170 if (const BuiltinType *BT = dyn_cast<BuiltinType>(CanonicalType))
6171 return BT->getKind() == BuiltinType::Void;
6175 inline bool Type::isHalfType() const {
6176 if (const BuiltinType *BT = dyn_cast<BuiltinType>(CanonicalType))
6177 return BT->getKind() == BuiltinType::Half;
6178 // FIXME: Should we allow complex __fp16? Probably not.
6182 inline bool Type::isNullPtrType() const {
6183 if (const BuiltinType *BT = getAs<BuiltinType>())
6184 return BT->getKind() == BuiltinType::NullPtr;
6188 bool IsEnumDeclComplete(EnumDecl *);
6189 bool IsEnumDeclScoped(EnumDecl *);
6191 inline bool Type::isIntegerType() const {
6192 if (const BuiltinType *BT = dyn_cast<BuiltinType>(CanonicalType))
6193 return BT->getKind() >= BuiltinType::Bool &&
6194 BT->getKind() <= BuiltinType::Int128;
6195 if (const EnumType *ET = dyn_cast<EnumType>(CanonicalType)) {
6196 // Incomplete enum types are not treated as integer types.
6197 // FIXME: In C++, enum types are never integer types.
6198 return IsEnumDeclComplete(ET->getDecl()) &&
6199 !IsEnumDeclScoped(ET->getDecl());
6204 inline bool Type::isScalarType() const {
6205 if (const BuiltinType *BT = dyn_cast<BuiltinType>(CanonicalType))
6206 return BT->getKind() > BuiltinType::Void &&
6207 BT->getKind() <= BuiltinType::NullPtr;
6208 if (const EnumType *ET = dyn_cast<EnumType>(CanonicalType))
6209 // Enums are scalar types, but only if they are defined. Incomplete enums
6210 // are not treated as scalar types.
6211 return IsEnumDeclComplete(ET->getDecl());
6212 return isa<PointerType>(CanonicalType) ||
6213 isa<BlockPointerType>(CanonicalType) ||
6214 isa<MemberPointerType>(CanonicalType) ||
6215 isa<ComplexType>(CanonicalType) ||
6216 isa<ObjCObjectPointerType>(CanonicalType);
6219 inline bool Type::isIntegralOrEnumerationType() const {
6220 if (const BuiltinType *BT = dyn_cast<BuiltinType>(CanonicalType))
6221 return BT->getKind() >= BuiltinType::Bool &&
6222 BT->getKind() <= BuiltinType::Int128;
6224 // Check for a complete enum type; incomplete enum types are not properly an
6225 // enumeration type in the sense required here.
6226 if (const EnumType *ET = dyn_cast<EnumType>(CanonicalType))
6227 return IsEnumDeclComplete(ET->getDecl());
6232 inline bool Type::isBooleanType() const {
6233 if (const BuiltinType *BT = dyn_cast<BuiltinType>(CanonicalType))
6234 return BT->getKind() == BuiltinType::Bool;
6238 inline bool Type::isUndeducedType() const {
6239 auto *DT = getContainedDeducedType();
6240 return DT && !DT->isDeduced();
6243 /// \brief Determines whether this is a type for which one can define
6244 /// an overloaded operator.
6245 inline bool Type::isOverloadableType() const {
6246 return isDependentType() || isRecordType() || isEnumeralType();
6249 /// \brief Determines whether this type can decay to a pointer type.
6250 inline bool Type::canDecayToPointerType() const {
6251 return isFunctionType() || isArrayType();
6254 inline bool Type::hasPointerRepresentation() const {
6255 return (isPointerType() || isReferenceType() || isBlockPointerType() ||
6256 isObjCObjectPointerType() || isNullPtrType());
6259 inline bool Type::hasObjCPointerRepresentation() const {
6260 return isObjCObjectPointerType();
6263 inline const Type *Type::getBaseElementTypeUnsafe() const {
6264 const Type *type = this;
6265 while (const ArrayType *arrayType = type->getAsArrayTypeUnsafe())
6266 type = arrayType->getElementType().getTypePtr();
6270 inline const Type *Type::getPointeeOrArrayElementType() const {
6271 const Type *type = this;
6272 if (type->isAnyPointerType())
6273 return type->getPointeeType().getTypePtr();
6274 else if (type->isArrayType())
6275 return type->getBaseElementTypeUnsafe();
6279 /// Insertion operator for diagnostics. This allows sending QualType's into a
6280 /// diagnostic with <<.
6281 inline const DiagnosticBuilder &operator<<(const DiagnosticBuilder &DB,
6283 DB.AddTaggedVal(reinterpret_cast<intptr_t>(T.getAsOpaquePtr()),
6284 DiagnosticsEngine::ak_qualtype);
6288 /// Insertion operator for partial diagnostics. This allows sending QualType's
6289 /// into a diagnostic with <<.
6290 inline const PartialDiagnostic &operator<<(const PartialDiagnostic &PD,
6292 PD.AddTaggedVal(reinterpret_cast<intptr_t>(T.getAsOpaquePtr()),
6293 DiagnosticsEngine::ak_qualtype);
6297 // Helper class template that is used by Type::getAs to ensure that one does
6298 // not try to look through a qualified type to get to an array type.
6299 template <typename T>
6300 using TypeIsArrayType =
6301 std::integral_constant<bool, std::is_same<T, ArrayType>::value ||
6302 std::is_base_of<ArrayType, T>::value>;
6304 // Member-template getAs<specific type>'.
6305 template <typename T> const T *Type::getAs() const {
6306 static_assert(!TypeIsArrayType<T>::value,
6307 "ArrayType cannot be used with getAs!");
6309 // If this is directly a T type, return it.
6310 if (const T *Ty = dyn_cast<T>(this))
6313 // If the canonical form of this type isn't the right kind, reject it.
6314 if (!isa<T>(CanonicalType))
6317 // If this is a typedef for the type, strip the typedef off without
6318 // losing all typedef information.
6319 return cast<T>(getUnqualifiedDesugaredType());
6322 template <typename T> const T *Type::getAsAdjusted() const {
6323 static_assert(!TypeIsArrayType<T>::value, "ArrayType cannot be used with getAsAdjusted!");
6325 // If this is directly a T type, return it.
6326 if (const T *Ty = dyn_cast<T>(this))
6329 // If the canonical form of this type isn't the right kind, reject it.
6330 if (!isa<T>(CanonicalType))
6333 // Strip off type adjustments that do not modify the underlying nature of the
6335 const Type *Ty = this;
6337 if (const auto *A = dyn_cast<AttributedType>(Ty))
6338 Ty = A->getModifiedType().getTypePtr();
6339 else if (const auto *E = dyn_cast<ElaboratedType>(Ty))
6340 Ty = E->desugar().getTypePtr();
6341 else if (const auto *P = dyn_cast<ParenType>(Ty))
6342 Ty = P->desugar().getTypePtr();
6343 else if (const auto *A = dyn_cast<AdjustedType>(Ty))
6344 Ty = A->desugar().getTypePtr();
6349 // Just because the canonical type is correct does not mean we can use cast<>,
6350 // since we may not have stripped off all the sugar down to the base type.
6351 return dyn_cast<T>(Ty);
6354 inline const ArrayType *Type::getAsArrayTypeUnsafe() const {
6355 // If this is directly an array type, return it.
6356 if (const ArrayType *arr = dyn_cast<ArrayType>(this))
6359 // If the canonical form of this type isn't the right kind, reject it.
6360 if (!isa<ArrayType>(CanonicalType))
6363 // If this is a typedef for the type, strip the typedef off without
6364 // losing all typedef information.
6365 return cast<ArrayType>(getUnqualifiedDesugaredType());
6368 template <typename T> const T *Type::castAs() const {
6369 static_assert(!TypeIsArrayType<T>::value,
6370 "ArrayType cannot be used with castAs!");
6372 if (const T *ty = dyn_cast<T>(this)) return ty;
6373 assert(isa<T>(CanonicalType));
6374 return cast<T>(getUnqualifiedDesugaredType());
6377 inline const ArrayType *Type::castAsArrayTypeUnsafe() const {
6378 assert(isa<ArrayType>(CanonicalType));
6379 if (const ArrayType *arr = dyn_cast<ArrayType>(this)) return arr;
6380 return cast<ArrayType>(getUnqualifiedDesugaredType());
6383 DecayedType::DecayedType(QualType OriginalType, QualType DecayedPtr,
6384 QualType CanonicalPtr)
6385 : AdjustedType(Decayed, OriginalType, DecayedPtr, CanonicalPtr) {
6387 QualType Adjusted = getAdjustedType();
6388 (void)AttributedType::stripOuterNullability(Adjusted);
6389 assert(isa<PointerType>(Adjusted));
6393 QualType DecayedType::getPointeeType() const {
6394 QualType Decayed = getDecayedType();
6395 (void)AttributedType::stripOuterNullability(Decayed);
6396 return cast<PointerType>(Decayed)->getPointeeType();
6399 } // namespace clang
6401 #endif // LLVM_CLANG_AST_TYPE_H