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