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