Type.h revision 25560122fbc4a39c864695b170e4ff9009e1f273
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  // Type Checking Functions: Check to see if this type is structurally the
933  // specified type, ignoring typedefs and qualifiers, and return a pointer to
934  // the best type we can.
935  const RecordType *getAsStructureType() const;
936  /// NOTE: getAs*ArrayType are methods on ASTContext.
937  const RecordType *getAsUnionType() const;
938  const ComplexType *getAsComplexIntegerType() const; // GCC complex int type.
939  // The following is a convenience method that returns an ObjCObjectPointerType
940  // for object declared using an interface.
941  const ObjCObjectPointerType *getAsObjCInterfacePointerType() const;
942  const ObjCObjectPointerType *getAsObjCQualifiedIdType() const;
943  const ObjCObjectType *getAsObjCQualifiedInterfaceType() const;
944  const CXXRecordDecl *getCXXRecordDeclForPointerType() const;
945
946  /// \brief Retrieves the CXXRecordDecl that this type refers to, either
947  /// because the type is a RecordType or because it is the injected-class-name
948  /// type of a class template or class template partial specialization.
949  CXXRecordDecl *getAsCXXRecordDecl() const;
950
951  // Member-template getAs<specific type>'.  This scheme will eventually
952  // replace the specific getAsXXXX methods above.
953  //
954  // There are some specializations of this member template listed
955  // immediately following this class.
956  template <typename T> const T *getAs() const;
957
958  /// getArrayElementTypeNoTypeQual - If this is an array type, return the
959  /// element type of the array, potentially with type qualifiers missing.
960  /// This method should never be used when type qualifiers are meaningful.
961  const Type *getArrayElementTypeNoTypeQual() const;
962
963  /// getPointeeType - If this is a pointer, ObjC object pointer, or block
964  /// pointer, this returns the respective pointee.
965  QualType getPointeeType() const;
966
967  /// getUnqualifiedDesugaredType() - Return the specified type with
968  /// any "sugar" removed from the type, removing any typedefs,
969  /// typeofs, etc., as well as any qualifiers.
970  const Type *getUnqualifiedDesugaredType() const;
971
972  /// More type predicates useful for type checking/promotion
973  bool isPromotableIntegerType() const; // C99 6.3.1.1p2
974
975  /// isSignedIntegerType - Return true if this is an integer type that is
976  /// signed, according to C99 6.2.5p4 [char, signed char, short, int, long..],
977  /// an enum decl which has a signed representation, or a vector of signed
978  /// integer element type.
979  bool isSignedIntegerType() const;
980
981  /// isUnsignedIntegerType - Return true if this is an integer type that is
982  /// unsigned, according to C99 6.2.5p6 [which returns true for _Bool], an enum
983  /// decl which has an unsigned representation, or a vector of unsigned integer
984  /// element type.
985  bool isUnsignedIntegerType() const;
986
987  /// isConstantSizeType - Return true if this is not a variable sized type,
988  /// according to the rules of C99 6.7.5p3.  It is not legal to call this on
989  /// incomplete types.
990  bool isConstantSizeType() const;
991
992  /// isSpecifierType - Returns true if this type can be represented by some
993  /// set of type specifiers.
994  bool isSpecifierType() const;
995
996  /// \brief Determine the linkage of this type.
997  Linkage getLinkage() const;
998
999  /// \brief Note that the linkage is no longer known.
1000  void ClearLinkageCache();
1001
1002  const char *getTypeClassName() const;
1003
1004  QualType getCanonicalTypeInternal() const {
1005    return CanonicalType;
1006  }
1007  CanQualType getCanonicalTypeUnqualified() const; // in CanonicalType.h
1008  void dump() const;
1009  static bool classof(const Type *) { return true; }
1010};
1011
1012template <> inline const TypedefType *Type::getAs() const {
1013  return dyn_cast<TypedefType>(this);
1014}
1015
1016// We can do canonical leaf types faster, because we don't have to
1017// worry about preserving child type decoration.
1018#define TYPE(Class, Base)
1019#define LEAF_TYPE(Class) \
1020template <> inline const Class##Type *Type::getAs() const { \
1021  return dyn_cast<Class##Type>(CanonicalType); \
1022}
1023#include "clang/AST/TypeNodes.def"
1024
1025
1026/// BuiltinType - This class is used for builtin types like 'int'.  Builtin
1027/// types are always canonical and have a literal name field.
1028class BuiltinType : public Type {
1029public:
1030  enum Kind {
1031    Void,
1032
1033    Bool,     // This is bool and/or _Bool.
1034    Char_U,   // This is 'char' for targets where char is unsigned.
1035    UChar,    // This is explicitly qualified unsigned char.
1036    Char16,   // This is 'char16_t' for C++.
1037    Char32,   // This is 'char32_t' for C++.
1038    UShort,
1039    UInt,
1040    ULong,
1041    ULongLong,
1042    UInt128,  // __uint128_t
1043
1044    Char_S,   // This is 'char' for targets where char is signed.
1045    SChar,    // This is explicitly qualified signed char.
1046    WChar,    // This is 'wchar_t' for C++.
1047    Short,
1048    Int,
1049    Long,
1050    LongLong,
1051    Int128,   // __int128_t
1052
1053    Float, Double, LongDouble,
1054
1055    NullPtr,  // This is the type of C++0x 'nullptr'.
1056
1057    Overload,  // This represents the type of an overloaded function declaration.
1058    Dependent, // This represents the type of a type-dependent expression.
1059
1060    UndeducedAuto, // In C++0x, this represents the type of an auto variable
1061                   // that has not been deduced yet.
1062
1063    /// The primitive Objective C 'id' type.  The type pointed to by the
1064    /// user-visible 'id' type.  Only ever shows up in an AST as the base
1065    /// type of an ObjCObjectType.
1066    ObjCId,
1067
1068    /// The primitive Objective C 'Class' type.  The type pointed to by the
1069    /// user-visible 'Class' type.  Only ever shows up in an AST as the
1070    /// base type of an ObjCObjectType.
1071    ObjCClass,
1072
1073    ObjCSel    // This represents the ObjC 'SEL' type.
1074  };
1075private:
1076  Kind TypeKind;
1077
1078protected:
1079  virtual Linkage getLinkageImpl() const;
1080
1081public:
1082  BuiltinType(Kind K)
1083    : Type(Builtin, QualType(), /*Dependent=*/(K == Dependent)),
1084      TypeKind(K) {}
1085
1086  Kind getKind() const { return TypeKind; }
1087  const char *getName(const LangOptions &LO) const;
1088
1089  bool isSugared() const { return false; }
1090  QualType desugar() const { return QualType(this, 0); }
1091
1092  bool isInteger() const {
1093    return TypeKind >= Bool && TypeKind <= Int128;
1094  }
1095
1096  bool isSignedInteger() const {
1097    return TypeKind >= Char_S && TypeKind <= Int128;
1098  }
1099
1100  bool isUnsignedInteger() const {
1101    return TypeKind >= Bool && TypeKind <= UInt128;
1102  }
1103
1104  bool isFloatingPoint() const {
1105    return TypeKind >= Float && TypeKind <= LongDouble;
1106  }
1107
1108  static bool classof(const Type *T) { return T->getTypeClass() == Builtin; }
1109  static bool classof(const BuiltinType *) { return true; }
1110};
1111
1112/// ComplexType - C99 6.2.5p11 - Complex values.  This supports the C99 complex
1113/// types (_Complex float etc) as well as the GCC integer complex extensions.
1114///
1115class ComplexType : public Type, public llvm::FoldingSetNode {
1116  QualType ElementType;
1117  ComplexType(QualType Element, QualType CanonicalPtr) :
1118    Type(Complex, CanonicalPtr, Element->isDependentType()),
1119    ElementType(Element) {
1120  }
1121  friend class ASTContext;  // ASTContext creates these.
1122
1123protected:
1124  virtual Linkage getLinkageImpl() const;
1125
1126public:
1127  QualType getElementType() const { return ElementType; }
1128
1129  bool isSugared() const { return false; }
1130  QualType desugar() const { return QualType(this, 0); }
1131
1132  void Profile(llvm::FoldingSetNodeID &ID) {
1133    Profile(ID, getElementType());
1134  }
1135  static void Profile(llvm::FoldingSetNodeID &ID, QualType Element) {
1136    ID.AddPointer(Element.getAsOpaquePtr());
1137  }
1138
1139  static bool classof(const Type *T) { return T->getTypeClass() == Complex; }
1140  static bool classof(const ComplexType *) { return true; }
1141};
1142
1143/// PointerType - C99 6.7.5.1 - Pointer Declarators.
1144///
1145class PointerType : public Type, public llvm::FoldingSetNode {
1146  QualType PointeeType;
1147
1148  PointerType(QualType Pointee, QualType CanonicalPtr) :
1149    Type(Pointer, CanonicalPtr, Pointee->isDependentType()), PointeeType(Pointee) {
1150  }
1151  friend class ASTContext;  // ASTContext creates these.
1152
1153protected:
1154  virtual Linkage getLinkageImpl() const;
1155
1156public:
1157
1158  QualType getPointeeType() const { return PointeeType; }
1159
1160  bool isSugared() const { return false; }
1161  QualType desugar() const { return QualType(this, 0); }
1162
1163  void Profile(llvm::FoldingSetNodeID &ID) {
1164    Profile(ID, getPointeeType());
1165  }
1166  static void Profile(llvm::FoldingSetNodeID &ID, QualType Pointee) {
1167    ID.AddPointer(Pointee.getAsOpaquePtr());
1168  }
1169
1170  static bool classof(const Type *T) { return T->getTypeClass() == Pointer; }
1171  static bool classof(const PointerType *) { return true; }
1172};
1173
1174/// BlockPointerType - pointer to a block type.
1175/// This type is to represent types syntactically represented as
1176/// "void (^)(int)", etc. Pointee is required to always be a function type.
1177///
1178class BlockPointerType : public Type, public llvm::FoldingSetNode {
1179  QualType PointeeType;  // Block is some kind of pointer type
1180  BlockPointerType(QualType Pointee, QualType CanonicalCls) :
1181    Type(BlockPointer, CanonicalCls, Pointee->isDependentType()),
1182    PointeeType(Pointee) {
1183  }
1184  friend class ASTContext;  // ASTContext creates these.
1185
1186protected:
1187  virtual Linkage getLinkageImpl() const;
1188
1189public:
1190
1191  // Get the pointee type. Pointee is required to always be a function type.
1192  QualType getPointeeType() const { return PointeeType; }
1193
1194  bool isSugared() const { return false; }
1195  QualType desugar() const { return QualType(this, 0); }
1196
1197  void Profile(llvm::FoldingSetNodeID &ID) {
1198      Profile(ID, getPointeeType());
1199  }
1200  static void Profile(llvm::FoldingSetNodeID &ID, QualType Pointee) {
1201      ID.AddPointer(Pointee.getAsOpaquePtr());
1202  }
1203
1204  static bool classof(const Type *T) {
1205    return T->getTypeClass() == BlockPointer;
1206  }
1207  static bool classof(const BlockPointerType *) { return true; }
1208};
1209
1210/// ReferenceType - Base for LValueReferenceType and RValueReferenceType
1211///
1212class ReferenceType : public Type, public llvm::FoldingSetNode {
1213  QualType PointeeType;
1214
1215  /// True if the type was originally spelled with an lvalue sigil.
1216  /// This is never true of rvalue references but can also be false
1217  /// on lvalue references because of C++0x [dcl.typedef]p9,
1218  /// as follows:
1219  ///
1220  ///   typedef int &ref;    // lvalue, spelled lvalue
1221  ///   typedef int &&rvref; // rvalue
1222  ///   ref &a;              // lvalue, inner ref, spelled lvalue
1223  ///   ref &&a;             // lvalue, inner ref
1224  ///   rvref &a;            // lvalue, inner ref, spelled lvalue
1225  ///   rvref &&a;           // rvalue, inner ref
1226  bool SpelledAsLValue;
1227
1228  /// True if the inner type is a reference type.  This only happens
1229  /// in non-canonical forms.
1230  bool InnerRef;
1231
1232protected:
1233  ReferenceType(TypeClass tc, QualType Referencee, QualType CanonicalRef,
1234                bool SpelledAsLValue) :
1235    Type(tc, CanonicalRef, Referencee->isDependentType()),
1236    PointeeType(Referencee), SpelledAsLValue(SpelledAsLValue),
1237    InnerRef(Referencee->isReferenceType()) {
1238  }
1239
1240  virtual Linkage getLinkageImpl() const;
1241
1242public:
1243  bool isSpelledAsLValue() const { return SpelledAsLValue; }
1244  bool isInnerRef() const { return InnerRef; }
1245
1246  QualType getPointeeTypeAsWritten() const { return PointeeType; }
1247  QualType getPointeeType() const {
1248    // FIXME: this might strip inner qualifiers; okay?
1249    const ReferenceType *T = this;
1250    while (T->InnerRef)
1251      T = T->PointeeType->getAs<ReferenceType>();
1252    return T->PointeeType;
1253  }
1254
1255  void Profile(llvm::FoldingSetNodeID &ID) {
1256    Profile(ID, PointeeType, SpelledAsLValue);
1257  }
1258  static void Profile(llvm::FoldingSetNodeID &ID,
1259                      QualType Referencee,
1260                      bool SpelledAsLValue) {
1261    ID.AddPointer(Referencee.getAsOpaquePtr());
1262    ID.AddBoolean(SpelledAsLValue);
1263  }
1264
1265  static bool classof(const Type *T) {
1266    return T->getTypeClass() == LValueReference ||
1267           T->getTypeClass() == RValueReference;
1268  }
1269  static bool classof(const ReferenceType *) { return true; }
1270};
1271
1272/// LValueReferenceType - C++ [dcl.ref] - Lvalue reference
1273///
1274class LValueReferenceType : public ReferenceType {
1275  LValueReferenceType(QualType Referencee, QualType CanonicalRef,
1276                      bool SpelledAsLValue) :
1277    ReferenceType(LValueReference, Referencee, CanonicalRef, SpelledAsLValue)
1278  {}
1279  friend class ASTContext; // ASTContext creates these
1280public:
1281  bool isSugared() const { return false; }
1282  QualType desugar() const { return QualType(this, 0); }
1283
1284  static bool classof(const Type *T) {
1285    return T->getTypeClass() == LValueReference;
1286  }
1287  static bool classof(const LValueReferenceType *) { return true; }
1288};
1289
1290/// RValueReferenceType - C++0x [dcl.ref] - Rvalue reference
1291///
1292class RValueReferenceType : public ReferenceType {
1293  RValueReferenceType(QualType Referencee, QualType CanonicalRef) :
1294    ReferenceType(RValueReference, Referencee, CanonicalRef, false) {
1295  }
1296  friend class ASTContext; // ASTContext creates these
1297public:
1298  bool isSugared() const { return false; }
1299  QualType desugar() const { return QualType(this, 0); }
1300
1301  static bool classof(const Type *T) {
1302    return T->getTypeClass() == RValueReference;
1303  }
1304  static bool classof(const RValueReferenceType *) { return true; }
1305};
1306
1307/// MemberPointerType - C++ 8.3.3 - Pointers to members
1308///
1309class MemberPointerType : public Type, public llvm::FoldingSetNode {
1310  QualType PointeeType;
1311  /// The class of which the pointee is a member. Must ultimately be a
1312  /// RecordType, but could be a typedef or a template parameter too.
1313  const Type *Class;
1314
1315  MemberPointerType(QualType Pointee, const Type *Cls, QualType CanonicalPtr) :
1316    Type(MemberPointer, CanonicalPtr,
1317         Cls->isDependentType() || Pointee->isDependentType()),
1318    PointeeType(Pointee), Class(Cls) {
1319  }
1320  friend class ASTContext; // ASTContext creates these.
1321
1322protected:
1323  virtual Linkage getLinkageImpl() const;
1324
1325public:
1326
1327  QualType getPointeeType() const { return PointeeType; }
1328
1329  const Type *getClass() const { return Class; }
1330
1331  bool isSugared() const { return false; }
1332  QualType desugar() const { return QualType(this, 0); }
1333
1334  void Profile(llvm::FoldingSetNodeID &ID) {
1335    Profile(ID, getPointeeType(), getClass());
1336  }
1337  static void Profile(llvm::FoldingSetNodeID &ID, QualType Pointee,
1338                      const Type *Class) {
1339    ID.AddPointer(Pointee.getAsOpaquePtr());
1340    ID.AddPointer(Class);
1341  }
1342
1343  static bool classof(const Type *T) {
1344    return T->getTypeClass() == MemberPointer;
1345  }
1346  static bool classof(const MemberPointerType *) { return true; }
1347};
1348
1349/// ArrayType - C99 6.7.5.2 - Array Declarators.
1350///
1351class ArrayType : public Type, public llvm::FoldingSetNode {
1352public:
1353  /// ArraySizeModifier - Capture whether this is a normal array (e.g. int X[4])
1354  /// an array with a static size (e.g. int X[static 4]), or an array
1355  /// with a star size (e.g. int X[*]).
1356  /// 'static' is only allowed on function parameters.
1357  enum ArraySizeModifier {
1358    Normal, Static, Star
1359  };
1360private:
1361  /// ElementType - The element type of the array.
1362  QualType ElementType;
1363
1364  // NOTE: VC++ treats enums as signed, avoid using the ArraySizeModifier enum
1365  /// NOTE: These fields are packed into the bitfields space in the Type class.
1366  unsigned SizeModifier : 2;
1367
1368  /// IndexTypeQuals - Capture qualifiers in declarations like:
1369  /// 'int X[static restrict 4]'. For function parameters only.
1370  unsigned IndexTypeQuals : 3;
1371
1372protected:
1373  // C++ [temp.dep.type]p1:
1374  //   A type is dependent if it is...
1375  //     - an array type constructed from any dependent type or whose
1376  //       size is specified by a constant expression that is
1377  //       value-dependent,
1378  ArrayType(TypeClass tc, QualType et, QualType can,
1379            ArraySizeModifier sm, unsigned tq)
1380    : Type(tc, can, et->isDependentType() || tc == DependentSizedArray),
1381      ElementType(et), SizeModifier(sm), IndexTypeQuals(tq) {}
1382
1383  friend class ASTContext;  // ASTContext creates these.
1384
1385  virtual Linkage getLinkageImpl() const;
1386
1387public:
1388  QualType getElementType() const { return ElementType; }
1389  ArraySizeModifier getSizeModifier() const {
1390    return ArraySizeModifier(SizeModifier);
1391  }
1392  Qualifiers getIndexTypeQualifiers() const {
1393    return Qualifiers::fromCVRMask(IndexTypeQuals);
1394  }
1395  unsigned getIndexTypeCVRQualifiers() const { return IndexTypeQuals; }
1396
1397  static bool classof(const Type *T) {
1398    return T->getTypeClass() == ConstantArray ||
1399           T->getTypeClass() == VariableArray ||
1400           T->getTypeClass() == IncompleteArray ||
1401           T->getTypeClass() == DependentSizedArray;
1402  }
1403  static bool classof(const ArrayType *) { return true; }
1404};
1405
1406/// ConstantArrayType - This class represents the canonical version of
1407/// C arrays with a specified constant size.  For example, the canonical
1408/// type for 'int A[4 + 4*100]' is a ConstantArrayType where the element
1409/// type is 'int' and the size is 404.
1410class ConstantArrayType : public ArrayType {
1411  llvm::APInt Size; // Allows us to unique the type.
1412
1413  ConstantArrayType(QualType et, QualType can, const llvm::APInt &size,
1414                    ArraySizeModifier sm, unsigned tq)
1415    : ArrayType(ConstantArray, et, can, sm, tq),
1416      Size(size) {}
1417protected:
1418  ConstantArrayType(TypeClass tc, QualType et, QualType can,
1419                    const llvm::APInt &size, ArraySizeModifier sm, unsigned tq)
1420    : ArrayType(tc, et, can, sm, tq), Size(size) {}
1421  friend class ASTContext;  // ASTContext creates these.
1422public:
1423  const llvm::APInt &getSize() const { return Size; }
1424  bool isSugared() const { return false; }
1425  QualType desugar() const { return QualType(this, 0); }
1426
1427  void Profile(llvm::FoldingSetNodeID &ID) {
1428    Profile(ID, getElementType(), getSize(),
1429            getSizeModifier(), getIndexTypeCVRQualifiers());
1430  }
1431  static void Profile(llvm::FoldingSetNodeID &ID, QualType ET,
1432                      const llvm::APInt &ArraySize, ArraySizeModifier SizeMod,
1433                      unsigned TypeQuals) {
1434    ID.AddPointer(ET.getAsOpaquePtr());
1435    ID.AddInteger(ArraySize.getZExtValue());
1436    ID.AddInteger(SizeMod);
1437    ID.AddInteger(TypeQuals);
1438  }
1439  static bool classof(const Type *T) {
1440    return T->getTypeClass() == ConstantArray;
1441  }
1442  static bool classof(const ConstantArrayType *) { return true; }
1443};
1444
1445/// IncompleteArrayType - This class represents C arrays with an unspecified
1446/// size.  For example 'int A[]' has an IncompleteArrayType where the element
1447/// type is 'int' and the size is unspecified.
1448class IncompleteArrayType : public ArrayType {
1449
1450  IncompleteArrayType(QualType et, QualType can,
1451                      ArraySizeModifier sm, unsigned tq)
1452    : ArrayType(IncompleteArray, et, can, sm, tq) {}
1453  friend class ASTContext;  // ASTContext creates these.
1454public:
1455  bool isSugared() const { return false; }
1456  QualType desugar() const { return QualType(this, 0); }
1457
1458  static bool classof(const Type *T) {
1459    return T->getTypeClass() == IncompleteArray;
1460  }
1461  static bool classof(const IncompleteArrayType *) { return true; }
1462
1463  friend class StmtIteratorBase;
1464
1465  void Profile(llvm::FoldingSetNodeID &ID) {
1466    Profile(ID, getElementType(), getSizeModifier(),
1467            getIndexTypeCVRQualifiers());
1468  }
1469
1470  static void Profile(llvm::FoldingSetNodeID &ID, QualType ET,
1471                      ArraySizeModifier SizeMod, unsigned TypeQuals) {
1472    ID.AddPointer(ET.getAsOpaquePtr());
1473    ID.AddInteger(SizeMod);
1474    ID.AddInteger(TypeQuals);
1475  }
1476};
1477
1478/// VariableArrayType - This class represents C arrays with a specified size
1479/// which is not an integer-constant-expression.  For example, 'int s[x+foo()]'.
1480/// Since the size expression is an arbitrary expression, we store it as such.
1481///
1482/// Note: VariableArrayType's aren't uniqued (since the expressions aren't) and
1483/// should not be: two lexically equivalent variable array types could mean
1484/// different things, for example, these variables do not have the same type
1485/// dynamically:
1486///
1487/// void foo(int x) {
1488///   int Y[x];
1489///   ++x;
1490///   int Z[x];
1491/// }
1492///
1493class VariableArrayType : public ArrayType {
1494  /// SizeExpr - An assignment expression. VLA's are only permitted within
1495  /// a function block.
1496  Stmt *SizeExpr;
1497  /// Brackets - The left and right array brackets.
1498  SourceRange Brackets;
1499
1500  VariableArrayType(QualType et, QualType can, Expr *e,
1501                    ArraySizeModifier sm, unsigned tq,
1502                    SourceRange brackets)
1503    : ArrayType(VariableArray, et, can, sm, tq),
1504      SizeExpr((Stmt*) e), Brackets(brackets) {}
1505  friend class ASTContext;  // ASTContext creates these.
1506  virtual void Destroy(ASTContext& C);
1507
1508public:
1509  Expr *getSizeExpr() const {
1510    // We use C-style casts instead of cast<> here because we do not wish
1511    // to have a dependency of Type.h on Stmt.h/Expr.h.
1512    return (Expr*) SizeExpr;
1513  }
1514  SourceRange getBracketsRange() const { return Brackets; }
1515  SourceLocation getLBracketLoc() const { return Brackets.getBegin(); }
1516  SourceLocation getRBracketLoc() const { return Brackets.getEnd(); }
1517
1518  bool isSugared() const { return false; }
1519  QualType desugar() const { return QualType(this, 0); }
1520
1521  static bool classof(const Type *T) {
1522    return T->getTypeClass() == VariableArray;
1523  }
1524  static bool classof(const VariableArrayType *) { return true; }
1525
1526  friend class StmtIteratorBase;
1527
1528  void Profile(llvm::FoldingSetNodeID &ID) {
1529    assert(0 && "Cannnot unique VariableArrayTypes.");
1530  }
1531};
1532
1533/// DependentSizedArrayType - This type represents an array type in
1534/// C++ whose size is a value-dependent expression. For example:
1535///
1536/// \code
1537/// template<typename T, int Size>
1538/// class array {
1539///   T data[Size];
1540/// };
1541/// \endcode
1542///
1543/// For these types, we won't actually know what the array bound is
1544/// until template instantiation occurs, at which point this will
1545/// become either a ConstantArrayType or a VariableArrayType.
1546class DependentSizedArrayType : public ArrayType {
1547  ASTContext &Context;
1548
1549  /// \brief An assignment expression that will instantiate to the
1550  /// size of the array.
1551  ///
1552  /// The expression itself might be NULL, in which case the array
1553  /// type will have its size deduced from an initializer.
1554  Stmt *SizeExpr;
1555
1556  /// Brackets - The left and right array brackets.
1557  SourceRange Brackets;
1558
1559  DependentSizedArrayType(ASTContext &Context, QualType et, QualType can,
1560                          Expr *e, ArraySizeModifier sm, unsigned tq,
1561                          SourceRange brackets)
1562    : ArrayType(DependentSizedArray, et, can, sm, tq),
1563      Context(Context), SizeExpr((Stmt*) e), Brackets(brackets) {}
1564  friend class ASTContext;  // ASTContext creates these.
1565  virtual void Destroy(ASTContext& C);
1566
1567public:
1568  Expr *getSizeExpr() const {
1569    // We use C-style casts instead of cast<> here because we do not wish
1570    // to have a dependency of Type.h on Stmt.h/Expr.h.
1571    return (Expr*) SizeExpr;
1572  }
1573  SourceRange getBracketsRange() const { return Brackets; }
1574  SourceLocation getLBracketLoc() const { return Brackets.getBegin(); }
1575  SourceLocation getRBracketLoc() const { return Brackets.getEnd(); }
1576
1577  bool isSugared() const { return false; }
1578  QualType desugar() const { return QualType(this, 0); }
1579
1580  static bool classof(const Type *T) {
1581    return T->getTypeClass() == DependentSizedArray;
1582  }
1583  static bool classof(const DependentSizedArrayType *) { return true; }
1584
1585  friend class StmtIteratorBase;
1586
1587
1588  void Profile(llvm::FoldingSetNodeID &ID) {
1589    Profile(ID, Context, getElementType(),
1590            getSizeModifier(), getIndexTypeCVRQualifiers(), getSizeExpr());
1591  }
1592
1593  static void Profile(llvm::FoldingSetNodeID &ID, ASTContext &Context,
1594                      QualType ET, ArraySizeModifier SizeMod,
1595                      unsigned TypeQuals, Expr *E);
1596};
1597
1598/// DependentSizedExtVectorType - This type represent an extended vector type
1599/// where either the type or size is dependent. For example:
1600/// @code
1601/// template<typename T, int Size>
1602/// class vector {
1603///   typedef T __attribute__((ext_vector_type(Size))) type;
1604/// }
1605/// @endcode
1606class DependentSizedExtVectorType : public Type, public llvm::FoldingSetNode {
1607  ASTContext &Context;
1608  Expr *SizeExpr;
1609  /// ElementType - The element type of the array.
1610  QualType ElementType;
1611  SourceLocation loc;
1612
1613  DependentSizedExtVectorType(ASTContext &Context, QualType ElementType,
1614                              QualType can, Expr *SizeExpr, SourceLocation loc)
1615    : Type (DependentSizedExtVector, can, true),
1616      Context(Context), SizeExpr(SizeExpr), ElementType(ElementType),
1617      loc(loc) {}
1618  friend class ASTContext;
1619  virtual void Destroy(ASTContext& C);
1620
1621public:
1622  Expr *getSizeExpr() const { return SizeExpr; }
1623  QualType getElementType() const { return ElementType; }
1624  SourceLocation getAttributeLoc() const { return loc; }
1625
1626  bool isSugared() const { return false; }
1627  QualType desugar() const { return QualType(this, 0); }
1628
1629  static bool classof(const Type *T) {
1630    return T->getTypeClass() == DependentSizedExtVector;
1631  }
1632  static bool classof(const DependentSizedExtVectorType *) { return true; }
1633
1634  void Profile(llvm::FoldingSetNodeID &ID) {
1635    Profile(ID, Context, getElementType(), getSizeExpr());
1636  }
1637
1638  static void Profile(llvm::FoldingSetNodeID &ID, ASTContext &Context,
1639                      QualType ElementType, Expr *SizeExpr);
1640};
1641
1642
1643/// VectorType - GCC generic vector type. This type is created using
1644/// __attribute__((vector_size(n)), where "n" specifies the vector size in
1645/// bytes; or from an Altivec __vector or vector declaration.
1646/// Since the constructor takes the number of vector elements, the
1647/// client is responsible for converting the size into the number of elements.
1648class VectorType : public Type, public llvm::FoldingSetNode {
1649protected:
1650  /// ElementType - The element type of the vector.
1651  QualType ElementType;
1652
1653  /// NumElements - The number of elements in the vector.
1654  unsigned NumElements;
1655
1656  /// AltiVec - True if this is for an Altivec vector.
1657  bool AltiVec;
1658
1659  /// Pixel - True if this is for an Altivec vector pixel.
1660  bool Pixel;
1661
1662  VectorType(QualType vecType, unsigned nElements, QualType canonType,
1663      bool isAltiVec, bool isPixel) :
1664    Type(Vector, canonType, vecType->isDependentType()),
1665    ElementType(vecType), NumElements(nElements),
1666    AltiVec(isAltiVec), Pixel(isPixel) {}
1667  VectorType(TypeClass tc, QualType vecType, unsigned nElements,
1668             QualType canonType, bool isAltiVec, bool isPixel)
1669    : Type(tc, canonType, vecType->isDependentType()), ElementType(vecType),
1670      NumElements(nElements), AltiVec(isAltiVec), Pixel(isPixel) {}
1671  friend class ASTContext;  // ASTContext creates these.
1672
1673  virtual Linkage getLinkageImpl() const;
1674
1675public:
1676
1677  QualType getElementType() const { return ElementType; }
1678  unsigned getNumElements() const { return NumElements; }
1679
1680  bool isSugared() const { return false; }
1681  QualType desugar() const { return QualType(this, 0); }
1682
1683  bool isAltiVec() const { return AltiVec; }
1684
1685  bool isPixel() const { return Pixel; }
1686
1687  void Profile(llvm::FoldingSetNodeID &ID) {
1688    Profile(ID, getElementType(), getNumElements(), getTypeClass(),
1689      AltiVec, Pixel);
1690  }
1691  static void Profile(llvm::FoldingSetNodeID &ID, QualType ElementType,
1692                      unsigned NumElements, TypeClass TypeClass,
1693                      bool isAltiVec, bool isPixel) {
1694    ID.AddPointer(ElementType.getAsOpaquePtr());
1695    ID.AddInteger(NumElements);
1696    ID.AddInteger(TypeClass);
1697    ID.AddBoolean(isAltiVec);
1698    ID.AddBoolean(isPixel);
1699  }
1700
1701  static bool classof(const Type *T) {
1702    return T->getTypeClass() == Vector || T->getTypeClass() == ExtVector;
1703  }
1704  static bool classof(const VectorType *) { return true; }
1705};
1706
1707/// ExtVectorType - Extended vector type. This type is created using
1708/// __attribute__((ext_vector_type(n)), where "n" is the number of elements.
1709/// Unlike vector_size, ext_vector_type is only allowed on typedef's. This
1710/// class enables syntactic extensions, like Vector Components for accessing
1711/// points, colors, and textures (modeled after OpenGL Shading Language).
1712class ExtVectorType : public VectorType {
1713  ExtVectorType(QualType vecType, unsigned nElements, QualType canonType) :
1714    VectorType(ExtVector, vecType, nElements, canonType, false, false) {}
1715  friend class ASTContext;  // ASTContext creates these.
1716public:
1717  static int getPointAccessorIdx(char c) {
1718    switch (c) {
1719    default: return -1;
1720    case 'x': return 0;
1721    case 'y': return 1;
1722    case 'z': return 2;
1723    case 'w': return 3;
1724    }
1725  }
1726  static int getNumericAccessorIdx(char c) {
1727    switch (c) {
1728      default: return -1;
1729      case '0': return 0;
1730      case '1': return 1;
1731      case '2': return 2;
1732      case '3': return 3;
1733      case '4': return 4;
1734      case '5': return 5;
1735      case '6': return 6;
1736      case '7': return 7;
1737      case '8': return 8;
1738      case '9': return 9;
1739      case 'A':
1740      case 'a': return 10;
1741      case 'B':
1742      case 'b': return 11;
1743      case 'C':
1744      case 'c': return 12;
1745      case 'D':
1746      case 'd': return 13;
1747      case 'E':
1748      case 'e': return 14;
1749      case 'F':
1750      case 'f': return 15;
1751    }
1752  }
1753
1754  static int getAccessorIdx(char c) {
1755    if (int idx = getPointAccessorIdx(c)+1) return idx-1;
1756    return getNumericAccessorIdx(c);
1757  }
1758
1759  bool isAccessorWithinNumElements(char c) const {
1760    if (int idx = getAccessorIdx(c)+1)
1761      return unsigned(idx-1) < NumElements;
1762    return false;
1763  }
1764  bool isSugared() const { return false; }
1765  QualType desugar() const { return QualType(this, 0); }
1766
1767  static bool classof(const Type *T) {
1768    return T->getTypeClass() == ExtVector;
1769  }
1770  static bool classof(const ExtVectorType *) { return true; }
1771};
1772
1773/// FunctionType - C99 6.7.5.3 - Function Declarators.  This is the common base
1774/// class of FunctionNoProtoType and FunctionProtoType.
1775///
1776class FunctionType : public Type {
1777  virtual void ANCHOR(); // Key function for FunctionType.
1778
1779  /// SubClassData - This field is owned by the subclass, put here to pack
1780  /// tightly with the ivars in Type.
1781  bool SubClassData : 1;
1782
1783  /// TypeQuals - Used only by FunctionProtoType, put here to pack with the
1784  /// other bitfields.
1785  /// The qualifiers are part of FunctionProtoType because...
1786  ///
1787  /// C++ 8.3.5p4: The return type, the parameter type list and the
1788  /// cv-qualifier-seq, [...], are part of the function type.
1789  ///
1790  unsigned TypeQuals : 3;
1791
1792  /// NoReturn - Indicates if the function type is attribute noreturn.
1793  unsigned NoReturn : 1;
1794
1795  /// RegParm - How many arguments to pass inreg.
1796  unsigned RegParm : 3;
1797
1798  /// CallConv - The calling convention used by the function.
1799  unsigned CallConv : 3;
1800
1801  // The type returned by the function.
1802  QualType ResultType;
1803
1804 public:
1805  // This class is used for passing arround the information needed to
1806  // construct a call. It is not actually used for storage, just for
1807  // factoring together common arguments.
1808  // If you add a field (say Foo), other than the obvious places (both, constructors,
1809  // compile failures), what you need to update is
1810  // * Operetor==
1811  // * getFoo
1812  // * withFoo
1813  // * functionType. Add Foo, getFoo.
1814  // * ASTContext::getFooType
1815  // * ASTContext::mergeFunctionTypes
1816  // * FunctionNoProtoType::Profile
1817  // * FunctionProtoType::Profile
1818  // * TypePrinter::PrintFunctionProto
1819  // * PCH read and write
1820  // * Codegen
1821
1822  class ExtInfo {
1823   public:
1824    // Constructor with no defaults. Use this when you know that you
1825    // have all the elements (when reading a PCH file for example).
1826    ExtInfo(bool noReturn, unsigned regParm, CallingConv cc) :
1827        NoReturn(noReturn), RegParm(regParm), CC(cc) {}
1828
1829    // Constructor with all defaults. Use when for example creating a
1830    // function know to use defaults.
1831    ExtInfo() : NoReturn(false), RegParm(0), CC(CC_Default) {}
1832
1833    bool getNoReturn() const { return NoReturn; }
1834    unsigned getRegParm() const { return RegParm; }
1835    CallingConv getCC() const { return CC; }
1836
1837    bool operator==(const ExtInfo &Other) const {
1838      return getNoReturn() == Other.getNoReturn() &&
1839          getRegParm() == Other.getRegParm() &&
1840          getCC() == Other.getCC();
1841    }
1842    bool operator!=(const ExtInfo &Other) const {
1843      return !(*this == Other);
1844    }
1845
1846    // Note that we don't have setters. That is by design, use
1847    // the following with methods instead of mutating these objects.
1848
1849    ExtInfo withNoReturn(bool noReturn) const {
1850      return ExtInfo(noReturn, getRegParm(), getCC());
1851    }
1852
1853    ExtInfo withRegParm(unsigned RegParm) const {
1854      return ExtInfo(getNoReturn(), RegParm, getCC());
1855    }
1856
1857    ExtInfo withCallingConv(CallingConv cc) const {
1858      return ExtInfo(getNoReturn(), getRegParm(), cc);
1859    }
1860
1861   private:
1862    // True if we have __attribute__((noreturn))
1863    bool NoReturn;
1864    // The value passed to __attribute__((regparm(x)))
1865    unsigned RegParm;
1866    // The calling convention as specified via
1867    // __attribute__((cdecl|stdcall|fastcall|thiscall))
1868    CallingConv CC;
1869  };
1870
1871protected:
1872  FunctionType(TypeClass tc, QualType res, bool SubclassInfo,
1873               unsigned typeQuals, QualType Canonical, bool Dependent,
1874               const ExtInfo &Info)
1875    : Type(tc, Canonical, Dependent),
1876      SubClassData(SubclassInfo), TypeQuals(typeQuals),
1877      NoReturn(Info.getNoReturn()),
1878      RegParm(Info.getRegParm()), CallConv(Info.getCC()), ResultType(res) {}
1879  bool getSubClassData() const { return SubClassData; }
1880  unsigned getTypeQuals() const { return TypeQuals; }
1881public:
1882
1883  QualType getResultType() const { return ResultType; }
1884  unsigned getRegParmType() const { return RegParm; }
1885  bool getNoReturnAttr() const { return NoReturn; }
1886  CallingConv getCallConv() const { return (CallingConv)CallConv; }
1887  ExtInfo getExtInfo() const {
1888    return ExtInfo(NoReturn, RegParm, (CallingConv)CallConv);
1889  }
1890
1891  static llvm::StringRef getNameForCallConv(CallingConv CC);
1892
1893  static bool classof(const Type *T) {
1894    return T->getTypeClass() == FunctionNoProto ||
1895           T->getTypeClass() == FunctionProto;
1896  }
1897  static bool classof(const FunctionType *) { return true; }
1898};
1899
1900/// FunctionNoProtoType - Represents a K&R-style 'int foo()' function, which has
1901/// no information available about its arguments.
1902class FunctionNoProtoType : public FunctionType, public llvm::FoldingSetNode {
1903  FunctionNoProtoType(QualType Result, QualType Canonical,
1904                      const ExtInfo &Info)
1905    : FunctionType(FunctionNoProto, Result, false, 0, Canonical,
1906                   /*Dependent=*/false, Info) {}
1907  friend class ASTContext;  // ASTContext creates these.
1908
1909protected:
1910  virtual Linkage getLinkageImpl() const;
1911
1912public:
1913  // No additional state past what FunctionType provides.
1914
1915  bool isSugared() const { return false; }
1916  QualType desugar() const { return QualType(this, 0); }
1917
1918  void Profile(llvm::FoldingSetNodeID &ID) {
1919    Profile(ID, getResultType(), getExtInfo());
1920  }
1921  static void Profile(llvm::FoldingSetNodeID &ID, QualType ResultType,
1922                      const ExtInfo &Info) {
1923    ID.AddInteger(Info.getCC());
1924    ID.AddInteger(Info.getRegParm());
1925    ID.AddInteger(Info.getNoReturn());
1926    ID.AddPointer(ResultType.getAsOpaquePtr());
1927  }
1928
1929  static bool classof(const Type *T) {
1930    return T->getTypeClass() == FunctionNoProto;
1931  }
1932  static bool classof(const FunctionNoProtoType *) { return true; }
1933};
1934
1935/// FunctionProtoType - Represents a prototype with argument type info, e.g.
1936/// 'int foo(int)' or 'int foo(void)'.  'void' is represented as having no
1937/// arguments, not as having a single void argument. Such a type can have an
1938/// exception specification, but this specification is not part of the canonical
1939/// type.
1940class FunctionProtoType : public FunctionType, public llvm::FoldingSetNode {
1941  /// hasAnyDependentType - Determine whether there are any dependent
1942  /// types within the arguments passed in.
1943  static bool hasAnyDependentType(const QualType *ArgArray, unsigned numArgs) {
1944    for (unsigned Idx = 0; Idx < numArgs; ++Idx)
1945      if (ArgArray[Idx]->isDependentType())
1946    return true;
1947
1948    return false;
1949  }
1950
1951  FunctionProtoType(QualType Result, const QualType *ArgArray, unsigned numArgs,
1952                    bool isVariadic, unsigned typeQuals, bool hasExs,
1953                    bool hasAnyExs, const QualType *ExArray,
1954                    unsigned numExs, QualType Canonical,
1955                    const ExtInfo &Info)
1956    : FunctionType(FunctionProto, Result, isVariadic, typeQuals, Canonical,
1957                   (Result->isDependentType() ||
1958                    hasAnyDependentType(ArgArray, numArgs)),
1959                   Info),
1960      NumArgs(numArgs), NumExceptions(numExs), HasExceptionSpec(hasExs),
1961      AnyExceptionSpec(hasAnyExs) {
1962    // Fill in the trailing argument array.
1963    QualType *ArgInfo = reinterpret_cast<QualType*>(this+1);
1964    for (unsigned i = 0; i != numArgs; ++i)
1965      ArgInfo[i] = ArgArray[i];
1966    // Fill in the exception array.
1967    QualType *Ex = ArgInfo + numArgs;
1968    for (unsigned i = 0; i != numExs; ++i)
1969      Ex[i] = ExArray[i];
1970  }
1971
1972  /// NumArgs - The number of arguments this function has, not counting '...'.
1973  unsigned NumArgs : 20;
1974
1975  /// NumExceptions - The number of types in the exception spec, if any.
1976  unsigned NumExceptions : 10;
1977
1978  /// HasExceptionSpec - Whether this function has an exception spec at all.
1979  bool HasExceptionSpec : 1;
1980
1981  /// AnyExceptionSpec - Whether this function has a throw(...) spec.
1982  bool AnyExceptionSpec : 1;
1983
1984  /// ArgInfo - There is an variable size array after the class in memory that
1985  /// holds the argument types.
1986
1987  /// Exceptions - There is another variable size array after ArgInfo that
1988  /// holds the exception types.
1989
1990  friend class ASTContext;  // ASTContext creates these.
1991
1992protected:
1993  virtual Linkage getLinkageImpl() const;
1994
1995public:
1996  unsigned getNumArgs() const { return NumArgs; }
1997  QualType getArgType(unsigned i) const {
1998    assert(i < NumArgs && "Invalid argument number!");
1999    return arg_type_begin()[i];
2000  }
2001
2002  bool hasExceptionSpec() const { return HasExceptionSpec; }
2003  bool hasAnyExceptionSpec() const { return AnyExceptionSpec; }
2004  unsigned getNumExceptions() const { return NumExceptions; }
2005  QualType getExceptionType(unsigned i) const {
2006    assert(i < NumExceptions && "Invalid exception number!");
2007    return exception_begin()[i];
2008  }
2009  bool hasEmptyExceptionSpec() const {
2010    return hasExceptionSpec() && !hasAnyExceptionSpec() &&
2011      getNumExceptions() == 0;
2012  }
2013
2014  bool isVariadic() const { return getSubClassData(); }
2015  unsigned getTypeQuals() const { return FunctionType::getTypeQuals(); }
2016
2017  typedef const QualType *arg_type_iterator;
2018  arg_type_iterator arg_type_begin() const {
2019    return reinterpret_cast<const QualType *>(this+1);
2020  }
2021  arg_type_iterator arg_type_end() const { return arg_type_begin()+NumArgs; }
2022
2023  typedef const QualType *exception_iterator;
2024  exception_iterator exception_begin() const {
2025    // exceptions begin where arguments end
2026    return arg_type_end();
2027  }
2028  exception_iterator exception_end() const {
2029    return exception_begin() + NumExceptions;
2030  }
2031
2032  bool isSugared() const { return false; }
2033  QualType desugar() const { return QualType(this, 0); }
2034
2035  static bool classof(const Type *T) {
2036    return T->getTypeClass() == FunctionProto;
2037  }
2038  static bool classof(const FunctionProtoType *) { return true; }
2039
2040  void Profile(llvm::FoldingSetNodeID &ID);
2041  static void Profile(llvm::FoldingSetNodeID &ID, QualType Result,
2042                      arg_type_iterator ArgTys, unsigned NumArgs,
2043                      bool isVariadic, unsigned TypeQuals,
2044                      bool hasExceptionSpec, bool anyExceptionSpec,
2045                      unsigned NumExceptions, exception_iterator Exs,
2046                      const ExtInfo &ExtInfo);
2047};
2048
2049
2050/// \brief Represents the dependent type named by a dependently-scoped
2051/// typename using declaration, e.g.
2052///   using typename Base<T>::foo;
2053/// Template instantiation turns these into the underlying type.
2054class UnresolvedUsingType : public Type {
2055  UnresolvedUsingTypenameDecl *Decl;
2056
2057  UnresolvedUsingType(const UnresolvedUsingTypenameDecl *D)
2058    : Type(UnresolvedUsing, QualType(), true),
2059      Decl(const_cast<UnresolvedUsingTypenameDecl*>(D)) {}
2060  friend class ASTContext; // ASTContext creates these.
2061public:
2062
2063  UnresolvedUsingTypenameDecl *getDecl() const { return Decl; }
2064
2065  bool isSugared() const { return false; }
2066  QualType desugar() const { return QualType(this, 0); }
2067
2068  static bool classof(const Type *T) {
2069    return T->getTypeClass() == UnresolvedUsing;
2070  }
2071  static bool classof(const UnresolvedUsingType *) { return true; }
2072
2073  void Profile(llvm::FoldingSetNodeID &ID) {
2074    return Profile(ID, Decl);
2075  }
2076  static void Profile(llvm::FoldingSetNodeID &ID,
2077                      UnresolvedUsingTypenameDecl *D) {
2078    ID.AddPointer(D);
2079  }
2080};
2081
2082
2083class TypedefType : public Type {
2084  TypedefDecl *Decl;
2085protected:
2086  TypedefType(TypeClass tc, const TypedefDecl *D, QualType can)
2087    : Type(tc, can, can->isDependentType()),
2088      Decl(const_cast<TypedefDecl*>(D)) {
2089    assert(!isa<TypedefType>(can) && "Invalid canonical type");
2090  }
2091  friend class ASTContext;  // ASTContext creates these.
2092public:
2093
2094  TypedefDecl *getDecl() const { return Decl; }
2095
2096  /// LookThroughTypedefs - Return the ultimate type this typedef corresponds to
2097  /// potentially looking through *all* consecutive typedefs.  This returns the
2098  /// sum of the type qualifiers, so if you have:
2099  ///   typedef const int A;
2100  ///   typedef volatile A B;
2101  /// looking through the typedefs for B will give you "const volatile A".
2102  QualType LookThroughTypedefs() const;
2103
2104  bool isSugared() const { return true; }
2105  QualType desugar() const;
2106
2107  static bool classof(const Type *T) { return T->getTypeClass() == Typedef; }
2108  static bool classof(const TypedefType *) { return true; }
2109};
2110
2111/// TypeOfExprType (GCC extension).
2112class TypeOfExprType : public Type {
2113  Expr *TOExpr;
2114
2115protected:
2116  TypeOfExprType(Expr *E, QualType can = QualType());
2117  friend class ASTContext;  // ASTContext creates these.
2118public:
2119  Expr *getUnderlyingExpr() const { return TOExpr; }
2120
2121  /// \brief Remove a single level of sugar.
2122  QualType desugar() const;
2123
2124  /// \brief Returns whether this type directly provides sugar.
2125  bool isSugared() const { return true; }
2126
2127  static bool classof(const Type *T) { return T->getTypeClass() == TypeOfExpr; }
2128  static bool classof(const TypeOfExprType *) { return true; }
2129};
2130
2131/// \brief Internal representation of canonical, dependent
2132/// typeof(expr) types.
2133///
2134/// This class is used internally by the ASTContext to manage
2135/// canonical, dependent types, only. Clients will only see instances
2136/// of this class via TypeOfExprType nodes.
2137class DependentTypeOfExprType
2138  : public TypeOfExprType, public llvm::FoldingSetNode {
2139  ASTContext &Context;
2140
2141public:
2142  DependentTypeOfExprType(ASTContext &Context, Expr *E)
2143    : TypeOfExprType(E), Context(Context) { }
2144
2145  bool isSugared() const { return false; }
2146  QualType desugar() const { return QualType(this, 0); }
2147
2148  void Profile(llvm::FoldingSetNodeID &ID) {
2149    Profile(ID, Context, getUnderlyingExpr());
2150  }
2151
2152  static void Profile(llvm::FoldingSetNodeID &ID, ASTContext &Context,
2153                      Expr *E);
2154};
2155
2156/// TypeOfType (GCC extension).
2157class TypeOfType : public Type {
2158  QualType TOType;
2159  TypeOfType(QualType T, QualType can)
2160    : Type(TypeOf, can, T->isDependentType()), TOType(T) {
2161    assert(!isa<TypedefType>(can) && "Invalid canonical type");
2162  }
2163  friend class ASTContext;  // ASTContext creates these.
2164public:
2165  QualType getUnderlyingType() const { return TOType; }
2166
2167  /// \brief Remove a single level of sugar.
2168  QualType desugar() const { return getUnderlyingType(); }
2169
2170  /// \brief Returns whether this type directly provides sugar.
2171  bool isSugared() const { return true; }
2172
2173  static bool classof(const Type *T) { return T->getTypeClass() == TypeOf; }
2174  static bool classof(const TypeOfType *) { return true; }
2175};
2176
2177/// DecltypeType (C++0x)
2178class DecltypeType : public Type {
2179  Expr *E;
2180
2181  // FIXME: We could get rid of UnderlyingType if we wanted to: We would have to
2182  // Move getDesugaredType to ASTContext so that it can call getDecltypeForExpr
2183  // from it.
2184  QualType UnderlyingType;
2185
2186protected:
2187  DecltypeType(Expr *E, QualType underlyingType, QualType can = QualType());
2188  friend class ASTContext;  // ASTContext creates these.
2189public:
2190  Expr *getUnderlyingExpr() const { return E; }
2191  QualType getUnderlyingType() const { return UnderlyingType; }
2192
2193  /// \brief Remove a single level of sugar.
2194  QualType desugar() const { return getUnderlyingType(); }
2195
2196  /// \brief Returns whether this type directly provides sugar.
2197  bool isSugared() const { return !isDependentType(); }
2198
2199  static bool classof(const Type *T) { return T->getTypeClass() == Decltype; }
2200  static bool classof(const DecltypeType *) { return true; }
2201};
2202
2203/// \brief Internal representation of canonical, dependent
2204/// decltype(expr) types.
2205///
2206/// This class is used internally by the ASTContext to manage
2207/// canonical, dependent types, only. Clients will only see instances
2208/// of this class via DecltypeType nodes.
2209class DependentDecltypeType : public DecltypeType, public llvm::FoldingSetNode {
2210  ASTContext &Context;
2211
2212public:
2213  DependentDecltypeType(ASTContext &Context, Expr *E);
2214
2215  bool isSugared() const { return false; }
2216  QualType desugar() const { return QualType(this, 0); }
2217
2218  void Profile(llvm::FoldingSetNodeID &ID) {
2219    Profile(ID, Context, getUnderlyingExpr());
2220  }
2221
2222  static void Profile(llvm::FoldingSetNodeID &ID, ASTContext &Context,
2223                      Expr *E);
2224};
2225
2226class TagType : public Type {
2227  /// Stores the TagDecl associated with this type. The decl will
2228  /// point to the TagDecl that actually defines the entity (or is a
2229  /// definition in progress), if there is such a definition. The
2230  /// single-bit value will be non-zero when this tag is in the
2231  /// process of being defined.
2232  mutable llvm::PointerIntPair<TagDecl *, 1> decl;
2233  friend class ASTContext;
2234  friend class TagDecl;
2235
2236protected:
2237  TagType(TypeClass TC, const TagDecl *D, QualType can);
2238
2239  virtual Linkage getLinkageImpl() const;
2240
2241public:
2242  TagDecl *getDecl() const { return decl.getPointer(); }
2243
2244  /// @brief Determines whether this type is in the process of being
2245  /// defined.
2246  bool isBeingDefined() const { return decl.getInt(); }
2247  void setBeingDefined(bool Def) const { decl.setInt(Def? 1 : 0); }
2248
2249  static bool classof(const Type *T) {
2250    return T->getTypeClass() >= TagFirst && T->getTypeClass() <= TagLast;
2251  }
2252  static bool classof(const TagType *) { return true; }
2253  static bool classof(const RecordType *) { return true; }
2254  static bool classof(const EnumType *) { return true; }
2255};
2256
2257/// RecordType - This is a helper class that allows the use of isa/cast/dyncast
2258/// to detect TagType objects of structs/unions/classes.
2259class RecordType : public TagType {
2260protected:
2261  explicit RecordType(const RecordDecl *D)
2262    : TagType(Record, reinterpret_cast<const TagDecl*>(D), QualType()) { }
2263  explicit RecordType(TypeClass TC, RecordDecl *D)
2264    : TagType(TC, reinterpret_cast<const TagDecl*>(D), QualType()) { }
2265  friend class ASTContext;   // ASTContext creates these.
2266public:
2267
2268  RecordDecl *getDecl() const {
2269    return reinterpret_cast<RecordDecl*>(TagType::getDecl());
2270  }
2271
2272  // FIXME: This predicate is a helper to QualType/Type. It needs to
2273  // recursively check all fields for const-ness. If any field is declared
2274  // const, it needs to return false.
2275  bool hasConstFields() const { return false; }
2276
2277  // FIXME: RecordType needs to check when it is created that all fields are in
2278  // the same address space, and return that.
2279  unsigned getAddressSpace() const { return 0; }
2280
2281  bool isSugared() const { return false; }
2282  QualType desugar() const { return QualType(this, 0); }
2283
2284  static bool classof(const TagType *T);
2285  static bool classof(const Type *T) {
2286    return isa<TagType>(T) && classof(cast<TagType>(T));
2287  }
2288  static bool classof(const RecordType *) { return true; }
2289};
2290
2291/// EnumType - This is a helper class that allows the use of isa/cast/dyncast
2292/// to detect TagType objects of enums.
2293class EnumType : public TagType {
2294  explicit EnumType(const EnumDecl *D)
2295    : TagType(Enum, reinterpret_cast<const TagDecl*>(D), QualType()) { }
2296  friend class ASTContext;   // ASTContext creates these.
2297public:
2298
2299  EnumDecl *getDecl() const {
2300    return reinterpret_cast<EnumDecl*>(TagType::getDecl());
2301  }
2302
2303  bool isSugared() const { return false; }
2304  QualType desugar() const { return QualType(this, 0); }
2305
2306  static bool classof(const TagType *T);
2307  static bool classof(const Type *T) {
2308    return isa<TagType>(T) && classof(cast<TagType>(T));
2309  }
2310  static bool classof(const EnumType *) { return true; }
2311};
2312
2313class TemplateTypeParmType : public Type, public llvm::FoldingSetNode {
2314  unsigned Depth : 15;
2315  unsigned Index : 16;
2316  unsigned ParameterPack : 1;
2317  IdentifierInfo *Name;
2318
2319  TemplateTypeParmType(unsigned D, unsigned I, bool PP, IdentifierInfo *N,
2320                       QualType Canon)
2321    : Type(TemplateTypeParm, Canon, /*Dependent=*/true),
2322      Depth(D), Index(I), ParameterPack(PP), Name(N) { }
2323
2324  TemplateTypeParmType(unsigned D, unsigned I, bool PP)
2325    : Type(TemplateTypeParm, QualType(this, 0), /*Dependent=*/true),
2326      Depth(D), Index(I), ParameterPack(PP), Name(0) { }
2327
2328  friend class ASTContext;  // ASTContext creates these
2329
2330public:
2331  unsigned getDepth() const { return Depth; }
2332  unsigned getIndex() const { return Index; }
2333  bool isParameterPack() const { return ParameterPack; }
2334  IdentifierInfo *getName() const { return Name; }
2335
2336  bool isSugared() const { return false; }
2337  QualType desugar() const { return QualType(this, 0); }
2338
2339  void Profile(llvm::FoldingSetNodeID &ID) {
2340    Profile(ID, Depth, Index, ParameterPack, Name);
2341  }
2342
2343  static void Profile(llvm::FoldingSetNodeID &ID, unsigned Depth,
2344                      unsigned Index, bool ParameterPack,
2345                      IdentifierInfo *Name) {
2346    ID.AddInteger(Depth);
2347    ID.AddInteger(Index);
2348    ID.AddBoolean(ParameterPack);
2349    ID.AddPointer(Name);
2350  }
2351
2352  static bool classof(const Type *T) {
2353    return T->getTypeClass() == TemplateTypeParm;
2354  }
2355  static bool classof(const TemplateTypeParmType *T) { return true; }
2356};
2357
2358/// \brief Represents the result of substituting a type for a template
2359/// type parameter.
2360///
2361/// Within an instantiated template, all template type parameters have
2362/// been replaced with these.  They are used solely to record that a
2363/// type was originally written as a template type parameter;
2364/// therefore they are never canonical.
2365class SubstTemplateTypeParmType : public Type, public llvm::FoldingSetNode {
2366  // The original type parameter.
2367  const TemplateTypeParmType *Replaced;
2368
2369  SubstTemplateTypeParmType(const TemplateTypeParmType *Param, QualType Canon)
2370    : Type(SubstTemplateTypeParm, Canon, Canon->isDependentType()),
2371      Replaced(Param) { }
2372
2373  friend class ASTContext;
2374
2375public:
2376  IdentifierInfo *getName() const { return Replaced->getName(); }
2377
2378  /// Gets the template parameter that was substituted for.
2379  const TemplateTypeParmType *getReplacedParameter() const {
2380    return Replaced;
2381  }
2382
2383  /// Gets the type that was substituted for the template
2384  /// parameter.
2385  QualType getReplacementType() const {
2386    return getCanonicalTypeInternal();
2387  }
2388
2389  bool isSugared() const { return true; }
2390  QualType desugar() const { return getReplacementType(); }
2391
2392  void Profile(llvm::FoldingSetNodeID &ID) {
2393    Profile(ID, getReplacedParameter(), getReplacementType());
2394  }
2395  static void Profile(llvm::FoldingSetNodeID &ID,
2396                      const TemplateTypeParmType *Replaced,
2397                      QualType Replacement) {
2398    ID.AddPointer(Replaced);
2399    ID.AddPointer(Replacement.getAsOpaquePtr());
2400  }
2401
2402  static bool classof(const Type *T) {
2403    return T->getTypeClass() == SubstTemplateTypeParm;
2404  }
2405  static bool classof(const SubstTemplateTypeParmType *T) { return true; }
2406};
2407
2408/// \brief Represents the type of a template specialization as written
2409/// in the source code.
2410///
2411/// Template specialization types represent the syntactic form of a
2412/// template-id that refers to a type, e.g., @c vector<int>. Some
2413/// template specialization types are syntactic sugar, whose canonical
2414/// type will point to some other type node that represents the
2415/// instantiation or class template specialization. For example, a
2416/// class template specialization type of @c vector<int> will refer to
2417/// a tag type for the instantiation
2418/// @c std::vector<int, std::allocator<int>>.
2419///
2420/// Other template specialization types, for which the template name
2421/// is dependent, may be canonical types. These types are always
2422/// dependent.
2423class TemplateSpecializationType
2424  : public Type, public llvm::FoldingSetNode {
2425  /// \brief The name of the template being specialized.
2426  TemplateName Template;
2427
2428  /// \brief - The number of template arguments named in this class
2429  /// template specialization.
2430  unsigned NumArgs;
2431
2432  TemplateSpecializationType(TemplateName T,
2433                             const TemplateArgument *Args,
2434                             unsigned NumArgs, QualType Canon);
2435
2436  virtual void Destroy(ASTContext& C);
2437
2438  friend class ASTContext;  // ASTContext creates these
2439
2440public:
2441  /// \brief Determine whether any of the given template arguments are
2442  /// dependent.
2443  static bool anyDependentTemplateArguments(const TemplateArgument *Args,
2444                                            unsigned NumArgs);
2445
2446  static bool anyDependentTemplateArguments(const TemplateArgumentLoc *Args,
2447                                            unsigned NumArgs);
2448
2449  static bool anyDependentTemplateArguments(const TemplateArgumentListInfo &);
2450
2451  /// \brief Print a template argument list, including the '<' and '>'
2452  /// enclosing the template arguments.
2453  static std::string PrintTemplateArgumentList(const TemplateArgument *Args,
2454                                               unsigned NumArgs,
2455                                               const PrintingPolicy &Policy);
2456
2457  static std::string PrintTemplateArgumentList(const TemplateArgumentLoc *Args,
2458                                               unsigned NumArgs,
2459                                               const PrintingPolicy &Policy);
2460
2461  static std::string PrintTemplateArgumentList(const TemplateArgumentListInfo &,
2462                                               const PrintingPolicy &Policy);
2463
2464  /// True if this template specialization type matches a current
2465  /// instantiation in the context in which it is found.
2466  bool isCurrentInstantiation() const {
2467    return isa<InjectedClassNameType>(getCanonicalTypeInternal());
2468  }
2469
2470  typedef const TemplateArgument * iterator;
2471
2472  iterator begin() const { return getArgs(); }
2473  iterator end() const; // defined inline in TemplateBase.h
2474
2475  /// \brief Retrieve the name of the template that we are specializing.
2476  TemplateName getTemplateName() const { return Template; }
2477
2478  /// \brief Retrieve the template arguments.
2479  const TemplateArgument *getArgs() const {
2480    return reinterpret_cast<const TemplateArgument *>(this + 1);
2481  }
2482
2483  /// \brief Retrieve the number of template arguments.
2484  unsigned getNumArgs() const { return NumArgs; }
2485
2486  /// \brief Retrieve a specific template argument as a type.
2487  /// \precondition @c isArgType(Arg)
2488  const TemplateArgument &getArg(unsigned Idx) const; // in TemplateBase.h
2489
2490  bool isSugared() const {
2491    return !isDependentType() || isCurrentInstantiation();
2492  }
2493  QualType desugar() const { return getCanonicalTypeInternal(); }
2494
2495  void Profile(llvm::FoldingSetNodeID &ID, ASTContext &Ctx) {
2496    Profile(ID, Template, getArgs(), NumArgs, Ctx);
2497  }
2498
2499  static void Profile(llvm::FoldingSetNodeID &ID, TemplateName T,
2500                      const TemplateArgument *Args,
2501                      unsigned NumArgs,
2502                      ASTContext &Context);
2503
2504  static bool classof(const Type *T) {
2505    return T->getTypeClass() == TemplateSpecialization;
2506  }
2507  static bool classof(const TemplateSpecializationType *T) { return true; }
2508};
2509
2510/// \brief The injected class name of a C++ class template or class
2511/// template partial specialization.  Used to record that a type was
2512/// spelled with a bare identifier rather than as a template-id; the
2513/// equivalent for non-templated classes is just RecordType.
2514///
2515/// Injected class name types are always dependent.  Template
2516/// instantiation turns these into RecordTypes.
2517///
2518/// Injected class name types are always canonical.  This works
2519/// because it is impossible to compare an injected class name type
2520/// with the corresponding non-injected template type, for the same
2521/// reason that it is impossible to directly compare template
2522/// parameters from different dependent contexts: injected class name
2523/// types can only occur within the scope of a particular templated
2524/// declaration, and within that scope every template specialization
2525/// will canonicalize to the injected class name (when appropriate
2526/// according to the rules of the language).
2527class InjectedClassNameType : public Type {
2528  CXXRecordDecl *Decl;
2529
2530  /// The template specialization which this type represents.
2531  /// For example, in
2532  ///   template <class T> class A { ... };
2533  /// this is A<T>, whereas in
2534  ///   template <class X, class Y> class A<B<X,Y> > { ... };
2535  /// this is A<B<X,Y> >.
2536  ///
2537  /// It is always unqualified, always a template specialization type,
2538  /// and always dependent.
2539  QualType InjectedType;
2540
2541  friend class ASTContext; // ASTContext creates these.
2542  friend class TagDecl; // TagDecl mutilates the Decl
2543  InjectedClassNameType(CXXRecordDecl *D, QualType TST)
2544    : Type(InjectedClassName, QualType(), true),
2545      Decl(D), InjectedType(TST) {
2546    assert(isa<TemplateSpecializationType>(TST));
2547    assert(!TST.hasQualifiers());
2548    assert(TST->isDependentType());
2549  }
2550
2551public:
2552  QualType getInjectedSpecializationType() const { return InjectedType; }
2553  const TemplateSpecializationType *getInjectedTST() const {
2554    return cast<TemplateSpecializationType>(InjectedType.getTypePtr());
2555  }
2556
2557  CXXRecordDecl *getDecl() const { return Decl; }
2558
2559  bool isSugared() const { return false; }
2560  QualType desugar() const { return QualType(this, 0); }
2561
2562  static bool classof(const Type *T) {
2563    return T->getTypeClass() == InjectedClassName;
2564  }
2565  static bool classof(const InjectedClassNameType *T) { return true; }
2566};
2567
2568/// \brief The kind of a tag type.
2569enum TagTypeKind {
2570  /// \brief The "struct" keyword.
2571  TTK_Struct,
2572  /// \brief The "union" keyword.
2573  TTK_Union,
2574  /// \brief The "class" keyword.
2575  TTK_Class,
2576  /// \brief The "enum" keyword.
2577  TTK_Enum
2578};
2579
2580/// \brief The elaboration keyword that precedes a qualified type name or
2581/// introduces an elaborated-type-specifier.
2582enum ElaboratedTypeKeyword {
2583  /// \brief The "struct" keyword introduces the elaborated-type-specifier.
2584  ETK_Struct,
2585  /// \brief The "union" keyword introduces the elaborated-type-specifier.
2586  ETK_Union,
2587  /// \brief The "class" keyword introduces the elaborated-type-specifier.
2588  ETK_Class,
2589  /// \brief The "enum" keyword introduces the elaborated-type-specifier.
2590  ETK_Enum,
2591  /// \brief The "typename" keyword precedes the qualified type name, e.g.,
2592  /// \c typename T::type.
2593  ETK_Typename,
2594  /// \brief No keyword precedes the qualified type name.
2595  ETK_None
2596};
2597
2598/// A helper class for Type nodes having an ElaboratedTypeKeyword.
2599/// The keyword in stored in the free bits of the base class.
2600/// Also provides a few static helpers for converting and printing
2601/// elaborated type keyword and tag type kind enumerations.
2602class TypeWithKeyword : public Type {
2603  /// Keyword - Encodes an ElaboratedTypeKeyword enumeration constant.
2604  unsigned Keyword : 3;
2605
2606protected:
2607  TypeWithKeyword(ElaboratedTypeKeyword Keyword, TypeClass tc,
2608                  QualType Canonical, bool dependent)
2609    : Type(tc, Canonical, dependent), Keyword(Keyword) {}
2610
2611public:
2612  virtual ~TypeWithKeyword(); // pin vtable to Type.cpp
2613
2614  ElaboratedTypeKeyword getKeyword() const {
2615    return static_cast<ElaboratedTypeKeyword>(Keyword);
2616  }
2617
2618  /// getKeywordForTypeSpec - Converts a type specifier (DeclSpec::TST)
2619  /// into an elaborated type keyword.
2620  static ElaboratedTypeKeyword getKeywordForTypeSpec(unsigned TypeSpec);
2621
2622  /// getTagTypeKindForTypeSpec - Converts a type specifier (DeclSpec::TST)
2623  /// into a tag type kind.  It is an error to provide a type specifier
2624  /// which *isn't* a tag kind here.
2625  static TagTypeKind getTagTypeKindForTypeSpec(unsigned TypeSpec);
2626
2627  /// getKeywordForTagDeclKind - Converts a TagTypeKind into an
2628  /// elaborated type keyword.
2629  static ElaboratedTypeKeyword getKeywordForTagTypeKind(TagTypeKind Tag);
2630
2631  /// getTagTypeKindForKeyword - Converts an elaborated type keyword into
2632  // a TagTypeKind. It is an error to provide an elaborated type keyword
2633  /// which *isn't* a tag kind here.
2634  static TagTypeKind getTagTypeKindForKeyword(ElaboratedTypeKeyword Keyword);
2635
2636  static bool KeywordIsTagTypeKind(ElaboratedTypeKeyword Keyword);
2637
2638  static const char *getKeywordName(ElaboratedTypeKeyword Keyword);
2639
2640  static const char *getTagTypeKindName(TagTypeKind Kind) {
2641    return getKeywordName(getKeywordForTagTypeKind(Kind));
2642  }
2643
2644  class CannotCastToThisType {};
2645  static CannotCastToThisType classof(const Type *);
2646};
2647
2648/// \brief Represents a type that was referred to using an elaborated type
2649/// keyword, e.g., struct S, or via a qualified name, e.g., N::M::type,
2650/// or both.
2651///
2652/// This type is used to keep track of a type name as written in the
2653/// source code, including tag keywords and any nested-name-specifiers.
2654/// The type itself is always "sugar", used to express what was written
2655/// in the source code but containing no additional semantic information.
2656class ElaboratedType : public TypeWithKeyword, public llvm::FoldingSetNode {
2657
2658  /// \brief The nested name specifier containing the qualifier.
2659  NestedNameSpecifier *NNS;
2660
2661  /// \brief The type that this qualified name refers to.
2662  QualType NamedType;
2663
2664  ElaboratedType(ElaboratedTypeKeyword Keyword, NestedNameSpecifier *NNS,
2665                 QualType NamedType, QualType CanonType)
2666    : TypeWithKeyword(Keyword, Elaborated, CanonType,
2667                      NamedType->isDependentType()),
2668      NNS(NNS), NamedType(NamedType) {
2669    assert(!(Keyword == ETK_None && NNS == 0) &&
2670           "ElaboratedType cannot have elaborated type keyword "
2671           "and name qualifier both null.");
2672  }
2673
2674  friend class ASTContext;  // ASTContext creates these
2675
2676public:
2677  ~ElaboratedType();
2678
2679  /// \brief Retrieve the qualification on this type.
2680  NestedNameSpecifier *getQualifier() const { return NNS; }
2681
2682  /// \brief Retrieve the type named by the qualified-id.
2683  QualType getNamedType() const { return NamedType; }
2684
2685  /// \brief Remove a single level of sugar.
2686  QualType desugar() const { return getNamedType(); }
2687
2688  /// \brief Returns whether this type directly provides sugar.
2689  bool isSugared() const { return true; }
2690
2691  void Profile(llvm::FoldingSetNodeID &ID) {
2692    Profile(ID, getKeyword(), NNS, NamedType);
2693  }
2694
2695  static void Profile(llvm::FoldingSetNodeID &ID, ElaboratedTypeKeyword Keyword,
2696                      NestedNameSpecifier *NNS, QualType NamedType) {
2697    ID.AddInteger(Keyword);
2698    ID.AddPointer(NNS);
2699    NamedType.Profile(ID);
2700  }
2701
2702  static bool classof(const Type *T) {
2703    return T->getTypeClass() == Elaborated;
2704  }
2705  static bool classof(const ElaboratedType *T) { return true; }
2706};
2707
2708/// \brief Represents a qualified type name for which the type name is
2709/// dependent.
2710///
2711/// DependentNameType represents a class of dependent types that involve a
2712/// dependent nested-name-specifier (e.g., "T::") followed by a (dependent)
2713/// name of a type. The DependentNameType may start with a "typename" (for a
2714/// typename-specifier), "class", "struct", "union", or "enum" (for a
2715/// dependent elaborated-type-specifier), or nothing (in contexts where we
2716/// know that we must be referring to a type, e.g., in a base class specifier).
2717class DependentNameType : public TypeWithKeyword, public llvm::FoldingSetNode {
2718
2719  /// \brief The nested name specifier containing the qualifier.
2720  NestedNameSpecifier *NNS;
2721
2722  /// \brief The type that this typename specifier refers to.
2723  const IdentifierInfo *Name;
2724
2725  DependentNameType(ElaboratedTypeKeyword Keyword, NestedNameSpecifier *NNS,
2726                    const IdentifierInfo *Name, QualType CanonType)
2727    : TypeWithKeyword(Keyword, DependentName, CanonType, true),
2728      NNS(NNS), Name(Name) {
2729    assert(NNS->isDependent() &&
2730           "DependentNameType requires a dependent nested-name-specifier");
2731  }
2732
2733  friend class ASTContext;  // ASTContext creates these
2734
2735public:
2736  virtual ~DependentNameType();
2737
2738  /// \brief Retrieve the qualification on this type.
2739  NestedNameSpecifier *getQualifier() const { return NNS; }
2740
2741  /// \brief Retrieve the type named by the typename specifier as an
2742  /// identifier.
2743  ///
2744  /// This routine will return a non-NULL identifier pointer when the
2745  /// form of the original typename was terminated by an identifier,
2746  /// e.g., "typename T::type".
2747  const IdentifierInfo *getIdentifier() const {
2748    return Name;
2749  }
2750
2751  bool isSugared() const { return false; }
2752  QualType desugar() const { return QualType(this, 0); }
2753
2754  void Profile(llvm::FoldingSetNodeID &ID) {
2755    Profile(ID, getKeyword(), NNS, Name);
2756  }
2757
2758  static void Profile(llvm::FoldingSetNodeID &ID, ElaboratedTypeKeyword Keyword,
2759                      NestedNameSpecifier *NNS, const IdentifierInfo *Name) {
2760    ID.AddInteger(Keyword);
2761    ID.AddPointer(NNS);
2762    ID.AddPointer(Name);
2763  }
2764
2765  static bool classof(const Type *T) {
2766    return T->getTypeClass() == DependentName;
2767  }
2768  static bool classof(const DependentNameType *T) { return true; }
2769};
2770
2771/// DependentTemplateSpecializationType - Represents a template
2772/// specialization type whose template cannot be resolved, e.g.
2773///   A<T>::template B<T>
2774class DependentTemplateSpecializationType :
2775  public TypeWithKeyword, public llvm::FoldingSetNode {
2776
2777  /// \brief The nested name specifier containing the qualifier.
2778  NestedNameSpecifier *NNS;
2779
2780  /// \brief The identifier of the template.
2781  const IdentifierInfo *Name;
2782
2783  /// \brief - The number of template arguments named in this class
2784  /// template specialization.
2785  unsigned NumArgs;
2786
2787  const TemplateArgument *getArgBuffer() const {
2788    return reinterpret_cast<const TemplateArgument*>(this+1);
2789  }
2790  TemplateArgument *getArgBuffer() {
2791    return reinterpret_cast<TemplateArgument*>(this+1);
2792  }
2793
2794  DependentTemplateSpecializationType(ElaboratedTypeKeyword Keyword,
2795                                      NestedNameSpecifier *NNS,
2796                                      const IdentifierInfo *Name,
2797                                      unsigned NumArgs,
2798                                      const TemplateArgument *Args,
2799                                      QualType Canon);
2800
2801  virtual void Destroy(ASTContext& C);
2802
2803  friend class ASTContext;  // ASTContext creates these
2804
2805public:
2806  virtual ~DependentTemplateSpecializationType();
2807
2808  NestedNameSpecifier *getQualifier() const { return NNS; }
2809  const IdentifierInfo *getIdentifier() const { return Name; }
2810
2811  /// \brief Retrieve the template arguments.
2812  const TemplateArgument *getArgs() const {
2813    return getArgBuffer();
2814  }
2815
2816  /// \brief Retrieve the number of template arguments.
2817  unsigned getNumArgs() const { return NumArgs; }
2818
2819  const TemplateArgument &getArg(unsigned Idx) const; // in TemplateBase.h
2820
2821  typedef const TemplateArgument * iterator;
2822  iterator begin() const { return getArgs(); }
2823  iterator end() const; // inline in TemplateBase.h
2824
2825  bool isSugared() const { return false; }
2826  QualType desugar() const { return QualType(this, 0); }
2827
2828  void Profile(llvm::FoldingSetNodeID &ID, ASTContext &Context) {
2829    Profile(ID, Context, getKeyword(), NNS, Name, NumArgs, getArgs());
2830  }
2831
2832  static void Profile(llvm::FoldingSetNodeID &ID,
2833                      ASTContext &Context,
2834                      ElaboratedTypeKeyword Keyword,
2835                      NestedNameSpecifier *Qualifier,
2836                      const IdentifierInfo *Name,
2837                      unsigned NumArgs,
2838                      const TemplateArgument *Args);
2839
2840  static bool classof(const Type *T) {
2841    return T->getTypeClass() == DependentTemplateSpecialization;
2842  }
2843  static bool classof(const DependentTemplateSpecializationType *T) {
2844    return true;
2845  }
2846};
2847
2848/// ObjCObjectType - Represents a class type in Objective C.
2849/// Every Objective C type is a combination of a base type and a
2850/// list of protocols.
2851///
2852/// Given the following declarations:
2853///   @class C;
2854///   @protocol P;
2855///
2856/// 'C' is an ObjCInterfaceType C.  It is sugar for an ObjCObjectType
2857/// with base C and no protocols.
2858///
2859/// 'C<P>' is an ObjCObjectType with base C and protocol list [P].
2860///
2861/// 'id' is a TypedefType which is sugar for an ObjCPointerType whose
2862/// pointee is an ObjCObjectType with base BuiltinType::ObjCIdType
2863/// and no protocols.
2864///
2865/// 'id<P>' is an ObjCPointerType whose pointee is an ObjCObjecType
2866/// with base BuiltinType::ObjCIdType and protocol list [P].  Eventually
2867/// this should get its own sugar class to better represent the source.
2868class ObjCObjectType : public Type {
2869  // Pad the bit count up so that NumProtocols is 2-byte aligned
2870  unsigned : BitsRemainingInType - 16;
2871
2872  /// \brief The number of protocols stored after the
2873  /// ObjCObjectPointerType node.
2874  ///
2875  /// These protocols are those written directly on the type.  If
2876  /// protocol qualifiers ever become additive, the iterators will
2877  /// get kindof complicated.
2878  ///
2879  /// In the canonical object type, these are sorted alphabetically
2880  /// and uniqued.
2881  unsigned NumProtocols : 16;
2882
2883  /// Either a BuiltinType or an InterfaceType or sugar for either.
2884  QualType BaseType;
2885
2886  ObjCProtocolDecl * const *getProtocolStorage() const {
2887    return const_cast<ObjCObjectType*>(this)->getProtocolStorage();
2888  }
2889
2890  ObjCProtocolDecl **getProtocolStorage();
2891
2892protected:
2893  ObjCObjectType(QualType Canonical, QualType Base,
2894                 ObjCProtocolDecl * const *Protocols, unsigned NumProtocols);
2895
2896  enum Nonce_ObjCInterface { Nonce_ObjCInterface };
2897  ObjCObjectType(enum Nonce_ObjCInterface)
2898    : Type(ObjCInterface, QualType(), false),
2899      NumProtocols(0),
2900      BaseType(QualType(this_(), 0)) {}
2901
2902protected:
2903  Linkage getLinkageImpl() const; // key function
2904
2905public:
2906  /// getBaseType - Gets the base type of this object type.  This is
2907  /// always (possibly sugar for) one of:
2908  ///  - the 'id' builtin type (as opposed to the 'id' type visible to the
2909  ///    user, which is a typedef for an ObjCPointerType)
2910  ///  - the 'Class' builtin type (same caveat)
2911  ///  - an ObjCObjectType (currently always an ObjCInterfaceType)
2912  QualType getBaseType() const { return BaseType; }
2913
2914  bool isObjCId() const {
2915    return getBaseType()->isSpecificBuiltinType(BuiltinType::ObjCId);
2916  }
2917  bool isObjCClass() const {
2918    return getBaseType()->isSpecificBuiltinType(BuiltinType::ObjCClass);
2919  }
2920  bool isObjCUnqualifiedId() const { return qual_empty() && isObjCId(); }
2921  bool isObjCUnqualifiedClass() const { return qual_empty() && isObjCClass(); }
2922  bool isObjCUnqualifiedIdOrClass() const {
2923    if (!qual_empty()) return false;
2924    if (const BuiltinType *T = getBaseType()->getAs<BuiltinType>())
2925      return T->getKind() == BuiltinType::ObjCId ||
2926             T->getKind() == BuiltinType::ObjCClass;
2927    return false;
2928  }
2929  bool isObjCQualifiedId() const { return !qual_empty() && isObjCId(); }
2930  bool isObjCQualifiedClass() const { return !qual_empty() && isObjCClass(); }
2931
2932  /// Gets the interface declaration for this object type, if the base type
2933  /// really is an interface.
2934  ObjCInterfaceDecl *getInterface() const;
2935
2936  typedef ObjCProtocolDecl * const *qual_iterator;
2937
2938  qual_iterator qual_begin() const { return getProtocolStorage(); }
2939  qual_iterator qual_end() const { return qual_begin() + getNumProtocols(); }
2940
2941  bool qual_empty() const { return getNumProtocols() == 0; }
2942
2943  /// getNumProtocols - Return the number of qualifying protocols in this
2944  /// interface type, or 0 if there are none.
2945  unsigned getNumProtocols() const { return NumProtocols; }
2946
2947  /// \brief Fetch a protocol by index.
2948  ObjCProtocolDecl *getProtocol(unsigned I) const {
2949    assert(I < getNumProtocols() && "Out-of-range protocol access");
2950    return qual_begin()[I];
2951  }
2952
2953  bool isSugared() const { return false; }
2954  QualType desugar() const { return QualType(this, 0); }
2955
2956  static bool classof(const Type *T) {
2957    return T->getTypeClass() == ObjCObject ||
2958           T->getTypeClass() == ObjCInterface;
2959  }
2960  static bool classof(const ObjCObjectType *) { return true; }
2961};
2962
2963/// ObjCObjectTypeImpl - A class providing a concrete implementation
2964/// of ObjCObjectType, so as to not increase the footprint of
2965/// ObjCInterfaceType.  Code outside of ASTContext and the core type
2966/// system should not reference this type.
2967class ObjCObjectTypeImpl : public ObjCObjectType, public llvm::FoldingSetNode {
2968  friend class ASTContext;
2969
2970  // If anyone adds fields here, ObjCObjectType::getProtocolStorage()
2971  // will need to be modified.
2972
2973  ObjCObjectTypeImpl(QualType Canonical, QualType Base,
2974                     ObjCProtocolDecl * const *Protocols,
2975                     unsigned NumProtocols)
2976    : ObjCObjectType(Canonical, Base, Protocols, NumProtocols) {}
2977
2978public:
2979  void Destroy(ASTContext& C); // key function
2980
2981  void Profile(llvm::FoldingSetNodeID &ID);
2982  static void Profile(llvm::FoldingSetNodeID &ID,
2983                      QualType Base,
2984                      ObjCProtocolDecl *const *protocols,
2985                      unsigned NumProtocols);
2986};
2987
2988inline ObjCProtocolDecl **ObjCObjectType::getProtocolStorage() {
2989  return reinterpret_cast<ObjCProtocolDecl**>(
2990            static_cast<ObjCObjectTypeImpl*>(this) + 1);
2991}
2992
2993/// ObjCInterfaceType - Interfaces are the core concept in Objective-C for
2994/// object oriented design.  They basically correspond to C++ classes.  There
2995/// are two kinds of interface types, normal interfaces like "NSString" and
2996/// qualified interfaces, which are qualified with a protocol list like
2997/// "NSString<NSCopyable, NSAmazing>".
2998///
2999/// ObjCInterfaceType guarantees the following properties when considered
3000/// as a subtype of its superclass, ObjCObjectType:
3001///   - There are no protocol qualifiers.  To reinforce this, code which
3002///     tries to invoke the protocol methods via an ObjCInterfaceType will
3003///     fail to compile.
3004///   - It is its own base type.  That is, if T is an ObjCInterfaceType*,
3005///     T->getBaseType() == QualType(T, 0).
3006class ObjCInterfaceType : public ObjCObjectType {
3007  ObjCInterfaceDecl *Decl;
3008
3009  ObjCInterfaceType(const ObjCInterfaceDecl *D)
3010    : ObjCObjectType(Nonce_ObjCInterface),
3011      Decl(const_cast<ObjCInterfaceDecl*>(D)) {}
3012  friend class ASTContext;  // ASTContext creates these.
3013public:
3014  void Destroy(ASTContext& C); // key function
3015
3016  /// getDecl - Get the declaration of this interface.
3017  ObjCInterfaceDecl *getDecl() const { return Decl; }
3018
3019  bool isSugared() const { return false; }
3020  QualType desugar() const { return QualType(this, 0); }
3021
3022  static bool classof(const Type *T) {
3023    return T->getTypeClass() == ObjCInterface;
3024  }
3025  static bool classof(const ObjCInterfaceType *) { return true; }
3026
3027  // Nonsense to "hide" certain members of ObjCObjectType within this
3028  // class.  People asking for protocols on an ObjCInterfaceType are
3029  // not going to get what they want: ObjCInterfaceTypes are
3030  // guaranteed to have no protocols.
3031  enum {
3032    qual_iterator,
3033    qual_begin,
3034    qual_end,
3035    getNumProtocols,
3036    getProtocol
3037  };
3038};
3039
3040inline ObjCInterfaceDecl *ObjCObjectType::getInterface() const {
3041  if (const ObjCInterfaceType *T =
3042        getBaseType()->getAs<ObjCInterfaceType>())
3043    return T->getDecl();
3044  return 0;
3045}
3046
3047/// ObjCObjectPointerType - Used to represent a pointer to an
3048/// Objective C object.  These are constructed from pointer
3049/// declarators when the pointee type is an ObjCObjectType (or sugar
3050/// for one).  In addition, the 'id' and 'Class' types are typedefs
3051/// for these, and the protocol-qualified types 'id<P>' and 'Class<P>'
3052/// are translated into these.
3053///
3054/// Pointers to pointers to Objective C objects are still PointerTypes;
3055/// only the first level of pointer gets it own type implementation.
3056class ObjCObjectPointerType : public Type, public llvm::FoldingSetNode {
3057  QualType PointeeType;
3058
3059  ObjCObjectPointerType(QualType Canonical, QualType Pointee)
3060    : Type(ObjCObjectPointer, Canonical, false),
3061      PointeeType(Pointee) {}
3062  friend class ASTContext;  // ASTContext creates these.
3063
3064protected:
3065  virtual Linkage getLinkageImpl() const;
3066
3067public:
3068  void Destroy(ASTContext& C);
3069
3070  /// getPointeeType - Gets the type pointed to by this ObjC pointer.
3071  /// The result will always be an ObjCObjectType or sugar thereof.
3072  QualType getPointeeType() const { return PointeeType; }
3073
3074  /// getObjCObjectType - Gets the type pointed to by this ObjC
3075  /// pointer.  This method always returns non-null.
3076  ///
3077  /// This method is equivalent to getPointeeType() except that
3078  /// it discards any typedefs (or other sugar) between this
3079  /// type and the "outermost" object type.  So for:
3080  ///   @class A; @protocol P; @protocol Q;
3081  ///   typedef A<P> AP;
3082  ///   typedef A A1;
3083  ///   typedef A1<P> A1P;
3084  ///   typedef A1P<Q> A1PQ;
3085  /// For 'A*', getObjectType() will return 'A'.
3086  /// For 'A<P>*', getObjectType() will return 'A<P>'.
3087  /// For 'AP*', getObjectType() will return 'A<P>'.
3088  /// For 'A1*', getObjectType() will return 'A'.
3089  /// For 'A1<P>*', getObjectType() will return 'A1<P>'.
3090  /// For 'A1P*', getObjectType() will return 'A1<P>'.
3091  /// For 'A1PQ*', getObjectType() will return 'A1<Q>', because
3092  ///   adding protocols to a protocol-qualified base discards the
3093  ///   old qualifiers (for now).  But if it didn't, getObjectType()
3094  ///   would return 'A1P<Q>' (and we'd have to make iterating over
3095  ///   qualifiers more complicated).
3096  const ObjCObjectType *getObjectType() const {
3097    return PointeeType->getAs<ObjCObjectType>();
3098  }
3099
3100  /// getInterfaceType - If this pointer points to an Objective C
3101  /// @interface type, gets the type for that interface.  Any protocol
3102  /// qualifiers on the interface are ignored.
3103  ///
3104  /// \return null if the base type for this pointer is 'id' or 'Class'
3105  const ObjCInterfaceType *getInterfaceType() const {
3106    return getObjectType()->getBaseType()->getAs<ObjCInterfaceType>();
3107  }
3108
3109  /// getInterfaceDecl - If this pointer points to an Objective @interface
3110  /// type, gets the declaration for that interface.
3111  ///
3112  /// \return null if the base type for this pointer is 'id' or 'Class'
3113  ObjCInterfaceDecl *getInterfaceDecl() const {
3114    return getObjectType()->getInterface();
3115  }
3116
3117  /// isObjCIdType - True if this is equivalent to the 'id' type, i.e. if
3118  /// its object type is the primitive 'id' type with no protocols.
3119  bool isObjCIdType() const {
3120    return getObjectType()->isObjCUnqualifiedId();
3121  }
3122
3123  /// isObjCClassType - True if this is equivalent to the 'Class' type,
3124  /// i.e. if its object tive is the primitive 'Class' type with no protocols.
3125  bool isObjCClassType() const {
3126    return getObjectType()->isObjCUnqualifiedClass();
3127  }
3128
3129  /// isObjCQualifiedIdType - True if this is equivalent to 'id<P>' for some
3130  /// non-empty set of protocols.
3131  bool isObjCQualifiedIdType() const {
3132    return getObjectType()->isObjCQualifiedId();
3133  }
3134
3135  /// isObjCQualifiedClassType - True if this is equivalent to 'Class<P>' for
3136  /// some non-empty set of protocols.
3137  bool isObjCQualifiedClassType() const {
3138    return getObjectType()->isObjCQualifiedClass();
3139  }
3140
3141  /// An iterator over the qualifiers on the object type.  Provided
3142  /// for convenience.  This will always iterate over the full set of
3143  /// protocols on a type, not just those provided directly.
3144  typedef ObjCObjectType::qual_iterator qual_iterator;
3145
3146  qual_iterator qual_begin() const {
3147    return getObjectType()->qual_begin();
3148  }
3149  qual_iterator qual_end() const {
3150    return getObjectType()->qual_end();
3151  }
3152  bool qual_empty() const { return getObjectType()->qual_empty(); }
3153
3154  /// getNumProtocols - Return the number of qualifying protocols on
3155  /// the object type.
3156  unsigned getNumProtocols() const {
3157    return getObjectType()->getNumProtocols();
3158  }
3159
3160  /// \brief Retrieve a qualifying protocol by index on the object
3161  /// type.
3162  ObjCProtocolDecl *getProtocol(unsigned I) const {
3163    return getObjectType()->getProtocol(I);
3164  }
3165
3166  bool isSugared() const { return false; }
3167  QualType desugar() const { return QualType(this, 0); }
3168
3169  void Profile(llvm::FoldingSetNodeID &ID) {
3170    Profile(ID, getPointeeType());
3171  }
3172  static void Profile(llvm::FoldingSetNodeID &ID, QualType T) {
3173    ID.AddPointer(T.getAsOpaquePtr());
3174  }
3175  static bool classof(const Type *T) {
3176    return T->getTypeClass() == ObjCObjectPointer;
3177  }
3178  static bool classof(const ObjCObjectPointerType *) { return true; }
3179};
3180
3181/// A qualifier set is used to build a set of qualifiers.
3182class QualifierCollector : public Qualifiers {
3183  ASTContext *Context;
3184
3185public:
3186  QualifierCollector(Qualifiers Qs = Qualifiers())
3187    : Qualifiers(Qs), Context(0) {}
3188  QualifierCollector(ASTContext &Context, Qualifiers Qs = Qualifiers())
3189    : Qualifiers(Qs), Context(&Context) {}
3190
3191  void setContext(ASTContext &C) { Context = &C; }
3192
3193  /// Collect any qualifiers on the given type and return an
3194  /// unqualified type.
3195  const Type *strip(QualType QT) {
3196    addFastQualifiers(QT.getLocalFastQualifiers());
3197    if (QT.hasLocalNonFastQualifiers()) {
3198      const ExtQuals *EQ = QT.getExtQualsUnsafe();
3199      Context = &EQ->getContext();
3200      addQualifiers(EQ->getQualifiers());
3201      return EQ->getBaseType();
3202    }
3203    return QT.getTypePtrUnsafe();
3204  }
3205
3206  /// Apply the collected qualifiers to the given type.
3207  QualType apply(QualType QT) const;
3208
3209  /// Apply the collected qualifiers to the given type.
3210  QualType apply(const Type* T) const;
3211
3212};
3213
3214
3215// Inline function definitions.
3216
3217inline bool QualType::isCanonical() const {
3218  const Type *T = getTypePtr();
3219  if (hasLocalQualifiers())
3220    return T->isCanonicalUnqualified() && !isa<ArrayType>(T);
3221  return T->isCanonicalUnqualified();
3222}
3223
3224inline bool QualType::isCanonicalAsParam() const {
3225  if (hasLocalQualifiers()) return false;
3226  const Type *T = getTypePtr();
3227  return T->isCanonicalUnqualified() &&
3228           !isa<FunctionType>(T) && !isa<ArrayType>(T);
3229}
3230
3231inline bool QualType::isConstQualified() const {
3232  return isLocalConstQualified() ||
3233              getTypePtr()->getCanonicalTypeInternal().isLocalConstQualified();
3234}
3235
3236inline bool QualType::isRestrictQualified() const {
3237  return isLocalRestrictQualified() ||
3238            getTypePtr()->getCanonicalTypeInternal().isLocalRestrictQualified();
3239}
3240
3241
3242inline bool QualType::isVolatileQualified() const {
3243  return isLocalVolatileQualified() ||
3244  getTypePtr()->getCanonicalTypeInternal().isLocalVolatileQualified();
3245}
3246
3247inline bool QualType::hasQualifiers() const {
3248  return hasLocalQualifiers() ||
3249                  getTypePtr()->getCanonicalTypeInternal().hasLocalQualifiers();
3250}
3251
3252inline Qualifiers QualType::getQualifiers() const {
3253  Qualifiers Quals = getLocalQualifiers();
3254  Quals.addQualifiers(
3255                 getTypePtr()->getCanonicalTypeInternal().getLocalQualifiers());
3256  return Quals;
3257}
3258
3259inline unsigned QualType::getCVRQualifiers() const {
3260  return getLocalCVRQualifiers() |
3261              getTypePtr()->getCanonicalTypeInternal().getLocalCVRQualifiers();
3262}
3263
3264/// getCVRQualifiersThroughArrayTypes - If there are CVR qualifiers for this
3265/// type, returns them. Otherwise, if this is an array type, recurses
3266/// on the element type until some qualifiers have been found or a non-array
3267/// type reached.
3268inline unsigned QualType::getCVRQualifiersThroughArrayTypes() const {
3269  if (unsigned Quals = getCVRQualifiers())
3270    return Quals;
3271  QualType CT = getTypePtr()->getCanonicalTypeInternal();
3272  if (const ArrayType *AT = dyn_cast<ArrayType>(CT))
3273    return AT->getElementType().getCVRQualifiersThroughArrayTypes();
3274  return 0;
3275}
3276
3277inline void QualType::removeConst() {
3278  removeFastQualifiers(Qualifiers::Const);
3279}
3280
3281inline void QualType::removeRestrict() {
3282  removeFastQualifiers(Qualifiers::Restrict);
3283}
3284
3285inline void QualType::removeVolatile() {
3286  QualifierCollector Qc;
3287  const Type *Ty = Qc.strip(*this);
3288  if (Qc.hasVolatile()) {
3289    Qc.removeVolatile();
3290    *this = Qc.apply(Ty);
3291  }
3292}
3293
3294inline void QualType::removeCVRQualifiers(unsigned Mask) {
3295  assert(!(Mask & ~Qualifiers::CVRMask) && "mask has non-CVR bits");
3296
3297  // Fast path: we don't need to touch the slow qualifiers.
3298  if (!(Mask & ~Qualifiers::FastMask)) {
3299    removeFastQualifiers(Mask);
3300    return;
3301  }
3302
3303  QualifierCollector Qc;
3304  const Type *Ty = Qc.strip(*this);
3305  Qc.removeCVRQualifiers(Mask);
3306  *this = Qc.apply(Ty);
3307}
3308
3309/// getAddressSpace - Return the address space of this type.
3310inline unsigned QualType::getAddressSpace() const {
3311  if (hasLocalNonFastQualifiers()) {
3312    const ExtQuals *EQ = getExtQualsUnsafe();
3313    if (EQ->hasAddressSpace())
3314      return EQ->getAddressSpace();
3315  }
3316
3317  QualType CT = getTypePtr()->getCanonicalTypeInternal();
3318  if (CT.hasLocalNonFastQualifiers()) {
3319    const ExtQuals *EQ = CT.getExtQualsUnsafe();
3320    if (EQ->hasAddressSpace())
3321      return EQ->getAddressSpace();
3322  }
3323
3324  if (const ArrayType *AT = dyn_cast<ArrayType>(CT))
3325    return AT->getElementType().getAddressSpace();
3326  if (const RecordType *RT = dyn_cast<RecordType>(CT))
3327    return RT->getAddressSpace();
3328  return 0;
3329}
3330
3331/// getObjCGCAttr - Return the gc attribute of this type.
3332inline Qualifiers::GC QualType::getObjCGCAttr() const {
3333  if (hasLocalNonFastQualifiers()) {
3334    const ExtQuals *EQ = getExtQualsUnsafe();
3335    if (EQ->hasObjCGCAttr())
3336      return EQ->getObjCGCAttr();
3337  }
3338
3339  QualType CT = getTypePtr()->getCanonicalTypeInternal();
3340  if (CT.hasLocalNonFastQualifiers()) {
3341    const ExtQuals *EQ = CT.getExtQualsUnsafe();
3342    if (EQ->hasObjCGCAttr())
3343      return EQ->getObjCGCAttr();
3344  }
3345
3346  if (const ArrayType *AT = dyn_cast<ArrayType>(CT))
3347      return AT->getElementType().getObjCGCAttr();
3348  if (const ObjCObjectPointerType *PT = CT->getAs<ObjCObjectPointerType>())
3349    return PT->getPointeeType().getObjCGCAttr();
3350  // We most look at all pointer types, not just pointer to interface types.
3351  if (const PointerType *PT = CT->getAs<PointerType>())
3352    return PT->getPointeeType().getObjCGCAttr();
3353  return Qualifiers::GCNone;
3354}
3355
3356inline FunctionType::ExtInfo getFunctionExtInfo(const Type &t) {
3357  if (const PointerType *PT = t.getAs<PointerType>()) {
3358    if (const FunctionType *FT = PT->getPointeeType()->getAs<FunctionType>())
3359      return FT->getExtInfo();
3360  } else if (const FunctionType *FT = t.getAs<FunctionType>())
3361    return FT->getExtInfo();
3362
3363  return FunctionType::ExtInfo();
3364}
3365
3366inline FunctionType::ExtInfo getFunctionExtInfo(QualType t) {
3367  return getFunctionExtInfo(*t);
3368}
3369
3370/// isMoreQualifiedThan - Determine whether this type is more
3371/// qualified than the Other type. For example, "const volatile int"
3372/// is more qualified than "const int", "volatile int", and
3373/// "int". However, it is not more qualified than "const volatile
3374/// int".
3375inline bool QualType::isMoreQualifiedThan(QualType Other) const {
3376  // FIXME: work on arbitrary qualifiers
3377  unsigned MyQuals = this->getCVRQualifiersThroughArrayTypes();
3378  unsigned OtherQuals = Other.getCVRQualifiersThroughArrayTypes();
3379  if (getAddressSpace() != Other.getAddressSpace())
3380    return false;
3381  return MyQuals != OtherQuals && (MyQuals | OtherQuals) == MyQuals;
3382}
3383
3384/// isAtLeastAsQualifiedAs - Determine whether this type is at last
3385/// as qualified as the Other type. For example, "const volatile
3386/// int" is at least as qualified as "const int", "volatile int",
3387/// "int", and "const volatile int".
3388inline bool QualType::isAtLeastAsQualifiedAs(QualType Other) const {
3389  // FIXME: work on arbitrary qualifiers
3390  unsigned MyQuals = this->getCVRQualifiersThroughArrayTypes();
3391  unsigned OtherQuals = Other.getCVRQualifiersThroughArrayTypes();
3392  if (getAddressSpace() != Other.getAddressSpace())
3393    return false;
3394  return (MyQuals | OtherQuals) == MyQuals;
3395}
3396
3397/// getNonReferenceType - If Type is a reference type (e.g., const
3398/// int&), returns the type that the reference refers to ("const
3399/// int"). Otherwise, returns the type itself. This routine is used
3400/// throughout Sema to implement C++ 5p6:
3401///
3402///   If an expression initially has the type "reference to T" (8.3.2,
3403///   8.5.3), the type is adjusted to "T" prior to any further
3404///   analysis, the expression designates the object or function
3405///   denoted by the reference, and the expression is an lvalue.
3406inline QualType QualType::getNonReferenceType() const {
3407  if (const ReferenceType *RefType = (*this)->getAs<ReferenceType>())
3408    return RefType->getPointeeType();
3409  else
3410    return *this;
3411}
3412
3413inline bool Type::isFunctionType() const {
3414  return isa<FunctionType>(CanonicalType);
3415}
3416inline bool Type::isPointerType() const {
3417  return isa<PointerType>(CanonicalType);
3418}
3419inline bool Type::isAnyPointerType() const {
3420  return isPointerType() || isObjCObjectPointerType();
3421}
3422inline bool Type::isBlockPointerType() const {
3423  return isa<BlockPointerType>(CanonicalType);
3424}
3425inline bool Type::isReferenceType() const {
3426  return isa<ReferenceType>(CanonicalType);
3427}
3428inline bool Type::isLValueReferenceType() const {
3429  return isa<LValueReferenceType>(CanonicalType);
3430}
3431inline bool Type::isRValueReferenceType() const {
3432  return isa<RValueReferenceType>(CanonicalType);
3433}
3434inline bool Type::isFunctionPointerType() const {
3435  if (const PointerType* T = getAs<PointerType>())
3436    return T->getPointeeType()->isFunctionType();
3437  else
3438    return false;
3439}
3440inline bool Type::isMemberPointerType() const {
3441  return isa<MemberPointerType>(CanonicalType);
3442}
3443inline bool Type::isMemberFunctionPointerType() const {
3444  if (const MemberPointerType* T = getAs<MemberPointerType>())
3445    return T->getPointeeType()->isFunctionType();
3446  else
3447    return false;
3448}
3449inline bool Type::isArrayType() const {
3450  return isa<ArrayType>(CanonicalType);
3451}
3452inline bool Type::isConstantArrayType() const {
3453  return isa<ConstantArrayType>(CanonicalType);
3454}
3455inline bool Type::isIncompleteArrayType() const {
3456  return isa<IncompleteArrayType>(CanonicalType);
3457}
3458inline bool Type::isVariableArrayType() const {
3459  return isa<VariableArrayType>(CanonicalType);
3460}
3461inline bool Type::isDependentSizedArrayType() const {
3462  return isa<DependentSizedArrayType>(CanonicalType);
3463}
3464inline bool Type::isRecordType() const {
3465  return isa<RecordType>(CanonicalType);
3466}
3467inline bool Type::isAnyComplexType() const {
3468  return isa<ComplexType>(CanonicalType);
3469}
3470inline bool Type::isVectorType() const {
3471  return isa<VectorType>(CanonicalType);
3472}
3473inline bool Type::isExtVectorType() const {
3474  return isa<ExtVectorType>(CanonicalType);
3475}
3476inline bool Type::isObjCObjectPointerType() const {
3477  return isa<ObjCObjectPointerType>(CanonicalType);
3478}
3479inline bool Type::isObjCObjectType() const {
3480  return isa<ObjCObjectType>(CanonicalType);
3481}
3482inline bool Type::isObjCQualifiedIdType() const {
3483  if (const ObjCObjectPointerType *OPT = getAs<ObjCObjectPointerType>())
3484    return OPT->isObjCQualifiedIdType();
3485  return false;
3486}
3487inline bool Type::isObjCQualifiedClassType() const {
3488  if (const ObjCObjectPointerType *OPT = getAs<ObjCObjectPointerType>())
3489    return OPT->isObjCQualifiedClassType();
3490  return false;
3491}
3492inline bool Type::isObjCIdType() const {
3493  if (const ObjCObjectPointerType *OPT = getAs<ObjCObjectPointerType>())
3494    return OPT->isObjCIdType();
3495  return false;
3496}
3497inline bool Type::isObjCClassType() const {
3498  if (const ObjCObjectPointerType *OPT = getAs<ObjCObjectPointerType>())
3499    return OPT->isObjCClassType();
3500  return false;
3501}
3502inline bool Type::isObjCSelType() const {
3503  if (const PointerType *OPT = getAs<PointerType>())
3504    return OPT->getPointeeType()->isSpecificBuiltinType(BuiltinType::ObjCSel);
3505  return false;
3506}
3507inline bool Type::isObjCBuiltinType() const {
3508  return isObjCIdType() || isObjCClassType() || isObjCSelType();
3509}
3510inline bool Type::isTemplateTypeParmType() const {
3511  return isa<TemplateTypeParmType>(CanonicalType);
3512}
3513
3514inline bool Type::isBuiltinType() const {
3515  return getAs<BuiltinType>();
3516}
3517
3518inline bool Type::isSpecificBuiltinType(unsigned K) const {
3519  if (const BuiltinType *BT = getAs<BuiltinType>())
3520    if (BT->getKind() == (BuiltinType::Kind) K)
3521      return true;
3522  return false;
3523}
3524
3525/// \brief Determines whether this is a type for which one can define
3526/// an overloaded operator.
3527inline bool Type::isOverloadableType() const {
3528  return isDependentType() || isRecordType() || isEnumeralType();
3529}
3530
3531inline bool Type::hasPointerRepresentation() const {
3532  return (isPointerType() || isReferenceType() || isBlockPointerType() ||
3533          isObjCObjectPointerType() || isNullPtrType());
3534}
3535
3536inline bool Type::hasObjCPointerRepresentation() const {
3537  return isObjCObjectPointerType();
3538}
3539
3540/// Insertion operator for diagnostics.  This allows sending QualType's into a
3541/// diagnostic with <<.
3542inline const DiagnosticBuilder &operator<<(const DiagnosticBuilder &DB,
3543                                           QualType T) {
3544  DB.AddTaggedVal(reinterpret_cast<intptr_t>(T.getAsOpaquePtr()),
3545                  Diagnostic::ak_qualtype);
3546  return DB;
3547}
3548
3549/// Insertion operator for partial diagnostics.  This allows sending QualType's
3550/// into a diagnostic with <<.
3551inline const PartialDiagnostic &operator<<(const PartialDiagnostic &PD,
3552                                           QualType T) {
3553  PD.AddTaggedVal(reinterpret_cast<intptr_t>(T.getAsOpaquePtr()),
3554                  Diagnostic::ak_qualtype);
3555  return PD;
3556}
3557
3558// Helper class template that is used by Type::getAs to ensure that one does
3559// not try to look through a qualified type to get to an array type.
3560template<typename T,
3561         bool isArrayType = (llvm::is_same<T, ArrayType>::value ||
3562                             llvm::is_base_of<ArrayType, T>::value)>
3563struct ArrayType_cannot_be_used_with_getAs { };
3564
3565template<typename T>
3566struct ArrayType_cannot_be_used_with_getAs<T, true>;
3567
3568/// Member-template getAs<specific type>'.
3569template <typename T> const T *Type::getAs() const {
3570  ArrayType_cannot_be_used_with_getAs<T> at;
3571  (void)at;
3572
3573  // If this is directly a T type, return it.
3574  if (const T *Ty = dyn_cast<T>(this))
3575    return Ty;
3576
3577  // If the canonical form of this type isn't the right kind, reject it.
3578  if (!isa<T>(CanonicalType))
3579    return 0;
3580
3581  // If this is a typedef for the type, strip the typedef off without
3582  // losing all typedef information.
3583  return cast<T>(getUnqualifiedDesugaredType());
3584}
3585
3586}  // end namespace clang
3587
3588#endif
3589