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