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