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