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