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