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