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