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