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