Type.h revision b001de7458d17c17e6d8b8034c7cfcefd3b70c00
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
1366  /// isSpecificPlaceholderType - Test for a specific placeholder type.
1367  bool isSpecificPlaceholderType(unsigned K) const;
1368
1369  /// isIntegerType() does *not* include complex integers (a GCC extension).
1370  /// isComplexIntegerType() can be used to test for complex integers.
1371  bool isIntegerType() const;     // C99 6.2.5p17 (int, char, bool, enum)
1372  bool isEnumeralType() const;
1373  bool isBooleanType() const;
1374  bool isCharType() const;
1375  bool isWideCharType() const;
1376  bool isChar16Type() const;
1377  bool isChar32Type() const;
1378  bool isAnyCharacterType() const;
1379  bool isIntegralType(ASTContext &Ctx) const;
1380
1381  /// \brief Determine whether this type is an integral or enumeration type.
1382  bool isIntegralOrEnumerationType() const;
1383  /// \brief Determine whether this type is an integral or unscoped enumeration
1384  /// type.
1385  bool isIntegralOrUnscopedEnumerationType() const;
1386
1387  /// Floating point categories.
1388  bool isRealFloatingType() const; // C99 6.2.5p10 (float, double, long double)
1389  /// isComplexType() does *not* include complex integers (a GCC extension).
1390  /// isComplexIntegerType() can be used to test for complex integers.
1391  bool isComplexType() const;      // C99 6.2.5p11 (complex)
1392  bool isAnyComplexType() const;   // C99 6.2.5p11 (complex) + Complex Int.
1393  bool isFloatingType() const;     // C99 6.2.5p11 (real floating + complex)
1394  bool isRealType() const;         // C99 6.2.5p17 (real floating + integer)
1395  bool isArithmeticType() const;   // C99 6.2.5p18 (integer + floating)
1396  bool isVoidType() const;         // C99 6.2.5p19
1397  bool isDerivedType() const;      // C99 6.2.5p20
1398  bool isScalarType() const;       // C99 6.2.5p21 (arithmetic + pointers)
1399  bool isAggregateType() const;
1400  bool isFundamentalType() const;
1401  bool isCompoundType() const;
1402
1403  // Type Predicates: Check to see if this type is structurally the specified
1404  // type, ignoring typedefs and qualifiers.
1405  bool isFunctionType() const;
1406  bool isFunctionNoProtoType() const { return getAs<FunctionNoProtoType>(); }
1407  bool isFunctionProtoType() const { return getAs<FunctionProtoType>(); }
1408  bool isPointerType() const;
1409  bool isAnyPointerType() const;   // Any C pointer or ObjC object pointer
1410  bool isBlockPointerType() const;
1411  bool isVoidPointerType() const;
1412  bool isReferenceType() const;
1413  bool isLValueReferenceType() const;
1414  bool isRValueReferenceType() const;
1415  bool isFunctionPointerType() const;
1416  bool isMemberPointerType() const;
1417  bool isMemberFunctionPointerType() const;
1418  bool isMemberDataPointerType() const;
1419  bool isArrayType() const;
1420  bool isConstantArrayType() const;
1421  bool isIncompleteArrayType() const;
1422  bool isVariableArrayType() const;
1423  bool isDependentSizedArrayType() const;
1424  bool isRecordType() const;
1425  bool isClassType() const;
1426  bool isStructureType() const;
1427  bool isStructureOrClassType() const;
1428  bool isUnionType() const;
1429  bool isComplexIntegerType() const;            // GCC _Complex integer type.
1430  bool isVectorType() const;                    // GCC vector type.
1431  bool isExtVectorType() const;                 // Extended vector type.
1432  bool isObjCObjectPointerType() const;         // pointer to ObjC object
1433  bool isObjCRetainableType() const;            // ObjC object or block pointer
1434  bool isObjCLifetimeType() const;              // (array of)* retainable type
1435  bool isObjCIndirectLifetimeType() const;      // (pointer to)* lifetime type
1436  bool isObjCNSObjectType() const;              // __attribute__((NSObject))
1437  // FIXME: change this to 'raw' interface type, so we can used 'interface' type
1438  // for the common case.
1439  bool isObjCObjectType() const;                // NSString or typeof(*(id)0)
1440  bool isObjCQualifiedInterfaceType() const;    // NSString<foo>
1441  bool isObjCQualifiedIdType() const;           // id<foo>
1442  bool isObjCQualifiedClassType() const;        // Class<foo>
1443  bool isObjCObjectOrInterfaceType() const;
1444  bool isObjCIdType() const;                    // id
1445  bool isObjCClassType() const;                 // Class
1446  bool isObjCSelType() const;                 // Class
1447  bool isObjCBuiltinType() const;               // 'id' or 'Class'
1448  bool isObjCARCBridgableType() const;
1449  bool isCARCBridgableType() const;
1450  bool isTemplateTypeParmType() const;          // C++ template type parameter
1451  bool isNullPtrType() const;                   // C++0x nullptr_t
1452  bool isAtomicType() const;                    // C1X _Atomic()
1453
1454  /// Determines if this type, which must satisfy
1455  /// isObjCLifetimeType(), is implicitly __unsafe_unretained rather
1456  /// than implicitly __strong.
1457  bool isObjCARCImplicitlyUnretainedType() const;
1458
1459  /// Return the implicit lifetime for this type, which must not be dependent.
1460  Qualifiers::ObjCLifetime getObjCARCImplicitLifetime() const;
1461
1462  enum ScalarTypeKind {
1463    STK_CPointer,
1464    STK_BlockPointer,
1465    STK_ObjCObjectPointer,
1466    STK_MemberPointer,
1467    STK_Bool,
1468    STK_Integral,
1469    STK_Floating,
1470    STK_IntegralComplex,
1471    STK_FloatingComplex
1472  };
1473  /// getScalarTypeKind - Given that this is a scalar type, classify it.
1474  ScalarTypeKind getScalarTypeKind() const;
1475
1476  /// isDependentType - Whether this type is a dependent type, meaning
1477  /// that its definition somehow depends on a template parameter
1478  /// (C++ [temp.dep.type]).
1479  bool isDependentType() const { return TypeBits.Dependent; }
1480
1481  /// \brief Determine whether this type is an instantiation-dependent type,
1482  /// meaning that the type involves a template parameter (even if the
1483  /// definition does not actually depend on the type substituted for that
1484  /// template parameter).
1485  bool isInstantiationDependentType() const {
1486    return TypeBits.InstantiationDependent;
1487  }
1488
1489  /// \brief Whether this type is a variably-modified type (C99 6.7.5).
1490  bool isVariablyModifiedType() const { return TypeBits.VariablyModified; }
1491
1492  /// \brief Whether this type involves a variable-length array type
1493  /// with a definite size.
1494  bool hasSizedVLAType() const;
1495
1496  /// \brief Whether this type is or contains a local or unnamed type.
1497  bool hasUnnamedOrLocalType() const;
1498
1499  bool isOverloadableType() const;
1500
1501  /// \brief Determine wither this type is a C++ elaborated-type-specifier.
1502  bool isElaboratedTypeSpecifier() const;
1503
1504  bool canDecayToPointerType() const;
1505
1506  /// hasPointerRepresentation - Whether this type is represented
1507  /// natively as a pointer; this includes pointers, references, block
1508  /// pointers, and Objective-C interface, qualified id, and qualified
1509  /// interface types, as well as nullptr_t.
1510  bool hasPointerRepresentation() const;
1511
1512  /// hasObjCPointerRepresentation - Whether this type can represent
1513  /// an objective pointer type for the purpose of GC'ability
1514  bool hasObjCPointerRepresentation() const;
1515
1516  /// \brief Determine whether this type has an integer representation
1517  /// of some sort, e.g., it is an integer type or a vector.
1518  bool hasIntegerRepresentation() const;
1519
1520  /// \brief Determine whether this type has an signed integer representation
1521  /// of some sort, e.g., it is an signed integer type or a vector.
1522  bool hasSignedIntegerRepresentation() const;
1523
1524  /// \brief Determine whether this type has an unsigned integer representation
1525  /// of some sort, e.g., it is an unsigned integer type or a vector.
1526  bool hasUnsignedIntegerRepresentation() const;
1527
1528  /// \brief Determine whether this type has a floating-point representation
1529  /// of some sort, e.g., it is a floating-point type or a vector thereof.
1530  bool hasFloatingRepresentation() const;
1531
1532  // Type Checking Functions: Check to see if this type is structurally the
1533  // specified type, ignoring typedefs and qualifiers, and return a pointer to
1534  // the best type we can.
1535  const RecordType *getAsStructureType() const;
1536  /// NOTE: getAs*ArrayType are methods on ASTContext.
1537  const RecordType *getAsUnionType() const;
1538  const ComplexType *getAsComplexIntegerType() const; // GCC complex int type.
1539  // The following is a convenience method that returns an ObjCObjectPointerType
1540  // for object declared using an interface.
1541  const ObjCObjectPointerType *getAsObjCInterfacePointerType() const;
1542  const ObjCObjectPointerType *getAsObjCQualifiedIdType() const;
1543  const ObjCObjectPointerType *getAsObjCQualifiedClassType() const;
1544  const ObjCObjectType *getAsObjCQualifiedInterfaceType() const;
1545  const CXXRecordDecl *getCXXRecordDeclForPointerType() const;
1546
1547  /// \brief Retrieves the CXXRecordDecl that this type refers to, either
1548  /// because the type is a RecordType or because it is the injected-class-name
1549  /// type of a class template or class template partial specialization.
1550  CXXRecordDecl *getAsCXXRecordDecl() const;
1551
1552  /// \brief Get the AutoType whose type will be deduced for a variable with
1553  /// an initializer of this type. This looks through declarators like pointer
1554  /// types, but not through decltype or typedefs.
1555  AutoType *getContainedAutoType() const;
1556
1557  /// Member-template getAs<specific type>'.  Look through sugar for
1558  /// an instance of <specific type>.   This scheme will eventually
1559  /// replace the specific getAsXXXX methods above.
1560  ///
1561  /// There are some specializations of this member template listed
1562  /// immediately following this class.
1563  template <typename T> const T *getAs() const;
1564
1565  /// A variant of getAs<> for array types which silently discards
1566  /// qualifiers from the outermost type.
1567  const ArrayType *getAsArrayTypeUnsafe() const;
1568
1569  /// Member-template castAs<specific type>.  Look through sugar for
1570  /// the underlying instance of <specific type>.
1571  ///
1572  /// This method has the same relationship to getAs<T> as cast<T> has
1573  /// to dyn_cast<T>; which is to say, the underlying type *must*
1574  /// have the intended type, and this method will never return null.
1575  template <typename T> const T *castAs() const;
1576
1577  /// A variant of castAs<> for array type which silently discards
1578  /// qualifiers from the outermost type.
1579  const ArrayType *castAsArrayTypeUnsafe() const;
1580
1581  /// getBaseElementTypeUnsafe - Get the base element type of this
1582  /// type, potentially discarding type qualifiers.  This method
1583  /// should never be used when type qualifiers are meaningful.
1584  const Type *getBaseElementTypeUnsafe() const;
1585
1586  /// getArrayElementTypeNoTypeQual - If this is an array type, return the
1587  /// element type of the array, potentially with type qualifiers missing.
1588  /// This method should never be used when type qualifiers are meaningful.
1589  const Type *getArrayElementTypeNoTypeQual() const;
1590
1591  /// getPointeeType - If this is a pointer, ObjC object pointer, or block
1592  /// pointer, this returns the respective pointee.
1593  QualType getPointeeType() const;
1594
1595  /// getUnqualifiedDesugaredType() - Return the specified type with
1596  /// any "sugar" removed from the type, removing any typedefs,
1597  /// typeofs, etc., as well as any qualifiers.
1598  const Type *getUnqualifiedDesugaredType() const;
1599
1600  /// More type predicates useful for type checking/promotion
1601  bool isPromotableIntegerType() const; // C99 6.3.1.1p2
1602
1603  /// isSignedIntegerType - Return true if this is an integer type that is
1604  /// signed, according to C99 6.2.5p4 [char, signed char, short, int, long..],
1605  /// or an enum decl which has a signed representation.
1606  bool isSignedIntegerType() const;
1607
1608  /// isUnsignedIntegerType - Return true if this is an integer type that is
1609  /// unsigned, according to C99 6.2.5p6 [which returns true for _Bool],
1610  /// or an enum decl which has an unsigned representation.
1611  bool isUnsignedIntegerType() const;
1612
1613  /// Determines whether this is an integer type that is signed or an
1614  /// enumeration types whose underlying type is a signed integer type.
1615  bool isSignedIntegerOrEnumerationType() const;
1616
1617  /// Determines whether this is an integer type that is unsigned or an
1618  /// enumeration types whose underlying type is a unsigned integer type.
1619  bool isUnsignedIntegerOrEnumerationType() const;
1620
1621  /// isConstantSizeType - Return true if this is not a variable sized type,
1622  /// according to the rules of C99 6.7.5p3.  It is not legal to call this on
1623  /// incomplete types.
1624  bool isConstantSizeType() const;
1625
1626  /// isSpecifierType - Returns true if this type can be represented by some
1627  /// set of type specifiers.
1628  bool isSpecifierType() const;
1629
1630  /// \brief Determine the linkage of this type.
1631  Linkage getLinkage() const;
1632
1633  /// \brief Determine the visibility of this type.
1634  Visibility getVisibility() const;
1635
1636  /// \brief Determine the linkage and visibility of this type.
1637  std::pair<Linkage,Visibility> getLinkageAndVisibility() const;
1638
1639  /// \brief Note that the linkage is no longer known.
1640  void ClearLinkageCache();
1641
1642  const char *getTypeClassName() const;
1643
1644  QualType getCanonicalTypeInternal() const {
1645    return CanonicalType;
1646  }
1647  CanQualType getCanonicalTypeUnqualified() const; // in CanonicalType.h
1648  void dump() const;
1649
1650  static bool classof(const Type *) { return true; }
1651
1652  friend class ASTReader;
1653  friend class ASTWriter;
1654};
1655
1656template <> inline const TypedefType *Type::getAs() const {
1657  return dyn_cast<TypedefType>(this);
1658}
1659
1660// We can do canonical leaf types faster, because we don't have to
1661// worry about preserving child type decoration.
1662#define TYPE(Class, Base)
1663#define LEAF_TYPE(Class) \
1664template <> inline const Class##Type *Type::getAs() const { \
1665  return dyn_cast<Class##Type>(CanonicalType); \
1666} \
1667template <> inline const Class##Type *Type::castAs() const { \
1668  return cast<Class##Type>(CanonicalType); \
1669}
1670#include "clang/AST/TypeNodes.def"
1671
1672
1673/// BuiltinType - This class is used for builtin types like 'int'.  Builtin
1674/// types are always canonical and have a literal name field.
1675class BuiltinType : public Type {
1676public:
1677  enum Kind {
1678    Void,
1679
1680    Bool,     // This is bool and/or _Bool.
1681    Char_U,   // This is 'char' for targets where char is unsigned.
1682    UChar,    // This is explicitly qualified unsigned char.
1683    WChar_U,  // This is 'wchar_t' for C++, when unsigned.
1684    Char16,   // This is 'char16_t' for C++.
1685    Char32,   // This is 'char32_t' for C++.
1686    UShort,
1687    UInt,
1688    ULong,
1689    ULongLong,
1690    UInt128,  // __uint128_t
1691
1692    Char_S,   // This is 'char' for targets where char is signed.
1693    SChar,    // This is explicitly qualified signed char.
1694    WChar_S,  // This is 'wchar_t' for C++, when signed.
1695    Short,
1696    Int,
1697    Long,
1698    LongLong,
1699    Int128,   // __int128_t
1700
1701    Float, Double, LongDouble,
1702
1703    NullPtr,  // This is the type of C++0x 'nullptr'.
1704
1705    /// The primitive Objective C 'id' type.  The user-visible 'id'
1706    /// type is a typedef of an ObjCObjectPointerType to an
1707    /// ObjCObjectType with this as its base.  In fact, this only ever
1708    /// shows up in an AST as the base type of an ObjCObjectType.
1709    ObjCId,
1710
1711    /// The primitive Objective C 'Class' type.  The user-visible
1712    /// 'Class' type is a typedef of an ObjCObjectPointerType to an
1713    /// ObjCObjectType with this as its base.  In fact, this only ever
1714    /// shows up in an AST as the base type of an ObjCObjectType.
1715    ObjCClass,
1716
1717    /// The primitive Objective C 'SEL' type.  The user-visible 'SEL'
1718    /// type is a typedef of a PointerType to this.
1719    ObjCSel,
1720
1721    /// This represents the type of an expression whose type is
1722    /// totally unknown, e.g. 'T::foo'.  It is permitted for this to
1723    /// appear in situations where the structure of the type is
1724    /// theoretically deducible.
1725    Dependent,
1726
1727    /// The type of an unresolved overload set.  A placeholder type.
1728    /// Expressions with this type have one of the following basic
1729    /// forms, with parentheses generally permitted:
1730    ///   foo          # possibly qualified, not if an implicit access
1731    ///   foo          # possibly qualified, not if an implicit access
1732    ///   &foo         # possibly qualified, not if an implicit access
1733    ///   x->foo       # only if might be a static member function
1734    ///   &x->foo      # only if might be a static member function
1735    ///   &Class::foo  # when a pointer-to-member; sub-expr also has this type
1736    /// OverloadExpr::find can be used to analyze the expression.
1737    Overload,
1738
1739    /// The type of a bound C++ non-static member function.
1740    /// A placeholder type.  Expressions with this type have one of the
1741    /// following basic forms:
1742    ///   foo          # if an implicit access
1743    ///   x->foo       # if only contains non-static members
1744    BoundMember,
1745
1746    /// __builtin_any_type.  A placeholder type.  Useful for clients
1747    /// like debuggers that don't know what type to give something.
1748    /// Only a small number of operations are valid on expressions of
1749    /// unknown type, most notably explicit casts.
1750    UnknownAny
1751  };
1752
1753public:
1754  BuiltinType(Kind K)
1755    : Type(Builtin, QualType(), /*Dependent=*/(K == Dependent),
1756           /*InstantiationDependent=*/(K == Dependent),
1757           /*VariablyModified=*/false,
1758           /*Unexpanded paramter pack=*/false) {
1759    BuiltinTypeBits.Kind = K;
1760  }
1761
1762  Kind getKind() const { return static_cast<Kind>(BuiltinTypeBits.Kind); }
1763  const char *getName(const PrintingPolicy &Policy) const;
1764
1765  bool isSugared() const { return false; }
1766  QualType desugar() const { return QualType(this, 0); }
1767
1768  bool isInteger() const {
1769    return getKind() >= Bool && getKind() <= Int128;
1770  }
1771
1772  bool isSignedInteger() const {
1773    return getKind() >= Char_S && getKind() <= Int128;
1774  }
1775
1776  bool isUnsignedInteger() const {
1777    return getKind() >= Bool && getKind() <= UInt128;
1778  }
1779
1780  bool isFloatingPoint() const {
1781    return getKind() >= Float && getKind() <= LongDouble;
1782  }
1783
1784  /// Determines whether this type is a placeholder type, i.e. a type
1785  /// which cannot appear in arbitrary positions in a fully-formed
1786  /// expression.
1787  bool isPlaceholderType() const {
1788    return getKind() >= Overload;
1789  }
1790
1791  static bool classof(const Type *T) { return T->getTypeClass() == Builtin; }
1792  static bool classof(const BuiltinType *) { return true; }
1793};
1794
1795/// ComplexType - C99 6.2.5p11 - Complex values.  This supports the C99 complex
1796/// types (_Complex float etc) as well as the GCC integer complex extensions.
1797///
1798class ComplexType : public Type, public llvm::FoldingSetNode {
1799  QualType ElementType;
1800  ComplexType(QualType Element, QualType CanonicalPtr) :
1801    Type(Complex, CanonicalPtr, Element->isDependentType(),
1802         Element->isInstantiationDependentType(),
1803         Element->isVariablyModifiedType(),
1804         Element->containsUnexpandedParameterPack()),
1805    ElementType(Element) {
1806  }
1807  friend class ASTContext;  // ASTContext creates these.
1808
1809public:
1810  QualType getElementType() const { return ElementType; }
1811
1812  bool isSugared() const { return false; }
1813  QualType desugar() const { return QualType(this, 0); }
1814
1815  void Profile(llvm::FoldingSetNodeID &ID) {
1816    Profile(ID, getElementType());
1817  }
1818  static void Profile(llvm::FoldingSetNodeID &ID, QualType Element) {
1819    ID.AddPointer(Element.getAsOpaquePtr());
1820  }
1821
1822  static bool classof(const Type *T) { return T->getTypeClass() == Complex; }
1823  static bool classof(const ComplexType *) { return true; }
1824};
1825
1826/// ParenType - Sugar for parentheses used when specifying types.
1827///
1828class ParenType : public Type, public llvm::FoldingSetNode {
1829  QualType Inner;
1830
1831  ParenType(QualType InnerType, QualType CanonType) :
1832    Type(Paren, CanonType, InnerType->isDependentType(),
1833         InnerType->isInstantiationDependentType(),
1834         InnerType->isVariablyModifiedType(),
1835         InnerType->containsUnexpandedParameterPack()),
1836    Inner(InnerType) {
1837  }
1838  friend class ASTContext;  // ASTContext creates these.
1839
1840public:
1841
1842  QualType getInnerType() const { return Inner; }
1843
1844  bool isSugared() const { return true; }
1845  QualType desugar() const { return getInnerType(); }
1846
1847  void Profile(llvm::FoldingSetNodeID &ID) {
1848    Profile(ID, getInnerType());
1849  }
1850  static void Profile(llvm::FoldingSetNodeID &ID, QualType Inner) {
1851    Inner.Profile(ID);
1852  }
1853
1854  static bool classof(const Type *T) { return T->getTypeClass() == Paren; }
1855  static bool classof(const ParenType *) { return true; }
1856};
1857
1858/// PointerType - C99 6.7.5.1 - Pointer Declarators.
1859///
1860class PointerType : public Type, public llvm::FoldingSetNode {
1861  QualType PointeeType;
1862
1863  PointerType(QualType Pointee, QualType CanonicalPtr) :
1864    Type(Pointer, CanonicalPtr, Pointee->isDependentType(),
1865         Pointee->isInstantiationDependentType(),
1866         Pointee->isVariablyModifiedType(),
1867         Pointee->containsUnexpandedParameterPack()),
1868    PointeeType(Pointee) {
1869  }
1870  friend class ASTContext;  // ASTContext creates these.
1871
1872public:
1873
1874  QualType getPointeeType() const { return PointeeType; }
1875
1876  bool isSugared() const { return false; }
1877  QualType desugar() const { return QualType(this, 0); }
1878
1879  void Profile(llvm::FoldingSetNodeID &ID) {
1880    Profile(ID, getPointeeType());
1881  }
1882  static void Profile(llvm::FoldingSetNodeID &ID, QualType Pointee) {
1883    ID.AddPointer(Pointee.getAsOpaquePtr());
1884  }
1885
1886  static bool classof(const Type *T) { return T->getTypeClass() == Pointer; }
1887  static bool classof(const PointerType *) { return true; }
1888};
1889
1890/// BlockPointerType - pointer to a block type.
1891/// This type is to represent types syntactically represented as
1892/// "void (^)(int)", etc. Pointee is required to always be a function type.
1893///
1894class BlockPointerType : public Type, public llvm::FoldingSetNode {
1895  QualType PointeeType;  // Block is some kind of pointer type
1896  BlockPointerType(QualType Pointee, QualType CanonicalCls) :
1897    Type(BlockPointer, CanonicalCls, Pointee->isDependentType(),
1898         Pointee->isInstantiationDependentType(),
1899         Pointee->isVariablyModifiedType(),
1900         Pointee->containsUnexpandedParameterPack()),
1901    PointeeType(Pointee) {
1902  }
1903  friend class ASTContext;  // ASTContext creates these.
1904
1905public:
1906
1907  // Get the pointee type. Pointee is required to always be a function type.
1908  QualType getPointeeType() const { return PointeeType; }
1909
1910  bool isSugared() const { return false; }
1911  QualType desugar() const { return QualType(this, 0); }
1912
1913  void Profile(llvm::FoldingSetNodeID &ID) {
1914      Profile(ID, getPointeeType());
1915  }
1916  static void Profile(llvm::FoldingSetNodeID &ID, QualType Pointee) {
1917      ID.AddPointer(Pointee.getAsOpaquePtr());
1918  }
1919
1920  static bool classof(const Type *T) {
1921    return T->getTypeClass() == BlockPointer;
1922  }
1923  static bool classof(const BlockPointerType *) { return true; }
1924};
1925
1926/// ReferenceType - Base for LValueReferenceType and RValueReferenceType
1927///
1928class ReferenceType : public Type, public llvm::FoldingSetNode {
1929  QualType PointeeType;
1930
1931protected:
1932  ReferenceType(TypeClass tc, QualType Referencee, QualType CanonicalRef,
1933                bool SpelledAsLValue) :
1934    Type(tc, CanonicalRef, Referencee->isDependentType(),
1935         Referencee->isInstantiationDependentType(),
1936         Referencee->isVariablyModifiedType(),
1937         Referencee->containsUnexpandedParameterPack()),
1938    PointeeType(Referencee)
1939  {
1940    ReferenceTypeBits.SpelledAsLValue = SpelledAsLValue;
1941    ReferenceTypeBits.InnerRef = Referencee->isReferenceType();
1942  }
1943
1944public:
1945  bool isSpelledAsLValue() const { return ReferenceTypeBits.SpelledAsLValue; }
1946  bool isInnerRef() const { return ReferenceTypeBits.InnerRef; }
1947
1948  QualType getPointeeTypeAsWritten() const { return PointeeType; }
1949  QualType getPointeeType() const {
1950    // FIXME: this might strip inner qualifiers; okay?
1951    const ReferenceType *T = this;
1952    while (T->isInnerRef())
1953      T = T->PointeeType->castAs<ReferenceType>();
1954    return T->PointeeType;
1955  }
1956
1957  void Profile(llvm::FoldingSetNodeID &ID) {
1958    Profile(ID, PointeeType, isSpelledAsLValue());
1959  }
1960  static void Profile(llvm::FoldingSetNodeID &ID,
1961                      QualType Referencee,
1962                      bool SpelledAsLValue) {
1963    ID.AddPointer(Referencee.getAsOpaquePtr());
1964    ID.AddBoolean(SpelledAsLValue);
1965  }
1966
1967  static bool classof(const Type *T) {
1968    return T->getTypeClass() == LValueReference ||
1969           T->getTypeClass() == RValueReference;
1970  }
1971  static bool classof(const ReferenceType *) { return true; }
1972};
1973
1974/// LValueReferenceType - C++ [dcl.ref] - Lvalue reference
1975///
1976class LValueReferenceType : public ReferenceType {
1977  LValueReferenceType(QualType Referencee, QualType CanonicalRef,
1978                      bool SpelledAsLValue) :
1979    ReferenceType(LValueReference, Referencee, CanonicalRef, SpelledAsLValue)
1980  {}
1981  friend class ASTContext; // ASTContext creates these
1982public:
1983  bool isSugared() const { return false; }
1984  QualType desugar() const { return QualType(this, 0); }
1985
1986  static bool classof(const Type *T) {
1987    return T->getTypeClass() == LValueReference;
1988  }
1989  static bool classof(const LValueReferenceType *) { return true; }
1990};
1991
1992/// RValueReferenceType - C++0x [dcl.ref] - Rvalue reference
1993///
1994class RValueReferenceType : public ReferenceType {
1995  RValueReferenceType(QualType Referencee, QualType CanonicalRef) :
1996    ReferenceType(RValueReference, Referencee, CanonicalRef, false) {
1997  }
1998  friend class ASTContext; // ASTContext creates these
1999public:
2000  bool isSugared() const { return false; }
2001  QualType desugar() const { return QualType(this, 0); }
2002
2003  static bool classof(const Type *T) {
2004    return T->getTypeClass() == RValueReference;
2005  }
2006  static bool classof(const RValueReferenceType *) { return true; }
2007};
2008
2009/// MemberPointerType - C++ 8.3.3 - Pointers to members
2010///
2011class MemberPointerType : public Type, public llvm::FoldingSetNode {
2012  QualType PointeeType;
2013  /// The class of which the pointee is a member. Must ultimately be a
2014  /// RecordType, but could be a typedef or a template parameter too.
2015  const Type *Class;
2016
2017  MemberPointerType(QualType Pointee, const Type *Cls, QualType CanonicalPtr) :
2018    Type(MemberPointer, CanonicalPtr,
2019         Cls->isDependentType() || Pointee->isDependentType(),
2020         (Cls->isInstantiationDependentType() ||
2021          Pointee->isInstantiationDependentType()),
2022         Pointee->isVariablyModifiedType(),
2023         (Cls->containsUnexpandedParameterPack() ||
2024          Pointee->containsUnexpandedParameterPack())),
2025    PointeeType(Pointee), Class(Cls) {
2026  }
2027  friend class ASTContext; // ASTContext creates these.
2028
2029public:
2030  QualType getPointeeType() const { return PointeeType; }
2031
2032  /// Returns true if the member type (i.e. the pointee type) is a
2033  /// function type rather than a data-member type.
2034  bool isMemberFunctionPointer() const {
2035    return PointeeType->isFunctionProtoType();
2036  }
2037
2038  /// Returns true if the member type (i.e. the pointee type) is a
2039  /// data type rather than a function type.
2040  bool isMemberDataPointer() const {
2041    return !PointeeType->isFunctionProtoType();
2042  }
2043
2044  const Type *getClass() const { return Class; }
2045
2046  bool isSugared() const { return false; }
2047  QualType desugar() const { return QualType(this, 0); }
2048
2049  void Profile(llvm::FoldingSetNodeID &ID) {
2050    Profile(ID, getPointeeType(), getClass());
2051  }
2052  static void Profile(llvm::FoldingSetNodeID &ID, QualType Pointee,
2053                      const Type *Class) {
2054    ID.AddPointer(Pointee.getAsOpaquePtr());
2055    ID.AddPointer(Class);
2056  }
2057
2058  static bool classof(const Type *T) {
2059    return T->getTypeClass() == MemberPointer;
2060  }
2061  static bool classof(const MemberPointerType *) { return true; }
2062};
2063
2064/// ArrayType - C99 6.7.5.2 - Array Declarators.
2065///
2066class ArrayType : public Type, public llvm::FoldingSetNode {
2067public:
2068  /// ArraySizeModifier - Capture whether this is a normal array (e.g. int X[4])
2069  /// an array with a static size (e.g. int X[static 4]), or an array
2070  /// with a star size (e.g. int X[*]).
2071  /// 'static' is only allowed on function parameters.
2072  enum ArraySizeModifier {
2073    Normal, Static, Star
2074  };
2075private:
2076  /// ElementType - The element type of the array.
2077  QualType ElementType;
2078
2079protected:
2080  // C++ [temp.dep.type]p1:
2081  //   A type is dependent if it is...
2082  //     - an array type constructed from any dependent type or whose
2083  //       size is specified by a constant expression that is
2084  //       value-dependent,
2085  ArrayType(TypeClass tc, QualType et, QualType can,
2086            ArraySizeModifier sm, unsigned tq,
2087            bool ContainsUnexpandedParameterPack)
2088    : Type(tc, can, et->isDependentType() || tc == DependentSizedArray,
2089           et->isInstantiationDependentType() || tc == DependentSizedArray,
2090           (tc == VariableArray || et->isVariablyModifiedType()),
2091           ContainsUnexpandedParameterPack),
2092      ElementType(et) {
2093    ArrayTypeBits.IndexTypeQuals = tq;
2094    ArrayTypeBits.SizeModifier = sm;
2095  }
2096
2097  friend class ASTContext;  // ASTContext creates these.
2098
2099public:
2100  QualType getElementType() const { return ElementType; }
2101  ArraySizeModifier getSizeModifier() const {
2102    return ArraySizeModifier(ArrayTypeBits.SizeModifier);
2103  }
2104  Qualifiers getIndexTypeQualifiers() const {
2105    return Qualifiers::fromCVRMask(getIndexTypeCVRQualifiers());
2106  }
2107  unsigned getIndexTypeCVRQualifiers() const {
2108    return ArrayTypeBits.IndexTypeQuals;
2109  }
2110
2111  static bool classof(const Type *T) {
2112    return T->getTypeClass() == ConstantArray ||
2113           T->getTypeClass() == VariableArray ||
2114           T->getTypeClass() == IncompleteArray ||
2115           T->getTypeClass() == DependentSizedArray;
2116  }
2117  static bool classof(const ArrayType *) { return true; }
2118};
2119
2120/// ConstantArrayType - This class represents the canonical version of
2121/// C arrays with a specified constant size.  For example, the canonical
2122/// type for 'int A[4 + 4*100]' is a ConstantArrayType where the element
2123/// type is 'int' and the size is 404.
2124class ConstantArrayType : public ArrayType {
2125  llvm::APInt Size; // Allows us to unique the type.
2126
2127  ConstantArrayType(QualType et, QualType can, const llvm::APInt &size,
2128                    ArraySizeModifier sm, unsigned tq)
2129    : ArrayType(ConstantArray, et, can, sm, tq,
2130                et->containsUnexpandedParameterPack()),
2131      Size(size) {}
2132protected:
2133  ConstantArrayType(TypeClass tc, QualType et, QualType can,
2134                    const llvm::APInt &size, ArraySizeModifier sm, unsigned tq)
2135    : ArrayType(tc, et, can, sm, tq, et->containsUnexpandedParameterPack()),
2136      Size(size) {}
2137  friend class ASTContext;  // ASTContext creates these.
2138public:
2139  const llvm::APInt &getSize() const { return Size; }
2140  bool isSugared() const { return false; }
2141  QualType desugar() const { return QualType(this, 0); }
2142
2143
2144  /// \brief Determine the number of bits required to address a member of
2145  // an array with the given element type and number of elements.
2146  static unsigned getNumAddressingBits(ASTContext &Context,
2147                                       QualType ElementType,
2148                                       const llvm::APInt &NumElements);
2149
2150  /// \brief Determine the maximum number of active bits that an array's size
2151  /// can require, which limits the maximum size of the array.
2152  static unsigned getMaxSizeBits(ASTContext &Context);
2153
2154  void Profile(llvm::FoldingSetNodeID &ID) {
2155    Profile(ID, getElementType(), getSize(),
2156            getSizeModifier(), getIndexTypeCVRQualifiers());
2157  }
2158  static void Profile(llvm::FoldingSetNodeID &ID, QualType ET,
2159                      const llvm::APInt &ArraySize, ArraySizeModifier SizeMod,
2160                      unsigned TypeQuals) {
2161    ID.AddPointer(ET.getAsOpaquePtr());
2162    ID.AddInteger(ArraySize.getZExtValue());
2163    ID.AddInteger(SizeMod);
2164    ID.AddInteger(TypeQuals);
2165  }
2166  static bool classof(const Type *T) {
2167    return T->getTypeClass() == ConstantArray;
2168  }
2169  static bool classof(const ConstantArrayType *) { return true; }
2170};
2171
2172/// IncompleteArrayType - This class represents C arrays with an unspecified
2173/// size.  For example 'int A[]' has an IncompleteArrayType where the element
2174/// type is 'int' and the size is unspecified.
2175class IncompleteArrayType : public ArrayType {
2176
2177  IncompleteArrayType(QualType et, QualType can,
2178                      ArraySizeModifier sm, unsigned tq)
2179    : ArrayType(IncompleteArray, et, can, sm, tq,
2180                et->containsUnexpandedParameterPack()) {}
2181  friend class ASTContext;  // ASTContext creates these.
2182public:
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() == IncompleteArray;
2188  }
2189  static bool classof(const IncompleteArrayType *) { return true; }
2190
2191  friend class StmtIteratorBase;
2192
2193  void Profile(llvm::FoldingSetNodeID &ID) {
2194    Profile(ID, getElementType(), getSizeModifier(),
2195            getIndexTypeCVRQualifiers());
2196  }
2197
2198  static void Profile(llvm::FoldingSetNodeID &ID, QualType ET,
2199                      ArraySizeModifier SizeMod, unsigned TypeQuals) {
2200    ID.AddPointer(ET.getAsOpaquePtr());
2201    ID.AddInteger(SizeMod);
2202    ID.AddInteger(TypeQuals);
2203  }
2204};
2205
2206/// VariableArrayType - This class represents C arrays with a specified size
2207/// which is not an integer-constant-expression.  For example, 'int s[x+foo()]'.
2208/// Since the size expression is an arbitrary expression, we store it as such.
2209///
2210/// Note: VariableArrayType's aren't uniqued (since the expressions aren't) and
2211/// should not be: two lexically equivalent variable array types could mean
2212/// different things, for example, these variables do not have the same type
2213/// dynamically:
2214///
2215/// void foo(int x) {
2216///   int Y[x];
2217///   ++x;
2218///   int Z[x];
2219/// }
2220///
2221class VariableArrayType : public ArrayType {
2222  /// SizeExpr - An assignment expression. VLA's are only permitted within
2223  /// a function block.
2224  Stmt *SizeExpr;
2225  /// Brackets - The left and right array brackets.
2226  SourceRange Brackets;
2227
2228  VariableArrayType(QualType et, QualType can, Expr *e,
2229                    ArraySizeModifier sm, unsigned tq,
2230                    SourceRange brackets)
2231    : ArrayType(VariableArray, et, can, sm, tq,
2232                et->containsUnexpandedParameterPack()),
2233      SizeExpr((Stmt*) e), Brackets(brackets) {}
2234  friend class ASTContext;  // ASTContext creates these.
2235
2236public:
2237  Expr *getSizeExpr() const {
2238    // We use C-style casts instead of cast<> here because we do not wish
2239    // to have a dependency of Type.h on Stmt.h/Expr.h.
2240    return (Expr*) SizeExpr;
2241  }
2242  SourceRange getBracketsRange() const { return Brackets; }
2243  SourceLocation getLBracketLoc() const { return Brackets.getBegin(); }
2244  SourceLocation getRBracketLoc() const { return Brackets.getEnd(); }
2245
2246  bool isSugared() const { return false; }
2247  QualType desugar() const { return QualType(this, 0); }
2248
2249  static bool classof(const Type *T) {
2250    return T->getTypeClass() == VariableArray;
2251  }
2252  static bool classof(const VariableArrayType *) { return true; }
2253
2254  friend class StmtIteratorBase;
2255
2256  void Profile(llvm::FoldingSetNodeID &ID) {
2257    llvm_unreachable("Cannot unique VariableArrayTypes.");
2258  }
2259};
2260
2261/// DependentSizedArrayType - This type represents an array type in
2262/// C++ whose size is a value-dependent expression. For example:
2263///
2264/// \code
2265/// template<typename T, int Size>
2266/// class array {
2267///   T data[Size];
2268/// };
2269/// \endcode
2270///
2271/// For these types, we won't actually know what the array bound is
2272/// until template instantiation occurs, at which point this will
2273/// become either a ConstantArrayType or a VariableArrayType.
2274class DependentSizedArrayType : public ArrayType {
2275  const ASTContext &Context;
2276
2277  /// \brief An assignment expression that will instantiate to the
2278  /// size of the array.
2279  ///
2280  /// The expression itself might be NULL, in which case the array
2281  /// type will have its size deduced from an initializer.
2282  Stmt *SizeExpr;
2283
2284  /// Brackets - The left and right array brackets.
2285  SourceRange Brackets;
2286
2287  DependentSizedArrayType(const ASTContext &Context, QualType et, QualType can,
2288                          Expr *e, ArraySizeModifier sm, unsigned tq,
2289                          SourceRange brackets);
2290
2291  friend class ASTContext;  // ASTContext creates these.
2292
2293public:
2294  Expr *getSizeExpr() const {
2295    // We use C-style casts instead of cast<> here because we do not wish
2296    // to have a dependency of Type.h on Stmt.h/Expr.h.
2297    return (Expr*) SizeExpr;
2298  }
2299  SourceRange getBracketsRange() const { return Brackets; }
2300  SourceLocation getLBracketLoc() const { return Brackets.getBegin(); }
2301  SourceLocation getRBracketLoc() const { return Brackets.getEnd(); }
2302
2303  bool isSugared() const { return false; }
2304  QualType desugar() const { return QualType(this, 0); }
2305
2306  static bool classof(const Type *T) {
2307    return T->getTypeClass() == DependentSizedArray;
2308  }
2309  static bool classof(const DependentSizedArrayType *) { return true; }
2310
2311  friend class StmtIteratorBase;
2312
2313
2314  void Profile(llvm::FoldingSetNodeID &ID) {
2315    Profile(ID, Context, getElementType(),
2316            getSizeModifier(), getIndexTypeCVRQualifiers(), getSizeExpr());
2317  }
2318
2319  static void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context,
2320                      QualType ET, ArraySizeModifier SizeMod,
2321                      unsigned TypeQuals, Expr *E);
2322};
2323
2324/// DependentSizedExtVectorType - This type represent an extended vector type
2325/// where either the type or size is dependent. For example:
2326/// @code
2327/// template<typename T, int Size>
2328/// class vector {
2329///   typedef T __attribute__((ext_vector_type(Size))) type;
2330/// }
2331/// @endcode
2332class DependentSizedExtVectorType : public Type, public llvm::FoldingSetNode {
2333  const ASTContext &Context;
2334  Expr *SizeExpr;
2335  /// ElementType - The element type of the array.
2336  QualType ElementType;
2337  SourceLocation loc;
2338
2339  DependentSizedExtVectorType(const ASTContext &Context, QualType ElementType,
2340                              QualType can, Expr *SizeExpr, SourceLocation loc);
2341
2342  friend class ASTContext;
2343
2344public:
2345  Expr *getSizeExpr() const { return SizeExpr; }
2346  QualType getElementType() const { return ElementType; }
2347  SourceLocation getAttributeLoc() const { return loc; }
2348
2349  bool isSugared() const { return false; }
2350  QualType desugar() const { return QualType(this, 0); }
2351
2352  static bool classof(const Type *T) {
2353    return T->getTypeClass() == DependentSizedExtVector;
2354  }
2355  static bool classof(const DependentSizedExtVectorType *) { return true; }
2356
2357  void Profile(llvm::FoldingSetNodeID &ID) {
2358    Profile(ID, Context, getElementType(), getSizeExpr());
2359  }
2360
2361  static void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context,
2362                      QualType ElementType, Expr *SizeExpr);
2363};
2364
2365
2366/// VectorType - GCC generic vector type. This type is created using
2367/// __attribute__((vector_size(n)), where "n" specifies the vector size in
2368/// bytes; or from an Altivec __vector or vector declaration.
2369/// Since the constructor takes the number of vector elements, the
2370/// client is responsible for converting the size into the number of elements.
2371class VectorType : public Type, public llvm::FoldingSetNode {
2372public:
2373  enum VectorKind {
2374    GenericVector,  // not a target-specific vector type
2375    AltiVecVector,  // is AltiVec vector
2376    AltiVecPixel,   // is AltiVec 'vector Pixel'
2377    AltiVecBool,    // is AltiVec 'vector bool ...'
2378    NeonVector,     // is ARM Neon vector
2379    NeonPolyVector  // is ARM Neon polynomial vector
2380  };
2381protected:
2382  /// ElementType - The element type of the vector.
2383  QualType ElementType;
2384
2385  VectorType(QualType vecType, unsigned nElements, QualType canonType,
2386             VectorKind vecKind);
2387
2388  VectorType(TypeClass tc, QualType vecType, unsigned nElements,
2389             QualType canonType, VectorKind vecKind);
2390
2391  friend class ASTContext;  // ASTContext creates these.
2392
2393public:
2394
2395  QualType getElementType() const { return ElementType; }
2396  unsigned getNumElements() const { return VectorTypeBits.NumElements; }
2397
2398  bool isSugared() const { return false; }
2399  QualType desugar() const { return QualType(this, 0); }
2400
2401  VectorKind getVectorKind() const {
2402    return VectorKind(VectorTypeBits.VecKind);
2403  }
2404
2405  void Profile(llvm::FoldingSetNodeID &ID) {
2406    Profile(ID, getElementType(), getNumElements(),
2407            getTypeClass(), getVectorKind());
2408  }
2409  static void Profile(llvm::FoldingSetNodeID &ID, QualType ElementType,
2410                      unsigned NumElements, TypeClass TypeClass,
2411                      VectorKind VecKind) {
2412    ID.AddPointer(ElementType.getAsOpaquePtr());
2413    ID.AddInteger(NumElements);
2414    ID.AddInteger(TypeClass);
2415    ID.AddInteger(VecKind);
2416  }
2417
2418  static bool classof(const Type *T) {
2419    return T->getTypeClass() == Vector || T->getTypeClass() == ExtVector;
2420  }
2421  static bool classof(const VectorType *) { return true; }
2422};
2423
2424/// ExtVectorType - Extended vector type. This type is created using
2425/// __attribute__((ext_vector_type(n)), where "n" is the number of elements.
2426/// Unlike vector_size, ext_vector_type is only allowed on typedef's. This
2427/// class enables syntactic extensions, like Vector Components for accessing
2428/// points, colors, and textures (modeled after OpenGL Shading Language).
2429class ExtVectorType : public VectorType {
2430  ExtVectorType(QualType vecType, unsigned nElements, QualType canonType) :
2431    VectorType(ExtVector, vecType, nElements, canonType, GenericVector) {}
2432  friend class ASTContext;  // ASTContext creates these.
2433public:
2434  static int getPointAccessorIdx(char c) {
2435    switch (c) {
2436    default: return -1;
2437    case 'x': return 0;
2438    case 'y': return 1;
2439    case 'z': return 2;
2440    case 'w': return 3;
2441    }
2442  }
2443  static int getNumericAccessorIdx(char c) {
2444    switch (c) {
2445      default: return -1;
2446      case '0': return 0;
2447      case '1': return 1;
2448      case '2': return 2;
2449      case '3': return 3;
2450      case '4': return 4;
2451      case '5': return 5;
2452      case '6': return 6;
2453      case '7': return 7;
2454      case '8': return 8;
2455      case '9': return 9;
2456      case 'A':
2457      case 'a': return 10;
2458      case 'B':
2459      case 'b': return 11;
2460      case 'C':
2461      case 'c': return 12;
2462      case 'D':
2463      case 'd': return 13;
2464      case 'E':
2465      case 'e': return 14;
2466      case 'F':
2467      case 'f': return 15;
2468    }
2469  }
2470
2471  static int getAccessorIdx(char c) {
2472    if (int idx = getPointAccessorIdx(c)+1) return idx-1;
2473    return getNumericAccessorIdx(c);
2474  }
2475
2476  bool isAccessorWithinNumElements(char c) const {
2477    if (int idx = getAccessorIdx(c)+1)
2478      return unsigned(idx-1) < getNumElements();
2479    return false;
2480  }
2481  bool isSugared() const { return false; }
2482  QualType desugar() const { return QualType(this, 0); }
2483
2484  static bool classof(const Type *T) {
2485    return T->getTypeClass() == ExtVector;
2486  }
2487  static bool classof(const ExtVectorType *) { return true; }
2488};
2489
2490/// FunctionType - C99 6.7.5.3 - Function Declarators.  This is the common base
2491/// class of FunctionNoProtoType and FunctionProtoType.
2492///
2493class FunctionType : public Type {
2494  // The type returned by the function.
2495  QualType ResultType;
2496
2497 public:
2498  /// ExtInfo - A class which abstracts out some details necessary for
2499  /// making a call.
2500  ///
2501  /// It is not actually used directly for storing this information in
2502  /// a FunctionType, although FunctionType does currently use the
2503  /// same bit-pattern.
2504  ///
2505  // If you add a field (say Foo), other than the obvious places (both,
2506  // constructors, compile failures), what you need to update is
2507  // * Operator==
2508  // * getFoo
2509  // * withFoo
2510  // * functionType. Add Foo, getFoo.
2511  // * ASTContext::getFooType
2512  // * ASTContext::mergeFunctionTypes
2513  // * FunctionNoProtoType::Profile
2514  // * FunctionProtoType::Profile
2515  // * TypePrinter::PrintFunctionProto
2516  // * AST read and write
2517  // * Codegen
2518  class ExtInfo {
2519    // Feel free to rearrange or add bits, but if you go over 8,
2520    // you'll need to adjust both the Bits field below and
2521    // Type::FunctionTypeBitfields.
2522
2523    //   |  CC  |noreturn|produces|regparm|
2524    //   |0 .. 2|   3    |    4   | 5 .. 7|
2525    //
2526    // regparm is either 0 (no regparm attribute) or the regparm value+1.
2527    enum { CallConvMask = 0x7 };
2528    enum { NoReturnMask = 0x8 };
2529    enum { ProducesResultMask = 0x10 };
2530    enum { RegParmMask = ~(CallConvMask | NoReturnMask | ProducesResultMask),
2531           RegParmOffset = 5 }; // Assumed to be the last field
2532
2533    uint16_t Bits;
2534
2535    ExtInfo(unsigned Bits) : Bits(static_cast<uint16_t>(Bits)) {}
2536
2537    friend class FunctionType;
2538
2539   public:
2540    // Constructor with no defaults. Use this when you know that you
2541    // have all the elements (when reading an AST file for example).
2542    ExtInfo(bool noReturn, bool hasRegParm, unsigned regParm, CallingConv cc,
2543            bool producesResult) {
2544      assert((!hasRegParm || regParm < 7) && "Invalid regparm value");
2545      Bits = ((unsigned) cc) |
2546             (noReturn ? NoReturnMask : 0) |
2547             (producesResult ? ProducesResultMask : 0) |
2548             (hasRegParm ? ((regParm + 1) << RegParmOffset) : 0);
2549    }
2550
2551    // Constructor with all defaults. Use when for example creating a
2552    // function know to use defaults.
2553    ExtInfo() : Bits(0) {}
2554
2555    bool getNoReturn() const { return Bits & NoReturnMask; }
2556    bool getProducesResult() const { return Bits & ProducesResultMask; }
2557    bool getHasRegParm() const { return (Bits >> RegParmOffset) != 0; }
2558    unsigned getRegParm() const {
2559      unsigned RegParm = Bits >> RegParmOffset;
2560      if (RegParm > 0)
2561        --RegParm;
2562      return RegParm;
2563    }
2564    CallingConv getCC() const { return CallingConv(Bits & CallConvMask); }
2565
2566    bool operator==(ExtInfo Other) const {
2567      return Bits == Other.Bits;
2568    }
2569    bool operator!=(ExtInfo Other) const {
2570      return Bits != Other.Bits;
2571    }
2572
2573    // Note that we don't have setters. That is by design, use
2574    // the following with methods instead of mutating these objects.
2575
2576    ExtInfo withNoReturn(bool noReturn) const {
2577      if (noReturn)
2578        return ExtInfo(Bits | NoReturnMask);
2579      else
2580        return ExtInfo(Bits & ~NoReturnMask);
2581    }
2582
2583    ExtInfo withProducesResult(bool producesResult) const {
2584      if (producesResult)
2585        return ExtInfo(Bits | ProducesResultMask);
2586      else
2587        return ExtInfo(Bits & ~ProducesResultMask);
2588    }
2589
2590    ExtInfo withRegParm(unsigned RegParm) const {
2591      assert(RegParm < 7 && "Invalid regparm value");
2592      return ExtInfo((Bits & ~RegParmMask) |
2593                     ((RegParm + 1) << RegParmOffset));
2594    }
2595
2596    ExtInfo withCallingConv(CallingConv cc) const {
2597      return ExtInfo((Bits & ~CallConvMask) | (unsigned) cc);
2598    }
2599
2600    void Profile(llvm::FoldingSetNodeID &ID) const {
2601      ID.AddInteger(Bits);
2602    }
2603  };
2604
2605protected:
2606  FunctionType(TypeClass tc, QualType res, bool variadic,
2607               unsigned typeQuals, RefQualifierKind RefQualifier,
2608               QualType Canonical, bool Dependent,
2609               bool InstantiationDependent,
2610               bool VariablyModified, bool ContainsUnexpandedParameterPack,
2611               ExtInfo Info)
2612    : Type(tc, Canonical, Dependent, InstantiationDependent, VariablyModified,
2613           ContainsUnexpandedParameterPack),
2614      ResultType(res) {
2615    FunctionTypeBits.ExtInfo = Info.Bits;
2616    FunctionTypeBits.Variadic = variadic;
2617    FunctionTypeBits.TypeQuals = typeQuals;
2618    FunctionTypeBits.RefQualifier = static_cast<unsigned>(RefQualifier);
2619  }
2620  bool isVariadic() const { return FunctionTypeBits.Variadic; }
2621  unsigned getTypeQuals() const { return FunctionTypeBits.TypeQuals; }
2622
2623  RefQualifierKind getRefQualifier() const {
2624    return static_cast<RefQualifierKind>(FunctionTypeBits.RefQualifier);
2625  }
2626
2627public:
2628
2629  QualType getResultType() const { return ResultType; }
2630
2631  bool getHasRegParm() const { return getExtInfo().getHasRegParm(); }
2632  unsigned getRegParmType() const { return getExtInfo().getRegParm(); }
2633  bool getNoReturnAttr() const { return getExtInfo().getNoReturn(); }
2634  CallingConv getCallConv() const { return getExtInfo().getCC(); }
2635  ExtInfo getExtInfo() const { return ExtInfo(FunctionTypeBits.ExtInfo); }
2636
2637  /// \brief Determine the type of an expression that calls a function of
2638  /// this type.
2639  QualType getCallResultType(ASTContext &Context) const {
2640    return getResultType().getNonLValueExprType(Context);
2641  }
2642
2643  static StringRef getNameForCallConv(CallingConv CC);
2644
2645  static bool classof(const Type *T) {
2646    return T->getTypeClass() == FunctionNoProto ||
2647           T->getTypeClass() == FunctionProto;
2648  }
2649  static bool classof(const FunctionType *) { return true; }
2650};
2651
2652/// FunctionNoProtoType - Represents a K&R-style 'int foo()' function, which has
2653/// no information available about its arguments.
2654class FunctionNoProtoType : public FunctionType, public llvm::FoldingSetNode {
2655  FunctionNoProtoType(QualType Result, QualType Canonical, ExtInfo Info)
2656    : FunctionType(FunctionNoProto, Result, false, 0, RQ_None, Canonical,
2657                   /*Dependent=*/false, /*InstantiationDependent=*/false,
2658                   Result->isVariablyModifiedType(),
2659                   /*ContainsUnexpandedParameterPack=*/false, Info) {}
2660
2661  friend class ASTContext;  // ASTContext creates these.
2662
2663public:
2664  // No additional state past what FunctionType provides.
2665
2666  bool isSugared() const { return false; }
2667  QualType desugar() const { return QualType(this, 0); }
2668
2669  void Profile(llvm::FoldingSetNodeID &ID) {
2670    Profile(ID, getResultType(), getExtInfo());
2671  }
2672  static void Profile(llvm::FoldingSetNodeID &ID, QualType ResultType,
2673                      ExtInfo Info) {
2674    Info.Profile(ID);
2675    ID.AddPointer(ResultType.getAsOpaquePtr());
2676  }
2677
2678  static bool classof(const Type *T) {
2679    return T->getTypeClass() == FunctionNoProto;
2680  }
2681  static bool classof(const FunctionNoProtoType *) { return true; }
2682};
2683
2684/// FunctionProtoType - Represents a prototype with argument type info, e.g.
2685/// 'int foo(int)' or 'int foo(void)'.  'void' is represented as having no
2686/// arguments, not as having a single void argument. Such a type can have an
2687/// exception specification, but this specification is not part of the canonical
2688/// type.
2689class FunctionProtoType : public FunctionType, public llvm::FoldingSetNode {
2690public:
2691  /// ExtProtoInfo - Extra information about a function prototype.
2692  struct ExtProtoInfo {
2693    ExtProtoInfo() :
2694      Variadic(false), ExceptionSpecType(EST_None), TypeQuals(0),
2695      RefQualifier(RQ_None), NumExceptions(0), Exceptions(0), NoexceptExpr(0),
2696      ConsumedArguments(0) {}
2697
2698    FunctionType::ExtInfo ExtInfo;
2699    bool Variadic;
2700    ExceptionSpecificationType ExceptionSpecType;
2701    unsigned char TypeQuals;
2702    RefQualifierKind RefQualifier;
2703    unsigned NumExceptions;
2704    const QualType *Exceptions;
2705    Expr *NoexceptExpr;
2706    const bool *ConsumedArguments;
2707  };
2708
2709private:
2710  /// \brief Determine whether there are any argument types that
2711  /// contain an unexpanded parameter pack.
2712  static bool containsAnyUnexpandedParameterPack(const QualType *ArgArray,
2713                                                 unsigned numArgs) {
2714    for (unsigned Idx = 0; Idx < numArgs; ++Idx)
2715      if (ArgArray[Idx]->containsUnexpandedParameterPack())
2716        return true;
2717
2718    return false;
2719  }
2720
2721  FunctionProtoType(QualType result, const QualType *args, unsigned numArgs,
2722                    QualType canonical, const ExtProtoInfo &epi);
2723
2724  /// NumArgs - The number of arguments this function has, not counting '...'.
2725  unsigned NumArgs : 19;
2726
2727  /// NumExceptions - The number of types in the exception spec, if any.
2728  unsigned NumExceptions : 9;
2729
2730  /// ExceptionSpecType - The type of exception specification this function has.
2731  unsigned ExceptionSpecType : 3;
2732
2733  /// HasAnyConsumedArgs - Whether this function has any consumed arguments.
2734  unsigned HasAnyConsumedArgs : 1;
2735
2736  /// ArgInfo - There is an variable size array after the class in memory that
2737  /// holds the argument types.
2738
2739  /// Exceptions - There is another variable size array after ArgInfo that
2740  /// holds the exception types.
2741
2742  /// NoexceptExpr - Instead of Exceptions, there may be a single Expr* pointing
2743  /// to the expression in the noexcept() specifier.
2744
2745  /// ConsumedArgs - A variable size array, following Exceptions
2746  /// and of length NumArgs, holding flags indicating which arguments
2747  /// are consumed.  This only appears if HasAnyConsumedArgs is true.
2748
2749  friend class ASTContext;  // ASTContext creates these.
2750
2751  const bool *getConsumedArgsBuffer() const {
2752    assert(hasAnyConsumedArgs());
2753
2754    // Find the end of the exceptions.
2755    Expr * const *eh_end = reinterpret_cast<Expr * const *>(arg_type_end());
2756    if (getExceptionSpecType() != EST_ComputedNoexcept)
2757      eh_end += NumExceptions;
2758    else
2759      eh_end += 1; // NoexceptExpr
2760
2761    return reinterpret_cast<const bool*>(eh_end);
2762  }
2763
2764public:
2765  unsigned getNumArgs() const { return NumArgs; }
2766  QualType getArgType(unsigned i) const {
2767    assert(i < NumArgs && "Invalid argument number!");
2768    return arg_type_begin()[i];
2769  }
2770
2771  ExtProtoInfo getExtProtoInfo() const {
2772    ExtProtoInfo EPI;
2773    EPI.ExtInfo = getExtInfo();
2774    EPI.Variadic = isVariadic();
2775    EPI.ExceptionSpecType = getExceptionSpecType();
2776    EPI.TypeQuals = static_cast<unsigned char>(getTypeQuals());
2777    EPI.RefQualifier = getRefQualifier();
2778    if (EPI.ExceptionSpecType == EST_Dynamic) {
2779      EPI.NumExceptions = NumExceptions;
2780      EPI.Exceptions = exception_begin();
2781    } else if (EPI.ExceptionSpecType == EST_ComputedNoexcept) {
2782      EPI.NoexceptExpr = getNoexceptExpr();
2783    }
2784    if (hasAnyConsumedArgs())
2785      EPI.ConsumedArguments = getConsumedArgsBuffer();
2786    return EPI;
2787  }
2788
2789  /// \brief Get the kind of exception specification on this function.
2790  ExceptionSpecificationType getExceptionSpecType() const {
2791    return static_cast<ExceptionSpecificationType>(ExceptionSpecType);
2792  }
2793  /// \brief Return whether this function has any kind of exception spec.
2794  bool hasExceptionSpec() const {
2795    return getExceptionSpecType() != EST_None;
2796  }
2797  /// \brief Return whether this function has a dynamic (throw) exception spec.
2798  bool hasDynamicExceptionSpec() const {
2799    return isDynamicExceptionSpec(getExceptionSpecType());
2800  }
2801  /// \brief Return whether this function has a noexcept exception spec.
2802  bool hasNoexceptExceptionSpec() const {
2803    return isNoexceptExceptionSpec(getExceptionSpecType());
2804  }
2805  /// \brief Result type of getNoexceptSpec().
2806  enum NoexceptResult {
2807    NR_NoNoexcept,  ///< There is no noexcept specifier.
2808    NR_BadNoexcept, ///< The noexcept specifier has a bad expression.
2809    NR_Dependent,   ///< The noexcept specifier is dependent.
2810    NR_Throw,       ///< The noexcept specifier evaluates to false.
2811    NR_Nothrow      ///< The noexcept specifier evaluates to true.
2812  };
2813  /// \brief Get the meaning of the noexcept spec on this function, if any.
2814  NoexceptResult getNoexceptSpec(ASTContext &Ctx) const;
2815  unsigned getNumExceptions() const { return NumExceptions; }
2816  QualType getExceptionType(unsigned i) const {
2817    assert(i < NumExceptions && "Invalid exception number!");
2818    return exception_begin()[i];
2819  }
2820  Expr *getNoexceptExpr() const {
2821    if (getExceptionSpecType() != EST_ComputedNoexcept)
2822      return 0;
2823    // NoexceptExpr sits where the arguments end.
2824    return *reinterpret_cast<Expr *const *>(arg_type_end());
2825  }
2826  bool isNothrow(ASTContext &Ctx) const {
2827    ExceptionSpecificationType EST = getExceptionSpecType();
2828    assert(EST != EST_Delayed);
2829    if (EST == EST_DynamicNone || EST == EST_BasicNoexcept)
2830      return true;
2831    if (EST != EST_ComputedNoexcept)
2832      return false;
2833    return getNoexceptSpec(Ctx) == NR_Nothrow;
2834  }
2835
2836  using FunctionType::isVariadic;
2837
2838  /// \brief Determines whether this function prototype contains a
2839  /// parameter pack at the end.
2840  ///
2841  /// A function template whose last parameter is a parameter pack can be
2842  /// called with an arbitrary number of arguments, much like a variadic
2843  /// function. However,
2844  bool isTemplateVariadic() const;
2845
2846  unsigned getTypeQuals() const { return FunctionType::getTypeQuals(); }
2847
2848
2849  /// \brief Retrieve the ref-qualifier associated with this function type.
2850  RefQualifierKind getRefQualifier() const {
2851    return FunctionType::getRefQualifier();
2852  }
2853
2854  typedef const QualType *arg_type_iterator;
2855  arg_type_iterator arg_type_begin() const {
2856    return reinterpret_cast<const QualType *>(this+1);
2857  }
2858  arg_type_iterator arg_type_end() const { return arg_type_begin()+NumArgs; }
2859
2860  typedef const QualType *exception_iterator;
2861  exception_iterator exception_begin() const {
2862    // exceptions begin where arguments end
2863    return arg_type_end();
2864  }
2865  exception_iterator exception_end() const {
2866    if (getExceptionSpecType() != EST_Dynamic)
2867      return exception_begin();
2868    return exception_begin() + NumExceptions;
2869  }
2870
2871  bool hasAnyConsumedArgs() const {
2872    return HasAnyConsumedArgs;
2873  }
2874  bool isArgConsumed(unsigned I) const {
2875    assert(I < getNumArgs() && "argument index out of range!");
2876    if (hasAnyConsumedArgs())
2877      return getConsumedArgsBuffer()[I];
2878    return false;
2879  }
2880
2881  bool isSugared() const { return false; }
2882  QualType desugar() const { return QualType(this, 0); }
2883
2884  static bool classof(const Type *T) {
2885    return T->getTypeClass() == FunctionProto;
2886  }
2887  static bool classof(const FunctionProtoType *) { return true; }
2888
2889  void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Ctx);
2890  static void Profile(llvm::FoldingSetNodeID &ID, QualType Result,
2891                      arg_type_iterator ArgTys, unsigned NumArgs,
2892                      const ExtProtoInfo &EPI, const ASTContext &Context);
2893};
2894
2895
2896/// \brief Represents the dependent type named by a dependently-scoped
2897/// typename using declaration, e.g.
2898///   using typename Base<T>::foo;
2899/// Template instantiation turns these into the underlying type.
2900class UnresolvedUsingType : public Type {
2901  UnresolvedUsingTypenameDecl *Decl;
2902
2903  UnresolvedUsingType(const UnresolvedUsingTypenameDecl *D)
2904    : Type(UnresolvedUsing, QualType(), true, true, false,
2905           /*ContainsUnexpandedParameterPack=*/false),
2906      Decl(const_cast<UnresolvedUsingTypenameDecl*>(D)) {}
2907  friend class ASTContext; // ASTContext creates these.
2908public:
2909
2910  UnresolvedUsingTypenameDecl *getDecl() const { return Decl; }
2911
2912  bool isSugared() const { return false; }
2913  QualType desugar() const { return QualType(this, 0); }
2914
2915  static bool classof(const Type *T) {
2916    return T->getTypeClass() == UnresolvedUsing;
2917  }
2918  static bool classof(const UnresolvedUsingType *) { return true; }
2919
2920  void Profile(llvm::FoldingSetNodeID &ID) {
2921    return Profile(ID, Decl);
2922  }
2923  static void Profile(llvm::FoldingSetNodeID &ID,
2924                      UnresolvedUsingTypenameDecl *D) {
2925    ID.AddPointer(D);
2926  }
2927};
2928
2929
2930class TypedefType : public Type {
2931  TypedefNameDecl *Decl;
2932protected:
2933  TypedefType(TypeClass tc, const TypedefNameDecl *D, QualType can)
2934    : Type(tc, can, can->isDependentType(),
2935           can->isInstantiationDependentType(),
2936           can->isVariablyModifiedType(),
2937           /*ContainsUnexpandedParameterPack=*/false),
2938      Decl(const_cast<TypedefNameDecl*>(D)) {
2939    assert(!isa<TypedefType>(can) && "Invalid canonical type");
2940  }
2941  friend class ASTContext;  // ASTContext creates these.
2942public:
2943
2944  TypedefNameDecl *getDecl() const { return Decl; }
2945
2946  bool isSugared() const { return true; }
2947  QualType desugar() const;
2948
2949  static bool classof(const Type *T) { return T->getTypeClass() == Typedef; }
2950  static bool classof(const TypedefType *) { return true; }
2951};
2952
2953/// TypeOfExprType (GCC extension).
2954class TypeOfExprType : public Type {
2955  Expr *TOExpr;
2956
2957protected:
2958  TypeOfExprType(Expr *E, QualType can = QualType());
2959  friend class ASTContext;  // ASTContext creates these.
2960public:
2961  Expr *getUnderlyingExpr() const { return TOExpr; }
2962
2963  /// \brief Remove a single level of sugar.
2964  QualType desugar() const;
2965
2966  /// \brief Returns whether this type directly provides sugar.
2967  bool isSugared() const;
2968
2969  static bool classof(const Type *T) { return T->getTypeClass() == TypeOfExpr; }
2970  static bool classof(const TypeOfExprType *) { return true; }
2971};
2972
2973/// \brief Internal representation of canonical, dependent
2974/// typeof(expr) types.
2975///
2976/// This class is used internally by the ASTContext to manage
2977/// canonical, dependent types, only. Clients will only see instances
2978/// of this class via TypeOfExprType nodes.
2979class DependentTypeOfExprType
2980  : public TypeOfExprType, public llvm::FoldingSetNode {
2981  const ASTContext &Context;
2982
2983public:
2984  DependentTypeOfExprType(const ASTContext &Context, Expr *E)
2985    : TypeOfExprType(E), Context(Context) { }
2986
2987  void Profile(llvm::FoldingSetNodeID &ID) {
2988    Profile(ID, Context, getUnderlyingExpr());
2989  }
2990
2991  static void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context,
2992                      Expr *E);
2993};
2994
2995/// TypeOfType (GCC extension).
2996class TypeOfType : public Type {
2997  QualType TOType;
2998  TypeOfType(QualType T, QualType can)
2999    : Type(TypeOf, can, T->isDependentType(),
3000           T->isInstantiationDependentType(),
3001           T->isVariablyModifiedType(),
3002           T->containsUnexpandedParameterPack()),
3003      TOType(T) {
3004    assert(!isa<TypedefType>(can) && "Invalid canonical type");
3005  }
3006  friend class ASTContext;  // ASTContext creates these.
3007public:
3008  QualType getUnderlyingType() const { return TOType; }
3009
3010  /// \brief Remove a single level of sugar.
3011  QualType desugar() const { return getUnderlyingType(); }
3012
3013  /// \brief Returns whether this type directly provides sugar.
3014  bool isSugared() const { return true; }
3015
3016  static bool classof(const Type *T) { return T->getTypeClass() == TypeOf; }
3017  static bool classof(const TypeOfType *) { return true; }
3018};
3019
3020/// DecltypeType (C++0x)
3021class DecltypeType : public Type {
3022  Expr *E;
3023
3024  // FIXME: We could get rid of UnderlyingType if we wanted to: We would have to
3025  // Move getDesugaredType to ASTContext so that it can call getDecltypeForExpr
3026  // from it.
3027  QualType UnderlyingType;
3028
3029protected:
3030  DecltypeType(Expr *E, QualType underlyingType, QualType can = QualType());
3031  friend class ASTContext;  // ASTContext creates these.
3032public:
3033  Expr *getUnderlyingExpr() const { return E; }
3034  QualType getUnderlyingType() const { return UnderlyingType; }
3035
3036  /// \brief Remove a single level of sugar.
3037  QualType desugar() const;
3038
3039  /// \brief Returns whether this type directly provides sugar.
3040  bool isSugared() const;
3041
3042  static bool classof(const Type *T) { return T->getTypeClass() == Decltype; }
3043  static bool classof(const DecltypeType *) { return true; }
3044};
3045
3046/// \brief Internal representation of canonical, dependent
3047/// decltype(expr) types.
3048///
3049/// This class is used internally by the ASTContext to manage
3050/// canonical, dependent types, only. Clients will only see instances
3051/// of this class via DecltypeType nodes.
3052class DependentDecltypeType : public DecltypeType, public llvm::FoldingSetNode {
3053  const ASTContext &Context;
3054
3055public:
3056  DependentDecltypeType(const ASTContext &Context, Expr *E);
3057
3058  void Profile(llvm::FoldingSetNodeID &ID) {
3059    Profile(ID, Context, getUnderlyingExpr());
3060  }
3061
3062  static void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context,
3063                      Expr *E);
3064};
3065
3066/// \brief A unary type transform, which is a type constructed from another
3067class UnaryTransformType : public Type {
3068public:
3069  enum UTTKind {
3070    EnumUnderlyingType
3071  };
3072
3073private:
3074  /// The untransformed type.
3075  QualType BaseType;
3076  /// The transformed type if not dependent, otherwise the same as BaseType.
3077  QualType UnderlyingType;
3078
3079  UTTKind UKind;
3080protected:
3081  UnaryTransformType(QualType BaseTy, QualType UnderlyingTy, UTTKind UKind,
3082                     QualType CanonicalTy);
3083  friend class ASTContext;
3084public:
3085  bool isSugared() const { return !isDependentType(); }
3086  QualType desugar() const { return UnderlyingType; }
3087
3088  QualType getUnderlyingType() const { return UnderlyingType; }
3089  QualType getBaseType() const { return BaseType; }
3090
3091  UTTKind getUTTKind() const { return UKind; }
3092
3093  static bool classof(const Type *T) {
3094    return T->getTypeClass() == UnaryTransform;
3095  }
3096  static bool classof(const UnaryTransformType *) { return true; }
3097};
3098
3099class TagType : public Type {
3100  /// Stores the TagDecl associated with this type. The decl may point to any
3101  /// TagDecl that declares the entity.
3102  TagDecl * decl;
3103
3104protected:
3105  TagType(TypeClass TC, const TagDecl *D, QualType can);
3106
3107public:
3108  TagDecl *getDecl() const;
3109
3110  /// @brief Determines whether this type is in the process of being
3111  /// defined.
3112  bool isBeingDefined() const;
3113
3114  static bool classof(const Type *T) {
3115    return T->getTypeClass() >= TagFirst && T->getTypeClass() <= TagLast;
3116  }
3117  static bool classof(const TagType *) { return true; }
3118  static bool classof(const RecordType *) { return true; }
3119  static bool classof(const EnumType *) { return true; }
3120};
3121
3122/// RecordType - This is a helper class that allows the use of isa/cast/dyncast
3123/// to detect TagType objects of structs/unions/classes.
3124class RecordType : public TagType {
3125protected:
3126  explicit RecordType(const RecordDecl *D)
3127    : TagType(Record, reinterpret_cast<const TagDecl*>(D), QualType()) { }
3128  explicit RecordType(TypeClass TC, RecordDecl *D)
3129    : TagType(TC, reinterpret_cast<const TagDecl*>(D), QualType()) { }
3130  friend class ASTContext;   // ASTContext creates these.
3131public:
3132
3133  RecordDecl *getDecl() const {
3134    return reinterpret_cast<RecordDecl*>(TagType::getDecl());
3135  }
3136
3137  // FIXME: This predicate is a helper to QualType/Type. It needs to
3138  // recursively check all fields for const-ness. If any field is declared
3139  // const, it needs to return false.
3140  bool hasConstFields() const { return false; }
3141
3142  bool isSugared() const { return false; }
3143  QualType desugar() const { return QualType(this, 0); }
3144
3145  static bool classof(const TagType *T);
3146  static bool classof(const Type *T) {
3147    return isa<TagType>(T) && classof(cast<TagType>(T));
3148  }
3149  static bool classof(const RecordType *) { return true; }
3150};
3151
3152/// EnumType - This is a helper class that allows the use of isa/cast/dyncast
3153/// to detect TagType objects of enums.
3154class EnumType : public TagType {
3155  explicit EnumType(const EnumDecl *D)
3156    : TagType(Enum, reinterpret_cast<const TagDecl*>(D), QualType()) { }
3157  friend class ASTContext;   // ASTContext creates these.
3158public:
3159
3160  EnumDecl *getDecl() const {
3161    return reinterpret_cast<EnumDecl*>(TagType::getDecl());
3162  }
3163
3164  bool isSugared() const { return false; }
3165  QualType desugar() const { return QualType(this, 0); }
3166
3167  static bool classof(const TagType *T);
3168  static bool classof(const Type *T) {
3169    return isa<TagType>(T) && classof(cast<TagType>(T));
3170  }
3171  static bool classof(const EnumType *) { return true; }
3172};
3173
3174/// AttributedType - An attributed type is a type to which a type
3175/// attribute has been applied.  The "modified type" is the
3176/// fully-sugared type to which the attributed type was applied;
3177/// generally it is not canonically equivalent to the attributed type.
3178/// The "equivalent type" is the minimally-desugared type which the
3179/// type is canonically equivalent to.
3180///
3181/// For example, in the following attributed type:
3182///     int32_t __attribute__((vector_size(16)))
3183///   - the modified type is the TypedefType for int32_t
3184///   - the equivalent type is VectorType(16, int32_t)
3185///   - the canonical type is VectorType(16, int)
3186class AttributedType : public Type, public llvm::FoldingSetNode {
3187public:
3188  // It is really silly to have yet another attribute-kind enum, but
3189  // clang::attr::Kind doesn't currently cover the pure type attrs.
3190  enum Kind {
3191    // Expression operand.
3192    attr_address_space,
3193    attr_regparm,
3194    attr_vector_size,
3195    attr_neon_vector_type,
3196    attr_neon_polyvector_type,
3197
3198    FirstExprOperandKind = attr_address_space,
3199    LastExprOperandKind = attr_neon_polyvector_type,
3200
3201    // Enumerated operand (string or keyword).
3202    attr_objc_gc,
3203    attr_objc_ownership,
3204    attr_pcs,
3205
3206    FirstEnumOperandKind = attr_objc_gc,
3207    LastEnumOperandKind = attr_pcs,
3208
3209    // No operand.
3210    attr_noreturn,
3211    attr_cdecl,
3212    attr_fastcall,
3213    attr_stdcall,
3214    attr_thiscall,
3215    attr_pascal
3216  };
3217
3218private:
3219  QualType ModifiedType;
3220  QualType EquivalentType;
3221
3222  friend class ASTContext; // creates these
3223
3224  AttributedType(QualType canon, Kind attrKind,
3225                 QualType modified, QualType equivalent)
3226    : Type(Attributed, canon, canon->isDependentType(),
3227           canon->isInstantiationDependentType(),
3228           canon->isVariablyModifiedType(),
3229           canon->containsUnexpandedParameterPack()),
3230      ModifiedType(modified), EquivalentType(equivalent) {
3231    AttributedTypeBits.AttrKind = attrKind;
3232  }
3233
3234public:
3235  Kind getAttrKind() const {
3236    return static_cast<Kind>(AttributedTypeBits.AttrKind);
3237  }
3238
3239  QualType getModifiedType() const { return ModifiedType; }
3240  QualType getEquivalentType() const { return EquivalentType; }
3241
3242  bool isSugared() const { return true; }
3243  QualType desugar() const { return getEquivalentType(); }
3244
3245  void Profile(llvm::FoldingSetNodeID &ID) {
3246    Profile(ID, getAttrKind(), ModifiedType, EquivalentType);
3247  }
3248
3249  static void Profile(llvm::FoldingSetNodeID &ID, Kind attrKind,
3250                      QualType modified, QualType equivalent) {
3251    ID.AddInteger(attrKind);
3252    ID.AddPointer(modified.getAsOpaquePtr());
3253    ID.AddPointer(equivalent.getAsOpaquePtr());
3254  }
3255
3256  static bool classof(const Type *T) {
3257    return T->getTypeClass() == Attributed;
3258  }
3259  static bool classof(const AttributedType *T) { return true; }
3260};
3261
3262class TemplateTypeParmType : public Type, public llvm::FoldingSetNode {
3263  // Helper data collector for canonical types.
3264  struct CanonicalTTPTInfo {
3265    unsigned Depth : 15;
3266    unsigned ParameterPack : 1;
3267    unsigned Index : 16;
3268  };
3269
3270  union {
3271    // Info for the canonical type.
3272    CanonicalTTPTInfo CanTTPTInfo;
3273    // Info for the non-canonical type.
3274    TemplateTypeParmDecl *TTPDecl;
3275  };
3276
3277  /// Build a non-canonical type.
3278  TemplateTypeParmType(TemplateTypeParmDecl *TTPDecl, QualType Canon)
3279    : Type(TemplateTypeParm, Canon, /*Dependent=*/true,
3280           /*InstantiationDependent=*/true,
3281           /*VariablyModified=*/false,
3282           Canon->containsUnexpandedParameterPack()),
3283      TTPDecl(TTPDecl) { }
3284
3285  /// Build the canonical type.
3286  TemplateTypeParmType(unsigned D, unsigned I, bool PP)
3287    : Type(TemplateTypeParm, QualType(this, 0),
3288           /*Dependent=*/true,
3289           /*InstantiationDependent=*/true,
3290           /*VariablyModified=*/false, PP) {
3291    CanTTPTInfo.Depth = D;
3292    CanTTPTInfo.Index = I;
3293    CanTTPTInfo.ParameterPack = PP;
3294  }
3295
3296  friend class ASTContext;  // ASTContext creates these
3297
3298  const CanonicalTTPTInfo& getCanTTPTInfo() const {
3299    QualType Can = getCanonicalTypeInternal();
3300    return Can->castAs<TemplateTypeParmType>()->CanTTPTInfo;
3301  }
3302
3303public:
3304  unsigned getDepth() const { return getCanTTPTInfo().Depth; }
3305  unsigned getIndex() const { return getCanTTPTInfo().Index; }
3306  bool isParameterPack() const { return getCanTTPTInfo().ParameterPack; }
3307
3308  TemplateTypeParmDecl *getDecl() const {
3309    return isCanonicalUnqualified() ? 0 : TTPDecl;
3310  }
3311
3312  IdentifierInfo *getIdentifier() const;
3313
3314  bool isSugared() const { return false; }
3315  QualType desugar() const { return QualType(this, 0); }
3316
3317  void Profile(llvm::FoldingSetNodeID &ID) {
3318    Profile(ID, getDepth(), getIndex(), isParameterPack(), getDecl());
3319  }
3320
3321  static void Profile(llvm::FoldingSetNodeID &ID, unsigned Depth,
3322                      unsigned Index, bool ParameterPack,
3323                      TemplateTypeParmDecl *TTPDecl) {
3324    ID.AddInteger(Depth);
3325    ID.AddInteger(Index);
3326    ID.AddBoolean(ParameterPack);
3327    ID.AddPointer(TTPDecl);
3328  }
3329
3330  static bool classof(const Type *T) {
3331    return T->getTypeClass() == TemplateTypeParm;
3332  }
3333  static bool classof(const TemplateTypeParmType *T) { return true; }
3334};
3335
3336/// \brief Represents the result of substituting a type for a template
3337/// type parameter.
3338///
3339/// Within an instantiated template, all template type parameters have
3340/// been replaced with these.  They are used solely to record that a
3341/// type was originally written as a template type parameter;
3342/// therefore they are never canonical.
3343class SubstTemplateTypeParmType : public Type, public llvm::FoldingSetNode {
3344  // The original type parameter.
3345  const TemplateTypeParmType *Replaced;
3346
3347  SubstTemplateTypeParmType(const TemplateTypeParmType *Param, QualType Canon)
3348    : Type(SubstTemplateTypeParm, Canon, Canon->isDependentType(),
3349           Canon->isInstantiationDependentType(),
3350           Canon->isVariablyModifiedType(),
3351           Canon->containsUnexpandedParameterPack()),
3352      Replaced(Param) { }
3353
3354  friend class ASTContext;
3355
3356public:
3357  /// Gets the template parameter that was substituted for.
3358  const TemplateTypeParmType *getReplacedParameter() const {
3359    return Replaced;
3360  }
3361
3362  /// Gets the type that was substituted for the template
3363  /// parameter.
3364  QualType getReplacementType() const {
3365    return getCanonicalTypeInternal();
3366  }
3367
3368  bool isSugared() const { return true; }
3369  QualType desugar() const { return getReplacementType(); }
3370
3371  void Profile(llvm::FoldingSetNodeID &ID) {
3372    Profile(ID, getReplacedParameter(), getReplacementType());
3373  }
3374  static void Profile(llvm::FoldingSetNodeID &ID,
3375                      const TemplateTypeParmType *Replaced,
3376                      QualType Replacement) {
3377    ID.AddPointer(Replaced);
3378    ID.AddPointer(Replacement.getAsOpaquePtr());
3379  }
3380
3381  static bool classof(const Type *T) {
3382    return T->getTypeClass() == SubstTemplateTypeParm;
3383  }
3384  static bool classof(const SubstTemplateTypeParmType *T) { return true; }
3385};
3386
3387/// \brief Represents the result of substituting a set of types for a template
3388/// type parameter pack.
3389///
3390/// When a pack expansion in the source code contains multiple parameter packs
3391/// and those parameter packs correspond to different levels of template
3392/// parameter lists, this type node is used to represent a template type
3393/// parameter pack from an outer level, which has already had its argument pack
3394/// substituted but that still lives within a pack expansion that itself
3395/// could not be instantiated. When actually performing a substitution into
3396/// that pack expansion (e.g., when all template parameters have corresponding
3397/// arguments), this type will be replaced with the \c SubstTemplateTypeParmType
3398/// at the current pack substitution index.
3399class SubstTemplateTypeParmPackType : public Type, public llvm::FoldingSetNode {
3400  /// \brief The original type parameter.
3401  const TemplateTypeParmType *Replaced;
3402
3403  /// \brief A pointer to the set of template arguments that this
3404  /// parameter pack is instantiated with.
3405  const TemplateArgument *Arguments;
3406
3407  /// \brief The number of template arguments in \c Arguments.
3408  unsigned NumArguments;
3409
3410  SubstTemplateTypeParmPackType(const TemplateTypeParmType *Param,
3411                                QualType Canon,
3412                                const TemplateArgument &ArgPack);
3413
3414  friend class ASTContext;
3415
3416public:
3417  IdentifierInfo *getIdentifier() const { return Replaced->getIdentifier(); }
3418
3419  /// Gets the template parameter that was substituted for.
3420  const TemplateTypeParmType *getReplacedParameter() const {
3421    return Replaced;
3422  }
3423
3424  bool isSugared() const { return false; }
3425  QualType desugar() const { return QualType(this, 0); }
3426
3427  TemplateArgument getArgumentPack() const;
3428
3429  void Profile(llvm::FoldingSetNodeID &ID);
3430  static void Profile(llvm::FoldingSetNodeID &ID,
3431                      const TemplateTypeParmType *Replaced,
3432                      const TemplateArgument &ArgPack);
3433
3434  static bool classof(const Type *T) {
3435    return T->getTypeClass() == SubstTemplateTypeParmPack;
3436  }
3437  static bool classof(const SubstTemplateTypeParmPackType *T) { return true; }
3438};
3439
3440/// \brief Represents a C++0x auto type.
3441///
3442/// These types are usually a placeholder for a deduced type. However, within
3443/// templates and before the initializer is attached, there is no deduced type
3444/// and an auto type is type-dependent and canonical.
3445class AutoType : public Type, public llvm::FoldingSetNode {
3446  AutoType(QualType DeducedType)
3447    : Type(Auto, DeducedType.isNull() ? QualType(this, 0) : DeducedType,
3448           /*Dependent=*/DeducedType.isNull(),
3449           /*InstantiationDependent=*/DeducedType.isNull(),
3450           /*VariablyModified=*/false, /*ContainsParameterPack=*/false) {
3451    assert((DeducedType.isNull() || !DeducedType->isDependentType()) &&
3452           "deduced a dependent type for auto");
3453  }
3454
3455  friend class ASTContext;  // ASTContext creates these
3456
3457public:
3458  bool isSugared() const { return isDeduced(); }
3459  QualType desugar() const { return getCanonicalTypeInternal(); }
3460
3461  QualType getDeducedType() const {
3462    return isDeduced() ? getCanonicalTypeInternal() : QualType();
3463  }
3464  bool isDeduced() const {
3465    return !isDependentType();
3466  }
3467
3468  void Profile(llvm::FoldingSetNodeID &ID) {
3469    Profile(ID, getDeducedType());
3470  }
3471
3472  static void Profile(llvm::FoldingSetNodeID &ID,
3473                      QualType Deduced) {
3474    ID.AddPointer(Deduced.getAsOpaquePtr());
3475  }
3476
3477  static bool classof(const Type *T) {
3478    return T->getTypeClass() == Auto;
3479  }
3480  static bool classof(const AutoType *T) { return true; }
3481};
3482
3483/// \brief Represents a type template specialization; the template
3484/// must be a class template, a type alias template, or a template
3485/// template parameter.  A template which cannot be resolved to one of
3486/// these, e.g. because it is written with a dependent scope
3487/// specifier, is instead represented as a
3488/// @c DependentTemplateSpecializationType.
3489///
3490/// A non-dependent template specialization type is always "sugar",
3491/// typically for a @c RecordType.  For example, a class template
3492/// specialization type of @c vector<int> will refer to a tag type for
3493/// the instantiation @c std::vector<int, std::allocator<int>>
3494///
3495/// Template specializations are dependent if either the template or
3496/// any of the template arguments are dependent, in which case the
3497/// type may also be canonical.
3498///
3499/// Instances of this type are allocated with a trailing array of
3500/// TemplateArguments, followed by a QualType representing the
3501/// non-canonical aliased type when the template is a type alias
3502/// template.
3503class TemplateSpecializationType
3504  : public Type, public llvm::FoldingSetNode {
3505  /// \brief The name of the template being specialized.  This is
3506  /// either a TemplateName::Template (in which case it is a
3507  /// ClassTemplateDecl*, a TemplateTemplateParmDecl*, or a
3508  /// TypeAliasTemplateDecl*), a
3509  /// TemplateName::SubstTemplateTemplateParmPack, or a
3510  /// TemplateName::SubstTemplateTemplateParm (in which case the
3511  /// replacement must, recursively, be one of these).
3512  TemplateName Template;
3513
3514  /// \brief - The number of template arguments named in this class
3515  /// template specialization.
3516  unsigned NumArgs;
3517
3518  TemplateSpecializationType(TemplateName T,
3519                             const TemplateArgument *Args,
3520                             unsigned NumArgs, QualType Canon,
3521                             QualType Aliased);
3522
3523  friend class ASTContext;  // ASTContext creates these
3524
3525public:
3526  /// \brief Determine whether any of the given template arguments are
3527  /// dependent.
3528  static bool anyDependentTemplateArguments(const TemplateArgument *Args,
3529                                            unsigned NumArgs,
3530                                            bool &InstantiationDependent);
3531
3532  static bool anyDependentTemplateArguments(const TemplateArgumentLoc *Args,
3533                                            unsigned NumArgs,
3534                                            bool &InstantiationDependent);
3535
3536  static bool anyDependentTemplateArguments(const TemplateArgumentListInfo &,
3537                                            bool &InstantiationDependent);
3538
3539  /// \brief Print a template argument list, including the '<' and '>'
3540  /// enclosing the template arguments.
3541  static std::string PrintTemplateArgumentList(const TemplateArgument *Args,
3542                                               unsigned NumArgs,
3543                                               const PrintingPolicy &Policy,
3544                                               bool SkipBrackets = false);
3545
3546  static std::string PrintTemplateArgumentList(const TemplateArgumentLoc *Args,
3547                                               unsigned NumArgs,
3548                                               const PrintingPolicy &Policy);
3549
3550  static std::string PrintTemplateArgumentList(const TemplateArgumentListInfo &,
3551                                               const PrintingPolicy &Policy);
3552
3553  /// True if this template specialization type matches a current
3554  /// instantiation in the context in which it is found.
3555  bool isCurrentInstantiation() const {
3556    return isa<InjectedClassNameType>(getCanonicalTypeInternal());
3557  }
3558
3559  /// True if this template specialization type is for a type alias
3560  /// template.
3561  bool isTypeAlias() const;
3562  /// Get the aliased type, if this is a specialization of a type alias
3563  /// template.
3564  QualType getAliasedType() const {
3565    assert(isTypeAlias() && "not a type alias template specialization");
3566    return *reinterpret_cast<const QualType*>(end());
3567  }
3568
3569  typedef const TemplateArgument * iterator;
3570
3571  iterator begin() const { return getArgs(); }
3572  iterator end() const; // defined inline in TemplateBase.h
3573
3574  /// \brief Retrieve the name of the template that we are specializing.
3575  TemplateName getTemplateName() const { return Template; }
3576
3577  /// \brief Retrieve the template arguments.
3578  const TemplateArgument *getArgs() const {
3579    return reinterpret_cast<const TemplateArgument *>(this + 1);
3580  }
3581
3582  /// \brief Retrieve the number of template arguments.
3583  unsigned getNumArgs() const { return NumArgs; }
3584
3585  /// \brief Retrieve a specific template argument as a type.
3586  /// \precondition @c isArgType(Arg)
3587  const TemplateArgument &getArg(unsigned Idx) const; // in TemplateBase.h
3588
3589  bool isSugared() const {
3590    return !isDependentType() || isCurrentInstantiation() || isTypeAlias();
3591  }
3592  QualType desugar() const { return getCanonicalTypeInternal(); }
3593
3594  void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Ctx) {
3595    Profile(ID, Template, getArgs(), NumArgs, Ctx);
3596    if (isTypeAlias())
3597      getAliasedType().Profile(ID);
3598  }
3599
3600  static void Profile(llvm::FoldingSetNodeID &ID, TemplateName T,
3601                      const TemplateArgument *Args,
3602                      unsigned NumArgs,
3603                      const ASTContext &Context);
3604
3605  static bool classof(const Type *T) {
3606    return T->getTypeClass() == TemplateSpecialization;
3607  }
3608  static bool classof(const TemplateSpecializationType *T) { return true; }
3609};
3610
3611/// \brief The injected class name of a C++ class template or class
3612/// template partial specialization.  Used to record that a type was
3613/// spelled with a bare identifier rather than as a template-id; the
3614/// equivalent for non-templated classes is just RecordType.
3615///
3616/// Injected class name types are always dependent.  Template
3617/// instantiation turns these into RecordTypes.
3618///
3619/// Injected class name types are always canonical.  This works
3620/// because it is impossible to compare an injected class name type
3621/// with the corresponding non-injected template type, for the same
3622/// reason that it is impossible to directly compare template
3623/// parameters from different dependent contexts: injected class name
3624/// types can only occur within the scope of a particular templated
3625/// declaration, and within that scope every template specialization
3626/// will canonicalize to the injected class name (when appropriate
3627/// according to the rules of the language).
3628class InjectedClassNameType : public Type {
3629  CXXRecordDecl *Decl;
3630
3631  /// The template specialization which this type represents.
3632  /// For example, in
3633  ///   template <class T> class A { ... };
3634  /// this is A<T>, whereas in
3635  ///   template <class X, class Y> class A<B<X,Y> > { ... };
3636  /// this is A<B<X,Y> >.
3637  ///
3638  /// It is always unqualified, always a template specialization type,
3639  /// and always dependent.
3640  QualType InjectedType;
3641
3642  friend class ASTContext; // ASTContext creates these.
3643  friend class ASTReader; // FIXME: ASTContext::getInjectedClassNameType is not
3644                          // currently suitable for AST reading, too much
3645                          // interdependencies.
3646  InjectedClassNameType(CXXRecordDecl *D, QualType TST)
3647    : Type(InjectedClassName, QualType(), /*Dependent=*/true,
3648           /*InstantiationDependent=*/true,
3649           /*VariablyModified=*/false,
3650           /*ContainsUnexpandedParameterPack=*/false),
3651      Decl(D), InjectedType(TST) {
3652    assert(isa<TemplateSpecializationType>(TST));
3653    assert(!TST.hasQualifiers());
3654    assert(TST->isDependentType());
3655  }
3656
3657public:
3658  QualType getInjectedSpecializationType() const { return InjectedType; }
3659  const TemplateSpecializationType *getInjectedTST() const {
3660    return cast<TemplateSpecializationType>(InjectedType.getTypePtr());
3661  }
3662
3663  CXXRecordDecl *getDecl() const;
3664
3665  bool isSugared() const { return false; }
3666  QualType desugar() const { return QualType(this, 0); }
3667
3668  static bool classof(const Type *T) {
3669    return T->getTypeClass() == InjectedClassName;
3670  }
3671  static bool classof(const InjectedClassNameType *T) { return true; }
3672};
3673
3674/// \brief The kind of a tag type.
3675enum TagTypeKind {
3676  /// \brief The "struct" keyword.
3677  TTK_Struct,
3678  /// \brief The "union" keyword.
3679  TTK_Union,
3680  /// \brief The "class" keyword.
3681  TTK_Class,
3682  /// \brief The "enum" keyword.
3683  TTK_Enum
3684};
3685
3686/// \brief The elaboration keyword that precedes a qualified type name or
3687/// introduces an elaborated-type-specifier.
3688enum ElaboratedTypeKeyword {
3689  /// \brief The "struct" keyword introduces the elaborated-type-specifier.
3690  ETK_Struct,
3691  /// \brief The "union" keyword introduces the elaborated-type-specifier.
3692  ETK_Union,
3693  /// \brief The "class" keyword introduces the elaborated-type-specifier.
3694  ETK_Class,
3695  /// \brief The "enum" keyword introduces the elaborated-type-specifier.
3696  ETK_Enum,
3697  /// \brief The "typename" keyword precedes the qualified type name, e.g.,
3698  /// \c typename T::type.
3699  ETK_Typename,
3700  /// \brief No keyword precedes the qualified type name.
3701  ETK_None
3702};
3703
3704/// A helper class for Type nodes having an ElaboratedTypeKeyword.
3705/// The keyword in stored in the free bits of the base class.
3706/// Also provides a few static helpers for converting and printing
3707/// elaborated type keyword and tag type kind enumerations.
3708class TypeWithKeyword : public Type {
3709protected:
3710  TypeWithKeyword(ElaboratedTypeKeyword Keyword, TypeClass tc,
3711                  QualType Canonical, bool Dependent,
3712                  bool InstantiationDependent, bool VariablyModified,
3713                  bool ContainsUnexpandedParameterPack)
3714  : Type(tc, Canonical, Dependent, InstantiationDependent, VariablyModified,
3715         ContainsUnexpandedParameterPack) {
3716    TypeWithKeywordBits.Keyword = Keyword;
3717  }
3718
3719public:
3720  ElaboratedTypeKeyword getKeyword() const {
3721    return static_cast<ElaboratedTypeKeyword>(TypeWithKeywordBits.Keyword);
3722  }
3723
3724  /// getKeywordForTypeSpec - Converts a type specifier (DeclSpec::TST)
3725  /// into an elaborated type keyword.
3726  static ElaboratedTypeKeyword getKeywordForTypeSpec(unsigned TypeSpec);
3727
3728  /// getTagTypeKindForTypeSpec - Converts a type specifier (DeclSpec::TST)
3729  /// into a tag type kind.  It is an error to provide a type specifier
3730  /// which *isn't* a tag kind here.
3731  static TagTypeKind getTagTypeKindForTypeSpec(unsigned TypeSpec);
3732
3733  /// getKeywordForTagDeclKind - Converts a TagTypeKind into an
3734  /// elaborated type keyword.
3735  static ElaboratedTypeKeyword getKeywordForTagTypeKind(TagTypeKind Tag);
3736
3737  /// getTagTypeKindForKeyword - Converts an elaborated type keyword into
3738  // a TagTypeKind. It is an error to provide an elaborated type keyword
3739  /// which *isn't* a tag kind here.
3740  static TagTypeKind getTagTypeKindForKeyword(ElaboratedTypeKeyword Keyword);
3741
3742  static bool KeywordIsTagTypeKind(ElaboratedTypeKeyword Keyword);
3743
3744  static const char *getKeywordName(ElaboratedTypeKeyword Keyword);
3745
3746  static const char *getTagTypeKindName(TagTypeKind Kind) {
3747    return getKeywordName(getKeywordForTagTypeKind(Kind));
3748  }
3749
3750  class CannotCastToThisType {};
3751  static CannotCastToThisType classof(const Type *);
3752};
3753
3754/// \brief Represents a type that was referred to using an elaborated type
3755/// keyword, e.g., struct S, or via a qualified name, e.g., N::M::type,
3756/// or both.
3757///
3758/// This type is used to keep track of a type name as written in the
3759/// source code, including tag keywords and any nested-name-specifiers.
3760/// The type itself is always "sugar", used to express what was written
3761/// in the source code but containing no additional semantic information.
3762class ElaboratedType : public TypeWithKeyword, public llvm::FoldingSetNode {
3763
3764  /// \brief The nested name specifier containing the qualifier.
3765  NestedNameSpecifier *NNS;
3766
3767  /// \brief The type that this qualified name refers to.
3768  QualType NamedType;
3769
3770  ElaboratedType(ElaboratedTypeKeyword Keyword, NestedNameSpecifier *NNS,
3771                 QualType NamedType, QualType CanonType)
3772    : TypeWithKeyword(Keyword, Elaborated, CanonType,
3773                      NamedType->isDependentType(),
3774                      NamedType->isInstantiationDependentType(),
3775                      NamedType->isVariablyModifiedType(),
3776                      NamedType->containsUnexpandedParameterPack()),
3777      NNS(NNS), NamedType(NamedType) {
3778    assert(!(Keyword == ETK_None && NNS == 0) &&
3779           "ElaboratedType cannot have elaborated type keyword "
3780           "and name qualifier both null.");
3781  }
3782
3783  friend class ASTContext;  // ASTContext creates these
3784
3785public:
3786  ~ElaboratedType();
3787
3788  /// \brief Retrieve the qualification on this type.
3789  NestedNameSpecifier *getQualifier() const { return NNS; }
3790
3791  /// \brief Retrieve the type named by the qualified-id.
3792  QualType getNamedType() const { return NamedType; }
3793
3794  /// \brief Remove a single level of sugar.
3795  QualType desugar() const { return getNamedType(); }
3796
3797  /// \brief Returns whether this type directly provides sugar.
3798  bool isSugared() const { return true; }
3799
3800  void Profile(llvm::FoldingSetNodeID &ID) {
3801    Profile(ID, getKeyword(), NNS, NamedType);
3802  }
3803
3804  static void Profile(llvm::FoldingSetNodeID &ID, ElaboratedTypeKeyword Keyword,
3805                      NestedNameSpecifier *NNS, QualType NamedType) {
3806    ID.AddInteger(Keyword);
3807    ID.AddPointer(NNS);
3808    NamedType.Profile(ID);
3809  }
3810
3811  static bool classof(const Type *T) {
3812    return T->getTypeClass() == Elaborated;
3813  }
3814  static bool classof(const ElaboratedType *T) { return true; }
3815};
3816
3817/// \brief Represents a qualified type name for which the type name is
3818/// dependent.
3819///
3820/// DependentNameType represents a class of dependent types that involve a
3821/// dependent nested-name-specifier (e.g., "T::") followed by a (dependent)
3822/// name of a type. The DependentNameType may start with a "typename" (for a
3823/// typename-specifier), "class", "struct", "union", or "enum" (for a
3824/// dependent elaborated-type-specifier), or nothing (in contexts where we
3825/// know that we must be referring to a type, e.g., in a base class specifier).
3826class DependentNameType : public TypeWithKeyword, public llvm::FoldingSetNode {
3827
3828  /// \brief The nested name specifier containing the qualifier.
3829  NestedNameSpecifier *NNS;
3830
3831  /// \brief The type that this typename specifier refers to.
3832  const IdentifierInfo *Name;
3833
3834  DependentNameType(ElaboratedTypeKeyword Keyword, NestedNameSpecifier *NNS,
3835                    const IdentifierInfo *Name, QualType CanonType)
3836    : TypeWithKeyword(Keyword, DependentName, CanonType, /*Dependent=*/true,
3837                      /*InstantiationDependent=*/true,
3838                      /*VariablyModified=*/false,
3839                      NNS->containsUnexpandedParameterPack()),
3840      NNS(NNS), Name(Name) {
3841    assert(NNS->isDependent() &&
3842           "DependentNameType requires a dependent nested-name-specifier");
3843  }
3844
3845  friend class ASTContext;  // ASTContext creates these
3846
3847public:
3848  /// \brief Retrieve the qualification on this type.
3849  NestedNameSpecifier *getQualifier() const { return NNS; }
3850
3851  /// \brief Retrieve the type named by the typename specifier as an
3852  /// identifier.
3853  ///
3854  /// This routine will return a non-NULL identifier pointer when the
3855  /// form of the original typename was terminated by an identifier,
3856  /// e.g., "typename T::type".
3857  const IdentifierInfo *getIdentifier() const {
3858    return Name;
3859  }
3860
3861  bool isSugared() const { return false; }
3862  QualType desugar() const { return QualType(this, 0); }
3863
3864  void Profile(llvm::FoldingSetNodeID &ID) {
3865    Profile(ID, getKeyword(), NNS, Name);
3866  }
3867
3868  static void Profile(llvm::FoldingSetNodeID &ID, ElaboratedTypeKeyword Keyword,
3869                      NestedNameSpecifier *NNS, const IdentifierInfo *Name) {
3870    ID.AddInteger(Keyword);
3871    ID.AddPointer(NNS);
3872    ID.AddPointer(Name);
3873  }
3874
3875  static bool classof(const Type *T) {
3876    return T->getTypeClass() == DependentName;
3877  }
3878  static bool classof(const DependentNameType *T) { return true; }
3879};
3880
3881/// DependentTemplateSpecializationType - Represents a template
3882/// specialization type whose template cannot be resolved, e.g.
3883///   A<T>::template B<T>
3884class DependentTemplateSpecializationType :
3885  public TypeWithKeyword, public llvm::FoldingSetNode {
3886
3887  /// \brief The nested name specifier containing the qualifier.
3888  NestedNameSpecifier *NNS;
3889
3890  /// \brief The identifier of the template.
3891  const IdentifierInfo *Name;
3892
3893  /// \brief - The number of template arguments named in this class
3894  /// template specialization.
3895  unsigned NumArgs;
3896
3897  const TemplateArgument *getArgBuffer() const {
3898    return reinterpret_cast<const TemplateArgument*>(this+1);
3899  }
3900  TemplateArgument *getArgBuffer() {
3901    return reinterpret_cast<TemplateArgument*>(this+1);
3902  }
3903
3904  DependentTemplateSpecializationType(ElaboratedTypeKeyword Keyword,
3905                                      NestedNameSpecifier *NNS,
3906                                      const IdentifierInfo *Name,
3907                                      unsigned NumArgs,
3908                                      const TemplateArgument *Args,
3909                                      QualType Canon);
3910
3911  friend class ASTContext;  // ASTContext creates these
3912
3913public:
3914  NestedNameSpecifier *getQualifier() const { return NNS; }
3915  const IdentifierInfo *getIdentifier() const { return Name; }
3916
3917  /// \brief Retrieve the template arguments.
3918  const TemplateArgument *getArgs() const {
3919    return getArgBuffer();
3920  }
3921
3922  /// \brief Retrieve the number of template arguments.
3923  unsigned getNumArgs() const { return NumArgs; }
3924
3925  const TemplateArgument &getArg(unsigned Idx) const; // in TemplateBase.h
3926
3927  typedef const TemplateArgument * iterator;
3928  iterator begin() const { return getArgs(); }
3929  iterator end() const; // inline in TemplateBase.h
3930
3931  bool isSugared() const { return false; }
3932  QualType desugar() const { return QualType(this, 0); }
3933
3934  void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context) {
3935    Profile(ID, Context, getKeyword(), NNS, Name, NumArgs, getArgs());
3936  }
3937
3938  static void Profile(llvm::FoldingSetNodeID &ID,
3939                      const ASTContext &Context,
3940                      ElaboratedTypeKeyword Keyword,
3941                      NestedNameSpecifier *Qualifier,
3942                      const IdentifierInfo *Name,
3943                      unsigned NumArgs,
3944                      const TemplateArgument *Args);
3945
3946  static bool classof(const Type *T) {
3947    return T->getTypeClass() == DependentTemplateSpecialization;
3948  }
3949  static bool classof(const DependentTemplateSpecializationType *T) {
3950    return true;
3951  }
3952};
3953
3954/// \brief Represents a pack expansion of types.
3955///
3956/// Pack expansions are part of C++0x variadic templates. A pack
3957/// expansion contains a pattern, which itself contains one or more
3958/// "unexpanded" parameter packs. When instantiated, a pack expansion
3959/// produces a series of types, each instantiated from the pattern of
3960/// the expansion, where the Ith instantiation of the pattern uses the
3961/// Ith arguments bound to each of the unexpanded parameter packs. The
3962/// pack expansion is considered to "expand" these unexpanded
3963/// parameter packs.
3964///
3965/// \code
3966/// template<typename ...Types> struct tuple;
3967///
3968/// template<typename ...Types>
3969/// struct tuple_of_references {
3970///   typedef tuple<Types&...> type;
3971/// };
3972/// \endcode
3973///
3974/// Here, the pack expansion \c Types&... is represented via a
3975/// PackExpansionType whose pattern is Types&.
3976class PackExpansionType : public Type, public llvm::FoldingSetNode {
3977  /// \brief The pattern of the pack expansion.
3978  QualType Pattern;
3979
3980  /// \brief The number of expansions that this pack expansion will
3981  /// generate when substituted (+1), or indicates that
3982  ///
3983  /// This field will only have a non-zero value when some of the parameter
3984  /// packs that occur within the pattern have been substituted but others have
3985  /// not.
3986  unsigned NumExpansions;
3987
3988  PackExpansionType(QualType Pattern, QualType Canon,
3989                    llvm::Optional<unsigned> NumExpansions)
3990    : Type(PackExpansion, Canon, /*Dependent=*/true,
3991           /*InstantiationDependent=*/true,
3992           /*VariableModified=*/Pattern->isVariablyModifiedType(),
3993           /*ContainsUnexpandedParameterPack=*/false),
3994      Pattern(Pattern),
3995      NumExpansions(NumExpansions? *NumExpansions + 1: 0) { }
3996
3997  friend class ASTContext;  // ASTContext creates these
3998
3999public:
4000  /// \brief Retrieve the pattern of this pack expansion, which is the
4001  /// type that will be repeatedly instantiated when instantiating the
4002  /// pack expansion itself.
4003  QualType getPattern() const { return Pattern; }
4004
4005  /// \brief Retrieve the number of expansions that this pack expansion will
4006  /// generate, if known.
4007  llvm::Optional<unsigned> getNumExpansions() const {
4008    if (NumExpansions)
4009      return NumExpansions - 1;
4010
4011    return llvm::Optional<unsigned>();
4012  }
4013
4014  bool isSugared() const { return false; }
4015  QualType desugar() const { return QualType(this, 0); }
4016
4017  void Profile(llvm::FoldingSetNodeID &ID) {
4018    Profile(ID, getPattern(), getNumExpansions());
4019  }
4020
4021  static void Profile(llvm::FoldingSetNodeID &ID, QualType Pattern,
4022                      llvm::Optional<unsigned> NumExpansions) {
4023    ID.AddPointer(Pattern.getAsOpaquePtr());
4024    ID.AddBoolean(NumExpansions);
4025    if (NumExpansions)
4026      ID.AddInteger(*NumExpansions);
4027  }
4028
4029  static bool classof(const Type *T) {
4030    return T->getTypeClass() == PackExpansion;
4031  }
4032  static bool classof(const PackExpansionType *T) {
4033    return true;
4034  }
4035};
4036
4037/// ObjCObjectType - Represents a class type in Objective C.
4038/// Every Objective C type is a combination of a base type and a
4039/// list of protocols.
4040///
4041/// Given the following declarations:
4042///   @class C;
4043///   @protocol P;
4044///
4045/// 'C' is an ObjCInterfaceType C.  It is sugar for an ObjCObjectType
4046/// with base C and no protocols.
4047///
4048/// 'C<P>' is an ObjCObjectType with base C and protocol list [P].
4049///
4050/// 'id' is a TypedefType which is sugar for an ObjCPointerType whose
4051/// pointee is an ObjCObjectType with base BuiltinType::ObjCIdType
4052/// and no protocols.
4053///
4054/// 'id<P>' is an ObjCPointerType whose pointee is an ObjCObjecType
4055/// with base BuiltinType::ObjCIdType and protocol list [P].  Eventually
4056/// this should get its own sugar class to better represent the source.
4057class ObjCObjectType : public Type {
4058  // ObjCObjectType.NumProtocols - the number of protocols stored
4059  // after the ObjCObjectPointerType node.
4060  //
4061  // These protocols are those written directly on the type.  If
4062  // protocol qualifiers ever become additive, the iterators will need
4063  // to get kindof complicated.
4064  //
4065  // In the canonical object type, these are sorted alphabetically
4066  // and uniqued.
4067
4068  /// Either a BuiltinType or an InterfaceType or sugar for either.
4069  QualType BaseType;
4070
4071  ObjCProtocolDecl * const *getProtocolStorage() const {
4072    return const_cast<ObjCObjectType*>(this)->getProtocolStorage();
4073  }
4074
4075  ObjCProtocolDecl **getProtocolStorage();
4076
4077protected:
4078  ObjCObjectType(QualType Canonical, QualType Base,
4079                 ObjCProtocolDecl * const *Protocols, unsigned NumProtocols);
4080
4081  enum Nonce_ObjCInterface { Nonce_ObjCInterface };
4082  ObjCObjectType(enum Nonce_ObjCInterface)
4083        : Type(ObjCInterface, QualType(), false, false, false, false),
4084      BaseType(QualType(this_(), 0)) {
4085    ObjCObjectTypeBits.NumProtocols = 0;
4086  }
4087
4088public:
4089  /// getBaseType - Gets the base type of this object type.  This is
4090  /// always (possibly sugar for) one of:
4091  ///  - the 'id' builtin type (as opposed to the 'id' type visible to the
4092  ///    user, which is a typedef for an ObjCPointerType)
4093  ///  - the 'Class' builtin type (same caveat)
4094  ///  - an ObjCObjectType (currently always an ObjCInterfaceType)
4095  QualType getBaseType() const { return BaseType; }
4096
4097  bool isObjCId() const {
4098    return getBaseType()->isSpecificBuiltinType(BuiltinType::ObjCId);
4099  }
4100  bool isObjCClass() const {
4101    return getBaseType()->isSpecificBuiltinType(BuiltinType::ObjCClass);
4102  }
4103  bool isObjCUnqualifiedId() const { return qual_empty() && isObjCId(); }
4104  bool isObjCUnqualifiedClass() const { return qual_empty() && isObjCClass(); }
4105  bool isObjCUnqualifiedIdOrClass() const {
4106    if (!qual_empty()) return false;
4107    if (const BuiltinType *T = getBaseType()->getAs<BuiltinType>())
4108      return T->getKind() == BuiltinType::ObjCId ||
4109             T->getKind() == BuiltinType::ObjCClass;
4110    return false;
4111  }
4112  bool isObjCQualifiedId() const { return !qual_empty() && isObjCId(); }
4113  bool isObjCQualifiedClass() const { return !qual_empty() && isObjCClass(); }
4114
4115  /// Gets the interface declaration for this object type, if the base type
4116  /// really is an interface.
4117  ObjCInterfaceDecl *getInterface() const;
4118
4119  typedef ObjCProtocolDecl * const *qual_iterator;
4120
4121  qual_iterator qual_begin() const { return getProtocolStorage(); }
4122  qual_iterator qual_end() const { return qual_begin() + getNumProtocols(); }
4123
4124  bool qual_empty() const { return getNumProtocols() == 0; }
4125
4126  /// getNumProtocols - Return the number of qualifying protocols in this
4127  /// interface type, or 0 if there are none.
4128  unsigned getNumProtocols() const { return ObjCObjectTypeBits.NumProtocols; }
4129
4130  /// \brief Fetch a protocol by index.
4131  ObjCProtocolDecl *getProtocol(unsigned I) const {
4132    assert(I < getNumProtocols() && "Out-of-range protocol access");
4133    return qual_begin()[I];
4134  }
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() == ObjCObject ||
4141           T->getTypeClass() == ObjCInterface;
4142  }
4143  static bool classof(const ObjCObjectType *) { return true; }
4144};
4145
4146/// ObjCObjectTypeImpl - A class providing a concrete implementation
4147/// of ObjCObjectType, so as to not increase the footprint of
4148/// ObjCInterfaceType.  Code outside of ASTContext and the core type
4149/// system should not reference this type.
4150class ObjCObjectTypeImpl : public ObjCObjectType, public llvm::FoldingSetNode {
4151  friend class ASTContext;
4152
4153  // If anyone adds fields here, ObjCObjectType::getProtocolStorage()
4154  // will need to be modified.
4155
4156  ObjCObjectTypeImpl(QualType Canonical, QualType Base,
4157                     ObjCProtocolDecl * const *Protocols,
4158                     unsigned NumProtocols)
4159    : ObjCObjectType(Canonical, Base, Protocols, NumProtocols) {}
4160
4161public:
4162  void Profile(llvm::FoldingSetNodeID &ID);
4163  static void Profile(llvm::FoldingSetNodeID &ID,
4164                      QualType Base,
4165                      ObjCProtocolDecl *const *protocols,
4166                      unsigned NumProtocols);
4167};
4168
4169inline ObjCProtocolDecl **ObjCObjectType::getProtocolStorage() {
4170  return reinterpret_cast<ObjCProtocolDecl**>(
4171            static_cast<ObjCObjectTypeImpl*>(this) + 1);
4172}
4173
4174/// ObjCInterfaceType - Interfaces are the core concept in Objective-C for
4175/// object oriented design.  They basically correspond to C++ classes.  There
4176/// are two kinds of interface types, normal interfaces like "NSString" and
4177/// qualified interfaces, which are qualified with a protocol list like
4178/// "NSString<NSCopyable, NSAmazing>".
4179///
4180/// ObjCInterfaceType guarantees the following properties when considered
4181/// as a subtype of its superclass, ObjCObjectType:
4182///   - There are no protocol qualifiers.  To reinforce this, code which
4183///     tries to invoke the protocol methods via an ObjCInterfaceType will
4184///     fail to compile.
4185///   - It is its own base type.  That is, if T is an ObjCInterfaceType*,
4186///     T->getBaseType() == QualType(T, 0).
4187class ObjCInterfaceType : public ObjCObjectType {
4188  ObjCInterfaceDecl *Decl;
4189
4190  ObjCInterfaceType(const ObjCInterfaceDecl *D)
4191    : ObjCObjectType(Nonce_ObjCInterface),
4192      Decl(const_cast<ObjCInterfaceDecl*>(D)) {}
4193  friend class ASTContext;  // ASTContext creates these.
4194
4195public:
4196  /// getDecl - Get the declaration of this interface.
4197  ObjCInterfaceDecl *getDecl() const { return Decl; }
4198
4199  bool isSugared() const { return false; }
4200  QualType desugar() const { return QualType(this, 0); }
4201
4202  static bool classof(const Type *T) {
4203    return T->getTypeClass() == ObjCInterface;
4204  }
4205  static bool classof(const ObjCInterfaceType *) { return true; }
4206
4207  // Nonsense to "hide" certain members of ObjCObjectType within this
4208  // class.  People asking for protocols on an ObjCInterfaceType are
4209  // not going to get what they want: ObjCInterfaceTypes are
4210  // guaranteed to have no protocols.
4211  enum {
4212    qual_iterator,
4213    qual_begin,
4214    qual_end,
4215    getNumProtocols,
4216    getProtocol
4217  };
4218};
4219
4220inline ObjCInterfaceDecl *ObjCObjectType::getInterface() const {
4221  if (const ObjCInterfaceType *T =
4222        getBaseType()->getAs<ObjCInterfaceType>())
4223    return T->getDecl();
4224  return 0;
4225}
4226
4227/// ObjCObjectPointerType - Used to represent a pointer to an
4228/// Objective C object.  These are constructed from pointer
4229/// declarators when the pointee type is an ObjCObjectType (or sugar
4230/// for one).  In addition, the 'id' and 'Class' types are typedefs
4231/// for these, and the protocol-qualified types 'id<P>' and 'Class<P>'
4232/// are translated into these.
4233///
4234/// Pointers to pointers to Objective C objects are still PointerTypes;
4235/// only the first level of pointer gets it own type implementation.
4236class ObjCObjectPointerType : public Type, public llvm::FoldingSetNode {
4237  QualType PointeeType;
4238
4239  ObjCObjectPointerType(QualType Canonical, QualType Pointee)
4240    : Type(ObjCObjectPointer, Canonical, false, false, false, false),
4241      PointeeType(Pointee) {}
4242  friend class ASTContext;  // ASTContext creates these.
4243
4244public:
4245  /// getPointeeType - Gets the type pointed to by this ObjC pointer.
4246  /// The result will always be an ObjCObjectType or sugar thereof.
4247  QualType getPointeeType() const { return PointeeType; }
4248
4249  /// getObjCObjectType - Gets the type pointed to by this ObjC
4250  /// pointer.  This method always returns non-null.
4251  ///
4252  /// This method is equivalent to getPointeeType() except that
4253  /// it discards any typedefs (or other sugar) between this
4254  /// type and the "outermost" object type.  So for:
4255  ///   @class A; @protocol P; @protocol Q;
4256  ///   typedef A<P> AP;
4257  ///   typedef A A1;
4258  ///   typedef A1<P> A1P;
4259  ///   typedef A1P<Q> A1PQ;
4260  /// For 'A*', getObjectType() will return 'A'.
4261  /// For 'A<P>*', getObjectType() will return 'A<P>'.
4262  /// For 'AP*', getObjectType() will return 'A<P>'.
4263  /// For 'A1*', getObjectType() will return 'A'.
4264  /// For 'A1<P>*', getObjectType() will return 'A1<P>'.
4265  /// For 'A1P*', getObjectType() will return 'A1<P>'.
4266  /// For 'A1PQ*', getObjectType() will return 'A1<Q>', because
4267  ///   adding protocols to a protocol-qualified base discards the
4268  ///   old qualifiers (for now).  But if it didn't, getObjectType()
4269  ///   would return 'A1P<Q>' (and we'd have to make iterating over
4270  ///   qualifiers more complicated).
4271  const ObjCObjectType *getObjectType() const {
4272    return PointeeType->castAs<ObjCObjectType>();
4273  }
4274
4275  /// getInterfaceType - If this pointer points to an Objective C
4276  /// @interface type, gets the type for that interface.  Any protocol
4277  /// qualifiers on the interface are ignored.
4278  ///
4279  /// \return null if the base type for this pointer is 'id' or 'Class'
4280  const ObjCInterfaceType *getInterfaceType() const {
4281    return getObjectType()->getBaseType()->getAs<ObjCInterfaceType>();
4282  }
4283
4284  /// getInterfaceDecl - If this pointer points to an Objective @interface
4285  /// type, gets the declaration for that interface.
4286  ///
4287  /// \return null if the base type for this pointer is 'id' or 'Class'
4288  ObjCInterfaceDecl *getInterfaceDecl() const {
4289    return getObjectType()->getInterface();
4290  }
4291
4292  /// isObjCIdType - True if this is equivalent to the 'id' type, i.e. if
4293  /// its object type is the primitive 'id' type with no protocols.
4294  bool isObjCIdType() const {
4295    return getObjectType()->isObjCUnqualifiedId();
4296  }
4297
4298  /// isObjCClassType - True if this is equivalent to the 'Class' type,
4299  /// i.e. if its object tive is the primitive 'Class' type with no protocols.
4300  bool isObjCClassType() const {
4301    return getObjectType()->isObjCUnqualifiedClass();
4302  }
4303
4304  /// isObjCQualifiedIdType - True if this is equivalent to 'id<P>' for some
4305  /// non-empty set of protocols.
4306  bool isObjCQualifiedIdType() const {
4307    return getObjectType()->isObjCQualifiedId();
4308  }
4309
4310  /// isObjCQualifiedClassType - True if this is equivalent to 'Class<P>' for
4311  /// some non-empty set of protocols.
4312  bool isObjCQualifiedClassType() const {
4313    return getObjectType()->isObjCQualifiedClass();
4314  }
4315
4316  /// An iterator over the qualifiers on the object type.  Provided
4317  /// for convenience.  This will always iterate over the full set of
4318  /// protocols on a type, not just those provided directly.
4319  typedef ObjCObjectType::qual_iterator qual_iterator;
4320
4321  qual_iterator qual_begin() const {
4322    return getObjectType()->qual_begin();
4323  }
4324  qual_iterator qual_end() const {
4325    return getObjectType()->qual_end();
4326  }
4327  bool qual_empty() const { return getObjectType()->qual_empty(); }
4328
4329  /// getNumProtocols - Return the number of qualifying protocols on
4330  /// the object type.
4331  unsigned getNumProtocols() const {
4332    return getObjectType()->getNumProtocols();
4333  }
4334
4335  /// \brief Retrieve a qualifying protocol by index on the object
4336  /// type.
4337  ObjCProtocolDecl *getProtocol(unsigned I) const {
4338    return getObjectType()->getProtocol(I);
4339  }
4340
4341  bool isSugared() const { return false; }
4342  QualType desugar() const { return QualType(this, 0); }
4343
4344  void Profile(llvm::FoldingSetNodeID &ID) {
4345    Profile(ID, getPointeeType());
4346  }
4347  static void Profile(llvm::FoldingSetNodeID &ID, QualType T) {
4348    ID.AddPointer(T.getAsOpaquePtr());
4349  }
4350  static bool classof(const Type *T) {
4351    return T->getTypeClass() == ObjCObjectPointer;
4352  }
4353  static bool classof(const ObjCObjectPointerType *) { return true; }
4354};
4355
4356class AtomicType : public Type, public llvm::FoldingSetNode {
4357  QualType ValueType;
4358
4359  AtomicType(QualType ValTy, QualType Canonical)
4360    : Type(Atomic, Canonical, ValTy->isDependentType(),
4361           ValTy->isInstantiationDependentType(),
4362           ValTy->isVariablyModifiedType(),
4363           ValTy->containsUnexpandedParameterPack()),
4364      ValueType(ValTy) {}
4365  friend class ASTContext;  // ASTContext creates these.
4366
4367  public:
4368  /// getValueType - Gets the type contained by this atomic type, i.e.
4369  /// the type returned by performing an atomic load of this atomic type.
4370  QualType getValueType() const { return ValueType; }
4371
4372  bool isSugared() const { return false; }
4373  QualType desugar() const { return QualType(this, 0); }
4374
4375  void Profile(llvm::FoldingSetNodeID &ID) {
4376    Profile(ID, getValueType());
4377  }
4378  static void Profile(llvm::FoldingSetNodeID &ID, QualType T) {
4379    ID.AddPointer(T.getAsOpaquePtr());
4380  }
4381  static bool classof(const Type *T) {
4382    return T->getTypeClass() == Atomic;
4383  }
4384  static bool classof(const AtomicType *) { return true; }
4385};
4386
4387/// A qualifier set is used to build a set of qualifiers.
4388class QualifierCollector : public Qualifiers {
4389public:
4390  QualifierCollector(Qualifiers Qs = Qualifiers()) : Qualifiers(Qs) {}
4391
4392  /// Collect any qualifiers on the given type and return an
4393  /// unqualified type.  The qualifiers are assumed to be consistent
4394  /// with those already in the type.
4395  const Type *strip(QualType type) {
4396    addFastQualifiers(type.getLocalFastQualifiers());
4397    if (!type.hasLocalNonFastQualifiers())
4398      return type.getTypePtrUnsafe();
4399
4400    const ExtQuals *extQuals = type.getExtQualsUnsafe();
4401    addConsistentQualifiers(extQuals->getQualifiers());
4402    return extQuals->getBaseType();
4403  }
4404
4405  /// Apply the collected qualifiers to the given type.
4406  QualType apply(const ASTContext &Context, QualType QT) const;
4407
4408  /// Apply the collected qualifiers to the given type.
4409  QualType apply(const ASTContext &Context, const Type* T) const;
4410};
4411
4412
4413// Inline function definitions.
4414
4415inline const Type *QualType::getTypePtr() const {
4416  return getCommonPtr()->BaseType;
4417}
4418
4419inline const Type *QualType::getTypePtrOrNull() const {
4420  return (isNull() ? 0 : getCommonPtr()->BaseType);
4421}
4422
4423inline SplitQualType QualType::split() const {
4424  if (!hasLocalNonFastQualifiers())
4425    return SplitQualType(getTypePtrUnsafe(),
4426                         Qualifiers::fromFastMask(getLocalFastQualifiers()));
4427
4428  const ExtQuals *eq = getExtQualsUnsafe();
4429  Qualifiers qs = eq->getQualifiers();
4430  qs.addFastQualifiers(getLocalFastQualifiers());
4431  return SplitQualType(eq->getBaseType(), qs);
4432}
4433
4434inline Qualifiers QualType::getLocalQualifiers() const {
4435  Qualifiers Quals;
4436  if (hasLocalNonFastQualifiers())
4437    Quals = getExtQualsUnsafe()->getQualifiers();
4438  Quals.addFastQualifiers(getLocalFastQualifiers());
4439  return Quals;
4440}
4441
4442inline Qualifiers QualType::getQualifiers() const {
4443  Qualifiers quals = getCommonPtr()->CanonicalType.getLocalQualifiers();
4444  quals.addFastQualifiers(getLocalFastQualifiers());
4445  return quals;
4446}
4447
4448inline unsigned QualType::getCVRQualifiers() const {
4449  unsigned cvr = getCommonPtr()->CanonicalType.getLocalCVRQualifiers();
4450  cvr |= getLocalCVRQualifiers();
4451  return cvr;
4452}
4453
4454inline QualType QualType::getCanonicalType() const {
4455  QualType canon = getCommonPtr()->CanonicalType;
4456  return canon.withFastQualifiers(getLocalFastQualifiers());
4457}
4458
4459inline bool QualType::isCanonical() const {
4460  return getTypePtr()->isCanonicalUnqualified();
4461}
4462
4463inline bool QualType::isCanonicalAsParam() const {
4464  if (!isCanonical()) return false;
4465  if (hasLocalQualifiers()) return false;
4466
4467  const Type *T = getTypePtr();
4468  if (T->isVariablyModifiedType() && T->hasSizedVLAType())
4469    return false;
4470
4471  return !isa<FunctionType>(T) && !isa<ArrayType>(T);
4472}
4473
4474inline bool QualType::isConstQualified() const {
4475  return isLocalConstQualified() ||
4476         getCommonPtr()->CanonicalType.isLocalConstQualified();
4477}
4478
4479inline bool QualType::isRestrictQualified() const {
4480  return isLocalRestrictQualified() ||
4481         getCommonPtr()->CanonicalType.isLocalRestrictQualified();
4482}
4483
4484
4485inline bool QualType::isVolatileQualified() const {
4486  return isLocalVolatileQualified() ||
4487         getCommonPtr()->CanonicalType.isLocalVolatileQualified();
4488}
4489
4490inline bool QualType::hasQualifiers() const {
4491  return hasLocalQualifiers() ||
4492         getCommonPtr()->CanonicalType.hasLocalQualifiers();
4493}
4494
4495inline QualType QualType::getUnqualifiedType() const {
4496  if (!getTypePtr()->getCanonicalTypeInternal().hasLocalQualifiers())
4497    return QualType(getTypePtr(), 0);
4498
4499  return QualType(getSplitUnqualifiedTypeImpl(*this).first, 0);
4500}
4501
4502inline SplitQualType QualType::getSplitUnqualifiedType() const {
4503  if (!getTypePtr()->getCanonicalTypeInternal().hasLocalQualifiers())
4504    return split();
4505
4506  return getSplitUnqualifiedTypeImpl(*this);
4507}
4508
4509inline void QualType::removeLocalConst() {
4510  removeLocalFastQualifiers(Qualifiers::Const);
4511}
4512
4513inline void QualType::removeLocalRestrict() {
4514  removeLocalFastQualifiers(Qualifiers::Restrict);
4515}
4516
4517inline void QualType::removeLocalVolatile() {
4518  removeLocalFastQualifiers(Qualifiers::Volatile);
4519}
4520
4521inline void QualType::removeLocalCVRQualifiers(unsigned Mask) {
4522  assert(!(Mask & ~Qualifiers::CVRMask) && "mask has non-CVR bits");
4523  assert((int)Qualifiers::CVRMask == (int)Qualifiers::FastMask);
4524
4525  // Fast path: we don't need to touch the slow qualifiers.
4526  removeLocalFastQualifiers(Mask);
4527}
4528
4529/// getAddressSpace - Return the address space of this type.
4530inline unsigned QualType::getAddressSpace() const {
4531  return getQualifiers().getAddressSpace();
4532}
4533
4534/// getObjCGCAttr - Return the gc attribute of this type.
4535inline Qualifiers::GC QualType::getObjCGCAttr() const {
4536  return getQualifiers().getObjCGCAttr();
4537}
4538
4539inline FunctionType::ExtInfo getFunctionExtInfo(const Type &t) {
4540  if (const PointerType *PT = t.getAs<PointerType>()) {
4541    if (const FunctionType *FT = PT->getPointeeType()->getAs<FunctionType>())
4542      return FT->getExtInfo();
4543  } else if (const FunctionType *FT = t.getAs<FunctionType>())
4544    return FT->getExtInfo();
4545
4546  return FunctionType::ExtInfo();
4547}
4548
4549inline FunctionType::ExtInfo getFunctionExtInfo(QualType t) {
4550  return getFunctionExtInfo(*t);
4551}
4552
4553/// isMoreQualifiedThan - Determine whether this type is more
4554/// qualified than the Other type. For example, "const volatile int"
4555/// is more qualified than "const int", "volatile int", and
4556/// "int". However, it is not more qualified than "const volatile
4557/// int".
4558inline bool QualType::isMoreQualifiedThan(QualType other) const {
4559  Qualifiers myQuals = getQualifiers();
4560  Qualifiers otherQuals = other.getQualifiers();
4561  return (myQuals != otherQuals && myQuals.compatiblyIncludes(otherQuals));
4562}
4563
4564/// isAtLeastAsQualifiedAs - Determine whether this type is at last
4565/// as qualified as the Other type. For example, "const volatile
4566/// int" is at least as qualified as "const int", "volatile int",
4567/// "int", and "const volatile int".
4568inline bool QualType::isAtLeastAsQualifiedAs(QualType other) const {
4569  return getQualifiers().compatiblyIncludes(other.getQualifiers());
4570}
4571
4572/// getNonReferenceType - If Type is a reference type (e.g., const
4573/// int&), returns the type that the reference refers to ("const
4574/// int"). Otherwise, returns the type itself. This routine is used
4575/// throughout Sema to implement C++ 5p6:
4576///
4577///   If an expression initially has the type "reference to T" (8.3.2,
4578///   8.5.3), the type is adjusted to "T" prior to any further
4579///   analysis, the expression designates the object or function
4580///   denoted by the reference, and the expression is an lvalue.
4581inline QualType QualType::getNonReferenceType() const {
4582  if (const ReferenceType *RefType = (*this)->getAs<ReferenceType>())
4583    return RefType->getPointeeType();
4584  else
4585    return *this;
4586}
4587
4588inline bool QualType::isCForbiddenLValueType() const {
4589  return ((getTypePtr()->isVoidType() && !hasQualifiers()) ||
4590          getTypePtr()->isFunctionType());
4591}
4592
4593/// \brief Tests whether the type is categorized as a fundamental type.
4594///
4595/// \returns True for types specified in C++0x [basic.fundamental].
4596inline bool Type::isFundamentalType() const {
4597  return isVoidType() ||
4598         // FIXME: It's really annoying that we don't have an
4599         // 'isArithmeticType()' which agrees with the standard definition.
4600         (isArithmeticType() && !isEnumeralType());
4601}
4602
4603/// \brief Tests whether the type is categorized as a compound type.
4604///
4605/// \returns True for types specified in C++0x [basic.compound].
4606inline bool Type::isCompoundType() const {
4607  // C++0x [basic.compound]p1:
4608  //   Compound types can be constructed in the following ways:
4609  //    -- arrays of objects of a given type [...];
4610  return isArrayType() ||
4611  //    -- functions, which have parameters of given types [...];
4612         isFunctionType() ||
4613  //    -- pointers to void or objects or functions [...];
4614         isPointerType() ||
4615  //    -- references to objects or functions of a given type. [...]
4616         isReferenceType() ||
4617  //    -- classes containing a sequence of objects of various types, [...];
4618         isRecordType() ||
4619  //    -- unions, which ar classes capable of containing objects of different types at different times;
4620         isUnionType() ||
4621  //    -- enumerations, which comprise a set of named constant values. [...];
4622         isEnumeralType() ||
4623  //    -- pointers to non-static class members, [...].
4624         isMemberPointerType();
4625}
4626
4627inline bool Type::isFunctionType() const {
4628  return isa<FunctionType>(CanonicalType);
4629}
4630inline bool Type::isPointerType() const {
4631  return isa<PointerType>(CanonicalType);
4632}
4633inline bool Type::isAnyPointerType() const {
4634  return isPointerType() || isObjCObjectPointerType();
4635}
4636inline bool Type::isBlockPointerType() const {
4637  return isa<BlockPointerType>(CanonicalType);
4638}
4639inline bool Type::isReferenceType() const {
4640  return isa<ReferenceType>(CanonicalType);
4641}
4642inline bool Type::isLValueReferenceType() const {
4643  return isa<LValueReferenceType>(CanonicalType);
4644}
4645inline bool Type::isRValueReferenceType() const {
4646  return isa<RValueReferenceType>(CanonicalType);
4647}
4648inline bool Type::isFunctionPointerType() const {
4649  if (const PointerType *T = getAs<PointerType>())
4650    return T->getPointeeType()->isFunctionType();
4651  else
4652    return false;
4653}
4654inline bool Type::isMemberPointerType() const {
4655  return isa<MemberPointerType>(CanonicalType);
4656}
4657inline bool Type::isMemberFunctionPointerType() const {
4658  if (const MemberPointerType* T = getAs<MemberPointerType>())
4659    return T->isMemberFunctionPointer();
4660  else
4661    return false;
4662}
4663inline bool Type::isMemberDataPointerType() const {
4664  if (const MemberPointerType* T = getAs<MemberPointerType>())
4665    return T->isMemberDataPointer();
4666  else
4667    return false;
4668}
4669inline bool Type::isArrayType() const {
4670  return isa<ArrayType>(CanonicalType);
4671}
4672inline bool Type::isConstantArrayType() const {
4673  return isa<ConstantArrayType>(CanonicalType);
4674}
4675inline bool Type::isIncompleteArrayType() const {
4676  return isa<IncompleteArrayType>(CanonicalType);
4677}
4678inline bool Type::isVariableArrayType() const {
4679  return isa<VariableArrayType>(CanonicalType);
4680}
4681inline bool Type::isDependentSizedArrayType() const {
4682  return isa<DependentSizedArrayType>(CanonicalType);
4683}
4684inline bool Type::isBuiltinType() const {
4685  return isa<BuiltinType>(CanonicalType);
4686}
4687inline bool Type::isRecordType() const {
4688  return isa<RecordType>(CanonicalType);
4689}
4690inline bool Type::isEnumeralType() const {
4691  return isa<EnumType>(CanonicalType);
4692}
4693inline bool Type::isAnyComplexType() const {
4694  return isa<ComplexType>(CanonicalType);
4695}
4696inline bool Type::isVectorType() const {
4697  return isa<VectorType>(CanonicalType);
4698}
4699inline bool Type::isExtVectorType() const {
4700  return isa<ExtVectorType>(CanonicalType);
4701}
4702inline bool Type::isObjCObjectPointerType() const {
4703  return isa<ObjCObjectPointerType>(CanonicalType);
4704}
4705inline bool Type::isObjCObjectType() const {
4706  return isa<ObjCObjectType>(CanonicalType);
4707}
4708inline bool Type::isObjCObjectOrInterfaceType() const {
4709  return isa<ObjCInterfaceType>(CanonicalType) ||
4710    isa<ObjCObjectType>(CanonicalType);
4711}
4712inline bool Type::isAtomicType() const {
4713  return isa<AtomicType>(CanonicalType);
4714}
4715
4716inline bool Type::isObjCQualifiedIdType() const {
4717  if (const ObjCObjectPointerType *OPT = getAs<ObjCObjectPointerType>())
4718    return OPT->isObjCQualifiedIdType();
4719  return false;
4720}
4721inline bool Type::isObjCQualifiedClassType() const {
4722  if (const ObjCObjectPointerType *OPT = getAs<ObjCObjectPointerType>())
4723    return OPT->isObjCQualifiedClassType();
4724  return false;
4725}
4726inline bool Type::isObjCIdType() const {
4727  if (const ObjCObjectPointerType *OPT = getAs<ObjCObjectPointerType>())
4728    return OPT->isObjCIdType();
4729  return false;
4730}
4731inline bool Type::isObjCClassType() const {
4732  if (const ObjCObjectPointerType *OPT = getAs<ObjCObjectPointerType>())
4733    return OPT->isObjCClassType();
4734  return false;
4735}
4736inline bool Type::isObjCSelType() const {
4737  if (const PointerType *OPT = getAs<PointerType>())
4738    return OPT->getPointeeType()->isSpecificBuiltinType(BuiltinType::ObjCSel);
4739  return false;
4740}
4741inline bool Type::isObjCBuiltinType() const {
4742  return isObjCIdType() || isObjCClassType() || isObjCSelType();
4743}
4744inline bool Type::isTemplateTypeParmType() const {
4745  return isa<TemplateTypeParmType>(CanonicalType);
4746}
4747
4748inline bool Type::isSpecificBuiltinType(unsigned K) const {
4749  if (const BuiltinType *BT = getAs<BuiltinType>())
4750    if (BT->getKind() == (BuiltinType::Kind) K)
4751      return true;
4752  return false;
4753}
4754
4755inline bool Type::isPlaceholderType() const {
4756  if (const BuiltinType *BT = getAs<BuiltinType>())
4757    return BT->isPlaceholderType();
4758  return false;
4759}
4760
4761inline bool Type::isSpecificPlaceholderType(unsigned K) const {
4762  if (const BuiltinType *BT = dyn_cast<BuiltinType>(this))
4763    return (BT->getKind() == (BuiltinType::Kind) K);
4764  return false;
4765}
4766
4767/// \brief Determines whether this is a type for which one can define
4768/// an overloaded operator.
4769inline bool Type::isOverloadableType() const {
4770  return isDependentType() || isRecordType() || isEnumeralType();
4771}
4772
4773/// \brief Determines whether this type can decay to a pointer type.
4774inline bool Type::canDecayToPointerType() const {
4775  return isFunctionType() || isArrayType();
4776}
4777
4778inline bool Type::hasPointerRepresentation() const {
4779  return (isPointerType() || isReferenceType() || isBlockPointerType() ||
4780          isObjCObjectPointerType() || isNullPtrType());
4781}
4782
4783inline bool Type::hasObjCPointerRepresentation() const {
4784  return isObjCObjectPointerType();
4785}
4786
4787inline const Type *Type::getBaseElementTypeUnsafe() const {
4788  const Type *type = this;
4789  while (const ArrayType *arrayType = type->getAsArrayTypeUnsafe())
4790    type = arrayType->getElementType().getTypePtr();
4791  return type;
4792}
4793
4794/// Insertion operator for diagnostics.  This allows sending QualType's into a
4795/// diagnostic with <<.
4796inline const DiagnosticBuilder &operator<<(const DiagnosticBuilder &DB,
4797                                           QualType T) {
4798  DB.AddTaggedVal(reinterpret_cast<intptr_t>(T.getAsOpaquePtr()),
4799                  DiagnosticsEngine::ak_qualtype);
4800  return DB;
4801}
4802
4803/// Insertion operator for partial diagnostics.  This allows sending QualType's
4804/// into a diagnostic with <<.
4805inline const PartialDiagnostic &operator<<(const PartialDiagnostic &PD,
4806                                           QualType T) {
4807  PD.AddTaggedVal(reinterpret_cast<intptr_t>(T.getAsOpaquePtr()),
4808                  DiagnosticsEngine::ak_qualtype);
4809  return PD;
4810}
4811
4812// Helper class template that is used by Type::getAs to ensure that one does
4813// not try to look through a qualified type to get to an array type.
4814template<typename T,
4815         bool isArrayType = (llvm::is_same<T, ArrayType>::value ||
4816                             llvm::is_base_of<ArrayType, T>::value)>
4817struct ArrayType_cannot_be_used_with_getAs { };
4818
4819template<typename T>
4820struct ArrayType_cannot_be_used_with_getAs<T, true>;
4821
4822/// Member-template getAs<specific type>'.
4823template <typename T> const T *Type::getAs() const {
4824  ArrayType_cannot_be_used_with_getAs<T> at;
4825  (void)at;
4826
4827  // If this is directly a T type, return it.
4828  if (const T *Ty = dyn_cast<T>(this))
4829    return Ty;
4830
4831  // If the canonical form of this type isn't the right kind, reject it.
4832  if (!isa<T>(CanonicalType))
4833    return 0;
4834
4835  // If this is a typedef for the type, strip the typedef off without
4836  // losing all typedef information.
4837  return cast<T>(getUnqualifiedDesugaredType());
4838}
4839
4840inline const ArrayType *Type::getAsArrayTypeUnsafe() const {
4841  // If this is directly an array type, return it.
4842  if (const ArrayType *arr = dyn_cast<ArrayType>(this))
4843    return arr;
4844
4845  // If the canonical form of this type isn't the right kind, reject it.
4846  if (!isa<ArrayType>(CanonicalType))
4847    return 0;
4848
4849  // If this is a typedef for the type, strip the typedef off without
4850  // losing all typedef information.
4851  return cast<ArrayType>(getUnqualifiedDesugaredType());
4852}
4853
4854template <typename T> const T *Type::castAs() const {
4855  ArrayType_cannot_be_used_with_getAs<T> at;
4856  (void) at;
4857
4858  assert(isa<T>(CanonicalType));
4859  if (const T *ty = dyn_cast<T>(this)) return ty;
4860  return cast<T>(getUnqualifiedDesugaredType());
4861}
4862
4863inline const ArrayType *Type::castAsArrayTypeUnsafe() const {
4864  assert(isa<ArrayType>(CanonicalType));
4865  if (const ArrayType *arr = dyn_cast<ArrayType>(this)) return arr;
4866  return cast<ArrayType>(getUnqualifiedDesugaredType());
4867}
4868
4869}  // end namespace clang
4870
4871#endif
4872