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