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