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