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