Type.h revision 3921aa9c84f6876fdf2b7feb596ccb94fb83989e
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/Basic/Diagnostic.h"
18#include "clang/Basic/IdentifierTable.h"
19#include "clang/AST/NestedNameSpecifier.h"
20#include "clang/AST/TemplateName.h"
21#include "llvm/Support/Casting.h"
22#include "llvm/Support/type_traits.h"
23#include "llvm/ADT/APSInt.h"
24#include "llvm/ADT/FoldingSet.h"
25#include "llvm/ADT/PointerIntPair.h"
26#include "llvm/ADT/PointerUnion.h"
27
28using llvm::isa;
29using llvm::cast;
30using llvm::cast_or_null;
31using llvm::dyn_cast;
32using llvm::dyn_cast_or_null;
33namespace clang {
34  enum {
35    TypeAlignmentInBits = 3,
36    TypeAlignment = 1 << TypeAlignmentInBits
37  };
38  class Type; class ExtQuals;
39}
40
41namespace llvm {
42  template <typename T>
43  class PointerLikeTypeTraits;
44  template<>
45  class PointerLikeTypeTraits< ::clang::Type*> {
46  public:
47    static inline void *getAsVoidPointer(::clang::Type *P) { return P; }
48    static inline ::clang::Type *getFromVoidPointer(void *P) {
49      return static_cast< ::clang::Type*>(P);
50    }
51    enum { NumLowBitsAvailable = clang::TypeAlignmentInBits };
52  };
53  template<>
54  class PointerLikeTypeTraits< ::clang::ExtQuals*> {
55  public:
56    static inline void *getAsVoidPointer(::clang::ExtQuals *P) { return P; }
57    static inline ::clang::ExtQuals *getFromVoidPointer(void *P) {
58      return static_cast< ::clang::ExtQuals*>(P);
59    }
60    enum { NumLowBitsAvailable = clang::TypeAlignmentInBits };
61  };
62}
63
64namespace clang {
65  class ASTContext;
66  class TypedefDecl;
67  class TemplateDecl;
68  class TemplateTypeParmDecl;
69  class NonTypeTemplateParmDecl;
70  class TemplateTemplateParmDecl;
71  class TagDecl;
72  class RecordDecl;
73  class CXXRecordDecl;
74  class EnumDecl;
75  class FieldDecl;
76  class ObjCInterfaceDecl;
77  class ObjCProtocolDecl;
78  class ObjCMethodDecl;
79  class Expr;
80  class Stmt;
81  class SourceLocation;
82  class StmtIteratorBase;
83  class TemplateArgument;
84  class QualifiedNameType;
85  struct PrintingPolicy;
86
87  // Provide forward declarations for all of the *Type classes
88#define TYPE(Class, Base) class Class##Type;
89#include "clang/AST/TypeNodes.def"
90
91/// Qualifiers - The collection of all-type qualifiers we support.
92/// Clang supports five independent qualifiers:
93/// * C99: const, volatile, and restrict
94/// * Embedded C (TR18037): address spaces
95/// * Objective C: the GC attributes (none, weak, or strong)
96class Qualifiers {
97public:
98  enum TQ { // NOTE: These flags must be kept in sync with DeclSpec::TQ.
99    Const    = 0x1,
100    Restrict = 0x2,
101    Volatile = 0x4,
102    CVRMask = Const | Volatile | Restrict
103  };
104
105  enum GC {
106    GCNone = 0,
107    Weak,
108    Strong
109  };
110
111  enum {
112    /// The maximum supported address space number.
113    /// 24 bits should be enough for anyone.
114    MaxAddressSpace = 0xffffffu,
115
116    /// The width of the "fast" qualifier mask.
117    FastWidth = 2,
118
119    /// The fast qualifier mask.
120    FastMask = (1 << FastWidth) - 1
121  };
122
123  Qualifiers() : Mask(0) {}
124
125  static Qualifiers fromFastMask(unsigned Mask) {
126    Qualifiers Qs;
127    Qs.addFastQualifiers(Mask);
128    return Qs;
129  }
130
131  static Qualifiers fromCVRMask(unsigned CVR) {
132    Qualifiers Qs;
133    Qs.addCVRQualifiers(CVR);
134    return Qs;
135  }
136
137  // Deserialize qualifiers from an opaque representation.
138  static Qualifiers fromOpaqueValue(unsigned opaque) {
139    Qualifiers Qs;
140    Qs.Mask = opaque;
141    return Qs;
142  }
143
144  // Serialize these qualifiers into an opaque representation.
145  unsigned getAsOpaqueValue() const {
146    return Mask;
147  }
148
149  bool hasConst() const { return Mask & Const; }
150  void setConst(bool flag) {
151    Mask = (Mask & ~Const) | (flag ? Const : 0);
152  }
153  void removeConst() { Mask &= ~Const; }
154  void addConst() { Mask |= Const; }
155
156  bool hasVolatile() const { return Mask & Volatile; }
157  void setVolatile(bool flag) {
158    Mask = (Mask & ~Volatile) | (flag ? Volatile : 0);
159  }
160  void removeVolatile() { Mask &= ~Volatile; }
161  void addVolatile() { Mask |= Volatile; }
162
163  bool hasRestrict() const { return Mask & Restrict; }
164  void setRestrict(bool flag) {
165    Mask = (Mask & ~Restrict) | (flag ? Restrict : 0);
166  }
167  void removeRestrict() { Mask &= ~Restrict; }
168  void addRestrict() { Mask |= Restrict; }
169
170  bool hasCVRQualifiers() const { return getCVRQualifiers(); }
171  unsigned getCVRQualifiers() const { return Mask & CVRMask; }
172  void setCVRQualifiers(unsigned mask) {
173    assert(!(mask & ~CVRMask) && "bitmask contains non-CVR bits");
174    Mask = (Mask & ~CVRMask) | mask;
175  }
176  void removeCVRQualifiers(unsigned mask) {
177    assert(!(mask & ~CVRMask) && "bitmask contains non-CVR bits");
178    Mask &= ~mask;
179  }
180  void removeCVRQualifiers() {
181    removeCVRQualifiers(CVRMask);
182  }
183  void addCVRQualifiers(unsigned mask) {
184    assert(!(mask & ~CVRMask) && "bitmask contains non-CVR bits");
185    Mask |= mask;
186  }
187
188  bool hasObjCGCAttr() const { return Mask & GCAttrMask; }
189  GC getObjCGCAttr() const { return GC((Mask & GCAttrMask) >> GCAttrShift); }
190  void setObjCGCAttr(GC type) {
191    Mask = (Mask & ~GCAttrMask) | (type << GCAttrShift);
192  }
193  void removeObjCGCAttr() { setObjCGCAttr(GCNone); }
194  void addObjCGCAttr(GC type) {
195    assert(type);
196    setObjCGCAttr(type);
197  }
198
199  bool hasAddressSpace() const { return Mask & AddressSpaceMask; }
200  unsigned getAddressSpace() const { return Mask >> AddressSpaceShift; }
201  void setAddressSpace(unsigned space) {
202    assert(space <= MaxAddressSpace);
203    Mask = (Mask & ~AddressSpaceMask)
204         | (((uint32_t) space) << AddressSpaceShift);
205  }
206  void removeAddressSpace() { setAddressSpace(0); }
207  void addAddressSpace(unsigned space) {
208    assert(space);
209    setAddressSpace(space);
210  }
211
212  // Fast qualifiers are those that can be allocated directly
213  // on a QualType object.
214  bool hasFastQualifiers() const { return getFastQualifiers(); }
215  unsigned getFastQualifiers() const { return Mask & FastMask; }
216  void setFastQualifiers(unsigned mask) {
217    assert(!(mask & ~FastMask) && "bitmask contains non-fast qualifier bits");
218    Mask = (Mask & ~FastMask) | mask;
219  }
220  void removeFastQualifiers(unsigned mask) {
221    assert(!(mask & ~FastMask) && "bitmask contains non-fast qualifier bits");
222    Mask &= ~mask;
223  }
224  void removeFastQualifiers() {
225    removeFastQualifiers(FastMask);
226  }
227  void addFastQualifiers(unsigned mask) {
228    assert(!(mask & ~FastMask) && "bitmask contains non-fast qualifier bits");
229    Mask |= mask;
230  }
231
232  /// hasNonFastQualifiers - Return true if the set contains any
233  /// qualifiers which require an ExtQuals node to be allocated.
234  bool hasNonFastQualifiers() const { return Mask & ~FastMask; }
235  Qualifiers getNonFastQualifiers() const {
236    Qualifiers Quals = *this;
237    Quals.setFastQualifiers(0);
238    return Quals;
239  }
240
241  /// hasQualifiers - Return true if the set contains any qualifiers.
242  bool hasQualifiers() const { return Mask; }
243  bool empty() const { return !Mask; }
244
245  /// \brief Add the qualifiers from the given set to this set.
246  void addQualifiers(Qualifiers Q) {
247    // If the other set doesn't have any non-boolean qualifiers, just
248    // bit-or it in.
249    if (!(Q.Mask & ~CVRMask))
250      Mask |= Q.Mask;
251    else {
252      Mask |= (Q.Mask & CVRMask);
253      if (Q.hasAddressSpace())
254        addAddressSpace(Q.getAddressSpace());
255      if (Q.hasObjCGCAttr())
256        addObjCGCAttr(Q.getObjCGCAttr());
257    }
258  }
259
260  bool operator==(Qualifiers Other) const { return Mask == Other.Mask; }
261  bool operator!=(Qualifiers Other) const { return Mask != Other.Mask; }
262
263  operator bool() const { return hasQualifiers(); }
264
265  Qualifiers &operator+=(Qualifiers R) {
266    addQualifiers(R);
267    return *this;
268  }
269
270  // Union two qualifier sets.  If an enumerated qualifier appears
271  // in both sets, use the one from the right.
272  friend Qualifiers operator+(Qualifiers L, Qualifiers R) {
273    L += R;
274    return L;
275  }
276
277  std::string getAsString() const;
278  std::string getAsString(const PrintingPolicy &Policy) const {
279    std::string Buffer;
280    getAsStringInternal(Buffer, Policy);
281    return Buffer;
282  }
283  void getAsStringInternal(std::string &S, const PrintingPolicy &Policy) const;
284
285  void Profile(llvm::FoldingSetNodeID &ID) const {
286    ID.AddInteger(Mask);
287  }
288
289private:
290
291  // bits:     |0 1 2|3 .. 4|5  ..  31|
292  //           |C R V|GCAttr|AddrSpace|
293  uint32_t Mask;
294
295  static const uint32_t GCAttrMask = 0x18;
296  static const uint32_t GCAttrShift = 3;
297  static const uint32_t AddressSpaceMask = ~(CVRMask | GCAttrMask);
298  static const uint32_t AddressSpaceShift = 5;
299};
300
301
302/// ExtQuals - We can encode up to three bits in the low bits of a
303/// type pointer, but there are many more type qualifiers that we want
304/// to be able to apply to an arbitrary type.  Therefore we have this
305/// struct, intended to be heap-allocated and used by QualType to
306/// store qualifiers.
307///
308/// The current design tags the 'const' and 'restrict' qualifiers in
309/// two low bits on the QualType pointer; a third bit records whether
310/// the pointer is an ExtQuals node.  'const' was chosen because it is
311/// orders of magnitude more common than the other two qualifiers, in
312/// both library and user code.  It's relatively rare to see
313/// 'restrict' in user code, but many standard C headers are saturated
314/// with 'restrict' declarations, so that representing them efficiently
315/// is a critical goal of this representation.
316class ExtQuals : public llvm::FoldingSetNode {
317  // NOTE: changing the fast qualifiers should be straightforward as
318  // long as you don't make 'const' non-fast.
319  // 1. Qualifiers:
320  //    a) Modify the bitmasks (Qualifiers::TQ and DeclSpec::TQ).
321  //       Fast qualifiers must occupy the low-order bits.
322  //    b) Update Qualifiers::FastWidth and FastMask.
323  // 2. QualType:
324  //    a) Update is{Volatile,Restrict}Qualified(), defined inline.
325  //    b) Update remove{Volatile,Restrict}, defined near the end of
326  //       this header.
327  // 3. ASTContext:
328  //    a) Update get{Volatile,Restrict}Type.
329
330  /// Context - the context to which this set belongs.  We save this
331  /// here so that QualifierCollector can use it to reapply extended
332  /// qualifiers to an arbitrary type without requiring a context to
333  /// be pushed through every single API dealing with qualifiers.
334  ASTContext& Context;
335
336  /// BaseType - the underlying type that this qualifies
337  const Type *BaseType;
338
339  /// Quals - the immutable set of qualifiers applied by this
340  /// node;  always contains extended qualifiers.
341  Qualifiers Quals;
342
343public:
344  ExtQuals(ASTContext& Context, const Type *Base, Qualifiers Quals)
345    : Context(Context), BaseType(Base), Quals(Quals)
346  {
347    assert(Quals.hasNonFastQualifiers()
348           && "ExtQuals created with no fast qualifiers");
349    assert(!Quals.hasFastQualifiers()
350           && "ExtQuals created with fast qualifiers");
351  }
352
353  Qualifiers getQualifiers() const { return Quals; }
354
355  bool hasVolatile() const { return Quals.hasVolatile(); }
356
357  bool hasObjCGCAttr() const { return Quals.hasObjCGCAttr(); }
358  Qualifiers::GC getObjCGCAttr() const { return Quals.getObjCGCAttr(); }
359
360  bool hasAddressSpace() const { return Quals.hasAddressSpace(); }
361  unsigned getAddressSpace() const { return Quals.getAddressSpace(); }
362
363  const Type *getBaseType() const { return BaseType; }
364
365  ASTContext &getContext() const { return Context; }
366
367public:
368  void Profile(llvm::FoldingSetNodeID &ID) const {
369    Profile(ID, getBaseType(), Quals);
370  }
371  static void Profile(llvm::FoldingSetNodeID &ID,
372                      const Type *BaseType,
373                      Qualifiers Quals) {
374    assert(!Quals.hasFastQualifiers() && "fast qualifiers in ExtQuals hash!");
375    ID.AddPointer(BaseType);
376    Quals.Profile(ID);
377  }
378};
379
380
381/// QualType - For efficiency, we don't store CV-qualified types as nodes on
382/// their own: instead each reference to a type stores the qualifiers.  This
383/// greatly reduces the number of nodes we need to allocate for types (for
384/// example we only need one for 'int', 'const int', 'volatile int',
385/// 'const volatile int', etc).
386///
387/// As an added efficiency bonus, instead of making this a pair, we
388/// just store the two bits we care about in the low bits of the
389/// pointer.  To handle the packing/unpacking, we make QualType be a
390/// simple wrapper class that acts like a smart pointer.  A third bit
391/// indicates whether there are extended qualifiers present, in which
392/// case the pointer points to a special structure.
393class QualType {
394  // Thankfully, these are efficiently composable.
395  llvm::PointerIntPair<llvm::PointerUnion<const Type*,const ExtQuals*>,
396                       Qualifiers::FastWidth> Value;
397
398  bool hasExtQuals() const {
399    return Value.getPointer().is<const ExtQuals*>();
400  }
401
402  const ExtQuals *getExtQualsUnsafe() const {
403    return Value.getPointer().get<const ExtQuals*>();
404  }
405
406  const Type *getTypePtrUnsafe() const {
407    return Value.getPointer().get<const Type*>();
408  }
409
410  friend class QualifierCollector;
411public:
412  QualType() {}
413
414  QualType(const Type *Ptr, unsigned Quals)
415    : Value(Ptr, Quals) {}
416  QualType(const ExtQuals *Ptr, unsigned Quals)
417    : Value(Ptr, Quals) {}
418
419  unsigned getFastQualifiers() const { return Value.getInt(); }
420  void setFastQualifiers(unsigned Quals) { Value.setInt(Quals); }
421
422  /// Retrieves a pointer to the underlying (unqualified) type.
423  /// This should really return a const Type, but it's not worth
424  /// changing all the users right now.
425  Type *getTypePtr() const {
426    if (hasNonFastQualifiers())
427      return const_cast<Type*>(getExtQualsUnsafe()->getBaseType());
428    return const_cast<Type*>(getTypePtrUnsafe());
429  }
430
431  void *getAsOpaquePtr() const { return Value.getOpaqueValue(); }
432  static QualType getFromOpaquePtr(void *Ptr) {
433    QualType T;
434    T.Value.setFromOpaqueValue(Ptr);
435    return T;
436  }
437
438  Type &operator*() const {
439    return *getTypePtr();
440  }
441
442  Type *operator->() const {
443    return getTypePtr();
444  }
445
446  /// isNull - Return true if this QualType doesn't point to a type yet.
447  bool isNull() const {
448    return Value.getPointer().isNull();
449  }
450
451  bool isConstQualified() const {
452    return (getFastQualifiers() & Qualifiers::Const);
453  }
454  bool isRestrictQualified() const {
455    return (getFastQualifiers() & Qualifiers::Restrict);
456  }
457  bool isVolatileQualified() const {
458    return (hasNonFastQualifiers() && getExtQualsUnsafe()->hasVolatile());
459  }
460
461  // Determines whether this type has any direct qualifiers.
462  bool hasQualifiers() const {
463    return getFastQualifiers() || hasNonFastQualifiers();
464  }
465
466  bool hasNonFastQualifiers() const {
467    return hasExtQuals();
468  }
469
470  // Retrieves the set of qualifiers belonging to this type.
471  Qualifiers getQualifiers() const {
472    Qualifiers Quals;
473    if (hasNonFastQualifiers())
474      Quals = getExtQualsUnsafe()->getQualifiers();
475    Quals.addFastQualifiers(getFastQualifiers());
476    return Quals;
477  }
478
479  // Retrieves the CVR qualifiers of this type.
480  unsigned getCVRQualifiers() const {
481    unsigned CVR = getFastQualifiers();
482    if (isVolatileQualified()) CVR |= Qualifiers::Volatile;
483    return CVR;
484  }
485
486  bool isConstant(ASTContext& Ctx) const;
487
488  // Don't promise in the API that anything besides 'const' can be
489  // easily added.
490
491  /// addConst - add the specified type qualifier to this QualType.
492  void addConst() {
493    addFastQualifiers(Qualifiers::Const);
494  }
495  QualType withConst() const {
496    return withFastQualifiers(Qualifiers::Const);
497  }
498
499  void addFastQualifiers(unsigned TQs) {
500    assert(!(TQs & ~Qualifiers::FastMask)
501           && "non-fast qualifier bits set in mask!");
502    Value.setInt(Value.getInt() | TQs);
503  }
504
505  void removeConst();
506  void removeVolatile();
507  void removeRestrict();
508  void removeCVRQualifiers(unsigned Mask);
509
510  void removeFastQualifiers() { Value.setInt(0); }
511  void removeFastQualifiers(unsigned Mask) {
512    assert(!(Mask & ~Qualifiers::FastMask) && "mask has non-fast qualifiers");
513    Value.setInt(Value.getInt() & ~Mask);
514  }
515
516  // Creates a type with the given qualifiers in addition to any
517  // qualifiers already on this type.
518  QualType withFastQualifiers(unsigned TQs) const {
519    QualType T = *this;
520    T.addFastQualifiers(TQs);
521    return T;
522  }
523
524  // Creates a type with exactly the given fast qualifiers, removing
525  // any existing fast qualifiers.
526  QualType withExactFastQualifiers(unsigned TQs) const {
527    return withoutFastQualifiers().withFastQualifiers(TQs);
528  }
529
530  // Removes fast qualifiers, but leaves any extended qualifiers in place.
531  QualType withoutFastQualifiers() const {
532    QualType T = *this;
533    T.removeFastQualifiers();
534    return T;
535  }
536
537  QualType getUnqualifiedType() const { return QualType(getTypePtr(), 0); }
538
539  bool isMoreQualifiedThan(QualType Other) const;
540  bool isAtLeastAsQualifiedAs(QualType Other) const;
541  QualType getNonReferenceType() const;
542
543  /// getDesugaredType - Return the specified type with any "sugar" removed from
544  /// the type.  This takes off typedefs, typeof's etc.  If the outer level of
545  /// the type is already concrete, it returns it unmodified.  This is similar
546  /// to getting the canonical type, but it doesn't remove *all* typedefs.  For
547  /// example, it returns "T*" as "T*", (not as "int*"), because the pointer is
548  /// concrete.
549  ///
550  /// Qualifiers are left in place.
551  QualType getDesugaredType(bool ForDisplay = false) const;
552
553  /// operator==/!= - Indicate whether the specified types and qualifiers are
554  /// identical.
555  friend bool operator==(const QualType &LHS, const QualType &RHS) {
556    return LHS.Value == RHS.Value;
557  }
558  friend bool operator!=(const QualType &LHS, const QualType &RHS) {
559    return LHS.Value != RHS.Value;
560  }
561  std::string getAsString() const;
562
563  std::string getAsString(const PrintingPolicy &Policy) const {
564    std::string S;
565    getAsStringInternal(S, Policy);
566    return S;
567  }
568  void getAsStringInternal(std::string &Str,
569                           const PrintingPolicy &Policy) const;
570
571  void dump(const char *s) const;
572  void dump() const;
573
574  void Profile(llvm::FoldingSetNodeID &ID) const {
575    ID.AddPointer(getAsOpaquePtr());
576  }
577
578  /// getAddressSpace - Return the address space of this type.
579  inline unsigned getAddressSpace() const;
580
581  /// GCAttrTypesAttr - Returns gc attribute of this type.
582  inline Qualifiers::GC getObjCGCAttr() const;
583
584  /// isObjCGCWeak true when Type is objc's weak.
585  bool isObjCGCWeak() const {
586    return getObjCGCAttr() == Qualifiers::Weak;
587  }
588
589  /// isObjCGCStrong true when Type is objc's strong.
590  bool isObjCGCStrong() const {
591    return getObjCGCAttr() == Qualifiers::Strong;
592  }
593
594  /// getNoReturnAttr - Returns true if the type has the noreturn attribute,
595  /// false otherwise.
596  bool getNoReturnAttr() const;
597};
598
599} // end clang.
600
601namespace llvm {
602/// Implement simplify_type for QualType, so that we can dyn_cast from QualType
603/// to a specific Type class.
604template<> struct simplify_type<const ::clang::QualType> {
605  typedef ::clang::Type* SimpleType;
606  static SimpleType getSimplifiedValue(const ::clang::QualType &Val) {
607    return Val.getTypePtr();
608  }
609};
610template<> struct simplify_type< ::clang::QualType>
611  : public simplify_type<const ::clang::QualType> {};
612
613// Teach SmallPtrSet that QualType is "basically a pointer".
614template<>
615class PointerLikeTypeTraits<clang::QualType> {
616public:
617  static inline void *getAsVoidPointer(clang::QualType P) {
618    return P.getAsOpaquePtr();
619  }
620  static inline clang::QualType getFromVoidPointer(void *P) {
621    return clang::QualType::getFromOpaquePtr(P);
622  }
623  // Various qualifiers go in low bits.
624  enum { NumLowBitsAvailable = 0 };
625};
626
627} // end namespace llvm
628
629namespace clang {
630
631/// Type - This is the base class of the type hierarchy.  A central concept
632/// with types is that each type always has a canonical type.  A canonical type
633/// is the type with any typedef names stripped out of it or the types it
634/// references.  For example, consider:
635///
636///  typedef int  foo;
637///  typedef foo* bar;
638///    'int *'    'foo *'    'bar'
639///
640/// There will be a Type object created for 'int'.  Since int is canonical, its
641/// canonicaltype pointer points to itself.  There is also a Type for 'foo' (a
642/// TypedefType).  Its CanonicalType pointer points to the 'int' Type.  Next
643/// there is a PointerType that represents 'int*', which, like 'int', is
644/// canonical.  Finally, there is a PointerType type for 'foo*' whose canonical
645/// type is 'int*', and there is a TypedefType for 'bar', whose canonical type
646/// is also 'int*'.
647///
648/// Non-canonical types are useful for emitting diagnostics, without losing
649/// information about typedefs being used.  Canonical types are useful for type
650/// comparisons (they allow by-pointer equality tests) and useful for reasoning
651/// about whether something has a particular form (e.g. is a function type),
652/// because they implicitly, recursively, strip all typedefs out of a type.
653///
654/// Types, once created, are immutable.
655///
656class Type {
657public:
658  enum TypeClass {
659#define TYPE(Class, Base) Class,
660#define ABSTRACT_TYPE(Class, Base)
661#include "clang/AST/TypeNodes.def"
662    TagFirst = Record, TagLast = Enum
663  };
664
665protected:
666  enum { TypeClassBitSize = 6 };
667
668private:
669  QualType CanonicalType;
670
671  /// Dependent - Whether this type is a dependent type (C++ [temp.dep.type]).
672  bool Dependent : 1;
673
674  /// TypeClass bitfield - Enum that specifies what subclass this belongs to.
675  /// Note that this should stay at the end of the ivars for Type so that
676  /// subclasses can pack their bitfields into the same word.
677  unsigned TC : TypeClassBitSize;
678
679  Type(const Type&);           // DO NOT IMPLEMENT.
680  void operator=(const Type&); // DO NOT IMPLEMENT.
681protected:
682  // silence VC++ warning C4355: 'this' : used in base member initializer list
683  Type *this_() { return this; }
684  Type(TypeClass tc, QualType Canonical, bool dependent)
685    : CanonicalType(Canonical.isNull() ? QualType(this_(), 0) : Canonical),
686      Dependent(dependent), TC(tc) {}
687  virtual ~Type() {}
688  virtual void Destroy(ASTContext& C);
689  friend class ASTContext;
690
691public:
692  TypeClass getTypeClass() const { return static_cast<TypeClass>(TC); }
693
694  bool isCanonical() const { return CanonicalType.getTypePtr() == this; }
695
696  /// Types are partitioned into 3 broad categories (C99 6.2.5p1):
697  /// object types, function types, and incomplete types.
698
699  /// \brief Determines whether the type describes an object in memory.
700  ///
701  /// Note that this definition of object type corresponds to the C++
702  /// definition of object type, which includes incomplete types, as
703  /// opposed to the C definition (which does not include incomplete
704  /// types).
705  bool isObjectType() const;
706
707  /// isIncompleteType - Return true if this is an incomplete type.
708  /// A type that can describe objects, but which lacks information needed to
709  /// determine its size (e.g. void, or a fwd declared struct). Clients of this
710  /// routine will need to determine if the size is actually required.
711  bool isIncompleteType() const;
712
713  /// isIncompleteOrObjectType - Return true if this is an incomplete or object
714  /// type, in other words, not a function type.
715  bool isIncompleteOrObjectType() const {
716    return !isFunctionType();
717  }
718
719  /// isPODType - Return true if this is a plain-old-data type (C++ 3.9p10).
720  bool isPODType() const;
721
722  /// isVariablyModifiedType (C99 6.7.5.2p2) - Return true for variable array
723  /// types that have a non-constant expression. This does not include "[]".
724  bool isVariablyModifiedType() const;
725
726  /// Helper methods to distinguish type categories. All type predicates
727  /// operate on the canonical type, ignoring typedefs and qualifiers.
728
729  /// isSpecificBuiltinType - Test for a particular builtin type.
730  bool isSpecificBuiltinType(unsigned K) const;
731
732  /// isIntegerType() does *not* include complex integers (a GCC extension).
733  /// isComplexIntegerType() can be used to test for complex integers.
734  bool isIntegerType() const;     // C99 6.2.5p17 (int, char, bool, enum)
735  bool isEnumeralType() const;
736  bool isBooleanType() const;
737  bool isCharType() const;
738  bool isWideCharType() const;
739  bool isIntegralType() const;
740
741  /// Floating point categories.
742  bool isRealFloatingType() const; // C99 6.2.5p10 (float, double, long double)
743  /// isComplexType() does *not* include complex integers (a GCC extension).
744  /// isComplexIntegerType() can be used to test for complex integers.
745  bool isComplexType() const;      // C99 6.2.5p11 (complex)
746  bool isAnyComplexType() const;   // C99 6.2.5p11 (complex) + Complex Int.
747  bool isFloatingType() const;     // C99 6.2.5p11 (real floating + complex)
748  bool isRealType() const;         // C99 6.2.5p17 (real floating + integer)
749  bool isArithmeticType() const;   // C99 6.2.5p18 (integer + floating)
750  bool isVoidType() const;         // C99 6.2.5p19
751  bool isDerivedType() const;      // C99 6.2.5p20
752  bool isScalarType() const;       // C99 6.2.5p21 (arithmetic + pointers)
753  bool isAggregateType() const;
754
755  // Type Predicates: Check to see if this type is structurally the specified
756  // type, ignoring typedefs and qualifiers.
757  bool isFunctionType() const;
758  bool isFunctionNoProtoType() const { return getAs<FunctionNoProtoType>(); }
759  bool isFunctionProtoType() const { return getAs<FunctionProtoType>(); }
760  bool isPointerType() const;
761  bool isAnyPointerType() const;   // Any C pointer or ObjC object pointer
762  bool isBlockPointerType() const;
763  bool isVoidPointerType() const;
764  bool isReferenceType() const;
765  bool isLValueReferenceType() const;
766  bool isRValueReferenceType() const;
767  bool isFunctionPointerType() const;
768  bool isMemberPointerType() const;
769  bool isMemberFunctionPointerType() const;
770  bool isArrayType() const;
771  bool isConstantArrayType() const;
772  bool isIncompleteArrayType() const;
773  bool isVariableArrayType() const;
774  bool isDependentSizedArrayType() const;
775  bool isRecordType() const;
776  bool isClassType() const;
777  bool isStructureType() const;
778  bool isUnionType() const;
779  bool isComplexIntegerType() const;            // GCC _Complex integer type.
780  bool isVectorType() const;                    // GCC vector type.
781  bool isExtVectorType() const;                 // Extended vector type.
782  bool isObjCObjectPointerType() const;         // Pointer to *any* ObjC object.
783  // FIXME: change this to 'raw' interface type, so we can used 'interface' type
784  // for the common case.
785  bool isObjCInterfaceType() const;             // NSString or NSString<foo>
786  bool isObjCQualifiedInterfaceType() const;    // NSString<foo>
787  bool isObjCQualifiedIdType() const;           // id<foo>
788  bool isObjCQualifiedClassType() const;        // Class<foo>
789  bool isObjCIdType() const;                    // id
790  bool isObjCClassType() const;                 // Class
791  bool isObjCBuiltinType() const;               // 'id' or 'Class'
792  bool isTemplateTypeParmType() const;          // C++ template type parameter
793  bool isNullPtrType() const;                   // C++0x nullptr_t
794
795  /// isDependentType - Whether this type is a dependent type, meaning
796  /// that its definition somehow depends on a template parameter
797  /// (C++ [temp.dep.type]).
798  bool isDependentType() const { return Dependent; }
799  bool isOverloadableType() const;
800
801  /// hasPointerRepresentation - Whether this type is represented
802  /// natively as a pointer; this includes pointers, references, block
803  /// pointers, and Objective-C interface, qualified id, and qualified
804  /// interface types, as well as nullptr_t.
805  bool hasPointerRepresentation() const;
806
807  /// hasObjCPointerRepresentation - Whether this type can represent
808  /// an objective pointer type for the purpose of GC'ability
809  bool hasObjCPointerRepresentation() const;
810
811  // Type Checking Functions: Check to see if this type is structurally the
812  // specified type, ignoring typedefs and qualifiers, and return a pointer to
813  // the best type we can.
814  const RecordType *getAsStructureType() const;
815  /// NOTE: getAs*ArrayType are methods on ASTContext.
816  const RecordType *getAsUnionType() const;
817  const ComplexType *getAsComplexIntegerType() const; // GCC complex int type.
818  // The following is a convenience method that returns an ObjCObjectPointerType
819  // for object declared using an interface.
820  const ObjCObjectPointerType *getAsObjCInterfacePointerType() const;
821  const ObjCObjectPointerType *getAsObjCQualifiedIdType() const;
822  const ObjCInterfaceType *getAsObjCQualifiedInterfaceType() const;
823  const CXXRecordDecl *getCXXRecordDeclForPointerType() const;
824
825  // Member-template getAs<specific type>'.  This scheme will eventually
826  // replace the specific getAsXXXX methods above.
827  //
828  // There are some specializations of this member template listed
829  // immediately following this class.
830  template <typename T> const T *getAs() const;
831
832  /// getAsPointerToObjCInterfaceType - If this is a pointer to an ObjC
833  /// interface, return the interface type, otherwise return null.
834  const ObjCInterfaceType *getAsPointerToObjCInterfaceType() const;
835
836  /// getArrayElementTypeNoTypeQual - If this is an array type, return the
837  /// element type of the array, potentially with type qualifiers missing.
838  /// This method should never be used when type qualifiers are meaningful.
839  const Type *getArrayElementTypeNoTypeQual() const;
840
841  /// getPointeeType - If this is a pointer, ObjC object pointer, or block
842  /// pointer, this returns the respective pointee.
843  QualType getPointeeType() const;
844
845  /// getDesugaredType - Return the specified type with any "sugar" removed from
846  /// the type.  This takes off typedefs, typeof's etc.  If the outer level of
847  /// the type is already concrete, it returns it unmodified.  This is similar
848  /// to getting the canonical type, but it doesn't remove *all* typedefs.  For
849  /// example, it returns "T*" as "T*", (not as "int*"), because the pointer is
850  /// concrete.
851  QualType getDesugaredType(bool ForDisplay = false) const;
852
853  /// More type predicates useful for type checking/promotion
854  bool isPromotableIntegerType() const; // C99 6.3.1.1p2
855
856  /// isSignedIntegerType - Return true if this is an integer type that is
857  /// signed, according to C99 6.2.5p4 [char, signed char, short, int, long..],
858  /// an enum decl which has a signed representation, or a vector of signed
859  /// integer element type.
860  bool isSignedIntegerType() const;
861
862  /// isUnsignedIntegerType - Return true if this is an integer type that is
863  /// unsigned, according to C99 6.2.5p6 [which returns true for _Bool], an enum
864  /// decl which has an unsigned representation, or a vector of unsigned integer
865  /// element type.
866  bool isUnsignedIntegerType() const;
867
868  /// isConstantSizeType - Return true if this is not a variable sized type,
869  /// according to the rules of C99 6.7.5p3.  It is not legal to call this on
870  /// incomplete types.
871  bool isConstantSizeType() const;
872
873  /// isSpecifierType - Returns true if this type can be represented by some
874  /// set of type specifiers.
875  bool isSpecifierType() const;
876
877  const char *getTypeClassName() const;
878
879  QualType getCanonicalTypeInternal() const { return CanonicalType; }
880  void dump() const;
881  virtual void getAsStringInternal(std::string &InnerString,
882                                   const PrintingPolicy &Policy) const = 0;
883  static bool classof(const Type *) { return true; }
884};
885
886template <> inline const TypedefType *Type::getAs() const {
887  return dyn_cast<TypedefType>(this);
888}
889
890// We can do canonical leaf types faster, because we don't have to
891// worry about preserving child type decoration.
892#define TYPE(Class, Base)
893#define LEAF_TYPE(Class) \
894template <> inline const Class##Type *Type::getAs() const { \
895  return dyn_cast<Class##Type>(CanonicalType); \
896}
897#include "clang/AST/TypeNodes.def"
898
899
900/// BuiltinType - This class is used for builtin types like 'int'.  Builtin
901/// types are always canonical and have a literal name field.
902class BuiltinType : public Type {
903public:
904  enum Kind {
905    Void,
906
907    Bool,     // This is bool and/or _Bool.
908    Char_U,   // This is 'char' for targets where char is unsigned.
909    UChar,    // This is explicitly qualified unsigned char.
910    Char16,   // This is 'char16_t' for C++.
911    Char32,   // This is 'char32_t' for C++.
912    UShort,
913    UInt,
914    ULong,
915    ULongLong,
916    UInt128,  // __uint128_t
917
918    Char_S,   // This is 'char' for targets where char is signed.
919    SChar,    // This is explicitly qualified signed char.
920    WChar,    // This is 'wchar_t' for C++.
921    Short,
922    Int,
923    Long,
924    LongLong,
925    Int128,   // __int128_t
926
927    Float, Double, LongDouble,
928
929    NullPtr,  // This is the type of C++0x 'nullptr'.
930
931    Overload,  // This represents the type of an overloaded function declaration.
932    Dependent, // This represents the type of a type-dependent expression.
933
934    UndeducedAuto, // In C++0x, this represents the type of an auto variable
935                   // that has not been deduced yet.
936    ObjCId,    // This represents the ObjC 'id' type.
937    ObjCClass  // This represents the ObjC 'Class' type.
938  };
939private:
940  Kind TypeKind;
941public:
942  BuiltinType(Kind K)
943    : Type(Builtin, QualType(), /*Dependent=*/(K == Dependent)),
944      TypeKind(K) {}
945
946  Kind getKind() const { return TypeKind; }
947  const char *getName(const LangOptions &LO) const;
948
949  virtual void getAsStringInternal(std::string &InnerString,
950                                   const PrintingPolicy &Policy) const;
951
952  static bool classof(const Type *T) { return T->getTypeClass() == Builtin; }
953  static bool classof(const BuiltinType *) { return true; }
954};
955
956/// FixedWidthIntType - Used for arbitrary width types that we either don't
957/// want to or can't map to named integer types.  These always have a lower
958/// integer rank than builtin types of the same width.
959class FixedWidthIntType : public Type {
960private:
961  unsigned Width;
962  bool Signed;
963public:
964  FixedWidthIntType(unsigned W, bool S) : Type(FixedWidthInt, QualType(), false),
965                                          Width(W), Signed(S) {}
966
967  unsigned getWidth() const { return Width; }
968  bool isSigned() const { return Signed; }
969  const char *getName() const;
970
971  virtual void getAsStringInternal(std::string &InnerString,
972                                   const PrintingPolicy &Policy) const;
973
974  static bool classof(const Type *T) { return T->getTypeClass() == FixedWidthInt; }
975  static bool classof(const FixedWidthIntType *) { return true; }
976};
977
978/// ComplexType - C99 6.2.5p11 - Complex values.  This supports the C99 complex
979/// types (_Complex float etc) as well as the GCC integer complex extensions.
980///
981class ComplexType : public Type, public llvm::FoldingSetNode {
982  QualType ElementType;
983  ComplexType(QualType Element, QualType CanonicalPtr) :
984    Type(Complex, CanonicalPtr, Element->isDependentType()),
985    ElementType(Element) {
986  }
987  friend class ASTContext;  // ASTContext creates these.
988public:
989  QualType getElementType() const { return ElementType; }
990
991  virtual void getAsStringInternal(std::string &InnerString,
992                                   const PrintingPolicy &Policy) const;
993
994  void Profile(llvm::FoldingSetNodeID &ID) {
995    Profile(ID, getElementType());
996  }
997  static void Profile(llvm::FoldingSetNodeID &ID, QualType Element) {
998    ID.AddPointer(Element.getAsOpaquePtr());
999  }
1000
1001  static bool classof(const Type *T) { return T->getTypeClass() == Complex; }
1002  static bool classof(const ComplexType *) { return true; }
1003};
1004
1005/// PointerType - C99 6.7.5.1 - Pointer Declarators.
1006///
1007class PointerType : public Type, public llvm::FoldingSetNode {
1008  QualType PointeeType;
1009
1010  PointerType(QualType Pointee, QualType CanonicalPtr) :
1011    Type(Pointer, CanonicalPtr, Pointee->isDependentType()), PointeeType(Pointee) {
1012  }
1013  friend class ASTContext;  // ASTContext creates these.
1014public:
1015
1016  virtual void getAsStringInternal(std::string &InnerString,
1017                                   const PrintingPolicy &Policy) const;
1018
1019  QualType getPointeeType() const { return PointeeType; }
1020
1021  void Profile(llvm::FoldingSetNodeID &ID) {
1022    Profile(ID, getPointeeType());
1023  }
1024  static void Profile(llvm::FoldingSetNodeID &ID, QualType Pointee) {
1025    ID.AddPointer(Pointee.getAsOpaquePtr());
1026  }
1027
1028  static bool classof(const Type *T) { return T->getTypeClass() == Pointer; }
1029  static bool classof(const PointerType *) { return true; }
1030};
1031
1032/// BlockPointerType - pointer to a block type.
1033/// This type is to represent types syntactically represented as
1034/// "void (^)(int)", etc. Pointee is required to always be a function type.
1035///
1036class BlockPointerType : public Type, public llvm::FoldingSetNode {
1037  QualType PointeeType;  // Block is some kind of pointer type
1038  BlockPointerType(QualType Pointee, QualType CanonicalCls) :
1039    Type(BlockPointer, CanonicalCls, Pointee->isDependentType()),
1040    PointeeType(Pointee) {
1041  }
1042  friend class ASTContext;  // ASTContext creates these.
1043public:
1044
1045  // Get the pointee type. Pointee is required to always be a function type.
1046  QualType getPointeeType() const { return PointeeType; }
1047
1048  virtual void getAsStringInternal(std::string &InnerString,
1049                                   const PrintingPolicy &Policy) const;
1050
1051  void Profile(llvm::FoldingSetNodeID &ID) {
1052      Profile(ID, getPointeeType());
1053  }
1054  static void Profile(llvm::FoldingSetNodeID &ID, QualType Pointee) {
1055      ID.AddPointer(Pointee.getAsOpaquePtr());
1056  }
1057
1058  static bool classof(const Type *T) {
1059    return T->getTypeClass() == BlockPointer;
1060  }
1061  static bool classof(const BlockPointerType *) { return true; }
1062};
1063
1064/// ReferenceType - Base for LValueReferenceType and RValueReferenceType
1065///
1066class ReferenceType : public Type, public llvm::FoldingSetNode {
1067  QualType PointeeType;
1068
1069protected:
1070  ReferenceType(TypeClass tc, QualType Referencee, QualType CanonicalRef) :
1071    Type(tc, CanonicalRef, Referencee->isDependentType()),
1072    PointeeType(Referencee) {
1073  }
1074public:
1075  QualType getPointeeType() const { return PointeeType; }
1076
1077  void Profile(llvm::FoldingSetNodeID &ID) {
1078    Profile(ID, getPointeeType());
1079  }
1080  static void Profile(llvm::FoldingSetNodeID &ID, QualType Referencee) {
1081    ID.AddPointer(Referencee.getAsOpaquePtr());
1082  }
1083
1084  static bool classof(const Type *T) {
1085    return T->getTypeClass() == LValueReference ||
1086           T->getTypeClass() == RValueReference;
1087  }
1088  static bool classof(const ReferenceType *) { return true; }
1089};
1090
1091/// LValueReferenceType - C++ [dcl.ref] - Lvalue reference
1092///
1093class LValueReferenceType : public ReferenceType {
1094  LValueReferenceType(QualType Referencee, QualType CanonicalRef) :
1095    ReferenceType(LValueReference, Referencee, CanonicalRef) {
1096  }
1097  friend class ASTContext; // ASTContext creates these
1098public:
1099  virtual void getAsStringInternal(std::string &InnerString,
1100                                   const PrintingPolicy &Policy) const;
1101
1102  static bool classof(const Type *T) {
1103    return T->getTypeClass() == LValueReference;
1104  }
1105  static bool classof(const LValueReferenceType *) { return true; }
1106};
1107
1108/// RValueReferenceType - C++0x [dcl.ref] - Rvalue reference
1109///
1110class RValueReferenceType : public ReferenceType {
1111  RValueReferenceType(QualType Referencee, QualType CanonicalRef) :
1112    ReferenceType(RValueReference, Referencee, CanonicalRef) {
1113  }
1114  friend class ASTContext; // ASTContext creates these
1115public:
1116  virtual void getAsStringInternal(std::string &InnerString,
1117                                   const PrintingPolicy &Policy) const;
1118
1119  static bool classof(const Type *T) {
1120    return T->getTypeClass() == RValueReference;
1121  }
1122  static bool classof(const RValueReferenceType *) { return true; }
1123};
1124
1125/// MemberPointerType - C++ 8.3.3 - Pointers to members
1126///
1127class MemberPointerType : public Type, public llvm::FoldingSetNode {
1128  QualType PointeeType;
1129  /// The class of which the pointee is a member. Must ultimately be a
1130  /// RecordType, but could be a typedef or a template parameter too.
1131  const Type *Class;
1132
1133  MemberPointerType(QualType Pointee, const Type *Cls, QualType CanonicalPtr) :
1134    Type(MemberPointer, CanonicalPtr,
1135         Cls->isDependentType() || Pointee->isDependentType()),
1136    PointeeType(Pointee), Class(Cls) {
1137  }
1138  friend class ASTContext; // ASTContext creates these.
1139public:
1140
1141  QualType getPointeeType() const { return PointeeType; }
1142
1143  const Type *getClass() const { return Class; }
1144
1145  virtual void getAsStringInternal(std::string &InnerString,
1146                                   const PrintingPolicy &Policy) const;
1147
1148  void Profile(llvm::FoldingSetNodeID &ID) {
1149    Profile(ID, getPointeeType(), getClass());
1150  }
1151  static void Profile(llvm::FoldingSetNodeID &ID, QualType Pointee,
1152                      const Type *Class) {
1153    ID.AddPointer(Pointee.getAsOpaquePtr());
1154    ID.AddPointer(Class);
1155  }
1156
1157  static bool classof(const Type *T) {
1158    return T->getTypeClass() == MemberPointer;
1159  }
1160  static bool classof(const MemberPointerType *) { return true; }
1161};
1162
1163/// ArrayType - C99 6.7.5.2 - Array Declarators.
1164///
1165class ArrayType : public Type, public llvm::FoldingSetNode {
1166public:
1167  /// ArraySizeModifier - Capture whether this is a normal array (e.g. int X[4])
1168  /// an array with a static size (e.g. int X[static 4]), or an array
1169  /// with a star size (e.g. int X[*]).
1170  /// 'static' is only allowed on function parameters.
1171  enum ArraySizeModifier {
1172    Normal, Static, Star
1173  };
1174private:
1175  /// ElementType - The element type of the array.
1176  QualType ElementType;
1177
1178  // NOTE: VC++ treats enums as signed, avoid using the ArraySizeModifier enum
1179  /// NOTE: These fields are packed into the bitfields space in the Type class.
1180  unsigned SizeModifier : 2;
1181
1182  /// IndexTypeQuals - Capture qualifiers in declarations like:
1183  /// 'int X[static restrict 4]'. For function parameters only.
1184  unsigned IndexTypeQuals : 3;
1185
1186protected:
1187  // C++ [temp.dep.type]p1:
1188  //   A type is dependent if it is...
1189  //     - an array type constructed from any dependent type or whose
1190  //       size is specified by a constant expression that is
1191  //       value-dependent,
1192  ArrayType(TypeClass tc, QualType et, QualType can,
1193            ArraySizeModifier sm, unsigned tq)
1194    : Type(tc, can, et->isDependentType() || tc == DependentSizedArray),
1195      ElementType(et), SizeModifier(sm), IndexTypeQuals(tq) {}
1196
1197  friend class ASTContext;  // ASTContext creates these.
1198public:
1199  QualType getElementType() const { return ElementType; }
1200  ArraySizeModifier getSizeModifier() const {
1201    return ArraySizeModifier(SizeModifier);
1202  }
1203  Qualifiers getIndexTypeQualifiers() const {
1204    return Qualifiers::fromCVRMask(IndexTypeQuals);
1205  }
1206  unsigned getIndexTypeCVRQualifiers() const { return IndexTypeQuals; }
1207
1208  static bool classof(const Type *T) {
1209    return T->getTypeClass() == ConstantArray ||
1210           T->getTypeClass() == ConstantArrayWithExpr ||
1211           T->getTypeClass() == ConstantArrayWithoutExpr ||
1212           T->getTypeClass() == VariableArray ||
1213           T->getTypeClass() == IncompleteArray ||
1214           T->getTypeClass() == DependentSizedArray;
1215  }
1216  static bool classof(const ArrayType *) { return true; }
1217};
1218
1219/// ConstantArrayType - This class represents the canonical version of
1220/// C arrays with a specified constant size.  For example, the canonical
1221/// type for 'int A[4 + 4*100]' is a ConstantArrayType where the element
1222/// type is 'int' and the size is 404.
1223class ConstantArrayType : public ArrayType {
1224  llvm::APInt Size; // Allows us to unique the type.
1225
1226  ConstantArrayType(QualType et, QualType can, const llvm::APInt &size,
1227                    ArraySizeModifier sm, unsigned tq)
1228    : ArrayType(ConstantArray, et, can, sm, tq),
1229      Size(size) {}
1230protected:
1231  ConstantArrayType(TypeClass tc, QualType et, QualType can,
1232                    const llvm::APInt &size, ArraySizeModifier sm, unsigned tq)
1233    : ArrayType(tc, et, can, sm, tq), Size(size) {}
1234  friend class ASTContext;  // ASTContext creates these.
1235public:
1236  const llvm::APInt &getSize() const { return Size; }
1237  virtual void getAsStringInternal(std::string &InnerString,
1238                                   const PrintingPolicy &Policy) const;
1239
1240  void Profile(llvm::FoldingSetNodeID &ID) {
1241    Profile(ID, getElementType(), getSize(),
1242            getSizeModifier(), getIndexTypeCVRQualifiers());
1243  }
1244  static void Profile(llvm::FoldingSetNodeID &ID, QualType ET,
1245                      const llvm::APInt &ArraySize, ArraySizeModifier SizeMod,
1246                      unsigned TypeQuals) {
1247    ID.AddPointer(ET.getAsOpaquePtr());
1248    ID.AddInteger(ArraySize.getZExtValue());
1249    ID.AddInteger(SizeMod);
1250    ID.AddInteger(TypeQuals);
1251  }
1252  static bool classof(const Type *T) {
1253    return T->getTypeClass() == ConstantArray ||
1254           T->getTypeClass() == ConstantArrayWithExpr ||
1255           T->getTypeClass() == ConstantArrayWithoutExpr;
1256  }
1257  static bool classof(const ConstantArrayType *) { return true; }
1258};
1259
1260/// ConstantArrayWithExprType - This class represents C arrays with a
1261/// constant size specified by means of an integer constant expression.
1262/// For example 'int A[sizeof(int)]' has ConstantArrayWithExprType where
1263/// the element type is 'int' and the size expression is 'sizeof(int)'.
1264/// These types are non-canonical.
1265class ConstantArrayWithExprType : public ConstantArrayType {
1266  /// SizeExpr - The ICE occurring in the concrete syntax.
1267  Expr *SizeExpr;
1268  /// Brackets - The left and right array brackets.
1269  SourceRange Brackets;
1270
1271  ConstantArrayWithExprType(QualType et, QualType can,
1272                            const llvm::APInt &size, Expr *e,
1273                            ArraySizeModifier sm, unsigned tq,
1274                            SourceRange brackets)
1275    : ConstantArrayType(ConstantArrayWithExpr, et, can, size, sm, tq),
1276      SizeExpr(e), Brackets(brackets) {}
1277  friend class ASTContext;  // ASTContext creates these.
1278  virtual void Destroy(ASTContext& C);
1279
1280public:
1281  Expr *getSizeExpr() const { return SizeExpr; }
1282  SourceRange getBracketsRange() const { return Brackets; }
1283  SourceLocation getLBracketLoc() const { return Brackets.getBegin(); }
1284  SourceLocation getRBracketLoc() const { return Brackets.getEnd(); }
1285
1286  virtual void getAsStringInternal(std::string &InnerString,
1287                                   const PrintingPolicy &Policy) const;
1288
1289  static bool classof(const Type *T) {
1290    return T->getTypeClass() == ConstantArrayWithExpr;
1291  }
1292  static bool classof(const ConstantArrayWithExprType *) { return true; }
1293
1294  void Profile(llvm::FoldingSetNodeID &ID) {
1295    assert(0 && "Cannot unique ConstantArrayWithExprTypes.");
1296  }
1297};
1298
1299/// ConstantArrayWithoutExprType - This class represents C arrays with a
1300/// constant size that was not specified by an integer constant expression,
1301/// but inferred by static semantics.
1302/// For example 'int A[] = { 0, 1, 2 }' has ConstantArrayWithoutExprType.
1303/// These types are non-canonical: the corresponding canonical type,
1304/// having the size specified in an APInt object, is a ConstantArrayType.
1305class ConstantArrayWithoutExprType : public ConstantArrayType {
1306
1307  ConstantArrayWithoutExprType(QualType et, QualType can,
1308                               const llvm::APInt &size,
1309                               ArraySizeModifier sm, unsigned tq)
1310    : ConstantArrayType(ConstantArrayWithoutExpr, et, can, size, sm, tq) {}
1311  friend class ASTContext;  // ASTContext creates these.
1312
1313public:
1314  virtual void getAsStringInternal(std::string &InnerString,
1315                                   const PrintingPolicy &Policy) const;
1316
1317  static bool classof(const Type *T) {
1318    return T->getTypeClass() == ConstantArrayWithoutExpr;
1319  }
1320  static bool classof(const ConstantArrayWithoutExprType *) { return true; }
1321
1322  void Profile(llvm::FoldingSetNodeID &ID) {
1323    assert(0 && "Cannot unique ConstantArrayWithoutExprTypes.");
1324  }
1325};
1326
1327/// IncompleteArrayType - This class represents C arrays with an unspecified
1328/// size.  For example 'int A[]' has an IncompleteArrayType where the element
1329/// type is 'int' and the size is unspecified.
1330class IncompleteArrayType : public ArrayType {
1331
1332  IncompleteArrayType(QualType et, QualType can,
1333                      ArraySizeModifier sm, unsigned tq)
1334    : ArrayType(IncompleteArray, et, can, sm, tq) {}
1335  friend class ASTContext;  // ASTContext creates these.
1336public:
1337  virtual void getAsStringInternal(std::string &InnerString,
1338                                   const PrintingPolicy &Policy) const;
1339
1340  static bool classof(const Type *T) {
1341    return T->getTypeClass() == IncompleteArray;
1342  }
1343  static bool classof(const IncompleteArrayType *) { return true; }
1344
1345  friend class StmtIteratorBase;
1346
1347  void Profile(llvm::FoldingSetNodeID &ID) {
1348    Profile(ID, getElementType(), getSizeModifier(),
1349            getIndexTypeCVRQualifiers());
1350  }
1351
1352  static void Profile(llvm::FoldingSetNodeID &ID, QualType ET,
1353                      ArraySizeModifier SizeMod, unsigned TypeQuals) {
1354    ID.AddPointer(ET.getAsOpaquePtr());
1355    ID.AddInteger(SizeMod);
1356    ID.AddInteger(TypeQuals);
1357  }
1358};
1359
1360/// VariableArrayType - This class represents C arrays with a specified size
1361/// which is not an integer-constant-expression.  For example, 'int s[x+foo()]'.
1362/// Since the size expression is an arbitrary expression, we store it as such.
1363///
1364/// Note: VariableArrayType's aren't uniqued (since the expressions aren't) and
1365/// should not be: two lexically equivalent variable array types could mean
1366/// different things, for example, these variables do not have the same type
1367/// dynamically:
1368///
1369/// void foo(int x) {
1370///   int Y[x];
1371///   ++x;
1372///   int Z[x];
1373/// }
1374///
1375class VariableArrayType : public ArrayType {
1376  /// SizeExpr - An assignment expression. VLA's are only permitted within
1377  /// a function block.
1378  Stmt *SizeExpr;
1379  /// Brackets - The left and right array brackets.
1380  SourceRange Brackets;
1381
1382  VariableArrayType(QualType et, QualType can, Expr *e,
1383                    ArraySizeModifier sm, unsigned tq,
1384                    SourceRange brackets)
1385    : ArrayType(VariableArray, et, can, sm, tq),
1386      SizeExpr((Stmt*) e), Brackets(brackets) {}
1387  friend class ASTContext;  // ASTContext creates these.
1388  virtual void Destroy(ASTContext& C);
1389
1390public:
1391  Expr *getSizeExpr() const {
1392    // We use C-style casts instead of cast<> here because we do not wish
1393    // to have a dependency of Type.h on Stmt.h/Expr.h.
1394    return (Expr*) SizeExpr;
1395  }
1396  SourceRange getBracketsRange() const { return Brackets; }
1397  SourceLocation getLBracketLoc() const { return Brackets.getBegin(); }
1398  SourceLocation getRBracketLoc() const { return Brackets.getEnd(); }
1399
1400  virtual void getAsStringInternal(std::string &InnerString,
1401                                   const PrintingPolicy &Policy) const;
1402
1403  static bool classof(const Type *T) {
1404    return T->getTypeClass() == VariableArray;
1405  }
1406  static bool classof(const VariableArrayType *) { return true; }
1407
1408  friend class StmtIteratorBase;
1409
1410  void Profile(llvm::FoldingSetNodeID &ID) {
1411    assert(0 && "Cannnot unique VariableArrayTypes.");
1412  }
1413};
1414
1415/// DependentSizedArrayType - This type represents an array type in
1416/// C++ whose size is a value-dependent expression. For example:
1417/// @code
1418/// template<typename T, int Size>
1419/// class array {
1420///   T data[Size];
1421/// };
1422/// @endcode
1423/// For these types, we won't actually know what the array bound is
1424/// until template instantiation occurs, at which point this will
1425/// become either a ConstantArrayType or a VariableArrayType.
1426class DependentSizedArrayType : public ArrayType {
1427  ASTContext &Context;
1428
1429  /// SizeExpr - An assignment expression that will instantiate to the
1430  /// size of the array.
1431  Stmt *SizeExpr;
1432  /// Brackets - The left and right array brackets.
1433  SourceRange Brackets;
1434
1435  DependentSizedArrayType(ASTContext &Context, QualType et, QualType can,
1436                          Expr *e, ArraySizeModifier sm, unsigned tq,
1437                          SourceRange brackets)
1438    : ArrayType(DependentSizedArray, et, can, sm, tq),
1439      Context(Context), SizeExpr((Stmt*) e), Brackets(brackets) {}
1440  friend class ASTContext;  // ASTContext creates these.
1441  virtual void Destroy(ASTContext& C);
1442
1443public:
1444  Expr *getSizeExpr() const {
1445    // We use C-style casts instead of cast<> here because we do not wish
1446    // to have a dependency of Type.h on Stmt.h/Expr.h.
1447    return (Expr*) SizeExpr;
1448  }
1449  SourceRange getBracketsRange() const { return Brackets; }
1450  SourceLocation getLBracketLoc() const { return Brackets.getBegin(); }
1451  SourceLocation getRBracketLoc() const { return Brackets.getEnd(); }
1452
1453  virtual void getAsStringInternal(std::string &InnerString,
1454                                   const PrintingPolicy &Policy) const;
1455
1456  static bool classof(const Type *T) {
1457    return T->getTypeClass() == DependentSizedArray;
1458  }
1459  static bool classof(const DependentSizedArrayType *) { return true; }
1460
1461  friend class StmtIteratorBase;
1462
1463
1464  void Profile(llvm::FoldingSetNodeID &ID) {
1465    Profile(ID, Context, getElementType(),
1466            getSizeModifier(), getIndexTypeCVRQualifiers(), getSizeExpr());
1467  }
1468
1469  static void Profile(llvm::FoldingSetNodeID &ID, ASTContext &Context,
1470                      QualType ET, ArraySizeModifier SizeMod,
1471                      unsigned TypeQuals, Expr *E);
1472};
1473
1474/// DependentSizedExtVectorType - This type represent an extended vector type
1475/// where either the type or size is dependent. For example:
1476/// @code
1477/// template<typename T, int Size>
1478/// class vector {
1479///   typedef T __attribute__((ext_vector_type(Size))) type;
1480/// }
1481/// @endcode
1482class DependentSizedExtVectorType : public Type, public llvm::FoldingSetNode {
1483  ASTContext &Context;
1484  Expr *SizeExpr;
1485  /// ElementType - The element type of the array.
1486  QualType ElementType;
1487  SourceLocation loc;
1488
1489  DependentSizedExtVectorType(ASTContext &Context, QualType ElementType,
1490                              QualType can, Expr *SizeExpr, SourceLocation loc)
1491    : Type (DependentSizedExtVector, can, true),
1492      Context(Context), SizeExpr(SizeExpr), ElementType(ElementType),
1493      loc(loc) {}
1494  friend class ASTContext;
1495  virtual void Destroy(ASTContext& C);
1496
1497public:
1498  Expr *getSizeExpr() const { return SizeExpr; }
1499  QualType getElementType() const { return ElementType; }
1500  SourceLocation getAttributeLoc() const { return loc; }
1501
1502  virtual void getAsStringInternal(std::string &InnerString,
1503                                   const PrintingPolicy &Policy) const;
1504
1505  static bool classof(const Type *T) {
1506    return T->getTypeClass() == DependentSizedExtVector;
1507  }
1508  static bool classof(const DependentSizedExtVectorType *) { return true; }
1509
1510  void Profile(llvm::FoldingSetNodeID &ID) {
1511    Profile(ID, Context, getElementType(), getSizeExpr());
1512  }
1513
1514  static void Profile(llvm::FoldingSetNodeID &ID, ASTContext &Context,
1515                      QualType ElementType, Expr *SizeExpr);
1516};
1517
1518
1519/// VectorType - GCC generic vector type. This type is created using
1520/// __attribute__((vector_size(n)), where "n" specifies the vector size in
1521/// bytes. Since the constructor takes the number of vector elements, the
1522/// client is responsible for converting the size into the number of elements.
1523class VectorType : public Type, public llvm::FoldingSetNode {
1524protected:
1525  /// ElementType - The element type of the vector.
1526  QualType ElementType;
1527
1528  /// NumElements - The number of elements in the vector.
1529  unsigned NumElements;
1530
1531  VectorType(QualType vecType, unsigned nElements, QualType canonType) :
1532    Type(Vector, canonType, vecType->isDependentType()),
1533    ElementType(vecType), NumElements(nElements) {}
1534  VectorType(TypeClass tc, QualType vecType, unsigned nElements,
1535             QualType canonType)
1536    : Type(tc, canonType, vecType->isDependentType()), ElementType(vecType),
1537      NumElements(nElements) {}
1538  friend class ASTContext;  // ASTContext creates these.
1539public:
1540
1541  QualType getElementType() const { return ElementType; }
1542  unsigned getNumElements() const { return NumElements; }
1543
1544  virtual void getAsStringInternal(std::string &InnerString,
1545                                   const PrintingPolicy &Policy) const;
1546
1547  void Profile(llvm::FoldingSetNodeID &ID) {
1548    Profile(ID, getElementType(), getNumElements(), getTypeClass());
1549  }
1550  static void Profile(llvm::FoldingSetNodeID &ID, QualType ElementType,
1551                      unsigned NumElements, TypeClass TypeClass) {
1552    ID.AddPointer(ElementType.getAsOpaquePtr());
1553    ID.AddInteger(NumElements);
1554    ID.AddInteger(TypeClass);
1555  }
1556  static bool classof(const Type *T) {
1557    return T->getTypeClass() == Vector || T->getTypeClass() == ExtVector;
1558  }
1559  static bool classof(const VectorType *) { return true; }
1560};
1561
1562/// ExtVectorType - Extended vector type. This type is created using
1563/// __attribute__((ext_vector_type(n)), where "n" is the number of elements.
1564/// Unlike vector_size, ext_vector_type is only allowed on typedef's. This
1565/// class enables syntactic extensions, like Vector Components for accessing
1566/// points, colors, and textures (modeled after OpenGL Shading Language).
1567class ExtVectorType : public VectorType {
1568  ExtVectorType(QualType vecType, unsigned nElements, QualType canonType) :
1569    VectorType(ExtVector, vecType, nElements, canonType) {}
1570  friend class ASTContext;  // ASTContext creates these.
1571public:
1572  static int getPointAccessorIdx(char c) {
1573    switch (c) {
1574    default: return -1;
1575    case 'x': return 0;
1576    case 'y': return 1;
1577    case 'z': return 2;
1578    case 'w': return 3;
1579    }
1580  }
1581  static int getNumericAccessorIdx(char c) {
1582    switch (c) {
1583      default: return -1;
1584      case '0': return 0;
1585      case '1': return 1;
1586      case '2': return 2;
1587      case '3': return 3;
1588      case '4': return 4;
1589      case '5': return 5;
1590      case '6': return 6;
1591      case '7': return 7;
1592      case '8': return 8;
1593      case '9': return 9;
1594      case 'A':
1595      case 'a': return 10;
1596      case 'B':
1597      case 'b': return 11;
1598      case 'C':
1599      case 'c': return 12;
1600      case 'D':
1601      case 'd': return 13;
1602      case 'E':
1603      case 'e': return 14;
1604      case 'F':
1605      case 'f': return 15;
1606    }
1607  }
1608
1609  static int getAccessorIdx(char c) {
1610    if (int idx = getPointAccessorIdx(c)+1) return idx-1;
1611    return getNumericAccessorIdx(c);
1612  }
1613
1614  bool isAccessorWithinNumElements(char c) const {
1615    if (int idx = getAccessorIdx(c)+1)
1616      return unsigned(idx-1) < NumElements;
1617    return false;
1618  }
1619  virtual void getAsStringInternal(std::string &InnerString,
1620                                   const PrintingPolicy &Policy) const;
1621
1622  static bool classof(const Type *T) {
1623    return T->getTypeClass() == ExtVector;
1624  }
1625  static bool classof(const ExtVectorType *) { return true; }
1626};
1627
1628/// FunctionType - C99 6.7.5.3 - Function Declarators.  This is the common base
1629/// class of FunctionNoProtoType and FunctionProtoType.
1630///
1631class FunctionType : public Type {
1632  /// SubClassData - This field is owned by the subclass, put here to pack
1633  /// tightly with the ivars in Type.
1634  bool SubClassData : 1;
1635
1636  /// TypeQuals - Used only by FunctionProtoType, put here to pack with the
1637  /// other bitfields.
1638  /// The qualifiers are part of FunctionProtoType because...
1639  ///
1640  /// C++ 8.3.5p4: The return type, the parameter type list and the
1641  /// cv-qualifier-seq, [...], are part of the function type.
1642  ///
1643  unsigned TypeQuals : 3;
1644
1645  /// NoReturn - Indicates if the function type is attribute noreturn.
1646  unsigned NoReturn : 1;
1647
1648  // The type returned by the function.
1649  QualType ResultType;
1650protected:
1651  FunctionType(TypeClass tc, QualType res, bool SubclassInfo,
1652               unsigned typeQuals, QualType Canonical, bool Dependent,
1653               bool noReturn = false)
1654    : Type(tc, Canonical, Dependent),
1655      SubClassData(SubclassInfo), TypeQuals(typeQuals), NoReturn(noReturn),
1656      ResultType(res) {}
1657  bool getSubClassData() const { return SubClassData; }
1658  unsigned getTypeQuals() const { return TypeQuals; }
1659public:
1660
1661  QualType getResultType() const { return ResultType; }
1662  bool getNoReturnAttr() const { return NoReturn; }
1663
1664
1665  static bool classof(const Type *T) {
1666    return T->getTypeClass() == FunctionNoProto ||
1667           T->getTypeClass() == FunctionProto;
1668  }
1669  static bool classof(const FunctionType *) { return true; }
1670};
1671
1672/// FunctionNoProtoType - Represents a K&R-style 'int foo()' function, which has
1673/// no information available about its arguments.
1674class FunctionNoProtoType : public FunctionType, public llvm::FoldingSetNode {
1675  FunctionNoProtoType(QualType Result, QualType Canonical,
1676                      bool NoReturn = false)
1677    : FunctionType(FunctionNoProto, Result, false, 0, Canonical,
1678                   /*Dependent=*/false, NoReturn) {}
1679  friend class ASTContext;  // ASTContext creates these.
1680public:
1681  // No additional state past what FunctionType provides.
1682
1683  virtual void getAsStringInternal(std::string &InnerString,
1684                                   const PrintingPolicy &Policy) const;
1685
1686  void Profile(llvm::FoldingSetNodeID &ID) {
1687    Profile(ID, getResultType(), getNoReturnAttr());
1688  }
1689  static void Profile(llvm::FoldingSetNodeID &ID, QualType ResultType,
1690                      bool NoReturn) {
1691    ID.AddInteger(NoReturn);
1692    ID.AddPointer(ResultType.getAsOpaquePtr());
1693  }
1694
1695  static bool classof(const Type *T) {
1696    return T->getTypeClass() == FunctionNoProto;
1697  }
1698  static bool classof(const FunctionNoProtoType *) { return true; }
1699};
1700
1701/// FunctionProtoType - Represents a prototype with argument type info, e.g.
1702/// 'int foo(int)' or 'int foo(void)'.  'void' is represented as having no
1703/// arguments, not as having a single void argument. Such a type can have an
1704/// exception specification, but this specification is not part of the canonical
1705/// type.
1706class FunctionProtoType : public FunctionType, public llvm::FoldingSetNode {
1707  /// hasAnyDependentType - Determine whether there are any dependent
1708  /// types within the arguments passed in.
1709  static bool hasAnyDependentType(const QualType *ArgArray, unsigned numArgs) {
1710    for (unsigned Idx = 0; Idx < numArgs; ++Idx)
1711      if (ArgArray[Idx]->isDependentType())
1712    return true;
1713
1714    return false;
1715  }
1716
1717  FunctionProtoType(QualType Result, const QualType *ArgArray, unsigned numArgs,
1718                    bool isVariadic, unsigned typeQuals, bool hasExs,
1719                    bool hasAnyExs, const QualType *ExArray,
1720                    unsigned numExs, QualType Canonical, bool NoReturn)
1721    : FunctionType(FunctionProto, Result, isVariadic, typeQuals, Canonical,
1722                   (Result->isDependentType() ||
1723                    hasAnyDependentType(ArgArray, numArgs)), NoReturn),
1724      NumArgs(numArgs), NumExceptions(numExs), HasExceptionSpec(hasExs),
1725      AnyExceptionSpec(hasAnyExs) {
1726    // Fill in the trailing argument array.
1727    QualType *ArgInfo = reinterpret_cast<QualType*>(this+1);
1728    for (unsigned i = 0; i != numArgs; ++i)
1729      ArgInfo[i] = ArgArray[i];
1730    // Fill in the exception array.
1731    QualType *Ex = ArgInfo + numArgs;
1732    for (unsigned i = 0; i != numExs; ++i)
1733      Ex[i] = ExArray[i];
1734  }
1735
1736  /// NumArgs - The number of arguments this function has, not counting '...'.
1737  unsigned NumArgs : 20;
1738
1739  /// NumExceptions - The number of types in the exception spec, if any.
1740  unsigned NumExceptions : 10;
1741
1742  /// HasExceptionSpec - Whether this function has an exception spec at all.
1743  bool HasExceptionSpec : 1;
1744
1745  /// AnyExceptionSpec - Whether this function has a throw(...) spec.
1746  bool AnyExceptionSpec : 1;
1747
1748  /// ArgInfo - There is an variable size array after the class in memory that
1749  /// holds the argument types.
1750
1751  /// Exceptions - There is another variable size array after ArgInfo that
1752  /// holds the exception types.
1753
1754  friend class ASTContext;  // ASTContext creates these.
1755
1756public:
1757  unsigned getNumArgs() const { return NumArgs; }
1758  QualType getArgType(unsigned i) const {
1759    assert(i < NumArgs && "Invalid argument number!");
1760    return arg_type_begin()[i];
1761  }
1762
1763  bool hasExceptionSpec() const { return HasExceptionSpec; }
1764  bool hasAnyExceptionSpec() const { return AnyExceptionSpec; }
1765  unsigned getNumExceptions() const { return NumExceptions; }
1766  QualType getExceptionType(unsigned i) const {
1767    assert(i < NumExceptions && "Invalid exception number!");
1768    return exception_begin()[i];
1769  }
1770  bool hasEmptyExceptionSpec() const {
1771    return hasExceptionSpec() && !hasAnyExceptionSpec() &&
1772      getNumExceptions() == 0;
1773  }
1774
1775  bool isVariadic() const { return getSubClassData(); }
1776  unsigned getTypeQuals() const { return FunctionType::getTypeQuals(); }
1777
1778  typedef const QualType *arg_type_iterator;
1779  arg_type_iterator arg_type_begin() const {
1780    return reinterpret_cast<const QualType *>(this+1);
1781  }
1782  arg_type_iterator arg_type_end() const { return arg_type_begin()+NumArgs; }
1783
1784  typedef const QualType *exception_iterator;
1785  exception_iterator exception_begin() const {
1786    // exceptions begin where arguments end
1787    return arg_type_end();
1788  }
1789  exception_iterator exception_end() const {
1790    return exception_begin() + NumExceptions;
1791  }
1792
1793  virtual void getAsStringInternal(std::string &InnerString,
1794                                   const PrintingPolicy &Policy) const;
1795
1796  static bool classof(const Type *T) {
1797    return T->getTypeClass() == FunctionProto;
1798  }
1799  static bool classof(const FunctionProtoType *) { return true; }
1800
1801  void Profile(llvm::FoldingSetNodeID &ID);
1802  static void Profile(llvm::FoldingSetNodeID &ID, QualType Result,
1803                      arg_type_iterator ArgTys, unsigned NumArgs,
1804                      bool isVariadic, unsigned TypeQuals,
1805                      bool hasExceptionSpec, bool anyExceptionSpec,
1806                      unsigned NumExceptions, exception_iterator Exs,
1807                      bool NoReturn);
1808};
1809
1810
1811class TypedefType : public Type {
1812  TypedefDecl *Decl;
1813protected:
1814  TypedefType(TypeClass tc, TypedefDecl *D, QualType can)
1815    : Type(tc, can, can->isDependentType()), Decl(D) {
1816    assert(!isa<TypedefType>(can) && "Invalid canonical type");
1817  }
1818  friend class ASTContext;  // ASTContext creates these.
1819public:
1820
1821  TypedefDecl *getDecl() const { return Decl; }
1822
1823  /// LookThroughTypedefs - Return the ultimate type this typedef corresponds to
1824  /// potentially looking through *all* consecutive typedefs.  This returns the
1825  /// sum of the type qualifiers, so if you have:
1826  ///   typedef const int A;
1827  ///   typedef volatile A B;
1828  /// looking through the typedefs for B will give you "const volatile A".
1829  QualType LookThroughTypedefs() const;
1830
1831  virtual void getAsStringInternal(std::string &InnerString,
1832                                   const PrintingPolicy &Policy) const;
1833
1834  static bool classof(const Type *T) { return T->getTypeClass() == Typedef; }
1835  static bool classof(const TypedefType *) { return true; }
1836};
1837
1838/// TypeOfExprType (GCC extension).
1839class TypeOfExprType : public Type {
1840  Expr *TOExpr;
1841
1842protected:
1843  TypeOfExprType(Expr *E, QualType can = QualType());
1844  friend class ASTContext;  // ASTContext creates these.
1845public:
1846  Expr *getUnderlyingExpr() const { return TOExpr; }
1847
1848  virtual void getAsStringInternal(std::string &InnerString,
1849                                   const PrintingPolicy &Policy) const;
1850
1851  static bool classof(const Type *T) { return T->getTypeClass() == TypeOfExpr; }
1852  static bool classof(const TypeOfExprType *) { return true; }
1853};
1854
1855/// Subclass of TypeOfExprType that is used for canonical, dependent
1856/// typeof(expr) types.
1857class DependentTypeOfExprType
1858  : public TypeOfExprType, public llvm::FoldingSetNode {
1859  ASTContext &Context;
1860
1861public:
1862  DependentTypeOfExprType(ASTContext &Context, Expr *E)
1863    : TypeOfExprType(E), Context(Context) { }
1864
1865  void Profile(llvm::FoldingSetNodeID &ID) {
1866    Profile(ID, Context, getUnderlyingExpr());
1867  }
1868
1869  static void Profile(llvm::FoldingSetNodeID &ID, ASTContext &Context,
1870                      Expr *E);
1871};
1872
1873/// TypeOfType (GCC extension).
1874class TypeOfType : public Type {
1875  QualType TOType;
1876  TypeOfType(QualType T, QualType can)
1877    : Type(TypeOf, can, T->isDependentType()), TOType(T) {
1878    assert(!isa<TypedefType>(can) && "Invalid canonical type");
1879  }
1880  friend class ASTContext;  // ASTContext creates these.
1881public:
1882  QualType getUnderlyingType() const { return TOType; }
1883
1884  virtual void getAsStringInternal(std::string &InnerString,
1885                                   const PrintingPolicy &Policy) const;
1886
1887  static bool classof(const Type *T) { return T->getTypeClass() == TypeOf; }
1888  static bool classof(const TypeOfType *) { return true; }
1889};
1890
1891/// DecltypeType (C++0x)
1892class DecltypeType : public Type {
1893  Expr *E;
1894
1895  // FIXME: We could get rid of UnderlyingType if we wanted to: We would have to
1896  // Move getDesugaredType to ASTContext so that it can call getDecltypeForExpr
1897  // from it.
1898  QualType UnderlyingType;
1899
1900protected:
1901  DecltypeType(Expr *E, QualType underlyingType, QualType can = QualType());
1902  friend class ASTContext;  // ASTContext creates these.
1903public:
1904  Expr *getUnderlyingExpr() const { return E; }
1905  QualType getUnderlyingType() const { return UnderlyingType; }
1906
1907  virtual void getAsStringInternal(std::string &InnerString,
1908                                   const PrintingPolicy &Policy) const;
1909
1910  static bool classof(const Type *T) { return T->getTypeClass() == Decltype; }
1911  static bool classof(const DecltypeType *) { return true; }
1912};
1913
1914/// Subclass of DecltypeType that is used for canonical, dependent
1915/// C++0x decltype types.
1916class DependentDecltypeType : public DecltypeType, public llvm::FoldingSetNode {
1917  ASTContext &Context;
1918
1919public:
1920  DependentDecltypeType(ASTContext &Context, Expr *E);
1921
1922  void Profile(llvm::FoldingSetNodeID &ID) {
1923    Profile(ID, Context, getUnderlyingExpr());
1924  }
1925
1926  static void Profile(llvm::FoldingSetNodeID &ID, ASTContext &Context,
1927                      Expr *E);
1928};
1929
1930class TagType : public Type {
1931  /// Stores the TagDecl associated with this type. The decl will
1932  /// point to the TagDecl that actually defines the entity (or is a
1933  /// definition in progress), if there is such a definition. The
1934  /// single-bit value will be non-zero when this tag is in the
1935  /// process of being defined.
1936  mutable llvm::PointerIntPair<TagDecl *, 1> decl;
1937  friend class ASTContext;
1938  friend class TagDecl;
1939
1940protected:
1941  TagType(TypeClass TC, TagDecl *D, QualType can);
1942
1943public:
1944  TagDecl *getDecl() const { return decl.getPointer(); }
1945
1946  /// @brief Determines whether this type is in the process of being
1947  /// defined.
1948  bool isBeingDefined() const { return decl.getInt(); }
1949  void setBeingDefined(bool Def) const { decl.setInt(Def? 1 : 0); }
1950
1951  virtual void getAsStringInternal(std::string &InnerString,
1952                                   const PrintingPolicy &Policy) const;
1953
1954  static bool classof(const Type *T) {
1955    return T->getTypeClass() >= TagFirst && T->getTypeClass() <= TagLast;
1956  }
1957  static bool classof(const TagType *) { return true; }
1958  static bool classof(const RecordType *) { return true; }
1959  static bool classof(const EnumType *) { return true; }
1960};
1961
1962/// RecordType - This is a helper class that allows the use of isa/cast/dyncast
1963/// to detect TagType objects of structs/unions/classes.
1964class RecordType : public TagType {
1965protected:
1966  explicit RecordType(RecordDecl *D)
1967    : TagType(Record, reinterpret_cast<TagDecl*>(D), QualType()) { }
1968  explicit RecordType(TypeClass TC, RecordDecl *D)
1969    : TagType(TC, reinterpret_cast<TagDecl*>(D), QualType()) { }
1970  friend class ASTContext;   // ASTContext creates these.
1971public:
1972
1973  RecordDecl *getDecl() const {
1974    return reinterpret_cast<RecordDecl*>(TagType::getDecl());
1975  }
1976
1977  // FIXME: This predicate is a helper to QualType/Type. It needs to
1978  // recursively check all fields for const-ness. If any field is declared
1979  // const, it needs to return false.
1980  bool hasConstFields() const { return false; }
1981
1982  // FIXME: RecordType needs to check when it is created that all fields are in
1983  // the same address space, and return that.
1984  unsigned getAddressSpace() const { return 0; }
1985
1986  static bool classof(const TagType *T);
1987  static bool classof(const Type *T) {
1988    return isa<TagType>(T) && classof(cast<TagType>(T));
1989  }
1990  static bool classof(const RecordType *) { return true; }
1991};
1992
1993/// EnumType - This is a helper class that allows the use of isa/cast/dyncast
1994/// to detect TagType objects of enums.
1995class EnumType : public TagType {
1996  explicit EnumType(EnumDecl *D)
1997    : TagType(Enum, reinterpret_cast<TagDecl*>(D), QualType()) { }
1998  friend class ASTContext;   // ASTContext creates these.
1999public:
2000
2001  EnumDecl *getDecl() const {
2002    return reinterpret_cast<EnumDecl*>(TagType::getDecl());
2003  }
2004
2005  static bool classof(const TagType *T);
2006  static bool classof(const Type *T) {
2007    return isa<TagType>(T) && classof(cast<TagType>(T));
2008  }
2009  static bool classof(const EnumType *) { return true; }
2010};
2011
2012/// ElaboratedType - A non-canonical type used to represents uses of
2013/// elaborated type specifiers in C++.  For example:
2014///
2015///   void foo(union MyUnion);
2016///            ^^^^^^^^^^^^^
2017///
2018/// At the moment, for efficiency we do not create elaborated types in
2019/// C, since outside of typedefs all references to structs would
2020/// necessarily be elaborated.
2021class ElaboratedType : public Type, public llvm::FoldingSetNode {
2022public:
2023  enum TagKind {
2024    TK_struct,
2025    TK_union,
2026    TK_class,
2027    TK_enum
2028  };
2029
2030private:
2031  /// The tag that was used in this elaborated type specifier.
2032  TagKind Tag;
2033
2034  /// The underlying type.
2035  QualType UnderlyingType;
2036
2037  explicit ElaboratedType(QualType Ty, TagKind Tag, QualType Canon)
2038    : Type(Elaborated, Canon, Canon->isDependentType()),
2039      Tag(Tag), UnderlyingType(Ty) { }
2040  friend class ASTContext;   // ASTContext creates these.
2041
2042public:
2043  TagKind getTagKind() const { return Tag; }
2044  QualType getUnderlyingType() const { return UnderlyingType; }
2045
2046  static const char *getNameForTagKind(TagKind Kind) {
2047    switch (Kind) {
2048    default: assert(0 && "Unknown TagKind!");
2049    case TK_struct: return "struct";
2050    case TK_union:  return "union";
2051    case TK_class:  return "class";
2052    case TK_enum:   return "enum";
2053    }
2054  }
2055
2056  virtual void getAsStringInternal(std::string &InnerString,
2057                                   const PrintingPolicy &Policy) const;
2058
2059  void Profile(llvm::FoldingSetNodeID &ID) {
2060    Profile(ID, getUnderlyingType(), getTagKind());
2061  }
2062  static void Profile(llvm::FoldingSetNodeID &ID, QualType T, TagKind Tag) {
2063    ID.AddPointer(T.getAsOpaquePtr());
2064    ID.AddInteger(Tag);
2065  }
2066
2067  static bool classof(const ElaboratedType*) { return true; }
2068  static bool classof(const Type *T) { return T->getTypeClass() == Elaborated; }
2069};
2070
2071class TemplateTypeParmType : public Type, public llvm::FoldingSetNode {
2072  unsigned Depth : 15;
2073  unsigned Index : 16;
2074  unsigned ParameterPack : 1;
2075  IdentifierInfo *Name;
2076
2077  TemplateTypeParmType(unsigned D, unsigned I, bool PP, IdentifierInfo *N,
2078                       QualType Canon)
2079    : Type(TemplateTypeParm, Canon, /*Dependent=*/true),
2080      Depth(D), Index(I), ParameterPack(PP), Name(N) { }
2081
2082  TemplateTypeParmType(unsigned D, unsigned I, bool PP)
2083    : Type(TemplateTypeParm, QualType(this, 0), /*Dependent=*/true),
2084      Depth(D), Index(I), ParameterPack(PP), Name(0) { }
2085
2086  friend class ASTContext;  // ASTContext creates these
2087
2088public:
2089  unsigned getDepth() const { return Depth; }
2090  unsigned getIndex() const { return Index; }
2091  bool isParameterPack() const { return ParameterPack; }
2092  IdentifierInfo *getName() const { return Name; }
2093
2094  virtual void getAsStringInternal(std::string &InnerString,
2095                                   const PrintingPolicy &Policy) const;
2096
2097  void Profile(llvm::FoldingSetNodeID &ID) {
2098    Profile(ID, Depth, Index, ParameterPack, Name);
2099  }
2100
2101  static void Profile(llvm::FoldingSetNodeID &ID, unsigned Depth,
2102                      unsigned Index, bool ParameterPack,
2103                      IdentifierInfo *Name) {
2104    ID.AddInteger(Depth);
2105    ID.AddInteger(Index);
2106    ID.AddBoolean(ParameterPack);
2107    ID.AddPointer(Name);
2108  }
2109
2110  static bool classof(const Type *T) {
2111    return T->getTypeClass() == TemplateTypeParm;
2112  }
2113  static bool classof(const TemplateTypeParmType *T) { return true; }
2114};
2115
2116/// \brief Represents the type of a template specialization as written
2117/// in the source code.
2118///
2119/// Template specialization types represent the syntactic form of a
2120/// template-id that refers to a type, e.g., @c vector<int>. Some
2121/// template specialization types are syntactic sugar, whose canonical
2122/// type will point to some other type node that represents the
2123/// instantiation or class template specialization. For example, a
2124/// class template specialization type of @c vector<int> will refer to
2125/// a tag type for the instantiation
2126/// @c std::vector<int, std::allocator<int>>.
2127///
2128/// Other template specialization types, for which the template name
2129/// is dependent, may be canonical types. These types are always
2130/// dependent.
2131class TemplateSpecializationType
2132  : public Type, public llvm::FoldingSetNode {
2133
2134  // FIXME: Currently needed for profiling expressions; can we avoid this?
2135  ASTContext &Context;
2136
2137    /// \brief The name of the template being specialized.
2138  TemplateName Template;
2139
2140  /// \brief - The number of template arguments named in this class
2141  /// template specialization.
2142  unsigned NumArgs;
2143
2144  TemplateSpecializationType(ASTContext &Context,
2145                             TemplateName T,
2146                             const TemplateArgument *Args,
2147                             unsigned NumArgs, QualType Canon);
2148
2149  virtual void Destroy(ASTContext& C);
2150
2151  friend class ASTContext;  // ASTContext creates these
2152
2153public:
2154  /// \brief Determine whether any of the given template arguments are
2155  /// dependent.
2156  static bool anyDependentTemplateArguments(const TemplateArgument *Args,
2157                                            unsigned NumArgs);
2158
2159  /// \brief Print a template argument list, including the '<' and '>'
2160  /// enclosing the template arguments.
2161  static std::string PrintTemplateArgumentList(const TemplateArgument *Args,
2162                                               unsigned NumArgs,
2163                                               const PrintingPolicy &Policy);
2164
2165  typedef const TemplateArgument * iterator;
2166
2167  iterator begin() const { return getArgs(); }
2168  iterator end() const;
2169
2170  /// \brief Retrieve the name of the template that we are specializing.
2171  TemplateName getTemplateName() const { return Template; }
2172
2173  /// \brief Retrieve the template arguments.
2174  const TemplateArgument *getArgs() const {
2175    return reinterpret_cast<const TemplateArgument *>(this + 1);
2176  }
2177
2178  /// \brief Retrieve the number of template arguments.
2179  unsigned getNumArgs() const { return NumArgs; }
2180
2181  /// \brief Retrieve a specific template argument as a type.
2182  /// \precondition @c isArgType(Arg)
2183  const TemplateArgument &getArg(unsigned Idx) const;
2184
2185  virtual void getAsStringInternal(std::string &InnerString,
2186                                   const PrintingPolicy &Policy) const;
2187
2188  void Profile(llvm::FoldingSetNodeID &ID) {
2189    Profile(ID, Template, getArgs(), NumArgs, Context);
2190  }
2191
2192  static void Profile(llvm::FoldingSetNodeID &ID, TemplateName T,
2193                      const TemplateArgument *Args, unsigned NumArgs,
2194                      ASTContext &Context);
2195
2196  static bool classof(const Type *T) {
2197    return T->getTypeClass() == TemplateSpecialization;
2198  }
2199  static bool classof(const TemplateSpecializationType *T) { return true; }
2200};
2201
2202/// \brief Represents a type that was referred to via a qualified
2203/// name, e.g., N::M::type.
2204///
2205/// This type is used to keep track of a type name as written in the
2206/// source code, including any nested-name-specifiers. The type itself
2207/// is always "sugar", used to express what was written in the source
2208/// code but containing no additional semantic information.
2209class QualifiedNameType : public Type, public llvm::FoldingSetNode {
2210  /// \brief The nested name specifier containing the qualifier.
2211  NestedNameSpecifier *NNS;
2212
2213  /// \brief The type that this qualified name refers to.
2214  QualType NamedType;
2215
2216  QualifiedNameType(NestedNameSpecifier *NNS, QualType NamedType,
2217                    QualType CanonType)
2218    : Type(QualifiedName, CanonType, NamedType->isDependentType()),
2219      NNS(NNS), NamedType(NamedType) { }
2220
2221  friend class ASTContext;  // ASTContext creates these
2222
2223public:
2224  /// \brief Retrieve the qualification on this type.
2225  NestedNameSpecifier *getQualifier() const { return NNS; }
2226
2227  /// \brief Retrieve the type named by the qualified-id.
2228  QualType getNamedType() const { return NamedType; }
2229
2230  virtual void getAsStringInternal(std::string &InnerString,
2231                                   const PrintingPolicy &Policy) const;
2232
2233  void Profile(llvm::FoldingSetNodeID &ID) {
2234    Profile(ID, NNS, NamedType);
2235  }
2236
2237  static void Profile(llvm::FoldingSetNodeID &ID, NestedNameSpecifier *NNS,
2238                      QualType NamedType) {
2239    ID.AddPointer(NNS);
2240    NamedType.Profile(ID);
2241  }
2242
2243  static bool classof(const Type *T) {
2244    return T->getTypeClass() == QualifiedName;
2245  }
2246  static bool classof(const QualifiedNameType *T) { return true; }
2247};
2248
2249/// \brief Represents a 'typename' specifier that names a type within
2250/// a dependent type, e.g., "typename T::type".
2251///
2252/// TypenameType has a very similar structure to QualifiedNameType,
2253/// which also involves a nested-name-specifier following by a type,
2254/// and (FIXME!) both can even be prefixed by the 'typename'
2255/// keyword. However, the two types serve very different roles:
2256/// QualifiedNameType is a non-semantic type that serves only as sugar
2257/// to show how a particular type was written in the source
2258/// code. TypenameType, on the other hand, only occurs when the
2259/// nested-name-specifier is dependent, such that we cannot resolve
2260/// the actual type until after instantiation.
2261class TypenameType : public Type, public llvm::FoldingSetNode {
2262  /// \brief The nested name specifier containing the qualifier.
2263  NestedNameSpecifier *NNS;
2264
2265  typedef llvm::PointerUnion<const IdentifierInfo *,
2266                             const TemplateSpecializationType *> NameType;
2267
2268  /// \brief The type that this typename specifier refers to.
2269  NameType Name;
2270
2271  TypenameType(NestedNameSpecifier *NNS, const IdentifierInfo *Name,
2272               QualType CanonType)
2273    : Type(Typename, CanonType, true), NNS(NNS), Name(Name) {
2274    assert(NNS->isDependent() &&
2275           "TypenameType requires a dependent nested-name-specifier");
2276  }
2277
2278  TypenameType(NestedNameSpecifier *NNS, const TemplateSpecializationType *Ty,
2279               QualType CanonType)
2280    : Type(Typename, CanonType, true), NNS(NNS), Name(Ty) {
2281    assert(NNS->isDependent() &&
2282           "TypenameType requires a dependent nested-name-specifier");
2283  }
2284
2285  friend class ASTContext;  // ASTContext creates these
2286
2287public:
2288  /// \brief Retrieve the qualification on this type.
2289  NestedNameSpecifier *getQualifier() const { return NNS; }
2290
2291  /// \brief Retrieve the type named by the typename specifier as an
2292  /// identifier.
2293  ///
2294  /// This routine will return a non-NULL identifier pointer when the
2295  /// form of the original typename was terminated by an identifier,
2296  /// e.g., "typename T::type".
2297  const IdentifierInfo *getIdentifier() const {
2298    return Name.dyn_cast<const IdentifierInfo *>();
2299  }
2300
2301  /// \brief Retrieve the type named by the typename specifier as a
2302  /// type specialization.
2303  const TemplateSpecializationType *getTemplateId() const {
2304    return Name.dyn_cast<const TemplateSpecializationType *>();
2305  }
2306
2307  virtual void getAsStringInternal(std::string &InnerString,
2308                                   const PrintingPolicy &Policy) const;
2309
2310  void Profile(llvm::FoldingSetNodeID &ID) {
2311    Profile(ID, NNS, Name);
2312  }
2313
2314  static void Profile(llvm::FoldingSetNodeID &ID, NestedNameSpecifier *NNS,
2315                      NameType Name) {
2316    ID.AddPointer(NNS);
2317    ID.AddPointer(Name.getOpaqueValue());
2318  }
2319
2320  static bool classof(const Type *T) {
2321    return T->getTypeClass() == Typename;
2322  }
2323  static bool classof(const TypenameType *T) { return true; }
2324};
2325
2326/// ObjCInterfaceType - Interfaces are the core concept in Objective-C for
2327/// object oriented design.  They basically correspond to C++ classes.  There
2328/// are two kinds of interface types, normal interfaces like "NSString" and
2329/// qualified interfaces, which are qualified with a protocol list like
2330/// "NSString<NSCopyable, NSAmazing>".
2331class ObjCInterfaceType : public Type, public llvm::FoldingSetNode {
2332  ObjCInterfaceDecl *Decl;
2333
2334  // List of protocols for this protocol conforming object type
2335  // List is sorted on protocol name. No protocol is enterred more than once.
2336  llvm::SmallVector<ObjCProtocolDecl*, 4> Protocols;
2337
2338  ObjCInterfaceType(ObjCInterfaceDecl *D,
2339                    ObjCProtocolDecl **Protos, unsigned NumP) :
2340    Type(ObjCInterface, QualType(), /*Dependent=*/false),
2341    Decl(D), Protocols(Protos, Protos+NumP) { }
2342  friend class ASTContext;  // ASTContext creates these.
2343public:
2344  ObjCInterfaceDecl *getDecl() const { return Decl; }
2345
2346  /// getNumProtocols - Return the number of qualifying protocols in this
2347  /// interface type, or 0 if there are none.
2348  unsigned getNumProtocols() const { return Protocols.size(); }
2349
2350  /// qual_iterator and friends: this provides access to the (potentially empty)
2351  /// list of protocols qualifying this interface.
2352  typedef llvm::SmallVector<ObjCProtocolDecl*, 8>::const_iterator qual_iterator;
2353  qual_iterator qual_begin() const { return Protocols.begin(); }
2354  qual_iterator qual_end() const   { return Protocols.end(); }
2355  bool qual_empty() const { return Protocols.size() == 0; }
2356
2357  virtual void getAsStringInternal(std::string &InnerString,
2358                                   const PrintingPolicy &Policy) const;
2359
2360  void Profile(llvm::FoldingSetNodeID &ID);
2361  static void Profile(llvm::FoldingSetNodeID &ID,
2362                      const ObjCInterfaceDecl *Decl,
2363                      ObjCProtocolDecl **protocols, unsigned NumProtocols);
2364
2365  static bool classof(const Type *T) {
2366    return T->getTypeClass() == ObjCInterface;
2367  }
2368  static bool classof(const ObjCInterfaceType *) { return true; }
2369};
2370
2371/// ObjCObjectPointerType - Used to represent 'id', 'Interface *', 'id <p>',
2372/// and 'Interface <p> *'.
2373///
2374/// Duplicate protocols are removed and protocol list is canonicalized to be in
2375/// alphabetical order.
2376class ObjCObjectPointerType : public Type, public llvm::FoldingSetNode {
2377  QualType PointeeType; // A builtin or interface type.
2378
2379  // List of protocols for this protocol conforming object type
2380  // List is sorted on protocol name. No protocol is entered more than once.
2381  llvm::SmallVector<ObjCProtocolDecl*, 8> Protocols;
2382
2383  ObjCObjectPointerType(QualType T, ObjCProtocolDecl **Protos, unsigned NumP) :
2384    Type(ObjCObjectPointer, QualType(), /*Dependent=*/false),
2385    PointeeType(T), Protocols(Protos, Protos+NumP) { }
2386  friend class ASTContext;  // ASTContext creates these.
2387
2388public:
2389  // Get the pointee type. Pointee will either be:
2390  // - a built-in type (for 'id' and 'Class').
2391  // - an interface type (for user-defined types).
2392  // - a TypedefType whose canonical type is an interface (as in 'T' below).
2393  //   For example: typedef NSObject T; T *var;
2394  QualType getPointeeType() const { return PointeeType; }
2395
2396  const ObjCInterfaceType *getInterfaceType() const {
2397    return PointeeType->getAs<ObjCInterfaceType>();
2398  }
2399  /// getInterfaceDecl - returns an interface decl for user-defined types.
2400  ObjCInterfaceDecl *getInterfaceDecl() const {
2401    return getInterfaceType() ? getInterfaceType()->getDecl() : 0;
2402  }
2403  /// isObjCIdType - true for "id".
2404  bool isObjCIdType() const {
2405    return getPointeeType()->isSpecificBuiltinType(BuiltinType::ObjCId) &&
2406           !Protocols.size();
2407  }
2408  /// isObjCClassType - true for "Class".
2409  bool isObjCClassType() const {
2410    return getPointeeType()->isSpecificBuiltinType(BuiltinType::ObjCClass) &&
2411           !Protocols.size();
2412  }
2413  /// isObjCQualifiedIdType - true for "id <p>".
2414  bool isObjCQualifiedIdType() const {
2415    return getPointeeType()->isSpecificBuiltinType(BuiltinType::ObjCId) &&
2416           Protocols.size();
2417  }
2418  /// isObjCQualifiedClassType - true for "Class <p>".
2419  bool isObjCQualifiedClassType() const {
2420    return getPointeeType()->isSpecificBuiltinType(BuiltinType::ObjCClass) &&
2421           Protocols.size();
2422  }
2423  /// qual_iterator and friends: this provides access to the (potentially empty)
2424  /// list of protocols qualifying this interface.
2425  typedef llvm::SmallVector<ObjCProtocolDecl*, 8>::const_iterator qual_iterator;
2426
2427  qual_iterator qual_begin() const { return Protocols.begin(); }
2428  qual_iterator qual_end() const   { return Protocols.end(); }
2429  bool qual_empty() const { return Protocols.size() == 0; }
2430
2431  /// getNumProtocols - Return the number of qualifying protocols in this
2432  /// interface type, or 0 if there are none.
2433  unsigned getNumProtocols() const { return Protocols.size(); }
2434
2435  void Profile(llvm::FoldingSetNodeID &ID);
2436  static void Profile(llvm::FoldingSetNodeID &ID, QualType T,
2437                      ObjCProtocolDecl **protocols, unsigned NumProtocols);
2438  virtual void getAsStringInternal(std::string &InnerString,
2439                                   const PrintingPolicy &Policy) const;
2440  static bool classof(const Type *T) {
2441    return T->getTypeClass() == ObjCObjectPointer;
2442  }
2443  static bool classof(const ObjCObjectPointerType *) { return true; }
2444};
2445
2446/// \brief An ObjC Protocol list that qualifies a type.
2447///
2448/// This is used only for keeping detailed type source information, it should
2449/// not participate in the semantics of the type system.
2450/// The protocol list is not canonicalized.
2451class ObjCProtocolListType : public Type, public llvm::FoldingSetNode {
2452  QualType BaseType;
2453
2454  // List of protocols for this protocol conforming object type.
2455  llvm::SmallVector<ObjCProtocolDecl*, 4> Protocols;
2456
2457  ObjCProtocolListType(QualType T, ObjCProtocolDecl **Protos, unsigned NumP) :
2458    Type(ObjCProtocolList, QualType(), /*Dependent=*/false),
2459    BaseType(T), Protocols(Protos, Protos+NumP) { }
2460  friend class ASTContext;  // ASTContext creates these.
2461
2462public:
2463  QualType getBaseType() const { return BaseType; }
2464
2465  /// \brief Provides access to the list of protocols qualifying the base type.
2466  typedef llvm::SmallVector<ObjCProtocolDecl*, 4>::const_iterator qual_iterator;
2467
2468  qual_iterator qual_begin() const { return Protocols.begin(); }
2469  qual_iterator qual_end() const   { return Protocols.end(); }
2470  bool qual_empty() const { return Protocols.size() == 0; }
2471
2472  /// \brief Return the number of qualifying protocols.
2473  unsigned getNumProtocols() const { return Protocols.size(); }
2474
2475  void Profile(llvm::FoldingSetNodeID &ID);
2476  static void Profile(llvm::FoldingSetNodeID &ID, QualType T,
2477                      ObjCProtocolDecl **protocols, unsigned NumProtocols);
2478  virtual void getAsStringInternal(std::string &InnerString,
2479                                   const PrintingPolicy &Policy) const;
2480  static bool classof(const Type *T) {
2481    return T->getTypeClass() == ObjCProtocolList;
2482  }
2483  static bool classof(const ObjCProtocolListType *) { return true; }
2484};
2485
2486/// A qualifier set is used to build a set of qualifiers.
2487class QualifierCollector : public Qualifiers {
2488  ASTContext *Context;
2489
2490public:
2491  QualifierCollector(Qualifiers Qs = Qualifiers())
2492    : Qualifiers(Qs), Context(0) {}
2493  QualifierCollector(ASTContext &Context, Qualifiers Qs = Qualifiers())
2494    : Qualifiers(Qs), Context(&Context) {}
2495
2496  void setContext(ASTContext &C) { Context = &C; }
2497
2498  /// Collect any qualifiers on the given type and return an
2499  /// unqualified type.
2500  const Type *strip(QualType QT) {
2501    addFastQualifiers(QT.getFastQualifiers());
2502    if (QT.hasNonFastQualifiers()) {
2503      const ExtQuals *EQ = QT.getExtQualsUnsafe();
2504      Context = &EQ->getContext();
2505      addQualifiers(EQ->getQualifiers());
2506      return EQ->getBaseType();
2507    }
2508    return QT.getTypePtrUnsafe();
2509  }
2510
2511  /// Apply the collected qualifiers to the given type.
2512  QualType apply(QualType QT) const;
2513
2514  /// Apply the collected qualifiers to the given type.
2515  QualType apply(const Type* T) const;
2516
2517};
2518
2519
2520// Inline function definitions.
2521
2522inline void QualType::removeConst() {
2523  removeFastQualifiers(Qualifiers::Const);
2524}
2525
2526inline void QualType::removeRestrict() {
2527  removeFastQualifiers(Qualifiers::Restrict);
2528}
2529
2530inline void QualType::removeVolatile() {
2531  QualifierCollector Qc;
2532  const Type *Ty = Qc.strip(*this);
2533  if (Qc.hasVolatile()) {
2534    Qc.removeVolatile();
2535    *this = Qc.apply(Ty);
2536  }
2537}
2538
2539inline void QualType::removeCVRQualifiers(unsigned Mask) {
2540  assert(!(Mask & ~Qualifiers::CVRMask) && "mask has non-CVR bits");
2541
2542  // Fast path: we don't need to touch the slow qualifiers.
2543  if (!(Mask & ~Qualifiers::FastMask)) {
2544    removeFastQualifiers(Mask);
2545    return;
2546  }
2547
2548  QualifierCollector Qc;
2549  const Type *Ty = Qc.strip(*this);
2550  Qc.removeCVRQualifiers(Mask);
2551  *this = Qc.apply(Ty);
2552}
2553
2554/// getAddressSpace - Return the address space of this type.
2555inline unsigned QualType::getAddressSpace() const {
2556  if (hasNonFastQualifiers()) {
2557    const ExtQuals *EQ = getExtQualsUnsafe();
2558    if (EQ->hasAddressSpace())
2559      return EQ->getAddressSpace();
2560  }
2561
2562  QualType CT = getTypePtr()->getCanonicalTypeInternal();
2563  if (CT.hasNonFastQualifiers()) {
2564    const ExtQuals *EQ = CT.getExtQualsUnsafe();
2565    if (EQ->hasAddressSpace())
2566      return EQ->getAddressSpace();
2567  }
2568
2569  if (const ArrayType *AT = dyn_cast<ArrayType>(CT))
2570    return AT->getElementType().getAddressSpace();
2571  if (const RecordType *RT = dyn_cast<RecordType>(CT))
2572    return RT->getAddressSpace();
2573  return 0;
2574}
2575
2576/// getObjCGCAttr - Return the gc attribute of this type.
2577inline Qualifiers::GC QualType::getObjCGCAttr() const {
2578  if (hasNonFastQualifiers()) {
2579    const ExtQuals *EQ = getExtQualsUnsafe();
2580    if (EQ->hasObjCGCAttr())
2581      return EQ->getObjCGCAttr();
2582  }
2583
2584  QualType CT = getTypePtr()->getCanonicalTypeInternal();
2585  if (CT.hasNonFastQualifiers()) {
2586    const ExtQuals *EQ = CT.getExtQualsUnsafe();
2587    if (EQ->hasObjCGCAttr())
2588      return EQ->getObjCGCAttr();
2589  }
2590
2591  if (const ArrayType *AT = dyn_cast<ArrayType>(CT))
2592      return AT->getElementType().getObjCGCAttr();
2593  if (const ObjCObjectPointerType *PT = CT->getAs<ObjCObjectPointerType>())
2594    return PT->getPointeeType().getObjCGCAttr();
2595  // We most look at all pointer types, not just pointer to interface types.
2596  if (const PointerType *PT = CT->getAs<PointerType>())
2597    return PT->getPointeeType().getObjCGCAttr();
2598  return Qualifiers::GCNone;
2599}
2600
2601  /// getNoReturnAttr - Returns true if the type has the noreturn attribute,
2602  /// false otherwise.
2603inline bool QualType::getNoReturnAttr() const {
2604  QualType CT = getTypePtr()->getCanonicalTypeInternal();
2605  if (const PointerType *PT = getTypePtr()->getAs<PointerType>()) {
2606    if (const FunctionType *FT = PT->getPointeeType()->getAs<FunctionType>())
2607      return FT->getNoReturnAttr();
2608  } else if (const FunctionType *FT = getTypePtr()->getAs<FunctionType>())
2609    return FT->getNoReturnAttr();
2610
2611  return false;
2612}
2613
2614/// isMoreQualifiedThan - Determine whether this type is more
2615/// qualified than the Other type. For example, "const volatile int"
2616/// is more qualified than "const int", "volatile int", and
2617/// "int". However, it is not more qualified than "const volatile
2618/// int".
2619inline bool QualType::isMoreQualifiedThan(QualType Other) const {
2620  // FIXME: work on arbitrary qualifiers
2621  unsigned MyQuals = this->getCVRQualifiers();
2622  unsigned OtherQuals = Other.getCVRQualifiers();
2623  if (getAddressSpace() != Other.getAddressSpace())
2624    return false;
2625  return MyQuals != OtherQuals && (MyQuals | OtherQuals) == MyQuals;
2626}
2627
2628/// isAtLeastAsQualifiedAs - Determine whether this type is at last
2629/// as qualified as the Other type. For example, "const volatile
2630/// int" is at least as qualified as "const int", "volatile int",
2631/// "int", and "const volatile int".
2632inline bool QualType::isAtLeastAsQualifiedAs(QualType Other) const {
2633  // FIXME: work on arbitrary qualifiers
2634  unsigned MyQuals = this->getCVRQualifiers();
2635  unsigned OtherQuals = Other.getCVRQualifiers();
2636  if (getAddressSpace() != Other.getAddressSpace())
2637    return false;
2638  return (MyQuals | OtherQuals) == MyQuals;
2639}
2640
2641/// getNonReferenceType - If Type is a reference type (e.g., const
2642/// int&), returns the type that the reference refers to ("const
2643/// int"). Otherwise, returns the type itself. This routine is used
2644/// throughout Sema to implement C++ 5p6:
2645///
2646///   If an expression initially has the type "reference to T" (8.3.2,
2647///   8.5.3), the type is adjusted to "T" prior to any further
2648///   analysis, the expression designates the object or function
2649///   denoted by the reference, and the expression is an lvalue.
2650inline QualType QualType::getNonReferenceType() const {
2651  if (const ReferenceType *RefType = (*this)->getAs<ReferenceType>())
2652    return RefType->getPointeeType();
2653  else
2654    return *this;
2655}
2656
2657inline const ObjCInterfaceType *Type::getAsPointerToObjCInterfaceType() const {
2658  if (const PointerType *PT = getAs<PointerType>())
2659    return PT->getPointeeType()->getAs<ObjCInterfaceType>();
2660  return 0;
2661}
2662
2663// NOTE: All of these methods use "getUnqualifiedType" to strip off address
2664// space qualifiers if present.
2665inline bool Type::isFunctionType() const {
2666  return isa<FunctionType>(CanonicalType.getUnqualifiedType());
2667}
2668inline bool Type::isPointerType() const {
2669  return isa<PointerType>(CanonicalType.getUnqualifiedType());
2670}
2671inline bool Type::isAnyPointerType() const {
2672  return isPointerType() || isObjCObjectPointerType();
2673}
2674inline bool Type::isBlockPointerType() const {
2675  return isa<BlockPointerType>(CanonicalType.getUnqualifiedType());
2676}
2677inline bool Type::isReferenceType() const {
2678  return isa<ReferenceType>(CanonicalType.getUnqualifiedType());
2679}
2680inline bool Type::isLValueReferenceType() const {
2681  return isa<LValueReferenceType>(CanonicalType.getUnqualifiedType());
2682}
2683inline bool Type::isRValueReferenceType() const {
2684  return isa<RValueReferenceType>(CanonicalType.getUnqualifiedType());
2685}
2686inline bool Type::isFunctionPointerType() const {
2687  if (const PointerType* T = getAs<PointerType>())
2688    return T->getPointeeType()->isFunctionType();
2689  else
2690    return false;
2691}
2692inline bool Type::isMemberPointerType() const {
2693  return isa<MemberPointerType>(CanonicalType.getUnqualifiedType());
2694}
2695inline bool Type::isMemberFunctionPointerType() const {
2696  if (const MemberPointerType* T = getAs<MemberPointerType>())
2697    return T->getPointeeType()->isFunctionType();
2698  else
2699    return false;
2700}
2701inline bool Type::isArrayType() const {
2702  return isa<ArrayType>(CanonicalType.getUnqualifiedType());
2703}
2704inline bool Type::isConstantArrayType() const {
2705  return isa<ConstantArrayType>(CanonicalType.getUnqualifiedType());
2706}
2707inline bool Type::isIncompleteArrayType() const {
2708  return isa<IncompleteArrayType>(CanonicalType.getUnqualifiedType());
2709}
2710inline bool Type::isVariableArrayType() const {
2711  return isa<VariableArrayType>(CanonicalType.getUnqualifiedType());
2712}
2713inline bool Type::isDependentSizedArrayType() const {
2714  return isa<DependentSizedArrayType>(CanonicalType.getUnqualifiedType());
2715}
2716inline bool Type::isRecordType() const {
2717  return isa<RecordType>(CanonicalType.getUnqualifiedType());
2718}
2719inline bool Type::isAnyComplexType() const {
2720  return isa<ComplexType>(CanonicalType.getUnqualifiedType());
2721}
2722inline bool Type::isVectorType() const {
2723  return isa<VectorType>(CanonicalType.getUnqualifiedType());
2724}
2725inline bool Type::isExtVectorType() const {
2726  return isa<ExtVectorType>(CanonicalType.getUnqualifiedType());
2727}
2728inline bool Type::isObjCObjectPointerType() const {
2729  return isa<ObjCObjectPointerType>(CanonicalType.getUnqualifiedType());
2730}
2731inline bool Type::isObjCInterfaceType() const {
2732  return isa<ObjCInterfaceType>(CanonicalType.getUnqualifiedType());
2733}
2734inline bool Type::isObjCQualifiedIdType() const {
2735  if (const ObjCObjectPointerType *OPT = getAs<ObjCObjectPointerType>())
2736    return OPT->isObjCQualifiedIdType();
2737  return false;
2738}
2739inline bool Type::isObjCQualifiedClassType() const {
2740  if (const ObjCObjectPointerType *OPT = getAs<ObjCObjectPointerType>())
2741    return OPT->isObjCQualifiedClassType();
2742  return false;
2743}
2744inline bool Type::isObjCIdType() const {
2745  if (const ObjCObjectPointerType *OPT = getAs<ObjCObjectPointerType>())
2746    return OPT->isObjCIdType();
2747  return false;
2748}
2749inline bool Type::isObjCClassType() const {
2750  if (const ObjCObjectPointerType *OPT = getAs<ObjCObjectPointerType>())
2751    return OPT->isObjCClassType();
2752  return false;
2753}
2754inline bool Type::isObjCBuiltinType() const {
2755  return isObjCIdType() || isObjCClassType();
2756}
2757inline bool Type::isTemplateTypeParmType() const {
2758  return isa<TemplateTypeParmType>(CanonicalType.getUnqualifiedType());
2759}
2760
2761inline bool Type::isSpecificBuiltinType(unsigned K) const {
2762  if (const BuiltinType *BT = getAs<BuiltinType>())
2763    if (BT->getKind() == (BuiltinType::Kind) K)
2764      return true;
2765  return false;
2766}
2767
2768/// \brief Determines whether this is a type for which one can define
2769/// an overloaded operator.
2770inline bool Type::isOverloadableType() const {
2771  return isDependentType() || isRecordType() || isEnumeralType();
2772}
2773
2774inline bool Type::hasPointerRepresentation() const {
2775  return (isPointerType() || isReferenceType() || isBlockPointerType() ||
2776          isObjCInterfaceType() || isObjCObjectPointerType() ||
2777          isObjCQualifiedInterfaceType() || isNullPtrType());
2778}
2779
2780inline bool Type::hasObjCPointerRepresentation() const {
2781  return (isObjCInterfaceType() || isObjCObjectPointerType() ||
2782          isObjCQualifiedInterfaceType());
2783}
2784
2785/// Insertion operator for diagnostics.  This allows sending QualType's into a
2786/// diagnostic with <<.
2787inline const DiagnosticBuilder &operator<<(const DiagnosticBuilder &DB,
2788                                           QualType T) {
2789  DB.AddTaggedVal(reinterpret_cast<intptr_t>(T.getAsOpaquePtr()),
2790                  Diagnostic::ak_qualtype);
2791  return DB;
2792}
2793
2794/// Member-template getAs<specific type>'.
2795template <typename T> const T *Type::getAs() const {
2796  // If this is directly a T type, return it.
2797  if (const T *Ty = dyn_cast<T>(this))
2798    return Ty;
2799
2800  // If the canonical form of this type isn't the right kind, reject it.
2801  if (!isa<T>(CanonicalType))
2802    return 0;
2803
2804  // If this is a typedef for the type, strip the typedef off without
2805  // losing all typedef information.
2806  return cast<T>(getDesugaredType());
2807}
2808
2809}  // end namespace clang
2810
2811#endif
2812