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