Type.h revision 6b304a0254a13f42390b865ff5ba668a49cc58ae
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  QualType getCanonicalTypeInternal() const { return CanonicalType; }
878  void dump() const;
879  virtual void getAsStringInternal(std::string &InnerString,
880                                   const PrintingPolicy &Policy) const = 0;
881  static bool classof(const Type *) { return true; }
882};
883
884template <> inline const TypedefType *Type::getAs() const {
885  return dyn_cast<TypedefType>(this);
886}
887
888// We can do canonical leaf types faster, because we don't have to
889// worry about preserving child type decoration.
890#define TYPE(Class, Base)
891#define LEAF_TYPE(Class) \
892template <> inline const Class##Type *Type::getAs() const { \
893  return dyn_cast<Class##Type>(CanonicalType); \
894}
895#include "clang/AST/TypeNodes.def"
896
897
898/// BuiltinType - This class is used for builtin types like 'int'.  Builtin
899/// types are always canonical and have a literal name field.
900class BuiltinType : public Type {
901public:
902  enum Kind {
903    Void,
904
905    Bool,     // This is bool and/or _Bool.
906    Char_U,   // This is 'char' for targets where char is unsigned.
907    UChar,    // This is explicitly qualified unsigned char.
908    Char16,   // This is 'char16_t' for C++.
909    Char32,   // This is 'char32_t' for C++.
910    UShort,
911    UInt,
912    ULong,
913    ULongLong,
914    UInt128,  // __uint128_t
915
916    Char_S,   // This is 'char' for targets where char is signed.
917    SChar,    // This is explicitly qualified signed char.
918    WChar,    // This is 'wchar_t' for C++.
919    Short,
920    Int,
921    Long,
922    LongLong,
923    Int128,   // __int128_t
924
925    Float, Double, LongDouble,
926
927    NullPtr,  // This is the type of C++0x 'nullptr'.
928
929    Overload,  // This represents the type of an overloaded function declaration.
930    Dependent, // This represents the type of a type-dependent expression.
931
932    UndeducedAuto, // In C++0x, this represents the type of an auto variable
933                   // that has not been deduced yet.
934    ObjCId,    // This represents the ObjC 'id' type.
935    ObjCClass  // This represents the ObjC 'Class' type.
936  };
937private:
938  Kind TypeKind;
939public:
940  BuiltinType(Kind K)
941    : Type(Builtin, QualType(), /*Dependent=*/(K == Dependent)),
942      TypeKind(K) {}
943
944  Kind getKind() const { return TypeKind; }
945  const char *getName(const LangOptions &LO) const;
946
947  virtual void getAsStringInternal(std::string &InnerString,
948                                   const PrintingPolicy &Policy) const;
949
950  static bool classof(const Type *T) { return T->getTypeClass() == Builtin; }
951  static bool classof(const BuiltinType *) { return true; }
952};
953
954/// FixedWidthIntType - Used for arbitrary width types that we either don't
955/// want to or can't map to named integer types.  These always have a lower
956/// integer rank than builtin types of the same width.
957class FixedWidthIntType : public Type {
958private:
959  unsigned Width;
960  bool Signed;
961public:
962  FixedWidthIntType(unsigned W, bool S) : Type(FixedWidthInt, QualType(), false),
963                                          Width(W), Signed(S) {}
964
965  unsigned getWidth() const { return Width; }
966  bool isSigned() const { return Signed; }
967  const char *getName() const;
968
969  virtual void getAsStringInternal(std::string &InnerString,
970                                   const PrintingPolicy &Policy) const;
971
972  static bool classof(const Type *T) { return T->getTypeClass() == FixedWidthInt; }
973  static bool classof(const FixedWidthIntType *) { return true; }
974};
975
976/// ComplexType - C99 6.2.5p11 - Complex values.  This supports the C99 complex
977/// types (_Complex float etc) as well as the GCC integer complex extensions.
978///
979class ComplexType : public Type, public llvm::FoldingSetNode {
980  QualType ElementType;
981  ComplexType(QualType Element, QualType CanonicalPtr) :
982    Type(Complex, CanonicalPtr, Element->isDependentType()),
983    ElementType(Element) {
984  }
985  friend class ASTContext;  // ASTContext creates these.
986public:
987  QualType getElementType() const { return ElementType; }
988
989  virtual void getAsStringInternal(std::string &InnerString,
990                                   const PrintingPolicy &Policy) const;
991
992  void Profile(llvm::FoldingSetNodeID &ID) {
993    Profile(ID, getElementType());
994  }
995  static void Profile(llvm::FoldingSetNodeID &ID, QualType Element) {
996    ID.AddPointer(Element.getAsOpaquePtr());
997  }
998
999  static bool classof(const Type *T) { return T->getTypeClass() == Complex; }
1000  static bool classof(const ComplexType *) { return true; }
1001};
1002
1003/// PointerType - C99 6.7.5.1 - Pointer Declarators.
1004///
1005class PointerType : public Type, public llvm::FoldingSetNode {
1006  QualType PointeeType;
1007
1008  PointerType(QualType Pointee, QualType CanonicalPtr) :
1009    Type(Pointer, CanonicalPtr, Pointee->isDependentType()), PointeeType(Pointee) {
1010  }
1011  friend class ASTContext;  // ASTContext creates these.
1012public:
1013
1014  virtual void getAsStringInternal(std::string &InnerString,
1015                                   const PrintingPolicy &Policy) const;
1016
1017  QualType getPointeeType() const { return PointeeType; }
1018
1019  void Profile(llvm::FoldingSetNodeID &ID) {
1020    Profile(ID, getPointeeType());
1021  }
1022  static void Profile(llvm::FoldingSetNodeID &ID, QualType Pointee) {
1023    ID.AddPointer(Pointee.getAsOpaquePtr());
1024  }
1025
1026  static bool classof(const Type *T) { return T->getTypeClass() == Pointer; }
1027  static bool classof(const PointerType *) { return true; }
1028};
1029
1030/// BlockPointerType - pointer to a block type.
1031/// This type is to represent types syntactically represented as
1032/// "void (^)(int)", etc. Pointee is required to always be a function type.
1033///
1034class BlockPointerType : public Type, public llvm::FoldingSetNode {
1035  QualType PointeeType;  // Block is some kind of pointer type
1036  BlockPointerType(QualType Pointee, QualType CanonicalCls) :
1037    Type(BlockPointer, CanonicalCls, Pointee->isDependentType()),
1038    PointeeType(Pointee) {
1039  }
1040  friend class ASTContext;  // ASTContext creates these.
1041public:
1042
1043  // Get the pointee type. Pointee is required to always be a function type.
1044  QualType getPointeeType() const { return PointeeType; }
1045
1046  virtual void getAsStringInternal(std::string &InnerString,
1047                                   const PrintingPolicy &Policy) const;
1048
1049  void Profile(llvm::FoldingSetNodeID &ID) {
1050      Profile(ID, getPointeeType());
1051  }
1052  static void Profile(llvm::FoldingSetNodeID &ID, QualType Pointee) {
1053      ID.AddPointer(Pointee.getAsOpaquePtr());
1054  }
1055
1056  static bool classof(const Type *T) {
1057    return T->getTypeClass() == BlockPointer;
1058  }
1059  static bool classof(const BlockPointerType *) { return true; }
1060};
1061
1062/// ReferenceType - Base for LValueReferenceType and RValueReferenceType
1063///
1064class ReferenceType : public Type, public llvm::FoldingSetNode {
1065  QualType PointeeType;
1066
1067protected:
1068  ReferenceType(TypeClass tc, QualType Referencee, QualType CanonicalRef) :
1069    Type(tc, CanonicalRef, Referencee->isDependentType()),
1070    PointeeType(Referencee) {
1071  }
1072public:
1073  QualType getPointeeType() const { return PointeeType; }
1074
1075  void Profile(llvm::FoldingSetNodeID &ID) {
1076    Profile(ID, getPointeeType());
1077  }
1078  static void Profile(llvm::FoldingSetNodeID &ID, QualType Referencee) {
1079    ID.AddPointer(Referencee.getAsOpaquePtr());
1080  }
1081
1082  static bool classof(const Type *T) {
1083    return T->getTypeClass() == LValueReference ||
1084           T->getTypeClass() == RValueReference;
1085  }
1086  static bool classof(const ReferenceType *) { return true; }
1087};
1088
1089/// LValueReferenceType - C++ [dcl.ref] - Lvalue reference
1090///
1091class LValueReferenceType : public ReferenceType {
1092  LValueReferenceType(QualType Referencee, QualType CanonicalRef) :
1093    ReferenceType(LValueReference, Referencee, CanonicalRef) {
1094  }
1095  friend class ASTContext; // ASTContext creates these
1096public:
1097  virtual void getAsStringInternal(std::string &InnerString,
1098                                   const PrintingPolicy &Policy) const;
1099
1100  static bool classof(const Type *T) {
1101    return T->getTypeClass() == LValueReference;
1102  }
1103  static bool classof(const LValueReferenceType *) { return true; }
1104};
1105
1106/// RValueReferenceType - C++0x [dcl.ref] - Rvalue reference
1107///
1108class RValueReferenceType : public ReferenceType {
1109  RValueReferenceType(QualType Referencee, QualType CanonicalRef) :
1110    ReferenceType(RValueReference, Referencee, CanonicalRef) {
1111  }
1112  friend class ASTContext; // ASTContext creates these
1113public:
1114  virtual void getAsStringInternal(std::string &InnerString,
1115                                   const PrintingPolicy &Policy) const;
1116
1117  static bool classof(const Type *T) {
1118    return T->getTypeClass() == RValueReference;
1119  }
1120  static bool classof(const RValueReferenceType *) { return true; }
1121};
1122
1123/// MemberPointerType - C++ 8.3.3 - Pointers to members
1124///
1125class MemberPointerType : public Type, public llvm::FoldingSetNode {
1126  QualType PointeeType;
1127  /// The class of which the pointee is a member. Must ultimately be a
1128  /// RecordType, but could be a typedef or a template parameter too.
1129  const Type *Class;
1130
1131  MemberPointerType(QualType Pointee, const Type *Cls, QualType CanonicalPtr) :
1132    Type(MemberPointer, CanonicalPtr,
1133         Cls->isDependentType() || Pointee->isDependentType()),
1134    PointeeType(Pointee), Class(Cls) {
1135  }
1136  friend class ASTContext; // ASTContext creates these.
1137public:
1138
1139  QualType getPointeeType() const { return PointeeType; }
1140
1141  const Type *getClass() const { return Class; }
1142
1143  virtual void getAsStringInternal(std::string &InnerString,
1144                                   const PrintingPolicy &Policy) const;
1145
1146  void Profile(llvm::FoldingSetNodeID &ID) {
1147    Profile(ID, getPointeeType(), getClass());
1148  }
1149  static void Profile(llvm::FoldingSetNodeID &ID, QualType Pointee,
1150                      const Type *Class) {
1151    ID.AddPointer(Pointee.getAsOpaquePtr());
1152    ID.AddPointer(Class);
1153  }
1154
1155  static bool classof(const Type *T) {
1156    return T->getTypeClass() == MemberPointer;
1157  }
1158  static bool classof(const MemberPointerType *) { return true; }
1159};
1160
1161/// ArrayType - C99 6.7.5.2 - Array Declarators.
1162///
1163class ArrayType : public Type, public llvm::FoldingSetNode {
1164public:
1165  /// ArraySizeModifier - Capture whether this is a normal array (e.g. int X[4])
1166  /// an array with a static size (e.g. int X[static 4]), or an array
1167  /// with a star size (e.g. int X[*]).
1168  /// 'static' is only allowed on function parameters.
1169  enum ArraySizeModifier {
1170    Normal, Static, Star
1171  };
1172private:
1173  /// ElementType - The element type of the array.
1174  QualType ElementType;
1175
1176  // NOTE: VC++ treats enums as signed, avoid using the ArraySizeModifier enum
1177  /// NOTE: These fields are packed into the bitfields space in the Type class.
1178  unsigned SizeModifier : 2;
1179
1180  /// IndexTypeQuals - Capture qualifiers in declarations like:
1181  /// 'int X[static restrict 4]'. For function parameters only.
1182  unsigned IndexTypeQuals : 3;
1183
1184protected:
1185  // C++ [temp.dep.type]p1:
1186  //   A type is dependent if it is...
1187  //     - an array type constructed from any dependent type or whose
1188  //       size is specified by a constant expression that is
1189  //       value-dependent,
1190  ArrayType(TypeClass tc, QualType et, QualType can,
1191            ArraySizeModifier sm, unsigned tq)
1192    : Type(tc, can, et->isDependentType() || tc == DependentSizedArray),
1193      ElementType(et), SizeModifier(sm), IndexTypeQuals(tq) {}
1194
1195  friend class ASTContext;  // ASTContext creates these.
1196public:
1197  QualType getElementType() const { return ElementType; }
1198  ArraySizeModifier getSizeModifier() const {
1199    return ArraySizeModifier(SizeModifier);
1200  }
1201  Qualifiers getIndexTypeQualifiers() const {
1202    return Qualifiers::fromCVRMask(IndexTypeQuals);
1203  }
1204  unsigned getIndexTypeCVRQualifiers() const { return IndexTypeQuals; }
1205
1206  static bool classof(const Type *T) {
1207    return T->getTypeClass() == ConstantArray ||
1208           T->getTypeClass() == ConstantArrayWithExpr ||
1209           T->getTypeClass() == ConstantArrayWithoutExpr ||
1210           T->getTypeClass() == VariableArray ||
1211           T->getTypeClass() == IncompleteArray ||
1212           T->getTypeClass() == DependentSizedArray;
1213  }
1214  static bool classof(const ArrayType *) { return true; }
1215};
1216
1217/// ConstantArrayType - This class represents the canonical version of
1218/// C arrays with a specified constant size.  For example, the canonical
1219/// type for 'int A[4 + 4*100]' is a ConstantArrayType where the element
1220/// type is 'int' and the size is 404.
1221class ConstantArrayType : public ArrayType {
1222  llvm::APInt Size; // Allows us to unique the type.
1223
1224  ConstantArrayType(QualType et, QualType can, const llvm::APInt &size,
1225                    ArraySizeModifier sm, unsigned tq)
1226    : ArrayType(ConstantArray, et, can, sm, tq),
1227      Size(size) {}
1228protected:
1229  ConstantArrayType(TypeClass tc, QualType et, QualType can,
1230                    const llvm::APInt &size, ArraySizeModifier sm, unsigned tq)
1231    : ArrayType(tc, et, can, sm, tq), Size(size) {}
1232  friend class ASTContext;  // ASTContext creates these.
1233public:
1234  const llvm::APInt &getSize() const { return Size; }
1235  virtual void getAsStringInternal(std::string &InnerString,
1236                                   const PrintingPolicy &Policy) const;
1237
1238  void Profile(llvm::FoldingSetNodeID &ID) {
1239    Profile(ID, getElementType(), getSize(),
1240            getSizeModifier(), getIndexTypeCVRQualifiers());
1241  }
1242  static void Profile(llvm::FoldingSetNodeID &ID, QualType ET,
1243                      const llvm::APInt &ArraySize, ArraySizeModifier SizeMod,
1244                      unsigned TypeQuals) {
1245    ID.AddPointer(ET.getAsOpaquePtr());
1246    ID.AddInteger(ArraySize.getZExtValue());
1247    ID.AddInteger(SizeMod);
1248    ID.AddInteger(TypeQuals);
1249  }
1250  static bool classof(const Type *T) {
1251    return T->getTypeClass() == ConstantArray ||
1252           T->getTypeClass() == ConstantArrayWithExpr ||
1253           T->getTypeClass() == ConstantArrayWithoutExpr;
1254  }
1255  static bool classof(const ConstantArrayType *) { return true; }
1256};
1257
1258/// ConstantArrayWithExprType - This class represents C arrays with a
1259/// constant size specified by means of an integer constant expression.
1260/// For example 'int A[sizeof(int)]' has ConstantArrayWithExprType where
1261/// the element type is 'int' and the size expression is 'sizeof(int)'.
1262/// These types are non-canonical.
1263class ConstantArrayWithExprType : public ConstantArrayType {
1264  /// SizeExpr - The ICE occurring in the concrete syntax.
1265  Expr *SizeExpr;
1266  /// Brackets - The left and right array brackets.
1267  SourceRange Brackets;
1268
1269  ConstantArrayWithExprType(QualType et, QualType can,
1270                            const llvm::APInt &size, Expr *e,
1271                            ArraySizeModifier sm, unsigned tq,
1272                            SourceRange brackets)
1273    : ConstantArrayType(ConstantArrayWithExpr, et, can, size, sm, tq),
1274      SizeExpr(e), Brackets(brackets) {}
1275  friend class ASTContext;  // ASTContext creates these.
1276  virtual void Destroy(ASTContext& C);
1277
1278public:
1279  Expr *getSizeExpr() const { return SizeExpr; }
1280  SourceRange getBracketsRange() const { return Brackets; }
1281  SourceLocation getLBracketLoc() const { return Brackets.getBegin(); }
1282  SourceLocation getRBracketLoc() const { return Brackets.getEnd(); }
1283
1284  virtual void getAsStringInternal(std::string &InnerString,
1285                                   const PrintingPolicy &Policy) const;
1286
1287  static bool classof(const Type *T) {
1288    return T->getTypeClass() == ConstantArrayWithExpr;
1289  }
1290  static bool classof(const ConstantArrayWithExprType *) { return true; }
1291
1292  void Profile(llvm::FoldingSetNodeID &ID) {
1293    assert(0 && "Cannot unique ConstantArrayWithExprTypes.");
1294  }
1295};
1296
1297/// ConstantArrayWithoutExprType - This class represents C arrays with a
1298/// constant size that was not specified by an integer constant expression,
1299/// but inferred by static semantics.
1300/// For example 'int A[] = { 0, 1, 2 }' has ConstantArrayWithoutExprType.
1301/// These types are non-canonical: the corresponding canonical type,
1302/// having the size specified in an APInt object, is a ConstantArrayType.
1303class ConstantArrayWithoutExprType : public ConstantArrayType {
1304
1305  ConstantArrayWithoutExprType(QualType et, QualType can,
1306                               const llvm::APInt &size,
1307                               ArraySizeModifier sm, unsigned tq)
1308    : ConstantArrayType(ConstantArrayWithoutExpr, et, can, size, sm, tq) {}
1309  friend class ASTContext;  // ASTContext creates these.
1310
1311public:
1312  virtual void getAsStringInternal(std::string &InnerString,
1313                                   const PrintingPolicy &Policy) const;
1314
1315  static bool classof(const Type *T) {
1316    return T->getTypeClass() == ConstantArrayWithoutExpr;
1317  }
1318  static bool classof(const ConstantArrayWithoutExprType *) { return true; }
1319
1320  void Profile(llvm::FoldingSetNodeID &ID) {
1321    assert(0 && "Cannot unique ConstantArrayWithoutExprTypes.");
1322  }
1323};
1324
1325/// IncompleteArrayType - This class represents C arrays with an unspecified
1326/// size.  For example 'int A[]' has an IncompleteArrayType where the element
1327/// type is 'int' and the size is unspecified.
1328class IncompleteArrayType : public ArrayType {
1329
1330  IncompleteArrayType(QualType et, QualType can,
1331                      ArraySizeModifier sm, unsigned tq)
1332    : ArrayType(IncompleteArray, et, can, sm, tq) {}
1333  friend class ASTContext;  // ASTContext creates these.
1334public:
1335  virtual void getAsStringInternal(std::string &InnerString,
1336                                   const PrintingPolicy &Policy) const;
1337
1338  static bool classof(const Type *T) {
1339    return T->getTypeClass() == IncompleteArray;
1340  }
1341  static bool classof(const IncompleteArrayType *) { return true; }
1342
1343  friend class StmtIteratorBase;
1344
1345  void Profile(llvm::FoldingSetNodeID &ID) {
1346    Profile(ID, getElementType(), getSizeModifier(),
1347            getIndexTypeCVRQualifiers());
1348  }
1349
1350  static void Profile(llvm::FoldingSetNodeID &ID, QualType ET,
1351                      ArraySizeModifier SizeMod, unsigned TypeQuals) {
1352    ID.AddPointer(ET.getAsOpaquePtr());
1353    ID.AddInteger(SizeMod);
1354    ID.AddInteger(TypeQuals);
1355  }
1356};
1357
1358/// VariableArrayType - This class represents C arrays with a specified size
1359/// which is not an integer-constant-expression.  For example, 'int s[x+foo()]'.
1360/// Since the size expression is an arbitrary expression, we store it as such.
1361///
1362/// Note: VariableArrayType's aren't uniqued (since the expressions aren't) and
1363/// should not be: two lexically equivalent variable array types could mean
1364/// different things, for example, these variables do not have the same type
1365/// dynamically:
1366///
1367/// void foo(int x) {
1368///   int Y[x];
1369///   ++x;
1370///   int Z[x];
1371/// }
1372///
1373class VariableArrayType : public ArrayType {
1374  /// SizeExpr - An assignment expression. VLA's are only permitted within
1375  /// a function block.
1376  Stmt *SizeExpr;
1377  /// Brackets - The left and right array brackets.
1378  SourceRange Brackets;
1379
1380  VariableArrayType(QualType et, QualType can, Expr *e,
1381                    ArraySizeModifier sm, unsigned tq,
1382                    SourceRange brackets)
1383    : ArrayType(VariableArray, et, can, sm, tq),
1384      SizeExpr((Stmt*) e), Brackets(brackets) {}
1385  friend class ASTContext;  // ASTContext creates these.
1386  virtual void Destroy(ASTContext& C);
1387
1388public:
1389  Expr *getSizeExpr() const {
1390    // We use C-style casts instead of cast<> here because we do not wish
1391    // to have a dependency of Type.h on Stmt.h/Expr.h.
1392    return (Expr*) SizeExpr;
1393  }
1394  SourceRange getBracketsRange() const { return Brackets; }
1395  SourceLocation getLBracketLoc() const { return Brackets.getBegin(); }
1396  SourceLocation getRBracketLoc() const { return Brackets.getEnd(); }
1397
1398  virtual void getAsStringInternal(std::string &InnerString,
1399                                   const PrintingPolicy &Policy) const;
1400
1401  static bool classof(const Type *T) {
1402    return T->getTypeClass() == VariableArray;
1403  }
1404  static bool classof(const VariableArrayType *) { return true; }
1405
1406  friend class StmtIteratorBase;
1407
1408  void Profile(llvm::FoldingSetNodeID &ID) {
1409    assert(0 && "Cannnot unique VariableArrayTypes.");
1410  }
1411};
1412
1413/// DependentSizedArrayType - This type represents an array type in
1414/// C++ whose size is a value-dependent expression. For example:
1415/// @code
1416/// template<typename T, int Size>
1417/// class array {
1418///   T data[Size];
1419/// };
1420/// @endcode
1421/// For these types, we won't actually know what the array bound is
1422/// until template instantiation occurs, at which point this will
1423/// become either a ConstantArrayType or a VariableArrayType.
1424class DependentSizedArrayType : public ArrayType {
1425  ASTContext &Context;
1426
1427  /// SizeExpr - An assignment expression that will instantiate to the
1428  /// size of the array.
1429  Stmt *SizeExpr;
1430  /// Brackets - The left and right array brackets.
1431  SourceRange Brackets;
1432
1433  DependentSizedArrayType(ASTContext &Context, QualType et, QualType can,
1434                          Expr *e, ArraySizeModifier sm, unsigned tq,
1435                          SourceRange brackets)
1436    : ArrayType(DependentSizedArray, et, can, sm, tq),
1437      Context(Context), SizeExpr((Stmt*) e), Brackets(brackets) {}
1438  friend class ASTContext;  // ASTContext creates these.
1439  virtual void Destroy(ASTContext& C);
1440
1441public:
1442  Expr *getSizeExpr() const {
1443    // We use C-style casts instead of cast<> here because we do not wish
1444    // to have a dependency of Type.h on Stmt.h/Expr.h.
1445    return (Expr*) SizeExpr;
1446  }
1447  SourceRange getBracketsRange() const { return Brackets; }
1448  SourceLocation getLBracketLoc() const { return Brackets.getBegin(); }
1449  SourceLocation getRBracketLoc() const { return Brackets.getEnd(); }
1450
1451  virtual void getAsStringInternal(std::string &InnerString,
1452                                   const PrintingPolicy &Policy) const;
1453
1454  static bool classof(const Type *T) {
1455    return T->getTypeClass() == DependentSizedArray;
1456  }
1457  static bool classof(const DependentSizedArrayType *) { return true; }
1458
1459  friend class StmtIteratorBase;
1460
1461
1462  void Profile(llvm::FoldingSetNodeID &ID) {
1463    Profile(ID, Context, getElementType(),
1464            getSizeModifier(), getIndexTypeCVRQualifiers(), getSizeExpr());
1465  }
1466
1467  static void Profile(llvm::FoldingSetNodeID &ID, ASTContext &Context,
1468                      QualType ET, ArraySizeModifier SizeMod,
1469                      unsigned TypeQuals, Expr *E);
1470};
1471
1472/// DependentSizedExtVectorType - This type represent an extended vector type
1473/// where either the type or size is dependent. For example:
1474/// @code
1475/// template<typename T, int Size>
1476/// class vector {
1477///   typedef T __attribute__((ext_vector_type(Size))) type;
1478/// }
1479/// @endcode
1480class DependentSizedExtVectorType : public Type, public llvm::FoldingSetNode {
1481  ASTContext &Context;
1482  Expr *SizeExpr;
1483  /// ElementType - The element type of the array.
1484  QualType ElementType;
1485  SourceLocation loc;
1486
1487  DependentSizedExtVectorType(ASTContext &Context, QualType ElementType,
1488                              QualType can, Expr *SizeExpr, SourceLocation loc)
1489    : Type (DependentSizedExtVector, can, true),
1490      Context(Context), SizeExpr(SizeExpr), ElementType(ElementType),
1491      loc(loc) {}
1492  friend class ASTContext;
1493  virtual void Destroy(ASTContext& C);
1494
1495public:
1496  Expr *getSizeExpr() const { return SizeExpr; }
1497  QualType getElementType() const { return ElementType; }
1498  SourceLocation getAttributeLoc() const { return loc; }
1499
1500  virtual void getAsStringInternal(std::string &InnerString,
1501                                   const PrintingPolicy &Policy) const;
1502
1503  static bool classof(const Type *T) {
1504    return T->getTypeClass() == DependentSizedExtVector;
1505  }
1506  static bool classof(const DependentSizedExtVectorType *) { return true; }
1507
1508  void Profile(llvm::FoldingSetNodeID &ID) {
1509    Profile(ID, Context, getElementType(), getSizeExpr());
1510  }
1511
1512  static void Profile(llvm::FoldingSetNodeID &ID, ASTContext &Context,
1513                      QualType ElementType, Expr *SizeExpr);
1514};
1515
1516
1517/// VectorType - GCC generic vector type. This type is created using
1518/// __attribute__((vector_size(n)), where "n" specifies the vector size in
1519/// bytes. Since the constructor takes the number of vector elements, the
1520/// client is responsible for converting the size into the number of elements.
1521class VectorType : public Type, public llvm::FoldingSetNode {
1522protected:
1523  /// ElementType - The element type of the vector.
1524  QualType ElementType;
1525
1526  /// NumElements - The number of elements in the vector.
1527  unsigned NumElements;
1528
1529  VectorType(QualType vecType, unsigned nElements, QualType canonType) :
1530    Type(Vector, canonType, vecType->isDependentType()),
1531    ElementType(vecType), NumElements(nElements) {}
1532  VectorType(TypeClass tc, QualType vecType, unsigned nElements,
1533             QualType canonType)
1534    : Type(tc, canonType, vecType->isDependentType()), ElementType(vecType),
1535      NumElements(nElements) {}
1536  friend class ASTContext;  // ASTContext creates these.
1537public:
1538
1539  QualType getElementType() const { return ElementType; }
1540  unsigned getNumElements() const { return NumElements; }
1541
1542  virtual void getAsStringInternal(std::string &InnerString,
1543                                   const PrintingPolicy &Policy) const;
1544
1545  void Profile(llvm::FoldingSetNodeID &ID) {
1546    Profile(ID, getElementType(), getNumElements(), getTypeClass());
1547  }
1548  static void Profile(llvm::FoldingSetNodeID &ID, QualType ElementType,
1549                      unsigned NumElements, TypeClass TypeClass) {
1550    ID.AddPointer(ElementType.getAsOpaquePtr());
1551    ID.AddInteger(NumElements);
1552    ID.AddInteger(TypeClass);
1553  }
1554  static bool classof(const Type *T) {
1555    return T->getTypeClass() == Vector || T->getTypeClass() == ExtVector;
1556  }
1557  static bool classof(const VectorType *) { return true; }
1558};
1559
1560/// ExtVectorType - Extended vector type. This type is created using
1561/// __attribute__((ext_vector_type(n)), where "n" is the number of elements.
1562/// Unlike vector_size, ext_vector_type is only allowed on typedef's. This
1563/// class enables syntactic extensions, like Vector Components for accessing
1564/// points, colors, and textures (modeled after OpenGL Shading Language).
1565class ExtVectorType : public VectorType {
1566  ExtVectorType(QualType vecType, unsigned nElements, QualType canonType) :
1567    VectorType(ExtVector, vecType, nElements, canonType) {}
1568  friend class ASTContext;  // ASTContext creates these.
1569public:
1570  static int getPointAccessorIdx(char c) {
1571    switch (c) {
1572    default: return -1;
1573    case 'x': return 0;
1574    case 'y': return 1;
1575    case 'z': return 2;
1576    case 'w': return 3;
1577    }
1578  }
1579  static int getNumericAccessorIdx(char c) {
1580    switch (c) {
1581      default: return -1;
1582      case '0': return 0;
1583      case '1': return 1;
1584      case '2': return 2;
1585      case '3': return 3;
1586      case '4': return 4;
1587      case '5': return 5;
1588      case '6': return 6;
1589      case '7': return 7;
1590      case '8': return 8;
1591      case '9': return 9;
1592      case 'A':
1593      case 'a': return 10;
1594      case 'B':
1595      case 'b': return 11;
1596      case 'C':
1597      case 'c': return 12;
1598      case 'D':
1599      case 'd': return 13;
1600      case 'E':
1601      case 'e': return 14;
1602      case 'F':
1603      case 'f': return 15;
1604    }
1605  }
1606
1607  static int getAccessorIdx(char c) {
1608    if (int idx = getPointAccessorIdx(c)+1) return idx-1;
1609    return getNumericAccessorIdx(c);
1610  }
1611
1612  bool isAccessorWithinNumElements(char c) const {
1613    if (int idx = getAccessorIdx(c)+1)
1614      return unsigned(idx-1) < NumElements;
1615    return false;
1616  }
1617  virtual void getAsStringInternal(std::string &InnerString,
1618                                   const PrintingPolicy &Policy) const;
1619
1620  static bool classof(const Type *T) {
1621    return T->getTypeClass() == ExtVector;
1622  }
1623  static bool classof(const ExtVectorType *) { return true; }
1624};
1625
1626/// FunctionType - C99 6.7.5.3 - Function Declarators.  This is the common base
1627/// class of FunctionNoProtoType and FunctionProtoType.
1628///
1629class FunctionType : public Type {
1630  /// SubClassData - This field is owned by the subclass, put here to pack
1631  /// tightly with the ivars in Type.
1632  bool SubClassData : 1;
1633
1634  /// TypeQuals - Used only by FunctionProtoType, put here to pack with the
1635  /// other bitfields.
1636  /// The qualifiers are part of FunctionProtoType because...
1637  ///
1638  /// C++ 8.3.5p4: The return type, the parameter type list and the
1639  /// cv-qualifier-seq, [...], are part of the function type.
1640  ///
1641  unsigned TypeQuals : 3;
1642
1643  /// NoReturn - Indicates if the function type is attribute noreturn.
1644  unsigned NoReturn : 1;
1645
1646  // The type returned by the function.
1647  QualType ResultType;
1648protected:
1649  FunctionType(TypeClass tc, QualType res, bool SubclassInfo,
1650               unsigned typeQuals, QualType Canonical, bool Dependent,
1651               bool noReturn = false)
1652    : Type(tc, Canonical, Dependent),
1653      SubClassData(SubclassInfo), TypeQuals(typeQuals), NoReturn(noReturn),
1654      ResultType(res) {}
1655  bool getSubClassData() const { return SubClassData; }
1656  unsigned getTypeQuals() const { return TypeQuals; }
1657public:
1658
1659  QualType getResultType() const { return ResultType; }
1660  bool getNoReturnAttr() const { return NoReturn; }
1661
1662
1663  static bool classof(const Type *T) {
1664    return T->getTypeClass() == FunctionNoProto ||
1665           T->getTypeClass() == FunctionProto;
1666  }
1667  static bool classof(const FunctionType *) { return true; }
1668};
1669
1670/// FunctionNoProtoType - Represents a K&R-style 'int foo()' function, which has
1671/// no information available about its arguments.
1672class FunctionNoProtoType : public FunctionType, public llvm::FoldingSetNode {
1673  FunctionNoProtoType(QualType Result, QualType Canonical,
1674                      bool NoReturn = false)
1675    : FunctionType(FunctionNoProto, Result, false, 0, Canonical,
1676                   /*Dependent=*/false, NoReturn) {}
1677  friend class ASTContext;  // ASTContext creates these.
1678public:
1679  // No additional state past what FunctionType provides.
1680
1681  virtual void getAsStringInternal(std::string &InnerString,
1682                                   const PrintingPolicy &Policy) const;
1683
1684  void Profile(llvm::FoldingSetNodeID &ID) {
1685    Profile(ID, getResultType(), getNoReturnAttr());
1686  }
1687  static void Profile(llvm::FoldingSetNodeID &ID, QualType ResultType,
1688                      bool NoReturn) {
1689    ID.AddInteger(NoReturn);
1690    ID.AddPointer(ResultType.getAsOpaquePtr());
1691  }
1692
1693  static bool classof(const Type *T) {
1694    return T->getTypeClass() == FunctionNoProto;
1695  }
1696  static bool classof(const FunctionNoProtoType *) { return true; }
1697};
1698
1699/// FunctionProtoType - Represents a prototype with argument type info, e.g.
1700/// 'int foo(int)' or 'int foo(void)'.  'void' is represented as having no
1701/// arguments, not as having a single void argument. Such a type can have an
1702/// exception specification, but this specification is not part of the canonical
1703/// type.
1704class FunctionProtoType : public FunctionType, public llvm::FoldingSetNode {
1705  /// hasAnyDependentType - Determine whether there are any dependent
1706  /// types within the arguments passed in.
1707  static bool hasAnyDependentType(const QualType *ArgArray, unsigned numArgs) {
1708    for (unsigned Idx = 0; Idx < numArgs; ++Idx)
1709      if (ArgArray[Idx]->isDependentType())
1710    return true;
1711
1712    return false;
1713  }
1714
1715  FunctionProtoType(QualType Result, const QualType *ArgArray, unsigned numArgs,
1716                    bool isVariadic, unsigned typeQuals, bool hasExs,
1717                    bool hasAnyExs, const QualType *ExArray,
1718                    unsigned numExs, QualType Canonical, bool NoReturn)
1719    : FunctionType(FunctionProto, Result, isVariadic, typeQuals, Canonical,
1720                   (Result->isDependentType() ||
1721                    hasAnyDependentType(ArgArray, numArgs)), NoReturn),
1722      NumArgs(numArgs), NumExceptions(numExs), HasExceptionSpec(hasExs),
1723      AnyExceptionSpec(hasAnyExs) {
1724    // Fill in the trailing argument array.
1725    QualType *ArgInfo = reinterpret_cast<QualType*>(this+1);
1726    for (unsigned i = 0; i != numArgs; ++i)
1727      ArgInfo[i] = ArgArray[i];
1728    // Fill in the exception array.
1729    QualType *Ex = ArgInfo + numArgs;
1730    for (unsigned i = 0; i != numExs; ++i)
1731      Ex[i] = ExArray[i];
1732  }
1733
1734  /// NumArgs - The number of arguments this function has, not counting '...'.
1735  unsigned NumArgs : 20;
1736
1737  /// NumExceptions - The number of types in the exception spec, if any.
1738  unsigned NumExceptions : 10;
1739
1740  /// HasExceptionSpec - Whether this function has an exception spec at all.
1741  bool HasExceptionSpec : 1;
1742
1743  /// AnyExceptionSpec - Whether this function has a throw(...) spec.
1744  bool AnyExceptionSpec : 1;
1745
1746  /// ArgInfo - There is an variable size array after the class in memory that
1747  /// holds the argument types.
1748
1749  /// Exceptions - There is another variable size array after ArgInfo that
1750  /// holds the exception types.
1751
1752  friend class ASTContext;  // ASTContext creates these.
1753
1754public:
1755  unsigned getNumArgs() const { return NumArgs; }
1756  QualType getArgType(unsigned i) const {
1757    assert(i < NumArgs && "Invalid argument number!");
1758    return arg_type_begin()[i];
1759  }
1760
1761  bool hasExceptionSpec() const { return HasExceptionSpec; }
1762  bool hasAnyExceptionSpec() const { return AnyExceptionSpec; }
1763  unsigned getNumExceptions() const { return NumExceptions; }
1764  QualType getExceptionType(unsigned i) const {
1765    assert(i < NumExceptions && "Invalid exception number!");
1766    return exception_begin()[i];
1767  }
1768  bool hasEmptyExceptionSpec() const {
1769    return hasExceptionSpec() && !hasAnyExceptionSpec() &&
1770      getNumExceptions() == 0;
1771  }
1772
1773  bool isVariadic() const { return getSubClassData(); }
1774  unsigned getTypeQuals() const { return FunctionType::getTypeQuals(); }
1775
1776  typedef const QualType *arg_type_iterator;
1777  arg_type_iterator arg_type_begin() const {
1778    return reinterpret_cast<const QualType *>(this+1);
1779  }
1780  arg_type_iterator arg_type_end() const { return arg_type_begin()+NumArgs; }
1781
1782  typedef const QualType *exception_iterator;
1783  exception_iterator exception_begin() const {
1784    // exceptions begin where arguments end
1785    return arg_type_end();
1786  }
1787  exception_iterator exception_end() const {
1788    return exception_begin() + NumExceptions;
1789  }
1790
1791  virtual void getAsStringInternal(std::string &InnerString,
1792                                   const PrintingPolicy &Policy) const;
1793
1794  static bool classof(const Type *T) {
1795    return T->getTypeClass() == FunctionProto;
1796  }
1797  static bool classof(const FunctionProtoType *) { return true; }
1798
1799  void Profile(llvm::FoldingSetNodeID &ID);
1800  static void Profile(llvm::FoldingSetNodeID &ID, QualType Result,
1801                      arg_type_iterator ArgTys, unsigned NumArgs,
1802                      bool isVariadic, unsigned TypeQuals,
1803                      bool hasExceptionSpec, bool anyExceptionSpec,
1804                      unsigned NumExceptions, exception_iterator Exs,
1805                      bool NoReturn);
1806};
1807
1808
1809class TypedefType : public Type {
1810  TypedefDecl *Decl;
1811protected:
1812  TypedefType(TypeClass tc, TypedefDecl *D, QualType can)
1813    : Type(tc, can, can->isDependentType()), Decl(D) {
1814    assert(!isa<TypedefType>(can) && "Invalid canonical type");
1815  }
1816  friend class ASTContext;  // ASTContext creates these.
1817public:
1818
1819  TypedefDecl *getDecl() const { return Decl; }
1820
1821  /// LookThroughTypedefs - Return the ultimate type this typedef corresponds to
1822  /// potentially looking through *all* consecutive typedefs.  This returns the
1823  /// sum of the type qualifiers, so if you have:
1824  ///   typedef const int A;
1825  ///   typedef volatile A B;
1826  /// looking through the typedefs for B will give you "const volatile A".
1827  QualType LookThroughTypedefs() const;
1828
1829  virtual void getAsStringInternal(std::string &InnerString,
1830                                   const PrintingPolicy &Policy) const;
1831
1832  static bool classof(const Type *T) { return T->getTypeClass() == Typedef; }
1833  static bool classof(const TypedefType *) { return true; }
1834};
1835
1836/// TypeOfExprType (GCC extension).
1837class TypeOfExprType : public Type {
1838  Expr *TOExpr;
1839
1840protected:
1841  TypeOfExprType(Expr *E, QualType can = QualType());
1842  friend class ASTContext;  // ASTContext creates these.
1843public:
1844  Expr *getUnderlyingExpr() const { return TOExpr; }
1845
1846  virtual void getAsStringInternal(std::string &InnerString,
1847                                   const PrintingPolicy &Policy) const;
1848
1849  static bool classof(const Type *T) { return T->getTypeClass() == TypeOfExpr; }
1850  static bool classof(const TypeOfExprType *) { return true; }
1851};
1852
1853/// Subclass of TypeOfExprType that is used for canonical, dependent
1854/// typeof(expr) types.
1855class DependentTypeOfExprType
1856  : public TypeOfExprType, public llvm::FoldingSetNode {
1857  ASTContext &Context;
1858
1859public:
1860  DependentTypeOfExprType(ASTContext &Context, Expr *E)
1861    : TypeOfExprType(E), Context(Context) { }
1862
1863  void Profile(llvm::FoldingSetNodeID &ID) {
1864    Profile(ID, Context, getUnderlyingExpr());
1865  }
1866
1867  static void Profile(llvm::FoldingSetNodeID &ID, ASTContext &Context,
1868                      Expr *E);
1869};
1870
1871/// TypeOfType (GCC extension).
1872class TypeOfType : public Type {
1873  QualType TOType;
1874  TypeOfType(QualType T, QualType can)
1875    : Type(TypeOf, can, T->isDependentType()), TOType(T) {
1876    assert(!isa<TypedefType>(can) && "Invalid canonical type");
1877  }
1878  friend class ASTContext;  // ASTContext creates these.
1879public:
1880  QualType getUnderlyingType() const { return TOType; }
1881
1882  virtual void getAsStringInternal(std::string &InnerString,
1883                                   const PrintingPolicy &Policy) const;
1884
1885  static bool classof(const Type *T) { return T->getTypeClass() == TypeOf; }
1886  static bool classof(const TypeOfType *) { return true; }
1887};
1888
1889/// DecltypeType (C++0x)
1890class DecltypeType : public Type {
1891  Expr *E;
1892
1893  // FIXME: We could get rid of UnderlyingType if we wanted to: We would have to
1894  // Move getDesugaredType to ASTContext so that it can call getDecltypeForExpr
1895  // from it.
1896  QualType UnderlyingType;
1897
1898protected:
1899  DecltypeType(Expr *E, QualType underlyingType, QualType can = QualType());
1900  friend class ASTContext;  // ASTContext creates these.
1901public:
1902  Expr *getUnderlyingExpr() const { return E; }
1903  QualType getUnderlyingType() const { return UnderlyingType; }
1904
1905  virtual void getAsStringInternal(std::string &InnerString,
1906                                   const PrintingPolicy &Policy) const;
1907
1908  static bool classof(const Type *T) { return T->getTypeClass() == Decltype; }
1909  static bool classof(const DecltypeType *) { return true; }
1910};
1911
1912/// Subclass of DecltypeType that is used for canonical, dependent
1913/// C++0x decltype types.
1914class DependentDecltypeType : public DecltypeType, public llvm::FoldingSetNode {
1915  ASTContext &Context;
1916
1917public:
1918  DependentDecltypeType(ASTContext &Context, Expr *E);
1919
1920  void Profile(llvm::FoldingSetNodeID &ID) {
1921    Profile(ID, Context, getUnderlyingExpr());
1922  }
1923
1924  static void Profile(llvm::FoldingSetNodeID &ID, ASTContext &Context,
1925                      Expr *E);
1926};
1927
1928class TagType : public Type {
1929  /// Stores the TagDecl associated with this type. The decl will
1930  /// point to the TagDecl that actually defines the entity (or is a
1931  /// definition in progress), if there is such a definition. The
1932  /// single-bit value will be non-zero when this tag is in the
1933  /// process of being defined.
1934  mutable llvm::PointerIntPair<TagDecl *, 1> decl;
1935  friend class ASTContext;
1936  friend class TagDecl;
1937
1938protected:
1939  TagType(TypeClass TC, TagDecl *D, QualType can);
1940
1941public:
1942  TagDecl *getDecl() const { return decl.getPointer(); }
1943
1944  /// @brief Determines whether this type is in the process of being
1945  /// defined.
1946  bool isBeingDefined() const { return decl.getInt(); }
1947  void setBeingDefined(bool Def) const { decl.setInt(Def? 1 : 0); }
1948
1949  virtual void getAsStringInternal(std::string &InnerString,
1950                                   const PrintingPolicy &Policy) const;
1951
1952  static bool classof(const Type *T) {
1953    return T->getTypeClass() >= TagFirst && T->getTypeClass() <= TagLast;
1954  }
1955  static bool classof(const TagType *) { return true; }
1956  static bool classof(const RecordType *) { return true; }
1957  static bool classof(const EnumType *) { return true; }
1958};
1959
1960/// RecordType - This is a helper class that allows the use of isa/cast/dyncast
1961/// to detect TagType objects of structs/unions/classes.
1962class RecordType : public TagType {
1963protected:
1964  explicit RecordType(RecordDecl *D)
1965    : TagType(Record, reinterpret_cast<TagDecl*>(D), QualType()) { }
1966  explicit RecordType(TypeClass TC, RecordDecl *D)
1967    : TagType(TC, reinterpret_cast<TagDecl*>(D), QualType()) { }
1968  friend class ASTContext;   // ASTContext creates these.
1969public:
1970
1971  RecordDecl *getDecl() const {
1972    return reinterpret_cast<RecordDecl*>(TagType::getDecl());
1973  }
1974
1975  // FIXME: This predicate is a helper to QualType/Type. It needs to
1976  // recursively check all fields for const-ness. If any field is declared
1977  // const, it needs to return false.
1978  bool hasConstFields() const { return false; }
1979
1980  // FIXME: RecordType needs to check when it is created that all fields are in
1981  // the same address space, and return that.
1982  unsigned getAddressSpace() const { return 0; }
1983
1984  static bool classof(const TagType *T);
1985  static bool classof(const Type *T) {
1986    return isa<TagType>(T) && classof(cast<TagType>(T));
1987  }
1988  static bool classof(const RecordType *) { return true; }
1989};
1990
1991/// EnumType - This is a helper class that allows the use of isa/cast/dyncast
1992/// to detect TagType objects of enums.
1993class EnumType : public TagType {
1994  explicit EnumType(EnumDecl *D)
1995    : TagType(Enum, reinterpret_cast<TagDecl*>(D), QualType()) { }
1996  friend class ASTContext;   // ASTContext creates these.
1997public:
1998
1999  EnumDecl *getDecl() const {
2000    return reinterpret_cast<EnumDecl*>(TagType::getDecl());
2001  }
2002
2003  static bool classof(const TagType *T);
2004  static bool classof(const Type *T) {
2005    return isa<TagType>(T) && classof(cast<TagType>(T));
2006  }
2007  static bool classof(const EnumType *) { return true; }
2008};
2009
2010/// ElaboratedType - A non-canonical type used to represents uses of
2011/// elaborated type specifiers in C++.  For example:
2012///
2013///   void foo(union MyUnion);
2014///            ^^^^^^^^^^^^^
2015///
2016/// At the moment, for efficiency we do not create elaborated types in
2017/// C, since outside of typedefs all references to structs would
2018/// necessarily be elaborated.
2019class ElaboratedType : public Type, public llvm::FoldingSetNode {
2020public:
2021  enum TagKind {
2022    TK_struct,
2023    TK_union,
2024    TK_class,
2025    TK_enum
2026  };
2027
2028private:
2029  /// The tag that was used in this elaborated type specifier.
2030  TagKind Tag;
2031
2032  /// The underlying type.
2033  QualType UnderlyingType;
2034
2035  explicit ElaboratedType(QualType Ty, TagKind Tag, QualType Canon)
2036    : Type(Elaborated, Canon, Canon->isDependentType()),
2037      Tag(Tag), UnderlyingType(Ty) { }
2038  friend class ASTContext;   // ASTContext creates these.
2039
2040public:
2041  TagKind getTagKind() const { return Tag; }
2042  QualType getUnderlyingType() const { return UnderlyingType; }
2043
2044  static const char *getNameForTagKind(TagKind Kind) {
2045    switch (Kind) {
2046    default: assert(0 && "Unknown TagKind!");
2047    case TK_struct: return "struct";
2048    case TK_union:  return "union";
2049    case TK_class:  return "class";
2050    case TK_enum:   return "enum";
2051    }
2052  }
2053
2054  virtual void getAsStringInternal(std::string &InnerString,
2055                                   const PrintingPolicy &Policy) const;
2056
2057  void Profile(llvm::FoldingSetNodeID &ID) {
2058    Profile(ID, getUnderlyingType(), getTagKind());
2059  }
2060  static void Profile(llvm::FoldingSetNodeID &ID, QualType T, TagKind Tag) {
2061    ID.AddPointer(T.getAsOpaquePtr());
2062    ID.AddInteger(Tag);
2063  }
2064
2065  static bool classof(const ElaboratedType*) { return true; }
2066  static bool classof(const Type *T) { return T->getTypeClass() == Elaborated; }
2067};
2068
2069class TemplateTypeParmType : public Type, public llvm::FoldingSetNode {
2070  unsigned Depth : 15;
2071  unsigned Index : 16;
2072  unsigned ParameterPack : 1;
2073  IdentifierInfo *Name;
2074
2075  TemplateTypeParmType(unsigned D, unsigned I, bool PP, IdentifierInfo *N,
2076                       QualType Canon)
2077    : Type(TemplateTypeParm, Canon, /*Dependent=*/true),
2078      Depth(D), Index(I), ParameterPack(PP), Name(N) { }
2079
2080  TemplateTypeParmType(unsigned D, unsigned I, bool PP)
2081    : Type(TemplateTypeParm, QualType(this, 0), /*Dependent=*/true),
2082      Depth(D), Index(I), ParameterPack(PP), Name(0) { }
2083
2084  friend class ASTContext;  // ASTContext creates these
2085
2086public:
2087  unsigned getDepth() const { return Depth; }
2088  unsigned getIndex() const { return Index; }
2089  bool isParameterPack() const { return ParameterPack; }
2090  IdentifierInfo *getName() const { return Name; }
2091
2092  virtual void getAsStringInternal(std::string &InnerString,
2093                                   const PrintingPolicy &Policy) const;
2094
2095  void Profile(llvm::FoldingSetNodeID &ID) {
2096    Profile(ID, Depth, Index, ParameterPack, Name);
2097  }
2098
2099  static void Profile(llvm::FoldingSetNodeID &ID, unsigned Depth,
2100                      unsigned Index, bool ParameterPack,
2101                      IdentifierInfo *Name) {
2102    ID.AddInteger(Depth);
2103    ID.AddInteger(Index);
2104    ID.AddBoolean(ParameterPack);
2105    ID.AddPointer(Name);
2106  }
2107
2108  static bool classof(const Type *T) {
2109    return T->getTypeClass() == TemplateTypeParm;
2110  }
2111  static bool classof(const TemplateTypeParmType *T) { return true; }
2112};
2113
2114/// \brief Represents the type of a template specialization as written
2115/// in the source code.
2116///
2117/// Template specialization types represent the syntactic form of a
2118/// template-id that refers to a type, e.g., @c vector<int>. Some
2119/// template specialization types are syntactic sugar, whose canonical
2120/// type will point to some other type node that represents the
2121/// instantiation or class template specialization. For example, a
2122/// class template specialization type of @c vector<int> will refer to
2123/// a tag type for the instantiation
2124/// @c std::vector<int, std::allocator<int>>.
2125///
2126/// Other template specialization types, for which the template name
2127/// is dependent, may be canonical types. These types are always
2128/// dependent.
2129class TemplateSpecializationType
2130  : public Type, public llvm::FoldingSetNode {
2131
2132  // FIXME: Currently needed for profiling expressions; can we avoid this?
2133  ASTContext &Context;
2134
2135    /// \brief The name of the template being specialized.
2136  TemplateName Template;
2137
2138  /// \brief - The number of template arguments named in this class
2139  /// template specialization.
2140  unsigned NumArgs;
2141
2142  TemplateSpecializationType(ASTContext &Context,
2143                             TemplateName T,
2144                             const TemplateArgument *Args,
2145                             unsigned NumArgs, QualType Canon);
2146
2147  virtual void Destroy(ASTContext& C);
2148
2149  friend class ASTContext;  // ASTContext creates these
2150
2151public:
2152  /// \brief Determine whether any of the given template arguments are
2153  /// dependent.
2154  static bool anyDependentTemplateArguments(const TemplateArgument *Args,
2155                                            unsigned NumArgs);
2156
2157  /// \brief Print a template argument list, including the '<' and '>'
2158  /// enclosing the template arguments.
2159  static std::string PrintTemplateArgumentList(const TemplateArgument *Args,
2160                                               unsigned NumArgs,
2161                                               const PrintingPolicy &Policy);
2162
2163  typedef const TemplateArgument * iterator;
2164
2165  iterator begin() const { return getArgs(); }
2166  iterator end() const;
2167
2168  /// \brief Retrieve the name of the template that we are specializing.
2169  TemplateName getTemplateName() const { return Template; }
2170
2171  /// \brief Retrieve the template arguments.
2172  const TemplateArgument *getArgs() const {
2173    return reinterpret_cast<const TemplateArgument *>(this + 1);
2174  }
2175
2176  /// \brief Retrieve the number of template arguments.
2177  unsigned getNumArgs() const { return NumArgs; }
2178
2179  /// \brief Retrieve a specific template argument as a type.
2180  /// \precondition @c isArgType(Arg)
2181  const TemplateArgument &getArg(unsigned Idx) const;
2182
2183  virtual void getAsStringInternal(std::string &InnerString,
2184                                   const PrintingPolicy &Policy) const;
2185
2186  void Profile(llvm::FoldingSetNodeID &ID) {
2187    Profile(ID, Template, getArgs(), NumArgs, Context);
2188  }
2189
2190  static void Profile(llvm::FoldingSetNodeID &ID, TemplateName T,
2191                      const TemplateArgument *Args, unsigned NumArgs,
2192                      ASTContext &Context);
2193
2194  static bool classof(const Type *T) {
2195    return T->getTypeClass() == TemplateSpecialization;
2196  }
2197  static bool classof(const TemplateSpecializationType *T) { return true; }
2198};
2199
2200/// \brief Represents a type that was referred to via a qualified
2201/// name, e.g., N::M::type.
2202///
2203/// This type is used to keep track of a type name as written in the
2204/// source code, including any nested-name-specifiers. The type itself
2205/// is always "sugar", used to express what was written in the source
2206/// code but containing no additional semantic information.
2207class QualifiedNameType : public Type, public llvm::FoldingSetNode {
2208  /// \brief The nested name specifier containing the qualifier.
2209  NestedNameSpecifier *NNS;
2210
2211  /// \brief The type that this qualified name refers to.
2212  QualType NamedType;
2213
2214  QualifiedNameType(NestedNameSpecifier *NNS, QualType NamedType,
2215                    QualType CanonType)
2216    : Type(QualifiedName, CanonType, NamedType->isDependentType()),
2217      NNS(NNS), NamedType(NamedType) { }
2218
2219  friend class ASTContext;  // ASTContext creates these
2220
2221public:
2222  /// \brief Retrieve the qualification on this type.
2223  NestedNameSpecifier *getQualifier() const { return NNS; }
2224
2225  /// \brief Retrieve the type named by the qualified-id.
2226  QualType getNamedType() const { return NamedType; }
2227
2228  virtual void getAsStringInternal(std::string &InnerString,
2229                                   const PrintingPolicy &Policy) const;
2230
2231  void Profile(llvm::FoldingSetNodeID &ID) {
2232    Profile(ID, NNS, NamedType);
2233  }
2234
2235  static void Profile(llvm::FoldingSetNodeID &ID, NestedNameSpecifier *NNS,
2236                      QualType NamedType) {
2237    ID.AddPointer(NNS);
2238    NamedType.Profile(ID);
2239  }
2240
2241  static bool classof(const Type *T) {
2242    return T->getTypeClass() == QualifiedName;
2243  }
2244  static bool classof(const QualifiedNameType *T) { return true; }
2245};
2246
2247/// \brief Represents a 'typename' specifier that names a type within
2248/// a dependent type, e.g., "typename T::type".
2249///
2250/// TypenameType has a very similar structure to QualifiedNameType,
2251/// which also involves a nested-name-specifier following by a type,
2252/// and (FIXME!) both can even be prefixed by the 'typename'
2253/// keyword. However, the two types serve very different roles:
2254/// QualifiedNameType is a non-semantic type that serves only as sugar
2255/// to show how a particular type was written in the source
2256/// code. TypenameType, on the other hand, only occurs when the
2257/// nested-name-specifier is dependent, such that we cannot resolve
2258/// the actual type until after instantiation.
2259class TypenameType : public Type, public llvm::FoldingSetNode {
2260  /// \brief The nested name specifier containing the qualifier.
2261  NestedNameSpecifier *NNS;
2262
2263  typedef llvm::PointerUnion<const IdentifierInfo *,
2264                             const TemplateSpecializationType *> NameType;
2265
2266  /// \brief The type that this typename specifier refers to.
2267  NameType Name;
2268
2269  TypenameType(NestedNameSpecifier *NNS, const IdentifierInfo *Name,
2270               QualType CanonType)
2271    : Type(Typename, CanonType, true), NNS(NNS), Name(Name) {
2272    assert(NNS->isDependent() &&
2273           "TypenameType requires a dependent nested-name-specifier");
2274  }
2275
2276  TypenameType(NestedNameSpecifier *NNS, const TemplateSpecializationType *Ty,
2277               QualType CanonType)
2278    : Type(Typename, CanonType, true), NNS(NNS), Name(Ty) {
2279    assert(NNS->isDependent() &&
2280           "TypenameType requires a dependent nested-name-specifier");
2281  }
2282
2283  friend class ASTContext;  // ASTContext creates these
2284
2285public:
2286  /// \brief Retrieve the qualification on this type.
2287  NestedNameSpecifier *getQualifier() const { return NNS; }
2288
2289  /// \brief Retrieve the type named by the typename specifier as an
2290  /// identifier.
2291  ///
2292  /// This routine will return a non-NULL identifier pointer when the
2293  /// form of the original typename was terminated by an identifier,
2294  /// e.g., "typename T::type".
2295  const IdentifierInfo *getIdentifier() const {
2296    return Name.dyn_cast<const IdentifierInfo *>();
2297  }
2298
2299  /// \brief Retrieve the type named by the typename specifier as a
2300  /// type specialization.
2301  const TemplateSpecializationType *getTemplateId() const {
2302    return Name.dyn_cast<const TemplateSpecializationType *>();
2303  }
2304
2305  virtual void getAsStringInternal(std::string &InnerString,
2306                                   const PrintingPolicy &Policy) const;
2307
2308  void Profile(llvm::FoldingSetNodeID &ID) {
2309    Profile(ID, NNS, Name);
2310  }
2311
2312  static void Profile(llvm::FoldingSetNodeID &ID, NestedNameSpecifier *NNS,
2313                      NameType Name) {
2314    ID.AddPointer(NNS);
2315    ID.AddPointer(Name.getOpaqueValue());
2316  }
2317
2318  static bool classof(const Type *T) {
2319    return T->getTypeClass() == Typename;
2320  }
2321  static bool classof(const TypenameType *T) { return true; }
2322};
2323
2324/// ObjCInterfaceType - Interfaces are the core concept in Objective-C for
2325/// object oriented design.  They basically correspond to C++ classes.  There
2326/// are two kinds of interface types, normal interfaces like "NSString" and
2327/// qualified interfaces, which are qualified with a protocol list like
2328/// "NSString<NSCopyable, NSAmazing>".
2329class ObjCInterfaceType : public Type, public llvm::FoldingSetNode {
2330  ObjCInterfaceDecl *Decl;
2331
2332  // List of protocols for this protocol conforming object type
2333  // List is sorted on protocol name. No protocol is enterred more than once.
2334  llvm::SmallVector<ObjCProtocolDecl*, 4> Protocols;
2335
2336  ObjCInterfaceType(ObjCInterfaceDecl *D,
2337                    ObjCProtocolDecl **Protos, unsigned NumP) :
2338    Type(ObjCInterface, QualType(), /*Dependent=*/false),
2339    Decl(D), Protocols(Protos, Protos+NumP) { }
2340  friend class ASTContext;  // ASTContext creates these.
2341public:
2342  ObjCInterfaceDecl *getDecl() const { return Decl; }
2343
2344  /// getNumProtocols - Return the number of qualifying protocols in this
2345  /// interface type, or 0 if there are none.
2346  unsigned getNumProtocols() const { return Protocols.size(); }
2347
2348  /// qual_iterator and friends: this provides access to the (potentially empty)
2349  /// list of protocols qualifying this interface.
2350  typedef llvm::SmallVector<ObjCProtocolDecl*, 8>::const_iterator qual_iterator;
2351  qual_iterator qual_begin() const { return Protocols.begin(); }
2352  qual_iterator qual_end() const   { return Protocols.end(); }
2353  bool qual_empty() const { return Protocols.size() == 0; }
2354
2355  virtual void getAsStringInternal(std::string &InnerString,
2356                                   const PrintingPolicy &Policy) const;
2357
2358  void Profile(llvm::FoldingSetNodeID &ID);
2359  static void Profile(llvm::FoldingSetNodeID &ID,
2360                      const ObjCInterfaceDecl *Decl,
2361                      ObjCProtocolDecl **protocols, unsigned NumProtocols);
2362
2363  static bool classof(const Type *T) {
2364    return T->getTypeClass() == ObjCInterface;
2365  }
2366  static bool classof(const ObjCInterfaceType *) { return true; }
2367};
2368
2369/// ObjCObjectPointerType - Used to represent 'id', 'Interface *', 'id <p>',
2370/// and 'Interface <p> *'.
2371///
2372/// Duplicate protocols are removed and protocol list is canonicalized to be in
2373/// alphabetical order.
2374class ObjCObjectPointerType : public Type, public llvm::FoldingSetNode {
2375  QualType PointeeType; // A builtin or interface type.
2376
2377  // List of protocols for this protocol conforming object type
2378  // List is sorted on protocol name. No protocol is entered more than once.
2379  llvm::SmallVector<ObjCProtocolDecl*, 8> Protocols;
2380
2381  ObjCObjectPointerType(QualType T, ObjCProtocolDecl **Protos, unsigned NumP) :
2382    Type(ObjCObjectPointer, QualType(), /*Dependent=*/false),
2383    PointeeType(T), Protocols(Protos, Protos+NumP) { }
2384  friend class ASTContext;  // ASTContext creates these.
2385
2386public:
2387  // Get the pointee type. Pointee will either be:
2388  // - a built-in type (for 'id' and 'Class').
2389  // - an interface type (for user-defined types).
2390  // - a TypedefType whose canonical type is an interface (as in 'T' below).
2391  //   For example: typedef NSObject T; T *var;
2392  QualType getPointeeType() const { return PointeeType; }
2393
2394  const ObjCInterfaceType *getInterfaceType() const {
2395    return PointeeType->getAs<ObjCInterfaceType>();
2396  }
2397  /// getInterfaceDecl - returns an interface decl for user-defined types.
2398  ObjCInterfaceDecl *getInterfaceDecl() const {
2399    return getInterfaceType() ? getInterfaceType()->getDecl() : 0;
2400  }
2401  /// isObjCIdType - true for "id".
2402  bool isObjCIdType() const {
2403    return getPointeeType()->isSpecificBuiltinType(BuiltinType::ObjCId) &&
2404           !Protocols.size();
2405  }
2406  /// isObjCClassType - true for "Class".
2407  bool isObjCClassType() const {
2408    return getPointeeType()->isSpecificBuiltinType(BuiltinType::ObjCClass) &&
2409           !Protocols.size();
2410  }
2411  /// isObjCQualifiedIdType - true for "id <p>".
2412  bool isObjCQualifiedIdType() const {
2413    return getPointeeType()->isSpecificBuiltinType(BuiltinType::ObjCId) &&
2414           Protocols.size();
2415  }
2416  /// isObjCQualifiedClassType - true for "Class <p>".
2417  bool isObjCQualifiedClassType() const {
2418    return getPointeeType()->isSpecificBuiltinType(BuiltinType::ObjCClass) &&
2419           Protocols.size();
2420  }
2421  /// qual_iterator and friends: this provides access to the (potentially empty)
2422  /// list of protocols qualifying this interface.
2423  typedef llvm::SmallVector<ObjCProtocolDecl*, 8>::const_iterator qual_iterator;
2424
2425  qual_iterator qual_begin() const { return Protocols.begin(); }
2426  qual_iterator qual_end() const   { return Protocols.end(); }
2427  bool qual_empty() const { return Protocols.size() == 0; }
2428
2429  /// getNumProtocols - Return the number of qualifying protocols in this
2430  /// interface type, or 0 if there are none.
2431  unsigned getNumProtocols() const { return Protocols.size(); }
2432
2433  void Profile(llvm::FoldingSetNodeID &ID);
2434  static void Profile(llvm::FoldingSetNodeID &ID, QualType T,
2435                      ObjCProtocolDecl **protocols, unsigned NumProtocols);
2436  virtual void getAsStringInternal(std::string &InnerString,
2437                                   const PrintingPolicy &Policy) const;
2438  static bool classof(const Type *T) {
2439    return T->getTypeClass() == ObjCObjectPointer;
2440  }
2441  static bool classof(const ObjCObjectPointerType *) { return true; }
2442};
2443
2444/// A qualifier set is used to build a set of qualifiers.
2445class QualifierCollector : public Qualifiers {
2446  ASTContext *Context;
2447
2448public:
2449  QualifierCollector(Qualifiers Qs = Qualifiers())
2450    : Qualifiers(Qs), Context(0) {}
2451  QualifierCollector(ASTContext &Context, Qualifiers Qs = Qualifiers())
2452    : Qualifiers(Qs), Context(&Context) {}
2453
2454  void setContext(ASTContext &C) { Context = &C; }
2455
2456  /// Collect any qualifiers on the given type and return an
2457  /// unqualified type.
2458  const Type *strip(QualType QT) {
2459    addFastQualifiers(QT.getFastQualifiers());
2460    if (QT.hasNonFastQualifiers()) {
2461      const ExtQuals *EQ = QT.getExtQualsUnsafe();
2462      Context = &EQ->getContext();
2463      addQualifiers(EQ->getQualifiers());
2464      return EQ->getBaseType();
2465    }
2466    return QT.getTypePtrUnsafe();
2467  }
2468
2469  /// Apply the collected qualifiers to the given type.
2470  QualType apply(QualType QT) const;
2471
2472  /// Apply the collected qualifiers to the given type.
2473  QualType apply(const Type* T) const;
2474
2475};
2476
2477
2478// Inline function definitions.
2479
2480inline void QualType::removeConst() {
2481  removeFastQualifiers(Qualifiers::Const);
2482}
2483
2484inline void QualType::removeRestrict() {
2485  removeFastQualifiers(Qualifiers::Restrict);
2486}
2487
2488inline void QualType::removeVolatile() {
2489  QualifierCollector Qc;
2490  const Type *Ty = Qc.strip(*this);
2491  if (Qc.hasVolatile()) {
2492    Qc.removeVolatile();
2493    *this = Qc.apply(Ty);
2494  }
2495}
2496
2497inline void QualType::removeCVRQualifiers(unsigned Mask) {
2498  assert(!(Mask & ~Qualifiers::CVRMask) && "mask has non-CVR bits");
2499
2500  // Fast path: we don't need to touch the slow qualifiers.
2501  if (!(Mask & ~Qualifiers::FastMask)) {
2502    removeFastQualifiers(Mask);
2503    return;
2504  }
2505
2506  QualifierCollector Qc;
2507  const Type *Ty = Qc.strip(*this);
2508  Qc.removeCVRQualifiers(Mask);
2509  *this = Qc.apply(Ty);
2510}
2511
2512/// getAddressSpace - Return the address space of this type.
2513inline unsigned QualType::getAddressSpace() const {
2514  if (hasNonFastQualifiers()) {
2515    const ExtQuals *EQ = getExtQualsUnsafe();
2516    if (EQ->hasAddressSpace())
2517      return EQ->getAddressSpace();
2518  }
2519
2520  QualType CT = getTypePtr()->getCanonicalTypeInternal();
2521  if (CT.hasNonFastQualifiers()) {
2522    const ExtQuals *EQ = CT.getExtQualsUnsafe();
2523    if (EQ->hasAddressSpace())
2524      return EQ->getAddressSpace();
2525  }
2526
2527  if (const ArrayType *AT = dyn_cast<ArrayType>(CT))
2528    return AT->getElementType().getAddressSpace();
2529  if (const RecordType *RT = dyn_cast<RecordType>(CT))
2530    return RT->getAddressSpace();
2531  return 0;
2532}
2533
2534/// getObjCGCAttr - Return the gc attribute of this type.
2535inline Qualifiers::GC QualType::getObjCGCAttr() const {
2536  if (hasNonFastQualifiers()) {
2537    const ExtQuals *EQ = getExtQualsUnsafe();
2538    if (EQ->hasObjCGCAttr())
2539      return EQ->getObjCGCAttr();
2540  }
2541
2542  QualType CT = getTypePtr()->getCanonicalTypeInternal();
2543  if (CT.hasNonFastQualifiers()) {
2544    const ExtQuals *EQ = CT.getExtQualsUnsafe();
2545    if (EQ->hasObjCGCAttr())
2546      return EQ->getObjCGCAttr();
2547  }
2548
2549  if (const ArrayType *AT = dyn_cast<ArrayType>(CT))
2550      return AT->getElementType().getObjCGCAttr();
2551  if (const ObjCObjectPointerType *PT = CT->getAs<ObjCObjectPointerType>())
2552    return PT->getPointeeType().getObjCGCAttr();
2553  // We most look at all pointer types, not just pointer to interface types.
2554  if (const PointerType *PT = CT->getAs<PointerType>())
2555    return PT->getPointeeType().getObjCGCAttr();
2556  return Qualifiers::GCNone;
2557}
2558
2559  /// getNoReturnAttr - Returns true if the type has the noreturn attribute,
2560  /// false otherwise.
2561inline bool QualType::getNoReturnAttr() const {
2562  QualType CT = getTypePtr()->getCanonicalTypeInternal();
2563  if (const PointerType *PT = getTypePtr()->getAs<PointerType>()) {
2564    if (const FunctionType *FT = PT->getPointeeType()->getAs<FunctionType>())
2565      return FT->getNoReturnAttr();
2566  } else if (const FunctionType *FT = getTypePtr()->getAs<FunctionType>())
2567    return FT->getNoReturnAttr();
2568
2569  return false;
2570}
2571
2572/// isMoreQualifiedThan - Determine whether this type is more
2573/// qualified than the Other type. For example, "const volatile int"
2574/// is more qualified than "const int", "volatile int", and
2575/// "int". However, it is not more qualified than "const volatile
2576/// int".
2577inline bool QualType::isMoreQualifiedThan(QualType Other) const {
2578  // FIXME: work on arbitrary qualifiers
2579  unsigned MyQuals = this->getCVRQualifiers();
2580  unsigned OtherQuals = Other.getCVRQualifiers();
2581  if (getAddressSpace() != Other.getAddressSpace())
2582    return false;
2583  return MyQuals != OtherQuals && (MyQuals | OtherQuals) == MyQuals;
2584}
2585
2586/// isAtLeastAsQualifiedAs - Determine whether this type is at last
2587/// as qualified as the Other type. For example, "const volatile
2588/// int" is at least as qualified as "const int", "volatile int",
2589/// "int", and "const volatile int".
2590inline bool QualType::isAtLeastAsQualifiedAs(QualType Other) const {
2591  // FIXME: work on arbitrary qualifiers
2592  unsigned MyQuals = this->getCVRQualifiers();
2593  unsigned OtherQuals = Other.getCVRQualifiers();
2594  if (getAddressSpace() != Other.getAddressSpace())
2595    return false;
2596  return (MyQuals | OtherQuals) == MyQuals;
2597}
2598
2599/// getNonReferenceType - If Type is a reference type (e.g., const
2600/// int&), returns the type that the reference refers to ("const
2601/// int"). Otherwise, returns the type itself. This routine is used
2602/// throughout Sema to implement C++ 5p6:
2603///
2604///   If an expression initially has the type "reference to T" (8.3.2,
2605///   8.5.3), the type is adjusted to "T" prior to any further
2606///   analysis, the expression designates the object or function
2607///   denoted by the reference, and the expression is an lvalue.
2608inline QualType QualType::getNonReferenceType() const {
2609  if (const ReferenceType *RefType = (*this)->getAs<ReferenceType>())
2610    return RefType->getPointeeType();
2611  else
2612    return *this;
2613}
2614
2615inline const ObjCInterfaceType *Type::getAsPointerToObjCInterfaceType() const {
2616  if (const PointerType *PT = getAs<PointerType>())
2617    return PT->getPointeeType()->getAs<ObjCInterfaceType>();
2618  return 0;
2619}
2620
2621// NOTE: All of these methods use "getUnqualifiedType" to strip off address
2622// space qualifiers if present.
2623inline bool Type::isFunctionType() const {
2624  return isa<FunctionType>(CanonicalType.getUnqualifiedType());
2625}
2626inline bool Type::isPointerType() const {
2627  return isa<PointerType>(CanonicalType.getUnqualifiedType());
2628}
2629inline bool Type::isAnyPointerType() const {
2630  return isPointerType() || isObjCObjectPointerType();
2631}
2632inline bool Type::isBlockPointerType() const {
2633  return isa<BlockPointerType>(CanonicalType.getUnqualifiedType());
2634}
2635inline bool Type::isReferenceType() const {
2636  return isa<ReferenceType>(CanonicalType.getUnqualifiedType());
2637}
2638inline bool Type::isLValueReferenceType() const {
2639  return isa<LValueReferenceType>(CanonicalType.getUnqualifiedType());
2640}
2641inline bool Type::isRValueReferenceType() const {
2642  return isa<RValueReferenceType>(CanonicalType.getUnqualifiedType());
2643}
2644inline bool Type::isFunctionPointerType() const {
2645  if (const PointerType* T = getAs<PointerType>())
2646    return T->getPointeeType()->isFunctionType();
2647  else
2648    return false;
2649}
2650inline bool Type::isMemberPointerType() const {
2651  return isa<MemberPointerType>(CanonicalType.getUnqualifiedType());
2652}
2653inline bool Type::isMemberFunctionPointerType() const {
2654  if (const MemberPointerType* T = getAs<MemberPointerType>())
2655    return T->getPointeeType()->isFunctionType();
2656  else
2657    return false;
2658}
2659inline bool Type::isArrayType() const {
2660  return isa<ArrayType>(CanonicalType.getUnqualifiedType());
2661}
2662inline bool Type::isConstantArrayType() const {
2663  return isa<ConstantArrayType>(CanonicalType.getUnqualifiedType());
2664}
2665inline bool Type::isIncompleteArrayType() const {
2666  return isa<IncompleteArrayType>(CanonicalType.getUnqualifiedType());
2667}
2668inline bool Type::isVariableArrayType() const {
2669  return isa<VariableArrayType>(CanonicalType.getUnqualifiedType());
2670}
2671inline bool Type::isDependentSizedArrayType() const {
2672  return isa<DependentSizedArrayType>(CanonicalType.getUnqualifiedType());
2673}
2674inline bool Type::isRecordType() const {
2675  return isa<RecordType>(CanonicalType.getUnqualifiedType());
2676}
2677inline bool Type::isAnyComplexType() const {
2678  return isa<ComplexType>(CanonicalType.getUnqualifiedType());
2679}
2680inline bool Type::isVectorType() const {
2681  return isa<VectorType>(CanonicalType.getUnqualifiedType());
2682}
2683inline bool Type::isExtVectorType() const {
2684  return isa<ExtVectorType>(CanonicalType.getUnqualifiedType());
2685}
2686inline bool Type::isObjCObjectPointerType() const {
2687  return isa<ObjCObjectPointerType>(CanonicalType.getUnqualifiedType());
2688}
2689inline bool Type::isObjCInterfaceType() const {
2690  return isa<ObjCInterfaceType>(CanonicalType.getUnqualifiedType());
2691}
2692inline bool Type::isObjCQualifiedIdType() const {
2693  if (const ObjCObjectPointerType *OPT = getAs<ObjCObjectPointerType>())
2694    return OPT->isObjCQualifiedIdType();
2695  return false;
2696}
2697inline bool Type::isObjCQualifiedClassType() const {
2698  if (const ObjCObjectPointerType *OPT = getAs<ObjCObjectPointerType>())
2699    return OPT->isObjCQualifiedClassType();
2700  return false;
2701}
2702inline bool Type::isObjCIdType() const {
2703  if (const ObjCObjectPointerType *OPT = getAs<ObjCObjectPointerType>())
2704    return OPT->isObjCIdType();
2705  return false;
2706}
2707inline bool Type::isObjCClassType() const {
2708  if (const ObjCObjectPointerType *OPT = getAs<ObjCObjectPointerType>())
2709    return OPT->isObjCClassType();
2710  return false;
2711}
2712inline bool Type::isObjCBuiltinType() const {
2713  return isObjCIdType() || isObjCClassType();
2714}
2715inline bool Type::isTemplateTypeParmType() const {
2716  return isa<TemplateTypeParmType>(CanonicalType.getUnqualifiedType());
2717}
2718
2719inline bool Type::isSpecificBuiltinType(unsigned K) const {
2720  if (const BuiltinType *BT = getAs<BuiltinType>())
2721    if (BT->getKind() == (BuiltinType::Kind) K)
2722      return true;
2723  return false;
2724}
2725
2726/// \brief Determines whether this is a type for which one can define
2727/// an overloaded operator.
2728inline bool Type::isOverloadableType() const {
2729  return isDependentType() || isRecordType() || isEnumeralType();
2730}
2731
2732inline bool Type::hasPointerRepresentation() const {
2733  return (isPointerType() || isReferenceType() || isBlockPointerType() ||
2734          isObjCInterfaceType() || isObjCObjectPointerType() ||
2735          isObjCQualifiedInterfaceType() || isNullPtrType());
2736}
2737
2738inline bool Type::hasObjCPointerRepresentation() const {
2739  return (isObjCInterfaceType() || isObjCObjectPointerType() ||
2740          isObjCQualifiedInterfaceType());
2741}
2742
2743/// Insertion operator for diagnostics.  This allows sending QualType's into a
2744/// diagnostic with <<.
2745inline const DiagnosticBuilder &operator<<(const DiagnosticBuilder &DB,
2746                                           QualType T) {
2747  DB.AddTaggedVal(reinterpret_cast<intptr_t>(T.getAsOpaquePtr()),
2748                  Diagnostic::ak_qualtype);
2749  return DB;
2750}
2751
2752/// Member-template getAs<specific type>'.
2753template <typename T> const T *Type::getAs() const {
2754  // If this is directly a T type, return it.
2755  if (const T *Ty = dyn_cast<T>(this))
2756    return Ty;
2757
2758  // If the canonical form of this type isn't the right kind, reject it.
2759  if (!isa<T>(CanonicalType))
2760    return 0;
2761
2762  // If this is a typedef for the type, strip the typedef off without
2763  // losing all typedef information.
2764  return cast<T>(getDesugaredType());
2765}
2766
2767}  // end namespace clang
2768
2769#endif
2770