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