clang  6.0.0svn
Type.h
Go to the documentation of this file.
1 //===- Type.h - C Language Family Type Representation -----------*- C++ -*-===//
2 //
3 // The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 /// \file
11 /// \brief C Language Family Type Representation
12 ///
13 /// This file defines the clang::Type interface and subclasses, used to
14 /// represent types for languages in the C family.
15 //
16 //===----------------------------------------------------------------------===//
17 
18 #ifndef LLVM_CLANG_AST_TYPE_H
19 #define LLVM_CLANG_AST_TYPE_H
20 
22 #include "clang/AST/TemplateName.h"
24 #include "clang/Basic/Diagnostic.h"
26 #include "clang/Basic/LLVM.h"
27 #include "clang/Basic/Linkage.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"
47 #include <cassert>
48 #include <cstddef>
49 #include <cstdint>
50 #include <cstring>
51 #include <string>
52 #include <type_traits>
53 #include <utility>
54 
55 namespace clang {
56 
57 class ExtQuals;
58 class QualType;
59 class Type;
60 
61 enum {
64 };
65 
66 } // namespace clang
67 
68 namespace llvm {
69 
70  template <typename T>
71  struct PointerLikeTypeTraits;
72  template<>
74  static inline void *getAsVoidPointer(::clang::Type *P) { return P; }
75 
76  static inline ::clang::Type *getFromVoidPointer(void *P) {
77  return static_cast< ::clang::Type*>(P);
78  }
79 
80  enum { NumLowBitsAvailable = clang::TypeAlignmentInBits };
81  };
82 
83  template<>
85  static inline void *getAsVoidPointer(::clang::ExtQuals *P) { return P; }
86 
87  static inline ::clang::ExtQuals *getFromVoidPointer(void *P) {
88  return static_cast< ::clang::ExtQuals*>(P);
89  }
90 
91  enum { NumLowBitsAvailable = clang::TypeAlignmentInBits };
92  };
93 
94  template <>
95  struct isPodLike<clang::QualType> { static const bool value = true; };
96 
97 } // namespace llvm
98 
99 namespace clang {
100 
101 class ArrayType;
102 class ASTContext;
103 class AttributedType;
104 class AutoType;
105 class BuiltinType;
106 template <typename> class CanQual;
107 class ComplexType;
108 class CXXRecordDecl;
109 class DeclContext;
110 class DeducedType;
111 class EnumDecl;
112 class Expr;
113 class ExtQualsTypeCommonBase;
114 class FunctionDecl;
115 class FunctionNoProtoType;
116 class FunctionProtoType;
117 class IdentifierInfo;
118 class InjectedClassNameType;
119 class NamedDecl;
120 class ObjCInterfaceDecl;
121 class ObjCObjectPointerType;
122 class ObjCObjectType;
123 class ObjCProtocolDecl;
124 class ObjCTypeParamDecl;
125 class ParenType;
126 struct PrintingPolicy;
127 class RecordDecl;
128 class RecordType;
129 class Stmt;
130 class TagDecl;
131 class TemplateArgument;
132 class TemplateArgumentListInfo;
133 class TemplateArgumentLoc;
134 class TemplateSpecializationType;
135 class TemplateTypeParmDecl;
136 class TypedefNameDecl;
137 class TypedefType;
138 class UnresolvedUsingTypenameDecl;
139 
140 using CanQualType = CanQual<Type>;
141 
142  // Provide forward declarations for all of the *Type classes
143 #define TYPE(Class, Base) class Class##Type;
144 #include "clang/AST/TypeNodes.def"
145 
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)
152 class Qualifiers {
153 public:
154  enum TQ { // NOTE: These flags must be kept in sync with DeclSpec::TQ.
155  Const = 0x1,
156  Restrict = 0x2,
157  Volatile = 0x4,
158  CVRMask = Const | Volatile | Restrict
159  };
160 
161  enum GC {
162  GCNone = 0,
164  Strong
165  };
166 
168  /// There is no lifetime qualification on this type.
170 
171  /// This object can be modified without requiring retains or
172  /// releases.
174 
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
179  /// live.
181 
182  /// Reading or writing from this object requires a barrier call.
184 
185  /// Assigning into this object requires a lifetime extension.
186  OCL_Autoreleasing
187  };
188 
189  enum {
190  /// The maximum supported address space number.
191  /// 23 bits should be enough for anyone.
192  MaxAddressSpace = 0x7fffffu,
193 
194  /// The width of the "fast" qualifier mask.
195  FastWidth = 3,
196 
197  /// The fast qualifier mask.
198  FastMask = (1 << FastWidth) - 1
199  };
200 
201  /// Returns the common set of qualifiers while removing them from
202  /// the given sets.
204  // If both are only CVR-qualified, bit operations are sufficient.
205  if (!(L.Mask & ~CVRMask) && !(R.Mask & ~CVRMask)) {
206  Qualifiers Q;
207  Q.Mask = L.Mask & R.Mask;
208  L.Mask &= ~Q.Mask;
209  R.Mask &= ~Q.Mask;
210  return Q;
211  }
212 
213  Qualifiers Q;
214  unsigned CommonCRV = L.getCVRQualifiers() & R.getCVRQualifiers();
215  Q.addCVRQualifiers(CommonCRV);
216  L.removeCVRQualifiers(CommonCRV);
217  R.removeCVRQualifiers(CommonCRV);
218 
219  if (L.getObjCGCAttr() == R.getObjCGCAttr()) {
221  L.removeObjCGCAttr();
222  R.removeObjCGCAttr();
223  }
224 
225  if (L.getObjCLifetime() == R.getObjCLifetime()) {
227  L.removeObjCLifetime();
228  R.removeObjCLifetime();
229  }
230 
231  if (L.getAddressSpace() == R.getAddressSpace()) {
233  L.removeAddressSpace();
234  R.removeAddressSpace();
235  }
236  return Q;
237  }
238 
239  static Qualifiers fromFastMask(unsigned Mask) {
240  Qualifiers Qs;
241  Qs.addFastQualifiers(Mask);
242  return Qs;
243  }
244 
245  static Qualifiers fromCVRMask(unsigned CVR) {
246  Qualifiers Qs;
247  Qs.addCVRQualifiers(CVR);
248  return Qs;
249  }
250 
251  static Qualifiers fromCVRUMask(unsigned CVRU) {
252  Qualifiers Qs;
253  Qs.addCVRUQualifiers(CVRU);
254  return Qs;
255  }
256 
257  // Deserialize qualifiers from an opaque representation.
258  static Qualifiers fromOpaqueValue(unsigned opaque) {
259  Qualifiers Qs;
260  Qs.Mask = opaque;
261  return Qs;
262  }
263 
264  // Serialize these qualifiers into an opaque representation.
265  unsigned getAsOpaqueValue() const {
266  return Mask;
267  }
268 
269  bool hasConst() const { return Mask & Const; }
270  void setConst(bool flag) {
271  Mask = (Mask & ~Const) | (flag ? Const : 0);
272  }
273  void removeConst() { Mask &= ~Const; }
274  void addConst() { Mask |= Const; }
275 
276  bool hasVolatile() const { return Mask & Volatile; }
277  void setVolatile(bool flag) {
278  Mask = (Mask & ~Volatile) | (flag ? Volatile : 0);
279  }
280  void removeVolatile() { Mask &= ~Volatile; }
281  void addVolatile() { Mask |= Volatile; }
282 
283  bool hasRestrict() const { return Mask & Restrict; }
284  void setRestrict(bool flag) {
285  Mask = (Mask & ~Restrict) | (flag ? Restrict : 0);
286  }
287  void removeRestrict() { Mask &= ~Restrict; }
288  void addRestrict() { Mask |= Restrict; }
289 
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;
295  }
296  void removeCVRQualifiers(unsigned mask) {
297  assert(!(mask & ~CVRMask) && "bitmask contains non-CVR bits");
298  Mask &= ~mask;
299  }
301  removeCVRQualifiers(CVRMask);
302  }
303  void addCVRQualifiers(unsigned mask) {
304  assert(!(mask & ~CVRMask) && "bitmask contains non-CVR bits");
305  Mask |= mask;
306  }
307  void addCVRUQualifiers(unsigned mask) {
308  assert(!(mask & ~CVRMask & ~UMask) && "bitmask contains non-CVRU bits");
309  Mask |= mask;
310  }
311 
312  bool hasUnaligned() const { return Mask & UMask; }
313  void setUnaligned(bool flag) {
314  Mask = (Mask & ~UMask) | (flag ? UMask : 0);
315  }
316  void removeUnaligned() { Mask &= ~UMask; }
317  void addUnaligned() { Mask |= UMask; }
318 
319  bool hasObjCGCAttr() const { return Mask & GCAttrMask; }
320  GC getObjCGCAttr() const { return GC((Mask & GCAttrMask) >> GCAttrShift); }
322  Mask = (Mask & ~GCAttrMask) | (type << GCAttrShift);
323  }
324  void removeObjCGCAttr() { setObjCGCAttr(GCNone); }
326  assert(type);
327  setObjCGCAttr(type);
328  }
330  Qualifiers qs = *this;
331  qs.removeObjCGCAttr();
332  return qs;
333  }
335  Qualifiers qs = *this;
336  qs.removeObjCLifetime();
337  return qs;
338  }
339 
340  bool hasObjCLifetime() const { return Mask & LifetimeMask; }
342  return ObjCLifetime((Mask & LifetimeMask) >> LifetimeShift);
343  }
345  Mask = (Mask & ~LifetimeMask) | (type << LifetimeShift);
346  }
347  void removeObjCLifetime() { setObjCLifetime(OCL_None); }
349  assert(type);
350  assert(!hasObjCLifetime());
351  Mask |= (type << LifetimeShift);
352  }
353 
354  /// True if the lifetime is neither None or ExplicitNone.
356  ObjCLifetime lifetime = getObjCLifetime();
357  return (lifetime > OCL_ExplicitNone);
358  }
359 
360  /// True if the lifetime is either strong or weak.
362  ObjCLifetime lifetime = getObjCLifetime();
363  return (lifetime == OCL_Strong || lifetime == OCL_Weak);
364  }
365 
366  bool hasAddressSpace() const { return Mask & AddressSpaceMask; }
368  return static_cast<LangAS>(Mask >> AddressSpaceShift);
369  }
371  return isTargetAddressSpace(getAddressSpace());
372  }
373  /// Get the address space attribute value to be printed by diagnostics.
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))).
385  return 0;
386  }
387  void setAddressSpace(LangAS space) {
388  assert((unsigned)space <= MaxAddressSpace);
389  Mask = (Mask & ~AddressSpaceMask)
390  | (((uint32_t) space) << AddressSpaceShift);
391  }
392  void removeAddressSpace() { setAddressSpace(LangAS::Default); }
393  void addAddressSpace(LangAS space) {
394  assert(space != LangAS::Default);
395  setAddressSpace(space);
396  }
397 
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;
405  }
406  void removeFastQualifiers(unsigned mask) {
407  assert(!(mask & ~FastMask) && "bitmask contains non-fast qualifier bits");
408  Mask &= ~mask;
409  }
411  removeFastQualifiers(FastMask);
412  }
413  void addFastQualifiers(unsigned mask) {
414  assert(!(mask & ~FastMask) && "bitmask contains non-fast qualifier bits");
415  Mask |= mask;
416  }
417 
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; }
422  Qualifiers Quals = *this;
423  Quals.setFastQualifiers(0);
424  return Quals;
425  }
426 
427  /// Return true if the set contains any qualifiers.
428  bool hasQualifiers() const { return Mask; }
429  bool empty() const { return !Mask; }
430 
431  /// Add the qualifiers from the given set to this set.
433  // If the other set doesn't have any non-boolean qualifiers, just
434  // bit-or it in.
435  if (!(Q.Mask & ~CVRMask))
436  Mask |= Q.Mask;
437  else {
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());
445  }
446  }
447 
448  /// \brief Remove the qualifiers from the given set from this set.
450  // If the other set doesn't have any non-boolean qualifiers, just
451  // bit-and the inverse in.
452  if (!(Q.Mask & ~CVRMask))
453  Mask &= ~Q.Mask;
454  else {
455  Mask &= ~(Q.Mask & CVRMask);
456  if (getObjCGCAttr() == Q.getObjCGCAttr())
457  removeObjCGCAttr();
458  if (getObjCLifetime() == Q.getObjCLifetime())
459  removeObjCLifetime();
460  if (getAddressSpace() == Q.getAddressSpace())
461  removeAddressSpace();
462  }
463  }
464 
465  /// Add the qualifiers from the given set to this set, given that
466  /// they don't conflict.
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());
474  Mask |= qs.Mask;
475  }
476 
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.
480  /// CL1.1 or CL1.2:
481  /// every address space is a superset of itself.
482  /// CL2.0 adds:
483  /// __generic is a superset of any address space except for __constant.
485  return
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 &&
492  }
493 
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
500  // be changed.
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());
509  }
510 
511  /// \brief Determines if these qualifiers compatibly include another set of
512  /// qualifiers from the narrow perspective of Objective-C ARC lifetime.
513  ///
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).
519  if (getObjCLifetime() == other.getObjCLifetime())
520  return true;
521 
522  if (getObjCLifetime() == OCL_Weak || other.getObjCLifetime() == OCL_Weak)
523  return false;
524 
525  if (getObjCLifetime() == OCL_None || other.getObjCLifetime() == OCL_None)
526  return true;
527 
528  return hasConst();
529  }
530 
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;
534 
535  bool operator==(Qualifiers Other) const { return Mask == Other.Mask; }
536  bool operator!=(Qualifiers Other) const { return Mask != Other.Mask; }
537 
538  explicit operator bool() const { return hasQualifiers(); }
539 
541  addQualifiers(R);
542  return *this;
543  }
544 
545  // Union two qualifier sets. If an enumerated qualifier appears
546  // in both sets, use the one from the right.
548  L += R;
549  return L;
550  }
551 
553  removeQualifiers(R);
554  return *this;
555  }
556 
557  /// \brief Compute the difference between two qualifier sets.
559  L -= R;
560  return L;
561  }
562 
563  std::string getAsString() const;
564  std::string getAsString(const PrintingPolicy &Policy) const;
565 
566  bool isEmptyWhenPrinted(const PrintingPolicy &Policy) const;
567  void print(raw_ostream &OS, const PrintingPolicy &Policy,
568  bool appendSpaceIfNonEmpty = false) const;
569 
570  void Profile(llvm::FoldingSetNodeID &ID) const {
571  ID.AddInteger(Mask);
572  }
573 
574 private:
575  // bits: |0 1 2|3|4 .. 5|6 .. 8|9 ... 31|
576  // |C R V|U|GCAttr|Lifetime|AddressSpace|
577  uint32_t Mask = 0;
578 
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;
588 };
589 
590 /// A std::pair-like structure for storing a qualified type split
591 /// into its local qualifiers and its locally-unqualified type.
593  /// The locally-unqualified type.
594  const Type *Ty = nullptr;
595 
596  /// The local qualifiers.
598 
599  SplitQualType() = default;
600  SplitQualType(const Type *ty, Qualifiers qs) : Ty(ty), Quals(qs) {}
601 
602  SplitQualType getSingleStepDesugaredType() const; // end of this file
603 
604  // Make std::tie work.
605  std::pair<const Type *,Qualifiers> asPair() const {
606  return std::pair<const Type *, Qualifiers>(Ty, Quals);
607  }
608 
610  return a.Ty == b.Ty && a.Quals == b.Quals;
611  }
613  return a.Ty != b.Ty || a.Quals != b.Quals;
614  }
615 };
616 
617 /// The kind of type we are substituting Objective-C type arguments into.
618 ///
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.
623  /// An ordinary type.
624  Ordinary,
625 
626  /// The result type of a method or function.
627  Result,
628 
629  /// The parameter type of a method or function.
630  Parameter,
631 
632  /// The type of a property.
633  Property,
634 
635  /// The superclass of a type.
636  Superclass,
637 };
638 
639 /// A (possibly-)qualified type.
640 ///
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).
646 ///
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.
653 class QualType {
654  friend class QualifierCollector;
655 
656  // Thankfully, these are efficiently composable.
657  llvm::PointerIntPair<llvm::PointerUnion<const Type *, const ExtQuals *>,
659 
660  const ExtQuals *getExtQualsUnsafe() const {
661  return Value.getPointer().get<const ExtQuals*>();
662  }
663 
664  const Type *getTypePtrUnsafe() const {
665  return Value.getPointer().get<const Type*>();
666  }
667 
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);
674  }
675 
676 public:
677  QualType() = default;
678  QualType(const Type *Ptr, unsigned Quals) : Value(Ptr, Quals) {}
679  QualType(const ExtQuals *Ptr, unsigned Quals) : Value(Ptr, Quals) {}
680 
681  unsigned getLocalFastQualifiers() const { return Value.getInt(); }
682  void setLocalFastQualifiers(unsigned Quals) { Value.setInt(Quals); }
683 
684  /// Retrieves a pointer to the underlying (unqualified) type.
685  ///
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;
689 
690  const Type *getTypePtrOrNull() const;
691 
692  /// Retrieves a pointer to the name of the base type.
693  const IdentifierInfo *getBaseTypeIdentifier() const;
694 
695  /// Divides a QualType into its unqualified type and a set of local
696  /// qualifiers.
697  SplitQualType split() const;
698 
699  void *getAsOpaquePtr() const { return Value.getOpaqueValue(); }
700 
701  static QualType getFromOpaquePtr(const void *Ptr) {
702  QualType T;
703  T.Value.setFromOpaqueValue(const_cast<void*>(Ptr));
704  return T;
705  }
706 
707  const Type &operator*() const {
708  return *getTypePtr();
709  }
710 
711  const Type *operator->() const {
712  return getTypePtr();
713  }
714 
715  bool isCanonical() const;
716  bool isCanonicalAsParam() const;
717 
718  /// Return true if this QualType doesn't point to a type yet.
719  bool isNull() const {
720  return Value.getPointer().isNull();
721  }
722 
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);
728  }
729 
730  /// \brief Determine whether this type is const-qualified.
731  bool isConstQualified() const;
732 
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.
737  return (getLocalFastQualifiers() & Qualifiers::Restrict);
738  }
739 
740  /// \brief Determine whether this type is restrict-qualified.
741  bool isRestrictQualified() const;
742 
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.
747  return (getLocalFastQualifiers() & Qualifiers::Volatile);
748  }
749 
750  /// \brief Determine whether this type is volatile-qualified.
751  bool isVolatileQualified() const;
752 
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();
758  }
759 
760  /// \brief Determine whether this type has any qualifiers.
761  bool hasQualifiers() const;
762 
763  /// \brief Determine whether this particular QualType instance has any
764  /// "non-fast" qualifiers, e.g., those that are stored in an ExtQualType
765  /// instance.
767  return Value.getPointer().is<const ExtQuals*>();
768  }
769 
770  /// \brief Retrieve the set of qualifiers local to this particular QualType
771  /// instance, not including any qualifiers acquired through typedefs or
772  /// other sugar.
773  Qualifiers getLocalQualifiers() const;
774 
775  /// \brief Retrieve the set of qualifiers applied to this type.
776  Qualifiers getQualifiers() const;
777 
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();
783  }
784 
785  /// \brief Retrieve the set of CVR (const-volatile-restrict) qualifiers
786  /// applied to this type.
787  unsigned getCVRQualifiers() const;
788 
789  bool isConstant(const ASTContext& Ctx) const {
790  return QualType::isConstant(*this, Ctx);
791  }
792 
793  /// \brief Determine whether this is a Plain Old Data (POD) type (C++ 3.9p10).
794  bool isPODType(const ASTContext &Context) const;
795 
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;
799 
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;
804 
805  /// Return true if this is a trivial type per (C++0x [basic.types]p9)
806  bool isTrivialType(const ASTContext &Context) const;
807 
808  /// Return true if this is a trivially copyable type (C++0x [basic.types]p9)
809  bool isTriviallyCopyableType(const ASTContext &Context) const;
810 
811  // Don't promise in the API that anything besides 'const' can be
812  // easily added.
813 
814  /// Add the `const` type qualifier to this QualType.
815  void addConst() {
816  addFastQualifiers(Qualifiers::Const);
817  }
818  QualType withConst() const {
819  return withFastQualifiers(Qualifiers::Const);
820  }
821 
822  /// Add the `volatile` type qualifier to this QualType.
823  void addVolatile() {
824  addFastQualifiers(Qualifiers::Volatile);
825  }
827  return withFastQualifiers(Qualifiers::Volatile);
828  }
829 
830  /// Add the `restrict` qualifier to this QualType.
831  void addRestrict() {
832  addFastQualifiers(Qualifiers::Restrict);
833  }
835  return withFastQualifiers(Qualifiers::Restrict);
836  }
837 
838  QualType withCVRQualifiers(unsigned CVR) const {
839  return withFastQualifiers(CVR);
840  }
841 
842  void addFastQualifiers(unsigned TQs) {
843  assert(!(TQs & ~Qualifiers::FastMask)
844  && "non-fast qualifier bits set in mask!");
845  Value.setInt(Value.getInt() | TQs);
846  }
847 
848  void removeLocalConst();
849  void removeLocalVolatile();
850  void removeLocalRestrict();
851  void removeLocalCVRQualifiers(unsigned Mask);
852 
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);
857  }
858 
859  // Creates a type with the given qualifiers in addition to any
860  // qualifiers already on this type.
861  QualType withFastQualifiers(unsigned TQs) const {
862  QualType T = *this;
863  T.addFastQualifiers(TQs);
864  return T;
865  }
866 
867  // Creates a type with exactly the given fast qualifiers, removing
868  // any existing fast qualifiers.
870  return withoutLocalFastQualifiers().withFastQualifiers(TQs);
871  }
872 
873  // Removes fast qualifiers, but leaves any extended qualifiers in place.
875  QualType T = *this;
877  return T;
878  }
879 
880  QualType getCanonicalType() const;
881 
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); }
886 
887  /// \brief Retrieve the unqualified variant of the given type,
888  /// removing as little sugar as possible.
889  ///
890  /// This routine looks through various kinds of sugar to find the
891  /// least-desugared type that is unqualified. For example, given:
892  ///
893  /// \code
894  /// typedef int Integer;
895  /// typedef const Integer CInteger;
896  /// typedef CInteger DifferenceType;
897  /// \endcode
898  ///
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.
901  ///
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;
906 
907  /// Retrieve the unqualified variant of the given type, removing as little
908  /// sugar as possible.
909  ///
910  /// Like getUnqualifiedType(), but also returns the set of
911  /// qualifiers that were built up.
912  ///
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;
917 
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;
921 
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;
925 
926  QualType getNonReferenceType() const;
927 
928  /// \brief Determine the type of a (typically non-lvalue) expression with the
929  /// specified result type.
930  ///
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;
937 
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
943  /// concrete.
944  ///
945  /// Qualifiers are left in place.
946  QualType getDesugaredType(const ASTContext &Context) const {
947  return getDesugaredType(*this, Context);
948  }
949 
951  return getSplitDesugaredType(*this);
952  }
953 
954  /// \brief Return the specified type with one level of "sugar" removed from
955  /// the type.
956  ///
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.
960  return getSingleStepDesugaredTypeImpl(*this, Context);
961  }
962 
963  /// Returns the specified type after dropping any
964  /// outer-level parentheses.
966  if (isa<ParenType>(*this))
967  return QualType::IgnoreParens(*this);
968  return *this;
969  }
970 
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;
974  }
975  friend bool operator!=(const QualType &LHS, const QualType &RHS) {
976  return LHS.Value != RHS.Value;
977  }
978 
979  std::string getAsString() const {
980  return getAsString(split());
981  }
982 
983  static std::string getAsString(SplitQualType split) {
984  return getAsString(split.Ty, split.Quals);
985  }
986 
987  static std::string getAsString(const Type *ty, Qualifiers qs);
988 
989  std::string getAsString(const PrintingPolicy &Policy) const;
990 
991  void print(raw_ostream &OS, const PrintingPolicy &Policy,
992  const Twine &PlaceHolder = Twine(),
993  unsigned Indentation = 0) const {
994  print(split(), OS, Policy, PlaceHolder, Indentation);
995  }
996 
997  static void print(SplitQualType split, raw_ostream &OS,
998  const PrintingPolicy &policy, const Twine &PlaceHolder,
999  unsigned Indentation = 0) {
1000  return print(split.Ty, split.Quals, OS, policy, PlaceHolder, Indentation);
1001  }
1002 
1003  static void print(const Type *ty, Qualifiers qs,
1004  raw_ostream &OS, const PrintingPolicy &policy,
1005  const Twine &PlaceHolder,
1006  unsigned Indentation = 0);
1007 
1008  void getAsStringInternal(std::string &Str,
1009  const PrintingPolicy &Policy) const {
1010  return getAsStringInternal(split(), Str, Policy);
1011  }
1012 
1013  static void getAsStringInternal(SplitQualType split, std::string &out,
1014  const PrintingPolicy &policy) {
1015  return getAsStringInternal(split.Ty, split.Quals, out, policy);
1016  }
1017 
1018  static void getAsStringInternal(const Type *ty, Qualifiers qs,
1019  std::string &out,
1020  const PrintingPolicy &policy);
1021 
1023  const QualType &T;
1024  const PrintingPolicy &Policy;
1025  const Twine &PlaceHolder;
1026  unsigned Indentation;
1027 
1028  public:
1030  const Twine &PlaceHolder, unsigned Indentation)
1031  : T(T), Policy(Policy), PlaceHolder(PlaceHolder),
1032  Indentation(Indentation) {}
1033 
1034  friend raw_ostream &operator<<(raw_ostream &OS,
1035  const StreamedQualTypeHelper &SQT) {
1036  SQT.T.print(OS, SQT.Policy, SQT.PlaceHolder, SQT.Indentation);
1037  return OS;
1038  }
1039  };
1040 
1042  const Twine &PlaceHolder = Twine(),
1043  unsigned Indentation = 0) const {
1044  return StreamedQualTypeHelper(*this, Policy, PlaceHolder, Indentation);
1045  }
1046 
1047  void dump(const char *s) const;
1048  void dump() const;
1049  void dump(llvm::raw_ostream &OS) const;
1050 
1051  void Profile(llvm::FoldingSetNodeID &ID) const {
1052  ID.AddPointer(getAsOpaquePtr());
1053  }
1054 
1055  /// Return the address space of this type.
1056  inline LangAS getAddressSpace() const;
1057 
1058  /// Returns gc attribute of this type.
1059  inline Qualifiers::GC getObjCGCAttr() const;
1060 
1061  /// true when Type is objc's weak.
1062  bool isObjCGCWeak() const {
1063  return getObjCGCAttr() == Qualifiers::Weak;
1064  }
1065 
1066  /// true when Type is objc's strong.
1067  bool isObjCGCStrong() const {
1068  return getObjCGCAttr() == Qualifiers::Strong;
1069  }
1070 
1071  /// Returns lifetime attribute of this type.
1073  return getQualifiers().getObjCLifetime();
1074  }
1075 
1077  return getQualifiers().hasNonTrivialObjCLifetime();
1078  }
1079 
1081  return getQualifiers().hasStrongOrWeakObjCLifetime();
1082  }
1083 
1084  // true when Type is objc's weak and weak is enabled but ARC isn't.
1085  bool isNonWeakInMRRWithObjCWeak(const ASTContext &Context) const;
1086 
1091  DK_objc_weak_lifetime
1092  };
1093 
1094  /// Returns a nonzero value if objects of this type require
1095  /// non-trivial work to clean up after. Non-zero because it's
1096  /// conceivable that qualifiers (objc_gc(weak)?) could make
1097  /// something require destruction.
1099  return isDestructedTypeImpl(*this);
1100  }
1101 
1102  /// Determine whether expressions of the given type are forbidden
1103  /// from being lvalues in C.
1104  ///
1105  /// The expression types that are forbidden to be lvalues are:
1106  /// - 'void', but not qualified void
1107  /// - function types
1108  ///
1109  /// The exact rule here is C99 6.3.2.1:
1110  /// An lvalue is an expression with an object type or an incomplete
1111  /// type other than void.
1112  bool isCForbiddenLValueType() const;
1113 
1114  /// Substitute type arguments for the Objective-C type parameters used in the
1115  /// subject type.
1116  ///
1117  /// \param ctx ASTContext in which the type exists.
1118  ///
1119  /// \param typeArgs The type arguments that will be substituted for the
1120  /// Objective-C type parameters in the subject type, which are generally
1121  /// computed via \c Type::getObjCSubstitutions. If empty, the type
1122  /// parameters will be replaced with their bounds or id/Class, as appropriate
1123  /// for the context.
1124  ///
1125  /// \param context The context in which the subject type was written.
1126  ///
1127  /// \returns the resulting type.
1128  QualType substObjCTypeArgs(ASTContext &ctx,
1129  ArrayRef<QualType> typeArgs,
1130  ObjCSubstitutionContext context) const;
1131 
1132  /// Substitute type arguments from an object type for the Objective-C type
1133  /// parameters used in the subject type.
1134  ///
1135  /// This operation combines the computation of type arguments for
1136  /// substitution (\c Type::getObjCSubstitutions) with the actual process of
1137  /// substitution (\c QualType::substObjCTypeArgs) for the convenience of
1138  /// callers that need to perform a single substitution in isolation.
1139  ///
1140  /// \param objectType The type of the object whose member type we're
1141  /// substituting into. For example, this might be the receiver of a message
1142  /// or the base of a property access.
1143  ///
1144  /// \param dc The declaration context from which the subject type was
1145  /// retrieved, which indicates (for example) which type parameters should
1146  /// be substituted.
1147  ///
1148  /// \param context The context in which the subject type was written.
1149  ///
1150  /// \returns the subject type after replacing all of the Objective-C type
1151  /// parameters with their corresponding arguments.
1152  QualType substObjCMemberType(QualType objectType,
1153  const DeclContext *dc,
1154  ObjCSubstitutionContext context) const;
1155 
1156  /// Strip Objective-C "__kindof" types from the given type.
1157  QualType stripObjCKindOfType(const ASTContext &ctx) const;
1158 
1159  /// Remove all qualifiers including _Atomic.
1160  QualType getAtomicUnqualifiedType() const;
1161 
1162 private:
1163  // These methods are implemented in a separate translation unit;
1164  // "static"-ize them to avoid creating temporary QualTypes in the
1165  // caller.
1166  static bool isConstant(QualType T, const ASTContext& Ctx);
1167  static QualType getDesugaredType(QualType T, const ASTContext &Context);
1168  static SplitQualType getSplitDesugaredType(QualType T);
1169  static SplitQualType getSplitUnqualifiedTypeImpl(QualType type);
1170  static QualType getSingleStepDesugaredTypeImpl(QualType type,
1171  const ASTContext &C);
1172  static QualType IgnoreParens(QualType T);
1173  static DestructionKind isDestructedTypeImpl(QualType type);
1174 };
1175 
1176 } // namespace clang
1177 
1178 namespace llvm {
1179 
1180 /// Implement simplify_type for QualType, so that we can dyn_cast from QualType
1181 /// to a specific Type class.
1182 template<> struct simplify_type< ::clang::QualType> {
1183  using SimpleType = const ::clang::Type *;
1184 
1186  return Val.getTypePtr();
1187  }
1188 };
1189 
1190 // Teach SmallPtrSet that QualType is "basically a pointer".
1191 template<>
1192 struct PointerLikeTypeTraits<clang::QualType> {
1193  static inline void *getAsVoidPointer(clang::QualType P) {
1194  return P.getAsOpaquePtr();
1195  }
1196 
1197  static inline clang::QualType getFromVoidPointer(void *P) {
1199  }
1200 
1201  // Various qualifiers go in low bits.
1202  enum { NumLowBitsAvailable = 0 };
1203 };
1204 
1205 } // namespace llvm
1206 
1207 namespace clang {
1208 
1209 /// \brief Base class that is common to both the \c ExtQuals and \c Type
1210 /// classes, which allows \c QualType to access the common fields between the
1211 /// two.
1213  friend class ExtQuals;
1214  friend class QualType;
1215  friend class Type;
1216 
1217  /// \brief The "base" type of an extended qualifiers type (\c ExtQuals) or
1218  /// a self-referential pointer (for \c Type).
1219  ///
1220  /// This pointer allows an efficient mapping from a QualType to its
1221  /// underlying type pointer.
1222  const Type *const BaseType;
1223 
1224  /// \brief The canonical type of this type. A QualType.
1225  QualType CanonicalType;
1226 
1227  ExtQualsTypeCommonBase(const Type *baseType, QualType canon)
1228  : BaseType(baseType), CanonicalType(canon) {}
1229 };
1230 
1231 /// We can encode up to four bits in the low bits of a
1232 /// type pointer, but there are many more type qualifiers that we want
1233 /// to be able to apply to an arbitrary type. Therefore we have this
1234 /// struct, intended to be heap-allocated and used by QualType to
1235 /// store qualifiers.
1236 ///
1237 /// The current design tags the 'const', 'restrict', and 'volatile' qualifiers
1238 /// in three low bits on the QualType pointer; a fourth bit records whether
1239 /// the pointer is an ExtQuals node. The extended qualifiers (address spaces,
1240 /// Objective-C GC attributes) are much more rare.
1241 class ExtQuals : public ExtQualsTypeCommonBase, public llvm::FoldingSetNode {
1242  // NOTE: changing the fast qualifiers should be straightforward as
1243  // long as you don't make 'const' non-fast.
1244  // 1. Qualifiers:
1245  // a) Modify the bitmasks (Qualifiers::TQ and DeclSpec::TQ).
1246  // Fast qualifiers must occupy the low-order bits.
1247  // b) Update Qualifiers::FastWidth and FastMask.
1248  // 2. QualType:
1249  // a) Update is{Volatile,Restrict}Qualified(), defined inline.
1250  // b) Update remove{Volatile,Restrict}, defined near the end of
1251  // this header.
1252  // 3. ASTContext:
1253  // a) Update get{Volatile,Restrict}Type.
1254 
1255  /// The immutable set of qualifiers applied by this node. Always contains
1256  /// extended qualifiers.
1257  Qualifiers Quals;
1258 
1259  ExtQuals *this_() { return this; }
1260 
1261 public:
1262  ExtQuals(const Type *baseType, QualType canon, Qualifiers quals)
1263  : ExtQualsTypeCommonBase(baseType,
1264  canon.isNull() ? QualType(this_(), 0) : canon),
1265  Quals(quals) {
1266  assert(Quals.hasNonFastQualifiers()
1267  && "ExtQuals created with no fast qualifiers");
1268  assert(!Quals.hasFastQualifiers()
1269  && "ExtQuals created with fast qualifiers");
1270  }
1271 
1272  Qualifiers getQualifiers() const { return Quals; }
1273 
1274  bool hasObjCGCAttr() const { return Quals.hasObjCGCAttr(); }
1275  Qualifiers::GC getObjCGCAttr() const { return Quals.getObjCGCAttr(); }
1276 
1277  bool hasObjCLifetime() const { return Quals.hasObjCLifetime(); }
1279  return Quals.getObjCLifetime();
1280  }
1281 
1282  bool hasAddressSpace() const { return Quals.hasAddressSpace(); }
1283  LangAS getAddressSpace() const { return Quals.getAddressSpace(); }
1284 
1285  const Type *getBaseType() const { return BaseType; }
1286 
1287 public:
1288  void Profile(llvm::FoldingSetNodeID &ID) const {
1289  Profile(ID, getBaseType(), Quals);
1290  }
1291 
1292  static void Profile(llvm::FoldingSetNodeID &ID,
1293  const Type *BaseType,
1294  Qualifiers Quals) {
1295  assert(!Quals.hasFastQualifiers() && "fast qualifiers in ExtQuals hash!");
1296  ID.AddPointer(BaseType);
1297  Quals.Profile(ID);
1298  }
1299 };
1300 
1301 /// The kind of C++11 ref-qualifier associated with a function type.
1302 /// This determines whether a member function's "this" object can be an
1303 /// lvalue, rvalue, or neither.
1305  /// \brief No ref-qualifier was provided.
1306  RQ_None = 0,
1307 
1308  /// \brief An lvalue ref-qualifier was provided (\c &).
1310 
1311  /// \brief An rvalue ref-qualifier was provided (\c &&).
1313 };
1314 
1315 /// Which keyword(s) were used to create an AutoType.
1316 enum class AutoTypeKeyword {
1317  /// \brief auto
1318  Auto,
1319 
1320  /// \brief decltype(auto)
1321  DecltypeAuto,
1322 
1323  /// \brief __auto_type (GNU extension)
1324  GNUAutoType
1325 };
1326 
1327 /// The base class of the type hierarchy.
1328 ///
1329 /// A central concept with types is that each type always has a canonical
1330 /// type. A canonical type is the type with any typedef names stripped out
1331 /// of it or the types it references. For example, consider:
1332 ///
1333 /// typedef int foo;
1334 /// typedef foo* bar;
1335 /// 'int *' 'foo *' 'bar'
1336 ///
1337 /// There will be a Type object created for 'int'. Since int is canonical, its
1338 /// CanonicalType pointer points to itself. There is also a Type for 'foo' (a
1339 /// TypedefType). Its CanonicalType pointer points to the 'int' Type. Next
1340 /// there is a PointerType that represents 'int*', which, like 'int', is
1341 /// canonical. Finally, there is a PointerType type for 'foo*' whose canonical
1342 /// type is 'int*', and there is a TypedefType for 'bar', whose canonical type
1343 /// is also 'int*'.
1344 ///
1345 /// Non-canonical types are useful for emitting diagnostics, without losing
1346 /// information about typedefs being used. Canonical types are useful for type
1347 /// comparisons (they allow by-pointer equality tests) and useful for reasoning
1348 /// about whether something has a particular form (e.g. is a function type),
1349 /// because they implicitly, recursively, strip all typedefs out of a type.
1350 ///
1351 /// Types, once created, are immutable.
1352 ///
1354 public:
1355  enum TypeClass {
1356 #define TYPE(Class, Base) Class,
1357 #define LAST_TYPE(Class) TypeLast = Class,
1358 #define ABSTRACT_TYPE(Class, Base)
1359 #include "clang/AST/TypeNodes.def"
1360  TagFirst = Record, TagLast = Enum
1361  };
1362 
1363 private:
1364  /// Bitfields required by the Type class.
1365  class TypeBitfields {
1366  friend class Type;
1367  template <class T> friend class TypePropertyCache;
1368 
1369  /// TypeClass bitfield - Enum that specifies what subclass this belongs to.
1370  unsigned TC : 8;
1371 
1372  /// Whether this type is a dependent type (C++ [temp.dep.type]).
1373  unsigned Dependent : 1;
1374 
1375  /// Whether this type somehow involves a template parameter, even
1376  /// if the resolution of the type does not depend on a template parameter.
1377  unsigned InstantiationDependent : 1;
1378 
1379  /// Whether this type is a variably-modified type (C99 6.7.5).
1380  unsigned VariablyModified : 1;
1381 
1382  /// \brief Whether this type contains an unexpanded parameter pack
1383  /// (for C++11 variadic templates).
1384  unsigned ContainsUnexpandedParameterPack : 1;
1385 
1386  /// \brief True if the cache (i.e. the bitfields here starting with
1387  /// 'Cache') is valid.
1388  mutable unsigned CacheValid : 1;
1389 
1390  /// \brief Linkage of this type.
1391  mutable unsigned CachedLinkage : 3;
1392 
1393  /// \brief Whether this type involves and local or unnamed types.
1394  mutable unsigned CachedLocalOrUnnamed : 1;
1395 
1396  /// \brief Whether this type comes from an AST file.
1397  mutable unsigned FromAST : 1;
1398 
1399  bool isCacheValid() const {
1400  return CacheValid;
1401  }
1402 
1403  Linkage getLinkage() const {
1404  assert(isCacheValid() && "getting linkage from invalid cache");
1405  return static_cast<Linkage>(CachedLinkage);
1406  }
1407 
1408  bool hasLocalOrUnnamedType() const {
1409  assert(isCacheValid() && "getting linkage from invalid cache");
1410  return CachedLocalOrUnnamed;
1411  }
1412  };
1413  enum { NumTypeBits = 18 };
1414 
1415 protected:
1416  // These classes allow subclasses to somewhat cleanly pack bitfields
1417  // into Type.
1418 
1420  friend class ArrayType;
1421 
1422  unsigned : NumTypeBits;
1423 
1424  /// CVR qualifiers from declarations like
1425  /// 'int X[static restrict 4]'. For function parameters only.
1426  unsigned IndexTypeQuals : 3;
1427 
1428  /// Storage class qualifiers from declarations like
1429  /// 'int X[static restrict 4]'. For function parameters only.
1430  /// Actually an ArrayType::ArraySizeModifier.
1431  unsigned SizeModifier : 3;
1432  };
1433 
1435  friend class BuiltinType;
1436 
1437  unsigned : NumTypeBits;
1438 
1439  /// The kind (BuiltinType::Kind) of builtin type this is.
1440  unsigned Kind : 8;
1441  };
1442 
1444  friend class FunctionProtoType;
1445  friend class FunctionType;
1446 
1447  unsigned : NumTypeBits;
1448 
1449  /// Extra information which affects how the function is called, like
1450  /// regparm and the calling convention.
1451  unsigned ExtInfo : 11;
1452 
1453  /// Used only by FunctionProtoType, put here to pack with the
1454  /// other bitfields.
1455  /// The qualifiers are part of FunctionProtoType because...
1456  ///
1457  /// C++ 8.3.5p4: The return type, the parameter type list and the
1458  /// cv-qualifier-seq, [...], are part of the function type.
1459  unsigned TypeQuals : 4;
1460 
1461  /// \brief The ref-qualifier associated with a \c FunctionProtoType.
1462  ///
1463  /// This is a value of type \c RefQualifierKind.
1464  unsigned RefQualifier : 2;
1465  };
1466 
1468  friend class ObjCObjectType;
1469 
1470  unsigned : NumTypeBits;
1471 
1472  /// The number of type arguments stored directly on this object type.
1473  unsigned NumTypeArgs : 7;
1474 
1475  /// The number of protocols stored directly on this object type.
1476  unsigned NumProtocols : 6;
1477 
1478  /// Whether this is a "kindof" type.
1479  unsigned IsKindOf : 1;
1480  };
1481 
1482  static_assert(NumTypeBits + 7 + 6 + 1 <= 32, "Does not fit in an unsigned");
1483 
1485  friend class ReferenceType;
1486 
1487  unsigned : NumTypeBits;
1488 
1489  /// True if the type was originally spelled with an lvalue sigil.
1490  /// This is never true of rvalue references but can also be false
1491  /// on lvalue references because of C++0x [dcl.typedef]p9,
1492  /// as follows:
1493  ///
1494  /// typedef int &ref; // lvalue, spelled lvalue
1495  /// typedef int &&rvref; // rvalue
1496  /// ref &a; // lvalue, inner ref, spelled lvalue
1497  /// ref &&a; // lvalue, inner ref
1498  /// rvref &a; // lvalue, inner ref, spelled lvalue
1499  /// rvref &&a; // rvalue, inner ref
1500  unsigned SpelledAsLValue : 1;
1501 
1502  /// True if the inner type is a reference type. This only happens
1503  /// in non-canonical forms.
1504  unsigned InnerRef : 1;
1505  };
1506 
1508  friend class TypeWithKeyword;
1509 
1510  unsigned : NumTypeBits;
1511 
1512  /// An ElaboratedTypeKeyword. 8 bits for efficient access.
1513  unsigned Keyword : 8;
1514  };
1515 
1517  friend class VectorType;
1518 
1519  unsigned : NumTypeBits;
1520 
1521  /// The kind of vector, either a generic vector type or some
1522  /// target-specific vector type such as for AltiVec or Neon.
1523  unsigned VecKind : 3;
1524 
1525  /// The number of elements in the vector.
1526  unsigned NumElements : 29 - NumTypeBits;
1527 
1528  enum { MaxNumElements = (1 << (29 - NumTypeBits)) - 1 };
1529  };
1530 
1532  friend class AttributedType;
1533 
1534  unsigned : NumTypeBits;
1535 
1536  /// An AttributedType::Kind
1537  unsigned AttrKind : 32 - NumTypeBits;
1538  };
1539 
1541  friend class AutoType;
1542 
1543  unsigned : NumTypeBits;
1544 
1545  /// Was this placeholder type spelled as 'auto', 'decltype(auto)',
1546  /// or '__auto_type'? AutoTypeKeyword value.
1547  unsigned Keyword : 2;
1548  };
1549 
1550  union {
1551  TypeBitfields TypeBits;
1561  };
1562 
1563 private:
1564  template <class T> friend class TypePropertyCache;
1565 
1566  /// \brief Set whether this type comes from an AST file.
1567  void setFromAST(bool V = true) const {
1568  TypeBits.FromAST = V;
1569  }
1570 
1571 protected:
1572  friend class ASTContext;
1573 
1574  Type(TypeClass tc, QualType canon, bool Dependent,
1575  bool InstantiationDependent, bool VariablyModified,
1576  bool ContainsUnexpandedParameterPack)
1577  : ExtQualsTypeCommonBase(this,
1578  canon.isNull() ? QualType(this_(), 0) : canon) {
1579  TypeBits.TC = tc;
1580  TypeBits.Dependent = Dependent;
1581  TypeBits.InstantiationDependent = Dependent || InstantiationDependent;
1582  TypeBits.VariablyModified = VariablyModified;
1583  TypeBits.ContainsUnexpandedParameterPack = ContainsUnexpandedParameterPack;
1584  TypeBits.CacheValid = false;
1585  TypeBits.CachedLocalOrUnnamed = false;
1586  TypeBits.CachedLinkage = NoLinkage;
1587  TypeBits.FromAST = false;
1588  }
1589 
1590  // silence VC++ warning C4355: 'this' : used in base member initializer list
1591  Type *this_() { return this; }
1592 
1593  void setDependent(bool D = true) {
1594  TypeBits.Dependent = D;
1595  if (D)
1596  TypeBits.InstantiationDependent = true;
1597  }
1598 
1599  void setInstantiationDependent(bool D = true) {
1600  TypeBits.InstantiationDependent = D; }
1601 
1602  void setVariablyModified(bool VM = true) { TypeBits.VariablyModified = VM; }
1603 
1604  void setContainsUnexpandedParameterPack(bool PP = true) {
1605  TypeBits.ContainsUnexpandedParameterPack = PP;
1606  }
1607 
1608 public:
1609  friend class ASTReader;
1610  friend class ASTWriter;
1611 
1612  Type(const Type &) = delete;
1613  Type &operator=(const Type &) = delete;
1614 
1615  TypeClass getTypeClass() const { return static_cast<TypeClass>(TypeBits.TC); }
1616 
1617  /// \brief Whether this type comes from an AST file.
1618  bool isFromAST() const { return TypeBits.FromAST; }
1619 
1620  /// \brief Whether this type is or contains an unexpanded parameter
1621  /// pack, used to support C++0x variadic templates.
1622  ///
1623  /// A type that contains a parameter pack shall be expanded by the
1624  /// ellipsis operator at some point. For example, the typedef in the
1625  /// following example contains an unexpanded parameter pack 'T':
1626  ///
1627  /// \code
1628  /// template<typename ...T>
1629  /// struct X {
1630  /// typedef T* pointer_types; // ill-formed; T is a parameter pack.
1631  /// };
1632  /// \endcode
1633  ///
1634  /// Note that this routine does not specify which
1636  return TypeBits.ContainsUnexpandedParameterPack;
1637  }
1638 
1639  /// Determines if this type would be canonical if it had no further
1640  /// qualification.
1641  bool isCanonicalUnqualified() const {
1642  return CanonicalType == QualType(this, 0);
1643  }
1644 
1645  /// Pull a single level of sugar off of this locally-unqualified type.
1646  /// Users should generally prefer SplitQualType::getSingleStepDesugaredType()
1647  /// or QualType::getSingleStepDesugaredType(const ASTContext&).
1648  QualType getLocallyUnqualifiedSingleStepDesugaredType() const;
1649 
1650  /// Types are partitioned into 3 broad categories (C99 6.2.5p1):
1651  /// object types, function types, and incomplete types.
1652 
1653  /// Return true if this is an incomplete type.
1654  /// A type that can describe objects, but which lacks information needed to
1655  /// determine its size (e.g. void, or a fwd declared struct). Clients of this
1656  /// routine will need to determine if the size is actually required.
1657  ///
1658  /// \brief Def If non-null, and the type refers to some kind of declaration
1659  /// that can be completed (such as a C struct, C++ class, or Objective-C
1660  /// class), will be set to the declaration.
1661  bool isIncompleteType(NamedDecl **Def = nullptr) const;
1662 
1663  /// Return true if this is an incomplete or object
1664  /// type, in other words, not a function type.
1666  return !isFunctionType();
1667  }
1668 
1669  /// \brief Determine whether this type is an object type.
1670  bool isObjectType() const {
1671  // C++ [basic.types]p8:
1672  // An object type is a (possibly cv-qualified) type that is not a
1673  // function type, not a reference type, and not a void type.
1674  return !isReferenceType() && !isFunctionType() && !isVoidType();
1675  }
1676 
1677  /// Return true if this is a literal type
1678  /// (C++11 [basic.types]p10)
1679  bool isLiteralType(const ASTContext &Ctx) const;
1680 
1681  /// Test if this type is a standard-layout type.
1682  /// (C++0x [basic.type]p9)
1683  bool isStandardLayoutType() const;
1684 
1685  /// Helper methods to distinguish type categories. All type predicates
1686  /// operate on the canonical type, ignoring typedefs and qualifiers.
1687 
1688  /// Returns true if the type is a builtin type.
1689  bool isBuiltinType() const;
1690 
1691  /// Test for a particular builtin type.
1692  bool isSpecificBuiltinType(unsigned K) const;
1693 
1694  /// Test for a type which does not represent an actual type-system type but
1695  /// is instead used as a placeholder for various convenient purposes within
1696  /// Clang. All such types are BuiltinTypes.
1697  bool isPlaceholderType() const;
1698  const BuiltinType *getAsPlaceholderType() const;
1699 
1700  /// Test for a specific placeholder type.
1701  bool isSpecificPlaceholderType(unsigned K) const;
1702 
1703  /// Test for a placeholder type other than Overload; see
1704  /// BuiltinType::isNonOverloadPlaceholderType.
1705  bool isNonOverloadPlaceholderType() const;
1706 
1707  /// isIntegerType() does *not* include complex integers (a GCC extension).
1708  /// isComplexIntegerType() can be used to test for complex integers.
1709  bool isIntegerType() const; // C99 6.2.5p17 (int, char, bool, enum)
1710  bool isEnumeralType() const;
1711  bool isBooleanType() const;
1712  bool isCharType() const;
1713  bool isWideCharType() const;
1714  bool isChar16Type() const;
1715  bool isChar32Type() const;
1716  bool isAnyCharacterType() const;
1717  bool isIntegralType(const ASTContext &Ctx) const;
1718 
1719  /// Determine whether this type is an integral or enumeration type.
1720  bool isIntegralOrEnumerationType() const;
1721 
1722  /// Determine whether this type is an integral or unscoped enumeration type.
1723  bool isIntegralOrUnscopedEnumerationType() const;
1724 
1725  /// Floating point categories.
1726  bool isRealFloatingType() const; // C99 6.2.5p10 (float, double, long double)
1727  /// isComplexType() does *not* include complex integers (a GCC extension).
1728  /// isComplexIntegerType() can be used to test for complex integers.
1729  bool isComplexType() const; // C99 6.2.5p11 (complex)
1730  bool isAnyComplexType() const; // C99 6.2.5p11 (complex) + Complex Int.
1731  bool isFloatingType() const; // C99 6.2.5p11 (real floating + complex)
1732  bool isHalfType() const; // OpenCL 6.1.1.1, NEON (IEEE 754-2008 half)
1733  bool isRealType() const; // C99 6.2.5p17 (real floating + integer)
1734  bool isArithmeticType() const; // C99 6.2.5p18 (integer + floating)
1735  bool isVoidType() const; // C99 6.2.5p19
1736  bool isScalarType() const; // C99 6.2.5p21 (arithmetic + pointers)
1737  bool isAggregateType() const;
1738  bool isFundamentalType() const;
1739  bool isCompoundType() const;
1740 
1741  // Type Predicates: Check to see if this type is structurally the specified
1742  // type, ignoring typedefs and qualifiers.
1743  bool isFunctionType() const;
1744  bool isFunctionNoProtoType() const { return getAs<FunctionNoProtoType>(); }
1745  bool isFunctionProtoType() const { return getAs<FunctionProtoType>(); }
1746  bool isPointerType() const;
1747  bool isAnyPointerType() const; // Any C pointer or ObjC object pointer
1748  bool isBlockPointerType() const;
1749  bool isVoidPointerType() const;
1750  bool isReferenceType() const;
1751  bool isLValueReferenceType() const;
1752  bool isRValueReferenceType() const;
1753  bool isFunctionPointerType() const;
1754  bool isMemberPointerType() const;
1755  bool isMemberFunctionPointerType() const;
1756  bool isMemberDataPointerType() const;
1757  bool isArrayType() const;
1758  bool isConstantArrayType() const;
1759  bool isIncompleteArrayType() const;
1760  bool isVariableArrayType() const;
1761  bool isDependentSizedArrayType() const;
1762  bool isRecordType() const;
1763  bool isClassType() const;
1764  bool isStructureType() const;
1765  bool isObjCBoxableRecordType() const;
1766  bool isInterfaceType() const;
1767  bool isStructureOrClassType() const;
1768  bool isUnionType() const;
1769  bool isComplexIntegerType() const; // GCC _Complex integer type.
1770  bool isVectorType() const; // GCC vector type.
1771  bool isExtVectorType() const; // Extended vector type.
1772  bool isDependentAddressSpaceType() const; // value-dependent address space qualifier
1773  bool isObjCObjectPointerType() const; // pointer to ObjC object
1774  bool isObjCRetainableType() const; // ObjC object or block pointer
1775  bool isObjCLifetimeType() const; // (array of)* retainable type
1776  bool isObjCIndirectLifetimeType() const; // (pointer to)* lifetime type
1777  bool isObjCNSObjectType() const; // __attribute__((NSObject))
1778  bool isObjCIndependentClassType() const; // __attribute__((objc_independent_class))
1779  // FIXME: change this to 'raw' interface type, so we can used 'interface' type
1780  // for the common case.
1781  bool isObjCObjectType() const; // NSString or typeof(*(id)0)
1782  bool isObjCQualifiedInterfaceType() const; // NSString<foo>
1783  bool isObjCQualifiedIdType() const; // id<foo>
1784  bool isObjCQualifiedClassType() const; // Class<foo>
1785  bool isObjCObjectOrInterfaceType() const;
1786  bool isObjCIdType() const; // id
1787  bool isObjCInertUnsafeUnretainedType() const;
1788 
1789  /// Whether the type is Objective-C 'id' or a __kindof type of an
1790  /// object type, e.g., __kindof NSView * or __kindof id
1791  /// <NSCopying>.
1792  ///
1793  /// \param bound Will be set to the bound on non-id subtype types,
1794  /// which will be (possibly specialized) Objective-C class type, or
1795  /// null for 'id.
1796  bool isObjCIdOrObjectKindOfType(const ASTContext &ctx,
1797  const ObjCObjectType *&bound) const;
1798 
1799  bool isObjCClassType() const; // Class
1800 
1801  /// Whether the type is Objective-C 'Class' or a __kindof type of an
1802  /// Class type, e.g., __kindof Class <NSCopying>.
1803  ///
1804  /// Unlike \c isObjCIdOrObjectKindOfType, there is no relevant bound
1805  /// here because Objective-C's type system cannot express "a class
1806  /// object for a subclass of NSFoo".
1807  bool isObjCClassOrClassKindOfType() const;
1808 
1809  bool isBlockCompatibleObjCPointerType(ASTContext &ctx) const;
1810  bool isObjCSelType() const; // Class
1811  bool isObjCBuiltinType() const; // 'id' or 'Class'
1812  bool isObjCARCBridgableType() const;
1813  bool isCARCBridgableType() const;
1814  bool isTemplateTypeParmType() const; // C++ template type parameter
1815  bool isNullPtrType() const; // C++11 std::nullptr_t
1816  bool isAlignValT() const; // C++17 std::align_val_t
1817  bool isStdByteType() const; // C++17 std::byte
1818  bool isAtomicType() const; // C11 _Atomic()
1819 
1820 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
1821  bool is##Id##Type() const;
1822 #include "clang/Basic/OpenCLImageTypes.def"
1823 
1824  bool isImageType() const; // Any OpenCL image type
1825 
1826  bool isSamplerT() const; // OpenCL sampler_t
1827  bool isEventT() const; // OpenCL event_t
1828  bool isClkEventT() const; // OpenCL clk_event_t
1829  bool isQueueT() const; // OpenCL queue_t
1830  bool isReserveIDT() const; // OpenCL reserve_id_t
1831 
1832  bool isPipeType() const; // OpenCL pipe type
1833  bool isOpenCLSpecificType() const; // Any OpenCL specific type
1834 
1835  /// Determines if this type, which must satisfy
1836  /// isObjCLifetimeType(), is implicitly __unsafe_unretained rather
1837  /// than implicitly __strong.
1838  bool isObjCARCImplicitlyUnretainedType() const;
1839 
1840  /// Return the implicit lifetime for this type, which must not be dependent.
1841  Qualifiers::ObjCLifetime getObjCARCImplicitLifetime() const;
1842 
1852  STK_FloatingComplex
1853  };
1854 
1855  /// Given that this is a scalar type, classify it.
1856  ScalarTypeKind getScalarTypeKind() const;
1857 
1858  /// Whether this type is a dependent type, meaning that its definition
1859  /// somehow depends on a template parameter (C++ [temp.dep.type]).
1860  bool isDependentType() const { return TypeBits.Dependent; }
1861 
1862  /// \brief Determine whether this type is an instantiation-dependent type,
1863  /// meaning that the type involves a template parameter (even if the
1864  /// definition does not actually depend on the type substituted for that
1865  /// template parameter).
1867  return TypeBits.InstantiationDependent;
1868  }
1869 
1870  /// \brief Determine whether this type is an undeduced type, meaning that
1871  /// it somehow involves a C++11 'auto' type or similar which has not yet been
1872  /// deduced.
1873  bool isUndeducedType() const;
1874 
1875  /// \brief Whether this type is a variably-modified type (C99 6.7.5).
1876  bool isVariablyModifiedType() const { return TypeBits.VariablyModified; }
1877 
1878  /// \brief Whether this type involves a variable-length array type
1879  /// with a definite size.
1880  bool hasSizedVLAType() const;
1881 
1882  /// \brief Whether this type is or contains a local or unnamed type.
1883  bool hasUnnamedOrLocalType() const;
1884 
1885  bool isOverloadableType() const;
1886 
1887  /// \brief Determine wither this type is a C++ elaborated-type-specifier.
1888  bool isElaboratedTypeSpecifier() const;
1889 
1890  bool canDecayToPointerType() const;
1891 
1892  /// Whether this type is represented natively as a pointer. This includes
1893  /// pointers, references, block pointers, and Objective-C interface,
1894  /// qualified id, and qualified interface types, as well as nullptr_t.
1895  bool hasPointerRepresentation() const;
1896 
1897  /// Whether this type can represent an objective pointer type for the
1898  /// purpose of GC'ability
1899  bool hasObjCPointerRepresentation() const;
1900 
1901  /// \brief Determine whether this type has an integer representation
1902  /// of some sort, e.g., it is an integer type or a vector.
1903  bool hasIntegerRepresentation() const;
1904 
1905  /// \brief Determine whether this type has an signed integer representation
1906  /// of some sort, e.g., it is an signed integer type or a vector.
1907  bool hasSignedIntegerRepresentation() const;
1908 
1909  /// \brief Determine whether this type has an unsigned integer representation
1910  /// of some sort, e.g., it is an unsigned integer type or a vector.
1911  bool hasUnsignedIntegerRepresentation() const;
1912 
1913  /// \brief Determine whether this type has a floating-point representation
1914  /// of some sort, e.g., it is a floating-point type or a vector thereof.
1915  bool hasFloatingRepresentation() const;
1916 
1917  // Type Checking Functions: Check to see if this type is structurally the
1918  // specified type, ignoring typedefs and qualifiers, and return a pointer to
1919  // the best type we can.
1920  const RecordType *getAsStructureType() const;
1921  /// NOTE: getAs*ArrayType are methods on ASTContext.
1922  const RecordType *getAsUnionType() const;
1923  const ComplexType *getAsComplexIntegerType() const; // GCC complex int type.
1924  const ObjCObjectType *getAsObjCInterfaceType() const;
1925 
1926  // The following is a convenience method that returns an ObjCObjectPointerType
1927  // for object declared using an interface.
1928  const ObjCObjectPointerType *getAsObjCInterfacePointerType() const;
1929  const ObjCObjectPointerType *getAsObjCQualifiedIdType() const;
1930  const ObjCObjectPointerType *getAsObjCQualifiedClassType() const;
1931  const ObjCObjectType *getAsObjCQualifiedInterfaceType() const;
1932 
1933  /// \brief Retrieves the CXXRecordDecl that this type refers to, either
1934  /// because the type is a RecordType or because it is the injected-class-name
1935  /// type of a class template or class template partial specialization.
1936  CXXRecordDecl *getAsCXXRecordDecl() const;
1937 
1938  /// \brief Retrieves the TagDecl that this type refers to, either
1939  /// because the type is a TagType or because it is the injected-class-name
1940  /// type of a class template or class template partial specialization.
1941  TagDecl *getAsTagDecl() const;
1942 
1943  /// If this is a pointer or reference to a RecordType, return the
1944  /// CXXRecordDecl that that type refers to.
1945  ///
1946  /// If this is not a pointer or reference, or the type being pointed to does
1947  /// not refer to a CXXRecordDecl, returns NULL.
1948  const CXXRecordDecl *getPointeeCXXRecordDecl() const;
1949 
1950  /// Get the DeducedType whose type will be deduced for a variable with
1951  /// an initializer of this type. This looks through declarators like pointer
1952  /// types, but not through decltype or typedefs.
1953  DeducedType *getContainedDeducedType() const;
1954 
1955  /// Get the AutoType whose type will be deduced for a variable with
1956  /// an initializer of this type. This looks through declarators like pointer
1957  /// types, but not through decltype or typedefs.
1959  return dyn_cast_or_null<AutoType>(getContainedDeducedType());
1960  }
1961 
1962  /// Determine whether this type was written with a leading 'auto'
1963  /// corresponding to a trailing return type (possibly for a nested
1964  /// function type within a pointer to function type or similar).
1965  bool hasAutoForTrailingReturnType() const;
1966 
1967  /// Member-template getAs<specific type>'. Look through sugar for
1968  /// an instance of <specific type>. This scheme will eventually
1969  /// replace the specific getAsXXXX methods above.
1970  ///
1971  /// There are some specializations of this member template listed
1972  /// immediately following this class.
1973  template <typename T> const T *getAs() const;
1974 
1975  /// Member-template getAsAdjusted<specific type>. Look through specific kinds
1976  /// of sugar (parens, attributes, etc) for an instance of <specific type>.
1977  /// This is used when you need to walk over sugar nodes that represent some
1978  /// kind of type adjustment from a type that was written as a <specific type>
1979  /// to another type that is still canonically a <specific type>.
1980  template <typename T> const T *getAsAdjusted() const;
1981 
1982  /// A variant of getAs<> for array types which silently discards
1983  /// qualifiers from the outermost type.
1984  const ArrayType *getAsArrayTypeUnsafe() const;
1985 
1986  /// Member-template castAs<specific type>. Look through sugar for
1987  /// the underlying instance of <specific type>.
1988  ///
1989  /// This method has the same relationship to getAs<T> as cast<T> has
1990  /// to dyn_cast<T>; which is to say, the underlying type *must*
1991  /// have the intended type, and this method will never return null.
1992  template <typename T> const T *castAs() const;
1993 
1994  /// A variant of castAs<> for array type which silently discards
1995  /// qualifiers from the outermost type.
1996  const ArrayType *castAsArrayTypeUnsafe() const;
1997 
1998  /// Get the base element type of this type, potentially discarding type
1999  /// qualifiers. This should never be used when type qualifiers
2000  /// are meaningful.
2001  const Type *getBaseElementTypeUnsafe() const;
2002 
2003  /// If this is an array type, return the element type of the array,
2004  /// potentially with type qualifiers missing.
2005  /// This should never be used when type qualifiers are meaningful.
2006  const Type *getArrayElementTypeNoTypeQual() const;
2007 
2008  /// If this is a pointer type, return the pointee type.
2009  /// If this is an array type, return the array element type.
2010  /// This should never be used when type qualifiers are meaningful.
2011  const Type *getPointeeOrArrayElementType() const;
2012 
2013  /// If this is a pointer, ObjC object pointer, or block
2014  /// pointer, this returns the respective pointee.
2015  QualType getPointeeType() const;
2016 
2017  /// Return the specified type with any "sugar" removed from the type,
2018  /// removing any typedefs, typeofs, etc., as well as any qualifiers.
2019  const Type *getUnqualifiedDesugaredType() const;
2020 
2021  /// More type predicates useful for type checking/promotion
2022  bool isPromotableIntegerType() const; // C99 6.3.1.1p2
2023 
2024  /// Return true if this is an integer type that is
2025  /// signed, according to C99 6.2.5p4 [char, signed char, short, int, long..],
2026  /// or an enum decl which has a signed representation.
2027  bool isSignedIntegerType() const;
2028 
2029  /// Return true if this is an integer type that is
2030  /// unsigned, according to C99 6.2.5p6 [which returns true for _Bool],
2031  /// or an enum decl which has an unsigned representation.
2032  bool isUnsignedIntegerType() const;
2033 
2034  /// Determines whether this is an integer type that is signed or an
2035  /// enumeration types whose underlying type is a signed integer type.
2036  bool isSignedIntegerOrEnumerationType() const;
2037 
2038  /// Determines whether this is an integer type that is unsigned or an
2039  /// enumeration types whose underlying type is a unsigned integer type.
2040  bool isUnsignedIntegerOrEnumerationType() const;
2041 
2042  /// Return true if this is not a variable sized type,
2043  /// according to the rules of C99 6.7.5p3. It is not legal to call this on
2044  /// incomplete types.
2045  bool isConstantSizeType() const;
2046 
2047  /// Returns true if this type can be represented by some
2048  /// set of type specifiers.
2049  bool isSpecifierType() const;
2050 
2051  /// Determine the linkage of this type.
2052  Linkage getLinkage() const;
2053 
2054  /// Determine the visibility of this type.
2056  return getLinkageAndVisibility().getVisibility();
2057  }
2058 
2059  /// Return true if the visibility was explicitly set is the code.
2060  bool isVisibilityExplicit() const {
2061  return getLinkageAndVisibility().isVisibilityExplicit();
2062  }
2063 
2064  /// Determine the linkage and visibility of this type.
2065  LinkageInfo getLinkageAndVisibility() const;
2066 
2067  /// True if the computed linkage is valid. Used for consistency
2068  /// checking. Should always return true.
2069  bool isLinkageValid() const;
2070 
2071  /// Determine the nullability of the given type.
2072  ///
2073  /// Note that nullability is only captured as sugar within the type
2074  /// system, not as part of the canonical type, so nullability will
2075  /// be lost by canonicalization and desugaring.
2076  Optional<NullabilityKind> getNullability(const ASTContext &context) const;
2077 
2078  /// Determine whether the given type can have a nullability
2079  /// specifier applied to it, i.e., if it is any kind of pointer type.
2080  ///
2081  /// \param ResultIfUnknown The value to return if we don't yet know whether
2082  /// this type can have nullability because it is dependent.
2083  bool canHaveNullability(bool ResultIfUnknown = true) const;
2084 
2085  /// Retrieve the set of substitutions required when accessing a member
2086  /// of the Objective-C receiver type that is declared in the given context.
2087  ///
2088  /// \c *this is the type of the object we're operating on, e.g., the
2089  /// receiver for a message send or the base of a property access, and is
2090  /// expected to be of some object or object pointer type.
2091  ///
2092  /// \param dc The declaration context for which we are building up a
2093  /// substitution mapping, which should be an Objective-C class, extension,
2094  /// category, or method within.
2095  ///
2096  /// \returns an array of type arguments that can be substituted for
2097  /// the type parameters of the given declaration context in any type described
2098  /// within that context, or an empty optional to indicate that no
2099  /// substitution is required.
2101  getObjCSubstitutions(const DeclContext *dc) const;
2102 
2103  /// Determines if this is an ObjC interface type that may accept type
2104  /// parameters.
2105  bool acceptsObjCTypeParams() const;
2106 
2107  const char *getTypeClassName() const;
2108 
2110  return CanonicalType;
2111  }
2112 
2113  CanQualType getCanonicalTypeUnqualified() const; // in CanonicalType.h
2114  void dump() const;
2115  void dump(llvm::raw_ostream &OS) const;
2116 };
2117 
2118 /// \brief This will check for a TypedefType by removing any existing sugar
2119 /// until it reaches a TypedefType or a non-sugared type.
2120 template <> const TypedefType *Type::getAs() const;
2121 
2122 /// \brief This will check for a TemplateSpecializationType by removing any
2123 /// existing sugar until it reaches a TemplateSpecializationType or a
2124 /// non-sugared type.
2125 template <> const TemplateSpecializationType *Type::getAs() const;
2126 
2127 /// \brief This will check for an AttributedType by removing any existing sugar
2128 /// until it reaches an AttributedType or a non-sugared type.
2129 template <> const AttributedType *Type::getAs() const;
2130 
2131 // We can do canonical leaf types faster, because we don't have to
2132 // worry about preserving child type decoration.
2133 #define TYPE(Class, Base)
2134 #define LEAF_TYPE(Class) \
2135 template <> inline const Class##Type *Type::getAs() const { \
2136  return dyn_cast<Class##Type>(CanonicalType); \
2137 } \
2138 template <> inline const Class##Type *Type::castAs() const { \
2139  return cast<Class##Type>(CanonicalType); \
2140 }
2141 #include "clang/AST/TypeNodes.def"
2142 
2143 /// This class is used for builtin types like 'int'. Builtin
2144 /// types are always canonical and have a literal name field.
2145 class BuiltinType : public Type {
2146 public:
2147  enum Kind {
2148 // OpenCL image types
2149 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) Id,
2150 #include "clang/Basic/OpenCLImageTypes.def"
2151 // All other builtin types
2152 #define BUILTIN_TYPE(Id, SingletonId) Id,
2153 #define LAST_BUILTIN_TYPE(Id) LastKind = Id
2154 #include "clang/AST/BuiltinTypes.def"
2155  };
2156 
2157 public:
2159  : Type(Builtin, QualType(), /*Dependent=*/(K == Dependent),
2160  /*InstantiationDependent=*/(K == Dependent),
2161  /*VariablyModified=*/false,
2162  /*Unexpanded parameter pack=*/false) {
2163  BuiltinTypeBits.Kind = K;
2164  }
2165 
2166  Kind getKind() const { return static_cast<Kind>(BuiltinTypeBits.Kind); }
2167  StringRef getName(const PrintingPolicy &Policy) const;
2168 
2169  const char *getNameAsCString(const PrintingPolicy &Policy) const {
2170  // The StringRef is null-terminated.
2171  StringRef str = getName(Policy);
2172  assert(!str.empty() && str.data()[str.size()] == '\0');
2173  return str.data();
2174  }
2175 
2176  bool isSugared() const { return false; }
2177  QualType desugar() const { return QualType(this, 0); }
2178 
2179  bool isInteger() const {
2180  return getKind() >= Bool && getKind() <= Int128;
2181  }
2182 
2183  bool isSignedInteger() const {
2184  return getKind() >= Char_S && getKind() <= Int128;
2185  }
2186 
2187  bool isUnsignedInteger() const {
2188  return getKind() >= Bool && getKind() <= UInt128;
2189  }
2190 
2191  bool isFloatingPoint() const {
2192  return getKind() >= Half && getKind() <= Float128;
2193  }
2194 
2195  /// Determines whether the given kind corresponds to a placeholder type.
2196  static bool isPlaceholderTypeKind(Kind K) {
2197  return K >= Overload;
2198  }
2199 
2200  /// Determines whether this type is a placeholder type, i.e. a type
2201  /// which cannot appear in arbitrary positions in a fully-formed
2202  /// expression.
2203  bool isPlaceholderType() const {
2204  return isPlaceholderTypeKind(getKind());
2205  }
2206 
2207  /// Determines whether this type is a placeholder type other than
2208  /// Overload. Most placeholder types require only syntactic
2209  /// information about their context in order to be resolved (e.g.
2210  /// whether it is a call expression), which means they can (and
2211  /// should) be resolved in an earlier "phase" of analysis.
2212  /// Overload expressions sometimes pick up further information
2213  /// from their context, like whether the context expects a
2214  /// specific function-pointer type, and so frequently need
2215  /// special treatment.
2217  return getKind() > Overload;
2218  }
2219 
2220  static bool classof(const Type *T) { return T->getTypeClass() == Builtin; }
2221 };
2222 
2223 /// Complex values, per C99 6.2.5p11. This supports the C99 complex
2224 /// types (_Complex float etc) as well as the GCC integer complex extensions.
2225 class ComplexType : public Type, public llvm::FoldingSetNode {
2226  friend class ASTContext; // ASTContext creates these.
2227 
2228  QualType ElementType;
2229 
2230  ComplexType(QualType Element, QualType CanonicalPtr)
2231  : Type(Complex, CanonicalPtr, Element->isDependentType(),
2232  Element->isInstantiationDependentType(),
2233  Element->isVariablyModifiedType(),
2234  Element->containsUnexpandedParameterPack()),
2235  ElementType(Element) {}
2236 
2237 public:
2238  QualType getElementType() const { return ElementType; }
2239 
2240  bool isSugared() const { return false; }
2241  QualType desugar() const { return QualType(this, 0); }
2242 
2243  void Profile(llvm::FoldingSetNodeID &ID) {
2244  Profile(ID, getElementType());
2245  }
2246 
2247  static void Profile(llvm::FoldingSetNodeID &ID, QualType Element) {
2248  ID.AddPointer(Element.getAsOpaquePtr());
2249  }
2250 
2251  static bool classof(const Type *T) { return T->getTypeClass() == Complex; }
2252 };
2253 
2254 /// Sugar for parentheses used when specifying types.
2255 class ParenType : public Type, public llvm::FoldingSetNode {
2256  friend class ASTContext; // ASTContext creates these.
2257 
2258  QualType Inner;
2259 
2260  ParenType(QualType InnerType, QualType CanonType)
2261  : Type(Paren, CanonType, InnerType->isDependentType(),
2262  InnerType->isInstantiationDependentType(),
2263  InnerType->isVariablyModifiedType(),
2264  InnerType->containsUnexpandedParameterPack()),
2265  Inner(InnerType) {}
2266 
2267 public:
2268  QualType getInnerType() const { return Inner; }
2269 
2270  bool isSugared() const { return true; }
2271  QualType desugar() const { return getInnerType(); }
2272 
2273  void Profile(llvm::FoldingSetNodeID &ID) {
2274  Profile(ID, getInnerType());
2275  }
2276 
2277  static void Profile(llvm::FoldingSetNodeID &ID, QualType Inner) {
2278  Inner.Profile(ID);
2279  }
2280 
2281  static bool classof(const Type *T) { return T->getTypeClass() == Paren; }
2282 };
2283 
2284 /// PointerType - C99 6.7.5.1 - Pointer Declarators.
2285 class PointerType : public Type, public llvm::FoldingSetNode {
2286  friend class ASTContext; // ASTContext creates these.
2287 
2288  QualType PointeeType;
2289 
2290  PointerType(QualType Pointee, QualType CanonicalPtr)
2291  : Type(Pointer, CanonicalPtr, Pointee->isDependentType(),
2292  Pointee->isInstantiationDependentType(),
2293  Pointee->isVariablyModifiedType(),
2294  Pointee->containsUnexpandedParameterPack()),
2295  PointeeType(Pointee) {}
2296 
2297 public:
2298  QualType getPointeeType() const { return PointeeType; }
2299 
2300  /// Returns true if address spaces of pointers overlap.
2301  /// OpenCL v2.0 defines conversion rules for pointers to different
2302  /// address spaces (OpenCLC v2.0 s6.5.5) and notion of overlapping
2303  /// address spaces.
2304  /// CL1.1 or CL1.2:
2305  /// address spaces overlap iff they are they same.
2306  /// CL2.0 adds:
2307  /// __generic overlaps with any address space except for __constant.
2308  bool isAddressSpaceOverlapping(const PointerType &other) const {
2309  Qualifiers thisQuals = PointeeType.getQualifiers();
2310  Qualifiers otherQuals = other.getPointeeType().getQualifiers();
2311  // Address spaces overlap if at least one of them is a superset of another
2312  return thisQuals.isAddressSpaceSupersetOf(otherQuals) ||
2313  otherQuals.isAddressSpaceSupersetOf(thisQuals);
2314  }
2315 
2316  bool isSugared() const { return false; }
2317  QualType desugar() const { return QualType(this, 0); }
2318 
2319  void Profile(llvm::FoldingSetNodeID &ID) {
2320  Profile(ID, getPointeeType());
2321  }
2322 
2323  static void Profile(llvm::FoldingSetNodeID &ID, QualType Pointee) {
2324  ID.AddPointer(Pointee.getAsOpaquePtr());
2325  }
2326 
2327  static bool classof(const Type *T) { return T->getTypeClass() == Pointer; }
2328 };
2329 
2330 /// Represents a type which was implicitly adjusted by the semantic
2331 /// engine for arbitrary reasons. For example, array and function types can
2332 /// decay, and function types can have their calling conventions adjusted.
2333 class AdjustedType : public Type, public llvm::FoldingSetNode {
2334  QualType OriginalTy;
2335  QualType AdjustedTy;
2336 
2337 protected:
2338  friend class ASTContext; // ASTContext creates these.
2339 
2340  AdjustedType(TypeClass TC, QualType OriginalTy, QualType AdjustedTy,
2341  QualType CanonicalPtr)
2342  : Type(TC, CanonicalPtr, OriginalTy->isDependentType(),
2343  OriginalTy->isInstantiationDependentType(),
2344  OriginalTy->isVariablyModifiedType(),
2345  OriginalTy->containsUnexpandedParameterPack()),
2346  OriginalTy(OriginalTy), AdjustedTy(AdjustedTy) {}
2347 
2348 public:
2349  QualType getOriginalType() const { return OriginalTy; }
2350  QualType getAdjustedType() const { return AdjustedTy; }
2351 
2352  bool isSugared() const { return true; }
2353  QualType desugar() const { return AdjustedTy; }
2354 
2355  void Profile(llvm::FoldingSetNodeID &ID) {
2356  Profile(ID, OriginalTy, AdjustedTy);
2357  }
2358 
2359  static void Profile(llvm::FoldingSetNodeID &ID, QualType Orig, QualType New) {
2360  ID.AddPointer(Orig.getAsOpaquePtr());
2361  ID.AddPointer(New.getAsOpaquePtr());
2362  }
2363 
2364  static bool classof(const Type *T) {
2365  return T->getTypeClass() == Adjusted || T->getTypeClass() == Decayed;
2366  }
2367 };
2368 
2369 /// Represents a pointer type decayed from an array or function type.
2370 class DecayedType : public AdjustedType {
2371  friend class ASTContext; // ASTContext creates these.
2372 
2373  inline
2374  DecayedType(QualType OriginalType, QualType Decayed, QualType Canonical);
2375 
2376 public:
2377  QualType getDecayedType() const { return getAdjustedType(); }
2378 
2379  inline QualType getPointeeType() const;
2380 
2381  static bool classof(const Type *T) { return T->getTypeClass() == Decayed; }
2382 };
2383 
2384 /// Pointer to a block type.
2385 /// This type is to represent types syntactically represented as
2386 /// "void (^)(int)", etc. Pointee is required to always be a function type.
2387 class BlockPointerType : public Type, public llvm::FoldingSetNode {
2388  friend class ASTContext; // ASTContext creates these.
2389 
2390  // Block is some kind of pointer type
2391  QualType PointeeType;
2392 
2393  BlockPointerType(QualType Pointee, QualType CanonicalCls)
2394  : Type(BlockPointer, CanonicalCls, Pointee->isDependentType(),
2395  Pointee->isInstantiationDependentType(),
2396  Pointee->isVariablyModifiedType(),
2397  Pointee->containsUnexpandedParameterPack()),
2398  PointeeType(Pointee) {}
2399 
2400 public:
2401  // Get the pointee type. Pointee is required to always be a function type.
2402  QualType getPointeeType() const { return PointeeType; }
2403 
2404  bool isSugared() const { return false; }
2405  QualType desugar() const { return QualType(this, 0); }
2406 
2407  void Profile(llvm::FoldingSetNodeID &ID) {
2408  Profile(ID, getPointeeType());
2409  }
2410 
2411  static void Profile(llvm::FoldingSetNodeID &ID, QualType Pointee) {
2412  ID.AddPointer(Pointee.getAsOpaquePtr());
2413  }
2414 
2415  static bool classof(const Type *T) {
2416  return T->getTypeClass() == BlockPointer;
2417  }
2418 };
2419 
2420 /// Base for LValueReferenceType and RValueReferenceType
2421 class ReferenceType : public Type, public llvm::FoldingSetNode {
2422  QualType PointeeType;
2423 
2424 protected:
2425  ReferenceType(TypeClass tc, QualType Referencee, QualType CanonicalRef,
2426  bool SpelledAsLValue)
2427  : Type(tc, CanonicalRef, Referencee->isDependentType(),
2428  Referencee->isInstantiationDependentType(),
2429  Referencee->isVariablyModifiedType(),
2430  Referencee->containsUnexpandedParameterPack()),
2431  PointeeType(Referencee) {
2432  ReferenceTypeBits.SpelledAsLValue = SpelledAsLValue;
2433  ReferenceTypeBits.InnerRef = Referencee->isReferenceType();
2434  }
2435 
2436 public:
2437  bool isSpelledAsLValue() const { return ReferenceTypeBits.SpelledAsLValue; }
2438  bool isInnerRef() const { return ReferenceTypeBits.InnerRef; }
2439 
2440  QualType getPointeeTypeAsWritten() const { return PointeeType; }
2441 
2443  // FIXME: this might strip inner qualifiers; okay?
2444  const ReferenceType *T = this;
2445  while (T->isInnerRef())
2446  T = T->PointeeType->castAs<ReferenceType>();
2447  return T->PointeeType;
2448  }
2449 
2450  void Profile(llvm::FoldingSetNodeID &ID) {
2451  Profile(ID, PointeeType, isSpelledAsLValue());
2452  }
2453 
2454  static void Profile(llvm::FoldingSetNodeID &ID,
2455  QualType Referencee,
2456  bool SpelledAsLValue) {
2457  ID.AddPointer(Referencee.getAsOpaquePtr());
2458  ID.AddBoolean(SpelledAsLValue);
2459  }
2460 
2461  static bool classof(const Type *T) {
2462  return T->getTypeClass() == LValueReference ||
2463  T->getTypeClass() == RValueReference;
2464  }
2465 };
2466 
2467 /// An lvalue reference type, per C++11 [dcl.ref].
2469  friend class ASTContext; // ASTContext creates these
2470 
2471  LValueReferenceType(QualType Referencee, QualType CanonicalRef,
2472  bool SpelledAsLValue)
2473  : ReferenceType(LValueReference, Referencee, CanonicalRef,
2474  SpelledAsLValue) {}
2475 
2476 public:
2477  bool isSugared() const { return false; }
2478  QualType desugar() const { return QualType(this, 0); }
2479 
2480  static bool classof(const Type *T) {
2481  return T->getTypeClass() == LValueReference;
2482  }
2483 };
2484 
2485 /// An rvalue reference type, per C++11 [dcl.ref].
2487  friend class ASTContext; // ASTContext creates these
2488 
2489  RValueReferenceType(QualType Referencee, QualType CanonicalRef)
2490  : ReferenceType(RValueReference, Referencee, CanonicalRef, false) {}
2491 
2492 public:
2493  bool isSugared() const { return false; }
2494  QualType desugar() const { return QualType(this, 0); }
2495 
2496  static bool classof(const Type *T) {
2497  return T->getTypeClass() == RValueReference;
2498  }
2499 };
2500 
2501 /// A pointer to member type per C++ 8.3.3 - Pointers to members.
2502 ///
2503 /// This includes both pointers to data members and pointer to member functions.
2504 class MemberPointerType : public Type, public llvm::FoldingSetNode {
2505  friend class ASTContext; // ASTContext creates these.
2506 
2507  QualType PointeeType;
2508 
2509  /// The class of which the pointee is a member. Must ultimately be a
2510  /// RecordType, but could be a typedef or a template parameter too.
2511  const Type *Class;
2512 
2513  MemberPointerType(QualType Pointee, const Type *Cls, QualType CanonicalPtr)
2514  : Type(MemberPointer, CanonicalPtr,
2515  Cls->isDependentType() || Pointee->isDependentType(),
2516  (Cls->isInstantiationDependentType() ||
2517  Pointee->isInstantiationDependentType()),
2518  Pointee->isVariablyModifiedType(),
2519  (Cls->containsUnexpandedParameterPack() ||
2520  Pointee->containsUnexpandedParameterPack())),
2521  PointeeType(Pointee), Class(Cls) {}
2522 
2523 public:
2524  QualType getPointeeType() const { return PointeeType; }
2525 
2526  /// Returns true if the member type (i.e. the pointee type) is a
2527  /// function type rather than a data-member type.
2529  return PointeeType->isFunctionProtoType();
2530  }
2531 
2532  /// Returns true if the member type (i.e. the pointee type) is a
2533  /// data type rather than a function type.
2534  bool isMemberDataPointer() const {
2535  return !PointeeType->isFunctionProtoType();
2536  }
2537 
2538  const Type *getClass() const { return Class; }
2539  CXXRecordDecl *getMostRecentCXXRecordDecl() const;
2540 
2541  bool isSugared() const { return false; }
2542  QualType desugar() const { return QualType(this, 0); }
2543 
2544  void Profile(llvm::FoldingSetNodeID &ID) {
2545  Profile(ID, getPointeeType(), getClass());
2546  }
2547 
2548  static void Profile(llvm::FoldingSetNodeID &ID, QualType Pointee,
2549  const Type *Class) {
2550  ID.AddPointer(Pointee.getAsOpaquePtr());
2551  ID.AddPointer(Class);
2552  }
2553 
2554  static bool classof(const Type *T) {
2555  return T->getTypeClass() == MemberPointer;
2556  }
2557 };
2558 
2559 /// Represents an array type, per C99 6.7.5.2 - Array Declarators.
2560 class ArrayType : public Type, public llvm::FoldingSetNode {
2561 public:
2562  /// Capture whether this is a normal array (e.g. int X[4])
2563  /// an array with a static size (e.g. int X[static 4]), or an array
2564  /// with a star size (e.g. int X[*]).
2565  /// 'static' is only allowed on function parameters.
2567  Normal, Static, Star
2568  };
2569 
2570 private:
2571  /// The element type of the array.
2572  QualType ElementType;
2573 
2574 protected:
2575  friend class ASTContext; // ASTContext creates these.
2576 
2577  // C++ [temp.dep.type]p1:
2578  // A type is dependent if it is...
2579  // - an array type constructed from any dependent type or whose
2580  // size is specified by a constant expression that is
2581  // value-dependent,
2583  ArraySizeModifier sm, unsigned tq,
2584  bool ContainsUnexpandedParameterPack)
2585  : Type(tc, can, et->isDependentType() || tc == DependentSizedArray,
2586  et->isInstantiationDependentType() || tc == DependentSizedArray,
2587  (tc == VariableArray || et->isVariablyModifiedType()),
2588  ContainsUnexpandedParameterPack),
2589  ElementType(et) {
2590  ArrayTypeBits.IndexTypeQuals = tq;
2591  ArrayTypeBits.SizeModifier = sm;
2592  }
2593 
2594 public:
2595  QualType getElementType() const { return ElementType; }
2596 
2598  return ArraySizeModifier(ArrayTypeBits.SizeModifier);
2599  }
2600 
2602  return Qualifiers::fromCVRMask(getIndexTypeCVRQualifiers());
2603  }
2604 
2605  unsigned getIndexTypeCVRQualifiers() const {
2606  return ArrayTypeBits.IndexTypeQuals;
2607  }
2608 
2609  static bool classof(const Type *T) {
2610  return T->getTypeClass() == ConstantArray ||
2611  T->getTypeClass() == VariableArray ||
2612  T->getTypeClass() == IncompleteArray ||
2613  T->getTypeClass() == DependentSizedArray;
2614  }
2615 };
2616 
2617 /// Represents the canonical version of C arrays with a specified constant size.
2618 /// For example, the canonical type for 'int A[4 + 4*100]' is a
2619 /// ConstantArrayType where the element type is 'int' and the size is 404.
2621  llvm::APInt Size; // Allows us to unique the type.
2622 
2623  ConstantArrayType(QualType et, QualType can, const llvm::APInt &size,
2624  ArraySizeModifier sm, unsigned tq)
2625  : ArrayType(ConstantArray, et, can, sm, tq,
2627  Size(size) {}
2628 
2629 protected:
2630  friend class ASTContext; // ASTContext creates these.
2631 
2633  const llvm::APInt &size, ArraySizeModifier sm, unsigned tq)
2634  : ArrayType(tc, et, can, sm, tq, et->containsUnexpandedParameterPack()),
2635  Size(size) {}
2636 
2637 public:
2638  const llvm::APInt &getSize() const { return Size; }
2639  bool isSugared() const { return false; }
2640  QualType desugar() const { return QualType(this, 0); }
2641 
2642  /// \brief Determine the number of bits required to address a member of
2643  // an array with the given element type and number of elements.
2644  static unsigned getNumAddressingBits(const ASTContext &Context,
2645  QualType ElementType,
2646  const llvm::APInt &NumElements);
2647 
2648  /// \brief Determine the maximum number of active bits that an array's size
2649  /// can require, which limits the maximum size of the array.
2650  static unsigned getMaxSizeBits(const ASTContext &Context);
2651 
2652  void Profile(llvm::FoldingSetNodeID &ID) {
2653  Profile(ID, getElementType(), getSize(),
2654  getSizeModifier(), getIndexTypeCVRQualifiers());
2655  }
2656 
2657  static void Profile(llvm::FoldingSetNodeID &ID, QualType ET,
2658  const llvm::APInt &ArraySize, ArraySizeModifier SizeMod,
2659  unsigned TypeQuals) {
2660  ID.AddPointer(ET.getAsOpaquePtr());
2661  ID.AddInteger(ArraySize.getZExtValue());
2662  ID.AddInteger(SizeMod);
2663  ID.AddInteger(TypeQuals);
2664  }
2665 
2666  static bool classof(const Type *T) {
2667  return T->getTypeClass() == ConstantArray;
2668  }
2669 };
2670 
2671 /// Represents a C array with an unspecified size. For example 'int A[]' has
2672 /// an IncompleteArrayType where the element type is 'int' and the size is
2673 /// unspecified.
2675  friend class ASTContext; // ASTContext creates these.
2676 
2678  ArraySizeModifier sm, unsigned tq)
2679  : ArrayType(IncompleteArray, et, can, sm, tq,
2680  et->containsUnexpandedParameterPack()) {}
2681 
2682 public:
2683  friend class StmtIteratorBase;
2684 
2685  bool isSugared() const { return false; }
2686  QualType desugar() const { return QualType(this, 0); }
2687 
2688  static bool classof(const Type *T) {
2689  return T->getTypeClass() == IncompleteArray;
2690  }
2691 
2692  void Profile(llvm::FoldingSetNodeID &ID) {
2693  Profile(ID, getElementType(), getSizeModifier(),
2694  getIndexTypeCVRQualifiers());
2695  }
2696 
2697  static void Profile(llvm::FoldingSetNodeID &ID, QualType ET,
2698  ArraySizeModifier SizeMod, unsigned TypeQuals) {
2699  ID.AddPointer(ET.getAsOpaquePtr());
2700  ID.AddInteger(SizeMod);
2701  ID.AddInteger(TypeQuals);
2702  }
2703 };
2704 
2705 /// Represents a C array with a specified size that is not an
2706 /// integer-constant-expression. For example, 'int s[x+foo()]'.
2707 /// Since the size expression is an arbitrary expression, we store it as such.
2708 ///
2709 /// Note: VariableArrayType's aren't uniqued (since the expressions aren't) and
2710 /// should not be: two lexically equivalent variable array types could mean
2711 /// different things, for example, these variables do not have the same type
2712 /// dynamically:
2713 ///
2714 /// void foo(int x) {
2715 /// int Y[x];
2716 /// ++x;
2717 /// int Z[x];
2718 /// }
2720  friend class ASTContext; // ASTContext creates these.
2721 
2722  /// An assignment-expression. VLA's are only permitted within
2723  /// a function block.
2724  Stmt *SizeExpr;
2725 
2726  /// The range spanned by the left and right array brackets.
2727  SourceRange Brackets;
2728 
2730  ArraySizeModifier sm, unsigned tq,
2731  SourceRange brackets)
2732  : ArrayType(VariableArray, et, can, sm, tq,
2733  et->containsUnexpandedParameterPack()),
2734  SizeExpr((Stmt*) e), Brackets(brackets) {}
2735 
2736 public:
2737  friend class StmtIteratorBase;
2738 
2739  Expr *getSizeExpr() const {
2740  // We use C-style casts instead of cast<> here because we do not wish
2741  // to have a dependency of Type.h on Stmt.h/Expr.h.
2742  return (Expr*) SizeExpr;
2743  }
2744 
2745  SourceRange getBracketsRange() const { return Brackets; }
2746  SourceLocation getLBracketLoc() const { return Brackets.getBegin(); }
2747  SourceLocation getRBracketLoc() const { return Brackets.getEnd(); }
2748 
2749  bool isSugared() const { return false; }
2750  QualType desugar() const { return QualType(this, 0); }
2751 
2752  static bool classof(const Type *T) {
2753  return T->getTypeClass() == VariableArray;
2754  }
2755 
2756  void Profile(llvm::FoldingSetNodeID &ID) {
2757  llvm_unreachable("Cannot unique VariableArrayTypes.");
2758  }
2759 };
2760 
2761 /// Represents an array type in C++ whose size is a value-dependent expression.
2762 ///
2763 /// For example:
2764 /// \code
2765 /// template<typename T, int Size>
2766 /// class array {
2767 /// T data[Size];
2768 /// };
2769 /// \endcode
2770 ///
2771 /// For these types, we won't actually know what the array bound is
2772 /// until template instantiation occurs, at which point this will
2773 /// become either a ConstantArrayType or a VariableArrayType.
2775  friend class ASTContext; // ASTContext creates these.
2776 
2777  const ASTContext &Context;
2778 
2779  /// \brief An assignment expression that will instantiate to the
2780  /// size of the array.
2781  ///
2782  /// The expression itself might be null, in which case the array
2783  /// type will have its size deduced from an initializer.
2784  Stmt *SizeExpr;
2785 
2786  /// The range spanned by the left and right array brackets.
2787  SourceRange Brackets;
2788 
2789  DependentSizedArrayType(const ASTContext &Context, QualType et, QualType can,
2790  Expr *e, ArraySizeModifier sm, unsigned tq,
2791  SourceRange brackets);
2792 
2793 public:
2794  friend class StmtIteratorBase;
2795 
2796  Expr *getSizeExpr() const {
2797  // We use C-style casts instead of cast<> here because we do not wish
2798  // to have a dependency of Type.h on Stmt.h/Expr.h.
2799  return (Expr*) SizeExpr;
2800  }
2801 
2802  SourceRange getBracketsRange() const { return Brackets; }
2803  SourceLocation getLBracketLoc() const { return Brackets.getBegin(); }
2804  SourceLocation getRBracketLoc() const { return Brackets.getEnd(); }
2805 
2806  bool isSugared() const { return false; }
2807  QualType desugar() const { return QualType(this, 0); }
2808 
2809  static bool classof(const Type *T) {
2810  return T->getTypeClass() == DependentSizedArray;
2811  }
2812 
2813  void Profile(llvm::FoldingSetNodeID &ID) {
2814  Profile(ID, Context, getElementType(),
2815  getSizeModifier(), getIndexTypeCVRQualifiers(), getSizeExpr());
2816  }
2817 
2818  static void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context,
2819  QualType ET, ArraySizeModifier SizeMod,
2820  unsigned TypeQuals, Expr *E);
2821 };
2822 
2823 /// Represents an extended address space qualifier where the input address space
2824 /// value is dependent. Non-dependent address spaces are not represented with a
2825 /// special Type subclass; they are stored on an ExtQuals node as part of a QualType.
2826 ///
2827 /// For example:
2828 /// \code
2829 /// template<typename T, int AddrSpace>
2830 /// class AddressSpace {
2831 /// typedef T __attribute__((address_space(AddrSpace))) type;
2832 /// }
2833 /// \endcode
2834 class DependentAddressSpaceType : public Type, public llvm::FoldingSetNode {
2835  friend class ASTContext;
2836 
2837  const ASTContext &Context;
2838  Expr *AddrSpaceExpr;
2839  QualType PointeeType;
2840  SourceLocation loc;
2841 
2842  DependentAddressSpaceType(const ASTContext &Context, QualType PointeeType,
2843  QualType can, Expr *AddrSpaceExpr,
2844  SourceLocation loc);
2845 
2846 public:
2847  Expr *getAddrSpaceExpr() const { return AddrSpaceExpr; }
2848  QualType getPointeeType() const { return PointeeType; }
2849  SourceLocation getAttributeLoc() const { return loc; }
2850 
2851  bool isSugared() const { return false; }
2852  QualType desugar() const { return QualType(this, 0); }
2853 
2854  static bool classof(const Type *T) {
2855  return T->getTypeClass() == DependentAddressSpace;
2856  }
2857 
2858  void Profile(llvm::FoldingSetNodeID &ID) {
2859  Profile(ID, Context, getPointeeType(), getAddrSpaceExpr());
2860  }
2861 
2862  static void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context,
2863  QualType PointeeType, Expr *AddrSpaceExpr);
2864 };
2865 
2866 /// Represents an extended vector type where either the type or size is
2867 /// dependent.
2868 ///
2869 /// For example:
2870 /// \code
2871 /// template<typename T, int Size>
2872 /// class vector {
2873 /// typedef T __attribute__((ext_vector_type(Size))) type;
2874 /// }
2875 /// \endcode
2876 class DependentSizedExtVectorType : public Type, public llvm::FoldingSetNode {
2877  friend class ASTContext;
2878 
2879  const ASTContext &Context;
2880  Expr *SizeExpr;
2881 
2882  /// The element type of the array.
2883  QualType ElementType;
2884 
2885  SourceLocation loc;
2886 
2887  DependentSizedExtVectorType(const ASTContext &Context, QualType ElementType,
2888  QualType can, Expr *SizeExpr, SourceLocation loc);
2889 
2890 public:
2891  Expr *getSizeExpr() const { return SizeExpr; }
2892  QualType getElementType() const { return ElementType; }
2893  SourceLocation getAttributeLoc() const { return loc; }
2894 
2895  bool isSugared() const { return false; }
2896  QualType desugar() const { return QualType(this, 0); }
2897 
2898  static bool classof(const Type *T) {
2899  return T->getTypeClass() == DependentSizedExtVector;
2900  }
2901 
2902  void Profile(llvm::FoldingSetNodeID &ID) {
2903  Profile(ID, Context, getElementType(), getSizeExpr());
2904  }
2905 
2906  static void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context,
2907  QualType ElementType, Expr *SizeExpr);
2908 };
2909 
2910 
2911 /// Represents a GCC generic vector type. This type is created using
2912 /// __attribute__((vector_size(n)), where "n" specifies the vector size in
2913 /// bytes; or from an Altivec __vector or vector declaration.
2914 /// Since the constructor takes the number of vector elements, the
2915 /// client is responsible for converting the size into the number of elements.
2916 class VectorType : public Type, public llvm::FoldingSetNode {
2917 public:
2918  enum VectorKind {
2919  /// not a target-specific vector type
2921 
2922  /// is AltiVec vector
2924 
2925  /// is AltiVec 'vector Pixel'
2927 
2928  /// is AltiVec 'vector bool ...'
2930 
2931  /// is ARM Neon vector
2933 
2934  /// is ARM Neon polynomial vector
2935  NeonPolyVector
2936  };
2937 
2938 protected:
2939  friend class ASTContext; // ASTContext creates these.
2940 
2941  /// The element type of the vector.
2943 
2944  VectorType(QualType vecType, unsigned nElements, QualType canonType,
2945  VectorKind vecKind);
2946 
2947  VectorType(TypeClass tc, QualType vecType, unsigned nElements,
2948  QualType canonType, VectorKind vecKind);
2949 
2950 public:
2951  QualType getElementType() const { return ElementType; }
2952  unsigned getNumElements() const { return VectorTypeBits.NumElements; }
2953 
2954  static bool isVectorSizeTooLarge(unsigned NumElements) {
2955  return NumElements > VectorTypeBitfields::MaxNumElements;
2956  }
2957 
2958  bool isSugared() const { return false; }
2959  QualType desugar() const { return QualType(this, 0); }
2960 
2962  return VectorKind(VectorTypeBits.VecKind);
2963  }
2964 
2965  void Profile(llvm::FoldingSetNodeID &ID) {
2966  Profile(ID, getElementType(), getNumElements(),
2967  getTypeClass(), getVectorKind());
2968  }
2969 
2970  static void Profile(llvm::FoldingSetNodeID &ID, QualType ElementType,
2971  unsigned NumElements, TypeClass TypeClass,
2972  VectorKind VecKind) {
2973  ID.AddPointer(ElementType.getAsOpaquePtr());
2974  ID.AddInteger(NumElements);
2975  ID.AddInteger(TypeClass);
2976  ID.AddInteger(VecKind);
2977  }
2978 
2979  static bool classof(const Type *T) {
2980  return T->getTypeClass() == Vector || T->getTypeClass() == ExtVector;
2981  }
2982 };
2983 
2984 /// ExtVectorType - Extended vector type. This type is created using
2985 /// __attribute__((ext_vector_type(n)), where "n" is the number of elements.
2986 /// Unlike vector_size, ext_vector_type is only allowed on typedef's. This
2987 /// class enables syntactic extensions, like Vector Components for accessing
2988 /// points (as .xyzw), colors (as .rgba), and textures (modeled after OpenGL
2989 /// Shading Language).
2990 class ExtVectorType : public VectorType {
2991  friend class ASTContext; // ASTContext creates these.
2992 
2993  ExtVectorType(QualType vecType, unsigned nElements, QualType canonType)
2994  : VectorType(ExtVector, vecType, nElements, canonType, GenericVector) {}
2995 
2996 public:
2997  static int getPointAccessorIdx(char c) {
2998  switch (c) {
2999  default: return -1;
3000  case 'x': case 'r': return 0;
3001  case 'y': case 'g': return 1;
3002  case 'z': case 'b': return 2;
3003  case 'w': case 'a': return 3;
3004  }
3005  }
3006 
3007  static int getNumericAccessorIdx(char c) {
3008  switch (c) {
3009  default: return -1;
3010  case '0': return 0;
3011  case '1': return 1;
3012  case '2': return 2;
3013  case '3': return 3;
3014  case '4': return 4;
3015  case '5': return 5;
3016  case '6': return 6;
3017  case '7': return 7;
3018  case '8': return 8;
3019  case '9': return 9;
3020  case 'A':
3021  case 'a': return 10;
3022  case 'B':
3023  case 'b': return 11;
3024  case 'C':
3025  case 'c': return 12;
3026  case 'D':
3027  case 'd': return 13;
3028  case 'E':
3029  case 'e': return 14;
3030  case 'F':
3031  case 'f': return 15;
3032  }
3033  }
3034 
3035  static int getAccessorIdx(char c, bool isNumericAccessor) {
3036  if (isNumericAccessor)
3037  return getNumericAccessorIdx(c);
3038  else
3039  return getPointAccessorIdx(c);
3040  }
3041 
3042  bool isAccessorWithinNumElements(char c, bool isNumericAccessor) const {
3043  if (int idx = getAccessorIdx(c, isNumericAccessor)+1)
3044  return unsigned(idx-1) < getNumElements();
3045  return false;
3046  }
3047 
3048  bool isSugared() const { return false; }
3049  QualType desugar() const { return QualType(this, 0); }
3050 
3051  static bool classof(const Type *T) {
3052  return T->getTypeClass() == ExtVector;
3053  }
3054 };
3055 
3056 /// FunctionType - C99 6.7.5.3 - Function Declarators. This is the common base
3057 /// class of FunctionNoProtoType and FunctionProtoType.
3058 class FunctionType : public Type {
3059  // The type returned by the function.
3060  QualType ResultType;
3061 
3062 public:
3063  /// A class which abstracts out some details necessary for
3064  /// making a call.
3065  ///
3066  /// It is not actually used directly for storing this information in
3067  /// a FunctionType, although FunctionType does currently use the
3068  /// same bit-pattern.
3069  ///
3070  // If you add a field (say Foo), other than the obvious places (both,
3071  // constructors, compile failures), what you need to update is
3072  // * Operator==
3073  // * getFoo
3074  // * withFoo
3075  // * functionType. Add Foo, getFoo.
3076  // * ASTContext::getFooType
3077  // * ASTContext::mergeFunctionTypes
3078  // * FunctionNoProtoType::Profile
3079  // * FunctionProtoType::Profile
3080  // * TypePrinter::PrintFunctionProto
3081  // * AST read and write
3082  // * Codegen
3083  class ExtInfo {
3084  friend class FunctionType;
3085 
3086  // Feel free to rearrange or add bits, but if you go over 11,
3087  // you'll need to adjust both the Bits field below and
3088  // Type::FunctionTypeBitfields.
3089 
3090  // | CC |noreturn|produces|nocallersavedregs|regparm|
3091  // |0 .. 4| 5 | 6 | 7 |8 .. 10|
3092  //
3093  // regparm is either 0 (no regparm attribute) or the regparm value+1.
3094  enum { CallConvMask = 0x1F };
3095  enum { NoReturnMask = 0x20 };
3096  enum { ProducesResultMask = 0x40 };
3097  enum { NoCallerSavedRegsMask = 0x80 };
3098  enum {
3099  RegParmMask = ~(CallConvMask | NoReturnMask | ProducesResultMask |
3100  NoCallerSavedRegsMask),
3101  RegParmOffset = 8
3102  }; // Assumed to be the last field
3103 
3104  uint16_t Bits = CC_C;
3105 
3106  ExtInfo(unsigned Bits) : Bits(static_cast<uint16_t>(Bits)) {}
3107 
3108  public:
3109  // Constructor with no defaults. Use this when you know that you
3110  // have all the elements (when reading an AST file for example).
3111  ExtInfo(bool noReturn, bool hasRegParm, unsigned regParm, CallingConv cc,
3112  bool producesResult, bool noCallerSavedRegs) {
3113  assert((!hasRegParm || regParm < 7) && "Invalid regparm value");
3114  Bits = ((unsigned)cc) | (noReturn ? NoReturnMask : 0) |
3115  (producesResult ? ProducesResultMask : 0) |
3116  (noCallerSavedRegs ? NoCallerSavedRegsMask : 0) |
3117  (hasRegParm ? ((regParm + 1) << RegParmOffset) : 0);
3118  }
3119 
3120  // Constructor with all defaults. Use when for example creating a
3121  // function known to use defaults.
3122  ExtInfo() = default;
3123 
3124  // Constructor with just the calling convention, which is an important part
3125  // of the canonical type.
3126  ExtInfo(CallingConv CC) : Bits(CC) {}
3127 
3128  bool getNoReturn() const { return Bits & NoReturnMask; }
3129  bool getProducesResult() const { return Bits & ProducesResultMask; }
3130  bool getNoCallerSavedRegs() const { return Bits & NoCallerSavedRegsMask; }
3131  bool getHasRegParm() const { return (Bits >> RegParmOffset) != 0; }
3132 
3133  unsigned getRegParm() const {
3134  unsigned RegParm = Bits >> RegParmOffset;
3135  if (RegParm > 0)
3136  --RegParm;
3137  return RegParm;
3138  }
3139 
3140  CallingConv getCC() const { return CallingConv(Bits & CallConvMask); }
3141 
3142  bool operator==(ExtInfo Other) const {
3143  return Bits == Other.Bits;
3144  }
3145  bool operator!=(ExtInfo Other) const {
3146  return Bits != Other.Bits;
3147  }
3148 
3149  // Note that we don't have setters. That is by design, use
3150  // the following with methods instead of mutating these objects.
3151 
3152  ExtInfo withNoReturn(bool noReturn) const {
3153  if (noReturn)
3154  return ExtInfo(Bits | NoReturnMask);
3155  else
3156  return ExtInfo(Bits & ~NoReturnMask);
3157  }
3158 
3159  ExtInfo withProducesResult(bool producesResult) const {
3160  if (producesResult)
3161  return ExtInfo(Bits | ProducesResultMask);
3162  else
3163  return ExtInfo(Bits & ~ProducesResultMask);
3164  }
3165 
3166  ExtInfo withNoCallerSavedRegs(bool noCallerSavedRegs) const {
3167  if (noCallerSavedRegs)
3168  return ExtInfo(Bits | NoCallerSavedRegsMask);
3169  else
3170  return ExtInfo(Bits & ~NoCallerSavedRegsMask);
3171  }
3172 
3173  ExtInfo withRegParm(unsigned RegParm) const {
3174  assert(RegParm < 7 && "Invalid regparm value");
3175  return ExtInfo((Bits & ~RegParmMask) |
3176  ((RegParm + 1) << RegParmOffset));
3177  }
3178 
3180  return ExtInfo((Bits & ~CallConvMask) | (unsigned) cc);
3181  }
3182 
3183  void Profile(llvm::FoldingSetNodeID &ID) const {
3184  ID.AddInteger(Bits);
3185  }
3186  };
3187 
3188 protected:
3190  QualType Canonical, bool Dependent,
3191  bool InstantiationDependent,
3192  bool VariablyModified, bool ContainsUnexpandedParameterPack,
3193  ExtInfo Info)
3194  : Type(tc, Canonical, Dependent, InstantiationDependent, VariablyModified,
3195  ContainsUnexpandedParameterPack),
3196  ResultType(res) {
3197  FunctionTypeBits.ExtInfo = Info.Bits;
3198  }
3199 
3200  unsigned getTypeQuals() const { return FunctionTypeBits.TypeQuals; }
3201 
3202 public:
3203  QualType getReturnType() const { return ResultType; }
3204 
3205  bool getHasRegParm() const { return getExtInfo().getHasRegParm(); }
3206  unsigned getRegParmType() const { return getExtInfo().getRegParm(); }
3207 
3208  /// Determine whether this function type includes the GNU noreturn
3209  /// attribute. The C++11 [[noreturn]] attribute does not affect the function
3210  /// type.
3211  bool getNoReturnAttr() const { return getExtInfo().getNoReturn(); }
3212 
3213  CallingConv getCallConv() const { return getExtInfo().getCC(); }
3214  ExtInfo getExtInfo() const { return ExtInfo(FunctionTypeBits.ExtInfo); }
3215  bool isConst() const { return getTypeQuals() & Qualifiers::Const; }
3216  bool isVolatile() const { return getTypeQuals() & Qualifiers::Volatile; }
3217  bool isRestrict() const { return getTypeQuals() & Qualifiers::Restrict; }
3218 
3219  /// \brief Determine the type of an expression that calls a function of
3220  /// this type.
3221  QualType getCallResultType(const ASTContext &Context) const {
3222  return getReturnType().getNonLValueExprType(Context);
3223  }
3224 
3225  static StringRef getNameForCallConv(CallingConv CC);
3226 
3227  static bool classof(const Type *T) {
3228  return T->getTypeClass() == FunctionNoProto ||
3229  T->getTypeClass() == FunctionProto;
3230  }
3231 };
3232 
3233 /// Represents a K&R-style 'int foo()' function, which has
3234 /// no information available about its arguments.
3235 class FunctionNoProtoType : public FunctionType, public llvm::FoldingSetNode {
3236  friend class ASTContext; // ASTContext creates these.
3237 
3239  : FunctionType(FunctionNoProto, Result, Canonical,
3240  /*Dependent=*/false, /*InstantiationDependent=*/false,
3241  Result->isVariablyModifiedType(),
3242  /*ContainsUnexpandedParameterPack=*/false, Info) {}
3243 
3244 public:
3245  // No additional state past what FunctionType provides.
3246 
3247  bool isSugared() const { return false; }
3248  QualType desugar() const { return QualType(this, 0); }
3249 
3250  void Profile(llvm::FoldingSetNodeID &ID) {
3251  Profile(ID, getReturnType(), getExtInfo());
3252  }
3253 
3254  static void Profile(llvm::FoldingSetNodeID &ID, QualType ResultType,
3255  ExtInfo Info) {
3256  Info.Profile(ID);
3257  ID.AddPointer(ResultType.getAsOpaquePtr());
3258  }
3259 
3260  static bool classof(const Type *T) {
3261  return T->getTypeClass() == FunctionNoProto;
3262  }
3263 };
3264 
3265 /// Represents a prototype with parameter type info, e.g.
3266 /// 'int foo(int)' or 'int foo(void)'. 'void' is represented as having no
3267 /// parameters, not as having a single void parameter. Such a type can have an
3268 /// exception specification, but this specification is not part of the canonical
3269 /// type.
3270 class FunctionProtoType : public FunctionType, public llvm::FoldingSetNode {
3271 public:
3272  /// Interesting information about a specific parameter that can't simply
3273  /// be reflected in parameter's type.
3274  ///
3275  /// It makes sense to model language features this way when there's some
3276  /// sort of parameter-specific override (such as an attribute) that
3277  /// affects how the function is called. For example, the ARC ns_consumed
3278  /// attribute changes whether a parameter is passed at +0 (the default)
3279  /// or +1 (ns_consumed). This must be reflected in the function type,
3280  /// but isn't really a change to the parameter type.
3281  ///
3282  /// One serious disadvantage of modelling language features this way is
3283  /// that they generally do not work with language features that attempt
3284  /// to destructure types. For example, template argument deduction will
3285  /// not be able to match a parameter declared as
3286  /// T (*)(U)
3287  /// against an argument of type
3288  /// void (*)(__attribute__((ns_consumed)) id)
3289  /// because the substitution of T=void, U=id into the former will
3290  /// not produce the latter.
3292  enum {
3293  ABIMask = 0x0F,
3294  IsConsumed = 0x10,
3295  HasPassObjSize = 0x20,
3296  IsNoEscape = 0x40,
3297  };
3298  unsigned char Data = 0;
3299 
3300  public:
3301  ExtParameterInfo() = default;
3302 
3303  /// Return the ABI treatment of this parameter.
3305  return ParameterABI(Data & ABIMask);
3306  }
3308  ExtParameterInfo copy = *this;
3309  copy.Data = (copy.Data & ~ABIMask) | unsigned(kind);
3310  return copy;
3311  }
3312 
3313  /// Is this parameter considered "consumed" by Objective-C ARC?
3314  /// Consumed parameters must have retainable object type.
3315  bool isConsumed() const {
3316  return (Data & IsConsumed);
3317  }
3318  ExtParameterInfo withIsConsumed(bool consumed) const {
3319  ExtParameterInfo copy = *this;
3320  if (consumed) {
3321  copy.Data |= IsConsumed;
3322  } else {
3323  copy.Data &= ~IsConsumed;
3324  }
3325  return copy;
3326  }
3327 
3328  bool hasPassObjectSize() const {
3329  return Data & HasPassObjSize;
3330  }
3332  ExtParameterInfo Copy = *this;
3333  Copy.Data |= HasPassObjSize;
3334  return Copy;
3335  }
3336 
3337  bool isNoEscape() const {
3338  return Data & IsNoEscape;
3339  }
3340 
3341  ExtParameterInfo withIsNoEscape(bool NoEscape) const {
3342  ExtParameterInfo Copy = *this;
3343  if (NoEscape)
3344  Copy.Data |= IsNoEscape;
3345  else
3346  Copy.Data &= ~IsNoEscape;
3347  return Copy;
3348  }
3349 
3350  unsigned char getOpaqueValue() const { return Data; }
3351  static ExtParameterInfo getFromOpaqueValue(unsigned char data) {
3352  ExtParameterInfo result;
3353  result.Data = data;
3354  return result;
3355  }
3356 
3358  return lhs.Data == rhs.Data;
3359  }
3361  return lhs.Data != rhs.Data;
3362  }
3363  };
3364 
3366  /// The kind of exception specification this is.
3368 
3369  /// Explicitly-specified list of exception types.
3371 
3372  /// Noexcept expression, if this is EST_ComputedNoexcept.
3373  Expr *NoexceptExpr = nullptr;
3374 
3375  /// The function whose exception specification this is, for
3376  /// EST_Unevaluated and EST_Uninstantiated.
3377  FunctionDecl *SourceDecl = nullptr;
3378 
3379  /// The function template whose exception specification this is instantiated
3380  /// from, for EST_Uninstantiated.
3381  FunctionDecl *SourceTemplate = nullptr;
3382 
3383  ExceptionSpecInfo() = default;
3384 
3386  };
3387 
3388  /// Extra information about a function prototype.
3389  struct ExtProtoInfo {
3391  bool Variadic : 1;
3393  unsigned char TypeQuals = 0;
3394  RefQualifierKind RefQualifier = RQ_None;
3396  const ExtParameterInfo *ExtParameterInfos = nullptr;
3397 
3399  : Variadic(false), HasTrailingReturn(false) {}
3400 
3402  : ExtInfo(CC), Variadic(false), HasTrailingReturn(false) {}
3403 
3405  ExtProtoInfo Result(*this);
3406  Result.ExceptionSpec = O;
3407  return Result;
3408  }
3409  };
3410 
3411 private:
3412  friend class ASTContext; // ASTContext creates these.
3413 
3414  /// \brief Determine whether there are any argument types that
3415  /// contain an unexpanded parameter pack.
3416  static bool containsAnyUnexpandedParameterPack(const QualType *ArgArray,
3417  unsigned numArgs) {
3418  for (unsigned Idx = 0; Idx < numArgs; ++Idx)
3419  if (ArgArray[Idx]->containsUnexpandedParameterPack())
3420  return true;
3421 
3422  return false;
3423  }
3424 
3426  QualType canonical, const ExtProtoInfo &epi);
3427 
3428  /// The number of parameters this function has, not counting '...'.
3429  unsigned NumParams : 15;
3430 
3431  /// The number of types in the exception spec, if any.
3432  unsigned NumExceptions : 9;
3433 
3434  /// The type of exception specification this function has.
3435  unsigned ExceptionSpecType : 4;
3436 
3437  /// Whether this function has extended parameter information.
3438  unsigned HasExtParameterInfos : 1;
3439 
3440  /// Whether the function is variadic.
3441  unsigned Variadic : 1;
3442 
3443  /// Whether this function has a trailing return type.
3444  unsigned HasTrailingReturn : 1;
3445 
3446  // ParamInfo - There is an variable size array after the class in memory that
3447  // holds the parameter types.
3448 
3449  // Exceptions - There is another variable size array after ArgInfo that
3450  // holds the exception types.
3451 
3452  // NoexceptExpr - Instead of Exceptions, there may be a single Expr* pointing
3453  // to the expression in the noexcept() specifier.
3454 
3455  // ExceptionSpecDecl, ExceptionSpecTemplate - Instead of Exceptions, there may
3456  // be a pair of FunctionDecl* pointing to the function which should be used to
3457  // instantiate this function type's exception specification, and the function
3458  // from which it should be instantiated.
3459 
3460  // ExtParameterInfos - A variable size array, following the exception
3461  // specification and of length NumParams, holding an ExtParameterInfo
3462  // for each of the parameters. This only appears if HasExtParameterInfos
3463  // is true.
3464 
3465  const ExtParameterInfo *getExtParameterInfosBuffer() const {
3466  assert(hasExtParameterInfos());
3467 
3468  // Find the end of the exception specification.
3469  const char *ptr = reinterpret_cast<const char *>(exception_begin());
3470  ptr += getExceptionSpecSize();
3471 
3472  return reinterpret_cast<const ExtParameterInfo *>(ptr);
3473  }
3474 
3475  size_t getExceptionSpecSize() const {
3476  switch (getExceptionSpecType()) {
3477  case EST_None: return 0;
3478  case EST_DynamicNone: return 0;
3479  case EST_MSAny: return 0;
3480  case EST_BasicNoexcept: return 0;
3481  case EST_Unparsed: return 0;
3482  case EST_Dynamic: return getNumExceptions() * sizeof(QualType);
3483  case EST_ComputedNoexcept: return sizeof(Expr*);
3484  case EST_Uninstantiated: return 2 * sizeof(FunctionDecl*);
3485  case EST_Unevaluated: return sizeof(FunctionDecl*);
3486  }
3487  llvm_unreachable("bad exception specification kind");
3488  }
3489 
3490 public:
3491  unsigned getNumParams() const { return NumParams; }
3492 
3493  QualType getParamType(unsigned i) const {
3494  assert(i < NumParams && "invalid parameter index");
3495  return param_type_begin()[i];
3496  }
3497 
3499  return llvm::makeArrayRef(param_type_begin(), param_type_end());
3500  }
3501 
3503  ExtProtoInfo EPI;
3504  EPI.ExtInfo = getExtInfo();
3505  EPI.Variadic = isVariadic();
3506  EPI.HasTrailingReturn = hasTrailingReturn();
3507  EPI.ExceptionSpec.Type = getExceptionSpecType();
3508  EPI.TypeQuals = static_cast<unsigned char>(getTypeQuals());
3509  EPI.RefQualifier = getRefQualifier();
3510  if (EPI.ExceptionSpec.Type == EST_Dynamic) {
3511  EPI.ExceptionSpec.Exceptions = exceptions();
3512  } else if (EPI.ExceptionSpec.Type == EST_ComputedNoexcept) {
3513  EPI.ExceptionSpec.NoexceptExpr = getNoexceptExpr();
3514  } else if (EPI.ExceptionSpec.Type == EST_Uninstantiated) {
3515  EPI.ExceptionSpec.SourceDecl = getExceptionSpecDecl();
3516  EPI.ExceptionSpec.SourceTemplate = getExceptionSpecTemplate();
3517  } else if (EPI.ExceptionSpec.Type == EST_Unevaluated) {
3518  EPI.ExceptionSpec.SourceDecl = getExceptionSpecDecl();
3519  }
3520  if (hasExtParameterInfos())
3521  EPI.ExtParameterInfos = getExtParameterInfosBuffer();
3522  return EPI;
3523  }
3524 
3525  /// Get the kind of exception specification on this function.
3527  return static_cast<ExceptionSpecificationType>(ExceptionSpecType);
3528  }
3529 
3530  /// Return whether this function has any kind of exception spec.
3531  bool hasExceptionSpec() const {
3532  return getExceptionSpecType() != EST_None;
3533  }
3534 
3535  /// Return whether this function has a dynamic (throw) exception spec.
3537  return isDynamicExceptionSpec(getExceptionSpecType());
3538  }
3539 
3540  /// Return whether this function has a noexcept exception spec.
3542  return isNoexceptExceptionSpec(getExceptionSpecType());
3543  }
3544 
3545  /// Return whether this function has a dependent exception spec.
3546  bool hasDependentExceptionSpec() const;
3547 
3548  /// Return whether this function has an instantiation-dependent exception
3549  /// spec.
3550  bool hasInstantiationDependentExceptionSpec() const;
3551 
3552  /// Result type of getNoexceptSpec().
3554  /// There is no noexcept specifier.
3556 
3557  /// The noexcept specifier has a bad expression.
3559 
3560  /// The noexcept specifier is dependent.
3562 
3563  /// The noexcept specifier evaluates to false.
3565 
3566  /// The noexcept specifier evaluates to true.
3567  NR_Nothrow
3568  };
3569 
3570  /// Get the meaning of the noexcept spec on this function, if any.
3571  NoexceptResult getNoexceptSpec(const ASTContext &Ctx) const;
3572  unsigned getNumExceptions() const { return NumExceptions; }
3573  QualType getExceptionType(unsigned i) const {
3574  assert(i < NumExceptions && "Invalid exception number!");
3575  return exception_begin()[i];
3576  }
3578  if (getExceptionSpecType() != EST_ComputedNoexcept)
3579  return nullptr;
3580  // NoexceptExpr sits where the arguments end.
3581  return *reinterpret_cast<Expr *const *>(param_type_end());
3582  }
3583 
3584  /// \brief If this function type has an exception specification which hasn't
3585  /// been determined yet (either because it has not been evaluated or because
3586  /// it has not been instantiated), this is the function whose exception
3587  /// specification is represented by this type.
3589  if (getExceptionSpecType() != EST_Uninstantiated &&
3590  getExceptionSpecType() != EST_Unevaluated)
3591  return nullptr;
3592  return reinterpret_cast<FunctionDecl *const *>(param_type_end())[0];
3593  }
3594 
3595  /// \brief If this function type has an uninstantiated exception
3596  /// specification, this is the function whose exception specification
3597  /// should be instantiated to find the exception specification for
3598  /// this type.
3600  if (getExceptionSpecType() != EST_Uninstantiated)
3601  return nullptr;
3602  return reinterpret_cast<FunctionDecl *const *>(param_type_end())[1];
3603  }
3604 
3605  /// Determine whether this function type has a non-throwing exception
3606  /// specification.
3607  CanThrowResult canThrow(const ASTContext &Ctx) const;
3608 
3609  /// Determine whether this function type has a non-throwing exception
3610  /// specification. If this depends on template arguments, returns
3611  /// \c ResultIfDependent.
3612  bool isNothrow(const ASTContext &Ctx, bool ResultIfDependent = false) const {
3613  return ResultIfDependent ? canThrow(Ctx) != CT_Can
3614  : canThrow(Ctx) == CT_Cannot;
3615  }
3616 
3617  bool isVariadic() const { return Variadic; }
3618 
3619  /// Determines whether this function prototype contains a
3620  /// parameter pack at the end.
3621  ///
3622  /// A function template whose last parameter is a parameter pack can be
3623  /// called with an arbitrary number of arguments, much like a variadic
3624  /// function.
3625  bool isTemplateVariadic() const;
3626 
3627  bool hasTrailingReturn() const { return HasTrailingReturn; }
3628 
3629  unsigned getTypeQuals() const { return FunctionType::getTypeQuals(); }
3630 
3631  /// Retrieve the ref-qualifier associated with this function type.
3633  return static_cast<RefQualifierKind>(FunctionTypeBits.RefQualifier);
3634  }
3635 
3637  using param_type_range = llvm::iterator_range<param_type_iterator>;
3638 
3640  return param_type_range(param_type_begin(), param_type_end());
3641  }
3642 
3644  return reinterpret_cast<const QualType *>(this+1);
3645  }
3646 
3648  return param_type_begin() + NumParams;
3649  }
3650 
3651  using exception_iterator = const QualType *;
3652 
3654  return llvm::makeArrayRef(exception_begin(), exception_end());
3655  }
3656 
3658  // exceptions begin where arguments end
3659  return param_type_end();
3660  }
3661 
3663  if (getExceptionSpecType() != EST_Dynamic)
3664  return exception_begin();
3665  return exception_begin() + NumExceptions;
3666  }
3667 
3668  /// Is there any interesting extra information for any of the parameters
3669  /// of this function type?
3670  bool hasExtParameterInfos() const { return HasExtParameterInfos; }
3672  assert(hasExtParameterInfos());
3673  return ArrayRef<ExtParameterInfo>(getExtParameterInfosBuffer(),
3674  getNumParams());
3675  }
3676 
3677  /// Return a pointer to the beginning of the array of extra parameter
3678  /// information, if present, or else null if none of the parameters
3679  /// carry it. This is equivalent to getExtProtoInfo().ExtParameterInfos.
3681  if (!hasExtParameterInfos())
3682  return nullptr;
3683  return getExtParameterInfosBuffer();
3684  }
3685 
3687  assert(I < getNumParams() && "parameter index out of range");
3688  if (hasExtParameterInfos())
3689  return getExtParameterInfosBuffer()[I];
3690  return ExtParameterInfo();
3691  }
3692 
3693  ParameterABI getParameterABI(unsigned I) const {
3694  assert(I < getNumParams() && "parameter index out of range");
3695  if (hasExtParameterInfos())
3696  return getExtParameterInfosBuffer()[I].getABI();
3697  return ParameterABI::Ordinary;
3698  }
3699 
3700  bool isParamConsumed(unsigned I) const {
3701  assert(I < getNumParams() && "parameter index out of range");
3702  if (hasExtParameterInfos())
3703  return getExtParameterInfosBuffer()[I].isConsumed();
3704  return false;
3705  }
3706 
3707  bool isSugared() const { return false; }
3708  QualType desugar() const { return QualType(this, 0); }
3709 
3710  void printExceptionSpecification(raw_ostream &OS,
3711  const PrintingPolicy &Policy) const;
3712 
3713  static bool classof(const Type *T) {
3714  return T->getTypeClass() == FunctionProto;
3715  }
3716 
3717  void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Ctx);
3718  static void Profile(llvm::FoldingSetNodeID &ID, QualType Result,
3719  param_type_iterator ArgTys, unsigned NumArgs,
3720  const ExtProtoInfo &EPI, const ASTContext &Context,
3721  bool Canonical);
3722 };
3723 
3724 /// \brief Represents the dependent type named by a dependently-scoped
3725 /// typename using declaration, e.g.
3726 /// using typename Base<T>::foo;
3727 ///
3728 /// Template instantiation turns these into the underlying type.
3729 class UnresolvedUsingType : public Type {
3730  friend class ASTContext; // ASTContext creates these.
3731 
3733 
3735  : Type(UnresolvedUsing, QualType(), true, true, false,
3736  /*ContainsUnexpandedParameterPack=*/false),
3737  Decl(const_cast<UnresolvedUsingTypenameDecl*>(D)) {}
3738 
3739 public:
3740  UnresolvedUsingTypenameDecl *getDecl() const { return Decl; }
3741 
3742  bool isSugared() const { return false; }
3743  QualType desugar() const { return QualType(this, 0); }
3744 
3745  static bool classof(const Type *T) {
3746  return T->getTypeClass() == UnresolvedUsing;
3747  }
3748 
3749  void Profile(llvm::FoldingSetNodeID &ID) {
3750  return Profile(ID, Decl);
3751  }
3752 
3753  static void Profile(llvm::FoldingSetNodeID &ID,
3755  ID.AddPointer(D);
3756  }
3757 };
3758 
3759 class TypedefType : public Type {
3761 
3762 protected:
3763  friend class ASTContext; // ASTContext creates these.
3764 
3766  : Type(tc, can, can->isDependentType(),
3767  can->isInstantiationDependentType(),
3768  can->isVariablyModifiedType(),
3769  /*ContainsUnexpandedParameterPack=*/false),
3770  Decl(const_cast<TypedefNameDecl*>(D)) {
3771  assert(!isa<TypedefType>(can) && "Invalid canonical type");
3772  }
3773 
3774 public:
3775  TypedefNameDecl *getDecl() const { return Decl; }
3776 
3777  bool isSugared() const { return true; }
3778  QualType desugar() const;
3779 
3780  static bool classof(const Type *T) { return T->getTypeClass() == Typedef; }
3781 };
3782 
3783 /// Represents a `typeof` (or __typeof__) expression (a GCC extension).
3784 class TypeOfExprType : public Type {
3785  Expr *TOExpr;
3786 
3787 protected:
3788  friend class ASTContext; // ASTContext creates these.
3789 
3790  TypeOfExprType(Expr *E, QualType can = QualType());
3791 
3792 public:
3793  Expr *getUnderlyingExpr() const { return TOExpr; }
3794 
3795  /// \brief Remove a single level of sugar.
3796  QualType desugar() const;
3797 
3798  /// \brief Returns whether this type directly provides sugar.
3799  bool isSugared() const;
3800 
3801  static bool classof(const Type *T) { return T->getTypeClass() == TypeOfExpr; }
3802 };
3803 
3804 /// \brief Internal representation of canonical, dependent
3805 /// `typeof(expr)` types.
3806 ///
3807 /// This class is used internally by the ASTContext to manage
3808 /// canonical, dependent types, only. Clients will only see instances
3809 /// of this class via TypeOfExprType nodes.
3811  : public TypeOfExprType, public llvm::FoldingSetNode {
3812  const ASTContext &Context;
3813 
3814 public:
3816  : TypeOfExprType(E), Context(Context) {}
3817 
3818  void Profile(llvm::FoldingSetNodeID &ID) {
3819  Profile(ID, Context, getUnderlyingExpr());
3820  }
3821 
3822  static void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context,
3823  Expr *E);
3824 };
3825 
3826 /// Represents `typeof(type)`, a GCC extension.
3827 class TypeOfType : public Type {
3828  friend class ASTContext; // ASTContext creates these.
3829 
3830  QualType TOType;
3831 
3833  : Type(TypeOf, can, T->isDependentType(),
3834  T->isInstantiationDependentType(),
3835  T->isVariablyModifiedType(),
3836  T->containsUnexpandedParameterPack()),
3837  TOType(T) {
3838  assert(!isa<TypedefType>(can) && "Invalid canonical type");
3839  }
3840 
3841 public:
3842  QualType getUnderlyingType() const { return TOType; }
3843 
3844  /// \brief Remove a single level of sugar.
3845  QualType desugar() const { return getUnderlyingType(); }
3846 
3847  /// \brief Returns whether this type directly provides sugar.
3848  bool isSugared() const { return true; }
3849 
3850  static bool classof(const Type *T) { return T->getTypeClass() == TypeOf; }
3851 };
3852 
3853 /// Represents the type `decltype(expr)` (C++11).
3854 class DecltypeType : public Type {
3855  Expr *E;
3856  QualType UnderlyingType;
3857 
3858 protected:
3859  friend class ASTContext; // ASTContext creates these.
3860 
3861  DecltypeType(Expr *E, QualType underlyingType, QualType can = QualType());
3862 
3863 public:
3864  Expr *getUnderlyingExpr() const { return E; }
3865  QualType getUnderlyingType() const { return UnderlyingType; }
3866 
3867  /// \brief Remove a single level of sugar.
3868  QualType desugar() const;
3869 
3870  /// \brief Returns whether this type directly provides sugar.
3871  bool isSugared() const;
3872 
3873  static bool classof(const Type *T) { return T->getTypeClass() == Decltype; }
3874 };
3875 
3876 /// \brief Internal representation of canonical, dependent
3877 /// decltype(expr) types.
3878 ///
3879 /// This class is used internally by the ASTContext to manage
3880 /// canonical, dependent types, only. Clients will only see instances
3881 /// of this class via DecltypeType nodes.
3882 class DependentDecltypeType : public DecltypeType, public llvm::FoldingSetNode {
3883  const ASTContext &Context;
3884 
3885 public:
3886  DependentDecltypeType(const ASTContext &Context, Expr *E);
3887 
3888  void Profile(llvm::FoldingSetNodeID &ID) {
3889  Profile(ID, Context, getUnderlyingExpr());
3890  }
3891 
3892  static void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context,
3893  Expr *E);
3894 };
3895 
3896 /// A unary type transform, which is a type constructed from another.
3897 class UnaryTransformType : public Type {
3898 public:
3899  enum UTTKind {
3900  EnumUnderlyingType
3901  };
3902 
3903 private:
3904  /// The untransformed type.
3905  QualType BaseType;
3906 
3907  /// The transformed type if not dependent, otherwise the same as BaseType.
3908  QualType UnderlyingType;
3909 
3910  UTTKind UKind;
3911 
3912 protected:
3913  friend class ASTContext;
3914 
3915  UnaryTransformType(QualType BaseTy, QualType UnderlyingTy, UTTKind UKind,
3916  QualType CanonicalTy);
3917 
3918 public:
3919  bool isSugared() const { return !isDependentType(); }
3920  QualType desugar() const { return UnderlyingType; }
3921 
3922  QualType getUnderlyingType() const { return UnderlyingType; }
3923  QualType getBaseType() const { return BaseType; }
3924 
3925  UTTKind getUTTKind() const { return UKind; }
3926 
3927  static bool classof(const Type *T) {
3928  return T->getTypeClass() == UnaryTransform;
3929  }
3930 };
3931 
3932 /// \brief Internal representation of canonical, dependent
3933 /// __underlying_type(type) types.
3934 ///
3935 /// This class is used internally by the ASTContext to manage
3936 /// canonical, dependent types, only. Clients will only see instances
3937 /// of this class via UnaryTransformType nodes.
3939  public llvm::FoldingSetNode {
3940 public:
3942  UTTKind UKind);
3943 
3944  void Profile(llvm::FoldingSetNodeID &ID) {
3945  Profile(ID, getBaseType(), getUTTKind());
3946  }
3947 
3948  static void Profile(llvm::FoldingSetNodeID &ID, QualType BaseType,
3949  UTTKind UKind) {
3950  ID.AddPointer(BaseType.getAsOpaquePtr());
3951  ID.AddInteger((unsigned)UKind);
3952  }
3953 };
3954 
3955 class TagType : public Type {
3956  friend class ASTReader;
3957 
3958  /// Stores the TagDecl associated with this type. The decl may point to any
3959  /// TagDecl that declares the entity.
3960  TagDecl *decl;
3961 
3962 protected:
3963  TagType(TypeClass TC, const TagDecl *D, QualType can);
3964 
3965 public:
3966  TagDecl *getDecl() const;
3967 
3968  /// Determines whether this type is in the process of being defined.
3969  bool isBeingDefined() const;
3970 
3971  static bool classof(const Type *T) {
3972  return T->getTypeClass() >= TagFirst && T->getTypeClass() <= TagLast;
3973  }
3974 };
3975 
3976 /// A helper class that allows the use of isa/cast/dyncast
3977 /// to detect TagType objects of structs/unions/classes.
3978 class RecordType : public TagType {
3979 protected:
3980  friend class ASTContext; // ASTContext creates these.
3981 
3982  explicit RecordType(const RecordDecl *D)
3983  : TagType(Record, reinterpret_cast<const TagDecl*>(D), QualType()) {}
3985  : TagType(TC, reinterpret_cast<const TagDecl*>(D), QualType()) {}
3986 
3987 public:
3988  RecordDecl *getDecl() const {
3989  return reinterpret_cast<RecordDecl*>(TagType::getDecl());
3990  }
3991 
3992  /// Recursively check all fields in the record for const-ness. If any field
3993  /// is declared const, return true. Otherwise, return false.
3994  bool hasConstFields() const;
3995 
3996  bool isSugared() const { return false; }
3997  QualType desugar() const { return QualType(this, 0); }
3998 
3999  static bool classof(const Type *T) { return T->getTypeClass() == Record; }
4000 };
4001 
4002 /// A helper class that allows the use of isa/cast/dyncast
4003 /// to detect TagType objects of enums.
4004 class EnumType : public TagType {
4005  friend class ASTContext; // ASTContext creates these.
4006 
4007  explicit EnumType(const EnumDecl *D)
4008  : TagType(Enum, reinterpret_cast<const TagDecl*>(D), QualType()) {}
4009 
4010 public:
4011  EnumDecl *getDecl() const {
4012  return reinterpret_cast<EnumDecl*>(TagType::getDecl());
4013  }
4014 
4015  bool isSugared() const { return false; }
4016  QualType desugar() const { return QualType(this, 0); }
4017 
4018  static bool classof(const Type *T) { return T->getTypeClass() == Enum; }
4019 };
4020 
4021 /// An attributed type is a type to which a type attribute has been applied.
4022 ///
4023 /// The "modified type" is the fully-sugared type to which the attributed
4024 /// type was applied; generally it is not canonically equivalent to the
4025 /// attributed type. The "equivalent type" is the minimally-desugared type
4026 /// which the type is canonically equivalent to.
4027 ///
4028 /// For example, in the following attributed type:
4029 /// int32_t __attribute__((vector_size(16)))
4030 /// - the modified type is the TypedefType for int32_t
4031 /// - the equivalent type is VectorType(16, int32_t)
4032 /// - the canonical type is VectorType(16, int)
4033 class AttributedType : public Type, public llvm::FoldingSetNode {
4034 public:
4035  // It is really silly to have yet another attribute-kind enum, but
4036  // clang::attr::Kind doesn't currently cover the pure type attrs.
4037  enum Kind {
4038  // Expression operand.
4044 
4045  FirstExprOperandKind = attr_address_space,
4046  LastExprOperandKind = attr_neon_polyvector_type,
4047 
4048  // Enumerated operand (string or keyword).
4053 
4054  FirstEnumOperandKind = attr_objc_gc,
4055  LastEnumOperandKind = attr_pcs_vfp,
4056 
4057  // No operand.
4082  };
4083 
4084 private:
4085  friend class ASTContext; // ASTContext creates these
4086 
4087  QualType ModifiedType;
4088  QualType EquivalentType;
4089 
4090  AttributedType(QualType canon, Kind attrKind, QualType modified,
4091  QualType equivalent)
4092  : Type(Attributed, canon, equivalent->isDependentType(),
4093  equivalent->isInstantiationDependentType(),
4094  equivalent->isVariablyModifiedType(),
4095  equivalent->containsUnexpandedParameterPack()),
4096  ModifiedType(modified), EquivalentType(equivalent) {
4097  AttributedTypeBits.AttrKind = attrKind;
4098  }
4099 
4100 public:
4101  Kind getAttrKind() const {
4102  return static_cast<Kind>(AttributedTypeBits.AttrKind);
4103  }
4104 
4105  QualType getModifiedType() const { return ModifiedType; }
4106  QualType getEquivalentType() const { return EquivalentType; }
4107 
4108  bool isSugared() const { return true; }
4109  QualType desugar() const { return getEquivalentType(); }
4110 
4111  /// Does this attribute behave like a type qualifier?
4112  ///
4113  /// A type qualifier adjusts a type to provide specialized rules for
4114  /// a specific object, like the standard const and volatile qualifiers.
4115  /// This includes attributes controlling things like nullability,
4116  /// address spaces, and ARC ownership. The value of the object is still
4117  /// largely described by the modified type.
4118  ///
4119  /// In contrast, many type attributes "rewrite" their modified type to
4120  /// produce a fundamentally different type, not necessarily related in any
4121  /// formalizable way to the original type. For example, calling convention
4122  /// and vector attributes are not simple type qualifiers.
4123  ///
4124  /// Type qualifiers are often, but not always, reflected in the canonical
4125  /// type.
4126  bool isQualifier() const;
4127 
4128  bool isMSTypeSpec() const;
4129 
4130  bool isCallingConv() const;
4131 
4132  llvm::Optional<NullabilityKind> getImmediateNullability() const;
4133 
4134  /// Retrieve the attribute kind corresponding to the given
4135  /// nullability kind.
4137  switch (kind) {
4139  return attr_nonnull;
4140 
4142  return attr_nullable;
4143 
4145  return attr_null_unspecified;
4146  }
4147  llvm_unreachable("Unknown nullability kind.");
4148  }
4149 
4150  /// Strip off the top-level nullability annotation on the given
4151  /// type, if it's there.
4152  ///
4153  /// \param T The type to strip. If the type is exactly an
4154  /// AttributedType specifying nullability (without looking through
4155  /// type sugar), the nullability is returned and this type changed
4156  /// to the underlying modified type.
4157  ///
4158  /// \returns the top-level nullability, if present.
4159  static Optional<NullabilityKind> stripOuterNullability(QualType &T);
4160 
4161  void Profile(llvm::FoldingSetNodeID &ID) {
4162  Profile(ID, getAttrKind(), ModifiedType, EquivalentType);
4163  }
4164 
4165  static void Profile(llvm::FoldingSetNodeID &ID, Kind attrKind,
4166  QualType modified, QualType equivalent) {
4167  ID.AddInteger(attrKind);
4168  ID.AddPointer(modified.getAsOpaquePtr());
4169  ID.AddPointer(equivalent.getAsOpaquePtr());
4170  }
4171 
4172  static bool classof(const Type *T) {
4173  return T->getTypeClass() == Attributed;
4174  }
4175 };
4176 
4177 class TemplateTypeParmType : public Type, public llvm::FoldingSetNode {
4178  friend class ASTContext; // ASTContext creates these
4179 
4180  // Helper data collector for canonical types.
4181  struct CanonicalTTPTInfo {
4182  unsigned Depth : 15;
4183  unsigned ParameterPack : 1;
4184  unsigned Index : 16;
4185  };
4186 
4187  union {
4188  // Info for the canonical type.
4189  CanonicalTTPTInfo CanTTPTInfo;
4190 
4191  // Info for the non-canonical type.
4193  };
4194 
4195  /// Build a non-canonical type.
4197  : Type(TemplateTypeParm, Canon, /*Dependent=*/true,
4198  /*InstantiationDependent=*/true,
4199  /*VariablyModified=*/false,
4200  Canon->containsUnexpandedParameterPack()),
4201  TTPDecl(TTPDecl) {}
4202 
4203  /// Build the canonical type.
4204  TemplateTypeParmType(unsigned D, unsigned I, bool PP)
4205  : Type(TemplateTypeParm, QualType(this, 0),
4206  /*Dependent=*/true,
4207  /*InstantiationDependent=*/true,
4208  /*VariablyModified=*/false, PP) {
4209  CanTTPTInfo.Depth = D;
4210  CanTTPTInfo.Index = I;
4211  CanTTPTInfo.ParameterPack = PP;
4212  }
4213 
4214  const CanonicalTTPTInfo& getCanTTPTInfo() const {
4215  QualType Can = getCanonicalTypeInternal();
4216  return Can->castAs<TemplateTypeParmType>()->CanTTPTInfo;
4217  }
4218 
4219 public:
4220  unsigned getDepth() const { return getCanTTPTInfo().Depth; }
4221  unsigned getIndex() const { return getCanTTPTInfo().Index; }
4222  bool isParameterPack() const { return getCanTTPTInfo().ParameterPack; }
4223 
4225  return isCanonicalUnqualified() ? nullptr : TTPDecl;
4226  }
4227 
4228  IdentifierInfo *getIdentifier() const;
4229 
4230  bool isSugared() const { return false; }
4231  QualType desugar() const { return QualType(this, 0); }
4232 
4233  void Profile(llvm::FoldingSetNodeID &ID) {
4234  Profile(ID, getDepth(), getIndex(), isParameterPack(), getDecl());
4235  }
4236 
4237  static void Profile(llvm::FoldingSetNodeID &ID, unsigned Depth,
4238  unsigned Index, bool ParameterPack,
4239  TemplateTypeParmDecl *TTPDecl) {
4240  ID.AddInteger(Depth);
4241  ID.AddInteger(Index);
4242  ID.AddBoolean(ParameterPack);
4243  ID.AddPointer(TTPDecl);
4244  }
4245 
4246  static bool classof(const Type *T) {
4247  return T->getTypeClass() == TemplateTypeParm;
4248  }
4249 };
4250 
4251 /// \brief Represents the result of substituting a type for a template
4252 /// type parameter.
4253 ///
4254 /// Within an instantiated template, all template type parameters have
4255 /// been replaced with these. They are used solely to record that a
4256 /// type was originally written as a template type parameter;
4257 /// therefore they are never canonical.
4258 class SubstTemplateTypeParmType : public Type, public llvm::FoldingSetNode {
4259  friend class ASTContext;
4260 
4261  // The original type parameter.
4262  const TemplateTypeParmType *Replaced;
4263 
4265  : Type(SubstTemplateTypeParm, Canon, Canon->isDependentType(),
4266  Canon->isInstantiationDependentType(),
4267  Canon->isVariablyModifiedType(),
4268  Canon->containsUnexpandedParameterPack()),
4269  Replaced(Param) {}
4270 
4271 public:
4272  /// Gets the template parameter that was substituted for.
4274  return Replaced;
4275  }
4276 
4277  /// Gets the type that was substituted for the template
4278  /// parameter.
4280  return getCanonicalTypeInternal();
4281  }
4282 
4283  bool isSugared() const { return true; }
4284  QualType desugar() const { return getReplacementType(); }
4285 
4286  void Profile(llvm::FoldingSetNodeID &ID) {
4287  Profile(ID, getReplacedParameter(), getReplacementType());
4288  }
4289 
4290  static void Profile(llvm::FoldingSetNodeID &ID,
4291  const TemplateTypeParmType *Replaced,
4293  ID.AddPointer(Replaced);
4294  ID.AddPointer(Replacement.getAsOpaquePtr());
4295  }
4296 
4297  static bool classof(const Type *T) {
4298  return T->getTypeClass() == SubstTemplateTypeParm;
4299  }
4300 };
4301 
4302 /// \brief Represents the result of substituting a set of types for a template
4303 /// type parameter pack.
4304 ///
4305 /// When a pack expansion in the source code contains multiple parameter packs
4306 /// and those parameter packs correspond to different levels of template
4307 /// parameter lists, this type node is used to represent a template type
4308 /// parameter pack from an outer level, which has already had its argument pack
4309 /// substituted but that still lives within a pack expansion that itself
4310 /// could not be instantiated. When actually performing a substitution into
4311 /// that pack expansion (e.g., when all template parameters have corresponding
4312 /// arguments), this type will be replaced with the \c SubstTemplateTypeParmType
4313 /// at the current pack substitution index.
4314 class SubstTemplateTypeParmPackType : public Type, public llvm::FoldingSetNode {
4315  friend class ASTContext;
4316 
4317  /// \brief The original type parameter.
4318  const TemplateTypeParmType *Replaced;
4319 
4320  /// \brief A pointer to the set of template arguments that this
4321  /// parameter pack is instantiated with.
4322  const TemplateArgument *Arguments;
4323 
4324  /// \brief The number of template arguments in \c Arguments.
4325  unsigned NumArguments;
4326 
4328  QualType Canon,
4329  const TemplateArgument &ArgPack);
4330 
4331 public:
4332  IdentifierInfo *getIdentifier() const { return Replaced->getIdentifier(); }
4333 
4334  /// Gets the template parameter that was substituted for.
4336  return Replaced;
4337  }
4338 
4339  bool isSugared() const { return false; }
4340  QualType desugar() const { return QualType(this, 0); }
4341 
4342  TemplateArgument getArgumentPack() const;
4343 
4344  void Profile(llvm::FoldingSetNodeID &ID);
4345  static void Profile(llvm::FoldingSetNodeID &ID,
4346  const TemplateTypeParmType *Replaced,
4347  const TemplateArgument &ArgPack);
4348 
4349  static bool classof(const Type *T) {
4350  return T->getTypeClass() == SubstTemplateTypeParmPack;
4351  }
4352 };
4353 
4354 /// \brief Common base class for placeholders for types that get replaced by
4355 /// placeholder type deduction: C++11 auto, C++14 decltype(auto), C++17 deduced
4356 /// class template types, and (eventually) constrained type names from the C++
4357 /// Concepts TS.
4358 ///
4359 /// These types are usually a placeholder for a deduced type. However, before
4360 /// the initializer is attached, or (usually) if the initializer is
4361 /// type-dependent, there is no deduced type and the type is canonical. In
4362 /// the latter case, it is also a dependent type.
4363 class DeducedType : public Type {
4364 protected:
4365  DeducedType(TypeClass TC, QualType DeducedAsType, bool IsDependent,
4366  bool IsInstantiationDependent, bool ContainsParameterPack)
4367  : Type(TC,
4368  // FIXME: Retain the sugared deduced type?
4369  DeducedAsType.isNull() ? QualType(this, 0)
4370  : DeducedAsType.getCanonicalType(),
4371  IsDependent, IsInstantiationDependent,
4372  /*VariablyModified=*/false, ContainsParameterPack) {
4373  if (!DeducedAsType.isNull()) {
4374  if (DeducedAsType->isDependentType())
4375  setDependent();
4376  if (DeducedAsType->isInstantiationDependentType())
4377  setInstantiationDependent();
4378  if (DeducedAsType->containsUnexpandedParameterPack())
4379  setContainsUnexpandedParameterPack();
4380  }
4381  }
4382 
4383 public:
4384  bool isSugared() const { return !isCanonicalUnqualified(); }
4385  QualType desugar() const { return getCanonicalTypeInternal(); }
4386 
4387  /// \brief Get the type deduced for this placeholder type, or null if it's
4388  /// either not been deduced or was deduced to a dependent type.
4390  return !isCanonicalUnqualified() ? getCanonicalTypeInternal() : QualType();
4391  }
4392  bool isDeduced() const {
4393  return !isCanonicalUnqualified() || isDependentType();
4394  }
4395 
4396  static bool classof(const Type *T) {
4397  return T->getTypeClass() == Auto ||
4398  T->getTypeClass() == DeducedTemplateSpecialization;
4399  }
4400 };
4401 
4402 /// \brief Represents a C++11 auto or C++14 decltype(auto) type.
4403 class AutoType : public DeducedType, public llvm::FoldingSetNode {
4404  friend class ASTContext; // ASTContext creates these
4405 
4406  AutoType(QualType DeducedAsType, AutoTypeKeyword Keyword,
4407  bool IsDeducedAsDependent)
4408  : DeducedType(Auto, DeducedAsType, IsDeducedAsDependent,
4409  IsDeducedAsDependent, /*ContainsPack=*/false) {
4410  AutoTypeBits.Keyword = (unsigned)Keyword;
4411  }
4412 
4413 public:
4414  bool isDecltypeAuto() const {
4415  return getKeyword() == AutoTypeKeyword::DecltypeAuto;
4416  }
4417 
4419  return (AutoTypeKeyword)AutoTypeBits.Keyword;
4420  }
4421 
4422  void Profile(llvm::FoldingSetNodeID &ID) {
4423  Profile(ID, getDeducedType(), getKeyword(), isDependentType());
4424  }
4425 
4426  static void Profile(llvm::FoldingSetNodeID &ID, QualType Deduced,
4427  AutoTypeKeyword Keyword, bool IsDependent) {
4428  ID.AddPointer(Deduced.getAsOpaquePtr());
4429  ID.AddInteger((unsigned)Keyword);
4430  ID.AddBoolean(IsDependent);
4431  }
4432 
4433  static bool classof(const Type *T) {
4434  return T->getTypeClass() == Auto;
4435  }
4436 };
4437 
4438 /// \brief Represents a C++17 deduced template specialization type.
4440  public llvm::FoldingSetNode {
4441  friend class ASTContext; // ASTContext creates these
4442 
4443  /// The name of the template whose arguments will be deduced.
4444  TemplateName Template;
4445 
4447  QualType DeducedAsType,
4448  bool IsDeducedAsDependent)
4449  : DeducedType(DeducedTemplateSpecialization, DeducedAsType,
4450  IsDeducedAsDependent || Template.isDependent(),
4451  IsDeducedAsDependent || Template.isInstantiationDependent(),
4452  Template.containsUnexpandedParameterPack()),
4453  Template(Template) {}
4454 
4455 public:
4456  /// Retrieve the name of the template that we are deducing.
4457  TemplateName getTemplateName() const { return Template;}
4458 
4459  void Profile(llvm::FoldingSetNodeID &ID) {
4460  Profile(ID, getTemplateName(), getDeducedType(), isDependentType());
4461  }
4462 
4463  static void Profile(llvm::FoldingSetNodeID &ID, TemplateName Template,
4464  QualType Deduced, bool IsDependent) {
4465  Template.Profile(ID);
4466  ID.AddPointer(Deduced.getAsOpaquePtr());
4467  ID.AddBoolean(IsDependent);
4468  }
4469 
4470  static bool classof(const Type *T) {
4471  return T->getTypeClass() == DeducedTemplateSpecialization;
4472  }
4473 };
4474 
4475 /// \brief Represents a type template specialization; the template
4476 /// must be a class template, a type alias template, or a template
4477 /// template parameter. A template which cannot be resolved to one of
4478 /// these, e.g. because it is written with a dependent scope
4479 /// specifier, is instead represented as a
4480 /// @c DependentTemplateSpecializationType.
4481 ///
4482 /// A non-dependent template specialization type is always "sugar",
4483 /// typically for a \c RecordType. For example, a class template
4484 /// specialization type of \c vector<int> will refer to a tag type for
4485 /// the instantiation \c std::vector<int, std::allocator<int>>
4486 ///
4487 /// Template specializations are dependent if either the template or
4488 /// any of the template arguments are dependent, in which case the
4489 /// type may also be canonical.
4490 ///
4491 /// Instances of this type are allocated with a trailing array of
4492 /// TemplateArguments, followed by a QualType representing the
4493 /// non-canonical aliased type when the template is a type alias
4494 /// template.
4495 class LLVM_ALIGNAS(/*alignof(uint64_t)*/ 8) TemplateSpecializationType
4496  : public Type,
4497  public llvm::FoldingSetNode {
4498  friend class ASTContext; // ASTContext creates these
4499 
4500  /// The name of the template being specialized. This is
4501  /// either a TemplateName::Template (in which case it is a
4502  /// ClassTemplateDecl*, a TemplateTemplateParmDecl*, or a
4503  /// TypeAliasTemplateDecl*), a
4504  /// TemplateName::SubstTemplateTemplateParmPack, or a
4505  /// TemplateName::SubstTemplateTemplateParm (in which case the
4506  /// replacement must, recursively, be one of these).
4507  TemplateName Template;
4508 
4509  /// The number of template arguments named in this class template
4510  /// specialization.
4511  unsigned NumArgs : 31;
4512 
4513  /// Whether this template specialization type is a substituted type alias.
4514  unsigned TypeAlias : 1;
4515 
4518  QualType Canon,
4519  QualType Aliased);
4520 
4521 public:
4522  /// Determine whether any of the given template arguments are dependent.
4523  static bool anyDependentTemplateArguments(ArrayRef<TemplateArgumentLoc> Args,
4524  bool &InstantiationDependent);
4525 
4526  static bool anyDependentTemplateArguments(const TemplateArgumentListInfo &,
4527  bool &InstantiationDependent);
4528 
4529  /// True if this template specialization type matches a current
4530  /// instantiation in the context in which it is found.
4531  bool isCurrentInstantiation() const {
4532  return isa<InjectedClassNameType>(getCanonicalTypeInternal());
4533  }
4534 
4535  /// \brief Determine if this template specialization type is for a type alias
4536  /// template that has been substituted.
4537  ///
4538  /// Nearly every template specialization type whose template is an alias
4539  /// template will be substituted. However, this is not the case when
4540  /// the specialization contains a pack expansion but the template alias
4541  /// does not have a corresponding parameter pack, e.g.,
4542  ///
4543  /// \code
4544  /// template<typename T, typename U, typename V> struct S;
4545  /// template<typename T, typename U> using A = S<T, int, U>;
4546  /// template<typename... Ts> struct X {
4547  /// typedef A<Ts...> type; // not a type alias
4548  /// };
4549  /// \endcode
4550  bool isTypeAlias() const { return TypeAlias; }
4551 
4552  /// Get the aliased type, if this is a specialization of a type alias
4553  /// template.
4555  assert(isTypeAlias() && "not a type alias template specialization");
4556  return *reinterpret_cast<const QualType*>(end());
4557  }
4558 
4559  using iterator = const TemplateArgument *;
4560 
4561  iterator begin() const { return getArgs(); }
4562  iterator end() const; // defined inline in TemplateBase.h
4563 
4564  /// Retrieve the name of the template that we are specializing.
4565  TemplateName getTemplateName() const { return Template; }
4566 
4567  /// Retrieve the template arguments.
4568  const TemplateArgument *getArgs() const {
4569  return reinterpret_cast<const TemplateArgument *>(this + 1);
4570  }
4571 
4572  /// Retrieve the number of template arguments.
4573  unsigned getNumArgs() const { return NumArgs; }
4574 
4575  /// Retrieve a specific template argument as a type.
4576  /// \pre \c isArgType(Arg)
4577  const TemplateArgument &getArg(unsigned Idx) const; // in TemplateBase.h
4578 
4580  return {getArgs(), NumArgs};
4581  }
4582 
4583  bool isSugared() const {
4584  return !isDependentType() || isCurrentInstantiation() || isTypeAlias();
4585  }
4586 
4587  QualType desugar() const { return getCanonicalTypeInternal(); }
4588 
4589  void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Ctx) {
4590  Profile(ID, Template, template_arguments(), Ctx);
4591  if (isTypeAlias())
4592  getAliasedType().Profile(ID);
4593  }
4594 
4595  static void Profile(llvm::FoldingSetNodeID &ID, TemplateName T,
4597  const ASTContext &Context);
4598 
4599  static bool classof(const Type *T) {
4600  return T->getTypeClass() == TemplateSpecialization;
4601  }
4602 };
4603 
4604 /// \brief Print a template argument list, including the '<' and '>'
4605 /// enclosing the template arguments.
4606 void printTemplateArgumentList(raw_ostream &OS,
4608  const PrintingPolicy &Policy);
4609 
4610 void printTemplateArgumentList(raw_ostream &OS,
4612  const PrintingPolicy &Policy);
4613 
4614 void printTemplateArgumentList(raw_ostream &OS,
4615  const TemplateArgumentListInfo &Args,
4616  const PrintingPolicy &Policy);
4617 
4618 /// The injected class name of a C++ class template or class
4619 /// template partial specialization. Used to record that a type was
4620 /// spelled with a bare identifier rather than as a template-id; the
4621 /// equivalent for non-templated classes is just RecordType.
4622 ///
4623 /// Injected class name types are always dependent. Template
4624 /// instantiation turns these into RecordTypes.
4625 ///
4626 /// Injected class name types are always canonical. This works
4627 /// because it is impossible to compare an injected class name type
4628 /// with the corresponding non-injected template type, for the same
4629 /// reason that it is impossible to directly compare template
4630 /// parameters from different dependent contexts: injected class name
4631 /// types can only occur within the scope of a particular templated
4632 /// declaration, and within that scope every template specialization
4633 /// will canonicalize to the injected class name (when appropriate
4634 /// according to the rules of the language).
4635 class InjectedClassNameType : public Type {
4636  friend class ASTContext; // ASTContext creates these.
4637  friend class ASTNodeImporter;
4638  friend class ASTReader; // FIXME: ASTContext::getInjectedClassNameType is not
4639  // currently suitable for AST reading, too much
4640  // interdependencies.
4641 
4643 
4644  /// The template specialization which this type represents.
4645  /// For example, in
4646  /// template <class T> class A { ... };
4647  /// this is A<T>, whereas in
4648  /// template <class X, class Y> class A<B<X,Y> > { ... };
4649  /// this is A<B<X,Y> >.
4650  ///
4651  /// It is always unqualified, always a template specialization type,
4652  /// and always dependent.
4653  QualType InjectedType;
4654 
4656  : Type(InjectedClassName, QualType(), /*Dependent=*/true,
4657  /*InstantiationDependent=*/true,
4658  /*VariablyModified=*/false,
4659  /*ContainsUnexpandedParameterPack=*/false),
4660  Decl(D), InjectedType(TST) {
4661  assert(isa<TemplateSpecializationType>(TST));
4662  assert(!TST.hasQualifiers());
4663  assert(TST->isDependentType());
4664  }
4665 
4666 public:
4667  QualType getInjectedSpecializationType() const { return InjectedType; }
4668 
4670  return cast<TemplateSpecializationType>(InjectedType.getTypePtr());
4671  }
4672 
4674  return getInjectedTST()->getTemplateName();
4675  }
4676 
4677  CXXRecordDecl *getDecl() const;
4678 
4679  bool isSugared() const { return false; }
4680  QualType desugar() const { return QualType(this, 0); }
4681 
4682  static bool classof(const Type *T) {
4683  return T->getTypeClass() == InjectedClassName;
4684  }
4685 };
4686 
4687 /// \brief The kind of a tag type.
4689  /// \brief The "struct" keyword.
4691 
4692  /// \brief The "__interface" keyword.
4694 
4695  /// \brief The "union" keyword.
4697 
4698  /// \brief The "class" keyword.
4700 
4701  /// \brief The "enum" keyword.
4703 };
4704 
4705 /// \brief The elaboration keyword that precedes a qualified type name or
4706 /// introduces an elaborated-type-specifier.
4708  /// \brief The "struct" keyword introduces the elaborated-type-specifier.
4710 
4711  /// \brief The "__interface" keyword introduces the elaborated-type-specifier.
4713 
4714  /// \brief The "union" keyword introduces the elaborated-type-specifier.
4716 
4717  /// \brief The "class" keyword introduces the elaborated-type-specifier.
4719 
4720  /// \brief The "enum" keyword introduces the elaborated-type-specifier.
4722 
4723  /// \brief The "typename" keyword precedes the qualified type name, e.g.,
4724  /// \c typename T::type.
4726 
4727  /// \brief No keyword precedes the qualified type name.
4729 };
4730 
4731 /// A helper class for Type nodes having an ElaboratedTypeKeyword.
4732 /// The keyword in stored in the free bits of the base class.
4733 /// Also provides a few static helpers for converting and printing
4734 /// elaborated type keyword and tag type kind enumerations.
4735 class TypeWithKeyword : public Type {
4736 protected:
4738  QualType Canonical, bool Dependent,
4739  bool InstantiationDependent, bool VariablyModified,
4740  bool ContainsUnexpandedParameterPack)
4741  : Type(tc, Canonical, Dependent, InstantiationDependent, VariablyModified,
4742  ContainsUnexpandedParameterPack) {
4743  TypeWithKeywordBits.Keyword = Keyword;
4744  }
4745 
4746 public:
4748  return static_cast<ElaboratedTypeKeyword>(TypeWithKeywordBits.Keyword);
4749  }
4750 
4751  /// Converts a type specifier (DeclSpec::TST) into an elaborated type keyword.
4752  static ElaboratedTypeKeyword getKeywordForTypeSpec(unsigned TypeSpec);
4753 
4754  /// Converts a type specifier (DeclSpec::TST) into a tag type kind.
4755  /// It is an error to provide a type specifier which *isn't* a tag kind here.
4756  static TagTypeKind getTagTypeKindForTypeSpec(unsigned TypeSpec);
4757 
4758  /// Converts a TagTypeKind into an elaborated type keyword.
4759  static ElaboratedTypeKeyword getKeywordForTagTypeKind(TagTypeKind Tag);
4760 
4761  /// Converts an elaborated type keyword into a TagTypeKind.
4762  /// It is an error to provide an elaborated type keyword
4763  /// which *isn't* a tag kind here.
4764  static TagTypeKind getTagTypeKindForKeyword(ElaboratedTypeKeyword Keyword);
4765 
4766  static bool KeywordIsTagTypeKind(ElaboratedTypeKeyword Keyword);
4767 
4768  static StringRef getKeywordName(ElaboratedTypeKeyword Keyword);
4769 
4771  return getKeywordName(getKeywordForTagTypeKind(Kind));
4772  }
4773 
4775  static CannotCastToThisType classof(const Type *);
4776 };
4777 
4778 /// \brief Represents a type that was referred to using an elaborated type
4779 /// keyword, e.g., struct S, or via a qualified name, e.g., N::M::type,
4780 /// or both.
4781 ///
4782 /// This type is used to keep track of a type name as written in the
4783 /// source code, including tag keywords and any nested-name-specifiers.
4784 /// The type itself is always "sugar", used to express what was written
4785 /// in the source code but containing no additional semantic information.
4786 class ElaboratedType : public TypeWithKeyword, public llvm::FoldingSetNode {
4787  friend class ASTContext; // ASTContext creates these
4788 
4789  /// The nested name specifier containing the qualifier.
4790  NestedNameSpecifier *NNS;
4791 
4792  /// The type that this qualified name refers to.
4793  QualType NamedType;
4794 
4796  QualType NamedType, QualType CanonType)
4797  : TypeWithKeyword(Keyword, Elaborated, CanonType,
4798  NamedType->isDependentType(),
4799  NamedType->isInstantiationDependentType(),
4800  NamedType->isVariablyModifiedType(),
4801  NamedType->containsUnexpandedParameterPack()),
4802  NNS(NNS), NamedType(NamedType) {
4803  assert(!(Keyword == ETK_None && NNS == nullptr) &&
4804  "ElaboratedType cannot have elaborated type keyword "
4805  "and name qualifier both null.");
4806  }
4807 
4808 public:
4809  ~ElaboratedType();
4810 
4811  /// Retrieve the qualification on this type.
4812  NestedNameSpecifier *getQualifier() const { return NNS; }
4813 
4814  /// Retrieve the type named by the qualified-id.
4815  QualType getNamedType() const { return NamedType; }
4816 
4817  /// Remove a single level of sugar.
4818  QualType desugar() const { return getNamedType(); }
4819 
4820  /// Returns whether this type directly provides sugar.
4821  bool isSugared() const { return true; }
4822 
4823  void Profile(llvm::FoldingSetNodeID &ID) {
4824  Profile(ID, getKeyword(), NNS, NamedType);
4825  }
4826 
4827  static void Profile(llvm::FoldingSetNodeID &ID, ElaboratedTypeKeyword Keyword,
4828  NestedNameSpecifier *NNS, QualType NamedType) {
4829  ID.AddInteger(Keyword);
4830  ID.AddPointer(NNS);
4831  NamedType.Profile(ID);
4832  }
4833 
4834  static bool classof(const Type *T) {
4835  return T->getTypeClass() == Elaborated;
4836  }
4837 };
4838 
4839 /// \brief Represents a qualified type name for which the type name is
4840 /// dependent.
4841 ///
4842 /// DependentNameType represents a class of dependent types that involve a
4843 /// possibly dependent nested-name-specifier (e.g., "T::") followed by a
4844 /// name of a type. The DependentNameType may start with a "typename" (for a
4845 /// typename-specifier), "class", "struct", "union", or "enum" (for a
4846 /// dependent elaborated-type-specifier), or nothing (in contexts where we
4847 /// know that we must be referring to a type, e.g., in a base class specifier).
4848 /// Typically the nested-name-specifier is dependent, but in MSVC compatibility
4849 /// mode, this type is used with non-dependent names to delay name lookup until
4850 /// instantiation.
4851 class DependentNameType : public TypeWithKeyword, public llvm::FoldingSetNode {
4852  friend class ASTContext; // ASTContext creates these
4853 
4854  /// \brief The nested name specifier containing the qualifier.
4855  NestedNameSpecifier *NNS;
4856 
4857  /// \brief The type that this typename specifier refers to.
4858  const IdentifierInfo *Name;
4859 
4861  const IdentifierInfo *Name, QualType CanonType)
4862  : TypeWithKeyword(Keyword, DependentName, CanonType, /*Dependent=*/true,
4863  /*InstantiationDependent=*/true,
4864  /*VariablyModified=*/false,
4865  NNS->containsUnexpandedParameterPack()),
4866  NNS(NNS), Name(Name) {}
4867 
4868 public:
4869  /// Retrieve the qualification on this type.
4870  NestedNameSpecifier *getQualifier() const { return NNS; }
4871 
4872  /// Retrieve the type named by the typename specifier as an identifier.
4873  ///
4874  /// This routine will return a non-NULL identifier pointer when the
4875  /// form of the original typename was terminated by an identifier,
4876  /// e.g., "typename T::type".
4878  return Name;
4879  }
4880 
4881  bool isSugared() const { return false; }
4882  QualType desugar() const { return QualType(this, 0); }
4883 
4884  void Profile(llvm::FoldingSetNodeID &ID) {
4885  Profile(ID, getKeyword(), NNS, Name);
4886  }
4887 
4888  static void Profile(llvm::FoldingSetNodeID &ID, ElaboratedTypeKeyword Keyword,
4889  NestedNameSpecifier *NNS, const IdentifierInfo *Name) {
4890  ID.AddInteger(Keyword);
4891  ID.AddPointer(NNS);
4892  ID.AddPointer(Name);
4893  }
4894 
4895  static bool classof(const Type *T) {
4896  return T->getTypeClass() == DependentName;
4897  }
4898 };
4899 
4900 /// Represents a template specialization type whose template cannot be
4901 /// resolved, e.g.
4902 /// A<T>::template B<T>
4903 class LLVM_ALIGNAS(/*alignof(uint64_t)*/ 8) DependentTemplateSpecializationType
4904  : public TypeWithKeyword,
4905  public llvm::FoldingSetNode {
4906  friend class ASTContext; // ASTContext creates these
4907 
4908  /// The nested name specifier containing the qualifier.
4909  NestedNameSpecifier *NNS;
4910 
4911  /// The identifier of the template.
4912  const IdentifierInfo *Name;
4913 
4914  /// \brief The number of template arguments named in this class template
4915  /// specialization.
4916  unsigned NumArgs;
4917 
4919  NestedNameSpecifier *NNS,
4920  const IdentifierInfo *Name,
4922  QualType Canon);
4923 
4924  const TemplateArgument *getArgBuffer() const {
4925  return reinterpret_cast<const TemplateArgument*>(this+1);
4926  }
4927 
4928  TemplateArgument *getArgBuffer() {
4929  return reinterpret_cast<TemplateArgument*>(this+1);
4930  }
4931 
4932 public:
4933  NestedNameSpecifier *getQualifier() const { return NNS; }
4934  const IdentifierInfo *getIdentifier() const { return Name; }
4935 
4936  /// \brief Retrieve the template arguments.
4937  const TemplateArgument *getArgs() const {
4938  return getArgBuffer();
4939  }
4940 
4941  /// \brief Retrieve the number of template arguments.
4942  unsigned getNumArgs() const { return NumArgs; }
4943 
4944  const TemplateArgument &getArg(unsigned Idx) const; // in TemplateBase.h
4945 
4947  return {getArgs(), NumArgs};
4948  }
4949 
4950  using iterator = const TemplateArgument *;
4951 
4952  iterator begin() const { return getArgs(); }
4953  iterator end() const; // inline in TemplateBase.h
4954 
4955  bool isSugared() const { return false; }
4956  QualType desugar() const { return QualType(this, 0); }
4957 
4958  void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context) {
4959  Profile(ID, Context, getKeyword(), NNS, Name, {getArgs(), NumArgs});
4960  }
4961 
4962  static void Profile(llvm::FoldingSetNodeID &ID,
4963  const ASTContext &Context,
4964  ElaboratedTypeKeyword Keyword,
4965  NestedNameSpecifier *Qualifier,
4966  const IdentifierInfo *Name,
4968 
4969  static bool classof(const Type *T) {
4970  return T->getTypeClass() == DependentTemplateSpecialization;
4971  }
4972 };
4973 
4974 /// \brief Represents a pack expansion of types.
4975 ///
4976 /// Pack expansions are part of C++11 variadic templates. A pack
4977 /// expansion contains a pattern, which itself contains one or more
4978 /// "unexpanded" parameter packs. When instantiated, a pack expansion
4979 /// produces a series of types, each instantiated from the pattern of
4980 /// the expansion, where the Ith instantiation of the pattern uses the
4981 /// Ith arguments bound to each of the unexpanded parameter packs. The
4982 /// pack expansion is considered to "expand" these unexpanded
4983 /// parameter packs.
4984 ///
4985 /// \code
4986 /// template<typename ...Types> struct tuple;
4987 ///
4988 /// template<typename ...Types>
4989 /// struct tuple_of_references {
4990 /// typedef tuple<Types&...> type;
4991 /// };
4992 /// \endcode
4993 ///
4994 /// Here, the pack expansion \c Types&... is represented via a
4995 /// PackExpansionType whose pattern is Types&.
4996 class PackExpansionType : public Type, public llvm::FoldingSetNode {
4997  friend class ASTContext; // ASTContext creates these
4998 
4999  /// \brief The pattern of the pack expansion.
5000  QualType Pattern;
5001 
5002  /// \brief The number of expansions that this pack expansion will
5003  /// generate when substituted (+1), or indicates that
5004  ///
5005  /// This field will only have a non-zero value when some of the parameter
5006  /// packs that occur within the pattern have been substituted but others have
5007  /// not.
5008  unsigned NumExpansions;
5009 
5010  PackExpansionType(QualType Pattern, QualType Canon,
5011  Optional<unsigned> NumExpansions)
5012  : Type(PackExpansion, Canon, /*Dependent=*/Pattern->isDependentType(),
5013  /*InstantiationDependent=*/true,
5014  /*VariablyModified=*/Pattern->isVariablyModifiedType(),
5015  /*ContainsUnexpandedParameterPack=*/false),
5016  Pattern(Pattern),
5017  NumExpansions(NumExpansions ? *NumExpansions + 1 : 0) {}
5018 
5019 public:
5020  /// \brief Retrieve the pattern of this pack expansion, which is the
5021  /// type that will be repeatedly instantiated when instantiating the
5022  /// pack expansion itself.
5023  QualType getPattern() const { return Pattern; }
5024 
5025  /// \brief Retrieve the number of expansions that this pack expansion will
5026  /// generate, if known.
5028  if (NumExpansions)
5029  return NumExpansions - 1;
5030 
5031  return None;
5032  }
5033 
5034  bool isSugared() const { return !Pattern->isDependentType(); }
5035  QualType desugar() const { return isSugared() ? Pattern : QualType(this, 0); }
5036 
5037  void Profile(llvm::FoldingSetNodeID &ID) {
5038  Profile(ID, getPattern(), getNumExpansions());
5039  }
5040 
5041  static void Profile(llvm::FoldingSetNodeID &ID, QualType Pattern,
5042  Optional<unsigned> NumExpansions) {
5043  ID.AddPointer(Pattern.getAsOpaquePtr());
5044  ID.AddBoolean(NumExpansions.hasValue());
5045  if (NumExpansions)
5046  ID.AddInteger(*NumExpansions);
5047  }
5048 
5049  static bool classof(const Type *T) {
5050  return T->getTypeClass() == PackExpansion;
5051  }
5052 };
5053 
5054 /// This class wraps the list of protocol qualifiers. For types that can
5055 /// take ObjC protocol qualifers, they can subclass this class.
5056 template <class T>
5058 protected:
5059  ObjCProtocolQualifiers() = default;
5060 
5062  return const_cast<ObjCProtocolQualifiers*>(this)->getProtocolStorage();
5063  }
5064 
5066  return static_cast<T*>(this)->getProtocolStorageImpl();
5067  }
5068 
5069  void setNumProtocols(unsigned N) {
5070  static_cast<T*>(this)->setNumProtocolsImpl(N);
5071  }
5072 
5074  setNumProtocols(protocols.size());
5075  assert(getNumProtocols() == protocols.size() &&
5076  "bitfield overflow in protocol count");
5077  if (!protocols.empty())
5078  memcpy(getProtocolStorage(), protocols.data(),
5079  protocols.size() * sizeof(ObjCProtocolDecl*));
5080  }
5081 
5082 public:
5083  using qual_iterator = ObjCProtocolDecl * const *;
5084  using qual_range = llvm::iterator_range<qual_iterator>;
5085 
5086  qual_range quals() const { return qual_range(qual_begin(), qual_end()); }
5087  qual_iterator qual_begin() const { return getProtocolStorage(); }
5088  qual_iterator qual_end() const { return qual_begin() + getNumProtocols(); }
5089 
5090  bool qual_empty() const { return getNumProtocols() == 0; }
5091 
5092  /// Return the number of qualifying protocols in this type, or 0 if
5093  /// there are none.
5094  unsigned getNumProtocols() const {
5095  return static_cast<const T*>(this)->getNumProtocolsImpl();
5096  }
5097 
5098  /// Fetch a protocol by index.
5099  ObjCProtocolDecl *getProtocol(unsigned I) const {
5100  assert(I < getNumProtocols() && "Out-of-range protocol access");
5101  return qual_begin()[I];
5102  }
5103 
5104  /// Retrieve all of the protocol qualifiers.
5106  return ArrayRef<ObjCProtocolDecl *>(qual_begin(), getNumProtocols());
5107  }
5108 };
5109 
5110 /// Represents a type parameter type in Objective C. It can take
5111 /// a list of protocols.
5112 class ObjCTypeParamType : public Type,
5113  public ObjCProtocolQualifiers<ObjCTypeParamType>,
5114  public llvm::FoldingSetNode {
5115  friend class ASTContext;
5117 
5118  /// The number of protocols stored on this type.
5119  unsigned NumProtocols : 6;
5120 
5121  ObjCTypeParamDecl *OTPDecl;
5122 
5123  /// The protocols are stored after the ObjCTypeParamType node. In the
5124  /// canonical type, the list of protocols are sorted alphabetically
5125  /// and uniqued.
5126  ObjCProtocolDecl **getProtocolStorageImpl();
5127 
5128  /// Return the number of qualifying protocols in this interface type,
5129  /// or 0 if there are none.
5130  unsigned getNumProtocolsImpl() const {
5131  return NumProtocols;
5132  }
5133 
5134  void setNumProtocolsImpl(unsigned N) {
5135  NumProtocols = N;
5136  }
5137 
5139  QualType can,
5140  ArrayRef<ObjCProtocolDecl *> protocols);
5141 
5142 public:
5143  bool isSugared() const { return true; }
5144  QualType desugar() const { return getCanonicalTypeInternal(); }
5145 
5146  static bool classof(const Type *T) {
5147  return T->getTypeClass() == ObjCTypeParam;
5148  }
5149 
5150  void Profile(llvm::FoldingSetNodeID &ID);
5151  static void Profile(llvm::FoldingSetNodeID &ID,
5152  const ObjCTypeParamDecl *OTPDecl,
5153  ArrayRef<ObjCProtocolDecl *> protocols);
5154 
5155  ObjCTypeParamDecl *getDecl() const { return OTPDecl; }
5156 };
5157 
5158 /// Represents a class type in Objective C.
5159 ///
5160 /// Every Objective C type is a combination of a base type, a set of
5161 /// type arguments (optional, for parameterized classes) and a list of
5162 /// protocols.
5163 ///
5164 /// Given the following declarations:
5165 /// \code
5166 /// \@class C<T>;
5167 /// \@protocol P;
5168 /// \endcode
5169 ///
5170 /// 'C' is an ObjCInterfaceType C. It is sugar for an Ob