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