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