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