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