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