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