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