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