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