Type.h revision efadb7768e7c7418185f5a4010ecd8b21ca9731b
1//===--- Type.h - C Language Family Type Representation ---------*- C++ -*-===//
2//
3//                     The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10//  This file defines the Type interface and subclasses.
11//
12//===----------------------------------------------------------------------===//
13
14#ifndef LLVM_CLANG_AST_TYPE_H
15#define LLVM_CLANG_AST_TYPE_H
16
17#include "clang/Basic/Diagnostic.h"
18#include "clang/Basic/IdentifierTable.h"
19#include "clang/AST/NestedNameSpecifier.h"
20#include "clang/AST/TemplateName.h"
21#include "llvm/Support/Casting.h"
22#include "llvm/ADT/APSInt.h"
23#include "llvm/ADT/FoldingSet.h"
24#include "llvm/ADT/PointerIntPair.h"
25#include "llvm/ADT/PointerUnion.h"
26
27using llvm::isa;
28using llvm::cast;
29using llvm::cast_or_null;
30using llvm::dyn_cast;
31using llvm::dyn_cast_or_null;
32namespace clang { class Type; }
33
34namespace llvm {
35  template <typename T>
36  class PointerLikeTypeTraits;
37  template<>
38  class PointerLikeTypeTraits< ::clang::Type*> {
39  public:
40    static inline void *getAsVoidPointer(::clang::Type *P) { return P; }
41    static inline ::clang::Type *getFromVoidPointer(void *P) {
42      return static_cast< ::clang::Type*>(P);
43    }
44    enum { NumLowBitsAvailable = 3 };
45  };
46}
47
48namespace clang {
49  class ASTContext;
50  class TypedefDecl;
51  class TemplateDecl;
52  class TemplateTypeParmDecl;
53  class NonTypeTemplateParmDecl;
54  class TemplateTemplateParmDecl;
55  class TagDecl;
56  class RecordDecl;
57  class CXXRecordDecl;
58  class EnumDecl;
59  class FieldDecl;
60  class ObjCInterfaceDecl;
61  class ObjCProtocolDecl;
62  class ObjCMethodDecl;
63  class Expr;
64  class Stmt;
65  class SourceLocation;
66  class StmtIteratorBase;
67  class TemplateArgument;
68  class QualifiedNameType;
69  struct PrintingPolicy;
70
71  // Provide forward declarations for all of the *Type classes
72#define TYPE(Class, Base) class Class##Type;
73#include "clang/AST/TypeNodes.def"
74
75/// QualType - For efficiency, we don't store CVR-qualified types as nodes on
76/// their own: instead each reference to a type stores the qualifiers.  This
77/// greatly reduces the number of nodes we need to allocate for types (for
78/// example we only need one for 'int', 'const int', 'volatile int',
79/// 'const volatile int', etc).
80///
81/// As an added efficiency bonus, instead of making this a pair, we just store
82/// the three bits we care about in the low bits of the pointer.  To handle the
83/// packing/unpacking, we make QualType be a simple wrapper class that acts like
84/// a smart pointer.
85class QualType {
86  llvm::PointerIntPair<Type*, 3> Value;
87public:
88  enum TQ {   // NOTE: These flags must be kept in sync with DeclSpec::TQ.
89    Const    = 0x1,
90    Restrict = 0x2,
91    Volatile = 0x4,
92    CVRFlags = Const|Restrict|Volatile
93  };
94
95  enum GCAttrTypes {
96    GCNone = 0,
97    Weak,
98    Strong
99  };
100
101  // 24 bits should be enough for anyone.
102  static const unsigned MaxAddressSpace = 0xffffffu;
103
104  QualType() {}
105
106  QualType(const Type *Ptr, unsigned Quals)
107    : Value(const_cast<Type*>(Ptr), Quals) {}
108
109  unsigned getCVRQualifiers() const { return Value.getInt(); }
110  void setCVRQualifiers(unsigned Quals) { Value.setInt(Quals); }
111  Type *getTypePtr() const { return Value.getPointer(); }
112
113  void *getAsOpaquePtr() const { return Value.getOpaqueValue(); }
114  static QualType getFromOpaquePtr(void *Ptr) {
115    QualType T;
116    T.Value.setFromOpaqueValue(Ptr);
117    return T;
118  }
119
120  Type &operator*() const {
121    return *getTypePtr();
122  }
123
124  Type *operator->() const {
125    return getTypePtr();
126  }
127
128  /// isNull - Return true if this QualType doesn't point to a type yet.
129  bool isNull() const {
130    return getTypePtr() == 0;
131  }
132
133  bool isConstQualified() const {
134    return (getCVRQualifiers() & Const) ? true : false;
135  }
136  bool isVolatileQualified() const {
137    return (getCVRQualifiers() & Volatile) ? true : false;
138  }
139  bool isRestrictQualified() const {
140    return (getCVRQualifiers() & Restrict) ? true : false;
141  }
142
143  bool isConstant(ASTContext& Ctx) const;
144
145  /// addConst/addVolatile/addRestrict - add the specified type qual to this
146  /// QualType.
147  void addConst()    { Value.setInt(Value.getInt() | Const); }
148  void addVolatile() { Value.setInt(Value.getInt() | Volatile); }
149  void addRestrict() { Value.setInt(Value.getInt() | Restrict); }
150
151  void removeConst()    { Value.setInt(Value.getInt() & ~Const); }
152  void removeVolatile() { Value.setInt(Value.getInt() & ~Volatile); }
153  void removeRestrict() { Value.setInt(Value.getInt() & ~Restrict); }
154
155  QualType getQualifiedType(unsigned TQs) const {
156    return QualType(getTypePtr(), TQs);
157  }
158  QualType getWithAdditionalQualifiers(unsigned TQs) const {
159    return QualType(getTypePtr(), TQs|getCVRQualifiers());
160  }
161
162  QualType withConst() const { return getWithAdditionalQualifiers(Const); }
163  QualType withVolatile() const { return getWithAdditionalQualifiers(Volatile);}
164  QualType withRestrict() const { return getWithAdditionalQualifiers(Restrict);}
165
166  QualType getUnqualifiedType() const;
167  bool isMoreQualifiedThan(QualType Other) const;
168  bool isAtLeastAsQualifiedAs(QualType Other) const;
169  QualType getNonReferenceType() const;
170
171  /// getDesugaredType - Return the specified type with any "sugar" removed from
172  /// the type.  This takes off typedefs, typeof's etc.  If the outer level of
173  /// the type is already concrete, it returns it unmodified.  This is similar
174  /// to getting the canonical type, but it doesn't remove *all* typedefs.  For
175  /// example, it returns "T*" as "T*", (not as "int*"), because the pointer is
176  /// concrete.
177  QualType getDesugaredType(bool ForDisplay = false) const;
178
179  /// operator==/!= - Indicate whether the specified types and qualifiers are
180  /// identical.
181  bool operator==(const QualType &RHS) const {
182    return Value == RHS.Value;
183  }
184  bool operator!=(const QualType &RHS) const {
185    return Value != RHS.Value;
186  }
187  std::string getAsString() const;
188
189  std::string getAsString(const PrintingPolicy &Policy) const {
190    std::string S;
191    getAsStringInternal(S, Policy);
192    return S;
193  }
194  void getAsStringInternal(std::string &Str,
195                           const PrintingPolicy &Policy) const;
196
197  void dump(const char *s) const;
198  void dump() const;
199
200  void Profile(llvm::FoldingSetNodeID &ID) const {
201    ID.AddPointer(getAsOpaquePtr());
202  }
203
204public:
205
206  /// getAddressSpace - Return the address space of this type.
207  inline unsigned getAddressSpace() const;
208
209  /// GCAttrTypesAttr - Returns gc attribute of this type.
210  inline QualType::GCAttrTypes getObjCGCAttr() const;
211
212  /// isObjCGCWeak true when Type is objc's weak.
213  bool isObjCGCWeak() const {
214    return getObjCGCAttr() == Weak;
215  }
216
217  /// isObjCGCStrong true when Type is objc's strong.
218  bool isObjCGCStrong() const {
219    return getObjCGCAttr() == Strong;
220  }
221
222  /// getNoReturnAttr - Returns true if the type has the noreturn attribute,
223  /// false otherwise.
224  bool getNoReturnAttr() const;
225};
226
227} // end clang.
228
229namespace llvm {
230/// Implement simplify_type for QualType, so that we can dyn_cast from QualType
231/// to a specific Type class.
232template<> struct simplify_type<const ::clang::QualType> {
233  typedef ::clang::Type* SimpleType;
234  static SimpleType getSimplifiedValue(const ::clang::QualType &Val) {
235    return Val.getTypePtr();
236  }
237};
238template<> struct simplify_type< ::clang::QualType>
239  : public simplify_type<const ::clang::QualType> {};
240
241// Teach SmallPtrSet that QualType is "basically a pointer".
242template<>
243class PointerLikeTypeTraits<clang::QualType> {
244public:
245  static inline void *getAsVoidPointer(clang::QualType P) {
246    return P.getAsOpaquePtr();
247  }
248  static inline clang::QualType getFromVoidPointer(void *P) {
249    return clang::QualType::getFromOpaquePtr(P);
250  }
251  // CVR qualifiers go in low bits.
252  enum { NumLowBitsAvailable = 0 };
253};
254} // end namespace llvm
255
256namespace clang {
257
258/// Type - This is the base class of the type hierarchy.  A central concept
259/// with types is that each type always has a canonical type.  A canonical type
260/// is the type with any typedef names stripped out of it or the types it
261/// references.  For example, consider:
262///
263///  typedef int  foo;
264///  typedef foo* bar;
265///    'int *'    'foo *'    'bar'
266///
267/// There will be a Type object created for 'int'.  Since int is canonical, its
268/// canonicaltype pointer points to itself.  There is also a Type for 'foo' (a
269/// TypedefType).  Its CanonicalType pointer points to the 'int' Type.  Next
270/// there is a PointerType that represents 'int*', which, like 'int', is
271/// canonical.  Finally, there is a PointerType type for 'foo*' whose canonical
272/// type is 'int*', and there is a TypedefType for 'bar', whose canonical type
273/// is also 'int*'.
274///
275/// Non-canonical types are useful for emitting diagnostics, without losing
276/// information about typedefs being used.  Canonical types are useful for type
277/// comparisons (they allow by-pointer equality tests) and useful for reasoning
278/// about whether something has a particular form (e.g. is a function type),
279/// because they implicitly, recursively, strip all typedefs out of a type.
280///
281/// Types, once created, are immutable.
282///
283class Type {
284public:
285  enum TypeClass {
286#define TYPE(Class, Base) Class,
287#define ABSTRACT_TYPE(Class, Base)
288#include "clang/AST/TypeNodes.def"
289    TagFirst = Record, TagLast = Enum
290  };
291
292private:
293  QualType CanonicalType;
294
295  /// Dependent - Whether this type is a dependent type (C++ [temp.dep.type]).
296  bool Dependent : 1;
297
298  /// TypeClass bitfield - Enum that specifies what subclass this belongs to.
299  /// Note that this should stay at the end of the ivars for Type so that
300  /// subclasses can pack their bitfields into the same word.
301  unsigned TC : 6;
302
303  Type(const Type&);           // DO NOT IMPLEMENT.
304  void operator=(const Type&); // DO NOT IMPLEMENT.
305protected:
306  // silence VC++ warning C4355: 'this' : used in base member initializer list
307  Type *this_() { return this; }
308  Type(TypeClass tc, QualType Canonical, bool dependent)
309    : CanonicalType(Canonical.isNull() ? QualType(this_(), 0) : Canonical),
310      Dependent(dependent), TC(tc) {}
311  virtual ~Type() {}
312  virtual void Destroy(ASTContext& C);
313  friend class ASTContext;
314
315public:
316  TypeClass getTypeClass() const { return static_cast<TypeClass>(TC); }
317
318  bool isCanonical() const { return CanonicalType.getTypePtr() == this; }
319
320  /// Types are partitioned into 3 broad categories (C99 6.2.5p1):
321  /// object types, function types, and incomplete types.
322
323  /// \brief Determines whether the type describes an object in memory.
324  ///
325  /// Note that this definition of object type corresponds to the C++
326  /// definition of object type, which includes incomplete types, as
327  /// opposed to the C definition (which does not include incomplete
328  /// types).
329  bool isObjectType() const;
330
331  /// isIncompleteType - Return true if this is an incomplete type.
332  /// A type that can describe objects, but which lacks information needed to
333  /// determine its size (e.g. void, or a fwd declared struct). Clients of this
334  /// routine will need to determine if the size is actually required.
335  bool isIncompleteType() const;
336
337  /// isIncompleteOrObjectType - Return true if this is an incomplete or object
338  /// type, in other words, not a function type.
339  bool isIncompleteOrObjectType() const {
340    return !isFunctionType();
341  }
342
343  /// isPODType - Return true if this is a plain-old-data type (C++ 3.9p10).
344  bool isPODType() const;
345
346  /// isVariablyModifiedType (C99 6.7.5.2p2) - Return true for variable array
347  /// types that have a non-constant expression. This does not include "[]".
348  bool isVariablyModifiedType() const;
349
350  /// Helper methods to distinguish type categories. All type predicates
351  /// operate on the canonical type, ignoring typedefs and qualifiers.
352
353  /// isSpecificBuiltinType - Test for a particular builtin type.
354  bool isSpecificBuiltinType(unsigned K) const;
355
356  /// isIntegerType() does *not* include complex integers (a GCC extension).
357  /// isComplexIntegerType() can be used to test for complex integers.
358  bool isIntegerType() const;     // C99 6.2.5p17 (int, char, bool, enum)
359  bool isEnumeralType() const;
360  bool isBooleanType() const;
361  bool isCharType() const;
362  bool isWideCharType() const;
363  bool isIntegralType() const;
364
365  /// Floating point categories.
366  bool isRealFloatingType() const; // C99 6.2.5p10 (float, double, long double)
367  /// isComplexType() does *not* include complex integers (a GCC extension).
368  /// isComplexIntegerType() can be used to test for complex integers.
369  bool isComplexType() const;      // C99 6.2.5p11 (complex)
370  bool isAnyComplexType() const;   // C99 6.2.5p11 (complex) + Complex Int.
371  bool isFloatingType() const;     // C99 6.2.5p11 (real floating + complex)
372  bool isRealType() const;         // C99 6.2.5p17 (real floating + integer)
373  bool isArithmeticType() const;   // C99 6.2.5p18 (integer + floating)
374  bool isVoidType() const;         // C99 6.2.5p19
375  bool isDerivedType() const;      // C99 6.2.5p20
376  bool isScalarType() const;       // C99 6.2.5p21 (arithmetic + pointers)
377  bool isAggregateType() const;
378
379  // Type Predicates: Check to see if this type is structurally the specified
380  // type, ignoring typedefs and qualifiers.
381  bool isFunctionType() const;
382  bool isFunctionNoProtoType() const { return getAsFunctionNoProtoType() != 0; }
383  bool isFunctionProtoType() const { return getAsFunctionProtoType() != 0; }
384  bool isPointerType() const;
385  bool isAnyPointerType() const;   // Any C pointer or ObjC object pointer
386  bool isBlockPointerType() const;
387  bool isVoidPointerType() const;
388  bool isReferenceType() const;
389  bool isLValueReferenceType() const;
390  bool isRValueReferenceType() const;
391  bool isFunctionPointerType() const;
392  bool isMemberPointerType() const;
393  bool isMemberFunctionPointerType() const;
394  bool isArrayType() const;
395  bool isConstantArrayType() const;
396  bool isIncompleteArrayType() const;
397  bool isVariableArrayType() const;
398  bool isDependentSizedArrayType() const;
399  bool isRecordType() const;
400  bool isClassType() const;
401  bool isStructureType() const;
402  bool isUnionType() const;
403  bool isComplexIntegerType() const;            // GCC _Complex integer type.
404  bool isVectorType() const;                    // GCC vector type.
405  bool isExtVectorType() const;                 // Extended vector type.
406  bool isObjCObjectPointerType() const;         // Pointer to *any* ObjC object.
407  // FIXME: change this to 'raw' interface type, so we can used 'interface' type
408  // for the common case.
409  bool isObjCInterfaceType() const;             // NSString or NSString<foo>
410  bool isObjCQualifiedInterfaceType() const;    // NSString<foo>
411  bool isObjCQualifiedIdType() const;           // id<foo>
412  bool isObjCQualifiedClassType() const;        // Class<foo>
413  bool isObjCIdType() const;                    // id
414  bool isObjCClassType() const;                 // Class
415  bool isObjCBuiltinType() const;               // 'id' or 'Class'
416  bool isTemplateTypeParmType() const;          // C++ template type parameter
417  bool isNullPtrType() const;                   // C++0x nullptr_t
418
419  /// isDependentType - Whether this type is a dependent type, meaning
420  /// that its definition somehow depends on a template parameter
421  /// (C++ [temp.dep.type]).
422  bool isDependentType() const { return Dependent; }
423  bool isOverloadableType() const;
424
425  /// hasPointerRepresentation - Whether this type is represented
426  /// natively as a pointer; this includes pointers, references, block
427  /// pointers, and Objective-C interface, qualified id, and qualified
428  /// interface types, as well as nullptr_t.
429  bool hasPointerRepresentation() const;
430
431  /// hasObjCPointerRepresentation - Whether this type can represent
432  /// an objective pointer type for the purpose of GC'ability
433  bool hasObjCPointerRepresentation() const;
434
435  // Type Checking Functions: Check to see if this type is structurally the
436  // specified type, ignoring typedefs and qualifiers, and return a pointer to
437  // the best type we can.
438  const BuiltinType *getAsBuiltinType() const;
439  const FunctionType *getAsFunctionType() const;
440  const FunctionNoProtoType *getAsFunctionNoProtoType() const;
441  const FunctionProtoType *getAsFunctionProtoType() const;
442  const PointerType *getAsPointerType() const;
443  const BlockPointerType *getAsBlockPointerType() const;
444  const ReferenceType *getAsReferenceType() const;
445  const LValueReferenceType *getAsLValueReferenceType() const;
446  const RValueReferenceType *getAsRValueReferenceType() const;
447  const MemberPointerType *getAsMemberPointerType() const;
448  const TagType *getAsTagType() const;
449  const RecordType *getAsRecordType() const;
450  const RecordType *getAsStructureType() const;
451  /// NOTE: getAs*ArrayType are methods on ASTContext.
452  const TypedefType *getAsTypedefType() const;
453  const RecordType *getAsUnionType() const;
454  const EnumType *getAsEnumType() const;
455  const VectorType *getAsVectorType() const; // GCC vector type.
456  const ComplexType *getAsComplexType() const;
457  const ComplexType *getAsComplexIntegerType() const; // GCC complex int type.
458  const ExtVectorType *getAsExtVectorType() const; // Extended vector type.
459  const ObjCObjectPointerType *getAsObjCObjectPointerType() const;
460  // The following is a convenience method that returns an ObjCObjectPointerType
461  // for object declared using an interface.
462  const ObjCObjectPointerType *getAsObjCInterfacePointerType() const;
463  const ObjCObjectPointerType *getAsObjCQualifiedIdType() const;
464  const ObjCInterfaceType *getAsObjCInterfaceType() const;
465  const ObjCInterfaceType *getAsObjCQualifiedInterfaceType() const;
466  const TemplateTypeParmType *getAsTemplateTypeParmType() const;
467
468  // Member-template getAs<specific type>'.  This scheme will eventually
469  // replace the specific getAsXXXX methods above.
470  template <typename T> const T *getAs() const;
471
472  const TemplateSpecializationType *
473    getAsTemplateSpecializationType() const;
474
475  /// getAsPointerToObjCInterfaceType - If this is a pointer to an ObjC
476  /// interface, return the interface type, otherwise return null.
477  const ObjCInterfaceType *getAsPointerToObjCInterfaceType() const;
478
479  /// getArrayElementTypeNoTypeQual - If this is an array type, return the
480  /// element type of the array, potentially with type qualifiers missing.
481  /// This method should never be used when type qualifiers are meaningful.
482  const Type *getArrayElementTypeNoTypeQual() const;
483
484  /// getPointeeType - If this is a pointer, ObjC object pointer, or block
485  /// pointer, this returns the respective pointee.
486  QualType getPointeeType() const;
487
488  /// getDesugaredType - Return the specified type with any "sugar" removed from
489  /// the type.  This takes off typedefs, typeof's etc.  If the outer level of
490  /// the type is already concrete, it returns it unmodified.  This is similar
491  /// to getting the canonical type, but it doesn't remove *all* typedefs.  For
492  /// example, it returns "T*" as "T*", (not as "int*"), because the pointer is
493  /// concrete.
494  QualType getDesugaredType(bool ForDisplay = false) const;
495
496  /// More type predicates useful for type checking/promotion
497  bool isPromotableIntegerType() const; // C99 6.3.1.1p2
498
499  /// isSignedIntegerType - Return true if this is an integer type that is
500  /// signed, according to C99 6.2.5p4 [char, signed char, short, int, long..],
501  /// an enum decl which has a signed representation, or a vector of signed
502  /// integer element type.
503  bool isSignedIntegerType() const;
504
505  /// isUnsignedIntegerType - Return true if this is an integer type that is
506  /// unsigned, according to C99 6.2.5p6 [which returns true for _Bool], an enum
507  /// decl which has an unsigned representation, or a vector of unsigned integer
508  /// element type.
509  bool isUnsignedIntegerType() const;
510
511  /// isConstantSizeType - Return true if this is not a variable sized type,
512  /// according to the rules of C99 6.7.5p3.  It is not legal to call this on
513  /// incomplete types.
514  bool isConstantSizeType() const;
515
516  /// isSpecifierType - Returns true if this type can be represented by some
517  /// set of type specifiers.
518  bool isSpecifierType() const;
519
520  QualType getCanonicalTypeInternal() const { return CanonicalType; }
521  void dump() const;
522  virtual void getAsStringInternal(std::string &InnerString,
523                                   const PrintingPolicy &Policy) const = 0;
524  static bool classof(const Type *) { return true; }
525};
526
527/// ExtQualType - TR18037 (C embedded extensions) 6.2.5p26
528/// This supports all kinds of type attributes; including,
529/// address space qualified types, objective-c's __weak and
530/// __strong attributes.
531///
532class ExtQualType : public Type, public llvm::FoldingSetNode {
533  /// BaseType - This is the underlying type that this qualifies.  All CVR
534  /// qualifiers are stored on the QualType that references this type, so we
535  /// can't have any here.
536  Type *BaseType;
537
538  /// Address Space ID - The address space ID this type is qualified with.
539  unsigned AddressSpace;
540  /// GC __weak/__strong attributes
541  QualType::GCAttrTypes GCAttrType;
542
543  ExtQualType(Type *Base, QualType CanonicalPtr, unsigned AddrSpace,
544              QualType::GCAttrTypes gcAttr) :
545      Type(ExtQual, CanonicalPtr, Base->isDependentType()), BaseType(Base),
546      AddressSpace(AddrSpace), GCAttrType(gcAttr) {
547    assert(!isa<ExtQualType>(BaseType) &&
548           "Cannot have ExtQualType of ExtQualType");
549  }
550  friend class ASTContext;  // ASTContext creates these.
551public:
552  Type *getBaseType() const { return BaseType; }
553  QualType::GCAttrTypes getObjCGCAttr() const { return GCAttrType; }
554  unsigned getAddressSpace() const { return AddressSpace; }
555
556  virtual void getAsStringInternal(std::string &InnerString,
557                                   const PrintingPolicy &Policy) const;
558
559  void Profile(llvm::FoldingSetNodeID &ID) {
560    Profile(ID, getBaseType(), AddressSpace, GCAttrType);
561  }
562  static void Profile(llvm::FoldingSetNodeID &ID, Type *Base,
563                      unsigned AddrSpace, QualType::GCAttrTypes gcAttr) {
564    ID.AddPointer(Base);
565    ID.AddInteger(AddrSpace);
566    ID.AddInteger(gcAttr);
567  }
568
569  static bool classof(const Type *T) { return T->getTypeClass() == ExtQual; }
570  static bool classof(const ExtQualType *) { return true; }
571};
572
573
574/// QualifierSet - This class is used to collect qualifiers.
575/// Clang supports five independent qualifiers:
576/// * C99: const, volatile, and restrict
577/// * Embedded C (TR18037): address spaces
578/// * Objective C: the GC attributes (none, weak, or strong)
579class QualifierSet {
580public:
581  QualifierSet() : Mask(0) {}
582
583  void removeConst() { removeCVR(QualType::Const); }
584  void removeVolatile() { removeCVR(QualType::Volatile); }
585  void removeRestrict() { removeCVR(QualType::Restrict); }
586  void removeCVR(unsigned mask) { Mask &= ~mask; }
587  void removeAddressSpace() { setAddressSpace(0); }
588  void removeObjCGCAttrType() { setGCAttrType(QualType::GCNone); }
589
590  void addConst() { addCVR(QualType::Const); }
591  void addVolatile() { addCVR(QualType::Volatile); }
592  void addRestrict() { addCVR(QualType::Restrict); }
593  void addCVR(unsigned mask) { Mask |= mask; }
594  void addAddressSpace(unsigned space) {
595    assert(space);
596    setAddressSpace(space);
597  }
598  void addObjCGCAttrType(QualType::GCAttrTypes type) {
599    assert(type);
600    setGCAttrType(type);
601  }
602
603  bool hasConst() const { return Mask & QualType::Const; }
604  bool hasVolatile() const { return Mask & QualType::Volatile; }
605  bool hasRestrict() const { return Mask & QualType::Restrict; }
606  unsigned getCVRMask() const { return Mask & CVRMask; }
607
608  bool hasObjCGCAttrType() const { return Mask & GCAttrMask; }
609  QualType::GCAttrTypes getObjCGCAttrType() const {
610    return QualType::GCAttrTypes((Mask & GCAttrMask) >> GCAttrShift);
611  }
612
613  bool hasAddressSpace() const { return Mask & AddressSpaceMask; }
614  unsigned getAddressSpace() const { return Mask >> AddressSpaceShift; }
615
616  /// empty() - Return true if there are no qualifiers collected
617  /// in this set.
618  bool empty() {
619    return (Mask == 0);
620  }
621
622  /// Collect any qualifiers on the given type and return an
623  /// unqualified type.
624  const Type *strip(QualType QT) {
625    Mask |= QT.getCVRQualifiers();
626    return strip(QT.getTypePtr());
627  }
628
629  /// Collect any qualifiers on the given type and return an
630  /// unqualified type.
631  const Type *strip(const Type* T);
632
633  /// Apply the collected qualifiers to the given type.
634  QualType apply(QualType QT, ASTContext& C);
635
636  /// Apply the collected qualifiers to the given type.
637  QualType apply(const Type* T, ASTContext& C) {
638    return apply(QualType(T, 0), C);
639  }
640
641  bool operator==(QualifierSet& Other) { return Mask == Other.Mask; }
642
643private:
644  void setAddressSpace(unsigned space) {
645    assert(space <= MaxAddressSpace);
646    Mask = (Mask & ~AddressSpaceMask)
647         | (((uint32_t) space) << AddressSpaceShift);
648  }
649
650  void setGCAttrType(QualType::GCAttrTypes type) {
651    Mask = (Mask & ~GCAttrMask) | (type << GCAttrShift);
652  }
653
654  // bits:     |0 1 2|3 .. 4|5  ..  31|
655  //           |C R V|GCAttr|AddrSpace|
656  uint32_t Mask;
657
658  static const uint32_t CVRMask = 0x07;
659  static const uint32_t GCAttrMask = 0x18;
660  static const uint32_t GCAttrShift = 3;
661  static const uint32_t AddressSpaceMask = ~(CVRMask | GCAttrMask);
662  static const uint32_t AddressSpaceShift = 5;
663  static const unsigned MaxAddressSpace = QualType::MaxAddressSpace;
664};
665
666
667/// BuiltinType - This class is used for builtin types like 'int'.  Builtin
668/// types are always canonical and have a literal name field.
669class BuiltinType : public Type {
670public:
671  enum Kind {
672    Void,
673
674    Bool,     // This is bool and/or _Bool.
675    Char_U,   // This is 'char' for targets where char is unsigned.
676    UChar,    // This is explicitly qualified unsigned char.
677    Char16,   // This is 'char16_t' for C++.
678    Char32,   // This is 'char32_t' for C++.
679    UShort,
680    UInt,
681    ULong,
682    ULongLong,
683    UInt128,  // __uint128_t
684
685    Char_S,   // This is 'char' for targets where char is signed.
686    SChar,    // This is explicitly qualified signed char.
687    WChar,    // This is 'wchar_t' for C++.
688    Short,
689    Int,
690    Long,
691    LongLong,
692    Int128,   // __int128_t
693
694    Float, Double, LongDouble,
695
696    NullPtr,  // This is the type of C++0x 'nullptr'.
697
698    Overload,  // This represents the type of an overloaded function declaration.
699    Dependent, // This represents the type of a type-dependent expression.
700
701    UndeducedAuto, // In C++0x, this represents the type of an auto variable
702                   // that has not been deduced yet.
703    ObjCId,    // This represents the ObjC 'id' type.
704    ObjCClass  // This represents the ObjC 'Class' type.
705  };
706private:
707  Kind TypeKind;
708public:
709  BuiltinType(Kind K)
710    : Type(Builtin, QualType(), /*Dependent=*/(K == Dependent)),
711      TypeKind(K) {}
712
713  Kind getKind() const { return TypeKind; }
714  const char *getName(const LangOptions &LO) const;
715
716  virtual void getAsStringInternal(std::string &InnerString,
717                                   const PrintingPolicy &Policy) const;
718
719  static bool classof(const Type *T) { return T->getTypeClass() == Builtin; }
720  static bool classof(const BuiltinType *) { return true; }
721};
722
723/// FixedWidthIntType - Used for arbitrary width types that we either don't
724/// want to or can't map to named integer types.  These always have a lower
725/// integer rank than builtin types of the same width.
726class FixedWidthIntType : public Type {
727private:
728  unsigned Width;
729  bool Signed;
730public:
731  FixedWidthIntType(unsigned W, bool S) : Type(FixedWidthInt, QualType(), false),
732                                          Width(W), Signed(S) {}
733
734  unsigned getWidth() const { return Width; }
735  bool isSigned() const { return Signed; }
736  const char *getName() const;
737
738  virtual void getAsStringInternal(std::string &InnerString,
739                                   const PrintingPolicy &Policy) const;
740
741  static bool classof(const Type *T) { return T->getTypeClass() == FixedWidthInt; }
742  static bool classof(const FixedWidthIntType *) { return true; }
743};
744
745/// ComplexType - C99 6.2.5p11 - Complex values.  This supports the C99 complex
746/// types (_Complex float etc) as well as the GCC integer complex extensions.
747///
748class ComplexType : public Type, public llvm::FoldingSetNode {
749  QualType ElementType;
750  ComplexType(QualType Element, QualType CanonicalPtr) :
751    Type(Complex, CanonicalPtr, Element->isDependentType()),
752    ElementType(Element) {
753  }
754  friend class ASTContext;  // ASTContext creates these.
755public:
756  QualType getElementType() const { return ElementType; }
757
758  virtual void getAsStringInternal(std::string &InnerString,
759                                   const PrintingPolicy &Policy) const;
760
761  void Profile(llvm::FoldingSetNodeID &ID) {
762    Profile(ID, getElementType());
763  }
764  static void Profile(llvm::FoldingSetNodeID &ID, QualType Element) {
765    ID.AddPointer(Element.getAsOpaquePtr());
766  }
767
768  static bool classof(const Type *T) { return T->getTypeClass() == Complex; }
769  static bool classof(const ComplexType *) { return true; }
770};
771
772/// PointerType - C99 6.7.5.1 - Pointer Declarators.
773///
774class PointerType : public Type, public llvm::FoldingSetNode {
775  QualType PointeeType;
776
777  PointerType(QualType Pointee, QualType CanonicalPtr) :
778    Type(Pointer, CanonicalPtr, Pointee->isDependentType()), PointeeType(Pointee) {
779  }
780  friend class ASTContext;  // ASTContext creates these.
781public:
782
783  virtual void getAsStringInternal(std::string &InnerString,
784                                   const PrintingPolicy &Policy) const;
785
786  QualType getPointeeType() const { return PointeeType; }
787
788  void Profile(llvm::FoldingSetNodeID &ID) {
789    Profile(ID, getPointeeType());
790  }
791  static void Profile(llvm::FoldingSetNodeID &ID, QualType Pointee) {
792    ID.AddPointer(Pointee.getAsOpaquePtr());
793  }
794
795  static bool classof(const Type *T) { return T->getTypeClass() == Pointer; }
796  static bool classof(const PointerType *) { return true; }
797};
798
799/// BlockPointerType - pointer to a block type.
800/// This type is to represent types syntactically represented as
801/// "void (^)(int)", etc. Pointee is required to always be a function type.
802///
803class BlockPointerType : public Type, public llvm::FoldingSetNode {
804  QualType PointeeType;  // Block is some kind of pointer type
805  BlockPointerType(QualType Pointee, QualType CanonicalCls) :
806    Type(BlockPointer, CanonicalCls, Pointee->isDependentType()),
807    PointeeType(Pointee) {
808  }
809  friend class ASTContext;  // ASTContext creates these.
810public:
811
812  // Get the pointee type. Pointee is required to always be a function type.
813  QualType getPointeeType() const { return PointeeType; }
814
815  virtual void getAsStringInternal(std::string &InnerString,
816                                   const PrintingPolicy &Policy) const;
817
818  void Profile(llvm::FoldingSetNodeID &ID) {
819      Profile(ID, getPointeeType());
820  }
821  static void Profile(llvm::FoldingSetNodeID &ID, QualType Pointee) {
822      ID.AddPointer(Pointee.getAsOpaquePtr());
823  }
824
825  static bool classof(const Type *T) {
826    return T->getTypeClass() == BlockPointer;
827  }
828  static bool classof(const BlockPointerType *) { return true; }
829};
830
831/// ReferenceType - Base for LValueReferenceType and RValueReferenceType
832///
833class ReferenceType : public Type, public llvm::FoldingSetNode {
834  QualType PointeeType;
835
836protected:
837  ReferenceType(TypeClass tc, QualType Referencee, QualType CanonicalRef) :
838    Type(tc, CanonicalRef, Referencee->isDependentType()),
839    PointeeType(Referencee) {
840  }
841public:
842  QualType getPointeeType() const { return PointeeType; }
843
844  void Profile(llvm::FoldingSetNodeID &ID) {
845    Profile(ID, getPointeeType());
846  }
847  static void Profile(llvm::FoldingSetNodeID &ID, QualType Referencee) {
848    ID.AddPointer(Referencee.getAsOpaquePtr());
849  }
850
851  static bool classof(const Type *T) {
852    return T->getTypeClass() == LValueReference ||
853           T->getTypeClass() == RValueReference;
854  }
855  static bool classof(const ReferenceType *) { return true; }
856};
857
858/// LValueReferenceType - C++ [dcl.ref] - Lvalue reference
859///
860class LValueReferenceType : public ReferenceType {
861  LValueReferenceType(QualType Referencee, QualType CanonicalRef) :
862    ReferenceType(LValueReference, Referencee, CanonicalRef) {
863  }
864  friend class ASTContext; // ASTContext creates these
865public:
866  virtual void getAsStringInternal(std::string &InnerString,
867                                   const PrintingPolicy &Policy) const;
868
869  static bool classof(const Type *T) {
870    return T->getTypeClass() == LValueReference;
871  }
872  static bool classof(const LValueReferenceType *) { return true; }
873};
874
875/// RValueReferenceType - C++0x [dcl.ref] - Rvalue reference
876///
877class RValueReferenceType : public ReferenceType {
878  RValueReferenceType(QualType Referencee, QualType CanonicalRef) :
879    ReferenceType(RValueReference, Referencee, CanonicalRef) {
880  }
881  friend class ASTContext; // ASTContext creates these
882public:
883  virtual void getAsStringInternal(std::string &InnerString,
884                                   const PrintingPolicy &Policy) const;
885
886  static bool classof(const Type *T) {
887    return T->getTypeClass() == RValueReference;
888  }
889  static bool classof(const RValueReferenceType *) { return true; }
890};
891
892/// MemberPointerType - C++ 8.3.3 - Pointers to members
893///
894class MemberPointerType : public Type, public llvm::FoldingSetNode {
895  QualType PointeeType;
896  /// The class of which the pointee is a member. Must ultimately be a
897  /// RecordType, but could be a typedef or a template parameter too.
898  const Type *Class;
899
900  MemberPointerType(QualType Pointee, const Type *Cls, QualType CanonicalPtr) :
901    Type(MemberPointer, CanonicalPtr,
902         Cls->isDependentType() || Pointee->isDependentType()),
903    PointeeType(Pointee), Class(Cls) {
904  }
905  friend class ASTContext; // ASTContext creates these.
906public:
907
908  QualType getPointeeType() const { return PointeeType; }
909
910  const Type *getClass() const { return Class; }
911
912  virtual void getAsStringInternal(std::string &InnerString,
913                                   const PrintingPolicy &Policy) const;
914
915  void Profile(llvm::FoldingSetNodeID &ID) {
916    Profile(ID, getPointeeType(), getClass());
917  }
918  static void Profile(llvm::FoldingSetNodeID &ID, QualType Pointee,
919                      const Type *Class) {
920    ID.AddPointer(Pointee.getAsOpaquePtr());
921    ID.AddPointer(Class);
922  }
923
924  static bool classof(const Type *T) {
925    return T->getTypeClass() == MemberPointer;
926  }
927  static bool classof(const MemberPointerType *) { return true; }
928};
929
930/// ArrayType - C99 6.7.5.2 - Array Declarators.
931///
932class ArrayType : public Type, public llvm::FoldingSetNode {
933public:
934  /// ArraySizeModifier - Capture whether this is a normal array (e.g. int X[4])
935  /// an array with a static size (e.g. int X[static 4]), or an array
936  /// with a star size (e.g. int X[*]).
937  /// 'static' is only allowed on function parameters.
938  enum ArraySizeModifier {
939    Normal, Static, Star
940  };
941private:
942  /// ElementType - The element type of the array.
943  QualType ElementType;
944
945  // NOTE: VC++ treats enums as signed, avoid using the ArraySizeModifier enum
946  /// NOTE: These fields are packed into the bitfields space in the Type class.
947  unsigned SizeModifier : 2;
948
949  /// IndexTypeQuals - Capture qualifiers in declarations like:
950  /// 'int X[static restrict 4]'. For function parameters only.
951  unsigned IndexTypeQuals : 3;
952
953protected:
954  // C++ [temp.dep.type]p1:
955  //   A type is dependent if it is...
956  //     - an array type constructed from any dependent type or whose
957  //       size is specified by a constant expression that is
958  //       value-dependent,
959  ArrayType(TypeClass tc, QualType et, QualType can,
960            ArraySizeModifier sm, unsigned tq)
961    : Type(tc, can, et->isDependentType() || tc == DependentSizedArray),
962      ElementType(et), SizeModifier(sm), IndexTypeQuals(tq) {}
963
964  friend class ASTContext;  // ASTContext creates these.
965public:
966  QualType getElementType() const { return ElementType; }
967  ArraySizeModifier getSizeModifier() const {
968    return ArraySizeModifier(SizeModifier);
969  }
970  unsigned getIndexTypeQualifier() const { return IndexTypeQuals; }
971
972  static bool classof(const Type *T) {
973    return T->getTypeClass() == ConstantArray ||
974           T->getTypeClass() == ConstantArrayWithExpr ||
975           T->getTypeClass() == ConstantArrayWithoutExpr ||
976           T->getTypeClass() == VariableArray ||
977           T->getTypeClass() == IncompleteArray ||
978           T->getTypeClass() == DependentSizedArray;
979  }
980  static bool classof(const ArrayType *) { return true; }
981};
982
983/// ConstantArrayType - This class represents the canonical version of
984/// C arrays with a specified constant size.  For example, the canonical
985/// type for 'int A[4 + 4*100]' is a ConstantArrayType where the element
986/// type is 'int' and the size is 404.
987class ConstantArrayType : public ArrayType {
988  llvm::APInt Size; // Allows us to unique the type.
989
990  ConstantArrayType(QualType et, QualType can, const llvm::APInt &size,
991                    ArraySizeModifier sm, unsigned tq)
992    : ArrayType(ConstantArray, et, can, sm, tq),
993      Size(size) {}
994protected:
995  ConstantArrayType(TypeClass tc, QualType et, QualType can,
996                    const llvm::APInt &size, ArraySizeModifier sm, unsigned tq)
997    : ArrayType(tc, et, can, sm, tq), Size(size) {}
998  friend class ASTContext;  // ASTContext creates these.
999public:
1000  const llvm::APInt &getSize() const { return Size; }
1001  virtual void getAsStringInternal(std::string &InnerString,
1002                                   const PrintingPolicy &Policy) const;
1003
1004  void Profile(llvm::FoldingSetNodeID &ID) {
1005    Profile(ID, getElementType(), getSize(),
1006            getSizeModifier(), getIndexTypeQualifier());
1007  }
1008  static void Profile(llvm::FoldingSetNodeID &ID, QualType ET,
1009                      const llvm::APInt &ArraySize, ArraySizeModifier SizeMod,
1010                      unsigned TypeQuals) {
1011    ID.AddPointer(ET.getAsOpaquePtr());
1012    ID.AddInteger(ArraySize.getZExtValue());
1013    ID.AddInteger(SizeMod);
1014    ID.AddInteger(TypeQuals);
1015  }
1016  static bool classof(const Type *T) {
1017    return T->getTypeClass() == ConstantArray ||
1018           T->getTypeClass() == ConstantArrayWithExpr ||
1019           T->getTypeClass() == ConstantArrayWithoutExpr;
1020  }
1021  static bool classof(const ConstantArrayType *) { return true; }
1022};
1023
1024/// ConstantArrayWithExprType - This class represents C arrays with a
1025/// constant size specified by means of an integer constant expression.
1026/// For example 'int A[sizeof(int)]' has ConstantArrayWithExprType where
1027/// the element type is 'int' and the size expression is 'sizeof(int)'.
1028/// These types are non-canonical.
1029class ConstantArrayWithExprType : public ConstantArrayType {
1030  /// SizeExpr - The ICE occurring in the concrete syntax.
1031  Expr *SizeExpr;
1032  /// Brackets - The left and right array brackets.
1033  SourceRange Brackets;
1034
1035  ConstantArrayWithExprType(QualType et, QualType can,
1036                            const llvm::APInt &size, Expr *e,
1037                            ArraySizeModifier sm, unsigned tq,
1038                            SourceRange brackets)
1039    : ConstantArrayType(ConstantArrayWithExpr, et, can, size, sm, tq),
1040      SizeExpr(e), Brackets(brackets) {}
1041  friend class ASTContext;  // ASTContext creates these.
1042  virtual void Destroy(ASTContext& C);
1043
1044public:
1045  Expr *getSizeExpr() const { return SizeExpr; }
1046  SourceRange getBracketsRange() const { return Brackets; }
1047  SourceLocation getLBracketLoc() const { return Brackets.getBegin(); }
1048  SourceLocation getRBracketLoc() const { return Brackets.getEnd(); }
1049
1050  virtual void getAsStringInternal(std::string &InnerString,
1051                                   const PrintingPolicy &Policy) const;
1052
1053  static bool classof(const Type *T) {
1054    return T->getTypeClass() == ConstantArrayWithExpr;
1055  }
1056  static bool classof(const ConstantArrayWithExprType *) { return true; }
1057
1058  void Profile(llvm::FoldingSetNodeID &ID) {
1059    assert(0 && "Cannot unique ConstantArrayWithExprTypes.");
1060  }
1061};
1062
1063/// ConstantArrayWithoutExprType - This class represents C arrays with a
1064/// constant size that was not specified by an integer constant expression,
1065/// but inferred by static semantics.
1066/// For example 'int A[] = { 0, 1, 2 }' has ConstantArrayWithoutExprType.
1067/// These types are non-canonical: the corresponding canonical type,
1068/// having the size specified in an APInt object, is a ConstantArrayType.
1069class ConstantArrayWithoutExprType : public ConstantArrayType {
1070
1071  ConstantArrayWithoutExprType(QualType et, QualType can,
1072                               const llvm::APInt &size,
1073                               ArraySizeModifier sm, unsigned tq)
1074    : ConstantArrayType(ConstantArrayWithoutExpr, et, can, size, sm, tq) {}
1075  friend class ASTContext;  // ASTContext creates these.
1076
1077public:
1078  virtual void getAsStringInternal(std::string &InnerString,
1079                                   const PrintingPolicy &Policy) const;
1080
1081  static bool classof(const Type *T) {
1082    return T->getTypeClass() == ConstantArrayWithoutExpr;
1083  }
1084  static bool classof(const ConstantArrayWithoutExprType *) { return true; }
1085
1086  void Profile(llvm::FoldingSetNodeID &ID) {
1087    assert(0 && "Cannot unique ConstantArrayWithoutExprTypes.");
1088  }
1089};
1090
1091/// IncompleteArrayType - This class represents C arrays with an unspecified
1092/// size.  For example 'int A[]' has an IncompleteArrayType where the element
1093/// type is 'int' and the size is unspecified.
1094class IncompleteArrayType : public ArrayType {
1095
1096  IncompleteArrayType(QualType et, QualType can,
1097                      ArraySizeModifier sm, unsigned tq)
1098    : ArrayType(IncompleteArray, et, can, sm, tq) {}
1099  friend class ASTContext;  // ASTContext creates these.
1100public:
1101  virtual void getAsStringInternal(std::string &InnerString,
1102                                   const PrintingPolicy &Policy) const;
1103
1104  static bool classof(const Type *T) {
1105    return T->getTypeClass() == IncompleteArray;
1106  }
1107  static bool classof(const IncompleteArrayType *) { return true; }
1108
1109  friend class StmtIteratorBase;
1110
1111  void Profile(llvm::FoldingSetNodeID &ID) {
1112    Profile(ID, getElementType(), getSizeModifier(), getIndexTypeQualifier());
1113  }
1114
1115  static void Profile(llvm::FoldingSetNodeID &ID, QualType ET,
1116                      ArraySizeModifier SizeMod, unsigned TypeQuals) {
1117    ID.AddPointer(ET.getAsOpaquePtr());
1118    ID.AddInteger(SizeMod);
1119    ID.AddInteger(TypeQuals);
1120  }
1121};
1122
1123/// VariableArrayType - This class represents C arrays with a specified size
1124/// which is not an integer-constant-expression.  For example, 'int s[x+foo()]'.
1125/// Since the size expression is an arbitrary expression, we store it as such.
1126///
1127/// Note: VariableArrayType's aren't uniqued (since the expressions aren't) and
1128/// should not be: two lexically equivalent variable array types could mean
1129/// different things, for example, these variables do not have the same type
1130/// dynamically:
1131///
1132/// void foo(int x) {
1133///   int Y[x];
1134///   ++x;
1135///   int Z[x];
1136/// }
1137///
1138class VariableArrayType : public ArrayType {
1139  /// SizeExpr - An assignment expression. VLA's are only permitted within
1140  /// a function block.
1141  Stmt *SizeExpr;
1142  /// Brackets - The left and right array brackets.
1143  SourceRange Brackets;
1144
1145  VariableArrayType(QualType et, QualType can, Expr *e,
1146                    ArraySizeModifier sm, unsigned tq,
1147                    SourceRange brackets)
1148    : ArrayType(VariableArray, et, can, sm, tq),
1149      SizeExpr((Stmt*) e), Brackets(brackets) {}
1150  friend class ASTContext;  // ASTContext creates these.
1151  virtual void Destroy(ASTContext& C);
1152
1153public:
1154  Expr *getSizeExpr() const {
1155    // We use C-style casts instead of cast<> here because we do not wish
1156    // to have a dependency of Type.h on Stmt.h/Expr.h.
1157    return (Expr*) SizeExpr;
1158  }
1159  SourceRange getBracketsRange() const { return Brackets; }
1160  SourceLocation getLBracketLoc() const { return Brackets.getBegin(); }
1161  SourceLocation getRBracketLoc() const { return Brackets.getEnd(); }
1162
1163  virtual void getAsStringInternal(std::string &InnerString,
1164                                   const PrintingPolicy &Policy) const;
1165
1166  static bool classof(const Type *T) {
1167    return T->getTypeClass() == VariableArray;
1168  }
1169  static bool classof(const VariableArrayType *) { return true; }
1170
1171  friend class StmtIteratorBase;
1172
1173  void Profile(llvm::FoldingSetNodeID &ID) {
1174    assert(0 && "Cannnot unique VariableArrayTypes.");
1175  }
1176};
1177
1178/// DependentSizedArrayType - This type represents an array type in
1179/// C++ whose size is a value-dependent expression. For example:
1180/// @code
1181/// template<typename T, int Size>
1182/// class array {
1183///   T data[Size];
1184/// };
1185/// @endcode
1186/// For these types, we won't actually know what the array bound is
1187/// until template instantiation occurs, at which point this will
1188/// become either a ConstantArrayType or a VariableArrayType.
1189class DependentSizedArrayType : public ArrayType {
1190  /// SizeExpr - An assignment expression that will instantiate to the
1191  /// size of the array.
1192  Stmt *SizeExpr;
1193  /// Brackets - The left and right array brackets.
1194  SourceRange Brackets;
1195
1196  DependentSizedArrayType(QualType et, QualType can, Expr *e,
1197			  ArraySizeModifier sm, unsigned tq,
1198                          SourceRange brackets)
1199    : ArrayType(DependentSizedArray, et, can, sm, tq),
1200      SizeExpr((Stmt*) e), Brackets(brackets) {}
1201  friend class ASTContext;  // ASTContext creates these.
1202  virtual void Destroy(ASTContext& C);
1203
1204public:
1205  Expr *getSizeExpr() const {
1206    // We use C-style casts instead of cast<> here because we do not wish
1207    // to have a dependency of Type.h on Stmt.h/Expr.h.
1208    return (Expr*) SizeExpr;
1209  }
1210  SourceRange getBracketsRange() const { return Brackets; }
1211  SourceLocation getLBracketLoc() const { return Brackets.getBegin(); }
1212  SourceLocation getRBracketLoc() const { return Brackets.getEnd(); }
1213
1214  virtual void getAsStringInternal(std::string &InnerString,
1215                                   const PrintingPolicy &Policy) const;
1216
1217  static bool classof(const Type *T) {
1218    return T->getTypeClass() == DependentSizedArray;
1219  }
1220  static bool classof(const DependentSizedArrayType *) { return true; }
1221
1222  friend class StmtIteratorBase;
1223
1224  void Profile(llvm::FoldingSetNodeID &ID) {
1225    assert(0 && "Cannnot unique DependentSizedArrayTypes.");
1226  }
1227};
1228
1229/// DependentSizedExtVectorType - This type represent an extended vector type
1230/// where either the type or size is dependent. For example:
1231/// @code
1232/// template<typename T, int Size>
1233/// class vector {
1234///   typedef T __attribute__((ext_vector_type(Size))) type;
1235/// }
1236/// @endcode
1237class DependentSizedExtVectorType : public Type {
1238  Expr *SizeExpr;
1239  /// ElementType - The element type of the array.
1240  QualType ElementType;
1241  SourceLocation loc;
1242
1243  DependentSizedExtVectorType(QualType ElementType, QualType can,
1244                              Expr *SizeExpr, SourceLocation loc)
1245    : Type (DependentSizedExtVector, can, true),
1246    SizeExpr(SizeExpr), ElementType(ElementType), loc(loc) {}
1247  friend class ASTContext;
1248  virtual void Destroy(ASTContext& C);
1249
1250public:
1251  const Expr *getSizeExpr() const { return SizeExpr; }
1252  QualType getElementType() const { return ElementType; }
1253  SourceLocation getAttributeLoc() const { return loc; }
1254
1255  virtual void getAsStringInternal(std::string &InnerString,
1256                                   const PrintingPolicy &Policy) const;
1257
1258  static bool classof(const Type *T) {
1259    return T->getTypeClass() == DependentSizedExtVector;
1260  }
1261  static bool classof(const DependentSizedExtVectorType *) { return true; }
1262};
1263
1264
1265/// VectorType - GCC generic vector type. This type is created using
1266/// __attribute__((vector_size(n)), where "n" specifies the vector size in
1267/// bytes. Since the constructor takes the number of vector elements, the
1268/// client is responsible for converting the size into the number of elements.
1269class VectorType : public Type, public llvm::FoldingSetNode {
1270protected:
1271  /// ElementType - The element type of the vector.
1272  QualType ElementType;
1273
1274  /// NumElements - The number of elements in the vector.
1275  unsigned NumElements;
1276
1277  VectorType(QualType vecType, unsigned nElements, QualType canonType) :
1278    Type(Vector, canonType, vecType->isDependentType()),
1279    ElementType(vecType), NumElements(nElements) {}
1280  VectorType(TypeClass tc, QualType vecType, unsigned nElements,
1281             QualType canonType)
1282    : Type(tc, canonType, vecType->isDependentType()), ElementType(vecType),
1283      NumElements(nElements) {}
1284  friend class ASTContext;  // ASTContext creates these.
1285public:
1286
1287  QualType getElementType() const { return ElementType; }
1288  unsigned getNumElements() const { return NumElements; }
1289
1290  virtual void getAsStringInternal(std::string &InnerString,
1291                                   const PrintingPolicy &Policy) const;
1292
1293  void Profile(llvm::FoldingSetNodeID &ID) {
1294    Profile(ID, getElementType(), getNumElements(), getTypeClass());
1295  }
1296  static void Profile(llvm::FoldingSetNodeID &ID, QualType ElementType,
1297                      unsigned NumElements, TypeClass TypeClass) {
1298    ID.AddPointer(ElementType.getAsOpaquePtr());
1299    ID.AddInteger(NumElements);
1300    ID.AddInteger(TypeClass);
1301  }
1302  static bool classof(const Type *T) {
1303    return T->getTypeClass() == Vector || T->getTypeClass() == ExtVector;
1304  }
1305  static bool classof(const VectorType *) { return true; }
1306};
1307
1308/// ExtVectorType - Extended vector type. This type is created using
1309/// __attribute__((ext_vector_type(n)), where "n" is the number of elements.
1310/// Unlike vector_size, ext_vector_type is only allowed on typedef's. This
1311/// class enables syntactic extensions, like Vector Components for accessing
1312/// points, colors, and textures (modeled after OpenGL Shading Language).
1313class ExtVectorType : public VectorType {
1314  ExtVectorType(QualType vecType, unsigned nElements, QualType canonType) :
1315    VectorType(ExtVector, vecType, nElements, canonType) {}
1316  friend class ASTContext;  // ASTContext creates these.
1317public:
1318  static int getPointAccessorIdx(char c) {
1319    switch (c) {
1320    default: return -1;
1321    case 'x': return 0;
1322    case 'y': return 1;
1323    case 'z': return 2;
1324    case 'w': return 3;
1325    }
1326  }
1327  static int getNumericAccessorIdx(char c) {
1328    switch (c) {
1329      default: return -1;
1330      case '0': return 0;
1331      case '1': return 1;
1332      case '2': return 2;
1333      case '3': return 3;
1334      case '4': return 4;
1335      case '5': return 5;
1336      case '6': return 6;
1337      case '7': return 7;
1338      case '8': return 8;
1339      case '9': return 9;
1340      case 'A':
1341      case 'a': return 10;
1342      case 'B':
1343      case 'b': return 11;
1344      case 'C':
1345      case 'c': return 12;
1346      case 'D':
1347      case 'd': return 13;
1348      case 'E':
1349      case 'e': return 14;
1350      case 'F':
1351      case 'f': return 15;
1352    }
1353  }
1354
1355  static int getAccessorIdx(char c) {
1356    if (int idx = getPointAccessorIdx(c)+1) return idx-1;
1357    return getNumericAccessorIdx(c);
1358  }
1359
1360  bool isAccessorWithinNumElements(char c) const {
1361    if (int idx = getAccessorIdx(c)+1)
1362      return unsigned(idx-1) < NumElements;
1363    return false;
1364  }
1365  virtual void getAsStringInternal(std::string &InnerString,
1366                                   const PrintingPolicy &Policy) const;
1367
1368  static bool classof(const Type *T) {
1369    return T->getTypeClass() == ExtVector;
1370  }
1371  static bool classof(const ExtVectorType *) { return true; }
1372};
1373
1374/// FunctionType - C99 6.7.5.3 - Function Declarators.  This is the common base
1375/// class of FunctionNoProtoType and FunctionProtoType.
1376///
1377class FunctionType : public Type {
1378  /// SubClassData - This field is owned by the subclass, put here to pack
1379  /// tightly with the ivars in Type.
1380  bool SubClassData : 1;
1381
1382  /// TypeQuals - Used only by FunctionProtoType, put here to pack with the
1383  /// other bitfields.
1384  /// The qualifiers are part of FunctionProtoType because...
1385  ///
1386  /// C++ 8.3.5p4: The return type, the parameter type list and the
1387  /// cv-qualifier-seq, [...], are part of the function type.
1388  ///
1389  unsigned TypeQuals : 3;
1390
1391  /// NoReturn - Indicates if the function type is attribute noreturn.
1392  unsigned NoReturn : 1;
1393
1394  // The type returned by the function.
1395  QualType ResultType;
1396protected:
1397  FunctionType(TypeClass tc, QualType res, bool SubclassInfo,
1398               unsigned typeQuals, QualType Canonical, bool Dependent,
1399               bool noReturn = false)
1400    : Type(tc, Canonical, Dependent),
1401      SubClassData(SubclassInfo), TypeQuals(typeQuals), NoReturn(noReturn),
1402      ResultType(res) {}
1403  bool getSubClassData() const { return SubClassData; }
1404  unsigned getTypeQuals() const { return TypeQuals; }
1405public:
1406
1407  QualType getResultType() const { return ResultType; }
1408  bool getNoReturnAttr() const { return NoReturn; }
1409
1410
1411  static bool classof(const Type *T) {
1412    return T->getTypeClass() == FunctionNoProto ||
1413           T->getTypeClass() == FunctionProto;
1414  }
1415  static bool classof(const FunctionType *) { return true; }
1416};
1417
1418/// FunctionNoProtoType - Represents a K&R-style 'int foo()' function, which has
1419/// no information available about its arguments.
1420class FunctionNoProtoType : public FunctionType, public llvm::FoldingSetNode {
1421  FunctionNoProtoType(QualType Result, QualType Canonical,
1422                      bool NoReturn = false)
1423    : FunctionType(FunctionNoProto, Result, false, 0, Canonical,
1424                   /*Dependent=*/false, NoReturn) {}
1425  friend class ASTContext;  // ASTContext creates these.
1426public:
1427  // No additional state past what FunctionType provides.
1428
1429  virtual void getAsStringInternal(std::string &InnerString,
1430                                   const PrintingPolicy &Policy) const;
1431
1432  void Profile(llvm::FoldingSetNodeID &ID) {
1433    Profile(ID, getResultType(), getNoReturnAttr());
1434  }
1435  static void Profile(llvm::FoldingSetNodeID &ID, QualType ResultType,
1436                      bool NoReturn) {
1437    ID.AddInteger(NoReturn);
1438    ID.AddPointer(ResultType.getAsOpaquePtr());
1439  }
1440
1441  static bool classof(const Type *T) {
1442    return T->getTypeClass() == FunctionNoProto;
1443  }
1444  static bool classof(const FunctionNoProtoType *) { return true; }
1445};
1446
1447/// FunctionProtoType - Represents a prototype with argument type info, e.g.
1448/// 'int foo(int)' or 'int foo(void)'.  'void' is represented as having no
1449/// arguments, not as having a single void argument. Such a type can have an
1450/// exception specification, but this specification is not part of the canonical
1451/// type.
1452class FunctionProtoType : public FunctionType, public llvm::FoldingSetNode {
1453  /// hasAnyDependentType - Determine whether there are any dependent
1454  /// types within the arguments passed in.
1455  static bool hasAnyDependentType(const QualType *ArgArray, unsigned numArgs) {
1456    for (unsigned Idx = 0; Idx < numArgs; ++Idx)
1457      if (ArgArray[Idx]->isDependentType())
1458    return true;
1459
1460    return false;
1461  }
1462
1463  FunctionProtoType(QualType Result, const QualType *ArgArray, unsigned numArgs,
1464                    bool isVariadic, unsigned typeQuals, bool hasExs,
1465                    bool hasAnyExs, const QualType *ExArray,
1466                    unsigned numExs, QualType Canonical, bool NoReturn)
1467    : FunctionType(FunctionProto, Result, isVariadic, typeQuals, Canonical,
1468                   (Result->isDependentType() ||
1469                    hasAnyDependentType(ArgArray, numArgs)), NoReturn),
1470      NumArgs(numArgs), NumExceptions(numExs), HasExceptionSpec(hasExs),
1471      AnyExceptionSpec(hasAnyExs) {
1472    // Fill in the trailing argument array.
1473    QualType *ArgInfo = reinterpret_cast<QualType*>(this+1);
1474    for (unsigned i = 0; i != numArgs; ++i)
1475      ArgInfo[i] = ArgArray[i];
1476    // Fill in the exception array.
1477    QualType *Ex = ArgInfo + numArgs;
1478    for (unsigned i = 0; i != numExs; ++i)
1479      Ex[i] = ExArray[i];
1480  }
1481
1482  /// NumArgs - The number of arguments this function has, not counting '...'.
1483  unsigned NumArgs : 20;
1484
1485  /// NumExceptions - The number of types in the exception spec, if any.
1486  unsigned NumExceptions : 10;
1487
1488  /// HasExceptionSpec - Whether this function has an exception spec at all.
1489  bool HasExceptionSpec : 1;
1490
1491  /// AnyExceptionSpec - Whether this function has a throw(...) spec.
1492  bool AnyExceptionSpec : 1;
1493
1494  /// ArgInfo - There is an variable size array after the class in memory that
1495  /// holds the argument types.
1496
1497  /// Exceptions - There is another variable size array after ArgInfo that
1498  /// holds the exception types.
1499
1500  friend class ASTContext;  // ASTContext creates these.
1501
1502public:
1503  unsigned getNumArgs() const { return NumArgs; }
1504  QualType getArgType(unsigned i) const {
1505    assert(i < NumArgs && "Invalid argument number!");
1506    return arg_type_begin()[i];
1507  }
1508
1509  bool hasExceptionSpec() const { return HasExceptionSpec; }
1510  bool hasAnyExceptionSpec() const { return AnyExceptionSpec; }
1511  unsigned getNumExceptions() const { return NumExceptions; }
1512  QualType getExceptionType(unsigned i) const {
1513    assert(i < NumExceptions && "Invalid exception number!");
1514    return exception_begin()[i];
1515  }
1516  bool hasEmptyExceptionSpec() const {
1517    return hasExceptionSpec() && !hasAnyExceptionSpec() &&
1518      getNumExceptions() == 0;
1519  }
1520
1521  bool isVariadic() const { return getSubClassData(); }
1522  unsigned getTypeQuals() const { return FunctionType::getTypeQuals(); }
1523
1524  typedef const QualType *arg_type_iterator;
1525  arg_type_iterator arg_type_begin() const {
1526    return reinterpret_cast<const QualType *>(this+1);
1527  }
1528  arg_type_iterator arg_type_end() const { return arg_type_begin()+NumArgs; }
1529
1530  typedef const QualType *exception_iterator;
1531  exception_iterator exception_begin() const {
1532    // exceptions begin where arguments end
1533    return arg_type_end();
1534  }
1535  exception_iterator exception_end() const {
1536    return exception_begin() + NumExceptions;
1537  }
1538
1539  virtual void getAsStringInternal(std::string &InnerString,
1540                                   const PrintingPolicy &Policy) const;
1541
1542  static bool classof(const Type *T) {
1543    return T->getTypeClass() == FunctionProto;
1544  }
1545  static bool classof(const FunctionProtoType *) { return true; }
1546
1547  void Profile(llvm::FoldingSetNodeID &ID);
1548  static void Profile(llvm::FoldingSetNodeID &ID, QualType Result,
1549                      arg_type_iterator ArgTys, unsigned NumArgs,
1550                      bool isVariadic, unsigned TypeQuals,
1551                      bool hasExceptionSpec, bool anyExceptionSpec,
1552                      unsigned NumExceptions, exception_iterator Exs,
1553                      bool NoReturn);
1554};
1555
1556
1557class TypedefType : public Type {
1558  TypedefDecl *Decl;
1559protected:
1560  TypedefType(TypeClass tc, TypedefDecl *D, QualType can)
1561    : Type(tc, can, can->isDependentType()), Decl(D) {
1562    assert(!isa<TypedefType>(can) && "Invalid canonical type");
1563  }
1564  friend class ASTContext;  // ASTContext creates these.
1565public:
1566
1567  TypedefDecl *getDecl() const { return Decl; }
1568
1569  /// LookThroughTypedefs - Return the ultimate type this typedef corresponds to
1570  /// potentially looking through *all* consecutive typedefs.  This returns the
1571  /// sum of the type qualifiers, so if you have:
1572  ///   typedef const int A;
1573  ///   typedef volatile A B;
1574  /// looking through the typedefs for B will give you "const volatile A".
1575  QualType LookThroughTypedefs() const;
1576
1577  virtual void getAsStringInternal(std::string &InnerString,
1578                                   const PrintingPolicy &Policy) const;
1579
1580  static bool classof(const Type *T) { return T->getTypeClass() == Typedef; }
1581  static bool classof(const TypedefType *) { return true; }
1582};
1583
1584/// TypeOfExprType (GCC extension).
1585class TypeOfExprType : public Type {
1586  Expr *TOExpr;
1587  TypeOfExprType(Expr *E, QualType can = QualType());
1588  friend class ASTContext;  // ASTContext creates these.
1589public:
1590  Expr *getUnderlyingExpr() const { return TOExpr; }
1591
1592  virtual void getAsStringInternal(std::string &InnerString,
1593                                   const PrintingPolicy &Policy) const;
1594
1595  static bool classof(const Type *T) { return T->getTypeClass() == TypeOfExpr; }
1596  static bool classof(const TypeOfExprType *) { return true; }
1597};
1598
1599/// TypeOfType (GCC extension).
1600class TypeOfType : public Type {
1601  QualType TOType;
1602  TypeOfType(QualType T, QualType can)
1603    : Type(TypeOf, can, T->isDependentType()), TOType(T) {
1604    assert(!isa<TypedefType>(can) && "Invalid canonical type");
1605  }
1606  friend class ASTContext;  // ASTContext creates these.
1607public:
1608  QualType getUnderlyingType() const { return TOType; }
1609
1610  virtual void getAsStringInternal(std::string &InnerString,
1611                                   const PrintingPolicy &Policy) const;
1612
1613  static bool classof(const Type *T) { return T->getTypeClass() == TypeOf; }
1614  static bool classof(const TypeOfType *) { return true; }
1615};
1616
1617/// DecltypeType (C++0x)
1618class DecltypeType : public Type {
1619  Expr *E;
1620
1621  // FIXME: We could get rid of UnderlyingType if we wanted to: We would have to
1622  // Move getDesugaredType to ASTContext so that it can call getDecltypeForExpr
1623  // from it.
1624  QualType UnderlyingType;
1625
1626  DecltypeType(Expr *E, QualType underlyingType, QualType can = QualType());
1627  friend class ASTContext;  // ASTContext creates these.
1628public:
1629  Expr *getUnderlyingExpr() const { return E; }
1630  QualType getUnderlyingType() const { return UnderlyingType; }
1631
1632  virtual void getAsStringInternal(std::string &InnerString,
1633                                   const PrintingPolicy &Policy) const;
1634
1635  static bool classof(const Type *T) { return T->getTypeClass() == Decltype; }
1636  static bool classof(const DecltypeType *) { return true; }
1637};
1638
1639class TagType : public Type {
1640  /// Stores the TagDecl associated with this type. The decl will
1641  /// point to the TagDecl that actually defines the entity (or is a
1642  /// definition in progress), if there is such a definition. The
1643  /// single-bit value will be non-zero when this tag is in the
1644  /// process of being defined.
1645  mutable llvm::PointerIntPair<TagDecl *, 1> decl;
1646  friend class ASTContext;
1647  friend class TagDecl;
1648
1649protected:
1650  TagType(TypeClass TC, TagDecl *D, QualType can);
1651
1652public:
1653  TagDecl *getDecl() const { return decl.getPointer(); }
1654
1655  /// @brief Determines whether this type is in the process of being
1656  /// defined.
1657  bool isBeingDefined() const { return decl.getInt(); }
1658  void setBeingDefined(bool Def) { decl.setInt(Def? 1 : 0); }
1659
1660  virtual void getAsStringInternal(std::string &InnerString,
1661                                   const PrintingPolicy &Policy) const;
1662
1663  static bool classof(const Type *T) {
1664    return T->getTypeClass() >= TagFirst && T->getTypeClass() <= TagLast;
1665  }
1666  static bool classof(const TagType *) { return true; }
1667  static bool classof(const RecordType *) { return true; }
1668  static bool classof(const EnumType *) { return true; }
1669};
1670
1671/// RecordType - This is a helper class that allows the use of isa/cast/dyncast
1672/// to detect TagType objects of structs/unions/classes.
1673class RecordType : public TagType {
1674protected:
1675  explicit RecordType(RecordDecl *D)
1676    : TagType(Record, reinterpret_cast<TagDecl*>(D), QualType()) { }
1677  explicit RecordType(TypeClass TC, RecordDecl *D)
1678    : TagType(TC, reinterpret_cast<TagDecl*>(D), QualType()) { }
1679  friend class ASTContext;   // ASTContext creates these.
1680public:
1681
1682  RecordDecl *getDecl() const {
1683    return reinterpret_cast<RecordDecl*>(TagType::getDecl());
1684  }
1685
1686  // FIXME: This predicate is a helper to QualType/Type. It needs to
1687  // recursively check all fields for const-ness. If any field is declared
1688  // const, it needs to return false.
1689  bool hasConstFields() const { return false; }
1690
1691  // FIXME: RecordType needs to check when it is created that all fields are in
1692  // the same address space, and return that.
1693  unsigned getAddressSpace() const { return 0; }
1694
1695  static bool classof(const TagType *T);
1696  static bool classof(const Type *T) {
1697    return isa<TagType>(T) && classof(cast<TagType>(T));
1698  }
1699  static bool classof(const RecordType *) { return true; }
1700};
1701
1702/// EnumType - This is a helper class that allows the use of isa/cast/dyncast
1703/// to detect TagType objects of enums.
1704class EnumType : public TagType {
1705  explicit EnumType(EnumDecl *D)
1706    : TagType(Enum, reinterpret_cast<TagDecl*>(D), QualType()) { }
1707  friend class ASTContext;   // ASTContext creates these.
1708public:
1709
1710  EnumDecl *getDecl() const {
1711    return reinterpret_cast<EnumDecl*>(TagType::getDecl());
1712  }
1713
1714  static bool classof(const TagType *T);
1715  static bool classof(const Type *T) {
1716    return isa<TagType>(T) && classof(cast<TagType>(T));
1717  }
1718  static bool classof(const EnumType *) { return true; }
1719};
1720
1721class TemplateTypeParmType : public Type, public llvm::FoldingSetNode {
1722  unsigned Depth : 15;
1723  unsigned Index : 16;
1724  unsigned ParameterPack : 1;
1725  IdentifierInfo *Name;
1726
1727  TemplateTypeParmType(unsigned D, unsigned I, bool PP, IdentifierInfo *N,
1728                       QualType Canon)
1729    : Type(TemplateTypeParm, Canon, /*Dependent=*/true),
1730      Depth(D), Index(I), ParameterPack(PP), Name(N) { }
1731
1732  TemplateTypeParmType(unsigned D, unsigned I, bool PP)
1733    : Type(TemplateTypeParm, QualType(this, 0), /*Dependent=*/true),
1734      Depth(D), Index(I), ParameterPack(PP), Name(0) { }
1735
1736  friend class ASTContext;  // ASTContext creates these
1737
1738public:
1739  unsigned getDepth() const { return Depth; }
1740  unsigned getIndex() const { return Index; }
1741  bool isParameterPack() const { return ParameterPack; }
1742  IdentifierInfo *getName() const { return Name; }
1743
1744  virtual void getAsStringInternal(std::string &InnerString,
1745                                   const PrintingPolicy &Policy) const;
1746
1747  void Profile(llvm::FoldingSetNodeID &ID) {
1748    Profile(ID, Depth, Index, ParameterPack, Name);
1749  }
1750
1751  static void Profile(llvm::FoldingSetNodeID &ID, unsigned Depth,
1752                      unsigned Index, bool ParameterPack,
1753                      IdentifierInfo *Name) {
1754    ID.AddInteger(Depth);
1755    ID.AddInteger(Index);
1756    ID.AddBoolean(ParameterPack);
1757    ID.AddPointer(Name);
1758  }
1759
1760  static bool classof(const Type *T) {
1761    return T->getTypeClass() == TemplateTypeParm;
1762  }
1763  static bool classof(const TemplateTypeParmType *T) { return true; }
1764};
1765
1766/// \brief Represents the type of a template specialization as written
1767/// in the source code.
1768///
1769/// Template specialization types represent the syntactic form of a
1770/// template-id that refers to a type, e.g., @c vector<int>. Some
1771/// template specialization types are syntactic sugar, whose canonical
1772/// type will point to some other type node that represents the
1773/// instantiation or class template specialization. For example, a
1774/// class template specialization type of @c vector<int> will refer to
1775/// a tag type for the instantiation
1776/// @c std::vector<int, std::allocator<int>>.
1777///
1778/// Other template specialization types, for which the template name
1779/// is dependent, may be canonical types. These types are always
1780/// dependent.
1781class TemplateSpecializationType
1782  : public Type, public llvm::FoldingSetNode {
1783
1784  /// \brief The name of the template being specialized.
1785  TemplateName Template;
1786
1787  /// \brief - The number of template arguments named in this class
1788  /// template specialization.
1789  unsigned NumArgs;
1790
1791  TemplateSpecializationType(TemplateName T,
1792                             const TemplateArgument *Args,
1793                             unsigned NumArgs, QualType Canon);
1794
1795  virtual void Destroy(ASTContext& C);
1796
1797  friend class ASTContext;  // ASTContext creates these
1798
1799public:
1800  /// \brief Determine whether any of the given template arguments are
1801  /// dependent.
1802  static bool anyDependentTemplateArguments(const TemplateArgument *Args,
1803                                            unsigned NumArgs);
1804
1805  /// \brief Print a template argument list, including the '<' and '>'
1806  /// enclosing the template arguments.
1807  static std::string PrintTemplateArgumentList(const TemplateArgument *Args,
1808                                               unsigned NumArgs,
1809                                               const PrintingPolicy &Policy);
1810
1811  typedef const TemplateArgument * iterator;
1812
1813  iterator begin() const { return getArgs(); }
1814  iterator end() const;
1815
1816  /// \brief Retrieve the name of the template that we are specializing.
1817  TemplateName getTemplateName() const { return Template; }
1818
1819  /// \brief Retrieve the template arguments.
1820  const TemplateArgument *getArgs() const {
1821    return reinterpret_cast<const TemplateArgument *>(this + 1);
1822  }
1823
1824  /// \brief Retrieve the number of template arguments.
1825  unsigned getNumArgs() const { return NumArgs; }
1826
1827  /// \brief Retrieve a specific template argument as a type.
1828  /// \precondition @c isArgType(Arg)
1829  const TemplateArgument &getArg(unsigned Idx) const;
1830
1831  virtual void getAsStringInternal(std::string &InnerString,
1832                                   const PrintingPolicy &Policy) const;
1833
1834  void Profile(llvm::FoldingSetNodeID &ID) {
1835    Profile(ID, Template, getArgs(), NumArgs);
1836  }
1837
1838  static void Profile(llvm::FoldingSetNodeID &ID, TemplateName T,
1839                      const TemplateArgument *Args, unsigned NumArgs);
1840
1841  static bool classof(const Type *T) {
1842    return T->getTypeClass() == TemplateSpecialization;
1843  }
1844  static bool classof(const TemplateSpecializationType *T) { return true; }
1845};
1846
1847/// \brief Represents a type that was referred to via a qualified
1848/// name, e.g., N::M::type.
1849///
1850/// This type is used to keep track of a type name as written in the
1851/// source code, including any nested-name-specifiers. The type itself
1852/// is always "sugar", used to express what was written in the source
1853/// code but containing no additional semantic information.
1854class QualifiedNameType : public Type, public llvm::FoldingSetNode {
1855  /// \brief The nested name specifier containing the qualifier.
1856  NestedNameSpecifier *NNS;
1857
1858  /// \brief The type that this qualified name refers to.
1859  QualType NamedType;
1860
1861  QualifiedNameType(NestedNameSpecifier *NNS, QualType NamedType,
1862                    QualType CanonType)
1863    : Type(QualifiedName, CanonType, NamedType->isDependentType()),
1864      NNS(NNS), NamedType(NamedType) { }
1865
1866  friend class ASTContext;  // ASTContext creates these
1867
1868public:
1869  /// \brief Retrieve the qualification on this type.
1870  NestedNameSpecifier *getQualifier() const { return NNS; }
1871
1872  /// \brief Retrieve the type named by the qualified-id.
1873  QualType getNamedType() const { return NamedType; }
1874
1875  virtual void getAsStringInternal(std::string &InnerString,
1876                                   const PrintingPolicy &Policy) const;
1877
1878  void Profile(llvm::FoldingSetNodeID &ID) {
1879    Profile(ID, NNS, NamedType);
1880  }
1881
1882  static void Profile(llvm::FoldingSetNodeID &ID, NestedNameSpecifier *NNS,
1883                      QualType NamedType) {
1884    ID.AddPointer(NNS);
1885    NamedType.Profile(ID);
1886  }
1887
1888  static bool classof(const Type *T) {
1889    return T->getTypeClass() == QualifiedName;
1890  }
1891  static bool classof(const QualifiedNameType *T) { return true; }
1892};
1893
1894/// \brief Represents a 'typename' specifier that names a type within
1895/// a dependent type, e.g., "typename T::type".
1896///
1897/// TypenameType has a very similar structure to QualifiedNameType,
1898/// which also involves a nested-name-specifier following by a type,
1899/// and (FIXME!) both can even be prefixed by the 'typename'
1900/// keyword. However, the two types serve very different roles:
1901/// QualifiedNameType is a non-semantic type that serves only as sugar
1902/// to show how a particular type was written in the source
1903/// code. TypenameType, on the other hand, only occurs when the
1904/// nested-name-specifier is dependent, such that we cannot resolve
1905/// the actual type until after instantiation.
1906class TypenameType : public Type, public llvm::FoldingSetNode {
1907  /// \brief The nested name specifier containing the qualifier.
1908  NestedNameSpecifier *NNS;
1909
1910  typedef llvm::PointerUnion<const IdentifierInfo *,
1911                             const TemplateSpecializationType *> NameType;
1912
1913  /// \brief The type that this typename specifier refers to.
1914  NameType Name;
1915
1916  TypenameType(NestedNameSpecifier *NNS, const IdentifierInfo *Name,
1917               QualType CanonType)
1918    : Type(Typename, CanonType, true), NNS(NNS), Name(Name) {
1919    assert(NNS->isDependent() &&
1920           "TypenameType requires a dependent nested-name-specifier");
1921  }
1922
1923  TypenameType(NestedNameSpecifier *NNS, const TemplateSpecializationType *Ty,
1924               QualType CanonType)
1925    : Type(Typename, CanonType, true), NNS(NNS), Name(Ty) {
1926    assert(NNS->isDependent() &&
1927           "TypenameType requires a dependent nested-name-specifier");
1928  }
1929
1930  friend class ASTContext;  // ASTContext creates these
1931
1932public:
1933  /// \brief Retrieve the qualification on this type.
1934  NestedNameSpecifier *getQualifier() const { return NNS; }
1935
1936  /// \brief Retrieve the type named by the typename specifier as an
1937  /// identifier.
1938  ///
1939  /// This routine will return a non-NULL identifier pointer when the
1940  /// form of the original typename was terminated by an identifier,
1941  /// e.g., "typename T::type".
1942  const IdentifierInfo *getIdentifier() const {
1943    return Name.dyn_cast<const IdentifierInfo *>();
1944  }
1945
1946  /// \brief Retrieve the type named by the typename specifier as a
1947  /// type specialization.
1948  const TemplateSpecializationType *getTemplateId() const {
1949    return Name.dyn_cast<const TemplateSpecializationType *>();
1950  }
1951
1952  virtual void getAsStringInternal(std::string &InnerString,
1953                                   const PrintingPolicy &Policy) const;
1954
1955  void Profile(llvm::FoldingSetNodeID &ID) {
1956    Profile(ID, NNS, Name);
1957  }
1958
1959  static void Profile(llvm::FoldingSetNodeID &ID, NestedNameSpecifier *NNS,
1960                      NameType Name) {
1961    ID.AddPointer(NNS);
1962    ID.AddPointer(Name.getOpaqueValue());
1963  }
1964
1965  static bool classof(const Type *T) {
1966    return T->getTypeClass() == Typename;
1967  }
1968  static bool classof(const TypenameType *T) { return true; }
1969};
1970
1971/// ObjCInterfaceType - Interfaces are the core concept in Objective-C for
1972/// object oriented design.  They basically correspond to C++ classes.  There
1973/// are two kinds of interface types, normal interfaces like "NSString" and
1974/// qualified interfaces, which are qualified with a protocol list like
1975/// "NSString<NSCopyable, NSAmazing>".
1976class ObjCInterfaceType : public Type, public llvm::FoldingSetNode {
1977  ObjCInterfaceDecl *Decl;
1978
1979  // List of protocols for this protocol conforming object type
1980  // List is sorted on protocol name. No protocol is enterred more than once.
1981  llvm::SmallVector<ObjCProtocolDecl*, 4> Protocols;
1982
1983  ObjCInterfaceType(ObjCInterfaceDecl *D,
1984                    ObjCProtocolDecl **Protos, unsigned NumP) :
1985    Type(ObjCInterface, QualType(), /*Dependent=*/false),
1986    Decl(D), Protocols(Protos, Protos+NumP) { }
1987  friend class ASTContext;  // ASTContext creates these.
1988public:
1989  ObjCInterfaceDecl *getDecl() const { return Decl; }
1990
1991  /// getNumProtocols - Return the number of qualifying protocols in this
1992  /// interface type, or 0 if there are none.
1993  unsigned getNumProtocols() const { return Protocols.size(); }
1994
1995  /// qual_iterator and friends: this provides access to the (potentially empty)
1996  /// list of protocols qualifying this interface.
1997  typedef llvm::SmallVector<ObjCProtocolDecl*, 8>::const_iterator qual_iterator;
1998  qual_iterator qual_begin() const { return Protocols.begin(); }
1999  qual_iterator qual_end() const   { return Protocols.end(); }
2000  bool qual_empty() const { return Protocols.size() == 0; }
2001
2002  virtual void getAsStringInternal(std::string &InnerString,
2003                                   const PrintingPolicy &Policy) const;
2004
2005  void Profile(llvm::FoldingSetNodeID &ID);
2006  static void Profile(llvm::FoldingSetNodeID &ID,
2007                      const ObjCInterfaceDecl *Decl,
2008                      ObjCProtocolDecl **protocols, unsigned NumProtocols);
2009
2010  static bool classof(const Type *T) {
2011    return T->getTypeClass() == ObjCInterface;
2012  }
2013  static bool classof(const ObjCInterfaceType *) { return true; }
2014};
2015
2016/// ObjCObjectPointerType - Used to represent 'id', 'Interface *', 'id <p>',
2017/// and 'Interface <p> *'.
2018///
2019/// Duplicate protocols are removed and protocol list is canonicalized to be in
2020/// alphabetical order.
2021class ObjCObjectPointerType : public Type, public llvm::FoldingSetNode {
2022  QualType PointeeType; // A builtin or interface type.
2023
2024  // List of protocols for this protocol conforming object type
2025  // List is sorted on protocol name. No protocol is entered more than once.
2026  llvm::SmallVector<ObjCProtocolDecl*, 8> Protocols;
2027
2028  ObjCObjectPointerType(QualType T, ObjCProtocolDecl **Protos, unsigned NumP) :
2029    Type(ObjCObjectPointer, QualType(), /*Dependent=*/false),
2030    PointeeType(T), Protocols(Protos, Protos+NumP) { }
2031  friend class ASTContext;  // ASTContext creates these.
2032
2033public:
2034  // Get the pointee type. Pointee will either be:
2035  // - a built-in type (for 'id' and 'Class').
2036  // - an interface type (for user-defined types).
2037  // - a TypedefType whose canonical type is an interface (as in 'T' below).
2038  //   For example: typedef NSObject T; T *var;
2039  QualType getPointeeType() const { return PointeeType; }
2040
2041  const ObjCInterfaceType *getInterfaceType() const {
2042    return PointeeType->getAsObjCInterfaceType();
2043  }
2044  /// getInterfaceDecl - returns an interface decl for user-defined types.
2045  ObjCInterfaceDecl *getInterfaceDecl() const {
2046    return getInterfaceType() ? getInterfaceType()->getDecl() : 0;
2047  }
2048  /// isObjCIdType - true for "id".
2049  bool isObjCIdType() const {
2050    return getPointeeType()->isSpecificBuiltinType(BuiltinType::ObjCId) &&
2051           !Protocols.size();
2052  }
2053  /// isObjCClassType - true for "Class".
2054  bool isObjCClassType() const {
2055    return getPointeeType()->isSpecificBuiltinType(BuiltinType::ObjCClass) &&
2056           !Protocols.size();
2057  }
2058  /// isObjCQualifiedIdType - true for "id <p>".
2059  bool isObjCQualifiedIdType() const {
2060    return getPointeeType()->isSpecificBuiltinType(BuiltinType::ObjCId) &&
2061           Protocols.size();
2062  }
2063  /// isObjCQualifiedClassType - true for "Class <p>".
2064  bool isObjCQualifiedClassType() const {
2065    return getPointeeType()->isSpecificBuiltinType(BuiltinType::ObjCClass) &&
2066           Protocols.size();
2067  }
2068  /// qual_iterator and friends: this provides access to the (potentially empty)
2069  /// list of protocols qualifying this interface.
2070  typedef llvm::SmallVector<ObjCProtocolDecl*, 8>::const_iterator qual_iterator;
2071
2072  qual_iterator qual_begin() const { return Protocols.begin(); }
2073  qual_iterator qual_end() const   { return Protocols.end(); }
2074  bool qual_empty() const { return Protocols.size() == 0; }
2075
2076  /// getNumProtocols - Return the number of qualifying protocols in this
2077  /// interface type, or 0 if there are none.
2078  unsigned getNumProtocols() const { return Protocols.size(); }
2079
2080  void Profile(llvm::FoldingSetNodeID &ID);
2081  static void Profile(llvm::FoldingSetNodeID &ID, QualType T,
2082                      ObjCProtocolDecl **protocols, unsigned NumProtocols);
2083  virtual void getAsStringInternal(std::string &InnerString,
2084                                   const PrintingPolicy &Policy) const;
2085  static bool classof(const Type *T) {
2086    return T->getTypeClass() == ObjCObjectPointer;
2087  }
2088  static bool classof(const ObjCObjectPointerType *) { return true; }
2089};
2090
2091// Inline function definitions.
2092
2093/// getUnqualifiedType - Return the type without any qualifiers.
2094inline QualType QualType::getUnqualifiedType() const {
2095  Type *TP = getTypePtr();
2096  if (const ExtQualType *EXTQT = dyn_cast<ExtQualType>(TP))
2097    TP = EXTQT->getBaseType();
2098  return QualType(TP, 0);
2099}
2100
2101/// getAddressSpace - Return the address space of this type.
2102inline unsigned QualType::getAddressSpace() const {
2103  QualType CT = getTypePtr()->getCanonicalTypeInternal();
2104  if (const ArrayType *AT = dyn_cast<ArrayType>(CT))
2105    return AT->getElementType().getAddressSpace();
2106  if (const RecordType *RT = dyn_cast<RecordType>(CT))
2107    return RT->getAddressSpace();
2108  if (const ExtQualType *EXTQT = dyn_cast<ExtQualType>(CT))
2109    return EXTQT->getAddressSpace();
2110  return 0;
2111}
2112
2113/// getObjCGCAttr - Return the gc attribute of this type.
2114inline QualType::GCAttrTypes QualType::getObjCGCAttr() const {
2115  QualType CT = getTypePtr()->getCanonicalTypeInternal();
2116  if (const ArrayType *AT = dyn_cast<ArrayType>(CT))
2117      return AT->getElementType().getObjCGCAttr();
2118  if (const ExtQualType *EXTQT = dyn_cast<ExtQualType>(CT))
2119    return EXTQT->getObjCGCAttr();
2120  if (const ObjCObjectPointerType *PT = CT->getAsObjCObjectPointerType())
2121    return PT->getPointeeType().getObjCGCAttr();
2122  return GCNone;
2123}
2124
2125  /// getNoReturnAttr - Returns true if the type has the noreturn attribute,
2126  /// false otherwise.
2127inline bool QualType::getNoReturnAttr() const {
2128  QualType CT = getTypePtr()->getCanonicalTypeInternal();
2129  if (const PointerType *PT = getTypePtr()->getAsPointerType()) {
2130    if (const FunctionType *FT = PT->getPointeeType()->getAsFunctionType())
2131      return FT->getNoReturnAttr();
2132  } else if (const FunctionType *FT = getTypePtr()->getAsFunctionType())
2133    return FT->getNoReturnAttr();
2134
2135  return false;
2136}
2137
2138/// isMoreQualifiedThan - Determine whether this type is more
2139/// qualified than the Other type. For example, "const volatile int"
2140/// is more qualified than "const int", "volatile int", and
2141/// "int". However, it is not more qualified than "const volatile
2142/// int".
2143inline bool QualType::isMoreQualifiedThan(QualType Other) const {
2144  unsigned MyQuals = this->getCVRQualifiers();
2145  unsigned OtherQuals = Other.getCVRQualifiers();
2146  if (getAddressSpace() != Other.getAddressSpace())
2147    return false;
2148  return MyQuals != OtherQuals && (MyQuals | OtherQuals) == MyQuals;
2149}
2150
2151/// isAtLeastAsQualifiedAs - Determine whether this type is at last
2152/// as qualified as the Other type. For example, "const volatile
2153/// int" is at least as qualified as "const int", "volatile int",
2154/// "int", and "const volatile int".
2155inline bool QualType::isAtLeastAsQualifiedAs(QualType Other) const {
2156  unsigned MyQuals = this->getCVRQualifiers();
2157  unsigned OtherQuals = Other.getCVRQualifiers();
2158  if (getAddressSpace() != Other.getAddressSpace())
2159    return false;
2160  return (MyQuals | OtherQuals) == MyQuals;
2161}
2162
2163/// getNonReferenceType - If Type is a reference type (e.g., const
2164/// int&), returns the type that the reference refers to ("const
2165/// int"). Otherwise, returns the type itself. This routine is used
2166/// throughout Sema to implement C++ 5p6:
2167///
2168///   If an expression initially has the type "reference to T" (8.3.2,
2169///   8.5.3), the type is adjusted to "T" prior to any further
2170///   analysis, the expression designates the object or function
2171///   denoted by the reference, and the expression is an lvalue.
2172inline QualType QualType::getNonReferenceType() const {
2173  if (const ReferenceType *RefType = (*this)->getAsReferenceType())
2174    return RefType->getPointeeType();
2175  else
2176    return *this;
2177}
2178
2179inline const TypedefType* Type::getAsTypedefType() const {
2180  return dyn_cast<TypedefType>(this);
2181}
2182inline const ObjCInterfaceType *Type::getAsPointerToObjCInterfaceType() const {
2183  if (const PointerType *PT = getAsPointerType())
2184    return PT->getPointeeType()->getAsObjCInterfaceType();
2185  return 0;
2186}
2187
2188// NOTE: All of these methods use "getUnqualifiedType" to strip off address
2189// space qualifiers if present.
2190inline bool Type::isFunctionType() const {
2191  return isa<FunctionType>(CanonicalType.getUnqualifiedType());
2192}
2193inline bool Type::isPointerType() const {
2194  return isa<PointerType>(CanonicalType.getUnqualifiedType());
2195}
2196inline bool Type::isAnyPointerType() const {
2197  return isPointerType() || isObjCObjectPointerType();
2198}
2199inline bool Type::isBlockPointerType() const {
2200  return isa<BlockPointerType>(CanonicalType.getUnqualifiedType());
2201}
2202inline bool Type::isReferenceType() const {
2203  return isa<ReferenceType>(CanonicalType.getUnqualifiedType());
2204}
2205inline bool Type::isLValueReferenceType() const {
2206  return isa<LValueReferenceType>(CanonicalType.getUnqualifiedType());
2207}
2208inline bool Type::isRValueReferenceType() const {
2209  return isa<RValueReferenceType>(CanonicalType.getUnqualifiedType());
2210}
2211inline bool Type::isFunctionPointerType() const {
2212  if (const PointerType* T = getAsPointerType())
2213    return T->getPointeeType()->isFunctionType();
2214  else
2215    return false;
2216}
2217inline bool Type::isMemberPointerType() const {
2218  return isa<MemberPointerType>(CanonicalType.getUnqualifiedType());
2219}
2220inline bool Type::isMemberFunctionPointerType() const {
2221  if (const MemberPointerType* T = getAsMemberPointerType())
2222    return T->getPointeeType()->isFunctionType();
2223  else
2224    return false;
2225}
2226inline bool Type::isArrayType() const {
2227  return isa<ArrayType>(CanonicalType.getUnqualifiedType());
2228}
2229inline bool Type::isConstantArrayType() const {
2230  return isa<ConstantArrayType>(CanonicalType.getUnqualifiedType());
2231}
2232inline bool Type::isIncompleteArrayType() const {
2233  return isa<IncompleteArrayType>(CanonicalType.getUnqualifiedType());
2234}
2235inline bool Type::isVariableArrayType() const {
2236  return isa<VariableArrayType>(CanonicalType.getUnqualifiedType());
2237}
2238inline bool Type::isDependentSizedArrayType() const {
2239  return isa<DependentSizedArrayType>(CanonicalType.getUnqualifiedType());
2240}
2241inline bool Type::isRecordType() const {
2242  return isa<RecordType>(CanonicalType.getUnqualifiedType());
2243}
2244inline bool Type::isAnyComplexType() const {
2245  return isa<ComplexType>(CanonicalType.getUnqualifiedType());
2246}
2247inline bool Type::isVectorType() const {
2248  return isa<VectorType>(CanonicalType.getUnqualifiedType());
2249}
2250inline bool Type::isExtVectorType() const {
2251  return isa<ExtVectorType>(CanonicalType.getUnqualifiedType());
2252}
2253inline bool Type::isObjCObjectPointerType() const {
2254  return isa<ObjCObjectPointerType>(CanonicalType.getUnqualifiedType());
2255}
2256inline bool Type::isObjCInterfaceType() const {
2257  return isa<ObjCInterfaceType>(CanonicalType.getUnqualifiedType());
2258}
2259inline bool Type::isObjCQualifiedIdType() const {
2260  if (const ObjCObjectPointerType *OPT = getAsObjCObjectPointerType())
2261    return OPT->isObjCQualifiedIdType();
2262  return false;
2263}
2264inline bool Type::isObjCQualifiedClassType() const {
2265  if (const ObjCObjectPointerType *OPT = getAsObjCObjectPointerType())
2266    return OPT->isObjCQualifiedClassType();
2267  return false;
2268}
2269inline bool Type::isObjCIdType() const {
2270  if (const ObjCObjectPointerType *OPT = getAsObjCObjectPointerType())
2271    return OPT->isObjCIdType();
2272  return false;
2273}
2274inline bool Type::isObjCClassType() const {
2275  if (const ObjCObjectPointerType *OPT = getAsObjCObjectPointerType())
2276    return OPT->isObjCClassType();
2277  return false;
2278}
2279inline bool Type::isObjCBuiltinType() const {
2280  return isObjCIdType() || isObjCClassType();
2281}
2282inline bool Type::isTemplateTypeParmType() const {
2283  return isa<TemplateTypeParmType>(CanonicalType.getUnqualifiedType());
2284}
2285
2286inline bool Type::isSpecificBuiltinType(unsigned K) const {
2287  if (const BuiltinType *BT = getAsBuiltinType())
2288    if (BT->getKind() == (BuiltinType::Kind) K)
2289      return true;
2290  return false;
2291}
2292
2293/// \brief Determines whether this is a type for which one can define
2294/// an overloaded operator.
2295inline bool Type::isOverloadableType() const {
2296  return isDependentType() || isRecordType() || isEnumeralType();
2297}
2298
2299inline bool Type::hasPointerRepresentation() const {
2300  return (isPointerType() || isReferenceType() || isBlockPointerType() ||
2301          isObjCInterfaceType() || isObjCObjectPointerType() ||
2302          isObjCQualifiedInterfaceType() || isNullPtrType());
2303}
2304
2305inline bool Type::hasObjCPointerRepresentation() const {
2306  return (isObjCInterfaceType() || isObjCObjectPointerType() ||
2307          isObjCQualifiedInterfaceType());
2308}
2309
2310/// Insertion operator for diagnostics.  This allows sending QualType's into a
2311/// diagnostic with <<.
2312inline const DiagnosticBuilder &operator<<(const DiagnosticBuilder &DB,
2313                                           QualType T) {
2314  DB.AddTaggedVal(reinterpret_cast<intptr_t>(T.getAsOpaquePtr()),
2315                  Diagnostic::ak_qualtype);
2316  return DB;
2317}
2318
2319/// Member-template getAs<specific type>'.
2320template <typename T> const T *Type::getAs() const {
2321  // If this is directly a T type, return it.
2322  if (const T *Ty = dyn_cast<T>(this))
2323    return Ty;
2324
2325  // If the canonical form of this type isn't the right kind, reject it.
2326  if (!isa<T>(CanonicalType)) {
2327    // Look through type qualifiers
2328    if (isa<T>(CanonicalType.getUnqualifiedType()))
2329      return CanonicalType.getUnqualifiedType()->getAs<T>();
2330    return 0;
2331  }
2332
2333  // If this is a typedef for a pointer type, strip the typedef off without
2334  // losing all typedef information.
2335  return cast<T>(getDesugaredType());
2336}
2337
2338}  // end namespace clang
2339
2340#endif
2341