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