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