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