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