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