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