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