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