Type.h revision 491328c90c00ecad6ad27fa0ab3cdf9195a4a820
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 : 2;
935
936    /// NumElements - The number of elements in the vector.
937    unsigned NumElements : 30 - 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  /// isDependentType - Whether this type is a dependent type, meaning
1127  /// that its definition somehow depends on a template parameter
1128  /// (C++ [temp.dep.type]).
1129  bool isDependentType() const { return TypeBits.Dependent; }
1130
1131  /// \brief Whether this type is a variably-modified type (C99 6.7.5).
1132  bool isVariablyModifiedType() const { return TypeBits.VariablyModified; }
1133
1134  /// \brief Whether this type is or contains a local or unnamed type.
1135  bool hasUnnamedOrLocalType() const;
1136
1137  bool isOverloadableType() const;
1138
1139  /// \brief Determine wither this type is a C++ elaborated-type-specifier.
1140  bool isElaboratedTypeSpecifier() const;
1141
1142  /// hasPointerRepresentation - Whether this type is represented
1143  /// natively as a pointer; this includes pointers, references, block
1144  /// pointers, and Objective-C interface, qualified id, and qualified
1145  /// interface types, as well as nullptr_t.
1146  bool hasPointerRepresentation() const;
1147
1148  /// hasObjCPointerRepresentation - Whether this type can represent
1149  /// an objective pointer type for the purpose of GC'ability
1150  bool hasObjCPointerRepresentation() const;
1151
1152  /// \brief Determine whether this type has an integer representation
1153  /// of some sort, e.g., it is an integer type or a vector.
1154  bool hasIntegerRepresentation() const;
1155
1156  /// \brief Determine whether this type has an signed integer representation
1157  /// of some sort, e.g., it is an signed integer type or a vector.
1158  bool hasSignedIntegerRepresentation() const;
1159
1160  /// \brief Determine whether this type has an unsigned integer representation
1161  /// of some sort, e.g., it is an unsigned integer type or a vector.
1162  bool hasUnsignedIntegerRepresentation() const;
1163
1164  /// \brief Determine whether this type has a floating-point representation
1165  /// of some sort, e.g., it is a floating-point type or a vector thereof.
1166  bool hasFloatingRepresentation() const;
1167
1168  // Type Checking Functions: Check to see if this type is structurally the
1169  // specified type, ignoring typedefs and qualifiers, and return a pointer to
1170  // the best type we can.
1171  const RecordType *getAsStructureType() const;
1172  /// NOTE: getAs*ArrayType are methods on ASTContext.
1173  const RecordType *getAsUnionType() const;
1174  const ComplexType *getAsComplexIntegerType() const; // GCC complex int type.
1175  // The following is a convenience method that returns an ObjCObjectPointerType
1176  // for object declared using an interface.
1177  const ObjCObjectPointerType *getAsObjCInterfacePointerType() const;
1178  const ObjCObjectPointerType *getAsObjCQualifiedIdType() const;
1179  const ObjCObjectType *getAsObjCQualifiedInterfaceType() const;
1180  const CXXRecordDecl *getCXXRecordDeclForPointerType() const;
1181
1182  /// \brief Retrieves the CXXRecordDecl that this type refers to, either
1183  /// because the type is a RecordType or because it is the injected-class-name
1184  /// type of a class template or class template partial specialization.
1185  CXXRecordDecl *getAsCXXRecordDecl() const;
1186
1187  // Member-template getAs<specific type>'.  Look through sugar for
1188  // an instance of <specific type>.   This scheme will eventually
1189  // replace the specific getAsXXXX methods above.
1190  //
1191  // There are some specializations of this member template listed
1192  // immediately following this class.
1193  template <typename T> const T *getAs() const;
1194
1195  /// getArrayElementTypeNoTypeQual - If this is an array type, return the
1196  /// element type of the array, potentially with type qualifiers missing.
1197  /// This method should never be used when type qualifiers are meaningful.
1198  const Type *getArrayElementTypeNoTypeQual() const;
1199
1200  /// getPointeeType - If this is a pointer, ObjC object pointer, or block
1201  /// pointer, this returns the respective pointee.
1202  QualType getPointeeType() const;
1203
1204  /// getUnqualifiedDesugaredType() - Return the specified type with
1205  /// any "sugar" removed from the type, removing any typedefs,
1206  /// typeofs, etc., as well as any qualifiers.
1207  const Type *getUnqualifiedDesugaredType() const;
1208
1209  /// More type predicates useful for type checking/promotion
1210  bool isPromotableIntegerType() const; // C99 6.3.1.1p2
1211
1212  /// isSignedIntegerType - Return true if this is an integer type that is
1213  /// signed, according to C99 6.2.5p4 [char, signed char, short, int, long..],
1214  /// an enum decl which has a signed representation, or a vector of signed
1215  /// integer element type.
1216  bool isSignedIntegerType() const;
1217
1218  /// isUnsignedIntegerType - Return true if this is an integer type that is
1219  /// unsigned, according to C99 6.2.5p6 [which returns true for _Bool], an enum
1220  /// decl which has an unsigned representation, or a vector of unsigned integer
1221  /// element type.
1222  bool isUnsignedIntegerType() const;
1223
1224  /// isConstantSizeType - Return true if this is not a variable sized type,
1225  /// according to the rules of C99 6.7.5p3.  It is not legal to call this on
1226  /// incomplete types.
1227  bool isConstantSizeType() const;
1228
1229  /// isSpecifierType - Returns true if this type can be represented by some
1230  /// set of type specifiers.
1231  bool isSpecifierType() const;
1232
1233  /// \brief Determine the linkage of this type.
1234  Linkage getLinkage() const;
1235
1236  /// \brief Determine the visibility of this type.
1237  Visibility getVisibility() const;
1238
1239  /// \brief Determine the linkage and visibility of this type.
1240  std::pair<Linkage,Visibility> getLinkageAndVisibility() const;
1241
1242  /// \brief Note that the linkage is no longer known.
1243  void ClearLinkageCache();
1244
1245  const char *getTypeClassName() const;
1246
1247  QualType getCanonicalTypeInternal() const {
1248    return CanonicalType;
1249  }
1250  CanQualType getCanonicalTypeUnqualified() const; // in CanonicalType.h
1251  void dump() const;
1252  static bool classof(const Type *) { return true; }
1253
1254  friend class ASTReader;
1255  friend class ASTWriter;
1256};
1257
1258template <> inline const TypedefType *Type::getAs() const {
1259  return dyn_cast<TypedefType>(this);
1260}
1261
1262// We can do canonical leaf types faster, because we don't have to
1263// worry about preserving child type decoration.
1264#define TYPE(Class, Base)
1265#define LEAF_TYPE(Class) \
1266template <> inline const Class##Type *Type::getAs() const { \
1267  return dyn_cast<Class##Type>(CanonicalType); \
1268}
1269#include "clang/AST/TypeNodes.def"
1270
1271
1272/// BuiltinType - This class is used for builtin types like 'int'.  Builtin
1273/// types are always canonical and have a literal name field.
1274class BuiltinType : public Type {
1275public:
1276  enum Kind {
1277    Void,
1278
1279    Bool,     // This is bool and/or _Bool.
1280    Char_U,   // This is 'char' for targets where char is unsigned.
1281    UChar,    // This is explicitly qualified unsigned char.
1282    Char16,   // This is 'char16_t' for C++.
1283    Char32,   // This is 'char32_t' for C++.
1284    UShort,
1285    UInt,
1286    ULong,
1287    ULongLong,
1288    UInt128,  // __uint128_t
1289
1290    Char_S,   // This is 'char' for targets where char is signed.
1291    SChar,    // This is explicitly qualified signed char.
1292    WChar,    // This is 'wchar_t' for C++.
1293    Short,
1294    Int,
1295    Long,
1296    LongLong,
1297    Int128,   // __int128_t
1298
1299    Float, Double, LongDouble,
1300
1301    NullPtr,  // This is the type of C++0x 'nullptr'.
1302
1303    /// This represents the type of an expression whose type is
1304    /// totally unknown, e.g. 'T::foo'.  It is permitted for this to
1305    /// appear in situations where the structure of the type is
1306    /// theoretically deducible.
1307    Dependent,
1308
1309    Overload,  // This represents the type of an overloaded function declaration.
1310
1311    UndeducedAuto, // In C++0x, this represents the type of an auto variable
1312                   // that has not been deduced yet.
1313
1314    /// The primitive Objective C 'id' type.  The type pointed to by the
1315    /// user-visible 'id' type.  Only ever shows up in an AST as the base
1316    /// type of an ObjCObjectType.
1317    ObjCId,
1318
1319    /// The primitive Objective C 'Class' type.  The type pointed to by the
1320    /// user-visible 'Class' type.  Only ever shows up in an AST as the
1321    /// base type of an ObjCObjectType.
1322    ObjCClass,
1323
1324    ObjCSel    // This represents the ObjC 'SEL' type.
1325  };
1326
1327protected:
1328  virtual CachedProperties getCachedProperties() const;
1329
1330public:
1331  BuiltinType(Kind K)
1332    : Type(Builtin, QualType(), /*Dependent=*/(K == Dependent),
1333           /*VariablyModified=*/false) {
1334    BuiltinTypeBits.Kind = K;
1335  }
1336
1337  Kind getKind() const { return static_cast<Kind>(BuiltinTypeBits.Kind); }
1338  const char *getName(const LangOptions &LO) const;
1339
1340  bool isSugared() const { return false; }
1341  QualType desugar() const { return QualType(this, 0); }
1342
1343  bool isInteger() const {
1344    return getKind() >= Bool && getKind() <= Int128;
1345  }
1346
1347  bool isSignedInteger() const {
1348    return getKind() >= Char_S && getKind() <= Int128;
1349  }
1350
1351  bool isUnsignedInteger() const {
1352    return getKind() >= Bool && getKind() <= UInt128;
1353  }
1354
1355  bool isFloatingPoint() const {
1356    return getKind() >= Float && getKind() <= LongDouble;
1357  }
1358
1359  /// Determines whether this type is a "forbidden" placeholder type,
1360  /// i.e. a type which cannot appear in arbitrary positions in a
1361  /// fully-formed expression.
1362  bool isPlaceholderType() const {
1363    return getKind() == Overload ||
1364           getKind() == UndeducedAuto;
1365  }
1366
1367  static bool classof(const Type *T) { return T->getTypeClass() == Builtin; }
1368  static bool classof(const BuiltinType *) { return true; }
1369};
1370
1371/// ComplexType - C99 6.2.5p11 - Complex values.  This supports the C99 complex
1372/// types (_Complex float etc) as well as the GCC integer complex extensions.
1373///
1374class ComplexType : public Type, public llvm::FoldingSetNode {
1375  QualType ElementType;
1376  ComplexType(QualType Element, QualType CanonicalPtr) :
1377    Type(Complex, CanonicalPtr, Element->isDependentType(),
1378         Element->isVariablyModifiedType()),
1379    ElementType(Element) {
1380  }
1381  friend class ASTContext;  // ASTContext creates these.
1382
1383protected:
1384  virtual CachedProperties getCachedProperties() const;
1385
1386public:
1387  QualType getElementType() const { return ElementType; }
1388
1389  bool isSugared() const { return false; }
1390  QualType desugar() const { return QualType(this, 0); }
1391
1392  void Profile(llvm::FoldingSetNodeID &ID) {
1393    Profile(ID, getElementType());
1394  }
1395  static void Profile(llvm::FoldingSetNodeID &ID, QualType Element) {
1396    ID.AddPointer(Element.getAsOpaquePtr());
1397  }
1398
1399  static bool classof(const Type *T) { return T->getTypeClass() == Complex; }
1400  static bool classof(const ComplexType *) { return true; }
1401};
1402
1403/// PointerType - C99 6.7.5.1 - Pointer Declarators.
1404///
1405class PointerType : public Type, public llvm::FoldingSetNode {
1406  QualType PointeeType;
1407
1408  PointerType(QualType Pointee, QualType CanonicalPtr) :
1409    Type(Pointer, CanonicalPtr, Pointee->isDependentType(),
1410         Pointee->isVariablyModifiedType()),
1411    PointeeType(Pointee) {
1412  }
1413  friend class ASTContext;  // ASTContext creates these.
1414
1415protected:
1416  virtual CachedProperties getCachedProperties() const;
1417
1418public:
1419
1420  QualType getPointeeType() const { return PointeeType; }
1421
1422  bool isSugared() const { return false; }
1423  QualType desugar() const { return QualType(this, 0); }
1424
1425  void Profile(llvm::FoldingSetNodeID &ID) {
1426    Profile(ID, getPointeeType());
1427  }
1428  static void Profile(llvm::FoldingSetNodeID &ID, QualType Pointee) {
1429    ID.AddPointer(Pointee.getAsOpaquePtr());
1430  }
1431
1432  static bool classof(const Type *T) { return T->getTypeClass() == Pointer; }
1433  static bool classof(const PointerType *) { return true; }
1434};
1435
1436/// BlockPointerType - pointer to a block type.
1437/// This type is to represent types syntactically represented as
1438/// "void (^)(int)", etc. Pointee is required to always be a function type.
1439///
1440class BlockPointerType : public Type, public llvm::FoldingSetNode {
1441  QualType PointeeType;  // Block is some kind of pointer type
1442  BlockPointerType(QualType Pointee, QualType CanonicalCls) :
1443    Type(BlockPointer, CanonicalCls, Pointee->isDependentType(),
1444         Pointee->isVariablyModifiedType()),
1445    PointeeType(Pointee) {
1446  }
1447  friend class ASTContext;  // ASTContext creates these.
1448
1449protected:
1450  virtual CachedProperties getCachedProperties() const;
1451
1452public:
1453
1454  // Get the pointee type. Pointee is required to always be a function type.
1455  QualType getPointeeType() const { return PointeeType; }
1456
1457  bool isSugared() const { return false; }
1458  QualType desugar() const { return QualType(this, 0); }
1459
1460  void Profile(llvm::FoldingSetNodeID &ID) {
1461      Profile(ID, getPointeeType());
1462  }
1463  static void Profile(llvm::FoldingSetNodeID &ID, QualType Pointee) {
1464      ID.AddPointer(Pointee.getAsOpaquePtr());
1465  }
1466
1467  static bool classof(const Type *T) {
1468    return T->getTypeClass() == BlockPointer;
1469  }
1470  static bool classof(const BlockPointerType *) { return true; }
1471};
1472
1473/// ReferenceType - Base for LValueReferenceType and RValueReferenceType
1474///
1475class ReferenceType : public Type, public llvm::FoldingSetNode {
1476  QualType PointeeType;
1477
1478protected:
1479  ReferenceType(TypeClass tc, QualType Referencee, QualType CanonicalRef,
1480                bool SpelledAsLValue) :
1481    Type(tc, CanonicalRef, Referencee->isDependentType(),
1482         Referencee->isVariablyModifiedType()), PointeeType(Referencee) {
1483    ReferenceTypeBits.SpelledAsLValue = SpelledAsLValue;
1484    ReferenceTypeBits.InnerRef = Referencee->isReferenceType();
1485  }
1486
1487  virtual CachedProperties getCachedProperties() const;
1488
1489public:
1490  bool isSpelledAsLValue() const { return ReferenceTypeBits.SpelledAsLValue; }
1491  bool isInnerRef() const { return ReferenceTypeBits.InnerRef; }
1492
1493  QualType getPointeeTypeAsWritten() const { return PointeeType; }
1494  QualType getPointeeType() const {
1495    // FIXME: this might strip inner qualifiers; okay?
1496    const ReferenceType *T = this;
1497    while (T->isInnerRef())
1498      T = T->PointeeType->getAs<ReferenceType>();
1499    return T->PointeeType;
1500  }
1501
1502  void Profile(llvm::FoldingSetNodeID &ID) {
1503    Profile(ID, PointeeType, isSpelledAsLValue());
1504  }
1505  static void Profile(llvm::FoldingSetNodeID &ID,
1506                      QualType Referencee,
1507                      bool SpelledAsLValue) {
1508    ID.AddPointer(Referencee.getAsOpaquePtr());
1509    ID.AddBoolean(SpelledAsLValue);
1510  }
1511
1512  static bool classof(const Type *T) {
1513    return T->getTypeClass() == LValueReference ||
1514           T->getTypeClass() == RValueReference;
1515  }
1516  static bool classof(const ReferenceType *) { return true; }
1517};
1518
1519/// LValueReferenceType - C++ [dcl.ref] - Lvalue reference
1520///
1521class LValueReferenceType : public ReferenceType {
1522  LValueReferenceType(QualType Referencee, QualType CanonicalRef,
1523                      bool SpelledAsLValue) :
1524    ReferenceType(LValueReference, Referencee, CanonicalRef, SpelledAsLValue)
1525  {}
1526  friend class ASTContext; // ASTContext creates these
1527public:
1528  bool isSugared() const { return false; }
1529  QualType desugar() const { return QualType(this, 0); }
1530
1531  static bool classof(const Type *T) {
1532    return T->getTypeClass() == LValueReference;
1533  }
1534  static bool classof(const LValueReferenceType *) { return true; }
1535};
1536
1537/// RValueReferenceType - C++0x [dcl.ref] - Rvalue reference
1538///
1539class RValueReferenceType : public ReferenceType {
1540  RValueReferenceType(QualType Referencee, QualType CanonicalRef) :
1541    ReferenceType(RValueReference, Referencee, CanonicalRef, false) {
1542  }
1543  friend class ASTContext; // ASTContext creates these
1544public:
1545  bool isSugared() const { return false; }
1546  QualType desugar() const { return QualType(this, 0); }
1547
1548  static bool classof(const Type *T) {
1549    return T->getTypeClass() == RValueReference;
1550  }
1551  static bool classof(const RValueReferenceType *) { return true; }
1552};
1553
1554/// MemberPointerType - C++ 8.3.3 - Pointers to members
1555///
1556class MemberPointerType : public Type, public llvm::FoldingSetNode {
1557  QualType PointeeType;
1558  /// The class of which the pointee is a member. Must ultimately be a
1559  /// RecordType, but could be a typedef or a template parameter too.
1560  const Type *Class;
1561
1562  MemberPointerType(QualType Pointee, const Type *Cls, QualType CanonicalPtr) :
1563    Type(MemberPointer, CanonicalPtr,
1564         Cls->isDependentType() || Pointee->isDependentType(),
1565         Pointee->isVariablyModifiedType()),
1566    PointeeType(Pointee), Class(Cls) {
1567  }
1568  friend class ASTContext; // ASTContext creates these.
1569
1570protected:
1571  virtual CachedProperties getCachedProperties() const;
1572
1573public:
1574  QualType getPointeeType() const { return PointeeType; }
1575
1576  /// Returns true if the member type (i.e. the pointee type) is a
1577  /// function type rather than a data-member type.
1578  bool isMemberFunctionPointer() const {
1579    return PointeeType->isFunctionProtoType();
1580  }
1581
1582  /// Returns true if the member type (i.e. the pointee type) is a
1583  /// data type rather than a function type.
1584  bool isMemberDataPointer() const {
1585    return !PointeeType->isFunctionProtoType();
1586  }
1587
1588  const Type *getClass() const { return Class; }
1589
1590  bool isSugared() const { return false; }
1591  QualType desugar() const { return QualType(this, 0); }
1592
1593  void Profile(llvm::FoldingSetNodeID &ID) {
1594    Profile(ID, getPointeeType(), getClass());
1595  }
1596  static void Profile(llvm::FoldingSetNodeID &ID, QualType Pointee,
1597                      const Type *Class) {
1598    ID.AddPointer(Pointee.getAsOpaquePtr());
1599    ID.AddPointer(Class);
1600  }
1601
1602  static bool classof(const Type *T) {
1603    return T->getTypeClass() == MemberPointer;
1604  }
1605  static bool classof(const MemberPointerType *) { return true; }
1606};
1607
1608/// ArrayType - C99 6.7.5.2 - Array Declarators.
1609///
1610class ArrayType : public Type, public llvm::FoldingSetNode {
1611public:
1612  /// ArraySizeModifier - Capture whether this is a normal array (e.g. int X[4])
1613  /// an array with a static size (e.g. int X[static 4]), or an array
1614  /// with a star size (e.g. int X[*]).
1615  /// 'static' is only allowed on function parameters.
1616  enum ArraySizeModifier {
1617    Normal, Static, Star
1618  };
1619private:
1620  /// ElementType - The element type of the array.
1621  QualType ElementType;
1622
1623protected:
1624  // C++ [temp.dep.type]p1:
1625  //   A type is dependent if it is...
1626  //     - an array type constructed from any dependent type or whose
1627  //       size is specified by a constant expression that is
1628  //       value-dependent,
1629  ArrayType(TypeClass tc, QualType et, QualType can,
1630            ArraySizeModifier sm, unsigned tq)
1631    : Type(tc, can, et->isDependentType() || tc == DependentSizedArray,
1632           (tc == VariableArray || et->isVariablyModifiedType())),
1633      ElementType(et) {
1634    ArrayTypeBits.IndexTypeQuals = tq;
1635    ArrayTypeBits.SizeModifier = sm;
1636  }
1637
1638  friend class ASTContext;  // ASTContext creates these.
1639
1640  virtual CachedProperties getCachedProperties() const;
1641
1642public:
1643  QualType getElementType() const { return ElementType; }
1644  ArraySizeModifier getSizeModifier() const {
1645    return ArraySizeModifier(ArrayTypeBits.SizeModifier);
1646  }
1647  Qualifiers getIndexTypeQualifiers() const {
1648    return Qualifiers::fromCVRMask(getIndexTypeCVRQualifiers());
1649  }
1650  unsigned getIndexTypeCVRQualifiers() const {
1651    return ArrayTypeBits.IndexTypeQuals;
1652  }
1653
1654  static bool classof(const Type *T) {
1655    return T->getTypeClass() == ConstantArray ||
1656           T->getTypeClass() == VariableArray ||
1657           T->getTypeClass() == IncompleteArray ||
1658           T->getTypeClass() == DependentSizedArray;
1659  }
1660  static bool classof(const ArrayType *) { return true; }
1661};
1662
1663/// ConstantArrayType - This class represents the canonical version of
1664/// C arrays with a specified constant size.  For example, the canonical
1665/// type for 'int A[4 + 4*100]' is a ConstantArrayType where the element
1666/// type is 'int' and the size is 404.
1667class ConstantArrayType : public ArrayType {
1668  llvm::APInt Size; // Allows us to unique the type.
1669
1670  ConstantArrayType(QualType et, QualType can, const llvm::APInt &size,
1671                    ArraySizeModifier sm, unsigned tq)
1672    : ArrayType(ConstantArray, et, can, sm, tq),
1673      Size(size) {}
1674protected:
1675  ConstantArrayType(TypeClass tc, QualType et, QualType can,
1676                    const llvm::APInt &size, ArraySizeModifier sm, unsigned tq)
1677    : ArrayType(tc, et, can, sm, tq), Size(size) {}
1678  friend class ASTContext;  // ASTContext creates these.
1679public:
1680  const llvm::APInt &getSize() const { return Size; }
1681  bool isSugared() const { return false; }
1682  QualType desugar() const { return QualType(this, 0); }
1683
1684
1685  /// \brief Determine the number of bits required to address a member of
1686  // an array with the given element type and number of elements.
1687  static unsigned getNumAddressingBits(ASTContext &Context,
1688                                       QualType ElementType,
1689                                       const llvm::APInt &NumElements);
1690
1691  /// \brief Determine the maximum number of active bits that an array's size
1692  /// can require, which limits the maximum size of the array.
1693  static unsigned getMaxSizeBits(ASTContext &Context);
1694
1695  void Profile(llvm::FoldingSetNodeID &ID) {
1696    Profile(ID, getElementType(), getSize(),
1697            getSizeModifier(), getIndexTypeCVRQualifiers());
1698  }
1699  static void Profile(llvm::FoldingSetNodeID &ID, QualType ET,
1700                      const llvm::APInt &ArraySize, ArraySizeModifier SizeMod,
1701                      unsigned TypeQuals) {
1702    ID.AddPointer(ET.getAsOpaquePtr());
1703    ID.AddInteger(ArraySize.getZExtValue());
1704    ID.AddInteger(SizeMod);
1705    ID.AddInteger(TypeQuals);
1706  }
1707  static bool classof(const Type *T) {
1708    return T->getTypeClass() == ConstantArray;
1709  }
1710  static bool classof(const ConstantArrayType *) { return true; }
1711};
1712
1713/// IncompleteArrayType - This class represents C arrays with an unspecified
1714/// size.  For example 'int A[]' has an IncompleteArrayType where the element
1715/// type is 'int' and the size is unspecified.
1716class IncompleteArrayType : public ArrayType {
1717
1718  IncompleteArrayType(QualType et, QualType can,
1719                      ArraySizeModifier sm, unsigned tq)
1720    : ArrayType(IncompleteArray, et, can, sm, tq) {}
1721  friend class ASTContext;  // ASTContext creates these.
1722public:
1723  bool isSugared() const { return false; }
1724  QualType desugar() const { return QualType(this, 0); }
1725
1726  static bool classof(const Type *T) {
1727    return T->getTypeClass() == IncompleteArray;
1728  }
1729  static bool classof(const IncompleteArrayType *) { return true; }
1730
1731  friend class StmtIteratorBase;
1732
1733  void Profile(llvm::FoldingSetNodeID &ID) {
1734    Profile(ID, getElementType(), getSizeModifier(),
1735            getIndexTypeCVRQualifiers());
1736  }
1737
1738  static void Profile(llvm::FoldingSetNodeID &ID, QualType ET,
1739                      ArraySizeModifier SizeMod, unsigned TypeQuals) {
1740    ID.AddPointer(ET.getAsOpaquePtr());
1741    ID.AddInteger(SizeMod);
1742    ID.AddInteger(TypeQuals);
1743  }
1744};
1745
1746/// VariableArrayType - This class represents C arrays with a specified size
1747/// which is not an integer-constant-expression.  For example, 'int s[x+foo()]'.
1748/// Since the size expression is an arbitrary expression, we store it as such.
1749///
1750/// Note: VariableArrayType's aren't uniqued (since the expressions aren't) and
1751/// should not be: two lexically equivalent variable array types could mean
1752/// different things, for example, these variables do not have the same type
1753/// dynamically:
1754///
1755/// void foo(int x) {
1756///   int Y[x];
1757///   ++x;
1758///   int Z[x];
1759/// }
1760///
1761class VariableArrayType : public ArrayType {
1762  /// SizeExpr - An assignment expression. VLA's are only permitted within
1763  /// a function block.
1764  Stmt *SizeExpr;
1765  /// Brackets - The left and right array brackets.
1766  SourceRange Brackets;
1767
1768  VariableArrayType(QualType et, QualType can, Expr *e,
1769                    ArraySizeModifier sm, unsigned tq,
1770                    SourceRange brackets)
1771    : ArrayType(VariableArray, et, can, sm, tq),
1772      SizeExpr((Stmt*) e), Brackets(brackets) {}
1773  friend class ASTContext;  // ASTContext creates these.
1774
1775public:
1776  Expr *getSizeExpr() const {
1777    // We use C-style casts instead of cast<> here because we do not wish
1778    // to have a dependency of Type.h on Stmt.h/Expr.h.
1779    return (Expr*) SizeExpr;
1780  }
1781  SourceRange getBracketsRange() const { return Brackets; }
1782  SourceLocation getLBracketLoc() const { return Brackets.getBegin(); }
1783  SourceLocation getRBracketLoc() const { return Brackets.getEnd(); }
1784
1785  bool isSugared() const { return false; }
1786  QualType desugar() const { return QualType(this, 0); }
1787
1788  static bool classof(const Type *T) {
1789    return T->getTypeClass() == VariableArray;
1790  }
1791  static bool classof(const VariableArrayType *) { return true; }
1792
1793  friend class StmtIteratorBase;
1794
1795  void Profile(llvm::FoldingSetNodeID &ID) {
1796    assert(0 && "Cannnot unique VariableArrayTypes.");
1797  }
1798};
1799
1800/// DependentSizedArrayType - This type represents an array type in
1801/// C++ whose size is a value-dependent expression. For example:
1802///
1803/// \code
1804/// template<typename T, int Size>
1805/// class array {
1806///   T data[Size];
1807/// };
1808/// \endcode
1809///
1810/// For these types, we won't actually know what the array bound is
1811/// until template instantiation occurs, at which point this will
1812/// become either a ConstantArrayType or a VariableArrayType.
1813class DependentSizedArrayType : public ArrayType {
1814  ASTContext &Context;
1815
1816  /// \brief An assignment expression that will instantiate to the
1817  /// size of the array.
1818  ///
1819  /// The expression itself might be NULL, in which case the array
1820  /// type will have its size deduced from an initializer.
1821  Stmt *SizeExpr;
1822
1823  /// Brackets - The left and right array brackets.
1824  SourceRange Brackets;
1825
1826  DependentSizedArrayType(ASTContext &Context, QualType et, QualType can,
1827                          Expr *e, ArraySizeModifier sm, unsigned tq,
1828                          SourceRange brackets)
1829    : ArrayType(DependentSizedArray, et, can, sm, tq),
1830      Context(Context), SizeExpr((Stmt*) e), Brackets(brackets) {}
1831  friend class ASTContext;  // ASTContext creates these.
1832
1833public:
1834  Expr *getSizeExpr() const {
1835    // We use C-style casts instead of cast<> here because we do not wish
1836    // to have a dependency of Type.h on Stmt.h/Expr.h.
1837    return (Expr*) SizeExpr;
1838  }
1839  SourceRange getBracketsRange() const { return Brackets; }
1840  SourceLocation getLBracketLoc() const { return Brackets.getBegin(); }
1841  SourceLocation getRBracketLoc() const { return Brackets.getEnd(); }
1842
1843  bool isSugared() const { return false; }
1844  QualType desugar() const { return QualType(this, 0); }
1845
1846  static bool classof(const Type *T) {
1847    return T->getTypeClass() == DependentSizedArray;
1848  }
1849  static bool classof(const DependentSizedArrayType *) { return true; }
1850
1851  friend class StmtIteratorBase;
1852
1853
1854  void Profile(llvm::FoldingSetNodeID &ID) {
1855    Profile(ID, Context, getElementType(),
1856            getSizeModifier(), getIndexTypeCVRQualifiers(), getSizeExpr());
1857  }
1858
1859  static void Profile(llvm::FoldingSetNodeID &ID, ASTContext &Context,
1860                      QualType ET, ArraySizeModifier SizeMod,
1861                      unsigned TypeQuals, Expr *E);
1862};
1863
1864/// DependentSizedExtVectorType - This type represent an extended vector type
1865/// where either the type or size is dependent. For example:
1866/// @code
1867/// template<typename T, int Size>
1868/// class vector {
1869///   typedef T __attribute__((ext_vector_type(Size))) type;
1870/// }
1871/// @endcode
1872class DependentSizedExtVectorType : public Type, public llvm::FoldingSetNode {
1873  ASTContext &Context;
1874  Expr *SizeExpr;
1875  /// ElementType - The element type of the array.
1876  QualType ElementType;
1877  SourceLocation loc;
1878
1879  DependentSizedExtVectorType(ASTContext &Context, QualType ElementType,
1880                              QualType can, Expr *SizeExpr, SourceLocation loc)
1881    : Type(DependentSizedExtVector, can, /*Dependent=*/true,
1882           ElementType->isVariablyModifiedType()),
1883      Context(Context), SizeExpr(SizeExpr), ElementType(ElementType),
1884      loc(loc) {}
1885  friend class ASTContext;
1886
1887public:
1888  Expr *getSizeExpr() const { return SizeExpr; }
1889  QualType getElementType() const { return ElementType; }
1890  SourceLocation getAttributeLoc() const { return loc; }
1891
1892  bool isSugared() const { return false; }
1893  QualType desugar() const { return QualType(this, 0); }
1894
1895  static bool classof(const Type *T) {
1896    return T->getTypeClass() == DependentSizedExtVector;
1897  }
1898  static bool classof(const DependentSizedExtVectorType *) { return true; }
1899
1900  void Profile(llvm::FoldingSetNodeID &ID) {
1901    Profile(ID, Context, getElementType(), getSizeExpr());
1902  }
1903
1904  static void Profile(llvm::FoldingSetNodeID &ID, ASTContext &Context,
1905                      QualType ElementType, Expr *SizeExpr);
1906};
1907
1908
1909/// VectorType - GCC generic vector type. This type is created using
1910/// __attribute__((vector_size(n)), where "n" specifies the vector size in
1911/// bytes; or from an Altivec __vector or vector declaration.
1912/// Since the constructor takes the number of vector elements, the
1913/// client is responsible for converting the size into the number of elements.
1914class VectorType : public Type, public llvm::FoldingSetNode {
1915public:
1916  enum VectorKind {
1917    GenericVector,  // not a target-specific vector type
1918    AltiVecVector,  // is AltiVec vector
1919    AltiVecPixel,   // is AltiVec 'vector Pixel'
1920    AltiVecBool,    // is AltiVec 'vector bool ...'
1921    NeonVector,     // is ARM Neon vector
1922    NeonPolyVector  // is ARM Neon polynomial vector
1923  };
1924protected:
1925  /// ElementType - The element type of the vector.
1926  QualType ElementType;
1927
1928  VectorType(QualType vecType, unsigned nElements, QualType canonType,
1929             VectorKind vecKind) :
1930    Type(Vector, canonType, vecType->isDependentType(),
1931         vecType->isVariablyModifiedType()), ElementType(vecType) {
1932    VectorTypeBits.VecKind = vecKind;
1933    VectorTypeBits.NumElements = nElements;
1934  }
1935
1936  VectorType(TypeClass tc, QualType vecType, unsigned nElements,
1937             QualType canonType, VectorKind vecKind)
1938    : Type(tc, canonType, vecType->isDependentType(),
1939           vecType->isVariablyModifiedType()), ElementType(vecType) {
1940    VectorTypeBits.VecKind = vecKind;
1941    VectorTypeBits.NumElements = nElements;
1942  }
1943  friend class ASTContext;  // ASTContext creates these.
1944
1945  virtual CachedProperties getCachedProperties() const;
1946
1947public:
1948
1949  QualType getElementType() const { return ElementType; }
1950  unsigned getNumElements() const { return VectorTypeBits.NumElements; }
1951
1952  bool isSugared() const { return false; }
1953  QualType desugar() const { return QualType(this, 0); }
1954
1955  VectorKind getVectorKind() const {
1956    return VectorKind(VectorTypeBits.VecKind);
1957  }
1958
1959  void Profile(llvm::FoldingSetNodeID &ID) {
1960    Profile(ID, getElementType(), getNumElements(),
1961            getTypeClass(), getVectorKind());
1962  }
1963  static void Profile(llvm::FoldingSetNodeID &ID, QualType ElementType,
1964                      unsigned NumElements, TypeClass TypeClass,
1965                      VectorKind VecKind) {
1966    ID.AddPointer(ElementType.getAsOpaquePtr());
1967    ID.AddInteger(NumElements);
1968    ID.AddInteger(TypeClass);
1969    ID.AddInteger(VecKind);
1970  }
1971
1972  static bool classof(const Type *T) {
1973    return T->getTypeClass() == Vector || T->getTypeClass() == ExtVector;
1974  }
1975  static bool classof(const VectorType *) { return true; }
1976};
1977
1978/// ExtVectorType - Extended vector type. This type is created using
1979/// __attribute__((ext_vector_type(n)), where "n" is the number of elements.
1980/// Unlike vector_size, ext_vector_type is only allowed on typedef's. This
1981/// class enables syntactic extensions, like Vector Components for accessing
1982/// points, colors, and textures (modeled after OpenGL Shading Language).
1983class ExtVectorType : public VectorType {
1984  ExtVectorType(QualType vecType, unsigned nElements, QualType canonType) :
1985    VectorType(ExtVector, vecType, nElements, canonType, GenericVector) {}
1986  friend class ASTContext;  // ASTContext creates these.
1987public:
1988  static int getPointAccessorIdx(char c) {
1989    switch (c) {
1990    default: return -1;
1991    case 'x': return 0;
1992    case 'y': return 1;
1993    case 'z': return 2;
1994    case 'w': return 3;
1995    }
1996  }
1997  static int getNumericAccessorIdx(char c) {
1998    switch (c) {
1999      default: return -1;
2000      case '0': return 0;
2001      case '1': return 1;
2002      case '2': return 2;
2003      case '3': return 3;
2004      case '4': return 4;
2005      case '5': return 5;
2006      case '6': return 6;
2007      case '7': return 7;
2008      case '8': return 8;
2009      case '9': return 9;
2010      case 'A':
2011      case 'a': return 10;
2012      case 'B':
2013      case 'b': return 11;
2014      case 'C':
2015      case 'c': return 12;
2016      case 'D':
2017      case 'd': return 13;
2018      case 'E':
2019      case 'e': return 14;
2020      case 'F':
2021      case 'f': return 15;
2022    }
2023  }
2024
2025  static int getAccessorIdx(char c) {
2026    if (int idx = getPointAccessorIdx(c)+1) return idx-1;
2027    return getNumericAccessorIdx(c);
2028  }
2029
2030  bool isAccessorWithinNumElements(char c) const {
2031    if (int idx = getAccessorIdx(c)+1)
2032      return unsigned(idx-1) < getNumElements();
2033    return false;
2034  }
2035  bool isSugared() const { return false; }
2036  QualType desugar() const { return QualType(this, 0); }
2037
2038  static bool classof(const Type *T) {
2039    return T->getTypeClass() == ExtVector;
2040  }
2041  static bool classof(const ExtVectorType *) { return true; }
2042};
2043
2044/// FunctionType - C99 6.7.5.3 - Function Declarators.  This is the common base
2045/// class of FunctionNoProtoType and FunctionProtoType.
2046///
2047class FunctionType : public Type {
2048  virtual void ANCHOR(); // Key function for FunctionType.
2049
2050  // The type returned by the function.
2051  QualType ResultType;
2052
2053 public:
2054  // This class is used for passing arround the information needed to
2055  // construct a call. It is not actually used for storage, just for
2056  // factoring together common arguments.
2057  // If you add a field (say Foo), other than the obvious places (both, constructors,
2058  // compile failures), what you need to update is
2059  // * Operetor==
2060  // * getFoo
2061  // * withFoo
2062  // * functionType. Add Foo, getFoo.
2063  // * ASTContext::getFooType
2064  // * ASTContext::mergeFunctionTypes
2065  // * FunctionNoProtoType::Profile
2066  // * FunctionProtoType::Profile
2067  // * TypePrinter::PrintFunctionProto
2068  // * AST read and write
2069  // * Codegen
2070
2071  class ExtInfo {
2072    enum { CallConvMask = 0x7 };
2073    enum { NoReturnMask = 0x8 };
2074    enum { RegParmMask = ~(CallConvMask | NoReturnMask),
2075           RegParmOffset = 4 };
2076
2077    unsigned Bits;
2078
2079    ExtInfo(unsigned Bits) : Bits(Bits) {}
2080
2081    friend class FunctionType;
2082
2083   public:
2084    // Constructor with no defaults. Use this when you know that you
2085    // have all the elements (when reading an AST file for example).
2086    ExtInfo(bool noReturn, unsigned regParm, CallingConv cc) {
2087      Bits = ((unsigned) cc) |
2088             (noReturn ? NoReturnMask : 0) |
2089             (regParm << RegParmOffset);
2090    }
2091
2092    // Constructor with all defaults. Use when for example creating a
2093    // function know to use defaults.
2094    ExtInfo() : Bits(0) {}
2095
2096    bool getNoReturn() const { return Bits & NoReturnMask; }
2097    unsigned getRegParm() const { return Bits >> RegParmOffset; }
2098    CallingConv getCC() const { return CallingConv(Bits & CallConvMask); }
2099
2100    bool operator==(ExtInfo Other) const {
2101      return Bits == Other.Bits;
2102    }
2103    bool operator!=(ExtInfo Other) const {
2104      return Bits != Other.Bits;
2105    }
2106
2107    // Note that we don't have setters. That is by design, use
2108    // the following with methods instead of mutating these objects.
2109
2110    ExtInfo withNoReturn(bool noReturn) const {
2111      if (noReturn)
2112        return ExtInfo(Bits | NoReturnMask);
2113      else
2114        return ExtInfo(Bits & ~NoReturnMask);
2115    }
2116
2117    ExtInfo withRegParm(unsigned RegParm) const {
2118      return ExtInfo((Bits & ~RegParmMask) | (RegParm << RegParmOffset));
2119    }
2120
2121    ExtInfo withCallingConv(CallingConv cc) const {
2122      return ExtInfo((Bits & ~CallConvMask) | (unsigned) cc);
2123    }
2124
2125    void Profile(llvm::FoldingSetNodeID &ID) {
2126      ID.AddInteger(Bits);
2127    }
2128  };
2129
2130protected:
2131  FunctionType(TypeClass tc, QualType res, bool SubclassInfo,
2132               unsigned typeQuals, QualType Canonical, bool Dependent,
2133               bool VariablyModified, ExtInfo Info)
2134    : Type(tc, Canonical, Dependent, VariablyModified), ResultType(res) {
2135    FunctionTypeBits.ExtInfo = Info.Bits;
2136    FunctionTypeBits.SubclassInfo = SubclassInfo;
2137    FunctionTypeBits.TypeQuals = typeQuals;
2138  }
2139  bool getSubClassData() const { return FunctionTypeBits.SubclassInfo; }
2140  unsigned getTypeQuals() const { return FunctionTypeBits.TypeQuals; }
2141public:
2142
2143  QualType getResultType() const { return ResultType; }
2144
2145  unsigned getRegParmType() const { return getExtInfo().getRegParm(); }
2146  bool getNoReturnAttr() const { return getExtInfo().getNoReturn(); }
2147  CallingConv getCallConv() const { return getExtInfo().getCC(); }
2148  ExtInfo getExtInfo() const { return ExtInfo(FunctionTypeBits.ExtInfo); }
2149
2150  /// \brief Determine the type of an expression that calls a function of
2151  /// this type.
2152  QualType getCallResultType(ASTContext &Context) const {
2153    return getResultType().getNonLValueExprType(Context);
2154  }
2155
2156  static llvm::StringRef getNameForCallConv(CallingConv CC);
2157
2158  static bool classof(const Type *T) {
2159    return T->getTypeClass() == FunctionNoProto ||
2160           T->getTypeClass() == FunctionProto;
2161  }
2162  static bool classof(const FunctionType *) { return true; }
2163};
2164
2165/// FunctionNoProtoType - Represents a K&R-style 'int foo()' function, which has
2166/// no information available about its arguments.
2167class FunctionNoProtoType : public FunctionType, public llvm::FoldingSetNode {
2168  FunctionNoProtoType(QualType Result, QualType Canonical, ExtInfo Info)
2169    : FunctionType(FunctionNoProto, Result, false, 0, Canonical,
2170                   /*Dependent=*/false, Result->isVariablyModifiedType(),
2171                   Info) {}
2172  friend class ASTContext;  // ASTContext creates these.
2173
2174protected:
2175  virtual CachedProperties getCachedProperties() const;
2176
2177public:
2178  // No additional state past what FunctionType provides.
2179
2180  bool isSugared() const { return false; }
2181  QualType desugar() const { return QualType(this, 0); }
2182
2183  void Profile(llvm::FoldingSetNodeID &ID) {
2184    Profile(ID, getResultType(), getExtInfo());
2185  }
2186  static void Profile(llvm::FoldingSetNodeID &ID, QualType ResultType,
2187                      ExtInfo Info) {
2188    Info.Profile(ID);
2189    ID.AddPointer(ResultType.getAsOpaquePtr());
2190  }
2191
2192  static bool classof(const Type *T) {
2193    return T->getTypeClass() == FunctionNoProto;
2194  }
2195  static bool classof(const FunctionNoProtoType *) { return true; }
2196};
2197
2198/// FunctionProtoType - Represents a prototype with argument type info, e.g.
2199/// 'int foo(int)' or 'int foo(void)'.  'void' is represented as having no
2200/// arguments, not as having a single void argument. Such a type can have an
2201/// exception specification, but this specification is not part of the canonical
2202/// type.
2203class FunctionProtoType : public FunctionType, public llvm::FoldingSetNode {
2204  FunctionProtoType(QualType Result, const QualType *ArgArray, unsigned numArgs,
2205                    bool isVariadic, unsigned typeQuals, bool hasExs,
2206                    bool hasAnyExs, const QualType *ExArray,
2207                    unsigned numExs, QualType Canonical,
2208                    const ExtInfo &Info);
2209
2210  /// NumArgs - The number of arguments this function has, not counting '...'.
2211  unsigned NumArgs : 20;
2212
2213  /// NumExceptions - The number of types in the exception spec, if any.
2214  unsigned NumExceptions : 10;
2215
2216  /// HasExceptionSpec - Whether this function has an exception spec at all.
2217  bool HasExceptionSpec : 1;
2218
2219  /// AnyExceptionSpec - Whether this function has a throw(...) spec.
2220  bool AnyExceptionSpec : 1;
2221
2222  /// ArgInfo - There is an variable size array after the class in memory that
2223  /// holds the argument types.
2224
2225  /// Exceptions - There is another variable size array after ArgInfo that
2226  /// holds the exception types.
2227
2228  friend class ASTContext;  // ASTContext creates these.
2229
2230protected:
2231  virtual CachedProperties getCachedProperties() const;
2232
2233public:
2234  unsigned getNumArgs() const { return NumArgs; }
2235  QualType getArgType(unsigned i) const {
2236    assert(i < NumArgs && "Invalid argument number!");
2237    return arg_type_begin()[i];
2238  }
2239
2240  bool hasExceptionSpec() const { return HasExceptionSpec; }
2241  bool hasAnyExceptionSpec() const { return AnyExceptionSpec; }
2242  unsigned getNumExceptions() const { return NumExceptions; }
2243  QualType getExceptionType(unsigned i) const {
2244    assert(i < NumExceptions && "Invalid exception number!");
2245    return exception_begin()[i];
2246  }
2247  bool hasEmptyExceptionSpec() const {
2248    return hasExceptionSpec() && !hasAnyExceptionSpec() &&
2249      getNumExceptions() == 0;
2250  }
2251
2252  bool isVariadic() const { return getSubClassData(); }
2253  unsigned getTypeQuals() const { return FunctionType::getTypeQuals(); }
2254
2255  typedef const QualType *arg_type_iterator;
2256  arg_type_iterator arg_type_begin() const {
2257    return reinterpret_cast<const QualType *>(this+1);
2258  }
2259  arg_type_iterator arg_type_end() const { return arg_type_begin()+NumArgs; }
2260
2261  typedef const QualType *exception_iterator;
2262  exception_iterator exception_begin() const {
2263    // exceptions begin where arguments end
2264    return arg_type_end();
2265  }
2266  exception_iterator exception_end() const {
2267    return exception_begin() + NumExceptions;
2268  }
2269
2270  bool isSugared() const { return false; }
2271  QualType desugar() const { return QualType(this, 0); }
2272
2273  static bool classof(const Type *T) {
2274    return T->getTypeClass() == FunctionProto;
2275  }
2276  static bool classof(const FunctionProtoType *) { return true; }
2277
2278  void Profile(llvm::FoldingSetNodeID &ID);
2279  static void Profile(llvm::FoldingSetNodeID &ID, QualType Result,
2280                      arg_type_iterator ArgTys, unsigned NumArgs,
2281                      bool isVariadic, unsigned TypeQuals,
2282                      bool hasExceptionSpec, bool anyExceptionSpec,
2283                      unsigned NumExceptions, exception_iterator Exs,
2284                      ExtInfo ExtInfo);
2285};
2286
2287
2288/// \brief Represents the dependent type named by a dependently-scoped
2289/// typename using declaration, e.g.
2290///   using typename Base<T>::foo;
2291/// Template instantiation turns these into the underlying type.
2292class UnresolvedUsingType : public Type {
2293  UnresolvedUsingTypenameDecl *Decl;
2294
2295  UnresolvedUsingType(const UnresolvedUsingTypenameDecl *D)
2296    : Type(UnresolvedUsing, QualType(), true, false),
2297      Decl(const_cast<UnresolvedUsingTypenameDecl*>(D)) {}
2298  friend class ASTContext; // ASTContext creates these.
2299public:
2300
2301  UnresolvedUsingTypenameDecl *getDecl() const { return Decl; }
2302
2303  bool isSugared() const { return false; }
2304  QualType desugar() const { return QualType(this, 0); }
2305
2306  static bool classof(const Type *T) {
2307    return T->getTypeClass() == UnresolvedUsing;
2308  }
2309  static bool classof(const UnresolvedUsingType *) { return true; }
2310
2311  void Profile(llvm::FoldingSetNodeID &ID) {
2312    return Profile(ID, Decl);
2313  }
2314  static void Profile(llvm::FoldingSetNodeID &ID,
2315                      UnresolvedUsingTypenameDecl *D) {
2316    ID.AddPointer(D);
2317  }
2318};
2319
2320
2321class TypedefType : public Type {
2322  TypedefDecl *Decl;
2323protected:
2324  TypedefType(TypeClass tc, const TypedefDecl *D, QualType can)
2325    : Type(tc, can, can->isDependentType(), can->isVariablyModifiedType()),
2326      Decl(const_cast<TypedefDecl*>(D)) {
2327    assert(!isa<TypedefType>(can) && "Invalid canonical type");
2328  }
2329  friend class ASTContext;  // ASTContext creates these.
2330public:
2331
2332  TypedefDecl *getDecl() const { return Decl; }
2333
2334  /// LookThroughTypedefs - Return the ultimate type this typedef corresponds to
2335  /// potentially looking through *all* consecutive typedefs.  This returns the
2336  /// sum of the type qualifiers, so if you have:
2337  ///   typedef const int A;
2338  ///   typedef volatile A B;
2339  /// looking through the typedefs for B will give you "const volatile A".
2340  QualType LookThroughTypedefs() const;
2341
2342  bool isSugared() const { return true; }
2343  QualType desugar() const;
2344
2345  static bool classof(const Type *T) { return T->getTypeClass() == Typedef; }
2346  static bool classof(const TypedefType *) { return true; }
2347};
2348
2349/// TypeOfExprType (GCC extension).
2350class TypeOfExprType : public Type {
2351  Expr *TOExpr;
2352
2353protected:
2354  TypeOfExprType(Expr *E, QualType can = QualType());
2355  friend class ASTContext;  // ASTContext creates these.
2356public:
2357  Expr *getUnderlyingExpr() const { return TOExpr; }
2358
2359  /// \brief Remove a single level of sugar.
2360  QualType desugar() const;
2361
2362  /// \brief Returns whether this type directly provides sugar.
2363  bool isSugared() const { return true; }
2364
2365  static bool classof(const Type *T) { return T->getTypeClass() == TypeOfExpr; }
2366  static bool classof(const TypeOfExprType *) { return true; }
2367};
2368
2369/// \brief Internal representation of canonical, dependent
2370/// typeof(expr) types.
2371///
2372/// This class is used internally by the ASTContext to manage
2373/// canonical, dependent types, only. Clients will only see instances
2374/// of this class via TypeOfExprType nodes.
2375class DependentTypeOfExprType
2376  : public TypeOfExprType, public llvm::FoldingSetNode {
2377  ASTContext &Context;
2378
2379public:
2380  DependentTypeOfExprType(ASTContext &Context, Expr *E)
2381    : TypeOfExprType(E), Context(Context) { }
2382
2383  bool isSugared() const { return false; }
2384  QualType desugar() const { return QualType(this, 0); }
2385
2386  void Profile(llvm::FoldingSetNodeID &ID) {
2387    Profile(ID, Context, getUnderlyingExpr());
2388  }
2389
2390  static void Profile(llvm::FoldingSetNodeID &ID, ASTContext &Context,
2391                      Expr *E);
2392};
2393
2394/// TypeOfType (GCC extension).
2395class TypeOfType : public Type {
2396  QualType TOType;
2397  TypeOfType(QualType T, QualType can)
2398    : Type(TypeOf, can, T->isDependentType(), T->isVariablyModifiedType()),
2399      TOType(T) {
2400    assert(!isa<TypedefType>(can) && "Invalid canonical type");
2401  }
2402  friend class ASTContext;  // ASTContext creates these.
2403public:
2404  QualType getUnderlyingType() const { return TOType; }
2405
2406  /// \brief Remove a single level of sugar.
2407  QualType desugar() const { return getUnderlyingType(); }
2408
2409  /// \brief Returns whether this type directly provides sugar.
2410  bool isSugared() const { return true; }
2411
2412  static bool classof(const Type *T) { return T->getTypeClass() == TypeOf; }
2413  static bool classof(const TypeOfType *) { return true; }
2414};
2415
2416/// DecltypeType (C++0x)
2417class DecltypeType : public Type {
2418  Expr *E;
2419
2420  // FIXME: We could get rid of UnderlyingType if we wanted to: We would have to
2421  // Move getDesugaredType to ASTContext so that it can call getDecltypeForExpr
2422  // from it.
2423  QualType UnderlyingType;
2424
2425protected:
2426  DecltypeType(Expr *E, QualType underlyingType, QualType can = QualType());
2427  friend class ASTContext;  // ASTContext creates these.
2428public:
2429  Expr *getUnderlyingExpr() const { return E; }
2430  QualType getUnderlyingType() const { return UnderlyingType; }
2431
2432  /// \brief Remove a single level of sugar.
2433  QualType desugar() const { return getUnderlyingType(); }
2434
2435  /// \brief Returns whether this type directly provides sugar.
2436  bool isSugared() const { return !isDependentType(); }
2437
2438  static bool classof(const Type *T) { return T->getTypeClass() == Decltype; }
2439  static bool classof(const DecltypeType *) { return true; }
2440};
2441
2442/// \brief Internal representation of canonical, dependent
2443/// decltype(expr) types.
2444///
2445/// This class is used internally by the ASTContext to manage
2446/// canonical, dependent types, only. Clients will only see instances
2447/// of this class via DecltypeType nodes.
2448class DependentDecltypeType : public DecltypeType, public llvm::FoldingSetNode {
2449  ASTContext &Context;
2450
2451public:
2452  DependentDecltypeType(ASTContext &Context, Expr *E);
2453
2454  bool isSugared() const { return false; }
2455  QualType desugar() const { return QualType(this, 0); }
2456
2457  void Profile(llvm::FoldingSetNodeID &ID) {
2458    Profile(ID, Context, getUnderlyingExpr());
2459  }
2460
2461  static void Profile(llvm::FoldingSetNodeID &ID, ASTContext &Context,
2462                      Expr *E);
2463};
2464
2465class TagType : public Type {
2466  /// Stores the TagDecl associated with this type. The decl may point to any
2467  /// TagDecl that declares the entity.
2468  TagDecl * decl;
2469
2470protected:
2471  TagType(TypeClass TC, const TagDecl *D, QualType can);
2472
2473  virtual CachedProperties getCachedProperties() const;
2474
2475public:
2476  TagDecl *getDecl() const;
2477
2478  /// @brief Determines whether this type is in the process of being
2479  /// defined.
2480  bool isBeingDefined() const;
2481
2482  static bool classof(const Type *T) {
2483    return T->getTypeClass() >= TagFirst && T->getTypeClass() <= TagLast;
2484  }
2485  static bool classof(const TagType *) { return true; }
2486  static bool classof(const RecordType *) { return true; }
2487  static bool classof(const EnumType *) { return true; }
2488};
2489
2490/// RecordType - This is a helper class that allows the use of isa/cast/dyncast
2491/// to detect TagType objects of structs/unions/classes.
2492class RecordType : public TagType {
2493protected:
2494  explicit RecordType(const RecordDecl *D)
2495    : TagType(Record, reinterpret_cast<const TagDecl*>(D), QualType()) { }
2496  explicit RecordType(TypeClass TC, RecordDecl *D)
2497    : TagType(TC, reinterpret_cast<const TagDecl*>(D), QualType()) { }
2498  friend class ASTContext;   // ASTContext creates these.
2499public:
2500
2501  RecordDecl *getDecl() const {
2502    return reinterpret_cast<RecordDecl*>(TagType::getDecl());
2503  }
2504
2505  // FIXME: This predicate is a helper to QualType/Type. It needs to
2506  // recursively check all fields for const-ness. If any field is declared
2507  // const, it needs to return false.
2508  bool hasConstFields() const { return false; }
2509
2510  // FIXME: RecordType needs to check when it is created that all fields are in
2511  // the same address space, and return that.
2512  unsigned getAddressSpace() const { return 0; }
2513
2514  bool isSugared() const { return false; }
2515  QualType desugar() const { return QualType(this, 0); }
2516
2517  static bool classof(const TagType *T);
2518  static bool classof(const Type *T) {
2519    return isa<TagType>(T) && classof(cast<TagType>(T));
2520  }
2521  static bool classof(const RecordType *) { return true; }
2522};
2523
2524/// EnumType - This is a helper class that allows the use of isa/cast/dyncast
2525/// to detect TagType objects of enums.
2526class EnumType : public TagType {
2527  explicit EnumType(const EnumDecl *D)
2528    : TagType(Enum, reinterpret_cast<const TagDecl*>(D), QualType()) { }
2529  friend class ASTContext;   // ASTContext creates these.
2530public:
2531
2532  EnumDecl *getDecl() const {
2533    return reinterpret_cast<EnumDecl*>(TagType::getDecl());
2534  }
2535
2536  bool isSugared() const { return false; }
2537  QualType desugar() const { return QualType(this, 0); }
2538
2539  static bool classof(const TagType *T);
2540  static bool classof(const Type *T) {
2541    return isa<TagType>(T) && classof(cast<TagType>(T));
2542  }
2543  static bool classof(const EnumType *) { return true; }
2544};
2545
2546class TemplateTypeParmType : public Type, public llvm::FoldingSetNode {
2547  unsigned Depth : 15;
2548  unsigned ParameterPack : 1;
2549  unsigned Index : 16;
2550  IdentifierInfo *Name;
2551
2552  TemplateTypeParmType(unsigned D, unsigned I, bool PP, IdentifierInfo *N,
2553                       QualType Canon)
2554    : Type(TemplateTypeParm, Canon, /*Dependent=*/true,
2555           /*VariablyModified=*/false),
2556      Depth(D), ParameterPack(PP), Index(I), Name(N) { }
2557
2558  TemplateTypeParmType(unsigned D, unsigned I, bool PP)
2559    : Type(TemplateTypeParm, QualType(this, 0), /*Dependent=*/true,
2560           /*VariablyModified=*/false),
2561      Depth(D), ParameterPack(PP), Index(I), Name(0) { }
2562
2563  friend class ASTContext;  // ASTContext creates these
2564
2565public:
2566  unsigned getDepth() const { return Depth; }
2567  unsigned getIndex() const { return Index; }
2568  bool isParameterPack() const { return ParameterPack; }
2569  IdentifierInfo *getName() const { return Name; }
2570
2571  bool isSugared() const { return false; }
2572  QualType desugar() const { return QualType(this, 0); }
2573
2574  void Profile(llvm::FoldingSetNodeID &ID) {
2575    Profile(ID, Depth, Index, ParameterPack, Name);
2576  }
2577
2578  static void Profile(llvm::FoldingSetNodeID &ID, unsigned Depth,
2579                      unsigned Index, bool ParameterPack,
2580                      IdentifierInfo *Name) {
2581    ID.AddInteger(Depth);
2582    ID.AddInteger(Index);
2583    ID.AddBoolean(ParameterPack);
2584    ID.AddPointer(Name);
2585  }
2586
2587  static bool classof(const Type *T) {
2588    return T->getTypeClass() == TemplateTypeParm;
2589  }
2590  static bool classof(const TemplateTypeParmType *T) { return true; }
2591};
2592
2593/// \brief Represents the result of substituting a type for a template
2594/// type parameter.
2595///
2596/// Within an instantiated template, all template type parameters have
2597/// been replaced with these.  They are used solely to record that a
2598/// type was originally written as a template type parameter;
2599/// therefore they are never canonical.
2600class SubstTemplateTypeParmType : public Type, public llvm::FoldingSetNode {
2601  // The original type parameter.
2602  const TemplateTypeParmType *Replaced;
2603
2604  SubstTemplateTypeParmType(const TemplateTypeParmType *Param, QualType Canon)
2605    : Type(SubstTemplateTypeParm, Canon, Canon->isDependentType(),
2606           Canon->isVariablyModifiedType()),
2607      Replaced(Param) { }
2608
2609  friend class ASTContext;
2610
2611public:
2612  IdentifierInfo *getName() const { return Replaced->getName(); }
2613
2614  /// Gets the template parameter that was substituted for.
2615  const TemplateTypeParmType *getReplacedParameter() const {
2616    return Replaced;
2617  }
2618
2619  /// Gets the type that was substituted for the template
2620  /// parameter.
2621  QualType getReplacementType() const {
2622    return getCanonicalTypeInternal();
2623  }
2624
2625  bool isSugared() const { return true; }
2626  QualType desugar() const { return getReplacementType(); }
2627
2628  void Profile(llvm::FoldingSetNodeID &ID) {
2629    Profile(ID, getReplacedParameter(), getReplacementType());
2630  }
2631  static void Profile(llvm::FoldingSetNodeID &ID,
2632                      const TemplateTypeParmType *Replaced,
2633                      QualType Replacement) {
2634    ID.AddPointer(Replaced);
2635    ID.AddPointer(Replacement.getAsOpaquePtr());
2636  }
2637
2638  static bool classof(const Type *T) {
2639    return T->getTypeClass() == SubstTemplateTypeParm;
2640  }
2641  static bool classof(const SubstTemplateTypeParmType *T) { return true; }
2642};
2643
2644/// \brief Represents the type of a template specialization as written
2645/// in the source code.
2646///
2647/// Template specialization types represent the syntactic form of a
2648/// template-id that refers to a type, e.g., @c vector<int>. Some
2649/// template specialization types are syntactic sugar, whose canonical
2650/// type will point to some other type node that represents the
2651/// instantiation or class template specialization. For example, a
2652/// class template specialization type of @c vector<int> will refer to
2653/// a tag type for the instantiation
2654/// @c std::vector<int, std::allocator<int>>.
2655///
2656/// Other template specialization types, for which the template name
2657/// is dependent, may be canonical types. These types are always
2658/// dependent.
2659class TemplateSpecializationType
2660  : public Type, public llvm::FoldingSetNode {
2661  /// \brief The name of the template being specialized.
2662  TemplateName Template;
2663
2664  /// \brief - The number of template arguments named in this class
2665  /// template specialization.
2666  unsigned NumArgs;
2667
2668  TemplateSpecializationType(TemplateName T,
2669                             const TemplateArgument *Args,
2670                             unsigned NumArgs, QualType Canon);
2671
2672  friend class ASTContext;  // ASTContext creates these
2673
2674public:
2675  /// \brief Determine whether any of the given template arguments are
2676  /// dependent.
2677  static bool anyDependentTemplateArguments(const TemplateArgument *Args,
2678                                            unsigned NumArgs);
2679
2680  static bool anyDependentTemplateArguments(const TemplateArgumentLoc *Args,
2681                                            unsigned NumArgs);
2682
2683  static bool anyDependentTemplateArguments(const TemplateArgumentListInfo &);
2684
2685  /// \brief Print a template argument list, including the '<' and '>'
2686  /// enclosing the template arguments.
2687  static std::string PrintTemplateArgumentList(const TemplateArgument *Args,
2688                                               unsigned NumArgs,
2689                                               const PrintingPolicy &Policy);
2690
2691  static std::string PrintTemplateArgumentList(const TemplateArgumentLoc *Args,
2692                                               unsigned NumArgs,
2693                                               const PrintingPolicy &Policy);
2694
2695  static std::string PrintTemplateArgumentList(const TemplateArgumentListInfo &,
2696                                               const PrintingPolicy &Policy);
2697
2698  /// True if this template specialization type matches a current
2699  /// instantiation in the context in which it is found.
2700  bool isCurrentInstantiation() const {
2701    return isa<InjectedClassNameType>(getCanonicalTypeInternal());
2702  }
2703
2704  typedef const TemplateArgument * iterator;
2705
2706  iterator begin() const { return getArgs(); }
2707  iterator end() const; // defined inline in TemplateBase.h
2708
2709  /// \brief Retrieve the name of the template that we are specializing.
2710  TemplateName getTemplateName() const { return Template; }
2711
2712  /// \brief Retrieve the template arguments.
2713  const TemplateArgument *getArgs() const {
2714    return reinterpret_cast<const TemplateArgument *>(this + 1);
2715  }
2716
2717  /// \brief Retrieve the number of template arguments.
2718  unsigned getNumArgs() const { return NumArgs; }
2719
2720  /// \brief Retrieve a specific template argument as a type.
2721  /// \precondition @c isArgType(Arg)
2722  const TemplateArgument &getArg(unsigned Idx) const; // in TemplateBase.h
2723
2724  bool isSugared() const {
2725    return !isDependentType() || isCurrentInstantiation();
2726  }
2727  QualType desugar() const { return getCanonicalTypeInternal(); }
2728
2729  void Profile(llvm::FoldingSetNodeID &ID, ASTContext &Ctx) {
2730    Profile(ID, Template, getArgs(), NumArgs, Ctx);
2731  }
2732
2733  static void Profile(llvm::FoldingSetNodeID &ID, TemplateName T,
2734                      const TemplateArgument *Args,
2735                      unsigned NumArgs,
2736                      ASTContext &Context);
2737
2738  static bool classof(const Type *T) {
2739    return T->getTypeClass() == TemplateSpecialization;
2740  }
2741  static bool classof(const TemplateSpecializationType *T) { return true; }
2742};
2743
2744/// \brief The injected class name of a C++ class template or class
2745/// template partial specialization.  Used to record that a type was
2746/// spelled with a bare identifier rather than as a template-id; the
2747/// equivalent for non-templated classes is just RecordType.
2748///
2749/// Injected class name types are always dependent.  Template
2750/// instantiation turns these into RecordTypes.
2751///
2752/// Injected class name types are always canonical.  This works
2753/// because it is impossible to compare an injected class name type
2754/// with the corresponding non-injected template type, for the same
2755/// reason that it is impossible to directly compare template
2756/// parameters from different dependent contexts: injected class name
2757/// types can only occur within the scope of a particular templated
2758/// declaration, and within that scope every template specialization
2759/// will canonicalize to the injected class name (when appropriate
2760/// according to the rules of the language).
2761class InjectedClassNameType : public Type {
2762  CXXRecordDecl *Decl;
2763
2764  /// The template specialization which this type represents.
2765  /// For example, in
2766  ///   template <class T> class A { ... };
2767  /// this is A<T>, whereas in
2768  ///   template <class X, class Y> class A<B<X,Y> > { ... };
2769  /// this is A<B<X,Y> >.
2770  ///
2771  /// It is always unqualified, always a template specialization type,
2772  /// and always dependent.
2773  QualType InjectedType;
2774
2775  friend class ASTContext; // ASTContext creates these.
2776  friend class ASTReader; // FIXME: ASTContext::getInjectedClassNameType is not
2777                          // currently suitable for AST reading, too much
2778                          // interdependencies.
2779  InjectedClassNameType(CXXRecordDecl *D, QualType TST)
2780    : Type(InjectedClassName, QualType(), /*Dependent=*/true,
2781           /*VariablyModified=*/false),
2782      Decl(D), InjectedType(TST) {
2783    assert(isa<TemplateSpecializationType>(TST));
2784    assert(!TST.hasQualifiers());
2785    assert(TST->isDependentType());
2786  }
2787
2788public:
2789  QualType getInjectedSpecializationType() const { return InjectedType; }
2790  const TemplateSpecializationType *getInjectedTST() const {
2791    return cast<TemplateSpecializationType>(InjectedType.getTypePtr());
2792  }
2793
2794  CXXRecordDecl *getDecl() const;
2795
2796  bool isSugared() const { return false; }
2797  QualType desugar() const { return QualType(this, 0); }
2798
2799  static bool classof(const Type *T) {
2800    return T->getTypeClass() == InjectedClassName;
2801  }
2802  static bool classof(const InjectedClassNameType *T) { return true; }
2803};
2804
2805/// \brief The kind of a tag type.
2806enum TagTypeKind {
2807  /// \brief The "struct" keyword.
2808  TTK_Struct,
2809  /// \brief The "union" keyword.
2810  TTK_Union,
2811  /// \brief The "class" keyword.
2812  TTK_Class,
2813  /// \brief The "enum" keyword.
2814  TTK_Enum
2815};
2816
2817/// \brief The elaboration keyword that precedes a qualified type name or
2818/// introduces an elaborated-type-specifier.
2819enum ElaboratedTypeKeyword {
2820  /// \brief The "struct" keyword introduces the elaborated-type-specifier.
2821  ETK_Struct,
2822  /// \brief The "union" keyword introduces the elaborated-type-specifier.
2823  ETK_Union,
2824  /// \brief The "class" keyword introduces the elaborated-type-specifier.
2825  ETK_Class,
2826  /// \brief The "enum" keyword introduces the elaborated-type-specifier.
2827  ETK_Enum,
2828  /// \brief The "typename" keyword precedes the qualified type name, e.g.,
2829  /// \c typename T::type.
2830  ETK_Typename,
2831  /// \brief No keyword precedes the qualified type name.
2832  ETK_None
2833};
2834
2835/// A helper class for Type nodes having an ElaboratedTypeKeyword.
2836/// The keyword in stored in the free bits of the base class.
2837/// Also provides a few static helpers for converting and printing
2838/// elaborated type keyword and tag type kind enumerations.
2839class TypeWithKeyword : public Type {
2840protected:
2841  TypeWithKeyword(ElaboratedTypeKeyword Keyword, TypeClass tc,
2842                  QualType Canonical, bool Dependent, bool VariablyModified)
2843    : Type(tc, Canonical, Dependent, VariablyModified) {
2844    TypeWithKeywordBits.Keyword = Keyword;
2845  }
2846
2847public:
2848  virtual ~TypeWithKeyword(); // pin vtable to Type.cpp
2849
2850  ElaboratedTypeKeyword getKeyword() const {
2851    return static_cast<ElaboratedTypeKeyword>(TypeWithKeywordBits.Keyword);
2852  }
2853
2854  /// getKeywordForTypeSpec - Converts a type specifier (DeclSpec::TST)
2855  /// into an elaborated type keyword.
2856  static ElaboratedTypeKeyword getKeywordForTypeSpec(unsigned TypeSpec);
2857
2858  /// getTagTypeKindForTypeSpec - Converts a type specifier (DeclSpec::TST)
2859  /// into a tag type kind.  It is an error to provide a type specifier
2860  /// which *isn't* a tag kind here.
2861  static TagTypeKind getTagTypeKindForTypeSpec(unsigned TypeSpec);
2862
2863  /// getKeywordForTagDeclKind - Converts a TagTypeKind into an
2864  /// elaborated type keyword.
2865  static ElaboratedTypeKeyword getKeywordForTagTypeKind(TagTypeKind Tag);
2866
2867  /// getTagTypeKindForKeyword - Converts an elaborated type keyword into
2868  // a TagTypeKind. It is an error to provide an elaborated type keyword
2869  /// which *isn't* a tag kind here.
2870  static TagTypeKind getTagTypeKindForKeyword(ElaboratedTypeKeyword Keyword);
2871
2872  static bool KeywordIsTagTypeKind(ElaboratedTypeKeyword Keyword);
2873
2874  static const char *getKeywordName(ElaboratedTypeKeyword Keyword);
2875
2876  static const char *getTagTypeKindName(TagTypeKind Kind) {
2877    return getKeywordName(getKeywordForTagTypeKind(Kind));
2878  }
2879
2880  class CannotCastToThisType {};
2881  static CannotCastToThisType classof(const Type *);
2882};
2883
2884/// \brief Represents a type that was referred to using an elaborated type
2885/// keyword, e.g., struct S, or via a qualified name, e.g., N::M::type,
2886/// or both.
2887///
2888/// This type is used to keep track of a type name as written in the
2889/// source code, including tag keywords and any nested-name-specifiers.
2890/// The type itself is always "sugar", used to express what was written
2891/// in the source code but containing no additional semantic information.
2892class ElaboratedType : public TypeWithKeyword, public llvm::FoldingSetNode {
2893
2894  /// \brief The nested name specifier containing the qualifier.
2895  NestedNameSpecifier *NNS;
2896
2897  /// \brief The type that this qualified name refers to.
2898  QualType NamedType;
2899
2900  ElaboratedType(ElaboratedTypeKeyword Keyword, NestedNameSpecifier *NNS,
2901                 QualType NamedType, QualType CanonType)
2902    : TypeWithKeyword(Keyword, Elaborated, CanonType,
2903                      NamedType->isDependentType(),
2904                      NamedType->isVariablyModifiedType()),
2905      NNS(NNS), NamedType(NamedType) {
2906    assert(!(Keyword == ETK_None && NNS == 0) &&
2907           "ElaboratedType cannot have elaborated type keyword "
2908           "and name qualifier both null.");
2909  }
2910
2911  friend class ASTContext;  // ASTContext creates these
2912
2913public:
2914  ~ElaboratedType();
2915
2916  /// \brief Retrieve the qualification on this type.
2917  NestedNameSpecifier *getQualifier() const { return NNS; }
2918
2919  /// \brief Retrieve the type named by the qualified-id.
2920  QualType getNamedType() const { return NamedType; }
2921
2922  /// \brief Remove a single level of sugar.
2923  QualType desugar() const { return getNamedType(); }
2924
2925  /// \brief Returns whether this type directly provides sugar.
2926  bool isSugared() const { return true; }
2927
2928  void Profile(llvm::FoldingSetNodeID &ID) {
2929    Profile(ID, getKeyword(), NNS, NamedType);
2930  }
2931
2932  static void Profile(llvm::FoldingSetNodeID &ID, ElaboratedTypeKeyword Keyword,
2933                      NestedNameSpecifier *NNS, QualType NamedType) {
2934    ID.AddInteger(Keyword);
2935    ID.AddPointer(NNS);
2936    NamedType.Profile(ID);
2937  }
2938
2939  static bool classof(const Type *T) {
2940    return T->getTypeClass() == Elaborated;
2941  }
2942  static bool classof(const ElaboratedType *T) { return true; }
2943};
2944
2945/// \brief Represents a qualified type name for which the type name is
2946/// dependent.
2947///
2948/// DependentNameType represents a class of dependent types that involve a
2949/// dependent nested-name-specifier (e.g., "T::") followed by a (dependent)
2950/// name of a type. The DependentNameType may start with a "typename" (for a
2951/// typename-specifier), "class", "struct", "union", or "enum" (for a
2952/// dependent elaborated-type-specifier), or nothing (in contexts where we
2953/// know that we must be referring to a type, e.g., in a base class specifier).
2954class DependentNameType : public TypeWithKeyword, public llvm::FoldingSetNode {
2955
2956  /// \brief The nested name specifier containing the qualifier.
2957  NestedNameSpecifier *NNS;
2958
2959  /// \brief The type that this typename specifier refers to.
2960  const IdentifierInfo *Name;
2961
2962  DependentNameType(ElaboratedTypeKeyword Keyword, NestedNameSpecifier *NNS,
2963                    const IdentifierInfo *Name, QualType CanonType)
2964    : TypeWithKeyword(Keyword, DependentName, CanonType, /*Dependent=*/true,
2965                      /*VariablyModified=*/false),
2966      NNS(NNS), Name(Name) {
2967    assert(NNS->isDependent() &&
2968           "DependentNameType requires a dependent nested-name-specifier");
2969  }
2970
2971  friend class ASTContext;  // ASTContext creates these
2972
2973public:
2974  virtual ~DependentNameType();
2975
2976  /// \brief Retrieve the qualification on this type.
2977  NestedNameSpecifier *getQualifier() const { return NNS; }
2978
2979  /// \brief Retrieve the type named by the typename specifier as an
2980  /// identifier.
2981  ///
2982  /// This routine will return a non-NULL identifier pointer when the
2983  /// form of the original typename was terminated by an identifier,
2984  /// e.g., "typename T::type".
2985  const IdentifierInfo *getIdentifier() const {
2986    return Name;
2987  }
2988
2989  bool isSugared() const { return false; }
2990  QualType desugar() const { return QualType(this, 0); }
2991
2992  void Profile(llvm::FoldingSetNodeID &ID) {
2993    Profile(ID, getKeyword(), NNS, Name);
2994  }
2995
2996  static void Profile(llvm::FoldingSetNodeID &ID, ElaboratedTypeKeyword Keyword,
2997                      NestedNameSpecifier *NNS, const IdentifierInfo *Name) {
2998    ID.AddInteger(Keyword);
2999    ID.AddPointer(NNS);
3000    ID.AddPointer(Name);
3001  }
3002
3003  static bool classof(const Type *T) {
3004    return T->getTypeClass() == DependentName;
3005  }
3006  static bool classof(const DependentNameType *T) { return true; }
3007};
3008
3009/// DependentTemplateSpecializationType - Represents a template
3010/// specialization type whose template cannot be resolved, e.g.
3011///   A<T>::template B<T>
3012class DependentTemplateSpecializationType :
3013  public TypeWithKeyword, public llvm::FoldingSetNode {
3014
3015  /// \brief The nested name specifier containing the qualifier.
3016  NestedNameSpecifier *NNS;
3017
3018  /// \brief The identifier of the template.
3019  const IdentifierInfo *Name;
3020
3021  /// \brief - The number of template arguments named in this class
3022  /// template specialization.
3023  unsigned NumArgs;
3024
3025  const TemplateArgument *getArgBuffer() const {
3026    return reinterpret_cast<const TemplateArgument*>(this+1);
3027  }
3028  TemplateArgument *getArgBuffer() {
3029    return reinterpret_cast<TemplateArgument*>(this+1);
3030  }
3031
3032  DependentTemplateSpecializationType(ElaboratedTypeKeyword Keyword,
3033                                      NestedNameSpecifier *NNS,
3034                                      const IdentifierInfo *Name,
3035                                      unsigned NumArgs,
3036                                      const TemplateArgument *Args,
3037                                      QualType Canon);
3038
3039  friend class ASTContext;  // ASTContext creates these
3040
3041public:
3042  virtual ~DependentTemplateSpecializationType();
3043
3044  NestedNameSpecifier *getQualifier() const { return NNS; }
3045  const IdentifierInfo *getIdentifier() const { return Name; }
3046
3047  /// \brief Retrieve the template arguments.
3048  const TemplateArgument *getArgs() const {
3049    return getArgBuffer();
3050  }
3051
3052  /// \brief Retrieve the number of template arguments.
3053  unsigned getNumArgs() const { return NumArgs; }
3054
3055  const TemplateArgument &getArg(unsigned Idx) const; // in TemplateBase.h
3056
3057  typedef const TemplateArgument * iterator;
3058  iterator begin() const { return getArgs(); }
3059  iterator end() const; // inline in TemplateBase.h
3060
3061  bool isSugared() const { return false; }
3062  QualType desugar() const { return QualType(this, 0); }
3063
3064  void Profile(llvm::FoldingSetNodeID &ID, ASTContext &Context) {
3065    Profile(ID, Context, getKeyword(), NNS, Name, NumArgs, getArgs());
3066  }
3067
3068  static void Profile(llvm::FoldingSetNodeID &ID,
3069                      ASTContext &Context,
3070                      ElaboratedTypeKeyword Keyword,
3071                      NestedNameSpecifier *Qualifier,
3072                      const IdentifierInfo *Name,
3073                      unsigned NumArgs,
3074                      const TemplateArgument *Args);
3075
3076  static bool classof(const Type *T) {
3077    return T->getTypeClass() == DependentTemplateSpecialization;
3078  }
3079  static bool classof(const DependentTemplateSpecializationType *T) {
3080    return true;
3081  }
3082};
3083
3084/// ObjCObjectType - Represents a class type in Objective C.
3085/// Every Objective C type is a combination of a base type and a
3086/// list of protocols.
3087///
3088/// Given the following declarations:
3089///   @class C;
3090///   @protocol P;
3091///
3092/// 'C' is an ObjCInterfaceType C.  It is sugar for an ObjCObjectType
3093/// with base C and no protocols.
3094///
3095/// 'C<P>' is an ObjCObjectType with base C and protocol list [P].
3096///
3097/// 'id' is a TypedefType which is sugar for an ObjCPointerType whose
3098/// pointee is an ObjCObjectType with base BuiltinType::ObjCIdType
3099/// and no protocols.
3100///
3101/// 'id<P>' is an ObjCPointerType whose pointee is an ObjCObjecType
3102/// with base BuiltinType::ObjCIdType and protocol list [P].  Eventually
3103/// this should get its own sugar class to better represent the source.
3104class ObjCObjectType : public Type {
3105  // ObjCObjectType.NumProtocols - the number of protocols stored
3106  // after the ObjCObjectPointerType node.
3107  //
3108  // These protocols are those written directly on the type.  If
3109  // protocol qualifiers ever become additive, the iterators will need
3110  // to get kindof complicated.
3111  //
3112  // In the canonical object type, these are sorted alphabetically
3113  // and uniqued.
3114
3115  /// Either a BuiltinType or an InterfaceType or sugar for either.
3116  QualType BaseType;
3117
3118  ObjCProtocolDecl * const *getProtocolStorage() const {
3119    return const_cast<ObjCObjectType*>(this)->getProtocolStorage();
3120  }
3121
3122  ObjCProtocolDecl **getProtocolStorage();
3123
3124protected:
3125  ObjCObjectType(QualType Canonical, QualType Base,
3126                 ObjCProtocolDecl * const *Protocols, unsigned NumProtocols);
3127
3128  enum Nonce_ObjCInterface { Nonce_ObjCInterface };
3129  ObjCObjectType(enum Nonce_ObjCInterface)
3130    : Type(ObjCInterface, QualType(), false, false),
3131      BaseType(QualType(this_(), 0)) {
3132    ObjCObjectTypeBits.NumProtocols = 0;
3133  }
3134
3135protected:
3136  CachedProperties getCachedProperties() const; // key function
3137
3138public:
3139  /// getBaseType - Gets the base type of this object type.  This is
3140  /// always (possibly sugar for) one of:
3141  ///  - the 'id' builtin type (as opposed to the 'id' type visible to the
3142  ///    user, which is a typedef for an ObjCPointerType)
3143  ///  - the 'Class' builtin type (same caveat)
3144  ///  - an ObjCObjectType (currently always an ObjCInterfaceType)
3145  QualType getBaseType() const { return BaseType; }
3146
3147  bool isObjCId() const {
3148    return getBaseType()->isSpecificBuiltinType(BuiltinType::ObjCId);
3149  }
3150  bool isObjCClass() const {
3151    return getBaseType()->isSpecificBuiltinType(BuiltinType::ObjCClass);
3152  }
3153  bool isObjCUnqualifiedId() const { return qual_empty() && isObjCId(); }
3154  bool isObjCUnqualifiedClass() const { return qual_empty() && isObjCClass(); }
3155  bool isObjCUnqualifiedIdOrClass() const {
3156    if (!qual_empty()) return false;
3157    if (const BuiltinType *T = getBaseType()->getAs<BuiltinType>())
3158      return T->getKind() == BuiltinType::ObjCId ||
3159             T->getKind() == BuiltinType::ObjCClass;
3160    return false;
3161  }
3162  bool isObjCQualifiedId() const { return !qual_empty() && isObjCId(); }
3163  bool isObjCQualifiedClass() const { return !qual_empty() && isObjCClass(); }
3164
3165  /// Gets the interface declaration for this object type, if the base type
3166  /// really is an interface.
3167  ObjCInterfaceDecl *getInterface() const;
3168
3169  typedef ObjCProtocolDecl * const *qual_iterator;
3170
3171  qual_iterator qual_begin() const { return getProtocolStorage(); }
3172  qual_iterator qual_end() const { return qual_begin() + getNumProtocols(); }
3173
3174  bool qual_empty() const { return getNumProtocols() == 0; }
3175
3176  /// getNumProtocols - Return the number of qualifying protocols in this
3177  /// interface type, or 0 if there are none.
3178  unsigned getNumProtocols() const { return ObjCObjectTypeBits.NumProtocols; }
3179
3180  /// \brief Fetch a protocol by index.
3181  ObjCProtocolDecl *getProtocol(unsigned I) const {
3182    assert(I < getNumProtocols() && "Out-of-range protocol access");
3183    return qual_begin()[I];
3184  }
3185
3186  bool isSugared() const { return false; }
3187  QualType desugar() const { return QualType(this, 0); }
3188
3189  static bool classof(const Type *T) {
3190    return T->getTypeClass() == ObjCObject ||
3191           T->getTypeClass() == ObjCInterface;
3192  }
3193  static bool classof(const ObjCObjectType *) { return true; }
3194};
3195
3196/// ObjCObjectTypeImpl - A class providing a concrete implementation
3197/// of ObjCObjectType, so as to not increase the footprint of
3198/// ObjCInterfaceType.  Code outside of ASTContext and the core type
3199/// system should not reference this type.
3200class ObjCObjectTypeImpl : public ObjCObjectType, public llvm::FoldingSetNode {
3201  friend class ASTContext;
3202
3203  // If anyone adds fields here, ObjCObjectType::getProtocolStorage()
3204  // will need to be modified.
3205
3206  ObjCObjectTypeImpl(QualType Canonical, QualType Base,
3207                     ObjCProtocolDecl * const *Protocols,
3208                     unsigned NumProtocols)
3209    : ObjCObjectType(Canonical, Base, Protocols, NumProtocols) {}
3210
3211public:
3212  void Profile(llvm::FoldingSetNodeID &ID);
3213  static void Profile(llvm::FoldingSetNodeID &ID,
3214                      QualType Base,
3215                      ObjCProtocolDecl *const *protocols,
3216                      unsigned NumProtocols);
3217};
3218
3219inline ObjCProtocolDecl **ObjCObjectType::getProtocolStorage() {
3220  return reinterpret_cast<ObjCProtocolDecl**>(
3221            static_cast<ObjCObjectTypeImpl*>(this) + 1);
3222}
3223
3224/// ObjCInterfaceType - Interfaces are the core concept in Objective-C for
3225/// object oriented design.  They basically correspond to C++ classes.  There
3226/// are two kinds of interface types, normal interfaces like "NSString" and
3227/// qualified interfaces, which are qualified with a protocol list like
3228/// "NSString<NSCopyable, NSAmazing>".
3229///
3230/// ObjCInterfaceType guarantees the following properties when considered
3231/// as a subtype of its superclass, ObjCObjectType:
3232///   - There are no protocol qualifiers.  To reinforce this, code which
3233///     tries to invoke the protocol methods via an ObjCInterfaceType will
3234///     fail to compile.
3235///   - It is its own base type.  That is, if T is an ObjCInterfaceType*,
3236///     T->getBaseType() == QualType(T, 0).
3237class ObjCInterfaceType : public ObjCObjectType {
3238  ObjCInterfaceDecl *Decl;
3239
3240  ObjCInterfaceType(const ObjCInterfaceDecl *D)
3241    : ObjCObjectType(Nonce_ObjCInterface),
3242      Decl(const_cast<ObjCInterfaceDecl*>(D)) {}
3243  friend class ASTContext;  // ASTContext creates these.
3244
3245protected:
3246  virtual CachedProperties getCachedProperties() const;
3247
3248public:
3249  /// getDecl - Get the declaration of this interface.
3250  ObjCInterfaceDecl *getDecl() const { return Decl; }
3251
3252  bool isSugared() const { return false; }
3253  QualType desugar() const { return QualType(this, 0); }
3254
3255  static bool classof(const Type *T) {
3256    return T->getTypeClass() == ObjCInterface;
3257  }
3258  static bool classof(const ObjCInterfaceType *) { return true; }
3259
3260  // Nonsense to "hide" certain members of ObjCObjectType within this
3261  // class.  People asking for protocols on an ObjCInterfaceType are
3262  // not going to get what they want: ObjCInterfaceTypes are
3263  // guaranteed to have no protocols.
3264  enum {
3265    qual_iterator,
3266    qual_begin,
3267    qual_end,
3268    getNumProtocols,
3269    getProtocol
3270  };
3271};
3272
3273inline ObjCInterfaceDecl *ObjCObjectType::getInterface() const {
3274  if (const ObjCInterfaceType *T =
3275        getBaseType()->getAs<ObjCInterfaceType>())
3276    return T->getDecl();
3277  return 0;
3278}
3279
3280/// ObjCObjectPointerType - Used to represent a pointer to an
3281/// Objective C object.  These are constructed from pointer
3282/// declarators when the pointee type is an ObjCObjectType (or sugar
3283/// for one).  In addition, the 'id' and 'Class' types are typedefs
3284/// for these, and the protocol-qualified types 'id<P>' and 'Class<P>'
3285/// are translated into these.
3286///
3287/// Pointers to pointers to Objective C objects are still PointerTypes;
3288/// only the first level of pointer gets it own type implementation.
3289class ObjCObjectPointerType : public Type, public llvm::FoldingSetNode {
3290  QualType PointeeType;
3291
3292  ObjCObjectPointerType(QualType Canonical, QualType Pointee)
3293    : Type(ObjCObjectPointer, Canonical, false, false),
3294      PointeeType(Pointee) {}
3295  friend class ASTContext;  // ASTContext creates these.
3296
3297protected:
3298  virtual CachedProperties getCachedProperties() const;
3299
3300public:
3301  /// getPointeeType - Gets the type pointed to by this ObjC pointer.
3302  /// The result will always be an ObjCObjectType or sugar thereof.
3303  QualType getPointeeType() const { return PointeeType; }
3304
3305  /// getObjCObjectType - Gets the type pointed to by this ObjC
3306  /// pointer.  This method always returns non-null.
3307  ///
3308  /// This method is equivalent to getPointeeType() except that
3309  /// it discards any typedefs (or other sugar) between this
3310  /// type and the "outermost" object type.  So for:
3311  ///   @class A; @protocol P; @protocol Q;
3312  ///   typedef A<P> AP;
3313  ///   typedef A A1;
3314  ///   typedef A1<P> A1P;
3315  ///   typedef A1P<Q> A1PQ;
3316  /// For 'A*', getObjectType() will return 'A'.
3317  /// For 'A<P>*', getObjectType() will return 'A<P>'.
3318  /// For 'AP*', getObjectType() will return 'A<P>'.
3319  /// For 'A1*', getObjectType() will return 'A'.
3320  /// For 'A1<P>*', getObjectType() will return 'A1<P>'.
3321  /// For 'A1P*', getObjectType() will return 'A1<P>'.
3322  /// For 'A1PQ*', getObjectType() will return 'A1<Q>', because
3323  ///   adding protocols to a protocol-qualified base discards the
3324  ///   old qualifiers (for now).  But if it didn't, getObjectType()
3325  ///   would return 'A1P<Q>' (and we'd have to make iterating over
3326  ///   qualifiers more complicated).
3327  const ObjCObjectType *getObjectType() const {
3328    return PointeeType->getAs<ObjCObjectType>();
3329  }
3330
3331  /// getInterfaceType - If this pointer points to an Objective C
3332  /// @interface type, gets the type for that interface.  Any protocol
3333  /// qualifiers on the interface are ignored.
3334  ///
3335  /// \return null if the base type for this pointer is 'id' or 'Class'
3336  const ObjCInterfaceType *getInterfaceType() const {
3337    return getObjectType()->getBaseType()->getAs<ObjCInterfaceType>();
3338  }
3339
3340  /// getInterfaceDecl - If this pointer points to an Objective @interface
3341  /// type, gets the declaration for that interface.
3342  ///
3343  /// \return null if the base type for this pointer is 'id' or 'Class'
3344  ObjCInterfaceDecl *getInterfaceDecl() const {
3345    return getObjectType()->getInterface();
3346  }
3347
3348  /// isObjCIdType - True if this is equivalent to the 'id' type, i.e. if
3349  /// its object type is the primitive 'id' type with no protocols.
3350  bool isObjCIdType() const {
3351    return getObjectType()->isObjCUnqualifiedId();
3352  }
3353
3354  /// isObjCClassType - True if this is equivalent to the 'Class' type,
3355  /// i.e. if its object tive is the primitive 'Class' type with no protocols.
3356  bool isObjCClassType() const {
3357    return getObjectType()->isObjCUnqualifiedClass();
3358  }
3359
3360  /// isObjCQualifiedIdType - True if this is equivalent to 'id<P>' for some
3361  /// non-empty set of protocols.
3362  bool isObjCQualifiedIdType() const {
3363    return getObjectType()->isObjCQualifiedId();
3364  }
3365
3366  /// isObjCQualifiedClassType - True if this is equivalent to 'Class<P>' for
3367  /// some non-empty set of protocols.
3368  bool isObjCQualifiedClassType() const {
3369    return getObjectType()->isObjCQualifiedClass();
3370  }
3371
3372  /// An iterator over the qualifiers on the object type.  Provided
3373  /// for convenience.  This will always iterate over the full set of
3374  /// protocols on a type, not just those provided directly.
3375  typedef ObjCObjectType::qual_iterator qual_iterator;
3376
3377  qual_iterator qual_begin() const {
3378    return getObjectType()->qual_begin();
3379  }
3380  qual_iterator qual_end() const {
3381    return getObjectType()->qual_end();
3382  }
3383  bool qual_empty() const { return getObjectType()->qual_empty(); }
3384
3385  /// getNumProtocols - Return the number of qualifying protocols on
3386  /// the object type.
3387  unsigned getNumProtocols() const {
3388    return getObjectType()->getNumProtocols();
3389  }
3390
3391  /// \brief Retrieve a qualifying protocol by index on the object
3392  /// type.
3393  ObjCProtocolDecl *getProtocol(unsigned I) const {
3394    return getObjectType()->getProtocol(I);
3395  }
3396
3397  bool isSugared() const { return false; }
3398  QualType desugar() const { return QualType(this, 0); }
3399
3400  void Profile(llvm::FoldingSetNodeID &ID) {
3401    Profile(ID, getPointeeType());
3402  }
3403  static void Profile(llvm::FoldingSetNodeID &ID, QualType T) {
3404    ID.AddPointer(T.getAsOpaquePtr());
3405  }
3406  static bool classof(const Type *T) {
3407    return T->getTypeClass() == ObjCObjectPointer;
3408  }
3409  static bool classof(const ObjCObjectPointerType *) { return true; }
3410};
3411
3412/// A qualifier set is used to build a set of qualifiers.
3413class QualifierCollector : public Qualifiers {
3414  ASTContext *Context;
3415
3416public:
3417  QualifierCollector(Qualifiers Qs = Qualifiers())
3418    : Qualifiers(Qs), Context(0) {}
3419  QualifierCollector(ASTContext &Context, Qualifiers Qs = Qualifiers())
3420    : Qualifiers(Qs), Context(&Context) {}
3421
3422  void setContext(ASTContext &C) { Context = &C; }
3423
3424  /// Collect any qualifiers on the given type and return an
3425  /// unqualified type.
3426  const Type *strip(QualType QT) {
3427    addFastQualifiers(QT.getLocalFastQualifiers());
3428    if (QT.hasLocalNonFastQualifiers()) {
3429      const ExtQuals *EQ = QT.getExtQualsUnsafe();
3430      Context = &EQ->getContext();
3431      addQualifiers(EQ->getQualifiers());
3432      return EQ->getBaseType();
3433    }
3434    return QT.getTypePtrUnsafe();
3435  }
3436
3437  /// Apply the collected qualifiers to the given type.
3438  QualType apply(QualType QT) const;
3439
3440  /// Apply the collected qualifiers to the given type.
3441  QualType apply(const Type* T) const;
3442
3443};
3444
3445
3446// Inline function definitions.
3447
3448inline bool QualType::isCanonical() const {
3449  const Type *T = getTypePtr();
3450  if (hasLocalQualifiers())
3451    return T->isCanonicalUnqualified() && !isa<ArrayType>(T);
3452  return T->isCanonicalUnqualified();
3453}
3454
3455inline bool QualType::isCanonicalAsParam() const {
3456  if (hasLocalQualifiers()) return false;
3457
3458  const Type *T = getTypePtr();
3459  if ((*this)->isPointerType()) {
3460    QualType BaseType = (*this)->getAs<PointerType>()->getPointeeType();
3461    if (isa<VariableArrayType>(BaseType)) {
3462      ArrayType *AT = dyn_cast<ArrayType>(BaseType);
3463      VariableArrayType *VAT = cast<VariableArrayType>(AT);
3464      if (VAT->getSizeExpr())
3465        T = BaseType.getTypePtr();
3466    }
3467  }
3468  return T->isCanonicalUnqualified() &&
3469           !isa<FunctionType>(T) && !isa<ArrayType>(T);
3470}
3471
3472inline bool QualType::isConstQualified() const {
3473  return isLocalConstQualified() ||
3474              getTypePtr()->getCanonicalTypeInternal().isLocalConstQualified();
3475}
3476
3477inline bool QualType::isRestrictQualified() const {
3478  return isLocalRestrictQualified() ||
3479            getTypePtr()->getCanonicalTypeInternal().isLocalRestrictQualified();
3480}
3481
3482
3483inline bool QualType::isVolatileQualified() const {
3484  return isLocalVolatileQualified() ||
3485  getTypePtr()->getCanonicalTypeInternal().isLocalVolatileQualified();
3486}
3487
3488inline bool QualType::hasQualifiers() const {
3489  return hasLocalQualifiers() ||
3490                  getTypePtr()->getCanonicalTypeInternal().hasLocalQualifiers();
3491}
3492
3493inline Qualifiers QualType::getQualifiers() const {
3494  Qualifiers Quals = getLocalQualifiers();
3495  Quals.addQualifiers(
3496                 getTypePtr()->getCanonicalTypeInternal().getLocalQualifiers());
3497  return Quals;
3498}
3499
3500inline unsigned QualType::getCVRQualifiers() const {
3501  return getLocalCVRQualifiers() |
3502              getTypePtr()->getCanonicalTypeInternal().getLocalCVRQualifiers();
3503}
3504
3505/// getCVRQualifiersThroughArrayTypes - If there are CVR qualifiers for this
3506/// type, returns them. Otherwise, if this is an array type, recurses
3507/// on the element type until some qualifiers have been found or a non-array
3508/// type reached.
3509inline unsigned QualType::getCVRQualifiersThroughArrayTypes() const {
3510  if (unsigned Quals = getCVRQualifiers())
3511    return Quals;
3512  QualType CT = getTypePtr()->getCanonicalTypeInternal();
3513  if (const ArrayType *AT = dyn_cast<ArrayType>(CT))
3514    return AT->getElementType().getCVRQualifiersThroughArrayTypes();
3515  return 0;
3516}
3517
3518inline void QualType::removeConst() {
3519  removeFastQualifiers(Qualifiers::Const);
3520}
3521
3522inline void QualType::removeRestrict() {
3523  removeFastQualifiers(Qualifiers::Restrict);
3524}
3525
3526inline void QualType::removeVolatile() {
3527  QualifierCollector Qc;
3528  const Type *Ty = Qc.strip(*this);
3529  if (Qc.hasVolatile()) {
3530    Qc.removeVolatile();
3531    *this = Qc.apply(Ty);
3532  }
3533}
3534
3535inline void QualType::removeCVRQualifiers(unsigned Mask) {
3536  assert(!(Mask & ~Qualifiers::CVRMask) && "mask has non-CVR bits");
3537
3538  // Fast path: we don't need to touch the slow qualifiers.
3539  if (!(Mask & ~Qualifiers::FastMask)) {
3540    removeFastQualifiers(Mask);
3541    return;
3542  }
3543
3544  QualifierCollector Qc;
3545  const Type *Ty = Qc.strip(*this);
3546  Qc.removeCVRQualifiers(Mask);
3547  *this = Qc.apply(Ty);
3548}
3549
3550/// getAddressSpace - Return the address space of this type.
3551inline unsigned QualType::getAddressSpace() const {
3552  if (hasLocalNonFastQualifiers()) {
3553    const ExtQuals *EQ = getExtQualsUnsafe();
3554    if (EQ->hasAddressSpace())
3555      return EQ->getAddressSpace();
3556  }
3557
3558  QualType CT = getTypePtr()->getCanonicalTypeInternal();
3559  if (CT.hasLocalNonFastQualifiers()) {
3560    const ExtQuals *EQ = CT.getExtQualsUnsafe();
3561    if (EQ->hasAddressSpace())
3562      return EQ->getAddressSpace();
3563  }
3564
3565  if (const ArrayType *AT = dyn_cast<ArrayType>(CT))
3566    return AT->getElementType().getAddressSpace();
3567  if (const RecordType *RT = dyn_cast<RecordType>(CT))
3568    return RT->getAddressSpace();
3569  return 0;
3570}
3571
3572/// getObjCGCAttr - Return the gc attribute of this type.
3573inline Qualifiers::GC QualType::getObjCGCAttr() const {
3574  if (hasLocalNonFastQualifiers()) {
3575    const ExtQuals *EQ = getExtQualsUnsafe();
3576    if (EQ->hasObjCGCAttr())
3577      return EQ->getObjCGCAttr();
3578  }
3579
3580  QualType CT = getTypePtr()->getCanonicalTypeInternal();
3581  if (CT.hasLocalNonFastQualifiers()) {
3582    const ExtQuals *EQ = CT.getExtQualsUnsafe();
3583    if (EQ->hasObjCGCAttr())
3584      return EQ->getObjCGCAttr();
3585  }
3586
3587  if (const ArrayType *AT = dyn_cast<ArrayType>(CT))
3588      return AT->getElementType().getObjCGCAttr();
3589  if (const ObjCObjectPointerType *PT = CT->getAs<ObjCObjectPointerType>())
3590    return PT->getPointeeType().getObjCGCAttr();
3591  // We most look at all pointer types, not just pointer to interface types.
3592  if (const PointerType *PT = CT->getAs<PointerType>())
3593    return PT->getPointeeType().getObjCGCAttr();
3594  return Qualifiers::GCNone;
3595}
3596
3597inline FunctionType::ExtInfo getFunctionExtInfo(const Type &t) {
3598  if (const PointerType *PT = t.getAs<PointerType>()) {
3599    if (const FunctionType *FT = PT->getPointeeType()->getAs<FunctionType>())
3600      return FT->getExtInfo();
3601  } else if (const FunctionType *FT = t.getAs<FunctionType>())
3602    return FT->getExtInfo();
3603
3604  return FunctionType::ExtInfo();
3605}
3606
3607inline FunctionType::ExtInfo getFunctionExtInfo(QualType t) {
3608  return getFunctionExtInfo(*t);
3609}
3610
3611/// \brief Determine whether this set of qualifiers is a superset of the given
3612/// set of qualifiers.
3613inline bool Qualifiers::isSupersetOf(Qualifiers Other) const {
3614  return Mask != Other.Mask && (Mask | Other.Mask) == Mask;
3615}
3616
3617/// isMoreQualifiedThan - Determine whether this type is more
3618/// qualified than the Other type. For example, "const volatile int"
3619/// is more qualified than "const int", "volatile int", and
3620/// "int". However, it is not more qualified than "const volatile
3621/// int".
3622inline bool QualType::isMoreQualifiedThan(QualType Other) const {
3623  // FIXME: work on arbitrary qualifiers
3624  unsigned MyQuals = this->getCVRQualifiersThroughArrayTypes();
3625  unsigned OtherQuals = Other.getCVRQualifiersThroughArrayTypes();
3626  if (getAddressSpace() != Other.getAddressSpace())
3627    return false;
3628  return MyQuals != OtherQuals && (MyQuals | OtherQuals) == MyQuals;
3629}
3630
3631/// isAtLeastAsQualifiedAs - Determine whether this type is at last
3632/// as qualified as the Other type. For example, "const volatile
3633/// int" is at least as qualified as "const int", "volatile int",
3634/// "int", and "const volatile int".
3635inline bool QualType::isAtLeastAsQualifiedAs(QualType Other) const {
3636  // FIXME: work on arbitrary qualifiers
3637  unsigned MyQuals = this->getCVRQualifiersThroughArrayTypes();
3638  unsigned OtherQuals = Other.getCVRQualifiersThroughArrayTypes();
3639  if (getAddressSpace() != Other.getAddressSpace())
3640    return false;
3641  return (MyQuals | OtherQuals) == MyQuals;
3642}
3643
3644/// getNonReferenceType - If Type is a reference type (e.g., const
3645/// int&), returns the type that the reference refers to ("const
3646/// int"). Otherwise, returns the type itself. This routine is used
3647/// throughout Sema to implement C++ 5p6:
3648///
3649///   If an expression initially has the type "reference to T" (8.3.2,
3650///   8.5.3), the type is adjusted to "T" prior to any further
3651///   analysis, the expression designates the object or function
3652///   denoted by the reference, and the expression is an lvalue.
3653inline QualType QualType::getNonReferenceType() const {
3654  if (const ReferenceType *RefType = (*this)->getAs<ReferenceType>())
3655    return RefType->getPointeeType();
3656  else
3657    return *this;
3658}
3659
3660inline bool Type::isFunctionType() const {
3661  return isa<FunctionType>(CanonicalType);
3662}
3663inline bool Type::isPointerType() const {
3664  return isa<PointerType>(CanonicalType);
3665}
3666inline bool Type::isAnyPointerType() const {
3667  return isPointerType() || isObjCObjectPointerType();
3668}
3669inline bool Type::isBlockPointerType() const {
3670  return isa<BlockPointerType>(CanonicalType);
3671}
3672inline bool Type::isReferenceType() const {
3673  return isa<ReferenceType>(CanonicalType);
3674}
3675inline bool Type::isLValueReferenceType() const {
3676  return isa<LValueReferenceType>(CanonicalType);
3677}
3678inline bool Type::isRValueReferenceType() const {
3679  return isa<RValueReferenceType>(CanonicalType);
3680}
3681inline bool Type::isFunctionPointerType() const {
3682  if (const PointerType* T = getAs<PointerType>())
3683    return T->getPointeeType()->isFunctionType();
3684  else
3685    return false;
3686}
3687inline bool Type::isMemberPointerType() const {
3688  return isa<MemberPointerType>(CanonicalType);
3689}
3690inline bool Type::isMemberFunctionPointerType() const {
3691  if (const MemberPointerType* T = getAs<MemberPointerType>())
3692    return T->isMemberFunctionPointer();
3693  else
3694    return false;
3695}
3696inline bool Type::isMemberDataPointerType() const {
3697  if (const MemberPointerType* T = getAs<MemberPointerType>())
3698    return T->isMemberDataPointer();
3699  else
3700    return false;
3701}
3702inline bool Type::isArrayType() const {
3703  return isa<ArrayType>(CanonicalType);
3704}
3705inline bool Type::isConstantArrayType() const {
3706  return isa<ConstantArrayType>(CanonicalType);
3707}
3708inline bool Type::isIncompleteArrayType() const {
3709  return isa<IncompleteArrayType>(CanonicalType);
3710}
3711inline bool Type::isVariableArrayType() const {
3712  return isa<VariableArrayType>(CanonicalType);
3713}
3714inline bool Type::isDependentSizedArrayType() const {
3715  return isa<DependentSizedArrayType>(CanonicalType);
3716}
3717inline bool Type::isBuiltinType() const {
3718  return isa<BuiltinType>(CanonicalType);
3719}
3720inline bool Type::isRecordType() const {
3721  return isa<RecordType>(CanonicalType);
3722}
3723inline bool Type::isEnumeralType() const {
3724  return isa<EnumType>(CanonicalType);
3725}
3726inline bool Type::isAnyComplexType() const {
3727  return isa<ComplexType>(CanonicalType);
3728}
3729inline bool Type::isVectorType() const {
3730  return isa<VectorType>(CanonicalType);
3731}
3732inline bool Type::isExtVectorType() const {
3733  return isa<ExtVectorType>(CanonicalType);
3734}
3735inline bool Type::isObjCObjectPointerType() const {
3736  return isa<ObjCObjectPointerType>(CanonicalType);
3737}
3738inline bool Type::isObjCObjectType() const {
3739  return isa<ObjCObjectType>(CanonicalType);
3740}
3741inline bool Type::isObjCObjectOrInterfaceType() const {
3742  return isa<ObjCInterfaceType>(CanonicalType) ||
3743    isa<ObjCObjectType>(CanonicalType);
3744}
3745
3746inline bool Type::isObjCQualifiedIdType() const {
3747  if (const ObjCObjectPointerType *OPT = getAs<ObjCObjectPointerType>())
3748    return OPT->isObjCQualifiedIdType();
3749  return false;
3750}
3751inline bool Type::isObjCQualifiedClassType() const {
3752  if (const ObjCObjectPointerType *OPT = getAs<ObjCObjectPointerType>())
3753    return OPT->isObjCQualifiedClassType();
3754  return false;
3755}
3756inline bool Type::isObjCIdType() const {
3757  if (const ObjCObjectPointerType *OPT = getAs<ObjCObjectPointerType>())
3758    return OPT->isObjCIdType();
3759  return false;
3760}
3761inline bool Type::isObjCClassType() const {
3762  if (const ObjCObjectPointerType *OPT = getAs<ObjCObjectPointerType>())
3763    return OPT->isObjCClassType();
3764  return false;
3765}
3766inline bool Type::isObjCSelType() const {
3767  if (const PointerType *OPT = getAs<PointerType>())
3768    return OPT->getPointeeType()->isSpecificBuiltinType(BuiltinType::ObjCSel);
3769  return false;
3770}
3771inline bool Type::isObjCBuiltinType() const {
3772  return isObjCIdType() || isObjCClassType() || isObjCSelType();
3773}
3774inline bool Type::isTemplateTypeParmType() const {
3775  return isa<TemplateTypeParmType>(CanonicalType);
3776}
3777
3778inline bool Type::isSpecificBuiltinType(unsigned K) const {
3779  if (const BuiltinType *BT = getAs<BuiltinType>())
3780    if (BT->getKind() == (BuiltinType::Kind) K)
3781      return true;
3782  return false;
3783}
3784
3785inline bool Type::isPlaceholderType() const {
3786  if (const BuiltinType *BT = getAs<BuiltinType>())
3787    return BT->isPlaceholderType();
3788  return false;
3789}
3790
3791/// \brief Determines whether this is a type for which one can define
3792/// an overloaded operator.
3793inline bool Type::isOverloadableType() const {
3794  return isDependentType() || isRecordType() || isEnumeralType();
3795}
3796
3797inline bool Type::hasPointerRepresentation() const {
3798  return (isPointerType() || isReferenceType() || isBlockPointerType() ||
3799          isObjCObjectPointerType() || isNullPtrType());
3800}
3801
3802inline bool Type::hasObjCPointerRepresentation() const {
3803  return isObjCObjectPointerType();
3804}
3805
3806/// Insertion operator for diagnostics.  This allows sending QualType's into a
3807/// diagnostic with <<.
3808inline const DiagnosticBuilder &operator<<(const DiagnosticBuilder &DB,
3809                                           QualType T) {
3810  DB.AddTaggedVal(reinterpret_cast<intptr_t>(T.getAsOpaquePtr()),
3811                  Diagnostic::ak_qualtype);
3812  return DB;
3813}
3814
3815/// Insertion operator for partial diagnostics.  This allows sending QualType's
3816/// into a diagnostic with <<.
3817inline const PartialDiagnostic &operator<<(const PartialDiagnostic &PD,
3818                                           QualType T) {
3819  PD.AddTaggedVal(reinterpret_cast<intptr_t>(T.getAsOpaquePtr()),
3820                  Diagnostic::ak_qualtype);
3821  return PD;
3822}
3823
3824// Helper class template that is used by Type::getAs to ensure that one does
3825// not try to look through a qualified type to get to an array type.
3826template<typename T,
3827         bool isArrayType = (llvm::is_same<T, ArrayType>::value ||
3828                             llvm::is_base_of<ArrayType, T>::value)>
3829struct ArrayType_cannot_be_used_with_getAs { };
3830
3831template<typename T>
3832struct ArrayType_cannot_be_used_with_getAs<T, true>;
3833
3834/// Member-template getAs<specific type>'.
3835template <typename T> const T *Type::getAs() const {
3836  ArrayType_cannot_be_used_with_getAs<T> at;
3837  (void)at;
3838
3839  // If this is directly a T type, return it.
3840  if (const T *Ty = dyn_cast<T>(this))
3841    return Ty;
3842
3843  // If the canonical form of this type isn't the right kind, reject it.
3844  if (!isa<T>(CanonicalType))
3845    return 0;
3846
3847  // If this is a typedef for the type, strip the typedef off without
3848  // losing all typedef information.
3849  return cast<T>(getUnqualifiedDesugaredType());
3850}
3851
3852}  // end namespace clang
3853
3854#endif
3855