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