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