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