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