Type.h revision bef0efd11bc4430a3ee437a3213cec5c18af855a
1//===--- Type.h - C Language Family Type Representation ---------*- C++ -*-===//
2//
3//                     The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10//  This file defines the Type interface and subclasses.
11//
12//===----------------------------------------------------------------------===//
13
14#ifndef LLVM_CLANG_AST_TYPE_H
15#define LLVM_CLANG_AST_TYPE_H
16
17#include "clang/Basic/Diagnostic.h"
18#include "clang/Basic/IdentifierTable.h"
19#include "clang/Basic/Linkage.h"
20#include "clang/Basic/PartialDiagnostic.h"
21#include "clang/AST/NestedNameSpecifier.h"
22#include "clang/AST/TemplateName.h"
23#include "llvm/Support/Casting.h"
24#include "llvm/Support/type_traits.h"
25#include "llvm/ADT/APSInt.h"
26#include "llvm/ADT/FoldingSet.h"
27#include "llvm/ADT/PointerIntPair.h"
28#include "llvm/ADT/PointerUnion.h"
29
30using llvm::isa;
31using llvm::cast;
32using llvm::cast_or_null;
33using llvm::dyn_cast;
34using llvm::dyn_cast_or_null;
35namespace clang {
36  enum {
37    TypeAlignmentInBits = 3,
38    TypeAlignment = 1 << TypeAlignmentInBits
39  };
40  class Type;
41  class ExtQuals;
42  class QualType;
43}
44
45namespace llvm {
46  template <typename T>
47  class PointerLikeTypeTraits;
48  template<>
49  class PointerLikeTypeTraits< ::clang::Type*> {
50  public:
51    static inline void *getAsVoidPointer(::clang::Type *P) { return P; }
52    static inline ::clang::Type *getFromVoidPointer(void *P) {
53      return static_cast< ::clang::Type*>(P);
54    }
55    enum { NumLowBitsAvailable = clang::TypeAlignmentInBits };
56  };
57  template<>
58  class PointerLikeTypeTraits< ::clang::ExtQuals*> {
59  public:
60    static inline void *getAsVoidPointer(::clang::ExtQuals *P) { return P; }
61    static inline ::clang::ExtQuals *getFromVoidPointer(void *P) {
62      return static_cast< ::clang::ExtQuals*>(P);
63    }
64    enum { NumLowBitsAvailable = clang::TypeAlignmentInBits };
65  };
66
67  template <>
68  struct isPodLike<clang::QualType> { static const bool value = true; };
69}
70
71namespace clang {
72  class ASTContext;
73  class TypedefDecl;
74  class TemplateDecl;
75  class TemplateTypeParmDecl;
76  class NonTypeTemplateParmDecl;
77  class TemplateTemplateParmDecl;
78  class TagDecl;
79  class RecordDecl;
80  class CXXRecordDecl;
81  class EnumDecl;
82  class FieldDecl;
83  class ObjCInterfaceDecl;
84  class ObjCProtocolDecl;
85  class ObjCMethodDecl;
86  class UnresolvedUsingTypenameDecl;
87  class Expr;
88  class Stmt;
89  class SourceLocation;
90  class StmtIteratorBase;
91  class TemplateArgument;
92  class TemplateArgumentLoc;
93  class TemplateArgumentListInfo;
94  class Type;
95  class ElaboratedType;
96  struct PrintingPolicy;
97
98  template <typename> class CanQual;
99  typedef CanQual<Type> CanQualType;
100
101  // Provide forward declarations for all of the *Type classes
102#define TYPE(Class, Base) class Class##Type;
103#include "clang/AST/TypeNodes.def"
104
105/// Qualifiers - The collection of all-type qualifiers we support.
106/// Clang supports five independent qualifiers:
107/// * C99: const, volatile, and restrict
108/// * Embedded C (TR18037): address spaces
109/// * Objective C: the GC attributes (none, weak, or strong)
110class Qualifiers {
111public:
112  enum TQ { // NOTE: These flags must be kept in sync with DeclSpec::TQ.
113    Const    = 0x1,
114    Restrict = 0x2,
115    Volatile = 0x4,
116    CVRMask = Const | Volatile | Restrict
117  };
118
119  enum GC {
120    GCNone = 0,
121    Weak,
122    Strong
123  };
124
125  enum {
126    /// The maximum supported address space number.
127    /// 24 bits should be enough for anyone.
128    MaxAddressSpace = 0xffffffu,
129
130    /// The width of the "fast" qualifier mask.
131    FastWidth = 2,
132
133    /// The fast qualifier mask.
134    FastMask = (1 << FastWidth) - 1
135  };
136
137  Qualifiers() : Mask(0) {}
138
139  static Qualifiers fromFastMask(unsigned Mask) {
140    Qualifiers Qs;
141    Qs.addFastQualifiers(Mask);
142    return Qs;
143  }
144
145  static Qualifiers fromCVRMask(unsigned CVR) {
146    Qualifiers Qs;
147    Qs.addCVRQualifiers(CVR);
148    return Qs;
149  }
150
151  // Deserialize qualifiers from an opaque representation.
152  static Qualifiers fromOpaqueValue(unsigned opaque) {
153    Qualifiers Qs;
154    Qs.Mask = opaque;
155    return Qs;
156  }
157
158  // Serialize these qualifiers into an opaque representation.
159  unsigned getAsOpaqueValue() const {
160    return Mask;
161  }
162
163  bool hasConst() const { return Mask & Const; }
164  void setConst(bool flag) {
165    Mask = (Mask & ~Const) | (flag ? Const : 0);
166  }
167  void removeConst() { Mask &= ~Const; }
168  void addConst() { Mask |= Const; }
169
170  bool hasVolatile() const { return Mask & Volatile; }
171  void setVolatile(bool flag) {
172    Mask = (Mask & ~Volatile) | (flag ? Volatile : 0);
173  }
174  void removeVolatile() { Mask &= ~Volatile; }
175  void addVolatile() { Mask |= Volatile; }
176
177  bool hasRestrict() const { return Mask & Restrict; }
178  void setRestrict(bool flag) {
179    Mask = (Mask & ~Restrict) | (flag ? Restrict : 0);
180  }
181  void removeRestrict() { Mask &= ~Restrict; }
182  void addRestrict() { Mask |= Restrict; }
183
184  bool hasCVRQualifiers() const { return getCVRQualifiers(); }
185  unsigned getCVRQualifiers() const { return Mask & CVRMask; }
186  void setCVRQualifiers(unsigned mask) {
187    assert(!(mask & ~CVRMask) && "bitmask contains non-CVR bits");
188    Mask = (Mask & ~CVRMask) | mask;
189  }
190  void removeCVRQualifiers(unsigned mask) {
191    assert(!(mask & ~CVRMask) && "bitmask contains non-CVR bits");
192    Mask &= ~mask;
193  }
194  void removeCVRQualifiers() {
195    removeCVRQualifiers(CVRMask);
196  }
197  void addCVRQualifiers(unsigned mask) {
198    assert(!(mask & ~CVRMask) && "bitmask contains non-CVR bits");
199    Mask |= mask;
200  }
201
202  bool hasObjCGCAttr() const { return Mask & GCAttrMask; }
203  GC getObjCGCAttr() const { return GC((Mask & GCAttrMask) >> GCAttrShift); }
204  void setObjCGCAttr(GC type) {
205    Mask = (Mask & ~GCAttrMask) | (type << GCAttrShift);
206  }
207  void removeObjCGCAttr() { setObjCGCAttr(GCNone); }
208  void addObjCGCAttr(GC type) {
209    assert(type);
210    setObjCGCAttr(type);
211  }
212
213  bool hasAddressSpace() const { return Mask & AddressSpaceMask; }
214  unsigned getAddressSpace() const { return Mask >> AddressSpaceShift; }
215  void setAddressSpace(unsigned space) {
216    assert(space <= MaxAddressSpace);
217    Mask = (Mask & ~AddressSpaceMask)
218         | (((uint32_t) space) << AddressSpaceShift);
219  }
220  void removeAddressSpace() { setAddressSpace(0); }
221  void addAddressSpace(unsigned space) {
222    assert(space);
223    setAddressSpace(space);
224  }
225
226  // Fast qualifiers are those that can be allocated directly
227  // on a QualType object.
228  bool hasFastQualifiers() const { return getFastQualifiers(); }
229  unsigned getFastQualifiers() const { return Mask & FastMask; }
230  void setFastQualifiers(unsigned mask) {
231    assert(!(mask & ~FastMask) && "bitmask contains non-fast qualifier bits");
232    Mask = (Mask & ~FastMask) | mask;
233  }
234  void removeFastQualifiers(unsigned mask) {
235    assert(!(mask & ~FastMask) && "bitmask contains non-fast qualifier bits");
236    Mask &= ~mask;
237  }
238  void removeFastQualifiers() {
239    removeFastQualifiers(FastMask);
240  }
241  void addFastQualifiers(unsigned mask) {
242    assert(!(mask & ~FastMask) && "bitmask contains non-fast qualifier bits");
243    Mask |= mask;
244  }
245
246  /// hasNonFastQualifiers - Return true if the set contains any
247  /// qualifiers which require an ExtQuals node to be allocated.
248  bool hasNonFastQualifiers() const { return Mask & ~FastMask; }
249  Qualifiers getNonFastQualifiers() const {
250    Qualifiers Quals = *this;
251    Quals.setFastQualifiers(0);
252    return Quals;
253  }
254
255  /// hasQualifiers - Return true if the set contains any qualifiers.
256  bool hasQualifiers() const { return Mask; }
257  bool empty() const { return !Mask; }
258
259  /// \brief Add the qualifiers from the given set to this set.
260  void addQualifiers(Qualifiers Q) {
261    // If the other set doesn't have any non-boolean qualifiers, just
262    // bit-or it in.
263    if (!(Q.Mask & ~CVRMask))
264      Mask |= Q.Mask;
265    else {
266      Mask |= (Q.Mask & CVRMask);
267      if (Q.hasAddressSpace())
268        addAddressSpace(Q.getAddressSpace());
269      if (Q.hasObjCGCAttr())
270        addObjCGCAttr(Q.getObjCGCAttr());
271    }
272  }
273
274  bool 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  /// \brief Retrieves the CXXRecordDecl that this type refers to, either
927  /// because the type is a RecordType or because it is the injected-class-name
928  /// type of a class template or class template partial specialization.
929  CXXRecordDecl *getAsCXXRecordDecl() const;
930
931  // Member-template getAs<specific type>'.  This scheme will eventually
932  // replace the specific getAsXXXX methods above.
933  //
934  // There are some specializations of this member template listed
935  // immediately following this class.
936  template <typename T> const T *getAs() const;
937
938  /// getAsPointerToObjCInterfaceType - If this is a pointer to an ObjC
939  /// interface, return the interface type, otherwise return null.
940  const ObjCInterfaceType *getAsPointerToObjCInterfaceType() const;
941
942  /// getArrayElementTypeNoTypeQual - If this is an array type, return the
943  /// element type of the array, potentially with type qualifiers missing.
944  /// This method should never be used when type qualifiers are meaningful.
945  const Type *getArrayElementTypeNoTypeQual() const;
946
947  /// getPointeeType - If this is a pointer, ObjC object pointer, or block
948  /// pointer, this returns the respective pointee.
949  QualType getPointeeType() const;
950
951  /// getUnqualifiedDesugaredType() - Return the specified type with
952  /// any "sugar" removed from the type, removing any typedefs,
953  /// typeofs, etc., as well as any qualifiers.
954  const Type *getUnqualifiedDesugaredType() const;
955
956  /// More type predicates useful for type checking/promotion
957  bool isPromotableIntegerType() const; // C99 6.3.1.1p2
958
959  /// isSignedIntegerType - Return true if this is an integer type that is
960  /// signed, according to C99 6.2.5p4 [char, signed char, short, int, long..],
961  /// an enum decl which has a signed representation, or a vector of signed
962  /// integer element type.
963  bool isSignedIntegerType() const;
964
965  /// isUnsignedIntegerType - Return true if this is an integer type that is
966  /// unsigned, according to C99 6.2.5p6 [which returns true for _Bool], an enum
967  /// decl which has an unsigned representation, or a vector of unsigned integer
968  /// element type.
969  bool isUnsignedIntegerType() const;
970
971  /// isConstantSizeType - Return true if this is not a variable sized type,
972  /// according to the rules of C99 6.7.5p3.  It is not legal to call this on
973  /// incomplete types.
974  bool isConstantSizeType() const;
975
976  /// isSpecifierType - Returns true if this type can be represented by some
977  /// set of type specifiers.
978  bool isSpecifierType() const;
979
980  const char *getTypeClassName() const;
981
982  /// \brief Determine the linkage of this type.
983  virtual Linkage getLinkage() const;
984
985  QualType getCanonicalTypeInternal() const {
986    return CanonicalType;
987  }
988  CanQualType getCanonicalTypeUnqualified() const; // in CanonicalType.h
989  void dump() const;
990  static bool classof(const Type *) { return true; }
991};
992
993template <> inline const TypedefType *Type::getAs() const {
994  return dyn_cast<TypedefType>(this);
995}
996
997// We can do canonical leaf types faster, because we don't have to
998// worry about preserving child type decoration.
999#define TYPE(Class, Base)
1000#define LEAF_TYPE(Class) \
1001template <> inline const Class##Type *Type::getAs() const { \
1002  return dyn_cast<Class##Type>(CanonicalType); \
1003}
1004#include "clang/AST/TypeNodes.def"
1005
1006
1007/// BuiltinType - This class is used for builtin types like 'int'.  Builtin
1008/// types are always canonical and have a literal name field.
1009class BuiltinType : public Type {
1010public:
1011  enum Kind {
1012    Void,
1013
1014    Bool,     // This is bool and/or _Bool.
1015    Char_U,   // This is 'char' for targets where char is unsigned.
1016    UChar,    // This is explicitly qualified unsigned char.
1017    Char16,   // This is 'char16_t' for C++.
1018    Char32,   // This is 'char32_t' for C++.
1019    UShort,
1020    UInt,
1021    ULong,
1022    ULongLong,
1023    UInt128,  // __uint128_t
1024
1025    Char_S,   // This is 'char' for targets where char is signed.
1026    SChar,    // This is explicitly qualified signed char.
1027    WChar,    // This is 'wchar_t' for C++.
1028    Short,
1029    Int,
1030    Long,
1031    LongLong,
1032    Int128,   // __int128_t
1033
1034    Float, Double, LongDouble,
1035
1036    NullPtr,  // This is the type of C++0x 'nullptr'.
1037
1038    Overload,  // This represents the type of an overloaded function declaration.
1039    Dependent, // This represents the type of a type-dependent expression.
1040
1041    UndeducedAuto, // In C++0x, this represents the type of an auto variable
1042                   // that has not been deduced yet.
1043    ObjCId,    // This represents the ObjC 'id' type.
1044    ObjCClass, // This represents the ObjC 'Class' type.
1045    ObjCSel    // This represents the ObjC 'SEL' type.
1046  };
1047private:
1048  Kind TypeKind;
1049public:
1050  BuiltinType(Kind K)
1051    : Type(Builtin, QualType(), /*Dependent=*/(K == Dependent)),
1052      TypeKind(K) {}
1053
1054  Kind getKind() const { return TypeKind; }
1055  const char *getName(const LangOptions &LO) const;
1056
1057  bool isSugared() const { return false; }
1058  QualType desugar() const { return QualType(this, 0); }
1059
1060  bool isInteger() const {
1061    return TypeKind >= Bool && TypeKind <= Int128;
1062  }
1063
1064  bool isSignedInteger() const {
1065    return TypeKind >= Char_S && TypeKind <= Int128;
1066  }
1067
1068  bool isUnsignedInteger() const {
1069    return TypeKind >= Bool && TypeKind <= UInt128;
1070  }
1071
1072  bool isFloatingPoint() const {
1073    return TypeKind >= Float && TypeKind <= LongDouble;
1074  }
1075
1076  virtual Linkage getLinkage() const;
1077
1078  static bool classof(const Type *T) { return T->getTypeClass() == Builtin; }
1079  static bool classof(const BuiltinType *) { return true; }
1080};
1081
1082/// ComplexType - C99 6.2.5p11 - Complex values.  This supports the C99 complex
1083/// types (_Complex float etc) as well as the GCC integer complex extensions.
1084///
1085class ComplexType : public Type, public llvm::FoldingSetNode {
1086  QualType ElementType;
1087  ComplexType(QualType Element, QualType CanonicalPtr) :
1088    Type(Complex, CanonicalPtr, Element->isDependentType()),
1089    ElementType(Element) {
1090  }
1091  friend class ASTContext;  // ASTContext creates these.
1092public:
1093  QualType getElementType() const { return ElementType; }
1094
1095  bool isSugared() const { return false; }
1096  QualType desugar() const { return QualType(this, 0); }
1097
1098  void Profile(llvm::FoldingSetNodeID &ID) {
1099    Profile(ID, getElementType());
1100  }
1101  static void Profile(llvm::FoldingSetNodeID &ID, QualType Element) {
1102    ID.AddPointer(Element.getAsOpaquePtr());
1103  }
1104
1105  virtual Linkage getLinkage() const;
1106
1107  static bool classof(const Type *T) { return T->getTypeClass() == Complex; }
1108  static bool classof(const ComplexType *) { return true; }
1109};
1110
1111/// PointerType - C99 6.7.5.1 - Pointer Declarators.
1112///
1113class PointerType : public Type, public llvm::FoldingSetNode {
1114  QualType PointeeType;
1115
1116  PointerType(QualType Pointee, QualType CanonicalPtr) :
1117    Type(Pointer, CanonicalPtr, Pointee->isDependentType()), PointeeType(Pointee) {
1118  }
1119  friend class ASTContext;  // ASTContext creates these.
1120public:
1121
1122  QualType getPointeeType() const { return PointeeType; }
1123
1124  bool isSugared() const { return false; }
1125  QualType desugar() const { return QualType(this, 0); }
1126
1127  void Profile(llvm::FoldingSetNodeID &ID) {
1128    Profile(ID, getPointeeType());
1129  }
1130  static void Profile(llvm::FoldingSetNodeID &ID, QualType Pointee) {
1131    ID.AddPointer(Pointee.getAsOpaquePtr());
1132  }
1133
1134  virtual Linkage getLinkage() const;
1135
1136  static bool classof(const Type *T) { return T->getTypeClass() == Pointer; }
1137  static bool classof(const PointerType *) { return true; }
1138};
1139
1140/// BlockPointerType - pointer to a block type.
1141/// This type is to represent types syntactically represented as
1142/// "void (^)(int)", etc. Pointee is required to always be a function type.
1143///
1144class BlockPointerType : public Type, public llvm::FoldingSetNode {
1145  QualType PointeeType;  // Block is some kind of pointer type
1146  BlockPointerType(QualType Pointee, QualType CanonicalCls) :
1147    Type(BlockPointer, CanonicalCls, Pointee->isDependentType()),
1148    PointeeType(Pointee) {
1149  }
1150  friend class ASTContext;  // ASTContext creates these.
1151public:
1152
1153  // Get the pointee type. Pointee is required to always be a function type.
1154  QualType getPointeeType() const { return PointeeType; }
1155
1156  bool isSugared() const { return false; }
1157  QualType desugar() const { return QualType(this, 0); }
1158
1159  void Profile(llvm::FoldingSetNodeID &ID) {
1160      Profile(ID, getPointeeType());
1161  }
1162  static void Profile(llvm::FoldingSetNodeID &ID, QualType Pointee) {
1163      ID.AddPointer(Pointee.getAsOpaquePtr());
1164  }
1165
1166  virtual Linkage getLinkage() const;
1167
1168  static bool classof(const Type *T) {
1169    return T->getTypeClass() == BlockPointer;
1170  }
1171  static bool classof(const BlockPointerType *) { return true; }
1172};
1173
1174/// ReferenceType - Base for LValueReferenceType and RValueReferenceType
1175///
1176class ReferenceType : public Type, public llvm::FoldingSetNode {
1177  QualType PointeeType;
1178
1179  /// True if the type was originally spelled with an lvalue sigil.
1180  /// This is never true of rvalue references but can also be false
1181  /// on lvalue references because of C++0x [dcl.typedef]p9,
1182  /// as follows:
1183  ///
1184  ///   typedef int &ref;    // lvalue, spelled lvalue
1185  ///   typedef int &&rvref; // rvalue
1186  ///   ref &a;              // lvalue, inner ref, spelled lvalue
1187  ///   ref &&a;             // lvalue, inner ref
1188  ///   rvref &a;            // lvalue, inner ref, spelled lvalue
1189  ///   rvref &&a;           // rvalue, inner ref
1190  bool SpelledAsLValue;
1191
1192  /// True if the inner type is a reference type.  This only happens
1193  /// in non-canonical forms.
1194  bool InnerRef;
1195
1196protected:
1197  ReferenceType(TypeClass tc, QualType Referencee, QualType CanonicalRef,
1198                bool SpelledAsLValue) :
1199    Type(tc, CanonicalRef, Referencee->isDependentType()),
1200    PointeeType(Referencee), SpelledAsLValue(SpelledAsLValue),
1201    InnerRef(Referencee->isReferenceType()) {
1202  }
1203public:
1204  bool isSpelledAsLValue() const { return SpelledAsLValue; }
1205  bool isInnerRef() const { return InnerRef; }
1206
1207  QualType getPointeeTypeAsWritten() const { return PointeeType; }
1208  QualType getPointeeType() const {
1209    // FIXME: this might strip inner qualifiers; okay?
1210    const ReferenceType *T = this;
1211    while (T->InnerRef)
1212      T = T->PointeeType->getAs<ReferenceType>();
1213    return T->PointeeType;
1214  }
1215
1216  void Profile(llvm::FoldingSetNodeID &ID) {
1217    Profile(ID, PointeeType, SpelledAsLValue);
1218  }
1219  static void Profile(llvm::FoldingSetNodeID &ID,
1220                      QualType Referencee,
1221                      bool SpelledAsLValue) {
1222    ID.AddPointer(Referencee.getAsOpaquePtr());
1223    ID.AddBoolean(SpelledAsLValue);
1224  }
1225
1226  virtual Linkage getLinkage() const;
1227
1228  static bool classof(const Type *T) {
1229    return T->getTypeClass() == LValueReference ||
1230           T->getTypeClass() == RValueReference;
1231  }
1232  static bool classof(const ReferenceType *) { return true; }
1233};
1234
1235/// LValueReferenceType - C++ [dcl.ref] - Lvalue reference
1236///
1237class LValueReferenceType : public ReferenceType {
1238  LValueReferenceType(QualType Referencee, QualType CanonicalRef,
1239                      bool SpelledAsLValue) :
1240    ReferenceType(LValueReference, Referencee, CanonicalRef, SpelledAsLValue)
1241  {}
1242  friend class ASTContext; // ASTContext creates these
1243public:
1244  bool isSugared() const { return false; }
1245  QualType desugar() const { return QualType(this, 0); }
1246
1247  static bool classof(const Type *T) {
1248    return T->getTypeClass() == LValueReference;
1249  }
1250  static bool classof(const LValueReferenceType *) { return true; }
1251};
1252
1253/// RValueReferenceType - C++0x [dcl.ref] - Rvalue reference
1254///
1255class RValueReferenceType : public ReferenceType {
1256  RValueReferenceType(QualType Referencee, QualType CanonicalRef) :
1257    ReferenceType(RValueReference, Referencee, CanonicalRef, false) {
1258  }
1259  friend class ASTContext; // ASTContext creates these
1260public:
1261  bool isSugared() const { return false; }
1262  QualType desugar() const { return QualType(this, 0); }
1263
1264  static bool classof(const Type *T) {
1265    return T->getTypeClass() == RValueReference;
1266  }
1267  static bool classof(const RValueReferenceType *) { return true; }
1268};
1269
1270/// MemberPointerType - C++ 8.3.3 - Pointers to members
1271///
1272class MemberPointerType : public Type, public llvm::FoldingSetNode {
1273  QualType PointeeType;
1274  /// The class of which the pointee is a member. Must ultimately be a
1275  /// RecordType, but could be a typedef or a template parameter too.
1276  const Type *Class;
1277
1278  MemberPointerType(QualType Pointee, const Type *Cls, QualType CanonicalPtr) :
1279    Type(MemberPointer, CanonicalPtr,
1280         Cls->isDependentType() || Pointee->isDependentType()),
1281    PointeeType(Pointee), Class(Cls) {
1282  }
1283  friend class ASTContext; // ASTContext creates these.
1284public:
1285
1286  QualType getPointeeType() const { return PointeeType; }
1287
1288  const Type *getClass() const { return Class; }
1289
1290  bool isSugared() const { return false; }
1291  QualType desugar() const { return QualType(this, 0); }
1292
1293  void Profile(llvm::FoldingSetNodeID &ID) {
1294    Profile(ID, getPointeeType(), getClass());
1295  }
1296  static void Profile(llvm::FoldingSetNodeID &ID, QualType Pointee,
1297                      const Type *Class) {
1298    ID.AddPointer(Pointee.getAsOpaquePtr());
1299    ID.AddPointer(Class);
1300  }
1301
1302  virtual Linkage getLinkage() const;
1303
1304  static bool classof(const Type *T) {
1305    return T->getTypeClass() == MemberPointer;
1306  }
1307  static bool classof(const MemberPointerType *) { return true; }
1308};
1309
1310/// ArrayType - C99 6.7.5.2 - Array Declarators.
1311///
1312class ArrayType : public Type, public llvm::FoldingSetNode {
1313public:
1314  /// ArraySizeModifier - Capture whether this is a normal array (e.g. int X[4])
1315  /// an array with a static size (e.g. int X[static 4]), or an array
1316  /// with a star size (e.g. int X[*]).
1317  /// 'static' is only allowed on function parameters.
1318  enum ArraySizeModifier {
1319    Normal, Static, Star
1320  };
1321private:
1322  /// ElementType - The element type of the array.
1323  QualType ElementType;
1324
1325  // NOTE: VC++ treats enums as signed, avoid using the ArraySizeModifier enum
1326  /// NOTE: These fields are packed into the bitfields space in the Type class.
1327  unsigned SizeModifier : 2;
1328
1329  /// IndexTypeQuals - Capture qualifiers in declarations like:
1330  /// 'int X[static restrict 4]'. For function parameters only.
1331  unsigned IndexTypeQuals : 3;
1332
1333protected:
1334  // C++ [temp.dep.type]p1:
1335  //   A type is dependent if it is...
1336  //     - an array type constructed from any dependent type or whose
1337  //       size is specified by a constant expression that is
1338  //       value-dependent,
1339  ArrayType(TypeClass tc, QualType et, QualType can,
1340            ArraySizeModifier sm, unsigned tq)
1341    : Type(tc, can, et->isDependentType() || tc == DependentSizedArray),
1342      ElementType(et), SizeModifier(sm), IndexTypeQuals(tq) {}
1343
1344  friend class ASTContext;  // ASTContext creates these.
1345public:
1346  QualType getElementType() const { return ElementType; }
1347  ArraySizeModifier getSizeModifier() const {
1348    return ArraySizeModifier(SizeModifier);
1349  }
1350  Qualifiers getIndexTypeQualifiers() const {
1351    return Qualifiers::fromCVRMask(IndexTypeQuals);
1352  }
1353  unsigned getIndexTypeCVRQualifiers() const { return IndexTypeQuals; }
1354
1355  virtual Linkage getLinkage() const;
1356
1357  static bool classof(const Type *T) {
1358    return T->getTypeClass() == ConstantArray ||
1359           T->getTypeClass() == VariableArray ||
1360           T->getTypeClass() == IncompleteArray ||
1361           T->getTypeClass() == DependentSizedArray;
1362  }
1363  static bool classof(const ArrayType *) { return true; }
1364};
1365
1366/// ConstantArrayType - This class represents the canonical version of
1367/// C arrays with a specified constant size.  For example, the canonical
1368/// type for 'int A[4 + 4*100]' is a ConstantArrayType where the element
1369/// type is 'int' and the size is 404.
1370class ConstantArrayType : public ArrayType {
1371  llvm::APInt Size; // Allows us to unique the type.
1372
1373  ConstantArrayType(QualType et, QualType can, const llvm::APInt &size,
1374                    ArraySizeModifier sm, unsigned tq)
1375    : ArrayType(ConstantArray, et, can, sm, tq),
1376      Size(size) {}
1377protected:
1378  ConstantArrayType(TypeClass tc, QualType et, QualType can,
1379                    const llvm::APInt &size, ArraySizeModifier sm, unsigned tq)
1380    : ArrayType(tc, et, can, sm, tq), Size(size) {}
1381  friend class ASTContext;  // ASTContext creates these.
1382public:
1383  const llvm::APInt &getSize() const { return Size; }
1384  bool isSugared() const { return false; }
1385  QualType desugar() const { return QualType(this, 0); }
1386
1387  void Profile(llvm::FoldingSetNodeID &ID) {
1388    Profile(ID, getElementType(), getSize(),
1389            getSizeModifier(), getIndexTypeCVRQualifiers());
1390  }
1391  static void Profile(llvm::FoldingSetNodeID &ID, QualType ET,
1392                      const llvm::APInt &ArraySize, ArraySizeModifier SizeMod,
1393                      unsigned TypeQuals) {
1394    ID.AddPointer(ET.getAsOpaquePtr());
1395    ID.AddInteger(ArraySize.getZExtValue());
1396    ID.AddInteger(SizeMod);
1397    ID.AddInteger(TypeQuals);
1398  }
1399  static bool classof(const Type *T) {
1400    return T->getTypeClass() == ConstantArray;
1401  }
1402  static bool classof(const ConstantArrayType *) { return true; }
1403};
1404
1405/// IncompleteArrayType - This class represents C arrays with an unspecified
1406/// size.  For example 'int A[]' has an IncompleteArrayType where the element
1407/// type is 'int' and the size is unspecified.
1408class IncompleteArrayType : public ArrayType {
1409
1410  IncompleteArrayType(QualType et, QualType can,
1411                      ArraySizeModifier sm, unsigned tq)
1412    : ArrayType(IncompleteArray, et, can, sm, tq) {}
1413  friend class ASTContext;  // ASTContext creates these.
1414public:
1415  bool isSugared() const { return false; }
1416  QualType desugar() const { return QualType(this, 0); }
1417
1418  static bool classof(const Type *T) {
1419    return T->getTypeClass() == IncompleteArray;
1420  }
1421  static bool classof(const IncompleteArrayType *) { return true; }
1422
1423  friend class StmtIteratorBase;
1424
1425  void Profile(llvm::FoldingSetNodeID &ID) {
1426    Profile(ID, getElementType(), getSizeModifier(),
1427            getIndexTypeCVRQualifiers());
1428  }
1429
1430  static void Profile(llvm::FoldingSetNodeID &ID, QualType ET,
1431                      ArraySizeModifier SizeMod, unsigned TypeQuals) {
1432    ID.AddPointer(ET.getAsOpaquePtr());
1433    ID.AddInteger(SizeMod);
1434    ID.AddInteger(TypeQuals);
1435  }
1436};
1437
1438/// VariableArrayType - This class represents C arrays with a specified size
1439/// which is not an integer-constant-expression.  For example, 'int s[x+foo()]'.
1440/// Since the size expression is an arbitrary expression, we store it as such.
1441///
1442/// Note: VariableArrayType's aren't uniqued (since the expressions aren't) and
1443/// should not be: two lexically equivalent variable array types could mean
1444/// different things, for example, these variables do not have the same type
1445/// dynamically:
1446///
1447/// void foo(int x) {
1448///   int Y[x];
1449///   ++x;
1450///   int Z[x];
1451/// }
1452///
1453class VariableArrayType : public ArrayType {
1454  /// SizeExpr - An assignment expression. VLA's are only permitted within
1455  /// a function block.
1456  Stmt *SizeExpr;
1457  /// Brackets - The left and right array brackets.
1458  SourceRange Brackets;
1459
1460  VariableArrayType(QualType et, QualType can, Expr *e,
1461                    ArraySizeModifier sm, unsigned tq,
1462                    SourceRange brackets)
1463    : ArrayType(VariableArray, et, can, sm, tq),
1464      SizeExpr((Stmt*) e), Brackets(brackets) {}
1465  friend class ASTContext;  // ASTContext creates these.
1466  virtual void Destroy(ASTContext& C);
1467
1468public:
1469  Expr *getSizeExpr() const {
1470    // We use C-style casts instead of cast<> here because we do not wish
1471    // to have a dependency of Type.h on Stmt.h/Expr.h.
1472    return (Expr*) SizeExpr;
1473  }
1474  SourceRange getBracketsRange() const { return Brackets; }
1475  SourceLocation getLBracketLoc() const { return Brackets.getBegin(); }
1476  SourceLocation getRBracketLoc() const { return Brackets.getEnd(); }
1477
1478  bool isSugared() const { return false; }
1479  QualType desugar() const { return QualType(this, 0); }
1480
1481  static bool classof(const Type *T) {
1482    return T->getTypeClass() == VariableArray;
1483  }
1484  static bool classof(const VariableArrayType *) { return true; }
1485
1486  friend class StmtIteratorBase;
1487
1488  void Profile(llvm::FoldingSetNodeID &ID) {
1489    assert(0 && "Cannnot unique VariableArrayTypes.");
1490  }
1491};
1492
1493/// DependentSizedArrayType - This type represents an array type in
1494/// C++ whose size is a value-dependent expression. For example:
1495///
1496/// \code
1497/// template<typename T, int Size>
1498/// class array {
1499///   T data[Size];
1500/// };
1501/// \endcode
1502///
1503/// For these types, we won't actually know what the array bound is
1504/// until template instantiation occurs, at which point this will
1505/// become either a ConstantArrayType or a VariableArrayType.
1506class DependentSizedArrayType : public ArrayType {
1507  ASTContext &Context;
1508
1509  /// \brief An assignment expression that will instantiate to the
1510  /// size of the array.
1511  ///
1512  /// The expression itself might be NULL, in which case the array
1513  /// type will have its size deduced from an initializer.
1514  Stmt *SizeExpr;
1515
1516  /// Brackets - The left and right array brackets.
1517  SourceRange Brackets;
1518
1519  DependentSizedArrayType(ASTContext &Context, QualType et, QualType can,
1520                          Expr *e, ArraySizeModifier sm, unsigned tq,
1521                          SourceRange brackets)
1522    : ArrayType(DependentSizedArray, et, can, sm, tq),
1523      Context(Context), SizeExpr((Stmt*) e), Brackets(brackets) {}
1524  friend class ASTContext;  // ASTContext creates these.
1525  virtual void Destroy(ASTContext& C);
1526
1527public:
1528  Expr *getSizeExpr() const {
1529    // We use C-style casts instead of cast<> here because we do not wish
1530    // to have a dependency of Type.h on Stmt.h/Expr.h.
1531    return (Expr*) SizeExpr;
1532  }
1533  SourceRange getBracketsRange() const { return Brackets; }
1534  SourceLocation getLBracketLoc() const { return Brackets.getBegin(); }
1535  SourceLocation getRBracketLoc() const { return Brackets.getEnd(); }
1536
1537  bool isSugared() const { return false; }
1538  QualType desugar() const { return QualType(this, 0); }
1539
1540  static bool classof(const Type *T) {
1541    return T->getTypeClass() == DependentSizedArray;
1542  }
1543  static bool classof(const DependentSizedArrayType *) { return true; }
1544
1545  friend class StmtIteratorBase;
1546
1547
1548  void Profile(llvm::FoldingSetNodeID &ID) {
1549    Profile(ID, Context, getElementType(),
1550            getSizeModifier(), getIndexTypeCVRQualifiers(), getSizeExpr());
1551  }
1552
1553  static void Profile(llvm::FoldingSetNodeID &ID, ASTContext &Context,
1554                      QualType ET, ArraySizeModifier SizeMod,
1555                      unsigned TypeQuals, Expr *E);
1556};
1557
1558/// DependentSizedExtVectorType - This type represent an extended vector type
1559/// where either the type or size is dependent. For example:
1560/// @code
1561/// template<typename T, int Size>
1562/// class vector {
1563///   typedef T __attribute__((ext_vector_type(Size))) type;
1564/// }
1565/// @endcode
1566class DependentSizedExtVectorType : public Type, public llvm::FoldingSetNode {
1567  ASTContext &Context;
1568  Expr *SizeExpr;
1569  /// ElementType - The element type of the array.
1570  QualType ElementType;
1571  SourceLocation loc;
1572
1573  DependentSizedExtVectorType(ASTContext &Context, QualType ElementType,
1574                              QualType can, Expr *SizeExpr, SourceLocation loc)
1575    : Type (DependentSizedExtVector, can, true),
1576      Context(Context), SizeExpr(SizeExpr), ElementType(ElementType),
1577      loc(loc) {}
1578  friend class ASTContext;
1579  virtual void Destroy(ASTContext& C);
1580
1581public:
1582  Expr *getSizeExpr() const { return SizeExpr; }
1583  QualType getElementType() const { return ElementType; }
1584  SourceLocation getAttributeLoc() const { return loc; }
1585
1586  bool isSugared() const { return false; }
1587  QualType desugar() const { return QualType(this, 0); }
1588
1589  static bool classof(const Type *T) {
1590    return T->getTypeClass() == DependentSizedExtVector;
1591  }
1592  static bool classof(const DependentSizedExtVectorType *) { return true; }
1593
1594  void Profile(llvm::FoldingSetNodeID &ID) {
1595    Profile(ID, Context, getElementType(), getSizeExpr());
1596  }
1597
1598  static void Profile(llvm::FoldingSetNodeID &ID, ASTContext &Context,
1599                      QualType ElementType, Expr *SizeExpr);
1600};
1601
1602
1603/// VectorType - GCC generic vector type. This type is created using
1604/// __attribute__((vector_size(n)), where "n" specifies the vector size in
1605/// bytes; or from an Altivec __vector or vector declaration.
1606/// Since the constructor takes the number of vector elements, the
1607/// client is responsible for converting the size into the number of elements.
1608class VectorType : public Type, public llvm::FoldingSetNode {
1609protected:
1610  /// ElementType - The element type of the vector.
1611  QualType ElementType;
1612
1613  /// NumElements - The number of elements in the vector.
1614  unsigned NumElements;
1615
1616  /// AltiVec - True if this is for an Altivec vector.
1617  bool AltiVec;
1618
1619  /// Pixel - True if this is for an Altivec vector pixel.
1620  bool Pixel;
1621
1622  VectorType(QualType vecType, unsigned nElements, QualType canonType,
1623      bool isAltiVec, bool isPixel) :
1624    Type(Vector, canonType, vecType->isDependentType()),
1625    ElementType(vecType), NumElements(nElements),
1626    AltiVec(isAltiVec), Pixel(isPixel) {}
1627  VectorType(TypeClass tc, QualType vecType, unsigned nElements,
1628             QualType canonType, bool isAltiVec, bool isPixel)
1629    : Type(tc, canonType, vecType->isDependentType()), ElementType(vecType),
1630      NumElements(nElements), AltiVec(isAltiVec), Pixel(isPixel) {}
1631  friend class ASTContext;  // ASTContext creates these.
1632public:
1633
1634  QualType getElementType() const { return ElementType; }
1635  unsigned getNumElements() const { return NumElements; }
1636
1637  bool isSugared() const { return false; }
1638  QualType desugar() const { return QualType(this, 0); }
1639
1640  bool isAltiVec() const { return AltiVec; }
1641
1642  bool isPixel() const { return Pixel; }
1643
1644  void Profile(llvm::FoldingSetNodeID &ID) {
1645    Profile(ID, getElementType(), getNumElements(), getTypeClass(),
1646      AltiVec, Pixel);
1647  }
1648  static void Profile(llvm::FoldingSetNodeID &ID, QualType ElementType,
1649                      unsigned NumElements, TypeClass TypeClass,
1650                      bool isAltiVec, bool isPixel) {
1651    ID.AddPointer(ElementType.getAsOpaquePtr());
1652    ID.AddInteger(NumElements);
1653    ID.AddInteger(TypeClass);
1654    ID.AddBoolean(isAltiVec);
1655    ID.AddBoolean(isPixel);
1656  }
1657
1658  virtual Linkage getLinkage() const;
1659
1660  static bool classof(const Type *T) {
1661    return T->getTypeClass() == Vector || T->getTypeClass() == ExtVector;
1662  }
1663  static bool classof(const VectorType *) { return true; }
1664};
1665
1666/// ExtVectorType - Extended vector type. This type is created using
1667/// __attribute__((ext_vector_type(n)), where "n" is the number of elements.
1668/// Unlike vector_size, ext_vector_type is only allowed on typedef's. This
1669/// class enables syntactic extensions, like Vector Components for accessing
1670/// points, colors, and textures (modeled after OpenGL Shading Language).
1671class ExtVectorType : public VectorType {
1672  ExtVectorType(QualType vecType, unsigned nElements, QualType canonType) :
1673    VectorType(ExtVector, vecType, nElements, canonType, false, false) {}
1674  friend class ASTContext;  // ASTContext creates these.
1675public:
1676  static int getPointAccessorIdx(char c) {
1677    switch (c) {
1678    default: return -1;
1679    case 'x': return 0;
1680    case 'y': return 1;
1681    case 'z': return 2;
1682    case 'w': return 3;
1683    }
1684  }
1685  static int getNumericAccessorIdx(char c) {
1686    switch (c) {
1687      default: return -1;
1688      case '0': return 0;
1689      case '1': return 1;
1690      case '2': return 2;
1691      case '3': return 3;
1692      case '4': return 4;
1693      case '5': return 5;
1694      case '6': return 6;
1695      case '7': return 7;
1696      case '8': return 8;
1697      case '9': return 9;
1698      case 'A':
1699      case 'a': return 10;
1700      case 'B':
1701      case 'b': return 11;
1702      case 'C':
1703      case 'c': return 12;
1704      case 'D':
1705      case 'd': return 13;
1706      case 'E':
1707      case 'e': return 14;
1708      case 'F':
1709      case 'f': return 15;
1710    }
1711  }
1712
1713  static int getAccessorIdx(char c) {
1714    if (int idx = getPointAccessorIdx(c)+1) return idx-1;
1715    return getNumericAccessorIdx(c);
1716  }
1717
1718  bool isAccessorWithinNumElements(char c) const {
1719    if (int idx = getAccessorIdx(c)+1)
1720      return unsigned(idx-1) < NumElements;
1721    return false;
1722  }
1723  bool isSugared() const { return false; }
1724  QualType desugar() const { return QualType(this, 0); }
1725
1726  static bool classof(const Type *T) {
1727    return T->getTypeClass() == ExtVector;
1728  }
1729  static bool classof(const ExtVectorType *) { return true; }
1730};
1731
1732/// FunctionType - C99 6.7.5.3 - Function Declarators.  This is the common base
1733/// class of FunctionNoProtoType and FunctionProtoType.
1734///
1735class FunctionType : public Type {
1736  virtual void ANCHOR(); // Key function for FunctionType.
1737
1738  /// SubClassData - This field is owned by the subclass, put here to pack
1739  /// tightly with the ivars in Type.
1740  bool SubClassData : 1;
1741
1742  /// TypeQuals - Used only by FunctionProtoType, put here to pack with the
1743  /// other bitfields.
1744  /// The qualifiers are part of FunctionProtoType because...
1745  ///
1746  /// C++ 8.3.5p4: The return type, the parameter type list and the
1747  /// cv-qualifier-seq, [...], are part of the function type.
1748  ///
1749  unsigned TypeQuals : 3;
1750
1751  /// NoReturn - Indicates if the function type is attribute noreturn.
1752  unsigned NoReturn : 1;
1753
1754  /// RegParm - How many arguments to pass inreg.
1755  unsigned RegParm : 3;
1756
1757  /// CallConv - The calling convention used by the function.
1758  unsigned CallConv : 2;
1759
1760  // The type returned by the function.
1761  QualType ResultType;
1762
1763 public:
1764  // This class is used for passing arround the information needed to
1765  // construct a call. It is not actually used for storage, just for
1766  // factoring together common arguments.
1767  // If you add a field (say Foo), other than the obvious places (both, constructors,
1768  // compile failures), what you need to update is
1769  // * Operetor==
1770  // * getFoo
1771  // * withFoo
1772  // * functionType. Add Foo, getFoo.
1773  // * ASTContext::getFooType
1774  // * ASTContext::mergeFunctionTypes
1775  // * FunctionNoProtoType::Profile
1776  // * FunctionProtoType::Profile
1777  // * TypePrinter::PrintFunctionProto
1778  // * PCH read and write
1779  // * Codegen
1780
1781  class ExtInfo {
1782   public:
1783    // Constructor with no defaults. Use this when you know that you
1784    // have all the elements (when reading a PCH file for example).
1785    ExtInfo(bool noReturn, unsigned regParm, CallingConv cc) :
1786        NoReturn(noReturn), RegParm(regParm), CC(cc) {}
1787
1788    // Constructor with all defaults. Use when for example creating a
1789    // function know to use defaults.
1790    ExtInfo() : NoReturn(false), RegParm(0), CC(CC_Default) {}
1791
1792    bool getNoReturn() const { return NoReturn; }
1793    unsigned getRegParm() const { return RegParm; }
1794    CallingConv getCC() const { return CC; }
1795
1796    bool operator==(const ExtInfo &Other) const {
1797      return getNoReturn() == Other.getNoReturn() &&
1798          getRegParm() == Other.getRegParm() &&
1799          getCC() == Other.getCC();
1800    }
1801    bool operator!=(const ExtInfo &Other) const {
1802      return !(*this == Other);
1803    }
1804
1805    // Note that we don't have setters. That is by design, use
1806    // the following with methods instead of mutating these objects.
1807
1808    ExtInfo withNoReturn(bool noReturn) const {
1809      return ExtInfo(noReturn, getRegParm(), getCC());
1810    }
1811
1812    ExtInfo withRegParm(unsigned RegParm) const {
1813      return ExtInfo(getNoReturn(), RegParm, getCC());
1814    }
1815
1816    ExtInfo withCallingConv(CallingConv cc) const {
1817      return ExtInfo(getNoReturn(), getRegParm(), cc);
1818    }
1819
1820   private:
1821    // True if we have __attribute__((noreturn))
1822    bool NoReturn;
1823    // The value passed to __attribute__((regparm(x)))
1824    unsigned RegParm;
1825    // The calling convention as specified via
1826    // __attribute__((cdecl|stdcall||fastcall))
1827    CallingConv CC;
1828  };
1829
1830protected:
1831  FunctionType(TypeClass tc, QualType res, bool SubclassInfo,
1832               unsigned typeQuals, QualType Canonical, bool Dependent,
1833               const ExtInfo &Info)
1834    : Type(tc, Canonical, Dependent),
1835      SubClassData(SubclassInfo), TypeQuals(typeQuals),
1836      NoReturn(Info.getNoReturn()),
1837      RegParm(Info.getRegParm()), CallConv(Info.getCC()), ResultType(res) {}
1838  bool getSubClassData() const { return SubClassData; }
1839  unsigned getTypeQuals() const { return TypeQuals; }
1840public:
1841
1842  QualType getResultType() const { return ResultType; }
1843  unsigned getRegParmType() const { return RegParm; }
1844  bool getNoReturnAttr() const { return NoReturn; }
1845  CallingConv getCallConv() const { return (CallingConv)CallConv; }
1846  ExtInfo getExtInfo() const {
1847    return ExtInfo(NoReturn, RegParm, (CallingConv)CallConv);
1848  }
1849
1850  static llvm::StringRef getNameForCallConv(CallingConv CC);
1851
1852  static bool classof(const Type *T) {
1853    return T->getTypeClass() == FunctionNoProto ||
1854           T->getTypeClass() == FunctionProto;
1855  }
1856  static bool classof(const FunctionType *) { return true; }
1857};
1858
1859/// FunctionNoProtoType - Represents a K&R-style 'int foo()' function, which has
1860/// no information available about its arguments.
1861class FunctionNoProtoType : public FunctionType, public llvm::FoldingSetNode {
1862  FunctionNoProtoType(QualType Result, QualType Canonical,
1863                      const ExtInfo &Info)
1864    : FunctionType(FunctionNoProto, Result, false, 0, Canonical,
1865                   /*Dependent=*/false, Info) {}
1866  friend class ASTContext;  // ASTContext creates these.
1867public:
1868  // No additional state past what FunctionType provides.
1869
1870  bool isSugared() const { return false; }
1871  QualType desugar() const { return QualType(this, 0); }
1872
1873  void Profile(llvm::FoldingSetNodeID &ID) {
1874    Profile(ID, getResultType(), getExtInfo());
1875  }
1876  static void Profile(llvm::FoldingSetNodeID &ID, QualType ResultType,
1877                      const ExtInfo &Info) {
1878    ID.AddInteger(Info.getCC());
1879    ID.AddInteger(Info.getRegParm());
1880    ID.AddInteger(Info.getNoReturn());
1881    ID.AddPointer(ResultType.getAsOpaquePtr());
1882  }
1883
1884  virtual Linkage getLinkage() const;
1885
1886  static bool classof(const Type *T) {
1887    return T->getTypeClass() == FunctionNoProto;
1888  }
1889  static bool classof(const FunctionNoProtoType *) { return true; }
1890};
1891
1892/// FunctionProtoType - Represents a prototype with argument type info, e.g.
1893/// 'int foo(int)' or 'int foo(void)'.  'void' is represented as having no
1894/// arguments, not as having a single void argument. Such a type can have an
1895/// exception specification, but this specification is not part of the canonical
1896/// type.
1897class FunctionProtoType : public FunctionType, public llvm::FoldingSetNode {
1898  /// hasAnyDependentType - Determine whether there are any dependent
1899  /// types within the arguments passed in.
1900  static bool hasAnyDependentType(const QualType *ArgArray, unsigned numArgs) {
1901    for (unsigned Idx = 0; Idx < numArgs; ++Idx)
1902      if (ArgArray[Idx]->isDependentType())
1903    return true;
1904
1905    return false;
1906  }
1907
1908  FunctionProtoType(QualType Result, const QualType *ArgArray, unsigned numArgs,
1909                    bool isVariadic, unsigned typeQuals, bool hasExs,
1910                    bool hasAnyExs, const QualType *ExArray,
1911                    unsigned numExs, QualType Canonical,
1912                    const ExtInfo &Info)
1913    : FunctionType(FunctionProto, Result, isVariadic, typeQuals, Canonical,
1914                   (Result->isDependentType() ||
1915                    hasAnyDependentType(ArgArray, numArgs)),
1916                   Info),
1917      NumArgs(numArgs), NumExceptions(numExs), HasExceptionSpec(hasExs),
1918      AnyExceptionSpec(hasAnyExs) {
1919    // Fill in the trailing argument array.
1920    QualType *ArgInfo = reinterpret_cast<QualType*>(this+1);
1921    for (unsigned i = 0; i != numArgs; ++i)
1922      ArgInfo[i] = ArgArray[i];
1923    // Fill in the exception array.
1924    QualType *Ex = ArgInfo + numArgs;
1925    for (unsigned i = 0; i != numExs; ++i)
1926      Ex[i] = ExArray[i];
1927  }
1928
1929  /// NumArgs - The number of arguments this function has, not counting '...'.
1930  unsigned NumArgs : 20;
1931
1932  /// NumExceptions - The number of types in the exception spec, if any.
1933  unsigned NumExceptions : 10;
1934
1935  /// HasExceptionSpec - Whether this function has an exception spec at all.
1936  bool HasExceptionSpec : 1;
1937
1938  /// AnyExceptionSpec - Whether this function has a throw(...) spec.
1939  bool AnyExceptionSpec : 1;
1940
1941  /// ArgInfo - There is an variable size array after the class in memory that
1942  /// holds the argument types.
1943
1944  /// Exceptions - There is another variable size array after ArgInfo that
1945  /// holds the exception types.
1946
1947  friend class ASTContext;  // ASTContext creates these.
1948
1949public:
1950  unsigned getNumArgs() const { return NumArgs; }
1951  QualType getArgType(unsigned i) const {
1952    assert(i < NumArgs && "Invalid argument number!");
1953    return arg_type_begin()[i];
1954  }
1955
1956  bool hasExceptionSpec() const { return HasExceptionSpec; }
1957  bool hasAnyExceptionSpec() const { return AnyExceptionSpec; }
1958  unsigned getNumExceptions() const { return NumExceptions; }
1959  QualType getExceptionType(unsigned i) const {
1960    assert(i < NumExceptions && "Invalid exception number!");
1961    return exception_begin()[i];
1962  }
1963  bool hasEmptyExceptionSpec() const {
1964    return hasExceptionSpec() && !hasAnyExceptionSpec() &&
1965      getNumExceptions() == 0;
1966  }
1967
1968  bool isVariadic() const { return getSubClassData(); }
1969  unsigned getTypeQuals() const { return FunctionType::getTypeQuals(); }
1970
1971  typedef const QualType *arg_type_iterator;
1972  arg_type_iterator arg_type_begin() const {
1973    return reinterpret_cast<const QualType *>(this+1);
1974  }
1975  arg_type_iterator arg_type_end() const { return arg_type_begin()+NumArgs; }
1976
1977  typedef const QualType *exception_iterator;
1978  exception_iterator exception_begin() const {
1979    // exceptions begin where arguments end
1980    return arg_type_end();
1981  }
1982  exception_iterator exception_end() const {
1983    return exception_begin() + NumExceptions;
1984  }
1985
1986  bool isSugared() const { return false; }
1987  QualType desugar() const { return QualType(this, 0); }
1988
1989  virtual Linkage getLinkage() const;
1990
1991  static bool classof(const Type *T) {
1992    return T->getTypeClass() == FunctionProto;
1993  }
1994  static bool classof(const FunctionProtoType *) { return true; }
1995
1996  void Profile(llvm::FoldingSetNodeID &ID);
1997  static void Profile(llvm::FoldingSetNodeID &ID, QualType Result,
1998                      arg_type_iterator ArgTys, unsigned NumArgs,
1999                      bool isVariadic, unsigned TypeQuals,
2000                      bool hasExceptionSpec, bool anyExceptionSpec,
2001                      unsigned NumExceptions, exception_iterator Exs,
2002                      const ExtInfo &ExtInfo);
2003};
2004
2005
2006/// \brief Represents the dependent type named by a dependently-scoped
2007/// typename using declaration, e.g.
2008///   using typename Base<T>::foo;
2009/// Template instantiation turns these into the underlying type.
2010class UnresolvedUsingType : public Type {
2011  UnresolvedUsingTypenameDecl *Decl;
2012
2013  UnresolvedUsingType(const UnresolvedUsingTypenameDecl *D)
2014    : Type(UnresolvedUsing, QualType(), true),
2015      Decl(const_cast<UnresolvedUsingTypenameDecl*>(D)) {}
2016  friend class ASTContext; // ASTContext creates these.
2017public:
2018
2019  UnresolvedUsingTypenameDecl *getDecl() const { return Decl; }
2020
2021  bool isSugared() const { return false; }
2022  QualType desugar() const { return QualType(this, 0); }
2023
2024  static bool classof(const Type *T) {
2025    return T->getTypeClass() == UnresolvedUsing;
2026  }
2027  static bool classof(const UnresolvedUsingType *) { return true; }
2028
2029  void Profile(llvm::FoldingSetNodeID &ID) {
2030    return Profile(ID, Decl);
2031  }
2032  static void Profile(llvm::FoldingSetNodeID &ID,
2033                      UnresolvedUsingTypenameDecl *D) {
2034    ID.AddPointer(D);
2035  }
2036};
2037
2038
2039class TypedefType : public Type {
2040  TypedefDecl *Decl;
2041protected:
2042  TypedefType(TypeClass tc, const TypedefDecl *D, QualType can)
2043    : Type(tc, can, can->isDependentType()),
2044      Decl(const_cast<TypedefDecl*>(D)) {
2045    assert(!isa<TypedefType>(can) && "Invalid canonical type");
2046  }
2047  friend class ASTContext;  // ASTContext creates these.
2048public:
2049
2050  TypedefDecl *getDecl() const { return Decl; }
2051
2052  /// LookThroughTypedefs - Return the ultimate type this typedef corresponds to
2053  /// potentially looking through *all* consecutive typedefs.  This returns the
2054  /// sum of the type qualifiers, so if you have:
2055  ///   typedef const int A;
2056  ///   typedef volatile A B;
2057  /// looking through the typedefs for B will give you "const volatile A".
2058  QualType LookThroughTypedefs() const;
2059
2060  bool isSugared() const { return true; }
2061  QualType desugar() const;
2062
2063  static bool classof(const Type *T) { return T->getTypeClass() == Typedef; }
2064  static bool classof(const TypedefType *) { return true; }
2065};
2066
2067/// TypeOfExprType (GCC extension).
2068class TypeOfExprType : public Type {
2069  Expr *TOExpr;
2070
2071protected:
2072  TypeOfExprType(Expr *E, QualType can = QualType());
2073  friend class ASTContext;  // ASTContext creates these.
2074public:
2075  Expr *getUnderlyingExpr() const { return TOExpr; }
2076
2077  /// \brief Remove a single level of sugar.
2078  QualType desugar() const;
2079
2080  /// \brief Returns whether this type directly provides sugar.
2081  bool isSugared() const { return true; }
2082
2083  static bool classof(const Type *T) { return T->getTypeClass() == TypeOfExpr; }
2084  static bool classof(const TypeOfExprType *) { return true; }
2085};
2086
2087/// \brief Internal representation of canonical, dependent
2088/// typeof(expr) types.
2089///
2090/// This class is used internally by the ASTContext to manage
2091/// canonical, dependent types, only. Clients will only see instances
2092/// of this class via TypeOfExprType nodes.
2093class DependentTypeOfExprType
2094  : public TypeOfExprType, public llvm::FoldingSetNode {
2095  ASTContext &Context;
2096
2097public:
2098  DependentTypeOfExprType(ASTContext &Context, Expr *E)
2099    : TypeOfExprType(E), Context(Context) { }
2100
2101  bool isSugared() const { return false; }
2102  QualType desugar() const { return QualType(this, 0); }
2103
2104  void Profile(llvm::FoldingSetNodeID &ID) {
2105    Profile(ID, Context, getUnderlyingExpr());
2106  }
2107
2108  static void Profile(llvm::FoldingSetNodeID &ID, ASTContext &Context,
2109                      Expr *E);
2110};
2111
2112/// TypeOfType (GCC extension).
2113class TypeOfType : public Type {
2114  QualType TOType;
2115  TypeOfType(QualType T, QualType can)
2116    : Type(TypeOf, can, T->isDependentType()), TOType(T) {
2117    assert(!isa<TypedefType>(can) && "Invalid canonical type");
2118  }
2119  friend class ASTContext;  // ASTContext creates these.
2120public:
2121  QualType getUnderlyingType() const { return TOType; }
2122
2123  /// \brief Remove a single level of sugar.
2124  QualType desugar() const { return getUnderlyingType(); }
2125
2126  /// \brief Returns whether this type directly provides sugar.
2127  bool isSugared() const { return true; }
2128
2129  static bool classof(const Type *T) { return T->getTypeClass() == TypeOf; }
2130  static bool classof(const TypeOfType *) { return true; }
2131};
2132
2133/// DecltypeType (C++0x)
2134class DecltypeType : public Type {
2135  Expr *E;
2136
2137  // FIXME: We could get rid of UnderlyingType if we wanted to: We would have to
2138  // Move getDesugaredType to ASTContext so that it can call getDecltypeForExpr
2139  // from it.
2140  QualType UnderlyingType;
2141
2142protected:
2143  DecltypeType(Expr *E, QualType underlyingType, QualType can = QualType());
2144  friend class ASTContext;  // ASTContext creates these.
2145public:
2146  Expr *getUnderlyingExpr() const { return E; }
2147  QualType getUnderlyingType() const { return UnderlyingType; }
2148
2149  /// \brief Remove a single level of sugar.
2150  QualType desugar() const { return getUnderlyingType(); }
2151
2152  /// \brief Returns whether this type directly provides sugar.
2153  bool isSugared() const { return !isDependentType(); }
2154
2155  static bool classof(const Type *T) { return T->getTypeClass() == Decltype; }
2156  static bool classof(const DecltypeType *) { return true; }
2157};
2158
2159/// \brief Internal representation of canonical, dependent
2160/// decltype(expr) types.
2161///
2162/// This class is used internally by the ASTContext to manage
2163/// canonical, dependent types, only. Clients will only see instances
2164/// of this class via DecltypeType nodes.
2165class DependentDecltypeType : public DecltypeType, public llvm::FoldingSetNode {
2166  ASTContext &Context;
2167
2168public:
2169  DependentDecltypeType(ASTContext &Context, Expr *E);
2170
2171  bool isSugared() const { return false; }
2172  QualType desugar() const { return QualType(this, 0); }
2173
2174  void Profile(llvm::FoldingSetNodeID &ID) {
2175    Profile(ID, Context, getUnderlyingExpr());
2176  }
2177
2178  static void Profile(llvm::FoldingSetNodeID &ID, ASTContext &Context,
2179                      Expr *E);
2180};
2181
2182class TagType : public Type {
2183  /// Stores the TagDecl associated with this type. The decl will
2184  /// point to the TagDecl that actually defines the entity (or is a
2185  /// definition in progress), if there is such a definition. The
2186  /// single-bit value will be non-zero when this tag is in the
2187  /// process of being defined.
2188  mutable llvm::PointerIntPair<TagDecl *, 1> decl;
2189  friend class ASTContext;
2190  friend class TagDecl;
2191
2192protected:
2193  TagType(TypeClass TC, const TagDecl *D, QualType can);
2194
2195public:
2196  TagDecl *getDecl() const { return decl.getPointer(); }
2197
2198  /// @brief Determines whether this type is in the process of being
2199  /// defined.
2200  bool isBeingDefined() const { return decl.getInt(); }
2201  void setBeingDefined(bool Def) const { decl.setInt(Def? 1 : 0); }
2202
2203  virtual Linkage getLinkage() const;
2204
2205  static bool classof(const Type *T) {
2206    return T->getTypeClass() >= TagFirst && T->getTypeClass() <= TagLast;
2207  }
2208  static bool classof(const TagType *) { return true; }
2209  static bool classof(const RecordType *) { return true; }
2210  static bool classof(const EnumType *) { return true; }
2211};
2212
2213/// RecordType - This is a helper class that allows the use of isa/cast/dyncast
2214/// to detect TagType objects of structs/unions/classes.
2215class RecordType : public TagType {
2216protected:
2217  explicit RecordType(const RecordDecl *D)
2218    : TagType(Record, reinterpret_cast<const TagDecl*>(D), QualType()) { }
2219  explicit RecordType(TypeClass TC, RecordDecl *D)
2220    : TagType(TC, reinterpret_cast<const TagDecl*>(D), QualType()) { }
2221  friend class ASTContext;   // ASTContext creates these.
2222public:
2223
2224  RecordDecl *getDecl() const {
2225    return reinterpret_cast<RecordDecl*>(TagType::getDecl());
2226  }
2227
2228  // FIXME: This predicate is a helper to QualType/Type. It needs to
2229  // recursively check all fields for const-ness. If any field is declared
2230  // const, it needs to return false.
2231  bool hasConstFields() const { return false; }
2232
2233  // FIXME: RecordType needs to check when it is created that all fields are in
2234  // the same address space, and return that.
2235  unsigned getAddressSpace() const { return 0; }
2236
2237  bool isSugared() const { return false; }
2238  QualType desugar() const { return QualType(this, 0); }
2239
2240  static bool classof(const TagType *T);
2241  static bool classof(const Type *T) {
2242    return isa<TagType>(T) && classof(cast<TagType>(T));
2243  }
2244  static bool classof(const RecordType *) { return true; }
2245};
2246
2247/// EnumType - This is a helper class that allows the use of isa/cast/dyncast
2248/// to detect TagType objects of enums.
2249class EnumType : public TagType {
2250  explicit EnumType(const EnumDecl *D)
2251    : TagType(Enum, reinterpret_cast<const TagDecl*>(D), QualType()) { }
2252  friend class ASTContext;   // ASTContext creates these.
2253public:
2254
2255  EnumDecl *getDecl() const {
2256    return reinterpret_cast<EnumDecl*>(TagType::getDecl());
2257  }
2258
2259  bool isSugared() const { return false; }
2260  QualType desugar() const { return QualType(this, 0); }
2261
2262  static bool classof(const TagType *T);
2263  static bool classof(const Type *T) {
2264    return isa<TagType>(T) && classof(cast<TagType>(T));
2265  }
2266  static bool classof(const EnumType *) { return true; }
2267};
2268
2269class TemplateTypeParmType : public Type, public llvm::FoldingSetNode {
2270  unsigned Depth : 15;
2271  unsigned Index : 16;
2272  unsigned ParameterPack : 1;
2273  IdentifierInfo *Name;
2274
2275  TemplateTypeParmType(unsigned D, unsigned I, bool PP, IdentifierInfo *N,
2276                       QualType Canon)
2277    : Type(TemplateTypeParm, Canon, /*Dependent=*/true),
2278      Depth(D), Index(I), ParameterPack(PP), Name(N) { }
2279
2280  TemplateTypeParmType(unsigned D, unsigned I, bool PP)
2281    : Type(TemplateTypeParm, QualType(this, 0), /*Dependent=*/true),
2282      Depth(D), Index(I), ParameterPack(PP), Name(0) { }
2283
2284  friend class ASTContext;  // ASTContext creates these
2285
2286public:
2287  unsigned getDepth() const { return Depth; }
2288  unsigned getIndex() const { return Index; }
2289  bool isParameterPack() const { return ParameterPack; }
2290  IdentifierInfo *getName() const { return Name; }
2291
2292  bool isSugared() const { return false; }
2293  QualType desugar() const { return QualType(this, 0); }
2294
2295  void Profile(llvm::FoldingSetNodeID &ID) {
2296    Profile(ID, Depth, Index, ParameterPack, Name);
2297  }
2298
2299  static void Profile(llvm::FoldingSetNodeID &ID, unsigned Depth,
2300                      unsigned Index, bool ParameterPack,
2301                      IdentifierInfo *Name) {
2302    ID.AddInteger(Depth);
2303    ID.AddInteger(Index);
2304    ID.AddBoolean(ParameterPack);
2305    ID.AddPointer(Name);
2306  }
2307
2308  static bool classof(const Type *T) {
2309    return T->getTypeClass() == TemplateTypeParm;
2310  }
2311  static bool classof(const TemplateTypeParmType *T) { return true; }
2312};
2313
2314/// \brief Represents the result of substituting a type for a template
2315/// type parameter.
2316///
2317/// Within an instantiated template, all template type parameters have
2318/// been replaced with these.  They are used solely to record that a
2319/// type was originally written as a template type parameter;
2320/// therefore they are never canonical.
2321class SubstTemplateTypeParmType : public Type, public llvm::FoldingSetNode {
2322  // The original type parameter.
2323  const TemplateTypeParmType *Replaced;
2324
2325  SubstTemplateTypeParmType(const TemplateTypeParmType *Param, QualType Canon)
2326    : Type(SubstTemplateTypeParm, Canon, Canon->isDependentType()),
2327      Replaced(Param) { }
2328
2329  friend class ASTContext;
2330
2331public:
2332  IdentifierInfo *getName() const { return Replaced->getName(); }
2333
2334  /// Gets the template parameter that was substituted for.
2335  const TemplateTypeParmType *getReplacedParameter() const {
2336    return Replaced;
2337  }
2338
2339  /// Gets the type that was substituted for the template
2340  /// parameter.
2341  QualType getReplacementType() const {
2342    return getCanonicalTypeInternal();
2343  }
2344
2345  bool isSugared() const { return true; }
2346  QualType desugar() const { return getReplacementType(); }
2347
2348  void Profile(llvm::FoldingSetNodeID &ID) {
2349    Profile(ID, getReplacedParameter(), getReplacementType());
2350  }
2351  static void Profile(llvm::FoldingSetNodeID &ID,
2352                      const TemplateTypeParmType *Replaced,
2353                      QualType Replacement) {
2354    ID.AddPointer(Replaced);
2355    ID.AddPointer(Replacement.getAsOpaquePtr());
2356  }
2357
2358  static bool classof(const Type *T) {
2359    return T->getTypeClass() == SubstTemplateTypeParm;
2360  }
2361  static bool classof(const SubstTemplateTypeParmType *T) { return true; }
2362};
2363
2364/// \brief Represents the type of a template specialization as written
2365/// in the source code.
2366///
2367/// Template specialization types represent the syntactic form of a
2368/// template-id that refers to a type, e.g., @c vector<int>. Some
2369/// template specialization types are syntactic sugar, whose canonical
2370/// type will point to some other type node that represents the
2371/// instantiation or class template specialization. For example, a
2372/// class template specialization type of @c vector<int> will refer to
2373/// a tag type for the instantiation
2374/// @c std::vector<int, std::allocator<int>>.
2375///
2376/// Other template specialization types, for which the template name
2377/// is dependent, may be canonical types. These types are always
2378/// dependent.
2379class TemplateSpecializationType
2380  : public Type, public llvm::FoldingSetNode {
2381
2382  // The ASTContext is currently needed in order to profile expressions.
2383  // FIXME: avoid this.
2384  //
2385  // The bool is whether this is a current instantiation.
2386  llvm::PointerIntPair<ASTContext*, 1, bool> ContextAndCurrentInstantiation;
2387
2388    /// \brief The name of the template being specialized.
2389  TemplateName Template;
2390
2391  /// \brief - The number of template arguments named in this class
2392  /// template specialization.
2393  unsigned NumArgs;
2394
2395  TemplateSpecializationType(ASTContext &Context,
2396                             TemplateName T,
2397                             bool IsCurrentInstantiation,
2398                             const TemplateArgument *Args,
2399                             unsigned NumArgs, QualType Canon);
2400
2401  virtual void Destroy(ASTContext& C);
2402
2403  friend class ASTContext;  // ASTContext creates these
2404
2405public:
2406  /// \brief Determine whether any of the given template arguments are
2407  /// dependent.
2408  static bool anyDependentTemplateArguments(const TemplateArgument *Args,
2409                                            unsigned NumArgs);
2410
2411  static bool anyDependentTemplateArguments(const TemplateArgumentLoc *Args,
2412                                            unsigned NumArgs);
2413
2414  static bool anyDependentTemplateArguments(const TemplateArgumentListInfo &);
2415
2416  /// \brief Print a template argument list, including the '<' and '>'
2417  /// enclosing the template arguments.
2418  static std::string PrintTemplateArgumentList(const TemplateArgument *Args,
2419                                               unsigned NumArgs,
2420                                               const PrintingPolicy &Policy);
2421
2422  static std::string PrintTemplateArgumentList(const TemplateArgumentLoc *Args,
2423                                               unsigned NumArgs,
2424                                               const PrintingPolicy &Policy);
2425
2426  static std::string PrintTemplateArgumentList(const TemplateArgumentListInfo &,
2427                                               const PrintingPolicy &Policy);
2428
2429  /// True if this template specialization type matches a current
2430  /// instantiation in the context in which it is found.
2431  bool isCurrentInstantiation() const {
2432    return ContextAndCurrentInstantiation.getInt();
2433  }
2434
2435  typedef const TemplateArgument * iterator;
2436
2437  iterator begin() const { return getArgs(); }
2438  iterator end() const;
2439
2440  /// \brief Retrieve the name of the template that we are specializing.
2441  TemplateName getTemplateName() const { return Template; }
2442
2443  /// \brief Retrieve the template arguments.
2444  const TemplateArgument *getArgs() const {
2445    return reinterpret_cast<const TemplateArgument *>(this + 1);
2446  }
2447
2448  /// \brief Retrieve the number of template arguments.
2449  unsigned getNumArgs() const { return NumArgs; }
2450
2451  /// \brief Retrieve a specific template argument as a type.
2452  /// \precondition @c isArgType(Arg)
2453  const TemplateArgument &getArg(unsigned Idx) const;
2454
2455  bool isSugared() const {
2456    return !isDependentType() || isCurrentInstantiation();
2457  }
2458  QualType desugar() const { return getCanonicalTypeInternal(); }
2459
2460  void Profile(llvm::FoldingSetNodeID &ID) {
2461    Profile(ID, Template, isCurrentInstantiation(), getArgs(), NumArgs,
2462            *ContextAndCurrentInstantiation.getPointer());
2463  }
2464
2465  static void Profile(llvm::FoldingSetNodeID &ID, TemplateName T,
2466                      bool IsCurrentInstantiation,
2467                      const TemplateArgument *Args,
2468                      unsigned NumArgs,
2469                      ASTContext &Context);
2470
2471  static bool classof(const Type *T) {
2472    return T->getTypeClass() == TemplateSpecialization;
2473  }
2474  static bool classof(const TemplateSpecializationType *T) { return true; }
2475};
2476
2477/// \brief The injected class name of a C++ class template or class
2478/// template partial specialization.  Used to record that a type was
2479/// spelled with a bare identifier rather than as a template-id; the
2480/// equivalent for non-templated classes is just RecordType.
2481///
2482/// Injected class name types are always dependent.  Template
2483/// instantiation turns these into RecordTypes.
2484///
2485/// Injected class name types are always canonical.  This works
2486/// because it is impossible to compare an injected class name type
2487/// with the corresponding non-injected template type, for the same
2488/// reason that it is impossible to directly compare template
2489/// parameters from different dependent contexts: injected class name
2490/// types can only occur within the scope of a particular templated
2491/// declaration, and within that scope every template specialization
2492/// will canonicalize to the injected class name (when appropriate
2493/// according to the rules of the language).
2494class InjectedClassNameType : public Type {
2495  CXXRecordDecl *Decl;
2496
2497  /// The template specialization which this type represents.
2498  /// For example, in
2499  ///   template <class T> class A { ... };
2500  /// this is A<T>, whereas in
2501  ///   template <class X, class Y> class A<B<X,Y> > { ... };
2502  /// this is A<B<X,Y> >.
2503  ///
2504  /// It is always unqualified, always a template specialization type,
2505  /// and always dependent.
2506  QualType InjectedType;
2507
2508  friend class ASTContext; // ASTContext creates these.
2509  friend class TagDecl; // TagDecl mutilates the Decl
2510  InjectedClassNameType(CXXRecordDecl *D, QualType TST)
2511    : Type(InjectedClassName, QualType(), true),
2512      Decl(D), InjectedType(TST) {
2513    assert(isa<TemplateSpecializationType>(TST));
2514    assert(!TST.hasQualifiers());
2515    assert(TST->isDependentType());
2516  }
2517
2518public:
2519  QualType getInjectedSpecializationType() const { return InjectedType; }
2520  const TemplateSpecializationType *getInjectedTST() const {
2521    return cast<TemplateSpecializationType>(InjectedType.getTypePtr());
2522  }
2523
2524  CXXRecordDecl *getDecl() const { return Decl; }
2525
2526  bool isSugared() const { return false; }
2527  QualType desugar() const { return QualType(this, 0); }
2528
2529  static bool classof(const Type *T) {
2530    return T->getTypeClass() == InjectedClassName;
2531  }
2532  static bool classof(const InjectedClassNameType *T) { return true; }
2533};
2534
2535/// \brief The kind of a tag type.
2536enum TagTypeKind {
2537  /// \brief The "struct" keyword.
2538  TTK_Struct,
2539  /// \brief The "union" keyword.
2540  TTK_Union,
2541  /// \brief The "class" keyword.
2542  TTK_Class,
2543  /// \brief The "enum" keyword.
2544  TTK_Enum
2545};
2546
2547/// \brief The elaboration keyword that precedes a qualified type name or
2548/// introduces an elaborated-type-specifier.
2549enum ElaboratedTypeKeyword {
2550  /// \brief The "struct" keyword introduces the elaborated-type-specifier.
2551  ETK_Struct,
2552  /// \brief The "union" keyword introduces the elaborated-type-specifier.
2553  ETK_Union,
2554  /// \brief The "class" keyword introduces the elaborated-type-specifier.
2555  ETK_Class,
2556  /// \brief The "enum" keyword introduces the elaborated-type-specifier.
2557  ETK_Enum,
2558  /// \brief The "typename" keyword precedes the qualified type name, e.g.,
2559  /// \c typename T::type.
2560  ETK_Typename,
2561  /// \brief No keyword precedes the qualified type name.
2562  ETK_None
2563};
2564
2565/// A helper class for Type nodes having an ElaboratedTypeKeyword.
2566/// The keyword in stored in the free bits of the base class.
2567/// Also provides a few static helpers for converting and printing
2568/// elaborated type keyword and tag type kind enumerations.
2569class TypeWithKeyword : public Type {
2570  /// Keyword - Encodes an ElaboratedTypeKeyword enumeration constant.
2571  unsigned Keyword : 3;
2572
2573protected:
2574  TypeWithKeyword(ElaboratedTypeKeyword Keyword, TypeClass tc,
2575                  QualType Canonical, bool dependent)
2576    : Type(tc, Canonical, dependent), Keyword(Keyword) {}
2577
2578public:
2579  virtual ~TypeWithKeyword(); // pin vtable to Type.cpp
2580
2581  ElaboratedTypeKeyword getKeyword() const {
2582    return static_cast<ElaboratedTypeKeyword>(Keyword);
2583  }
2584
2585  /// getKeywordForTypeSpec - Converts a type specifier (DeclSpec::TST)
2586  /// into an elaborated type keyword.
2587  static ElaboratedTypeKeyword getKeywordForTypeSpec(unsigned TypeSpec);
2588
2589  /// getTagTypeKindForTypeSpec - Converts a type specifier (DeclSpec::TST)
2590  /// into a tag type kind.  It is an error to provide a type specifier
2591  /// which *isn't* a tag kind here.
2592  static TagTypeKind getTagTypeKindForTypeSpec(unsigned TypeSpec);
2593
2594  /// getKeywordForTagDeclKind - Converts a TagTypeKind into an
2595  /// elaborated type keyword.
2596  static ElaboratedTypeKeyword getKeywordForTagTypeKind(TagTypeKind Tag);
2597
2598  /// getTagTypeKindForKeyword - Converts an elaborated type keyword into
2599  // a TagTypeKind. It is an error to provide an elaborated type keyword
2600  /// which *isn't* a tag kind here.
2601  static TagTypeKind getTagTypeKindForKeyword(ElaboratedTypeKeyword Keyword);
2602
2603  static bool KeywordIsTagTypeKind(ElaboratedTypeKeyword Keyword);
2604
2605  static const char *getKeywordName(ElaboratedTypeKeyword Keyword);
2606
2607  static const char *getTagTypeKindName(TagTypeKind Kind) {
2608    return getKeywordName(getKeywordForTagTypeKind(Kind));
2609  }
2610
2611  class CannotCastToThisType {};
2612  static CannotCastToThisType classof(const Type *);
2613};
2614
2615/// \brief Represents a type that was referred to using an elaborated type
2616/// keyword, e.g., struct S, or via a qualified name, e.g., N::M::type,
2617/// or both.
2618///
2619/// This type is used to keep track of a type name as written in the
2620/// source code, including tag keywords and any nested-name-specifiers.
2621/// The type itself is always "sugar", used to express what was written
2622/// in the source code but containing no additional semantic information.
2623class ElaboratedType : public TypeWithKeyword, public llvm::FoldingSetNode {
2624
2625  /// \brief The nested name specifier containing the qualifier.
2626  NestedNameSpecifier *NNS;
2627
2628  /// \brief The type that this qualified name refers to.
2629  QualType NamedType;
2630
2631  ElaboratedType(ElaboratedTypeKeyword Keyword, NestedNameSpecifier *NNS,
2632                 QualType NamedType, QualType CanonType)
2633    : TypeWithKeyword(Keyword, Elaborated, CanonType,
2634                      NamedType->isDependentType()),
2635      NNS(NNS), NamedType(NamedType) {
2636    assert(!(Keyword == ETK_None && NNS == 0) &&
2637           "ElaboratedType cannot have elaborated type keyword "
2638           "and name qualifier both null.");
2639  }
2640
2641  friend class ASTContext;  // ASTContext creates these
2642
2643public:
2644
2645  /// \brief Retrieve the qualification on this type.
2646  NestedNameSpecifier *getQualifier() const { return NNS; }
2647
2648  /// \brief Retrieve the type named by the qualified-id.
2649  QualType getNamedType() const { return NamedType; }
2650
2651  /// \brief Remove a single level of sugar.
2652  QualType desugar() const { return getNamedType(); }
2653
2654  /// \brief Returns whether this type directly provides sugar.
2655  bool isSugared() const { return true; }
2656
2657  void Profile(llvm::FoldingSetNodeID &ID) {
2658    Profile(ID, getKeyword(), NNS, NamedType);
2659  }
2660
2661  static void Profile(llvm::FoldingSetNodeID &ID, ElaboratedTypeKeyword Keyword,
2662                      NestedNameSpecifier *NNS, QualType NamedType) {
2663    ID.AddInteger(Keyword);
2664    ID.AddPointer(NNS);
2665    NamedType.Profile(ID);
2666  }
2667
2668  static bool classof(const Type *T) {
2669    return T->getTypeClass() == Elaborated;
2670  }
2671  static bool classof(const ElaboratedType *T) { return true; }
2672};
2673
2674/// \brief Represents a qualified type name for which the type name is
2675/// dependent.
2676///
2677/// DependentNameType represents a class of dependent types that involve a
2678/// dependent nested-name-specifier (e.g., "T::") followed by a (dependent)
2679/// name of a type. The DependentNameType may start with a "typename" (for a
2680/// typename-specifier), "class", "struct", "union", or "enum" (for a
2681/// dependent elaborated-type-specifier), or nothing (in contexts where we
2682/// know that we must be referring to a type, e.g., in a base class specifier).
2683class DependentNameType : public TypeWithKeyword, public llvm::FoldingSetNode {
2684
2685  /// \brief The nested name specifier containing the qualifier.
2686  NestedNameSpecifier *NNS;
2687
2688  typedef llvm::PointerUnion<const IdentifierInfo *,
2689                             const TemplateSpecializationType *> NameType;
2690
2691  /// \brief The type that this typename specifier refers to.
2692  NameType Name;
2693
2694  DependentNameType(ElaboratedTypeKeyword Keyword, NestedNameSpecifier *NNS,
2695                    const IdentifierInfo *Name, QualType CanonType)
2696    : TypeWithKeyword(Keyword, DependentName, CanonType, true),
2697      NNS(NNS), Name(Name) {
2698    assert(NNS->isDependent() &&
2699           "DependentNameType requires a dependent nested-name-specifier");
2700  }
2701
2702  DependentNameType(ElaboratedTypeKeyword Keyword, NestedNameSpecifier *NNS,
2703                    const TemplateSpecializationType *Ty, QualType CanonType)
2704    : TypeWithKeyword(Keyword, DependentName, CanonType, true),
2705      NNS(NNS), Name(Ty) {
2706    assert(NNS->isDependent() &&
2707           "DependentNameType requires a dependent nested-name-specifier");
2708  }
2709
2710  friend class ASTContext;  // ASTContext creates these
2711
2712public:
2713
2714  /// \brief Retrieve the qualification on this type.
2715  NestedNameSpecifier *getQualifier() const { return NNS; }
2716
2717  /// \brief Retrieve the type named by the typename specifier as an
2718  /// identifier.
2719  ///
2720  /// This routine will return a non-NULL identifier pointer when the
2721  /// form of the original typename was terminated by an identifier,
2722  /// e.g., "typename T::type".
2723  const IdentifierInfo *getIdentifier() const {
2724    return Name.dyn_cast<const IdentifierInfo *>();
2725  }
2726
2727  /// \brief Retrieve the type named by the typename specifier as a
2728  /// type specialization.
2729  const TemplateSpecializationType *getTemplateId() const {
2730    return Name.dyn_cast<const TemplateSpecializationType *>();
2731  }
2732
2733  bool isSugared() const { return false; }
2734  QualType desugar() const { return QualType(this, 0); }
2735
2736  void Profile(llvm::FoldingSetNodeID &ID) {
2737    Profile(ID, getKeyword(), NNS, Name);
2738  }
2739
2740  static void Profile(llvm::FoldingSetNodeID &ID, ElaboratedTypeKeyword Keyword,
2741                      NestedNameSpecifier *NNS, NameType Name) {
2742    ID.AddInteger(Keyword);
2743    ID.AddPointer(NNS);
2744    ID.AddPointer(Name.getOpaqueValue());
2745  }
2746
2747  static bool classof(const Type *T) {
2748    return T->getTypeClass() == DependentName;
2749  }
2750  static bool classof(const DependentNameType *T) { return true; }
2751};
2752
2753/// ObjCInterfaceType - Interfaces are the core concept in Objective-C for
2754/// object oriented design.  They basically correspond to C++ classes.  There
2755/// are two kinds of interface types, normal interfaces like "NSString" and
2756/// qualified interfaces, which are qualified with a protocol list like
2757/// "NSString<NSCopyable, NSAmazing>".
2758class ObjCInterfaceType : public Type, public llvm::FoldingSetNode {
2759  ObjCInterfaceDecl *Decl;
2760
2761  /// \brief The number of protocols stored after the ObjCInterfaceType node.
2762  /// The list of protocols is sorted on protocol name. No protocol is enterred
2763  /// more than once.
2764  unsigned NumProtocols;
2765
2766  ObjCInterfaceType(QualType Canonical, ObjCInterfaceDecl *D,
2767                    ObjCProtocolDecl **Protos, unsigned NumP);
2768  friend class ASTContext;  // ASTContext creates these.
2769public:
2770  void Destroy(ASTContext& C);
2771
2772  ObjCInterfaceDecl *getDecl() const { return Decl; }
2773
2774  /// getNumProtocols - Return the number of qualifying protocols in this
2775  /// interface type, or 0 if there are none.
2776  unsigned getNumProtocols() const { return NumProtocols; }
2777
2778  /// \brief Retrieve the Ith protocol.
2779  ObjCProtocolDecl *getProtocol(unsigned I) const {
2780    assert(I < getNumProtocols() && "Out-of-range protocol access");
2781    return qual_begin()[I];
2782  }
2783
2784  /// qual_iterator and friends: this provides access to the (potentially empty)
2785  /// list of protocols qualifying this interface.
2786  typedef ObjCProtocolDecl*  const * qual_iterator;
2787  qual_iterator qual_begin() const {
2788    return reinterpret_cast<qual_iterator>(this + 1);
2789  }
2790  qual_iterator qual_end() const   {
2791    return qual_begin() + NumProtocols;
2792  }
2793  bool qual_empty() const { return NumProtocols == 0; }
2794
2795  bool isSugared() const { return false; }
2796  QualType desugar() const { return QualType(this, 0); }
2797
2798  void Profile(llvm::FoldingSetNodeID &ID);
2799  static void Profile(llvm::FoldingSetNodeID &ID,
2800                      const ObjCInterfaceDecl *Decl,
2801                      ObjCProtocolDecl * const *protocols,
2802                      unsigned NumProtocols);
2803
2804  virtual Linkage getLinkage() const;
2805
2806  static bool classof(const Type *T) {
2807    return T->getTypeClass() == ObjCInterface;
2808  }
2809  static bool classof(const ObjCInterfaceType *) { return true; }
2810};
2811
2812/// ObjCObjectPointerType - Used to represent 'id', 'Interface *', 'id <p>',
2813/// and 'Interface <p> *'.
2814///
2815/// Duplicate protocols are removed and protocol list is canonicalized to be in
2816/// alphabetical order.
2817class ObjCObjectPointerType : public Type, public llvm::FoldingSetNode {
2818  QualType PointeeType; // A builtin or interface type.
2819
2820  /// \brief The number of protocols stored after the ObjCObjectPointerType
2821  /// node.
2822  ///
2823  /// The list of protocols is sorted on protocol name. No protocol is enterred
2824  /// more than once.
2825  unsigned NumProtocols;
2826
2827  ObjCObjectPointerType(QualType Canonical, QualType T,
2828                        ObjCProtocolDecl **Protos, unsigned NumP);
2829  friend class ASTContext;  // ASTContext creates these.
2830
2831public:
2832  void Destroy(ASTContext& C);
2833
2834  // Get the pointee type. Pointee will either be:
2835  // - a built-in type (for 'id' and 'Class').
2836  // - an interface type (for user-defined types).
2837  // - a TypedefType whose canonical type is an interface (as in 'T' below).
2838  //   For example: typedef NSObject T; T *var;
2839  QualType getPointeeType() const { return PointeeType; }
2840
2841  const ObjCInterfaceType *getInterfaceType() const {
2842    return PointeeType->getAs<ObjCInterfaceType>();
2843  }
2844  /// getInterfaceDecl - returns an interface decl for user-defined types.
2845  ObjCInterfaceDecl *getInterfaceDecl() const {
2846    return getInterfaceType() ? getInterfaceType()->getDecl() : 0;
2847  }
2848  /// isObjCIdType - true for "id".
2849  bool isObjCIdType() const {
2850    return getPointeeType()->isSpecificBuiltinType(BuiltinType::ObjCId) &&
2851           !NumProtocols;
2852  }
2853  /// isObjCClassType - true for "Class".
2854  bool isObjCClassType() const {
2855    return getPointeeType()->isSpecificBuiltinType(BuiltinType::ObjCClass) &&
2856           !NumProtocols;
2857  }
2858
2859  /// isObjCQualifiedIdType - true for "id <p>".
2860  bool isObjCQualifiedIdType() const {
2861    return getPointeeType()->isSpecificBuiltinType(BuiltinType::ObjCId) &&
2862           NumProtocols;
2863  }
2864  /// isObjCQualifiedClassType - true for "Class <p>".
2865  bool isObjCQualifiedClassType() const {
2866    return getPointeeType()->isSpecificBuiltinType(BuiltinType::ObjCClass) &&
2867           NumProtocols;
2868  }
2869  /// qual_iterator and friends: this provides access to the (potentially empty)
2870  /// list of protocols qualifying this interface.
2871  typedef ObjCProtocolDecl*  const * qual_iterator;
2872
2873  qual_iterator qual_begin() const {
2874    return reinterpret_cast<qual_iterator> (this + 1);
2875  }
2876  qual_iterator qual_end() const   {
2877    return qual_begin() + NumProtocols;
2878  }
2879  bool qual_empty() const { return NumProtocols == 0; }
2880
2881  /// getNumProtocols - Return the number of qualifying protocols in this
2882  /// interface type, or 0 if there are none.
2883  unsigned getNumProtocols() const { return NumProtocols; }
2884
2885  /// \brief Retrieve the Ith protocol.
2886  ObjCProtocolDecl *getProtocol(unsigned I) const {
2887    assert(I < getNumProtocols() && "Out-of-range protocol access");
2888    return qual_begin()[I];
2889  }
2890
2891  bool isSugared() const { return false; }
2892  QualType desugar() const { return QualType(this, 0); }
2893
2894  virtual Linkage getLinkage() const;
2895
2896  void Profile(llvm::FoldingSetNodeID &ID);
2897  static void Profile(llvm::FoldingSetNodeID &ID, QualType T,
2898                      ObjCProtocolDecl *const *protocols,
2899                      unsigned NumProtocols);
2900  static bool classof(const Type *T) {
2901    return T->getTypeClass() == ObjCObjectPointer;
2902  }
2903  static bool classof(const ObjCObjectPointerType *) { return true; }
2904};
2905
2906/// A qualifier set is used to build a set of qualifiers.
2907class QualifierCollector : public Qualifiers {
2908  ASTContext *Context;
2909
2910public:
2911  QualifierCollector(Qualifiers Qs = Qualifiers())
2912    : Qualifiers(Qs), Context(0) {}
2913  QualifierCollector(ASTContext &Context, Qualifiers Qs = Qualifiers())
2914    : Qualifiers(Qs), Context(&Context) {}
2915
2916  void setContext(ASTContext &C) { Context = &C; }
2917
2918  /// Collect any qualifiers on the given type and return an
2919  /// unqualified type.
2920  const Type *strip(QualType QT) {
2921    addFastQualifiers(QT.getLocalFastQualifiers());
2922    if (QT.hasLocalNonFastQualifiers()) {
2923      const ExtQuals *EQ = QT.getExtQualsUnsafe();
2924      Context = &EQ->getContext();
2925      addQualifiers(EQ->getQualifiers());
2926      return EQ->getBaseType();
2927    }
2928    return QT.getTypePtrUnsafe();
2929  }
2930
2931  /// Apply the collected qualifiers to the given type.
2932  QualType apply(QualType QT) const;
2933
2934  /// Apply the collected qualifiers to the given type.
2935  QualType apply(const Type* T) const;
2936
2937};
2938
2939
2940// Inline function definitions.
2941
2942inline bool QualType::isCanonical() const {
2943  const Type *T = getTypePtr();
2944  if (hasLocalQualifiers())
2945    return T->isCanonicalUnqualified() && !isa<ArrayType>(T);
2946  return T->isCanonicalUnqualified();
2947}
2948
2949inline bool QualType::isCanonicalAsParam() const {
2950  if (hasLocalQualifiers()) return false;
2951  const Type *T = getTypePtr();
2952  return T->isCanonicalUnqualified() &&
2953           !isa<FunctionType>(T) && !isa<ArrayType>(T);
2954}
2955
2956inline bool QualType::isConstQualified() const {
2957  return isLocalConstQualified() ||
2958              getTypePtr()->getCanonicalTypeInternal().isLocalConstQualified();
2959}
2960
2961inline bool QualType::isRestrictQualified() const {
2962  return isLocalRestrictQualified() ||
2963            getTypePtr()->getCanonicalTypeInternal().isLocalRestrictQualified();
2964}
2965
2966
2967inline bool QualType::isVolatileQualified() const {
2968  return isLocalVolatileQualified() ||
2969  getTypePtr()->getCanonicalTypeInternal().isLocalVolatileQualified();
2970}
2971
2972inline bool QualType::hasQualifiers() const {
2973  return hasLocalQualifiers() ||
2974                  getTypePtr()->getCanonicalTypeInternal().hasLocalQualifiers();
2975}
2976
2977inline Qualifiers QualType::getQualifiers() const {
2978  Qualifiers Quals = getLocalQualifiers();
2979  Quals.addQualifiers(
2980                 getTypePtr()->getCanonicalTypeInternal().getLocalQualifiers());
2981  return Quals;
2982}
2983
2984inline unsigned QualType::getCVRQualifiers() const {
2985  return getLocalCVRQualifiers() |
2986              getTypePtr()->getCanonicalTypeInternal().getLocalCVRQualifiers();
2987}
2988
2989/// getCVRQualifiersThroughArrayTypes - If there are CVR qualifiers for this
2990/// type, returns them. Otherwise, if this is an array type, recurses
2991/// on the element type until some qualifiers have been found or a non-array
2992/// type reached.
2993inline unsigned QualType::getCVRQualifiersThroughArrayTypes() const {
2994  if (unsigned Quals = getCVRQualifiers())
2995    return Quals;
2996  QualType CT = getTypePtr()->getCanonicalTypeInternal();
2997  if (const ArrayType *AT = dyn_cast<ArrayType>(CT))
2998    return AT->getElementType().getCVRQualifiersThroughArrayTypes();
2999  return 0;
3000}
3001
3002inline void QualType::removeConst() {
3003  removeFastQualifiers(Qualifiers::Const);
3004}
3005
3006inline void QualType::removeRestrict() {
3007  removeFastQualifiers(Qualifiers::Restrict);
3008}
3009
3010inline void QualType::removeVolatile() {
3011  QualifierCollector Qc;
3012  const Type *Ty = Qc.strip(*this);
3013  if (Qc.hasVolatile()) {
3014    Qc.removeVolatile();
3015    *this = Qc.apply(Ty);
3016  }
3017}
3018
3019inline void QualType::removeCVRQualifiers(unsigned Mask) {
3020  assert(!(Mask & ~Qualifiers::CVRMask) && "mask has non-CVR bits");
3021
3022  // Fast path: we don't need to touch the slow qualifiers.
3023  if (!(Mask & ~Qualifiers::FastMask)) {
3024    removeFastQualifiers(Mask);
3025    return;
3026  }
3027
3028  QualifierCollector Qc;
3029  const Type *Ty = Qc.strip(*this);
3030  Qc.removeCVRQualifiers(Mask);
3031  *this = Qc.apply(Ty);
3032}
3033
3034/// getAddressSpace - Return the address space of this type.
3035inline unsigned QualType::getAddressSpace() const {
3036  if (hasLocalNonFastQualifiers()) {
3037    const ExtQuals *EQ = getExtQualsUnsafe();
3038    if (EQ->hasAddressSpace())
3039      return EQ->getAddressSpace();
3040  }
3041
3042  QualType CT = getTypePtr()->getCanonicalTypeInternal();
3043  if (CT.hasLocalNonFastQualifiers()) {
3044    const ExtQuals *EQ = CT.getExtQualsUnsafe();
3045    if (EQ->hasAddressSpace())
3046      return EQ->getAddressSpace();
3047  }
3048
3049  if (const ArrayType *AT = dyn_cast<ArrayType>(CT))
3050    return AT->getElementType().getAddressSpace();
3051  if (const RecordType *RT = dyn_cast<RecordType>(CT))
3052    return RT->getAddressSpace();
3053  return 0;
3054}
3055
3056/// getObjCGCAttr - Return the gc attribute of this type.
3057inline Qualifiers::GC QualType::getObjCGCAttr() const {
3058  if (hasLocalNonFastQualifiers()) {
3059    const ExtQuals *EQ = getExtQualsUnsafe();
3060    if (EQ->hasObjCGCAttr())
3061      return EQ->getObjCGCAttr();
3062  }
3063
3064  QualType CT = getTypePtr()->getCanonicalTypeInternal();
3065  if (CT.hasLocalNonFastQualifiers()) {
3066    const ExtQuals *EQ = CT.getExtQualsUnsafe();
3067    if (EQ->hasObjCGCAttr())
3068      return EQ->getObjCGCAttr();
3069  }
3070
3071  if (const ArrayType *AT = dyn_cast<ArrayType>(CT))
3072      return AT->getElementType().getObjCGCAttr();
3073  if (const ObjCObjectPointerType *PT = CT->getAs<ObjCObjectPointerType>())
3074    return PT->getPointeeType().getObjCGCAttr();
3075  // We most look at all pointer types, not just pointer to interface types.
3076  if (const PointerType *PT = CT->getAs<PointerType>())
3077    return PT->getPointeeType().getObjCGCAttr();
3078  return Qualifiers::GCNone;
3079}
3080
3081inline FunctionType::ExtInfo getFunctionExtInfo(const Type &t) {
3082  if (const PointerType *PT = t.getAs<PointerType>()) {
3083    if (const FunctionType *FT = PT->getPointeeType()->getAs<FunctionType>())
3084      return FT->getExtInfo();
3085  } else if (const FunctionType *FT = t.getAs<FunctionType>())
3086    return FT->getExtInfo();
3087
3088  return FunctionType::ExtInfo();
3089}
3090
3091inline FunctionType::ExtInfo getFunctionExtInfo(QualType t) {
3092  return getFunctionExtInfo(*t);
3093}
3094
3095/// isMoreQualifiedThan - Determine whether this type is more
3096/// qualified than the Other type. For example, "const volatile int"
3097/// is more qualified than "const int", "volatile int", and
3098/// "int". However, it is not more qualified than "const volatile
3099/// int".
3100inline bool QualType::isMoreQualifiedThan(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 | OtherQuals) == MyQuals;
3107}
3108
3109/// isAtLeastAsQualifiedAs - Determine whether this type is at last
3110/// as qualified as the Other type. For example, "const volatile
3111/// int" is at least as qualified as "const int", "volatile int",
3112/// "int", and "const volatile int".
3113inline bool QualType::isAtLeastAsQualifiedAs(QualType Other) const {
3114  // FIXME: work on arbitrary qualifiers
3115  unsigned MyQuals = this->getCVRQualifiersThroughArrayTypes();
3116  unsigned OtherQuals = Other.getCVRQualifiersThroughArrayTypes();
3117  if (getAddressSpace() != Other.getAddressSpace())
3118    return false;
3119  return (MyQuals | OtherQuals) == MyQuals;
3120}
3121
3122/// getNonReferenceType - If Type is a reference type (e.g., const
3123/// int&), returns the type that the reference refers to ("const
3124/// int"). Otherwise, returns the type itself. This routine is used
3125/// throughout Sema to implement C++ 5p6:
3126///
3127///   If an expression initially has the type "reference to T" (8.3.2,
3128///   8.5.3), the type is adjusted to "T" prior to any further
3129///   analysis, the expression designates the object or function
3130///   denoted by the reference, and the expression is an lvalue.
3131inline QualType QualType::getNonReferenceType() const {
3132  if (const ReferenceType *RefType = (*this)->getAs<ReferenceType>())
3133    return RefType->getPointeeType();
3134  else
3135    return *this;
3136}
3137
3138inline const ObjCInterfaceType *Type::getAsPointerToObjCInterfaceType() const {
3139  if (const PointerType *PT = getAs<PointerType>())
3140    return PT->getPointeeType()->getAs<ObjCInterfaceType>();
3141  return 0;
3142}
3143
3144inline bool Type::isFunctionType() const {
3145  return isa<FunctionType>(CanonicalType);
3146}
3147inline bool Type::isPointerType() const {
3148  return isa<PointerType>(CanonicalType);
3149}
3150inline bool Type::isAnyPointerType() const {
3151  return isPointerType() || isObjCObjectPointerType();
3152}
3153inline bool Type::isBlockPointerType() const {
3154  return isa<BlockPointerType>(CanonicalType);
3155}
3156inline bool Type::isReferenceType() const {
3157  return isa<ReferenceType>(CanonicalType);
3158}
3159inline bool Type::isLValueReferenceType() const {
3160  return isa<LValueReferenceType>(CanonicalType);
3161}
3162inline bool Type::isRValueReferenceType() const {
3163  return isa<RValueReferenceType>(CanonicalType);
3164}
3165inline bool Type::isFunctionPointerType() const {
3166  if (const PointerType* T = getAs<PointerType>())
3167    return T->getPointeeType()->isFunctionType();
3168  else
3169    return false;
3170}
3171inline bool Type::isMemberPointerType() const {
3172  return isa<MemberPointerType>(CanonicalType);
3173}
3174inline bool Type::isMemberFunctionPointerType() const {
3175  if (const MemberPointerType* T = getAs<MemberPointerType>())
3176    return T->getPointeeType()->isFunctionType();
3177  else
3178    return false;
3179}
3180inline bool Type::isArrayType() const {
3181  return isa<ArrayType>(CanonicalType);
3182}
3183inline bool Type::isConstantArrayType() const {
3184  return isa<ConstantArrayType>(CanonicalType);
3185}
3186inline bool Type::isIncompleteArrayType() const {
3187  return isa<IncompleteArrayType>(CanonicalType);
3188}
3189inline bool Type::isVariableArrayType() const {
3190  return isa<VariableArrayType>(CanonicalType);
3191}
3192inline bool Type::isDependentSizedArrayType() const {
3193  return isa<DependentSizedArrayType>(CanonicalType);
3194}
3195inline bool Type::isRecordType() const {
3196  return isa<RecordType>(CanonicalType);
3197}
3198inline bool Type::isAnyComplexType() const {
3199  return isa<ComplexType>(CanonicalType);
3200}
3201inline bool Type::isVectorType() const {
3202  return isa<VectorType>(CanonicalType);
3203}
3204inline bool Type::isExtVectorType() const {
3205  return isa<ExtVectorType>(CanonicalType);
3206}
3207inline bool Type::isObjCObjectPointerType() const {
3208  return isa<ObjCObjectPointerType>(CanonicalType);
3209}
3210inline bool Type::isObjCInterfaceType() const {
3211  return isa<ObjCInterfaceType>(CanonicalType);
3212}
3213inline bool Type::isObjCQualifiedIdType() const {
3214  if (const ObjCObjectPointerType *OPT = getAs<ObjCObjectPointerType>())
3215    return OPT->isObjCQualifiedIdType();
3216  return false;
3217}
3218inline bool Type::isObjCQualifiedClassType() const {
3219  if (const ObjCObjectPointerType *OPT = getAs<ObjCObjectPointerType>())
3220    return OPT->isObjCQualifiedClassType();
3221  return false;
3222}
3223inline bool Type::isObjCIdType() const {
3224  if (const ObjCObjectPointerType *OPT = getAs<ObjCObjectPointerType>())
3225    return OPT->isObjCIdType();
3226  return false;
3227}
3228inline bool Type::isObjCClassType() const {
3229  if (const ObjCObjectPointerType *OPT = getAs<ObjCObjectPointerType>())
3230    return OPT->isObjCClassType();
3231  return false;
3232}
3233inline bool Type::isObjCSelType() const {
3234  if (const PointerType *OPT = getAs<PointerType>())
3235    return OPT->getPointeeType()->isSpecificBuiltinType(BuiltinType::ObjCSel);
3236  return false;
3237}
3238inline bool Type::isObjCBuiltinType() const {
3239  return isObjCIdType() || isObjCClassType() || isObjCSelType();
3240}
3241inline bool Type::isTemplateTypeParmType() const {
3242  return isa<TemplateTypeParmType>(CanonicalType);
3243}
3244
3245inline bool Type::isSpecificBuiltinType(unsigned K) const {
3246  if (const BuiltinType *BT = getAs<BuiltinType>())
3247    if (BT->getKind() == (BuiltinType::Kind) K)
3248      return true;
3249  return false;
3250}
3251
3252/// \brief Determines whether this is a type for which one can define
3253/// an overloaded operator.
3254inline bool Type::isOverloadableType() const {
3255  return isDependentType() || isRecordType() || isEnumeralType();
3256}
3257
3258inline bool Type::hasPointerRepresentation() const {
3259  return (isPointerType() || isReferenceType() || isBlockPointerType() ||
3260          isObjCInterfaceType() || isObjCObjectPointerType() ||
3261          isObjCQualifiedInterfaceType() || isNullPtrType());
3262}
3263
3264inline bool Type::hasObjCPointerRepresentation() const {
3265  return (isObjCInterfaceType() || isObjCObjectPointerType() ||
3266          isObjCQualifiedInterfaceType());
3267}
3268
3269/// Insertion operator for diagnostics.  This allows sending QualType's into a
3270/// diagnostic with <<.
3271inline const DiagnosticBuilder &operator<<(const DiagnosticBuilder &DB,
3272                                           QualType T) {
3273  DB.AddTaggedVal(reinterpret_cast<intptr_t>(T.getAsOpaquePtr()),
3274                  Diagnostic::ak_qualtype);
3275  return DB;
3276}
3277
3278/// Insertion operator for partial diagnostics.  This allows sending QualType's
3279/// into a diagnostic with <<.
3280inline const PartialDiagnostic &operator<<(const PartialDiagnostic &PD,
3281                                           QualType T) {
3282  PD.AddTaggedVal(reinterpret_cast<intptr_t>(T.getAsOpaquePtr()),
3283                  Diagnostic::ak_qualtype);
3284  return PD;
3285}
3286
3287// Helper class template that is used by Type::getAs to ensure that one does
3288// not try to look through a qualified type to get to an array type.
3289template<typename T,
3290         bool isArrayType = (llvm::is_same<T, ArrayType>::value ||
3291                             llvm::is_base_of<ArrayType, T>::value)>
3292struct ArrayType_cannot_be_used_with_getAs { };
3293
3294template<typename T>
3295struct ArrayType_cannot_be_used_with_getAs<T, true>;
3296
3297/// Member-template getAs<specific type>'.
3298template <typename T> const T *Type::getAs() const {
3299  ArrayType_cannot_be_used_with_getAs<T> at;
3300  (void)at;
3301
3302  // If this is directly a T type, return it.
3303  if (const T *Ty = dyn_cast<T>(this))
3304    return Ty;
3305
3306  // If the canonical form of this type isn't the right kind, reject it.
3307  if (!isa<T>(CanonicalType))
3308    return 0;
3309
3310  // If this is a typedef for the type, strip the typedef off without
3311  // losing all typedef information.
3312  return cast<T>(getUnqualifiedDesugaredType());
3313}
3314
3315}  // end namespace clang
3316
3317#endif
3318