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