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