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