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