]> CyberLeo.Net >> Repos - FreeBSD/releng/9.0.git/blob - contrib/llvm/tools/clang/include/clang/AST/Type.h
Copy stable/9 to releng/9.0 as part of the FreeBSD 9.0-RELEASE release
[FreeBSD/releng/9.0.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/ExceptionSpecificationType.h"
19 #include "clang/Basic/IdentifierTable.h"
20 #include "clang/Basic/Linkage.h"
21 #include "clang/Basic/PartialDiagnostic.h"
22 #include "clang/Basic/Visibility.h"
23 #include "clang/AST/NestedNameSpecifier.h"
24 #include "clang/AST/TemplateName.h"
25 #include "llvm/Support/type_traits.h"
26 #include "llvm/Support/ErrorHandling.h"
27 #include "llvm/ADT/APSInt.h"
28 #include "llvm/ADT/FoldingSet.h"
29 #include "llvm/ADT/Optional.h"
30 #include "llvm/ADT/PointerIntPair.h"
31 #include "llvm/ADT/PointerUnion.h"
32 #include "clang/Basic/LLVM.h"
33
34 namespace clang {
35   enum {
36     TypeAlignmentInBits = 4,
37     TypeAlignment = 1 << TypeAlignmentInBits
38   };
39   class Type;
40   class ExtQuals;
41   class QualType;
42 }
43
44 namespace llvm {
45   template <typename T>
46   class PointerLikeTypeTraits;
47   template<>
48   class PointerLikeTypeTraits< ::clang::Type*> {
49   public:
50     static inline void *getAsVoidPointer(::clang::Type *P) { return P; }
51     static inline ::clang::Type *getFromVoidPointer(void *P) {
52       return static_cast< ::clang::Type*>(P);
53     }
54     enum { NumLowBitsAvailable = clang::TypeAlignmentInBits };
55   };
56   template<>
57   class PointerLikeTypeTraits< ::clang::ExtQuals*> {
58   public:
59     static inline void *getAsVoidPointer(::clang::ExtQuals *P) { return P; }
60     static inline ::clang::ExtQuals *getFromVoidPointer(void *P) {
61       return static_cast< ::clang::ExtQuals*>(P);
62     }
63     enum { NumLowBitsAvailable = clang::TypeAlignmentInBits };
64   };
65
66   template <>
67   struct isPodLike<clang::QualType> { static const bool value = true; };
68 }
69
70 namespace clang {
71   class ASTContext;
72   class TypedefNameDecl;
73   class TemplateDecl;
74   class TemplateTypeParmDecl;
75   class NonTypeTemplateParmDecl;
76   class TemplateTemplateParmDecl;
77   class TagDecl;
78   class RecordDecl;
79   class CXXRecordDecl;
80   class EnumDecl;
81   class FieldDecl;
82   class ObjCInterfaceDecl;
83   class ObjCProtocolDecl;
84   class ObjCMethodDecl;
85   class UnresolvedUsingTypenameDecl;
86   class Expr;
87   class Stmt;
88   class SourceLocation;
89   class StmtIteratorBase;
90   class TemplateArgument;
91   class TemplateArgumentLoc;
92   class TemplateArgumentListInfo;
93   class ElaboratedType;
94   class ExtQuals;
95   class ExtQualsTypeCommonBase;
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 ObjCLifetime {
126     /// There is no lifetime qualification on this type.
127     OCL_None,
128
129     /// This object can be modified without requiring retains or
130     /// releases.
131     OCL_ExplicitNone,
132
133     /// Assigning into this object requires the old value to be
134     /// released and the new value to be retained.  The timing of the
135     /// release of the old value is inexact: it may be moved to
136     /// immediately after the last known point where the value is
137     /// live.
138     OCL_Strong,
139
140     /// Reading or writing from this object requires a barrier call.
141     OCL_Weak,
142
143     /// Assigning into this object requires a lifetime extension.
144     OCL_Autoreleasing
145   };
146
147   enum {
148     /// The maximum supported address space number.
149     /// 24 bits should be enough for anyone.
150     MaxAddressSpace = 0xffffffu,
151
152     /// The width of the "fast" qualifier mask.
153     FastWidth = 3,
154
155     /// The fast qualifier mask.
156     FastMask = (1 << FastWidth) - 1
157   };
158
159   Qualifiers() : Mask(0) {}
160
161   static Qualifiers fromFastMask(unsigned Mask) {
162     Qualifiers Qs;
163     Qs.addFastQualifiers(Mask);
164     return Qs;
165   }
166
167   static Qualifiers fromCVRMask(unsigned CVR) {
168     Qualifiers Qs;
169     Qs.addCVRQualifiers(CVR);
170     return Qs;
171   }
172
173   // Deserialize qualifiers from an opaque representation.
174   static Qualifiers fromOpaqueValue(unsigned opaque) {
175     Qualifiers Qs;
176     Qs.Mask = opaque;
177     return Qs;
178   }
179
180   // Serialize these qualifiers into an opaque representation.
181   unsigned getAsOpaqueValue() const {
182     return Mask;
183   }
184
185   bool hasConst() const { return Mask & Const; }
186   void setConst(bool flag) {
187     Mask = (Mask & ~Const) | (flag ? Const : 0);
188   }
189   void removeConst() { Mask &= ~Const; }
190   void addConst() { Mask |= Const; }
191
192   bool hasVolatile() const { return Mask & Volatile; }
193   void setVolatile(bool flag) {
194     Mask = (Mask & ~Volatile) | (flag ? Volatile : 0);
195   }
196   void removeVolatile() { Mask &= ~Volatile; }
197   void addVolatile() { Mask |= Volatile; }
198
199   bool hasRestrict() const { return Mask & Restrict; }
200   void setRestrict(bool flag) {
201     Mask = (Mask & ~Restrict) | (flag ? Restrict : 0);
202   }
203   void removeRestrict() { Mask &= ~Restrict; }
204   void addRestrict() { Mask |= Restrict; }
205
206   bool hasCVRQualifiers() const { return getCVRQualifiers(); }
207   unsigned getCVRQualifiers() const { return Mask & CVRMask; }
208   void setCVRQualifiers(unsigned mask) {
209     assert(!(mask & ~CVRMask) && "bitmask contains non-CVR bits");
210     Mask = (Mask & ~CVRMask) | mask;
211   }
212   void removeCVRQualifiers(unsigned mask) {
213     assert(!(mask & ~CVRMask) && "bitmask contains non-CVR bits");
214     Mask &= ~mask;
215   }
216   void removeCVRQualifiers() {
217     removeCVRQualifiers(CVRMask);
218   }
219   void addCVRQualifiers(unsigned mask) {
220     assert(!(mask & ~CVRMask) && "bitmask contains non-CVR bits");
221     Mask |= mask;
222   }
223
224   bool hasObjCGCAttr() const { return Mask & GCAttrMask; }
225   GC getObjCGCAttr() const { return GC((Mask & GCAttrMask) >> GCAttrShift); }
226   void setObjCGCAttr(GC type) {
227     Mask = (Mask & ~GCAttrMask) | (type << GCAttrShift);
228   }
229   void removeObjCGCAttr() { setObjCGCAttr(GCNone); }
230   void addObjCGCAttr(GC type) {
231     assert(type);
232     setObjCGCAttr(type);
233   }
234   Qualifiers withoutObjCGCAttr() const {
235     Qualifiers qs = *this;
236     qs.removeObjCGCAttr();
237     return qs;
238   }
239   Qualifiers withoutObjCGLifetime() const {
240     Qualifiers qs = *this;
241     qs.removeObjCLifetime();
242     return qs;
243   }
244
245   bool hasObjCLifetime() const { return Mask & LifetimeMask; }
246   ObjCLifetime getObjCLifetime() const {
247     return ObjCLifetime((Mask & LifetimeMask) >> LifetimeShift);
248   }
249   void setObjCLifetime(ObjCLifetime type) {
250     Mask = (Mask & ~LifetimeMask) | (type << LifetimeShift);
251   }
252   void removeObjCLifetime() { setObjCLifetime(OCL_None); }
253   void addObjCLifetime(ObjCLifetime type) {
254     assert(type);
255     setObjCLifetime(type);
256   }
257
258   /// True if the lifetime is neither None or ExplicitNone.
259   bool hasNonTrivialObjCLifetime() const {
260     ObjCLifetime lifetime = getObjCLifetime();
261     return (lifetime > OCL_ExplicitNone);
262   }
263
264   /// True if the lifetime is either strong or weak.
265   bool hasStrongOrWeakObjCLifetime() const {
266     ObjCLifetime lifetime = getObjCLifetime();
267     return (lifetime == OCL_Strong || lifetime == OCL_Weak);
268   }
269   
270   bool hasAddressSpace() const { return Mask & AddressSpaceMask; }
271   unsigned getAddressSpace() const { return Mask >> AddressSpaceShift; }
272   void setAddressSpace(unsigned space) {
273     assert(space <= MaxAddressSpace);
274     Mask = (Mask & ~AddressSpaceMask)
275          | (((uint32_t) space) << AddressSpaceShift);
276   }
277   void removeAddressSpace() { setAddressSpace(0); }
278   void addAddressSpace(unsigned space) {
279     assert(space);
280     setAddressSpace(space);
281   }
282
283   // Fast qualifiers are those that can be allocated directly
284   // on a QualType object.
285   bool hasFastQualifiers() const { return getFastQualifiers(); }
286   unsigned getFastQualifiers() const { return Mask & FastMask; }
287   void setFastQualifiers(unsigned mask) {
288     assert(!(mask & ~FastMask) && "bitmask contains non-fast qualifier bits");
289     Mask = (Mask & ~FastMask) | mask;
290   }
291   void removeFastQualifiers(unsigned mask) {
292     assert(!(mask & ~FastMask) && "bitmask contains non-fast qualifier bits");
293     Mask &= ~mask;
294   }
295   void removeFastQualifiers() {
296     removeFastQualifiers(FastMask);
297   }
298   void addFastQualifiers(unsigned mask) {
299     assert(!(mask & ~FastMask) && "bitmask contains non-fast qualifier bits");
300     Mask |= mask;
301   }
302
303   /// hasNonFastQualifiers - Return true if the set contains any
304   /// qualifiers which require an ExtQuals node to be allocated.
305   bool hasNonFastQualifiers() const { return Mask & ~FastMask; }
306   Qualifiers getNonFastQualifiers() const {
307     Qualifiers Quals = *this;
308     Quals.setFastQualifiers(0);
309     return Quals;
310   }
311
312   /// hasQualifiers - Return true if the set contains any qualifiers.
313   bool hasQualifiers() const { return Mask; }
314   bool empty() const { return !Mask; }
315
316   /// \brief Add the qualifiers from the given set to this set.
317   void addQualifiers(Qualifiers Q) {
318     // If the other set doesn't have any non-boolean qualifiers, just
319     // bit-or it in.
320     if (!(Q.Mask & ~CVRMask))
321       Mask |= Q.Mask;
322     else {
323       Mask |= (Q.Mask & CVRMask);
324       if (Q.hasAddressSpace())
325         addAddressSpace(Q.getAddressSpace());
326       if (Q.hasObjCGCAttr())
327         addObjCGCAttr(Q.getObjCGCAttr());
328       if (Q.hasObjCLifetime())
329         addObjCLifetime(Q.getObjCLifetime());
330     }
331   }
332
333   /// \brief Add the qualifiers from the given set to this set, given that
334   /// they don't conflict.
335   void addConsistentQualifiers(Qualifiers qs) {
336     assert(getAddressSpace() == qs.getAddressSpace() ||
337            !hasAddressSpace() || !qs.hasAddressSpace());
338     assert(getObjCGCAttr() == qs.getObjCGCAttr() ||
339            !hasObjCGCAttr() || !qs.hasObjCGCAttr());
340     assert(getObjCLifetime() == qs.getObjCLifetime() ||
341            !hasObjCLifetime() || !qs.hasObjCLifetime());
342     Mask |= qs.Mask;
343   }
344
345   /// \brief Determines if these qualifiers compatibly include another set.
346   /// Generally this answers the question of whether an object with the other
347   /// qualifiers can be safely used as an object with these qualifiers.
348   bool compatiblyIncludes(Qualifiers other) const {
349     return 
350       // Address spaces must match exactly.
351       getAddressSpace() == other.getAddressSpace() &&
352       // ObjC GC qualifiers can match, be added, or be removed, but can't be
353       // changed.
354       (getObjCGCAttr() == other.getObjCGCAttr() ||
355        !hasObjCGCAttr() || !other.hasObjCGCAttr()) &&
356       // ObjC lifetime qualifiers must match exactly.
357       getObjCLifetime() == other.getObjCLifetime() &&
358       // CVR qualifiers may subset.
359       (((Mask & CVRMask) | (other.Mask & CVRMask)) == (Mask & CVRMask));
360   }
361
362   /// \brief Determines if these qualifiers compatibly include another set of
363   /// qualifiers from the narrow perspective of Objective-C ARC lifetime.
364   ///
365   /// One set of Objective-C lifetime qualifiers compatibly includes the other
366   /// if the lifetime qualifiers match, or if both are non-__weak and the 
367   /// including set also contains the 'const' qualifier.
368   bool compatiblyIncludesObjCLifetime(Qualifiers other) const {
369     if (getObjCLifetime() == other.getObjCLifetime())
370       return true;
371     
372     if (getObjCLifetime() == OCL_Weak || other.getObjCLifetime() == OCL_Weak)
373       return false;
374     
375     return hasConst();
376   }
377   
378   bool isSupersetOf(Qualifiers Other) const;
379
380   /// \brief Determine whether this set of qualifiers is a strict superset of
381   /// another set of qualifiers, not considering qualifier compatibility.
382   bool isStrictSupersetOf(Qualifiers Other) const;
383   
384   bool operator==(Qualifiers Other) const { return Mask == Other.Mask; }
385   bool operator!=(Qualifiers Other) const { return Mask != Other.Mask; }
386
387   operator bool() const { return hasQualifiers(); }
388
389   Qualifiers &operator+=(Qualifiers R) {
390     addQualifiers(R);
391     return *this;
392   }
393
394   // Union two qualifier sets.  If an enumerated qualifier appears
395   // in both sets, use the one from the right.
396   friend Qualifiers operator+(Qualifiers L, Qualifiers R) {
397     L += R;
398     return L;
399   }
400   
401   Qualifiers &operator-=(Qualifiers R) {
402     Mask = Mask & ~(R.Mask);
403     return *this;
404   }
405
406   /// \brief Compute the difference between two qualifier sets.
407   friend Qualifiers operator-(Qualifiers L, Qualifiers R) {
408     L -= R;
409     return L;
410   }
411   
412   std::string getAsString() const;
413   std::string getAsString(const PrintingPolicy &Policy) const {
414     std::string Buffer;
415     getAsStringInternal(Buffer, Policy);
416     return Buffer;
417   }
418   void getAsStringInternal(std::string &S, const PrintingPolicy &Policy) const;
419
420   void Profile(llvm::FoldingSetNodeID &ID) const {
421     ID.AddInteger(Mask);
422   }
423
424 private:
425
426   // bits:     |0 1 2|3 .. 4|5  ..  7|8   ...   31|
427   //           |C R V|GCAttr|Lifetime|AddressSpace|
428   uint32_t Mask;
429
430   static const uint32_t GCAttrMask = 0x18;
431   static const uint32_t GCAttrShift = 3;
432   static const uint32_t LifetimeMask = 0xE0;
433   static const uint32_t LifetimeShift = 5;
434   static const uint32_t AddressSpaceMask = ~(CVRMask|GCAttrMask|LifetimeMask);
435   static const uint32_t AddressSpaceShift = 8;
436 };
437
438 /// CallingConv - Specifies the calling convention that a function uses.
439 enum CallingConv {
440   CC_Default,
441   CC_C,           // __attribute__((cdecl))
442   CC_X86StdCall,  // __attribute__((stdcall))
443   CC_X86FastCall, // __attribute__((fastcall))
444   CC_X86ThisCall, // __attribute__((thiscall))
445   CC_X86Pascal,   // __attribute__((pascal))
446   CC_AAPCS,       // __attribute__((pcs("aapcs")))
447   CC_AAPCS_VFP    // __attribute__((pcs("aapcs-vfp")))
448 };
449
450 typedef std::pair<const Type*, Qualifiers> SplitQualType;
451
452 /// QualType - For efficiency, we don't store CV-qualified types as nodes on
453 /// their own: instead each reference to a type stores the qualifiers.  This
454 /// greatly reduces the number of nodes we need to allocate for types (for
455 /// example we only need one for 'int', 'const int', 'volatile int',
456 /// 'const volatile int', etc).
457 ///
458 /// As an added efficiency bonus, instead of making this a pair, we
459 /// just store the two bits we care about in the low bits of the
460 /// pointer.  To handle the packing/unpacking, we make QualType be a
461 /// simple wrapper class that acts like a smart pointer.  A third bit
462 /// indicates whether there are extended qualifiers present, in which
463 /// case the pointer points to a special structure.
464 class QualType {
465   // Thankfully, these are efficiently composable.
466   llvm::PointerIntPair<llvm::PointerUnion<const Type*,const ExtQuals*>,
467                        Qualifiers::FastWidth> Value;
468
469   const ExtQuals *getExtQualsUnsafe() const {
470     return Value.getPointer().get<const ExtQuals*>();
471   }
472
473   const Type *getTypePtrUnsafe() const {
474     return Value.getPointer().get<const Type*>();
475   }
476
477   const ExtQualsTypeCommonBase *getCommonPtr() const {
478     assert(!isNull() && "Cannot retrieve a NULL type pointer");
479     uintptr_t CommonPtrVal
480       = reinterpret_cast<uintptr_t>(Value.getOpaqueValue());
481     CommonPtrVal &= ~(uintptr_t)((1 << TypeAlignmentInBits) - 1);
482     return reinterpret_cast<ExtQualsTypeCommonBase*>(CommonPtrVal);
483   }
484
485   friend class QualifierCollector;
486 public:
487   QualType() {}
488
489   QualType(const Type *Ptr, unsigned Quals)
490     : Value(Ptr, Quals) {}
491   QualType(const ExtQuals *Ptr, unsigned Quals)
492     : Value(Ptr, Quals) {}
493
494   unsigned getLocalFastQualifiers() const { return Value.getInt(); }
495   void setLocalFastQualifiers(unsigned Quals) { Value.setInt(Quals); }
496
497   /// Retrieves a pointer to the underlying (unqualified) type.
498   /// This should really return a const Type, but it's not worth
499   /// changing all the users right now.
500   ///
501   /// This function requires that the type not be NULL. If the type might be
502   /// NULL, use the (slightly less efficient) \c getTypePtrOrNull().
503   const Type *getTypePtr() const;
504   
505   const Type *getTypePtrOrNull() const;
506
507   /// Retrieves a pointer to the name of the base type.
508   const IdentifierInfo *getBaseTypeIdentifier() const;
509
510   /// Divides a QualType into its unqualified type and a set of local
511   /// qualifiers.
512   SplitQualType split() const;
513
514   void *getAsOpaquePtr() const { return Value.getOpaqueValue(); }
515   static QualType getFromOpaquePtr(const void *Ptr) {
516     QualType T;
517     T.Value.setFromOpaqueValue(const_cast<void*>(Ptr));
518     return T;
519   }
520
521   const Type &operator*() const {
522     return *getTypePtr();
523   }
524
525   const Type *operator->() const {
526     return getTypePtr();
527   }
528
529   bool isCanonical() const;
530   bool isCanonicalAsParam() const;
531
532   /// isNull - Return true if this QualType doesn't point to a type yet.
533   bool isNull() const {
534     return Value.getPointer().isNull();
535   }
536
537   /// \brief Determine whether this particular QualType instance has the 
538   /// "const" qualifier set, without looking through typedefs that may have
539   /// added "const" at a different level.
540   bool isLocalConstQualified() const {
541     return (getLocalFastQualifiers() & Qualifiers::Const);
542   }
543   
544   /// \brief Determine whether this type is const-qualified.
545   bool isConstQualified() const;
546   
547   /// \brief Determine whether this particular QualType instance has the 
548   /// "restrict" qualifier set, without looking through typedefs that may have
549   /// added "restrict" at a different level.
550   bool isLocalRestrictQualified() const {
551     return (getLocalFastQualifiers() & Qualifiers::Restrict);
552   }
553   
554   /// \brief Determine whether this type is restrict-qualified.
555   bool isRestrictQualified() const;
556   
557   /// \brief Determine whether this particular QualType instance has the 
558   /// "volatile" qualifier set, without looking through typedefs that may have
559   /// added "volatile" at a different level.
560   bool isLocalVolatileQualified() const {
561     return (getLocalFastQualifiers() & Qualifiers::Volatile);
562   }
563
564   /// \brief Determine whether this type is volatile-qualified.
565   bool isVolatileQualified() const;
566   
567   /// \brief Determine whether this particular QualType instance has any
568   /// qualifiers, without looking through any typedefs that might add 
569   /// qualifiers at a different level.
570   bool hasLocalQualifiers() const {
571     return getLocalFastQualifiers() || hasLocalNonFastQualifiers();
572   }
573
574   /// \brief Determine whether this type has any qualifiers.
575   bool hasQualifiers() const;
576   
577   /// \brief Determine whether this particular QualType instance has any
578   /// "non-fast" qualifiers, e.g., those that are stored in an ExtQualType
579   /// instance.
580   bool hasLocalNonFastQualifiers() const {
581     return Value.getPointer().is<const ExtQuals*>();
582   }
583
584   /// \brief Retrieve the set of qualifiers local to this particular QualType
585   /// instance, not including any qualifiers acquired through typedefs or
586   /// other sugar.
587   Qualifiers getLocalQualifiers() const;
588
589   /// \brief Retrieve the set of qualifiers applied to this type.
590   Qualifiers getQualifiers() const;
591   
592   /// \brief Retrieve the set of CVR (const-volatile-restrict) qualifiers 
593   /// local to this particular QualType instance, not including any qualifiers
594   /// acquired through typedefs or other sugar.
595   unsigned getLocalCVRQualifiers() const {
596     return getLocalFastQualifiers();
597   }
598
599   /// \brief Retrieve the set of CVR (const-volatile-restrict) qualifiers 
600   /// applied to this type.
601   unsigned getCVRQualifiers() const;
602
603   bool isConstant(ASTContext& Ctx) const {
604     return QualType::isConstant(*this, Ctx);
605   }
606
607   /// \brief Determine whether this is a Plain Old Data (POD) type (C++ 3.9p10).
608   bool isPODType(ASTContext &Context) const;
609
610   /// isCXX11PODType() - Return true if this is a POD type according to the
611   /// more relaxed rules of the C++11 standard, regardless of the current
612   /// compilation's language.
613   /// (C++0x [basic.types]p9)
614   bool isCXX11PODType(ASTContext &Context) const;
615   
616   /// isTrivialType - Return true if this is a trivial type
617   /// (C++0x [basic.types]p9)
618   bool isTrivialType(ASTContext &Context) const;  
619
620   /// isTriviallyCopyableType - Return true if this is a trivially
621   /// copyable type (C++0x [basic.types]p9)
622   bool isTriviallyCopyableType(ASTContext &Context) const;
623
624   // Don't promise in the API that anything besides 'const' can be
625   // easily added.
626
627   /// addConst - add the specified type qualifier to this QualType.  
628   void addConst() {
629     addFastQualifiers(Qualifiers::Const);
630   }
631   QualType withConst() const {
632     return withFastQualifiers(Qualifiers::Const);
633   }
634
635   /// addVolatile - add the specified type qualifier to this QualType.  
636   void addVolatile() {
637     addFastQualifiers(Qualifiers::Volatile);
638   }
639   QualType withVolatile() const {
640     return withFastQualifiers(Qualifiers::Volatile);
641   }
642
643   QualType withCVRQualifiers(unsigned CVR) const {
644     return withFastQualifiers(CVR);
645   }
646
647   void addFastQualifiers(unsigned TQs) {
648     assert(!(TQs & ~Qualifiers::FastMask)
649            && "non-fast qualifier bits set in mask!");
650     Value.setInt(Value.getInt() | TQs);
651   }
652
653   void removeLocalConst();
654   void removeLocalVolatile();
655   void removeLocalRestrict();
656   void removeLocalCVRQualifiers(unsigned Mask);
657
658   void removeLocalFastQualifiers() { Value.setInt(0); }
659   void removeLocalFastQualifiers(unsigned Mask) {
660     assert(!(Mask & ~Qualifiers::FastMask) && "mask has non-fast qualifiers");
661     Value.setInt(Value.getInt() & ~Mask);
662   }
663
664   // Creates a type with the given qualifiers in addition to any
665   // qualifiers already on this type.
666   QualType withFastQualifiers(unsigned TQs) const {
667     QualType T = *this;
668     T.addFastQualifiers(TQs);
669     return T;
670   }
671
672   // Creates a type with exactly the given fast qualifiers, removing
673   // any existing fast qualifiers.
674   QualType withExactLocalFastQualifiers(unsigned TQs) const {
675     return withoutLocalFastQualifiers().withFastQualifiers(TQs);
676   }
677
678   // Removes fast qualifiers, but leaves any extended qualifiers in place.
679   QualType withoutLocalFastQualifiers() const {
680     QualType T = *this;
681     T.removeLocalFastQualifiers();
682     return T;
683   }
684
685   QualType getCanonicalType() const;
686
687   /// \brief Return this type with all of the instance-specific qualifiers
688   /// removed, but without removing any qualifiers that may have been applied
689   /// through typedefs.
690   QualType getLocalUnqualifiedType() const { return QualType(getTypePtr(), 0); }
691
692   /// \brief Retrieve the unqualified variant of the given type,
693   /// removing as little sugar as possible.
694   ///
695   /// This routine looks through various kinds of sugar to find the
696   /// least-desugared type that is unqualified. For example, given:
697   ///
698   /// \code
699   /// typedef int Integer;
700   /// typedef const Integer CInteger;
701   /// typedef CInteger DifferenceType;
702   /// \endcode
703   ///
704   /// Executing \c getUnqualifiedType() on the type \c DifferenceType will
705   /// desugar until we hit the type \c Integer, which has no qualifiers on it.
706   ///
707   /// The resulting type might still be qualified if it's an array
708   /// type.  To strip qualifiers even from within an array type, use
709   /// ASTContext::getUnqualifiedArrayType.
710   inline QualType getUnqualifiedType() const;
711
712   /// getSplitUnqualifiedType - Retrieve the unqualified variant of the
713   /// given type, removing as little sugar as possible.
714   ///
715   /// Like getUnqualifiedType(), but also returns the set of
716   /// qualifiers that were built up.
717   ///
718   /// The resulting type might still be qualified if it's an array
719   /// type.  To strip qualifiers even from within an array type, use
720   /// ASTContext::getUnqualifiedArrayType.
721   inline SplitQualType getSplitUnqualifiedType() const;
722   
723   /// \brief Determine whether this type is more qualified than the other
724   /// given type, requiring exact equality for non-CVR qualifiers.
725   bool isMoreQualifiedThan(QualType Other) const;
726
727   /// \brief Determine whether this type is at least as qualified as the other
728   /// given type, requiring exact equality for non-CVR qualifiers.
729   bool isAtLeastAsQualifiedAs(QualType Other) const;
730   
731   QualType getNonReferenceType() const;
732
733   /// \brief Determine the type of a (typically non-lvalue) expression with the
734   /// specified result type.
735   ///                       
736   /// This routine should be used for expressions for which the return type is
737   /// explicitly specified (e.g., in a cast or call) and isn't necessarily
738   /// an lvalue. It removes a top-level reference (since there are no 
739   /// expressions of reference type) and deletes top-level cvr-qualifiers
740   /// from non-class types (in C++) or all types (in C).
741   QualType getNonLValueExprType(ASTContext &Context) const;
742   
743   /// getDesugaredType - Return the specified type with any "sugar" removed from
744   /// the type.  This takes off typedefs, typeof's etc.  If the outer level of
745   /// the type is already concrete, it returns it unmodified.  This is similar
746   /// to getting the canonical type, but it doesn't remove *all* typedefs.  For
747   /// example, it returns "T*" as "T*", (not as "int*"), because the pointer is
748   /// concrete.
749   ///
750   /// Qualifiers are left in place.
751   QualType getDesugaredType(const ASTContext &Context) const {
752     return getDesugaredType(*this, Context);
753   }
754
755   SplitQualType getSplitDesugaredType() const {
756     return getSplitDesugaredType(*this);
757   }
758
759   /// \brief Return the specified type with one level of "sugar" removed from
760   /// the type. 
761   ///
762   /// This routine takes off the first typedef, typeof, etc. If the outer level
763   /// of the type is already concrete, it returns it unmodified.
764   QualType getSingleStepDesugaredType(const ASTContext &Context) const;
765   
766   /// IgnoreParens - Returns the specified type after dropping any
767   /// outer-level parentheses.
768   QualType IgnoreParens() const {
769     if (isa<ParenType>(*this))
770       return QualType::IgnoreParens(*this);
771     return *this;
772   }
773
774   /// operator==/!= - Indicate whether the specified types and qualifiers are
775   /// identical.
776   friend bool operator==(const QualType &LHS, const QualType &RHS) {
777     return LHS.Value == RHS.Value;
778   }
779   friend bool operator!=(const QualType &LHS, const QualType &RHS) {
780     return LHS.Value != RHS.Value;
781   }
782   std::string getAsString() const {
783     return getAsString(split());
784   }
785   static std::string getAsString(SplitQualType split) {
786     return getAsString(split.first, split.second);
787   }
788   static std::string getAsString(const Type *ty, Qualifiers qs);
789
790   std::string getAsString(const PrintingPolicy &Policy) const {
791     std::string S;
792     getAsStringInternal(S, Policy);
793     return S;
794   }
795   void getAsStringInternal(std::string &Str,
796                            const PrintingPolicy &Policy) const {
797     return getAsStringInternal(split(), Str, Policy);
798   }
799   static void getAsStringInternal(SplitQualType split, std::string &out,
800                                   const PrintingPolicy &policy) {
801     return getAsStringInternal(split.first, split.second, out, policy);
802   }
803   static void getAsStringInternal(const Type *ty, Qualifiers qs,
804                                   std::string &out,
805                                   const PrintingPolicy &policy);
806
807   void dump(const char *s) const;
808   void dump() const;
809
810   void Profile(llvm::FoldingSetNodeID &ID) const {
811     ID.AddPointer(getAsOpaquePtr());
812   }
813
814   /// getAddressSpace - Return the address space of this type.
815   inline unsigned getAddressSpace() const;
816
817   /// getObjCGCAttr - Returns gc attribute of this type.
818   inline Qualifiers::GC getObjCGCAttr() const;
819
820   /// isObjCGCWeak true when Type is objc's weak.
821   bool isObjCGCWeak() const {
822     return getObjCGCAttr() == Qualifiers::Weak;
823   }
824
825   /// isObjCGCStrong true when Type is objc's strong.
826   bool isObjCGCStrong() const {
827     return getObjCGCAttr() == Qualifiers::Strong;
828   }
829
830   /// getObjCLifetime - Returns lifetime attribute of this type.
831   Qualifiers::ObjCLifetime getObjCLifetime() const {
832     return getQualifiers().getObjCLifetime();
833   }
834
835   bool hasNonTrivialObjCLifetime() const {
836     return getQualifiers().hasNonTrivialObjCLifetime();
837   }
838
839   bool hasStrongOrWeakObjCLifetime() const {
840     return getQualifiers().hasStrongOrWeakObjCLifetime();
841   }
842
843   enum DestructionKind {
844     DK_none,
845     DK_cxx_destructor,
846     DK_objc_strong_lifetime,
847     DK_objc_weak_lifetime
848   };
849
850   /// isDestructedType - nonzero if objects of this type require
851   /// non-trivial work to clean up after.  Non-zero because it's
852   /// conceivable that qualifiers (objc_gc(weak)?) could make
853   /// something require destruction.
854   DestructionKind isDestructedType() const {
855     return isDestructedTypeImpl(*this);
856   }
857
858   /// \brief Determine whether expressions of the given type are forbidden 
859   /// from being lvalues in C.
860   ///
861   /// The expression types that are forbidden to be lvalues are:
862   ///   - 'void', but not qualified void
863   ///   - function types
864   ///
865   /// The exact rule here is C99 6.3.2.1:
866   ///   An lvalue is an expression with an object type or an incomplete
867   ///   type other than void.
868   bool isCForbiddenLValueType() const;
869
870   /// \brief Determine whether this type has trivial copy/move-assignment
871   ///        semantics.
872   bool hasTrivialAssignment(ASTContext &Context, bool Copying) const;
873   
874 private:
875   // These methods are implemented in a separate translation unit;
876   // "static"-ize them to avoid creating temporary QualTypes in the
877   // caller.
878   static bool isConstant(QualType T, ASTContext& Ctx);
879   static QualType getDesugaredType(QualType T, const ASTContext &Context);
880   static SplitQualType getSplitDesugaredType(QualType T);
881   static SplitQualType getSplitUnqualifiedTypeImpl(QualType type);
882   static QualType IgnoreParens(QualType T);
883   static DestructionKind isDestructedTypeImpl(QualType type);
884 };
885
886 } // end clang.
887
888 namespace llvm {
889 /// Implement simplify_type for QualType, so that we can dyn_cast from QualType
890 /// to a specific Type class.
891 template<> struct simplify_type<const ::clang::QualType> {
892   typedef const ::clang::Type *SimpleType;
893   static SimpleType getSimplifiedValue(const ::clang::QualType &Val) {
894     return Val.getTypePtr();
895   }
896 };
897 template<> struct simplify_type< ::clang::QualType>
898   : public simplify_type<const ::clang::QualType> {};
899
900 // Teach SmallPtrSet that QualType is "basically a pointer".
901 template<>
902 class PointerLikeTypeTraits<clang::QualType> {
903 public:
904   static inline void *getAsVoidPointer(clang::QualType P) {
905     return P.getAsOpaquePtr();
906   }
907   static inline clang::QualType getFromVoidPointer(void *P) {
908     return clang::QualType::getFromOpaquePtr(P);
909   }
910   // Various qualifiers go in low bits.
911   enum { NumLowBitsAvailable = 0 };
912 };
913
914 } // end namespace llvm
915
916 namespace clang {
917
918 /// \brief Base class that is common to both the \c ExtQuals and \c Type 
919 /// classes, which allows \c QualType to access the common fields between the
920 /// two.
921 ///
922 class ExtQualsTypeCommonBase {
923   ExtQualsTypeCommonBase(const Type *baseType, QualType canon)
924     : BaseType(baseType), CanonicalType(canon) {}
925
926   /// \brief The "base" type of an extended qualifiers type (\c ExtQuals) or
927   /// a self-referential pointer (for \c Type).
928   ///
929   /// This pointer allows an efficient mapping from a QualType to its 
930   /// underlying type pointer.
931   const Type *const BaseType;
932
933   /// \brief The canonical type of this type.  A QualType.
934   QualType CanonicalType;
935
936   friend class QualType;
937   friend class Type;
938   friend class ExtQuals;
939 };
940   
941 /// ExtQuals - We can encode up to four bits in the low bits of a
942 /// type pointer, but there are many more type qualifiers that we want
943 /// to be able to apply to an arbitrary type.  Therefore we have this
944 /// struct, intended to be heap-allocated and used by QualType to
945 /// store qualifiers.
946 ///
947 /// The current design tags the 'const', 'restrict', and 'volatile' qualifiers 
948 /// in three low bits on the QualType pointer; a fourth bit records whether
949 /// the pointer is an ExtQuals node. The extended qualifiers (address spaces,
950 /// Objective-C GC attributes) are much more rare.
951 class ExtQuals : public ExtQualsTypeCommonBase, public llvm::FoldingSetNode {
952   // NOTE: changing the fast qualifiers should be straightforward as
953   // long as you don't make 'const' non-fast.
954   // 1. Qualifiers:
955   //    a) Modify the bitmasks (Qualifiers::TQ and DeclSpec::TQ).
956   //       Fast qualifiers must occupy the low-order bits.
957   //    b) Update Qualifiers::FastWidth and FastMask.
958   // 2. QualType:
959   //    a) Update is{Volatile,Restrict}Qualified(), defined inline.
960   //    b) Update remove{Volatile,Restrict}, defined near the end of
961   //       this header.
962   // 3. ASTContext:
963   //    a) Update get{Volatile,Restrict}Type.
964
965   /// Quals - the immutable set of qualifiers applied by this
966   /// node;  always contains extended qualifiers.
967   Qualifiers Quals;
968
969   ExtQuals *this_() { return this; }
970
971 public:
972   ExtQuals(const Type *baseType, QualType canon, Qualifiers quals) 
973     : ExtQualsTypeCommonBase(baseType,
974                              canon.isNull() ? QualType(this_(), 0) : canon),
975       Quals(quals)
976   {
977     assert(Quals.hasNonFastQualifiers()
978            && "ExtQuals created with no fast qualifiers");
979     assert(!Quals.hasFastQualifiers()
980            && "ExtQuals created with fast qualifiers");
981   }
982
983   Qualifiers getQualifiers() const { return Quals; }
984
985   bool hasObjCGCAttr() const { return Quals.hasObjCGCAttr(); }
986   Qualifiers::GC getObjCGCAttr() const { return Quals.getObjCGCAttr(); }
987
988   bool hasObjCLifetime() const { return Quals.hasObjCLifetime(); }
989   Qualifiers::ObjCLifetime getObjCLifetime() const {
990     return Quals.getObjCLifetime();
991   }
992
993   bool hasAddressSpace() const { return Quals.hasAddressSpace(); }
994   unsigned getAddressSpace() const { return Quals.getAddressSpace(); }
995
996   const Type *getBaseType() const { return BaseType; }
997
998 public:
999   void Profile(llvm::FoldingSetNodeID &ID) const {
1000     Profile(ID, getBaseType(), Quals);
1001   }
1002   static void Profile(llvm::FoldingSetNodeID &ID,
1003                       const Type *BaseType,
1004                       Qualifiers Quals) {
1005     assert(!Quals.hasFastQualifiers() && "fast qualifiers in ExtQuals hash!");
1006     ID.AddPointer(BaseType);
1007     Quals.Profile(ID);
1008   }
1009 };
1010
1011 /// \brief The kind of C++0x ref-qualifier associated with a function type, 
1012 /// which determines whether a member function's "this" object can be an 
1013 /// lvalue, rvalue, or neither.
1014 enum RefQualifierKind {
1015   /// \brief No ref-qualifier was provided.
1016   RQ_None = 0,
1017   /// \brief An lvalue ref-qualifier was provided (\c &).
1018   RQ_LValue,
1019   /// \brief An rvalue ref-qualifier was provided (\c &&).
1020   RQ_RValue
1021 };
1022   
1023 /// Type - This is the base class of the type hierarchy.  A central concept
1024 /// with types is that each type always has a canonical type.  A canonical type
1025 /// is the type with any typedef names stripped out of it or the types it
1026 /// references.  For example, consider:
1027 ///
1028 ///  typedef int  foo;
1029 ///  typedef foo* bar;
1030 ///    'int *'    'foo *'    'bar'
1031 ///
1032 /// There will be a Type object created for 'int'.  Since int is canonical, its
1033 /// canonicaltype pointer points to itself.  There is also a Type for 'foo' (a
1034 /// TypedefType).  Its CanonicalType pointer points to the 'int' Type.  Next
1035 /// there is a PointerType that represents 'int*', which, like 'int', is
1036 /// canonical.  Finally, there is a PointerType type for 'foo*' whose canonical
1037 /// type is 'int*', and there is a TypedefType for 'bar', whose canonical type
1038 /// is also 'int*'.
1039 ///
1040 /// Non-canonical types are useful for emitting diagnostics, without losing
1041 /// information about typedefs being used.  Canonical types are useful for type
1042 /// comparisons (they allow by-pointer equality tests) and useful for reasoning
1043 /// about whether something has a particular form (e.g. is a function type),
1044 /// because they implicitly, recursively, strip all typedefs out of a type.
1045 ///
1046 /// Types, once created, are immutable.
1047 ///
1048 class Type : public ExtQualsTypeCommonBase {
1049 public:
1050   enum TypeClass {
1051 #define TYPE(Class, Base) Class,
1052 #define LAST_TYPE(Class) TypeLast = Class,
1053 #define ABSTRACT_TYPE(Class, Base)
1054 #include "clang/AST/TypeNodes.def"
1055     TagFirst = Record, TagLast = Enum
1056   };
1057
1058 private:
1059   Type(const Type&);           // DO NOT IMPLEMENT.
1060   void operator=(const Type&); // DO NOT IMPLEMENT.
1061
1062   /// Bitfields required by the Type class.
1063   class TypeBitfields {
1064     friend class Type;
1065     template <class T> friend class TypePropertyCache;
1066
1067     /// TypeClass bitfield - Enum that specifies what subclass this belongs to.
1068     unsigned TC : 8;
1069
1070     /// Dependent - Whether this type is a dependent type (C++ [temp.dep.type]).
1071     /// Note that this should stay at the end of the ivars for Type so that
1072     /// subclasses can pack their bitfields into the same word.
1073     unsigned Dependent : 1;
1074   
1075     /// \brief Whether this type somehow involves a template parameter, even 
1076     /// if the resolution of the type does not depend on a template parameter.
1077     unsigned InstantiationDependent : 1;
1078     
1079     /// \brief Whether this type is a variably-modified type (C99 6.7.5).
1080     unsigned VariablyModified : 1;
1081
1082     /// \brief Whether this type contains an unexpanded parameter pack
1083     /// (for C++0x variadic templates).
1084     unsigned ContainsUnexpandedParameterPack : 1;
1085   
1086     /// \brief Nonzero if the cache (i.e. the bitfields here starting
1087     /// with 'Cache') is valid.  If so, then this is a
1088     /// LangOptions::VisibilityMode+1.
1089     mutable unsigned CacheValidAndVisibility : 2;
1090   
1091     /// \brief Linkage of this type.
1092     mutable unsigned CachedLinkage : 2;
1093
1094     /// \brief Whether this type involves and local or unnamed types. 
1095     mutable unsigned CachedLocalOrUnnamed : 1;
1096   
1097     /// \brief FromAST - Whether this type comes from an AST file.
1098     mutable unsigned FromAST : 1;
1099
1100     bool isCacheValid() const {
1101       return (CacheValidAndVisibility != 0);
1102     }
1103     Visibility getVisibility() const {
1104       assert(isCacheValid() && "getting linkage from invalid cache");
1105       return static_cast<Visibility>(CacheValidAndVisibility-1);
1106     }
1107     Linkage getLinkage() const {
1108       assert(isCacheValid() && "getting linkage from invalid cache");
1109       return static_cast<Linkage>(CachedLinkage);
1110     }
1111     bool hasLocalOrUnnamedType() const {
1112       assert(isCacheValid() && "getting linkage from invalid cache");
1113       return CachedLocalOrUnnamed;
1114     }
1115   };
1116   enum { NumTypeBits = 18 };
1117
1118 protected:
1119   // These classes allow subclasses to somewhat cleanly pack bitfields
1120   // into Type.
1121
1122   class ArrayTypeBitfields {
1123     friend class ArrayType;
1124
1125     unsigned : NumTypeBits;
1126
1127     /// IndexTypeQuals - CVR qualifiers from declarations like
1128     /// 'int X[static restrict 4]'. For function parameters only.
1129     unsigned IndexTypeQuals : 3;
1130
1131     /// SizeModifier - storage class qualifiers from declarations like
1132     /// 'int X[static restrict 4]'. For function parameters only.
1133     /// Actually an ArrayType::ArraySizeModifier.
1134     unsigned SizeModifier : 3;
1135   };
1136
1137   class BuiltinTypeBitfields {
1138     friend class BuiltinType;
1139
1140     unsigned : NumTypeBits;
1141
1142     /// The kind (BuiltinType::Kind) of builtin type this is.
1143     unsigned Kind : 8;
1144   };
1145
1146   class FunctionTypeBitfields {
1147     friend class FunctionType;
1148
1149     unsigned : NumTypeBits;
1150
1151     /// Extra information which affects how the function is called, like
1152     /// regparm and the calling convention.
1153     unsigned ExtInfo : 8;
1154
1155     /// Whether the function is variadic.  Only used by FunctionProtoType.
1156     unsigned Variadic : 1;
1157
1158     /// TypeQuals - Used only by FunctionProtoType, put here to pack with the
1159     /// other bitfields.
1160     /// The qualifiers are part of FunctionProtoType because...
1161     ///
1162     /// C++ 8.3.5p4: The return type, the parameter type list and the
1163     /// cv-qualifier-seq, [...], are part of the function type.
1164     unsigned TypeQuals : 3;
1165     
1166     /// \brief The ref-qualifier associated with a \c FunctionProtoType.
1167     ///
1168     /// This is a value of type \c RefQualifierKind.
1169     unsigned RefQualifier : 2;
1170   };
1171
1172   class ObjCObjectTypeBitfields {
1173     friend class ObjCObjectType;
1174
1175     unsigned : NumTypeBits;
1176
1177     /// NumProtocols - The number of protocols stored directly on this
1178     /// object type.
1179     unsigned NumProtocols : 32 - NumTypeBits;
1180   };
1181
1182   class ReferenceTypeBitfields {
1183     friend class ReferenceType;
1184
1185     unsigned : NumTypeBits;
1186
1187     /// True if the type was originally spelled with an lvalue sigil.
1188     /// This is never true of rvalue references but can also be false
1189     /// on lvalue references because of C++0x [dcl.typedef]p9,
1190     /// as follows:
1191     ///
1192     ///   typedef int &ref;    // lvalue, spelled lvalue
1193     ///   typedef int &&rvref; // rvalue
1194     ///   ref &a;              // lvalue, inner ref, spelled lvalue
1195     ///   ref &&a;             // lvalue, inner ref
1196     ///   rvref &a;            // lvalue, inner ref, spelled lvalue
1197     ///   rvref &&a;           // rvalue, inner ref
1198     unsigned SpelledAsLValue : 1;
1199
1200     /// True if the inner type is a reference type.  This only happens
1201     /// in non-canonical forms.
1202     unsigned InnerRef : 1;
1203   };
1204
1205   class TypeWithKeywordBitfields {
1206     friend class TypeWithKeyword;
1207
1208     unsigned : NumTypeBits;
1209
1210     /// An ElaboratedTypeKeyword.  8 bits for efficient access.
1211     unsigned Keyword : 8;
1212   };
1213
1214   class VectorTypeBitfields {
1215     friend class VectorType;
1216
1217     unsigned : NumTypeBits;
1218
1219     /// VecKind - The kind of vector, either a generic vector type or some
1220     /// target-specific vector type such as for AltiVec or Neon.
1221     unsigned VecKind : 3;
1222
1223     /// NumElements - The number of elements in the vector.
1224     unsigned NumElements : 29 - NumTypeBits;
1225   };
1226
1227   class AttributedTypeBitfields {
1228     friend class AttributedType;
1229
1230     unsigned : NumTypeBits;
1231
1232     /// AttrKind - an AttributedType::Kind
1233     unsigned AttrKind : 32 - NumTypeBits;
1234   };
1235
1236   union {
1237     TypeBitfields TypeBits;
1238     ArrayTypeBitfields ArrayTypeBits;
1239     AttributedTypeBitfields AttributedTypeBits;
1240     BuiltinTypeBitfields BuiltinTypeBits;
1241     FunctionTypeBitfields FunctionTypeBits;
1242     ObjCObjectTypeBitfields ObjCObjectTypeBits;
1243     ReferenceTypeBitfields ReferenceTypeBits;
1244     TypeWithKeywordBitfields TypeWithKeywordBits;
1245     VectorTypeBitfields VectorTypeBits;
1246   };
1247
1248 private:
1249   /// \brief Set whether this type comes from an AST file.
1250   void setFromAST(bool V = true) const { 
1251     TypeBits.FromAST = V;
1252   }
1253
1254   template <class T> friend class TypePropertyCache;
1255
1256 protected:
1257   // silence VC++ warning C4355: 'this' : used in base member initializer list
1258   Type *this_() { return this; }
1259   Type(TypeClass tc, QualType canon, bool Dependent, 
1260        bool InstantiationDependent, bool VariablyModified,
1261        bool ContainsUnexpandedParameterPack)
1262     : ExtQualsTypeCommonBase(this,
1263                              canon.isNull() ? QualType(this_(), 0) : canon) {
1264     TypeBits.TC = tc;
1265     TypeBits.Dependent = Dependent;
1266     TypeBits.InstantiationDependent = Dependent || InstantiationDependent;
1267     TypeBits.VariablyModified = VariablyModified;
1268     TypeBits.ContainsUnexpandedParameterPack = ContainsUnexpandedParameterPack;
1269     TypeBits.CacheValidAndVisibility = 0;
1270     TypeBits.CachedLocalOrUnnamed = false;
1271     TypeBits.CachedLinkage = NoLinkage;
1272     TypeBits.FromAST = false;
1273   }
1274   friend class ASTContext;
1275
1276   void setDependent(bool D = true) { 
1277     TypeBits.Dependent = D; 
1278     if (D)
1279       TypeBits.InstantiationDependent = true;
1280   }
1281   void setInstantiationDependent(bool D = true) { 
1282     TypeBits.InstantiationDependent = D; }
1283   void setVariablyModified(bool VM = true) { TypeBits.VariablyModified = VM; 
1284   }
1285   void setContainsUnexpandedParameterPack(bool PP = true) {
1286     TypeBits.ContainsUnexpandedParameterPack = PP;
1287   }
1288
1289 public:
1290   TypeClass getTypeClass() const { return static_cast<TypeClass>(TypeBits.TC); }
1291
1292   /// \brief Whether this type comes from an AST file.
1293   bool isFromAST() const { return TypeBits.FromAST; }
1294
1295   /// \brief Whether this type is or contains an unexpanded parameter
1296   /// pack, used to support C++0x variadic templates.
1297   ///
1298   /// A type that contains a parameter pack shall be expanded by the
1299   /// ellipsis operator at some point. For example, the typedef in the
1300   /// following example contains an unexpanded parameter pack 'T':
1301   ///
1302   /// \code
1303   /// template<typename ...T>
1304   /// struct X {
1305   ///   typedef T* pointer_types; // ill-formed; T is a parameter pack.
1306   /// };
1307   /// \endcode
1308   ///
1309   /// Note that this routine does not specify which 
1310   bool containsUnexpandedParameterPack() const { 
1311     return TypeBits.ContainsUnexpandedParameterPack;
1312   }
1313
1314   /// Determines if this type would be canonical if it had no further
1315   /// qualification.
1316   bool isCanonicalUnqualified() const {
1317     return CanonicalType == QualType(this, 0);
1318   }
1319
1320   /// Types are partitioned into 3 broad categories (C99 6.2.5p1):
1321   /// object types, function types, and incomplete types.
1322
1323   /// isIncompleteType - Return true if this is an incomplete type.
1324   /// A type that can describe objects, but which lacks information needed to
1325   /// determine its size (e.g. void, or a fwd declared struct). Clients of this
1326   /// routine will need to determine if the size is actually required.
1327   bool isIncompleteType() const;
1328
1329   /// isIncompleteOrObjectType - Return true if this is an incomplete or object
1330   /// type, in other words, not a function type.
1331   bool isIncompleteOrObjectType() const {
1332     return !isFunctionType();
1333   }
1334   
1335   /// \brief Determine whether this type is an object type.
1336   bool isObjectType() const {
1337     // C++ [basic.types]p8:
1338     //   An object type is a (possibly cv-qualified) type that is not a 
1339     //   function type, not a reference type, and not a void type.
1340     return !isReferenceType() && !isFunctionType() && !isVoidType();
1341   }
1342
1343   /// isLiteralType - Return true if this is a literal type
1344   /// (C++0x [basic.types]p10)
1345   bool isLiteralType() const;
1346
1347   /// \brief Test if this type is a standard-layout type.
1348   /// (C++0x [basic.type]p9)
1349   bool isStandardLayoutType() const;
1350
1351   /// Helper methods to distinguish type categories. All type predicates
1352   /// operate on the canonical type, ignoring typedefs and qualifiers.
1353
1354   /// isBuiltinType - returns true if the type is a builtin type.
1355   bool isBuiltinType() const;
1356
1357   /// isSpecificBuiltinType - Test for a particular builtin type.
1358   bool isSpecificBuiltinType(unsigned K) const;
1359
1360   /// isPlaceholderType - Test for a type which does not represent an
1361   /// actual type-system type but is instead used as a placeholder for
1362   /// various convenient purposes within Clang.  All such types are
1363   /// BuiltinTypes.
1364   bool isPlaceholderType() const;
1365   const BuiltinType *getAsPlaceholderType() const;
1366
1367   /// isSpecificPlaceholderType - Test for a specific placeholder type.
1368   bool isSpecificPlaceholderType(unsigned K) const;
1369
1370   /// isIntegerType() does *not* include complex integers (a GCC extension).
1371   /// isComplexIntegerType() can be used to test for complex integers.
1372   bool isIntegerType() const;     // C99 6.2.5p17 (int, char, bool, enum)
1373   bool isEnumeralType() const;
1374   bool isBooleanType() const;
1375   bool isCharType() const;
1376   bool isWideCharType() const;
1377   bool isChar16Type() const;
1378   bool isChar32Type() const;
1379   bool isAnyCharacterType() const;
1380   bool isIntegralType(ASTContext &Ctx) const;
1381   
1382   /// \brief Determine whether this type is an integral or enumeration type.
1383   bool isIntegralOrEnumerationType() const;
1384   /// \brief Determine whether this type is an integral or unscoped enumeration
1385   /// type.
1386   bool isIntegralOrUnscopedEnumerationType() const;
1387                                    
1388   /// Floating point categories.
1389   bool isRealFloatingType() const; // C99 6.2.5p10 (float, double, long double)
1390   /// isComplexType() does *not* include complex integers (a GCC extension).
1391   /// isComplexIntegerType() can be used to test for complex integers.
1392   bool isComplexType() const;      // C99 6.2.5p11 (complex)
1393   bool isAnyComplexType() const;   // C99 6.2.5p11 (complex) + Complex Int.
1394   bool isFloatingType() const;     // C99 6.2.5p11 (real floating + complex)
1395   bool isHalfType() const;         // OpenCL 6.1.1.1, NEON (IEEE 754-2008 half)
1396   bool isRealType() const;         // C99 6.2.5p17 (real floating + integer)
1397   bool isArithmeticType() const;   // C99 6.2.5p18 (integer + floating)
1398   bool isVoidType() const;         // C99 6.2.5p19
1399   bool isDerivedType() const;      // C99 6.2.5p20
1400   bool isScalarType() const;       // C99 6.2.5p21 (arithmetic + pointers)
1401   bool isAggregateType() const;
1402   bool isFundamentalType() const;
1403   bool isCompoundType() const;
1404
1405   // Type Predicates: Check to see if this type is structurally the specified
1406   // type, ignoring typedefs and qualifiers.
1407   bool isFunctionType() const;
1408   bool isFunctionNoProtoType() const { return getAs<FunctionNoProtoType>(); }
1409   bool isFunctionProtoType() const { return getAs<FunctionProtoType>(); }
1410   bool isPointerType() const;
1411   bool isAnyPointerType() const;   // Any C pointer or ObjC object pointer
1412   bool isBlockPointerType() const;
1413   bool isVoidPointerType() const;
1414   bool isReferenceType() const;
1415   bool isLValueReferenceType() const;
1416   bool isRValueReferenceType() const;
1417   bool isFunctionPointerType() const;
1418   bool isMemberPointerType() const;
1419   bool isMemberFunctionPointerType() const;
1420   bool isMemberDataPointerType() const;
1421   bool isArrayType() const;
1422   bool isConstantArrayType() const;
1423   bool isIncompleteArrayType() const;
1424   bool isVariableArrayType() const;
1425   bool isDependentSizedArrayType() const;
1426   bool isRecordType() const;
1427   bool isClassType() const;
1428   bool isStructureType() const;
1429   bool isStructureOrClassType() const;
1430   bool isUnionType() const;
1431   bool isComplexIntegerType() const;            // GCC _Complex integer type.
1432   bool isVectorType() const;                    // GCC vector type.
1433   bool isExtVectorType() const;                 // Extended vector type.
1434   bool isObjCObjectPointerType() const;         // pointer to ObjC object
1435   bool isObjCRetainableType() const;            // ObjC object or block pointer
1436   bool isObjCLifetimeType() const;              // (array of)* retainable type
1437   bool isObjCIndirectLifetimeType() const;      // (pointer to)* lifetime type
1438   bool isObjCNSObjectType() const;              // __attribute__((NSObject))
1439   // FIXME: change this to 'raw' interface type, so we can used 'interface' type
1440   // for the common case.
1441   bool isObjCObjectType() const;                // NSString or typeof(*(id)0)
1442   bool isObjCQualifiedInterfaceType() const;    // NSString<foo>
1443   bool isObjCQualifiedIdType() const;           // id<foo>
1444   bool isObjCQualifiedClassType() const;        // Class<foo>
1445   bool isObjCObjectOrInterfaceType() const;
1446   bool isObjCIdType() const;                    // id
1447   bool isObjCClassType() const;                 // Class
1448   bool isObjCSelType() const;                 // Class
1449   bool isObjCBuiltinType() const;               // 'id' or 'Class'
1450   bool isObjCARCBridgableType() const;
1451   bool isCARCBridgableType() const;
1452   bool isTemplateTypeParmType() const;          // C++ template type parameter
1453   bool isNullPtrType() const;                   // C++0x nullptr_t
1454   bool isAtomicType() const;                    // C1X _Atomic()
1455
1456   /// Determines if this type, which must satisfy
1457   /// isObjCLifetimeType(), is implicitly __unsafe_unretained rather
1458   /// than implicitly __strong.
1459   bool isObjCARCImplicitlyUnretainedType() const;
1460
1461   /// Return the implicit lifetime for this type, which must not be dependent.
1462   Qualifiers::ObjCLifetime getObjCARCImplicitLifetime() const;
1463
1464   enum ScalarTypeKind {
1465     STK_CPointer,
1466     STK_BlockPointer,
1467     STK_ObjCObjectPointer,
1468     STK_MemberPointer,
1469     STK_Bool,
1470     STK_Integral,
1471     STK_Floating,
1472     STK_IntegralComplex,
1473     STK_FloatingComplex
1474   };
1475   /// getScalarTypeKind - Given that this is a scalar type, classify it.
1476   ScalarTypeKind getScalarTypeKind() const;
1477
1478   /// isDependentType - Whether this type is a dependent type, meaning
1479   /// that its definition somehow depends on a template parameter
1480   /// (C++ [temp.dep.type]).
1481   bool isDependentType() const { return TypeBits.Dependent; }
1482   
1483   /// \brief Determine whether this type is an instantiation-dependent type,
1484   /// meaning that the type involves a template parameter (even if the
1485   /// definition does not actually depend on the type substituted for that
1486   /// template parameter).
1487   bool isInstantiationDependentType() const { 
1488     return TypeBits.InstantiationDependent; 
1489   }
1490   
1491   /// \brief Whether this type is a variably-modified type (C99 6.7.5).
1492   bool isVariablyModifiedType() const { return TypeBits.VariablyModified; }
1493
1494   /// \brief Whether this type involves a variable-length array type
1495   /// with a definite size.
1496   bool hasSizedVLAType() const;
1497   
1498   /// \brief Whether this type is or contains a local or unnamed type.
1499   bool hasUnnamedOrLocalType() const;
1500   
1501   bool isOverloadableType() const;
1502
1503   /// \brief Determine wither this type is a C++ elaborated-type-specifier.
1504   bool isElaboratedTypeSpecifier() const;
1505
1506   bool canDecayToPointerType() const;
1507   
1508   /// hasPointerRepresentation - Whether this type is represented
1509   /// natively as a pointer; this includes pointers, references, block
1510   /// pointers, and Objective-C interface, qualified id, and qualified
1511   /// interface types, as well as nullptr_t.
1512   bool hasPointerRepresentation() const;
1513
1514   /// hasObjCPointerRepresentation - Whether this type can represent
1515   /// an objective pointer type for the purpose of GC'ability
1516   bool hasObjCPointerRepresentation() const;
1517
1518   /// \brief Determine whether this type has an integer representation
1519   /// of some sort, e.g., it is an integer type or a vector.
1520   bool hasIntegerRepresentation() const;
1521
1522   /// \brief Determine whether this type has an signed integer representation
1523   /// of some sort, e.g., it is an signed integer type or a vector.
1524   bool hasSignedIntegerRepresentation() const;
1525
1526   /// \brief Determine whether this type has an unsigned integer representation
1527   /// of some sort, e.g., it is an unsigned integer type or a vector.
1528   bool hasUnsignedIntegerRepresentation() const;
1529
1530   /// \brief Determine whether this type has a floating-point representation
1531   /// of some sort, e.g., it is a floating-point type or a vector thereof.
1532   bool hasFloatingRepresentation() const;
1533
1534   // Type Checking Functions: Check to see if this type is structurally the
1535   // specified type, ignoring typedefs and qualifiers, and return a pointer to
1536   // the best type we can.
1537   const RecordType *getAsStructureType() const;
1538   /// NOTE: getAs*ArrayType are methods on ASTContext.
1539   const RecordType *getAsUnionType() const;
1540   const ComplexType *getAsComplexIntegerType() const; // GCC complex int type.
1541   // The following is a convenience method that returns an ObjCObjectPointerType
1542   // for object declared using an interface.
1543   const ObjCObjectPointerType *getAsObjCInterfacePointerType() const;
1544   const ObjCObjectPointerType *getAsObjCQualifiedIdType() const;
1545   const ObjCObjectPointerType *getAsObjCQualifiedClassType() const;
1546   const ObjCObjectType *getAsObjCQualifiedInterfaceType() const;
1547   const CXXRecordDecl *getCXXRecordDeclForPointerType() const;
1548
1549   /// \brief Retrieves the CXXRecordDecl that this type refers to, either
1550   /// because the type is a RecordType or because it is the injected-class-name 
1551   /// type of a class template or class template partial specialization.
1552   CXXRecordDecl *getAsCXXRecordDecl() const;
1553
1554   /// \brief Get the AutoType whose type will be deduced for a variable with
1555   /// an initializer of this type. This looks through declarators like pointer
1556   /// types, but not through decltype or typedefs.
1557   AutoType *getContainedAutoType() const;
1558   
1559   /// Member-template getAs<specific type>'.  Look through sugar for
1560   /// an instance of <specific type>.   This scheme will eventually
1561   /// replace the specific getAsXXXX methods above.
1562   ///
1563   /// There are some specializations of this member template listed
1564   /// immediately following this class.
1565   template <typename T> const T *getAs() const;
1566
1567   /// A variant of getAs<> for array types which silently discards
1568   /// qualifiers from the outermost type.
1569   const ArrayType *getAsArrayTypeUnsafe() const;
1570
1571   /// Member-template castAs<specific type>.  Look through sugar for
1572   /// the underlying instance of <specific type>.
1573   ///
1574   /// This method has the same relationship to getAs<T> as cast<T> has
1575   /// to dyn_cast<T>; which is to say, the underlying type *must*
1576   /// have the intended type, and this method will never return null.
1577   template <typename T> const T *castAs() const;
1578
1579   /// A variant of castAs<> for array type which silently discards
1580   /// qualifiers from the outermost type.
1581   const ArrayType *castAsArrayTypeUnsafe() const;
1582
1583   /// getBaseElementTypeUnsafe - Get the base element type of this
1584   /// type, potentially discarding type qualifiers.  This method
1585   /// should never be used when type qualifiers are meaningful.
1586   const Type *getBaseElementTypeUnsafe() const;
1587
1588   /// getArrayElementTypeNoTypeQual - If this is an array type, return the
1589   /// element type of the array, potentially with type qualifiers missing.
1590   /// This method should never be used when type qualifiers are meaningful.
1591   const Type *getArrayElementTypeNoTypeQual() const;
1592
1593   /// getPointeeType - If this is a pointer, ObjC object pointer, or block
1594   /// pointer, this returns the respective pointee.
1595   QualType getPointeeType() const;
1596
1597   /// getUnqualifiedDesugaredType() - Return the specified type with
1598   /// any "sugar" removed from the type, removing any typedefs,
1599   /// typeofs, etc., as well as any qualifiers.
1600   const Type *getUnqualifiedDesugaredType() const;
1601
1602   /// More type predicates useful for type checking/promotion
1603   bool isPromotableIntegerType() const; // C99 6.3.1.1p2
1604
1605   /// isSignedIntegerType - Return true if this is an integer type that is
1606   /// signed, according to C99 6.2.5p4 [char, signed char, short, int, long..],
1607   /// or an enum decl which has a signed representation.
1608   bool isSignedIntegerType() const;
1609
1610   /// isUnsignedIntegerType - Return true if this is an integer type that is
1611   /// unsigned, according to C99 6.2.5p6 [which returns true for _Bool], 
1612   /// or an enum decl which has an unsigned representation.
1613   bool isUnsignedIntegerType() const;
1614
1615   /// Determines whether this is an integer type that is signed or an 
1616   /// enumeration types whose underlying type is a signed integer type.
1617   bool isSignedIntegerOrEnumerationType() const;
1618   
1619   /// Determines whether this is an integer type that is unsigned or an 
1620   /// enumeration types whose underlying type is a unsigned integer type.
1621   bool isUnsignedIntegerOrEnumerationType() const;
1622
1623   /// isConstantSizeType - Return true if this is not a variable sized type,
1624   /// according to the rules of C99 6.7.5p3.  It is not legal to call this on
1625   /// incomplete types.
1626   bool isConstantSizeType() const;
1627
1628   /// isSpecifierType - Returns true if this type can be represented by some
1629   /// set of type specifiers.
1630   bool isSpecifierType() const;
1631
1632   /// \brief Determine the linkage of this type.
1633   Linkage getLinkage() const;
1634
1635   /// \brief Determine the visibility of this type.
1636   Visibility getVisibility() const;
1637
1638   /// \brief Determine the linkage and visibility of this type.
1639   std::pair<Linkage,Visibility> getLinkageAndVisibility() const;
1640   
1641   /// \brief Note that the linkage is no longer known.
1642   void ClearLinkageCache();
1643   
1644   const char *getTypeClassName() const;
1645
1646   QualType getCanonicalTypeInternal() const {
1647     return CanonicalType;
1648   }
1649   CanQualType getCanonicalTypeUnqualified() const; // in CanonicalType.h
1650   void dump() const;
1651
1652   static bool classof(const Type *) { return true; }
1653
1654   friend class ASTReader;
1655   friend class ASTWriter;
1656 };
1657
1658 template <> inline const TypedefType *Type::getAs() const {
1659   return dyn_cast<TypedefType>(this);
1660 }
1661
1662 // We can do canonical leaf types faster, because we don't have to
1663 // worry about preserving child type decoration.
1664 #define TYPE(Class, Base)
1665 #define LEAF_TYPE(Class) \
1666 template <> inline const Class##Type *Type::getAs() const { \
1667   return dyn_cast<Class##Type>(CanonicalType); \
1668 } \
1669 template <> inline const Class##Type *Type::castAs() const { \
1670   return cast<Class##Type>(CanonicalType); \
1671 }
1672 #include "clang/AST/TypeNodes.def"
1673
1674
1675 /// BuiltinType - This class is used for builtin types like 'int'.  Builtin
1676 /// types are always canonical and have a literal name field.
1677 class BuiltinType : public Type {
1678 public:
1679   enum Kind {
1680     Void,
1681
1682     Bool,     // This is bool and/or _Bool.
1683     Char_U,   // This is 'char' for targets where char is unsigned.
1684     UChar,    // This is explicitly qualified unsigned char.
1685     WChar_U,  // This is 'wchar_t' for C++, when unsigned.
1686     Char16,   // This is 'char16_t' for C++.
1687     Char32,   // This is 'char32_t' for C++.
1688     UShort,
1689     UInt,
1690     ULong,
1691     ULongLong,
1692     UInt128,  // __uint128_t
1693
1694     Char_S,   // This is 'char' for targets where char is signed.
1695     SChar,    // This is explicitly qualified signed char.
1696     WChar_S,  // This is 'wchar_t' for C++, when signed.
1697     Short,
1698     Int,
1699     Long,
1700     LongLong,
1701     Int128,   // __int128_t
1702
1703     Half,     // This is the 'half' type in OpenCL,
1704               // __fp16 in case of ARM NEON.
1705     Float, Double, LongDouble,
1706
1707     NullPtr,  // This is the type of C++0x 'nullptr'.
1708
1709     /// The primitive Objective C 'id' type.  The user-visible 'id'
1710     /// type is a typedef of an ObjCObjectPointerType to an
1711     /// ObjCObjectType with this as its base.  In fact, this only ever
1712     /// shows up in an AST as the base type of an ObjCObjectType.
1713     ObjCId,
1714
1715     /// The primitive Objective C 'Class' type.  The user-visible
1716     /// 'Class' type is a typedef of an ObjCObjectPointerType to an
1717     /// ObjCObjectType with this as its base.  In fact, this only ever
1718     /// shows up in an AST as the base type of an ObjCObjectType.
1719     ObjCClass,
1720
1721     /// The primitive Objective C 'SEL' type.  The user-visible 'SEL'
1722     /// type is a typedef of a PointerType to this.
1723     ObjCSel,
1724
1725     /// This represents the type of an expression whose type is
1726     /// totally unknown, e.g. 'T::foo'.  It is permitted for this to
1727     /// appear in situations where the structure of the type is
1728     /// theoretically deducible.
1729     Dependent,
1730
1731     /// The type of an unresolved overload set.  A placeholder type.
1732     /// Expressions with this type have one of the following basic
1733     /// forms, with parentheses generally permitted:
1734     ///   foo          # possibly qualified, not if an implicit access
1735     ///   foo          # possibly qualified, not if an implicit access
1736     ///   &foo         # possibly qualified, not if an implicit access
1737     ///   x->foo       # only if might be a static member function
1738     ///   &x->foo      # only if might be a static member function
1739     ///   &Class::foo  # when a pointer-to-member; sub-expr also has this type
1740     /// OverloadExpr::find can be used to analyze the expression.
1741     Overload,
1742
1743     /// The type of a bound C++ non-static member function.
1744     /// A placeholder type.  Expressions with this type have one of the
1745     /// following basic forms:
1746     ///   foo          # if an implicit access
1747     ///   x->foo       # if only contains non-static members
1748     BoundMember,
1749
1750     /// __builtin_any_type.  A placeholder type.  Useful for clients
1751     /// like debuggers that don't know what type to give something.
1752     /// Only a small number of operations are valid on expressions of
1753     /// unknown type, most notably explicit casts.
1754     UnknownAny
1755   };
1756
1757 public:
1758   BuiltinType(Kind K)
1759     : Type(Builtin, QualType(), /*Dependent=*/(K == Dependent),
1760            /*InstantiationDependent=*/(K == Dependent),
1761            /*VariablyModified=*/false,
1762            /*Unexpanded paramter pack=*/false) {
1763     BuiltinTypeBits.Kind = K;
1764   }
1765
1766   Kind getKind() const { return static_cast<Kind>(BuiltinTypeBits.Kind); }
1767   const char *getName(const PrintingPolicy &Policy) const;
1768
1769   bool isSugared() const { return false; }
1770   QualType desugar() const { return QualType(this, 0); }
1771
1772   bool isInteger() const {
1773     return getKind() >= Bool && getKind() <= Int128;
1774   }
1775
1776   bool isSignedInteger() const {
1777     return getKind() >= Char_S && getKind() <= Int128;
1778   }
1779
1780   bool isUnsignedInteger() const {
1781     return getKind() >= Bool && getKind() <= UInt128;
1782   }
1783
1784   bool isFloatingPoint() const {
1785     return getKind() >= Half && getKind() <= LongDouble;
1786   }
1787
1788   /// Determines whether this type is a placeholder type, i.e. a type
1789   /// which cannot appear in arbitrary positions in a fully-formed
1790   /// expression.
1791   bool isPlaceholderType() const {
1792     return getKind() >= Overload;
1793   }
1794
1795   static bool classof(const Type *T) { return T->getTypeClass() == Builtin; }
1796   static bool classof(const BuiltinType *) { return true; }
1797 };
1798
1799 /// ComplexType - C99 6.2.5p11 - Complex values.  This supports the C99 complex
1800 /// types (_Complex float etc) as well as the GCC integer complex extensions.
1801 ///
1802 class ComplexType : public Type, public llvm::FoldingSetNode {
1803   QualType ElementType;
1804   ComplexType(QualType Element, QualType CanonicalPtr) :
1805     Type(Complex, CanonicalPtr, Element->isDependentType(),
1806          Element->isInstantiationDependentType(),
1807          Element->isVariablyModifiedType(),
1808          Element->containsUnexpandedParameterPack()),
1809     ElementType(Element) {
1810   }
1811   friend class ASTContext;  // ASTContext creates these.
1812
1813 public:
1814   QualType getElementType() const { return ElementType; }
1815
1816   bool isSugared() const { return false; }
1817   QualType desugar() const { return QualType(this, 0); }
1818
1819   void Profile(llvm::FoldingSetNodeID &ID) {
1820     Profile(ID, getElementType());
1821   }
1822   static void Profile(llvm::FoldingSetNodeID &ID, QualType Element) {
1823     ID.AddPointer(Element.getAsOpaquePtr());
1824   }
1825
1826   static bool classof(const Type *T) { return T->getTypeClass() == Complex; }
1827   static bool classof(const ComplexType *) { return true; }
1828 };
1829
1830 /// ParenType - Sugar for parentheses used when specifying types.
1831 ///
1832 class ParenType : public Type, public llvm::FoldingSetNode {
1833   QualType Inner;
1834
1835   ParenType(QualType InnerType, QualType CanonType) :
1836     Type(Paren, CanonType, InnerType->isDependentType(),
1837          InnerType->isInstantiationDependentType(),
1838          InnerType->isVariablyModifiedType(),
1839          InnerType->containsUnexpandedParameterPack()),
1840     Inner(InnerType) {
1841   }
1842   friend class ASTContext;  // ASTContext creates these.
1843
1844 public:
1845
1846   QualType getInnerType() const { return Inner; }
1847
1848   bool isSugared() const { return true; }
1849   QualType desugar() const { return getInnerType(); }
1850
1851   void Profile(llvm::FoldingSetNodeID &ID) {
1852     Profile(ID, getInnerType());
1853   }
1854   static void Profile(llvm::FoldingSetNodeID &ID, QualType Inner) {
1855     Inner.Profile(ID);
1856   }
1857
1858   static bool classof(const Type *T) { return T->getTypeClass() == Paren; }
1859   static bool classof(const ParenType *) { return true; }
1860 };
1861
1862 /// PointerType - C99 6.7.5.1 - Pointer Declarators.
1863 ///
1864 class PointerType : public Type, public llvm::FoldingSetNode {
1865   QualType PointeeType;
1866
1867   PointerType(QualType Pointee, QualType CanonicalPtr) :
1868     Type(Pointer, CanonicalPtr, Pointee->isDependentType(),
1869          Pointee->isInstantiationDependentType(),
1870          Pointee->isVariablyModifiedType(),
1871          Pointee->containsUnexpandedParameterPack()), 
1872     PointeeType(Pointee) {
1873   }
1874   friend class ASTContext;  // ASTContext creates these.
1875
1876 public:
1877
1878   QualType getPointeeType() const { return PointeeType; }
1879
1880   bool isSugared() const { return false; }
1881   QualType desugar() const { return QualType(this, 0); }
1882
1883   void Profile(llvm::FoldingSetNodeID &ID) {
1884     Profile(ID, getPointeeType());
1885   }
1886   static void Profile(llvm::FoldingSetNodeID &ID, QualType Pointee) {
1887     ID.AddPointer(Pointee.getAsOpaquePtr());
1888   }
1889
1890   static bool classof(const Type *T) { return T->getTypeClass() == Pointer; }
1891   static bool classof(const PointerType *) { return true; }
1892 };
1893
1894 /// BlockPointerType - pointer to a block type.
1895 /// This type is to represent types syntactically represented as
1896 /// "void (^)(int)", etc. Pointee is required to always be a function type.
1897 ///
1898 class BlockPointerType : public Type, public llvm::FoldingSetNode {
1899   QualType PointeeType;  // Block is some kind of pointer type
1900   BlockPointerType(QualType Pointee, QualType CanonicalCls) :
1901     Type(BlockPointer, CanonicalCls, Pointee->isDependentType(),
1902          Pointee->isInstantiationDependentType(),
1903          Pointee->isVariablyModifiedType(),
1904          Pointee->containsUnexpandedParameterPack()),
1905     PointeeType(Pointee) {
1906   }
1907   friend class ASTContext;  // ASTContext creates these.
1908   
1909 public:
1910
1911   // Get the pointee type. Pointee is required to always be a function type.
1912   QualType getPointeeType() const { return PointeeType; }
1913
1914   bool isSugared() const { return false; }
1915   QualType desugar() const { return QualType(this, 0); }
1916
1917   void Profile(llvm::FoldingSetNodeID &ID) {
1918       Profile(ID, getPointeeType());
1919   }
1920   static void Profile(llvm::FoldingSetNodeID &ID, QualType Pointee) {
1921       ID.AddPointer(Pointee.getAsOpaquePtr());
1922   }
1923
1924   static bool classof(const Type *T) {
1925     return T->getTypeClass() == BlockPointer;
1926   }
1927   static bool classof(const BlockPointerType *) { return true; }
1928 };
1929
1930 /// ReferenceType - Base for LValueReferenceType and RValueReferenceType
1931 ///
1932 class ReferenceType : public Type, public llvm::FoldingSetNode {
1933   QualType PointeeType;
1934
1935 protected:
1936   ReferenceType(TypeClass tc, QualType Referencee, QualType CanonicalRef,
1937                 bool SpelledAsLValue) :
1938     Type(tc, CanonicalRef, Referencee->isDependentType(),
1939          Referencee->isInstantiationDependentType(),
1940          Referencee->isVariablyModifiedType(),
1941          Referencee->containsUnexpandedParameterPack()), 
1942     PointeeType(Referencee) 
1943   {
1944     ReferenceTypeBits.SpelledAsLValue = SpelledAsLValue;
1945     ReferenceTypeBits.InnerRef = Referencee->isReferenceType();
1946   }
1947   
1948 public:
1949   bool isSpelledAsLValue() const { return ReferenceTypeBits.SpelledAsLValue; }
1950   bool isInnerRef() const { return ReferenceTypeBits.InnerRef; }
1951   
1952   QualType getPointeeTypeAsWritten() const { return PointeeType; }
1953   QualType getPointeeType() const {
1954     // FIXME: this might strip inner qualifiers; okay?
1955     const ReferenceType *T = this;
1956     while (T->isInnerRef())
1957       T = T->PointeeType->castAs<ReferenceType>();
1958     return T->PointeeType;
1959   }
1960
1961   void Profile(llvm::FoldingSetNodeID &ID) {
1962     Profile(ID, PointeeType, isSpelledAsLValue());
1963   }
1964   static void Profile(llvm::FoldingSetNodeID &ID,
1965                       QualType Referencee,
1966                       bool SpelledAsLValue) {
1967     ID.AddPointer(Referencee.getAsOpaquePtr());
1968     ID.AddBoolean(SpelledAsLValue);
1969   }
1970
1971   static bool classof(const Type *T) {
1972     return T->getTypeClass() == LValueReference ||
1973            T->getTypeClass() == RValueReference;
1974   }
1975   static bool classof(const ReferenceType *) { return true; }
1976 };
1977
1978 /// LValueReferenceType - C++ [dcl.ref] - Lvalue reference
1979 ///
1980 class LValueReferenceType : public ReferenceType {
1981   LValueReferenceType(QualType Referencee, QualType CanonicalRef,
1982                       bool SpelledAsLValue) :
1983     ReferenceType(LValueReference, Referencee, CanonicalRef, SpelledAsLValue)
1984   {}
1985   friend class ASTContext; // ASTContext creates these
1986 public:
1987   bool isSugared() const { return false; }
1988   QualType desugar() const { return QualType(this, 0); }
1989
1990   static bool classof(const Type *T) {
1991     return T->getTypeClass() == LValueReference;
1992   }
1993   static bool classof(const LValueReferenceType *) { return true; }
1994 };
1995
1996 /// RValueReferenceType - C++0x [dcl.ref] - Rvalue reference
1997 ///
1998 class RValueReferenceType : public ReferenceType {
1999   RValueReferenceType(QualType Referencee, QualType CanonicalRef) :
2000     ReferenceType(RValueReference, Referencee, CanonicalRef, false) {
2001   }
2002   friend class ASTContext; // ASTContext creates these
2003 public:
2004   bool isSugared() const { return false; }
2005   QualType desugar() const { return QualType(this, 0); }
2006
2007   static bool classof(const Type *T) {
2008     return T->getTypeClass() == RValueReference;
2009   }
2010   static bool classof(const RValueReferenceType *) { return true; }
2011 };
2012
2013 /// MemberPointerType - C++ 8.3.3 - Pointers to members
2014 ///
2015 class MemberPointerType : public Type, public llvm::FoldingSetNode {
2016   QualType PointeeType;
2017   /// The class of which the pointee is a member. Must ultimately be a
2018   /// RecordType, but could be a typedef or a template parameter too.
2019   const Type *Class;
2020
2021   MemberPointerType(QualType Pointee, const Type *Cls, QualType CanonicalPtr) :
2022     Type(MemberPointer, CanonicalPtr,
2023          Cls->isDependentType() || Pointee->isDependentType(),
2024          (Cls->isInstantiationDependentType() || 
2025           Pointee->isInstantiationDependentType()),
2026          Pointee->isVariablyModifiedType(),
2027          (Cls->containsUnexpandedParameterPack() || 
2028           Pointee->containsUnexpandedParameterPack())),
2029     PointeeType(Pointee), Class(Cls) {
2030   }
2031   friend class ASTContext; // ASTContext creates these.
2032   
2033 public:
2034   QualType getPointeeType() const { return PointeeType; }
2035
2036   /// Returns true if the member type (i.e. the pointee type) is a
2037   /// function type rather than a data-member type.
2038   bool isMemberFunctionPointer() const {
2039     return PointeeType->isFunctionProtoType();
2040   }
2041
2042   /// Returns true if the member type (i.e. the pointee type) is a
2043   /// data type rather than a function type.
2044   bool isMemberDataPointer() const {
2045     return !PointeeType->isFunctionProtoType();
2046   }
2047
2048   const Type *getClass() const { return Class; }
2049
2050   bool isSugared() const { return false; }
2051   QualType desugar() const { return QualType(this, 0); }
2052
2053   void Profile(llvm::FoldingSetNodeID &ID) {
2054     Profile(ID, getPointeeType(), getClass());
2055   }
2056   static void Profile(llvm::FoldingSetNodeID &ID, QualType Pointee,
2057                       const Type *Class) {
2058     ID.AddPointer(Pointee.getAsOpaquePtr());
2059     ID.AddPointer(Class);
2060   }
2061
2062   static bool classof(const Type *T) {
2063     return T->getTypeClass() == MemberPointer;
2064   }
2065   static bool classof(const MemberPointerType *) { return true; }
2066 };
2067
2068 /// ArrayType - C99 6.7.5.2 - Array Declarators.
2069 ///
2070 class ArrayType : public Type, public llvm::FoldingSetNode {
2071 public:
2072   /// ArraySizeModifier - Capture whether this is a normal array (e.g. int X[4])
2073   /// an array with a static size (e.g. int X[static 4]), or an array
2074   /// with a star size (e.g. int X[*]).
2075   /// 'static' is only allowed on function parameters.
2076   enum ArraySizeModifier {
2077     Normal, Static, Star
2078   };
2079 private:
2080   /// ElementType - The element type of the array.
2081   QualType ElementType;
2082
2083 protected:
2084   // C++ [temp.dep.type]p1:
2085   //   A type is dependent if it is...
2086   //     - an array type constructed from any dependent type or whose
2087   //       size is specified by a constant expression that is
2088   //       value-dependent,
2089   ArrayType(TypeClass tc, QualType et, QualType can,
2090             ArraySizeModifier sm, unsigned tq,
2091             bool ContainsUnexpandedParameterPack)
2092     : Type(tc, can, et->isDependentType() || tc == DependentSizedArray,
2093            et->isInstantiationDependentType() || tc == DependentSizedArray,
2094            (tc == VariableArray || et->isVariablyModifiedType()),
2095            ContainsUnexpandedParameterPack),
2096       ElementType(et) {
2097     ArrayTypeBits.IndexTypeQuals = tq;
2098     ArrayTypeBits.SizeModifier = sm;
2099   }
2100
2101   friend class ASTContext;  // ASTContext creates these.
2102
2103 public:
2104   QualType getElementType() const { return ElementType; }
2105   ArraySizeModifier getSizeModifier() const {
2106     return ArraySizeModifier(ArrayTypeBits.SizeModifier);
2107   }
2108   Qualifiers getIndexTypeQualifiers() const {
2109     return Qualifiers::fromCVRMask(getIndexTypeCVRQualifiers());
2110   }
2111   unsigned getIndexTypeCVRQualifiers() const {
2112     return ArrayTypeBits.IndexTypeQuals;
2113   }
2114
2115   static bool classof(const Type *T) {
2116     return T->getTypeClass() == ConstantArray ||
2117            T->getTypeClass() == VariableArray ||
2118            T->getTypeClass() == IncompleteArray ||
2119            T->getTypeClass() == DependentSizedArray;
2120   }
2121   static bool classof(const ArrayType *) { return true; }
2122 };
2123
2124 /// ConstantArrayType - This class represents the canonical version of
2125 /// C arrays with a specified constant size.  For example, the canonical
2126 /// type for 'int A[4 + 4*100]' is a ConstantArrayType where the element
2127 /// type is 'int' and the size is 404.
2128 class ConstantArrayType : public ArrayType {
2129   llvm::APInt Size; // Allows us to unique the type.
2130
2131   ConstantArrayType(QualType et, QualType can, const llvm::APInt &size,
2132                     ArraySizeModifier sm, unsigned tq)
2133     : ArrayType(ConstantArray, et, can, sm, tq,
2134                 et->containsUnexpandedParameterPack()),
2135       Size(size) {}
2136 protected:
2137   ConstantArrayType(TypeClass tc, QualType et, QualType can,
2138                     const llvm::APInt &size, ArraySizeModifier sm, unsigned tq)
2139     : ArrayType(tc, et, can, sm, tq, et->containsUnexpandedParameterPack()), 
2140       Size(size) {}
2141   friend class ASTContext;  // ASTContext creates these.
2142 public:
2143   const llvm::APInt &getSize() const { return Size; }
2144   bool isSugared() const { return false; }
2145   QualType desugar() const { return QualType(this, 0); }
2146
2147   
2148   /// \brief Determine the number of bits required to address a member of
2149   // an array with the given element type and number of elements.
2150   static unsigned getNumAddressingBits(ASTContext &Context,
2151                                        QualType ElementType,
2152                                        const llvm::APInt &NumElements);
2153   
2154   /// \brief Determine the maximum number of active bits that an array's size
2155   /// can require, which limits the maximum size of the array.
2156   static unsigned getMaxSizeBits(ASTContext &Context);
2157   
2158   void Profile(llvm::FoldingSetNodeID &ID) {
2159     Profile(ID, getElementType(), getSize(),
2160             getSizeModifier(), getIndexTypeCVRQualifiers());
2161   }
2162   static void Profile(llvm::FoldingSetNodeID &ID, QualType ET,
2163                       const llvm::APInt &ArraySize, ArraySizeModifier SizeMod,
2164                       unsigned TypeQuals) {
2165     ID.AddPointer(ET.getAsOpaquePtr());
2166     ID.AddInteger(ArraySize.getZExtValue());
2167     ID.AddInteger(SizeMod);
2168     ID.AddInteger(TypeQuals);
2169   }
2170   static bool classof(const Type *T) {
2171     return T->getTypeClass() == ConstantArray;
2172   }
2173   static bool classof(const ConstantArrayType *) { return true; }
2174 };
2175
2176 /// IncompleteArrayType - This class represents C arrays with an unspecified
2177 /// size.  For example 'int A[]' has an IncompleteArrayType where the element
2178 /// type is 'int' and the size is unspecified.
2179 class IncompleteArrayType : public ArrayType {
2180
2181   IncompleteArrayType(QualType et, QualType can,
2182                       ArraySizeModifier sm, unsigned tq)
2183     : ArrayType(IncompleteArray, et, can, sm, tq, 
2184                 et->containsUnexpandedParameterPack()) {}
2185   friend class ASTContext;  // ASTContext creates these.
2186 public:
2187   bool isSugared() const { return false; }
2188   QualType desugar() const { return QualType(this, 0); }
2189
2190   static bool classof(const Type *T) {
2191     return T->getTypeClass() == IncompleteArray;
2192   }
2193   static bool classof(const IncompleteArrayType *) { return true; }
2194
2195   friend class StmtIteratorBase;
2196
2197   void Profile(llvm::FoldingSetNodeID &ID) {
2198     Profile(ID, getElementType(), getSizeModifier(),
2199             getIndexTypeCVRQualifiers());
2200   }
2201
2202   static void Profile(llvm::FoldingSetNodeID &ID, QualType ET,
2203                       ArraySizeModifier SizeMod, unsigned TypeQuals) {
2204     ID.AddPointer(ET.getAsOpaquePtr());
2205     ID.AddInteger(SizeMod);
2206     ID.AddInteger(TypeQuals);
2207   }
2208 };
2209
2210 /// VariableArrayType - This class represents C arrays with a specified size
2211 /// which is not an integer-constant-expression.  For example, 'int s[x+foo()]'.
2212 /// Since the size expression is an arbitrary expression, we store it as such.
2213 ///
2214 /// Note: VariableArrayType's aren't uniqued (since the expressions aren't) and
2215 /// should not be: two lexically equivalent variable array types could mean
2216 /// different things, for example, these variables do not have the same type
2217 /// dynamically:
2218 ///
2219 /// void foo(int x) {
2220 ///   int Y[x];
2221 ///   ++x;
2222 ///   int Z[x];
2223 /// }
2224 ///
2225 class VariableArrayType : public ArrayType {
2226   /// SizeExpr - An assignment expression. VLA's are only permitted within
2227   /// a function block.
2228   Stmt *SizeExpr;
2229   /// Brackets - The left and right array brackets.
2230   SourceRange Brackets;
2231
2232   VariableArrayType(QualType et, QualType can, Expr *e,
2233                     ArraySizeModifier sm, unsigned tq,
2234                     SourceRange brackets)
2235     : ArrayType(VariableArray, et, can, sm, tq, 
2236                 et->containsUnexpandedParameterPack()),
2237       SizeExpr((Stmt*) e), Brackets(brackets) {}
2238   friend class ASTContext;  // ASTContext creates these.
2239
2240 public:
2241   Expr *getSizeExpr() const {
2242     // We use C-style casts instead of cast<> here because we do not wish
2243     // to have a dependency of Type.h on Stmt.h/Expr.h.
2244     return (Expr*) SizeExpr;
2245   }
2246   SourceRange getBracketsRange() const { return Brackets; }
2247   SourceLocation getLBracketLoc() const { return Brackets.getBegin(); }
2248   SourceLocation getRBracketLoc() const { return Brackets.getEnd(); }
2249
2250   bool isSugared() const { return false; }
2251   QualType desugar() const { return QualType(this, 0); }
2252
2253   static bool classof(const Type *T) {
2254     return T->getTypeClass() == VariableArray;
2255   }
2256   static bool classof(const VariableArrayType *) { return true; }
2257
2258   friend class StmtIteratorBase;
2259
2260   void Profile(llvm::FoldingSetNodeID &ID) {
2261     llvm_unreachable("Cannot unique VariableArrayTypes.");
2262   }
2263 };
2264
2265 /// DependentSizedArrayType - This type represents an array type in
2266 /// C++ whose size is a value-dependent expression. For example:
2267 ///
2268 /// \code
2269 /// template<typename T, int Size>
2270 /// class array {
2271 ///   T data[Size];
2272 /// };
2273 /// \endcode
2274 ///
2275 /// For these types, we won't actually know what the array bound is
2276 /// until template instantiation occurs, at which point this will
2277 /// become either a ConstantArrayType or a VariableArrayType.
2278 class DependentSizedArrayType : public ArrayType {
2279   const ASTContext &Context;
2280
2281   /// \brief An assignment expression that will instantiate to the
2282   /// size of the array.
2283   ///
2284   /// The expression itself might be NULL, in which case the array
2285   /// type will have its size deduced from an initializer.
2286   Stmt *SizeExpr;
2287
2288   /// Brackets - The left and right array brackets.
2289   SourceRange Brackets;
2290
2291   DependentSizedArrayType(const ASTContext &Context, QualType et, QualType can,
2292                           Expr *e, ArraySizeModifier sm, unsigned tq,
2293                           SourceRange brackets);
2294
2295   friend class ASTContext;  // ASTContext creates these.
2296
2297 public:
2298   Expr *getSizeExpr() const {
2299     // We use C-style casts instead of cast<> here because we do not wish
2300     // to have a dependency of Type.h on Stmt.h/Expr.h.
2301     return (Expr*) SizeExpr;
2302   }
2303   SourceRange getBracketsRange() const { return Brackets; }
2304   SourceLocation getLBracketLoc() const { return Brackets.getBegin(); }
2305   SourceLocation getRBracketLoc() const { return Brackets.getEnd(); }
2306
2307   bool isSugared() const { return false; }
2308   QualType desugar() const { return QualType(this, 0); }
2309
2310   static bool classof(const Type *T) {
2311     return T->getTypeClass() == DependentSizedArray;
2312   }
2313   static bool classof(const DependentSizedArrayType *) { return true; }
2314
2315   friend class StmtIteratorBase;
2316
2317
2318   void Profile(llvm::FoldingSetNodeID &ID) {
2319     Profile(ID, Context, getElementType(),
2320             getSizeModifier(), getIndexTypeCVRQualifiers(), getSizeExpr());
2321   }
2322
2323   static void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context,
2324                       QualType ET, ArraySizeModifier SizeMod,
2325                       unsigned TypeQuals, Expr *E);
2326 };
2327
2328 /// DependentSizedExtVectorType - This type represent an extended vector type
2329 /// where either the type or size is dependent. For example:
2330 /// @code
2331 /// template<typename T, int Size>
2332 /// class vector {
2333 ///   typedef T __attribute__((ext_vector_type(Size))) type;
2334 /// }
2335 /// @endcode
2336 class DependentSizedExtVectorType : public Type, public llvm::FoldingSetNode {
2337   const ASTContext &Context;
2338   Expr *SizeExpr;
2339   /// ElementType - The element type of the array.
2340   QualType ElementType;
2341   SourceLocation loc;
2342
2343   DependentSizedExtVectorType(const ASTContext &Context, QualType ElementType,
2344                               QualType can, Expr *SizeExpr, SourceLocation loc);
2345
2346   friend class ASTContext;
2347
2348 public:
2349   Expr *getSizeExpr() const { return SizeExpr; }
2350   QualType getElementType() const { return ElementType; }
2351   SourceLocation getAttributeLoc() const { return loc; }
2352
2353   bool isSugared() const { return false; }
2354   QualType desugar() const { return QualType(this, 0); }
2355
2356   static bool classof(const Type *T) {
2357     return T->getTypeClass() == DependentSizedExtVector;
2358   }
2359   static bool classof(const DependentSizedExtVectorType *) { return true; }
2360
2361   void Profile(llvm::FoldingSetNodeID &ID) {
2362     Profile(ID, Context, getElementType(), getSizeExpr());
2363   }
2364
2365   static void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context,
2366                       QualType ElementType, Expr *SizeExpr);
2367 };
2368
2369
2370 /// VectorType - GCC generic vector type. This type is created using
2371 /// __attribute__((vector_size(n)), where "n" specifies the vector size in
2372 /// bytes; or from an Altivec __vector or vector declaration.
2373 /// Since the constructor takes the number of vector elements, the
2374 /// client is responsible for converting the size into the number of elements.
2375 class VectorType : public Type, public llvm::FoldingSetNode {
2376 public:
2377   enum VectorKind {
2378     GenericVector,  // not a target-specific vector type
2379     AltiVecVector,  // is AltiVec vector
2380     AltiVecPixel,   // is AltiVec 'vector Pixel'
2381     AltiVecBool,    // is AltiVec 'vector bool ...'
2382     NeonVector,     // is ARM Neon vector
2383     NeonPolyVector  // is ARM Neon polynomial vector
2384   };
2385 protected:
2386   /// ElementType - The element type of the vector.
2387   QualType ElementType;
2388
2389   VectorType(QualType vecType, unsigned nElements, QualType canonType,
2390              VectorKind vecKind);
2391   
2392   VectorType(TypeClass tc, QualType vecType, unsigned nElements,
2393              QualType canonType, VectorKind vecKind);
2394
2395   friend class ASTContext;  // ASTContext creates these.
2396   
2397 public:
2398
2399   QualType getElementType() const { return ElementType; }
2400   unsigned getNumElements() const { return VectorTypeBits.NumElements; }
2401
2402   bool isSugared() const { return false; }
2403   QualType desugar() const { return QualType(this, 0); }
2404
2405   VectorKind getVectorKind() const {
2406     return VectorKind(VectorTypeBits.VecKind);
2407   }
2408
2409   void Profile(llvm::FoldingSetNodeID &ID) {
2410     Profile(ID, getElementType(), getNumElements(),
2411             getTypeClass(), getVectorKind());
2412   }
2413   static void Profile(llvm::FoldingSetNodeID &ID, QualType ElementType,
2414                       unsigned NumElements, TypeClass TypeClass,
2415                       VectorKind VecKind) {
2416     ID.AddPointer(ElementType.getAsOpaquePtr());
2417     ID.AddInteger(NumElements);
2418     ID.AddInteger(TypeClass);
2419     ID.AddInteger(VecKind);
2420   }
2421
2422   static bool classof(const Type *T) {
2423     return T->getTypeClass() == Vector || T->getTypeClass() == ExtVector;
2424   }
2425   static bool classof(const VectorType *) { return true; }
2426 };
2427
2428 /// ExtVectorType - Extended vector type. This type is created using
2429 /// __attribute__((ext_vector_type(n)), where "n" is the number of elements.
2430 /// Unlike vector_size, ext_vector_type is only allowed on typedef's. This
2431 /// class enables syntactic extensions, like Vector Components for accessing
2432 /// points, colors, and textures (modeled after OpenGL Shading Language).
2433 class ExtVectorType : public VectorType {
2434   ExtVectorType(QualType vecType, unsigned nElements, QualType canonType) :
2435     VectorType(ExtVector, vecType, nElements, canonType, GenericVector) {}
2436   friend class ASTContext;  // ASTContext creates these.
2437 public:
2438   static int getPointAccessorIdx(char c) {
2439     switch (c) {
2440     default: return -1;
2441     case 'x': return 0;
2442     case 'y': return 1;
2443     case 'z': return 2;
2444     case 'w': return 3;
2445     }
2446   }
2447   static int getNumericAccessorIdx(char c) {
2448     switch (c) {
2449       default: return -1;
2450       case '0': return 0;
2451       case '1': return 1;
2452       case '2': return 2;
2453       case '3': return 3;
2454       case '4': return 4;
2455       case '5': return 5;
2456       case '6': return 6;
2457       case '7': return 7;
2458       case '8': return 8;
2459       case '9': return 9;
2460       case 'A':
2461       case 'a': return 10;
2462       case 'B':
2463       case 'b': return 11;
2464       case 'C':
2465       case 'c': return 12;
2466       case 'D':
2467       case 'd': return 13;
2468       case 'E':
2469       case 'e': return 14;
2470       case 'F':
2471       case 'f': return 15;
2472     }
2473   }
2474
2475   static int getAccessorIdx(char c) {
2476     if (int idx = getPointAccessorIdx(c)+1) return idx-1;
2477     return getNumericAccessorIdx(c);
2478   }
2479
2480   bool isAccessorWithinNumElements(char c) const {
2481     if (int idx = getAccessorIdx(c)+1)
2482       return unsigned(idx-1) < getNumElements();
2483     return false;
2484   }
2485   bool isSugared() const { return false; }
2486   QualType desugar() const { return QualType(this, 0); }
2487
2488   static bool classof(const Type *T) {
2489     return T->getTypeClass() == ExtVector;
2490   }
2491   static bool classof(const ExtVectorType *) { return true; }
2492 };
2493
2494 /// FunctionType - C99 6.7.5.3 - Function Declarators.  This is the common base
2495 /// class of FunctionNoProtoType and FunctionProtoType.
2496 ///
2497 class FunctionType : public Type {
2498   // The type returned by the function.
2499   QualType ResultType;
2500
2501  public:
2502   /// ExtInfo - A class which abstracts out some details necessary for
2503   /// making a call.
2504   ///
2505   /// It is not actually used directly for storing this information in
2506   /// a FunctionType, although FunctionType does currently use the
2507   /// same bit-pattern.
2508   ///
2509   // If you add a field (say Foo), other than the obvious places (both,
2510   // constructors, compile failures), what you need to update is
2511   // * Operator==
2512   // * getFoo
2513   // * withFoo
2514   // * functionType. Add Foo, getFoo.
2515   // * ASTContext::getFooType
2516   // * ASTContext::mergeFunctionTypes
2517   // * FunctionNoProtoType::Profile
2518   // * FunctionProtoType::Profile
2519   // * TypePrinter::PrintFunctionProto
2520   // * AST read and write
2521   // * Codegen
2522   class ExtInfo {
2523     // Feel free to rearrange or add bits, but if you go over 8,
2524     // you'll need to adjust both the Bits field below and
2525     // Type::FunctionTypeBitfields.
2526
2527     //   |  CC  |noreturn|produces|regparm|
2528     //   |0 .. 2|   3    |    4   | 5 .. 7|
2529     //
2530     // regparm is either 0 (no regparm attribute) or the regparm value+1.
2531     enum { CallConvMask = 0x7 };
2532     enum { NoReturnMask = 0x8 };
2533     enum { ProducesResultMask = 0x10 };
2534     enum { RegParmMask = ~(CallConvMask | NoReturnMask | ProducesResultMask),
2535            RegParmOffset = 5 }; // Assumed to be the last field
2536
2537     uint16_t Bits;
2538
2539     ExtInfo(unsigned Bits) : Bits(static_cast<uint16_t>(Bits)) {}
2540
2541     friend class FunctionType;
2542
2543    public:
2544     // Constructor with no defaults. Use this when you know that you
2545     // have all the elements (when reading an AST file for example).
2546     ExtInfo(bool noReturn, bool hasRegParm, unsigned regParm, CallingConv cc,
2547             bool producesResult) {
2548       assert((!hasRegParm || regParm < 7) && "Invalid regparm value");
2549       Bits = ((unsigned) cc) |
2550              (noReturn ? NoReturnMask : 0) |
2551              (producesResult ? ProducesResultMask : 0) |
2552              (hasRegParm ? ((regParm + 1) << RegParmOffset) : 0);
2553     }
2554
2555     // Constructor with all defaults. Use when for example creating a
2556     // function know to use defaults.
2557     ExtInfo() : Bits(0) {}
2558
2559     bool getNoReturn() const { return Bits & NoReturnMask; }
2560     bool getProducesResult() const { return Bits & ProducesResultMask; }
2561     bool getHasRegParm() const { return (Bits >> RegParmOffset) != 0; }
2562     unsigned getRegParm() const { 
2563       unsigned RegParm = Bits >> RegParmOffset;
2564       if (RegParm > 0)
2565         --RegParm;
2566       return RegParm;
2567     }
2568     CallingConv getCC() const { return CallingConv(Bits & CallConvMask); }
2569
2570     bool operator==(ExtInfo Other) const {
2571       return Bits == Other.Bits;
2572     }
2573     bool operator!=(ExtInfo Other) const {
2574       return Bits != Other.Bits;
2575     }
2576
2577     // Note that we don't have setters. That is by design, use
2578     // the following with methods instead of mutating these objects.
2579
2580     ExtInfo withNoReturn(bool noReturn) const {
2581       if (noReturn)
2582         return ExtInfo(Bits | NoReturnMask);
2583       else
2584         return ExtInfo(Bits & ~NoReturnMask);
2585     }
2586
2587     ExtInfo withProducesResult(bool producesResult) const {
2588       if (producesResult)
2589         return ExtInfo(Bits | ProducesResultMask);
2590       else
2591         return ExtInfo(Bits & ~ProducesResultMask);
2592     }
2593
2594     ExtInfo withRegParm(unsigned RegParm) const {
2595       assert(RegParm < 7 && "Invalid regparm value");
2596       return ExtInfo((Bits & ~RegParmMask) |
2597                      ((RegParm + 1) << RegParmOffset));
2598     }
2599
2600     ExtInfo withCallingConv(CallingConv cc) const {
2601       return ExtInfo((Bits & ~CallConvMask) | (unsigned) cc);
2602     }
2603
2604     void Profile(llvm::FoldingSetNodeID &ID) const {
2605       ID.AddInteger(Bits);
2606     }
2607   };
2608
2609 protected:
2610   FunctionType(TypeClass tc, QualType res, bool variadic,
2611                unsigned typeQuals, RefQualifierKind RefQualifier,
2612                QualType Canonical, bool Dependent,
2613                bool InstantiationDependent,
2614                bool VariablyModified, bool ContainsUnexpandedParameterPack, 
2615                ExtInfo Info)
2616     : Type(tc, Canonical, Dependent, InstantiationDependent, VariablyModified, 
2617            ContainsUnexpandedParameterPack), 
2618       ResultType(res) {
2619     FunctionTypeBits.ExtInfo = Info.Bits;
2620     FunctionTypeBits.Variadic = variadic;
2621     FunctionTypeBits.TypeQuals = typeQuals;
2622     FunctionTypeBits.RefQualifier = static_cast<unsigned>(RefQualifier);
2623   }
2624   bool isVariadic() const { return FunctionTypeBits.Variadic; }
2625   unsigned getTypeQuals() const { return FunctionTypeBits.TypeQuals; }
2626   
2627   RefQualifierKind getRefQualifier() const {
2628     return static_cast<RefQualifierKind>(FunctionTypeBits.RefQualifier);
2629   }
2630
2631 public:
2632
2633   QualType getResultType() const { return ResultType; }
2634
2635   bool getHasRegParm() const { return getExtInfo().getHasRegParm(); }
2636   unsigned getRegParmType() const { return getExtInfo().getRegParm(); }
2637   bool getNoReturnAttr() const { return getExtInfo().getNoReturn(); }
2638   CallingConv getCallConv() const { return getExtInfo().getCC(); }
2639   ExtInfo getExtInfo() const { return ExtInfo(FunctionTypeBits.ExtInfo); }
2640
2641   /// \brief Determine the type of an expression that calls a function of
2642   /// this type.
2643   QualType getCallResultType(ASTContext &Context) const { 
2644     return getResultType().getNonLValueExprType(Context);
2645   }
2646
2647   static StringRef getNameForCallConv(CallingConv CC);
2648
2649   static bool classof(const Type *T) {
2650     return T->getTypeClass() == FunctionNoProto ||
2651            T->getTypeClass() == FunctionProto;
2652   }
2653   static bool classof(const FunctionType *) { return true; }
2654 };
2655
2656 /// FunctionNoProtoType - Represents a K&R-style 'int foo()' function, which has
2657 /// no information available about its arguments.
2658 class FunctionNoProtoType : public FunctionType, public llvm::FoldingSetNode {
2659   FunctionNoProtoType(QualType Result, QualType Canonical, ExtInfo Info)
2660     : FunctionType(FunctionNoProto, Result, false, 0, RQ_None, Canonical,
2661                    /*Dependent=*/false, /*InstantiationDependent=*/false,
2662                    Result->isVariablyModifiedType(), 
2663                    /*ContainsUnexpandedParameterPack=*/false, Info) {}
2664
2665   friend class ASTContext;  // ASTContext creates these.
2666   
2667 public:
2668   // No additional state past what FunctionType provides.
2669
2670   bool isSugared() const { return false; }
2671   QualType desugar() const { return QualType(this, 0); }
2672
2673   void Profile(llvm::FoldingSetNodeID &ID) {
2674     Profile(ID, getResultType(), getExtInfo());
2675   }
2676   static void Profile(llvm::FoldingSetNodeID &ID, QualType ResultType,
2677                       ExtInfo Info) {
2678     Info.Profile(ID);
2679     ID.AddPointer(ResultType.getAsOpaquePtr());
2680   }
2681
2682   static bool classof(const Type *T) {
2683     return T->getTypeClass() == FunctionNoProto;
2684   }
2685   static bool classof(const FunctionNoProtoType *) { return true; }
2686 };
2687
2688 /// FunctionProtoType - Represents a prototype with argument type info, e.g.
2689 /// 'int foo(int)' or 'int foo(void)'.  'void' is represented as having no
2690 /// arguments, not as having a single void argument. Such a type can have an
2691 /// exception specification, but this specification is not part of the canonical
2692 /// type.
2693 class FunctionProtoType : public FunctionType, public llvm::FoldingSetNode {
2694 public:
2695   /// ExtProtoInfo - Extra information about a function prototype.
2696   struct ExtProtoInfo {
2697     ExtProtoInfo() :
2698       Variadic(false), ExceptionSpecType(EST_None), TypeQuals(0),
2699       RefQualifier(RQ_None), NumExceptions(0), Exceptions(0), NoexceptExpr(0),
2700       ConsumedArguments(0) {}
2701
2702     FunctionType::ExtInfo ExtInfo;
2703     bool Variadic;
2704     ExceptionSpecificationType ExceptionSpecType;
2705     unsigned char TypeQuals;
2706     RefQualifierKind RefQualifier;
2707     unsigned NumExceptions;
2708
2709     /// Exceptions - A variable size array after that holds the exception types.
2710     const QualType *Exceptions;
2711
2712     /// NoexceptExpr - Instead of Exceptions, there may be a single Expr*
2713     /// pointing to the expression in the noexcept() specifier.
2714     Expr *NoexceptExpr;
2715     
2716     /// ConsumedArgs - A variable size array, following Exceptions
2717     /// and of length NumArgs, holding flags indicating which arguments
2718     /// are consumed.  This only appears if HasAnyConsumedArgs is true.
2719     const bool *ConsumedArguments;
2720   };
2721
2722 private:
2723   /// \brief Determine whether there are any argument types that
2724   /// contain an unexpanded parameter pack.
2725   static bool containsAnyUnexpandedParameterPack(const QualType *ArgArray, 
2726                                                  unsigned numArgs) {
2727     for (unsigned Idx = 0; Idx < numArgs; ++Idx)
2728       if (ArgArray[Idx]->containsUnexpandedParameterPack())
2729         return true;
2730
2731     return false;
2732   }
2733
2734   FunctionProtoType(QualType result, const QualType *args, unsigned numArgs,
2735                     QualType canonical, const ExtProtoInfo &epi);
2736
2737   /// NumArgs - The number of arguments this function has, not counting '...'.
2738   unsigned NumArgs : 19;
2739
2740   /// NumExceptions - The number of types in the exception spec, if any.
2741   unsigned NumExceptions : 9;
2742
2743   /// ExceptionSpecType - The type of exception specification this function has.
2744   unsigned ExceptionSpecType : 3;
2745
2746   /// HasAnyConsumedArgs - Whether this function has any consumed arguments.
2747   unsigned HasAnyConsumedArgs : 1;
2748
2749   friend class ASTContext;  // ASTContext creates these.
2750
2751   const bool *getConsumedArgsBuffer() const {
2752     assert(hasAnyConsumedArgs());
2753
2754     // Find the end of the exceptions.
2755     Expr * const *eh_end = reinterpret_cast<Expr * const *>(arg_type_end());
2756     if (getExceptionSpecType() != EST_ComputedNoexcept)
2757       eh_end += NumExceptions;
2758     else
2759       eh_end += 1; // NoexceptExpr
2760
2761     return reinterpret_cast<const bool*>(eh_end);
2762   }
2763
2764 public:
2765   unsigned getNumArgs() const { return NumArgs; }
2766   QualType getArgType(unsigned i) const {
2767     assert(i < NumArgs && "Invalid argument number!");
2768     return arg_type_begin()[i];
2769   }
2770
2771   ExtProtoInfo getExtProtoInfo() const {
2772     ExtProtoInfo EPI;
2773     EPI.ExtInfo = getExtInfo();
2774     EPI.Variadic = isVariadic();
2775     EPI.ExceptionSpecType = getExceptionSpecType();
2776     EPI.TypeQuals = static_cast<unsigned char>(getTypeQuals());
2777     EPI.RefQualifier = getRefQualifier();
2778     if (EPI.ExceptionSpecType == EST_Dynamic) {
2779       EPI.NumExceptions = NumExceptions;
2780       EPI.Exceptions = exception_begin();
2781     } else if (EPI.ExceptionSpecType == EST_ComputedNoexcept) {
2782       EPI.NoexceptExpr = getNoexceptExpr();
2783     }
2784     if (hasAnyConsumedArgs())
2785       EPI.ConsumedArguments = getConsumedArgsBuffer();
2786     return EPI;
2787   }
2788
2789   /// \brief Get the kind of exception specification on this function.
2790   ExceptionSpecificationType getExceptionSpecType() const {
2791     return static_cast<ExceptionSpecificationType>(ExceptionSpecType);
2792   }
2793   /// \brief Return whether this function has any kind of exception spec.
2794   bool hasExceptionSpec() const {
2795     return getExceptionSpecType() != EST_None;
2796   }
2797   /// \brief Return whether this function has a dynamic (throw) exception spec.
2798   bool hasDynamicExceptionSpec() const {
2799     return isDynamicExceptionSpec(getExceptionSpecType());
2800   }
2801   /// \brief Return whether this function has a noexcept exception spec.
2802   bool hasNoexceptExceptionSpec() const {
2803     return isNoexceptExceptionSpec(getExceptionSpecType());
2804   }
2805   /// \brief Result type of getNoexceptSpec().
2806   enum NoexceptResult {
2807     NR_NoNoexcept,  ///< There is no noexcept specifier.
2808     NR_BadNoexcept, ///< The noexcept specifier has a bad expression.
2809     NR_Dependent,   ///< The noexcept specifier is dependent.
2810     NR_Throw,       ///< The noexcept specifier evaluates to false.
2811     NR_Nothrow      ///< The noexcept specifier evaluates to true.
2812   };
2813   /// \brief Get the meaning of the noexcept spec on this function, if any.
2814   NoexceptResult getNoexceptSpec(ASTContext &Ctx) const;
2815   unsigned getNumExceptions() const { return NumExceptions; }
2816   QualType getExceptionType(unsigned i) const {
2817     assert(i < NumExceptions && "Invalid exception number!");
2818     return exception_begin()[i];
2819   }
2820   Expr *getNoexceptExpr() const {
2821     if (getExceptionSpecType() != EST_ComputedNoexcept)
2822       return 0;
2823     // NoexceptExpr sits where the arguments end.
2824     return *reinterpret_cast<Expr *const *>(arg_type_end());
2825   }
2826   bool isNothrow(ASTContext &Ctx) const {
2827     ExceptionSpecificationType EST = getExceptionSpecType();
2828     assert(EST != EST_Delayed);
2829     if (EST == EST_DynamicNone || EST == EST_BasicNoexcept)
2830       return true;
2831     if (EST != EST_ComputedNoexcept)
2832       return false;
2833     return getNoexceptSpec(Ctx) == NR_Nothrow;
2834   }
2835
2836   using FunctionType::isVariadic;
2837
2838   /// \brief Determines whether this function prototype contains a
2839   /// parameter pack at the end.
2840   ///
2841   /// A function template whose last parameter is a parameter pack can be
2842   /// called with an arbitrary number of arguments, much like a variadic
2843   /// function. However, 
2844   bool isTemplateVariadic() const;
2845   
2846   unsigned getTypeQuals() const { return FunctionType::getTypeQuals(); }
2847
2848   
2849   /// \brief Retrieve the ref-qualifier associated with this function type.
2850   RefQualifierKind getRefQualifier() const {
2851     return FunctionType::getRefQualifier();
2852   }
2853   
2854   typedef const QualType *arg_type_iterator;
2855   arg_type_iterator arg_type_begin() const {
2856     return reinterpret_cast<const QualType *>(this+1);
2857   }
2858   arg_type_iterator arg_type_end() const { return arg_type_begin()+NumArgs; }
2859
2860   typedef const QualType *exception_iterator;
2861   exception_iterator exception_begin() const {
2862     // exceptions begin where arguments end
2863     return arg_type_end();
2864   }
2865   exception_iterator exception_end() const {
2866     if (getExceptionSpecType() != EST_Dynamic)
2867       return exception_begin();
2868     return exception_begin() + NumExceptions;
2869   }
2870
2871   bool hasAnyConsumedArgs() const {
2872     return HasAnyConsumedArgs;
2873   }
2874   bool isArgConsumed(unsigned I) const {
2875     assert(I < getNumArgs() && "argument index out of range!");
2876     if (hasAnyConsumedArgs())
2877       return getConsumedArgsBuffer()[I];
2878     return false;
2879   }
2880
2881   bool isSugared() const { return false; }
2882   QualType desugar() const { return QualType(this, 0); }
2883
2884   static bool classof(const Type *T) {
2885     return T->getTypeClass() == FunctionProto;
2886   }
2887   static bool classof(const FunctionProtoType *) { return true; }
2888
2889   void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Ctx);
2890   static void Profile(llvm::FoldingSetNodeID &ID, QualType Result,
2891                       arg_type_iterator ArgTys, unsigned NumArgs,
2892                       const ExtProtoInfo &EPI, const ASTContext &Context);
2893 };
2894
2895
2896 /// \brief Represents the dependent type named by a dependently-scoped
2897 /// typename using declaration, e.g.
2898 ///   using typename Base<T>::foo;
2899 /// Template instantiation turns these into the underlying type.
2900 class UnresolvedUsingType : public Type {
2901   UnresolvedUsingTypenameDecl *Decl;
2902
2903   UnresolvedUsingType(const UnresolvedUsingTypenameDecl *D)
2904     : Type(UnresolvedUsing, QualType(), true, true, false, 
2905            /*ContainsUnexpandedParameterPack=*/false),
2906       Decl(const_cast<UnresolvedUsingTypenameDecl*>(D)) {}
2907   friend class ASTContext; // ASTContext creates these.
2908 public:
2909
2910   UnresolvedUsingTypenameDecl *getDecl() const { return Decl; }
2911
2912   bool isSugared() const { return false; }
2913   QualType desugar() const { return QualType(this, 0); }
2914
2915   static bool classof(const Type *T) {
2916     return T->getTypeClass() == UnresolvedUsing;
2917   }
2918   static bool classof(const UnresolvedUsingType *) { return true; }
2919
2920   void Profile(llvm::FoldingSetNodeID &ID) {
2921     return Profile(ID, Decl);
2922   }
2923   static void Profile(llvm::FoldingSetNodeID &ID,
2924                       UnresolvedUsingTypenameDecl *D) {
2925     ID.AddPointer(D);
2926   }
2927 };
2928
2929
2930 class TypedefType : public Type {
2931   TypedefNameDecl *Decl;
2932 protected:
2933   TypedefType(TypeClass tc, const TypedefNameDecl *D, QualType can)
2934     : Type(tc, can, can->isDependentType(), 
2935            can->isInstantiationDependentType(),
2936            can->isVariablyModifiedType(), 
2937            /*ContainsUnexpandedParameterPack=*/false),
2938       Decl(const_cast<TypedefNameDecl*>(D)) {
2939     assert(!isa<TypedefType>(can) && "Invalid canonical type");
2940   }
2941   friend class ASTContext;  // ASTContext creates these.
2942 public:
2943
2944   TypedefNameDecl *getDecl() const { return Decl; }
2945
2946   bool isSugared() const { return true; }
2947   QualType desugar() const;
2948
2949   static bool classof(const Type *T) { return T->getTypeClass() == Typedef; }
2950   static bool classof(const TypedefType *) { return true; }
2951 };
2952
2953 /// TypeOfExprType (GCC extension).
2954 class TypeOfExprType : public Type {
2955   Expr *TOExpr;
2956
2957 protected:
2958   TypeOfExprType(Expr *E, QualType can = QualType());
2959   friend class ASTContext;  // ASTContext creates these.
2960 public:
2961   Expr *getUnderlyingExpr() const { return TOExpr; }
2962
2963   /// \brief Remove a single level of sugar.
2964   QualType desugar() const;
2965
2966   /// \brief Returns whether this type directly provides sugar.
2967   bool isSugared() const;
2968
2969   static bool classof(const Type *T) { return T->getTypeClass() == TypeOfExpr; }
2970   static bool classof(const TypeOfExprType *) { return true; }
2971 };
2972
2973 /// \brief Internal representation of canonical, dependent
2974 /// typeof(expr) types.
2975 ///
2976 /// This class is used internally by the ASTContext to manage
2977 /// canonical, dependent types, only. Clients will only see instances
2978 /// of this class via TypeOfExprType nodes.
2979 class DependentTypeOfExprType
2980   : public TypeOfExprType, public llvm::FoldingSetNode {
2981   const ASTContext &Context;
2982
2983 public:
2984   DependentTypeOfExprType(const ASTContext &Context, Expr *E)
2985     : TypeOfExprType(E), Context(Context) { }
2986
2987   void Profile(llvm::FoldingSetNodeID &ID) {
2988     Profile(ID, Context, getUnderlyingExpr());
2989   }
2990
2991   static void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context,
2992                       Expr *E);
2993 };
2994
2995 /// TypeOfType (GCC extension).
2996 class TypeOfType : public Type {
2997   QualType TOType;
2998   TypeOfType(QualType T, QualType can)
2999     : Type(TypeOf, can, T->isDependentType(), 
3000            T->isInstantiationDependentType(),
3001            T->isVariablyModifiedType(), 
3002            T->containsUnexpandedParameterPack()), 
3003       TOType(T) {
3004     assert(!isa<TypedefType>(can) && "Invalid canonical type");
3005   }
3006   friend class ASTContext;  // ASTContext creates these.
3007 public:
3008   QualType getUnderlyingType() const { return TOType; }
3009
3010   /// \brief Remove a single level of sugar.
3011   QualType desugar() const { return getUnderlyingType(); }
3012
3013   /// \brief Returns whether this type directly provides sugar.
3014   bool isSugared() const { return true; }
3015
3016   static bool classof(const Type *T) { return T->getTypeClass() == TypeOf; }
3017   static bool classof(const TypeOfType *) { return true; }
3018 };
3019
3020 /// DecltypeType (C++0x)
3021 class DecltypeType : public Type {
3022   Expr *E;
3023
3024   // FIXME: We could get rid of UnderlyingType if we wanted to: We would have to
3025   // Move getDesugaredType to ASTContext so that it can call getDecltypeForExpr
3026   // from it.
3027   QualType UnderlyingType;
3028
3029 protected:
3030   DecltypeType(Expr *E, QualType underlyingType, QualType can = QualType());
3031   friend class ASTContext;  // ASTContext creates these.
3032 public:
3033   Expr *getUnderlyingExpr() const { return E; }
3034   QualType getUnderlyingType() const { return UnderlyingType; }
3035
3036   /// \brief Remove a single level of sugar.
3037   QualType desugar() const;
3038
3039   /// \brief Returns whether this type directly provides sugar.
3040   bool isSugared() const;
3041
3042   static bool classof(const Type *T) { return T->getTypeClass() == Decltype; }
3043   static bool classof(const DecltypeType *) { return true; }
3044 };
3045
3046 /// \brief Internal representation of canonical, dependent
3047 /// decltype(expr) types.
3048 ///
3049 /// This class is used internally by the ASTContext to manage
3050 /// canonical, dependent types, only. Clients will only see instances
3051 /// of this class via DecltypeType nodes.
3052 class DependentDecltypeType : public DecltypeType, public llvm::FoldingSetNode {
3053   const ASTContext &Context;
3054
3055 public:
3056   DependentDecltypeType(const ASTContext &Context, Expr *E);
3057
3058   void Profile(llvm::FoldingSetNodeID &ID) {
3059     Profile(ID, Context, getUnderlyingExpr());
3060   }
3061
3062   static void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context,
3063                       Expr *E);
3064 };
3065
3066 /// \brief A unary type transform, which is a type constructed from another
3067 class UnaryTransformType : public Type {
3068 public:
3069   enum UTTKind {
3070     EnumUnderlyingType
3071   };
3072
3073 private:
3074   /// The untransformed type.
3075   QualType BaseType;
3076   /// The transformed type if not dependent, otherwise the same as BaseType.
3077   QualType UnderlyingType;
3078
3079   UTTKind UKind;
3080 protected:
3081   UnaryTransformType(QualType BaseTy, QualType UnderlyingTy, UTTKind UKind,
3082                      QualType CanonicalTy);
3083   friend class ASTContext;
3084 public:
3085   bool isSugared() const { return !isDependentType(); }
3086   QualType desugar() const { return UnderlyingType; }
3087
3088   QualType getUnderlyingType() const { return UnderlyingType; }
3089   QualType getBaseType() const { return BaseType; }
3090
3091   UTTKind getUTTKind() const { return UKind; }
3092   
3093   static bool classof(const Type *T) {
3094     return T->getTypeClass() == UnaryTransform;
3095   }
3096   static bool classof(const UnaryTransformType *) { return true; }
3097 };
3098
3099 class TagType : public Type {
3100   /// Stores the TagDecl associated with this type. The decl may point to any
3101   /// TagDecl that declares the entity.
3102   TagDecl * decl;
3103
3104 protected:
3105   TagType(TypeClass TC, const TagDecl *D, QualType can);
3106
3107 public:
3108   TagDecl *getDecl() const;
3109
3110   /// @brief Determines whether this type is in the process of being
3111   /// defined.
3112   bool isBeingDefined() const;
3113
3114   static bool classof(const Type *T) {
3115     return T->getTypeClass() >= TagFirst && T->getTypeClass() <= TagLast;
3116   }
3117   static bool classof(const TagType *) { return true; }
3118   static bool classof(const RecordType *) { return true; }
3119   static bool classof(const EnumType *) { return true; }
3120 };
3121
3122 /// RecordType - This is a helper class that allows the use of isa/cast/dyncast
3123 /// to detect TagType objects of structs/unions/classes.
3124 class RecordType : public TagType {
3125 protected:
3126   explicit RecordType(const RecordDecl *D)
3127     : TagType(Record, reinterpret_cast<const TagDecl*>(D), QualType()) { }
3128   explicit RecordType(TypeClass TC, RecordDecl *D)
3129     : TagType(TC, reinterpret_cast<const TagDecl*>(D), QualType()) { }
3130   friend class ASTContext;   // ASTContext creates these.
3131 public:
3132
3133   RecordDecl *getDecl() const {
3134     return reinterpret_cast<RecordDecl*>(TagType::getDecl());
3135   }
3136
3137   // FIXME: This predicate is a helper to QualType/Type. It needs to
3138   // recursively check all fields for const-ness. If any field is declared
3139   // const, it needs to return false.
3140   bool hasConstFields() const { return false; }
3141
3142   bool isSugared() const { return false; }
3143   QualType desugar() const { return QualType(this, 0); }
3144
3145   static bool classof(const TagType *T);
3146   static bool classof(const Type *T) {
3147     return isa<TagType>(T) && classof(cast<TagType>(T));
3148   }
3149   static bool classof(const RecordType *) { return true; }
3150 };
3151
3152 /// EnumType - This is a helper class that allows the use of isa/cast/dyncast
3153 /// to detect TagType objects of enums.
3154 class EnumType : public TagType {
3155   explicit EnumType(const EnumDecl *D)
3156     : TagType(Enum, reinterpret_cast<const TagDecl*>(D), QualType()) { }
3157   friend class ASTContext;   // ASTContext creates these.
3158 public:
3159
3160   EnumDecl *getDecl() const {
3161     return reinterpret_cast<EnumDecl*>(TagType::getDecl());
3162   }
3163
3164   bool isSugared() const { return false; }
3165   QualType desugar() const { return QualType(this, 0); }
3166
3167   static bool classof(const TagType *T);
3168   static bool classof(const Type *T) {
3169     return isa<TagType>(T) && classof(cast<TagType>(T));
3170   }
3171   static bool classof(const EnumType *) { return true; }
3172 };
3173
3174 /// AttributedType - An attributed type is a type to which a type
3175 /// attribute has been applied.  The "modified type" is the
3176 /// fully-sugared type to which the attributed type was applied;
3177 /// generally it is not canonically equivalent to the attributed type.
3178 /// The "equivalent type" is the minimally-desugared type which the
3179 /// type is canonically equivalent to.
3180 ///
3181 /// For example, in the following attributed type:
3182 ///     int32_t __attribute__((vector_size(16)))
3183 ///   - the modified type is the TypedefType for int32_t
3184 ///   - the equivalent type is VectorType(16, int32_t)
3185 ///   - the canonical type is VectorType(16, int)
3186 class AttributedType : public Type, public llvm::FoldingSetNode {
3187 public:
3188   // It is really silly to have yet another attribute-kind enum, but
3189   // clang::attr::Kind doesn't currently cover the pure type attrs.
3190   enum Kind {
3191     // Expression operand.
3192     attr_address_space,
3193     attr_regparm,
3194     attr_vector_size,
3195     attr_neon_vector_type,
3196     attr_neon_polyvector_type,
3197
3198     FirstExprOperandKind = attr_address_space,
3199     LastExprOperandKind = attr_neon_polyvector_type,
3200
3201     // Enumerated operand (string or keyword).
3202     attr_objc_gc,
3203     attr_objc_ownership,
3204     attr_pcs,
3205
3206     FirstEnumOperandKind = attr_objc_gc,
3207     LastEnumOperandKind = attr_pcs,
3208
3209     // No operand.
3210     attr_noreturn,
3211     attr_cdecl,
3212     attr_fastcall,
3213     attr_stdcall,
3214     attr_thiscall,
3215     attr_pascal
3216   };
3217
3218 private:
3219   QualType ModifiedType;
3220   QualType EquivalentType;
3221
3222   friend class ASTContext; // creates these
3223
3224   AttributedType(QualType canon, Kind attrKind,
3225                  QualType modified, QualType equivalent)
3226     : Type(Attributed, canon, canon->isDependentType(),
3227            canon->isInstantiationDependentType(),
3228            canon->isVariablyModifiedType(),
3229            canon->containsUnexpandedParameterPack()),
3230       ModifiedType(modified), EquivalentType(equivalent) {
3231     AttributedTypeBits.AttrKind = attrKind;
3232   }
3233
3234 public:
3235   Kind getAttrKind() const {
3236     return static_cast<Kind>(AttributedTypeBits.AttrKind);
3237   }
3238
3239   QualType getModifiedType() const { return ModifiedType; }
3240   QualType getEquivalentType() const { return EquivalentType; }
3241
3242   bool isSugared() const { return true; }
3243   QualType desugar() const { return getEquivalentType(); }
3244
3245   void Profile(llvm::FoldingSetNodeID &ID) {
3246     Profile(ID, getAttrKind(), ModifiedType, EquivalentType);
3247   }
3248
3249   static void Profile(llvm::FoldingSetNodeID &ID, Kind attrKind,
3250                       QualType modified, QualType equivalent) {
3251     ID.AddInteger(attrKind);
3252     ID.AddPointer(modified.getAsOpaquePtr());
3253     ID.AddPointer(equivalent.getAsOpaquePtr());
3254   }
3255
3256   static bool classof(const Type *T) {
3257     return T->getTypeClass() == Attributed;
3258   }
3259   static bool classof(const AttributedType *T) { return true; }
3260 };
3261
3262 class TemplateTypeParmType : public Type, public llvm::FoldingSetNode {
3263   // Helper data collector for canonical types.
3264   struct CanonicalTTPTInfo {
3265     unsigned Depth : 15;
3266     unsigned ParameterPack : 1;
3267     unsigned Index : 16;
3268   };
3269
3270   union {
3271     // Info for the canonical type.
3272     CanonicalTTPTInfo CanTTPTInfo;
3273     // Info for the non-canonical type.
3274     TemplateTypeParmDecl *TTPDecl;
3275   };
3276
3277   /// Build a non-canonical type.
3278   TemplateTypeParmType(TemplateTypeParmDecl *TTPDecl, QualType Canon)
3279     : Type(TemplateTypeParm, Canon, /*Dependent=*/true,
3280            /*InstantiationDependent=*/true,
3281            /*VariablyModified=*/false,
3282            Canon->containsUnexpandedParameterPack()),
3283       TTPDecl(TTPDecl) { }
3284
3285   /// Build the canonical type.
3286   TemplateTypeParmType(unsigned D, unsigned I, bool PP)
3287     : Type(TemplateTypeParm, QualType(this, 0), 
3288            /*Dependent=*/true,
3289            /*InstantiationDependent=*/true,
3290            /*VariablyModified=*/false, PP) {
3291     CanTTPTInfo.Depth = D;
3292     CanTTPTInfo.Index = I;
3293     CanTTPTInfo.ParameterPack = PP;
3294   }
3295
3296   friend class ASTContext;  // ASTContext creates these
3297
3298   const CanonicalTTPTInfo& getCanTTPTInfo() const {
3299     QualType Can = getCanonicalTypeInternal();
3300     return Can->castAs<TemplateTypeParmType>()->CanTTPTInfo;
3301   }
3302
3303 public:
3304   unsigned getDepth() const { return getCanTTPTInfo().Depth; }
3305   unsigned getIndex() const { return getCanTTPTInfo().Index; }
3306   bool isParameterPack() const { return getCanTTPTInfo().ParameterPack; }
3307
3308   TemplateTypeParmDecl *getDecl() const {
3309     return isCanonicalUnqualified() ? 0 : TTPDecl;
3310   }
3311
3312   IdentifierInfo *getIdentifier() const;
3313
3314   bool isSugared() const { return false; }
3315   QualType desugar() const { return QualType(this, 0); }
3316
3317   void Profile(llvm::FoldingSetNodeID &ID) {
3318     Profile(ID, getDepth(), getIndex(), isParameterPack(), getDecl());
3319   }
3320
3321   static void Profile(llvm::FoldingSetNodeID &ID, unsigned Depth,
3322                       unsigned Index, bool ParameterPack,
3323                       TemplateTypeParmDecl *TTPDecl) {
3324     ID.AddInteger(Depth);
3325     ID.AddInteger(Index);
3326     ID.AddBoolean(ParameterPack);
3327     ID.AddPointer(TTPDecl);
3328   }
3329
3330   static bool classof(const Type *T) {
3331     return T->getTypeClass() == TemplateTypeParm;
3332   }
3333   static bool classof(const TemplateTypeParmType *T) { return true; }
3334 };
3335
3336 /// \brief Represents the result of substituting a type for a template
3337 /// type parameter.
3338 ///
3339 /// Within an instantiated template, all template type parameters have
3340 /// been replaced with these.  They are used solely to record that a
3341 /// type was originally written as a template type parameter;
3342 /// therefore they are never canonical.
3343 class SubstTemplateTypeParmType : public Type, public llvm::FoldingSetNode {
3344   // The original type parameter.
3345   const TemplateTypeParmType *Replaced;
3346
3347   SubstTemplateTypeParmType(const TemplateTypeParmType *Param, QualType Canon)
3348     : Type(SubstTemplateTypeParm, Canon, Canon->isDependentType(),
3349            Canon->isInstantiationDependentType(),
3350            Canon->isVariablyModifiedType(),
3351            Canon->containsUnexpandedParameterPack()),
3352       Replaced(Param) { }
3353
3354   friend class ASTContext;
3355
3356 public:
3357   /// Gets the template parameter that was substituted for.
3358   const TemplateTypeParmType *getReplacedParameter() const {
3359     return Replaced;
3360   }
3361
3362   /// Gets the type that was substituted for the template
3363   /// parameter.
3364   QualType getReplacementType() const {
3365     return getCanonicalTypeInternal();
3366   }
3367
3368   bool isSugared() const { return true; }
3369   QualType desugar() const { return getReplacementType(); }
3370
3371   void Profile(llvm::FoldingSetNodeID &ID) {
3372     Profile(ID, getReplacedParameter(), getReplacementType());
3373   }
3374   static void Profile(llvm::FoldingSetNodeID &ID,
3375                       const TemplateTypeParmType *Replaced,
3376                       QualType Replacement) {
3377     ID.AddPointer(Replaced);
3378     ID.AddPointer(Replacement.getAsOpaquePtr());
3379   }
3380
3381   static bool classof(const Type *T) {
3382     return T->getTypeClass() == SubstTemplateTypeParm;
3383   }
3384   static bool classof(const SubstTemplateTypeParmType *T) { return true; }
3385 };
3386
3387 /// \brief Represents the result of substituting a set of types for a template
3388 /// type parameter pack.
3389 ///
3390 /// When a pack expansion in the source code contains multiple parameter packs
3391 /// and those parameter packs correspond to different levels of template
3392 /// parameter lists, this type node is used to represent a template type 
3393 /// parameter pack from an outer level, which has already had its argument pack
3394 /// substituted but that still lives within a pack expansion that itself
3395 /// could not be instantiated. When actually performing a substitution into
3396 /// that pack expansion (e.g., when all template parameters have corresponding
3397 /// arguments), this type will be replaced with the \c SubstTemplateTypeParmType
3398 /// at the current pack substitution index.
3399 class SubstTemplateTypeParmPackType : public Type, public llvm::FoldingSetNode {
3400   /// \brief The original type parameter.
3401   const TemplateTypeParmType *Replaced;
3402   
3403   /// \brief A pointer to the set of template arguments that this
3404   /// parameter pack is instantiated with.
3405   const TemplateArgument *Arguments;
3406   
3407   /// \brief The number of template arguments in \c Arguments.
3408   unsigned NumArguments;
3409   
3410   SubstTemplateTypeParmPackType(const TemplateTypeParmType *Param, 
3411                                 QualType Canon,
3412                                 const TemplateArgument &ArgPack);
3413   
3414   friend class ASTContext;
3415   
3416 public:
3417   IdentifierInfo *getIdentifier() const { return Replaced->getIdentifier(); }
3418   
3419   /// Gets the template parameter that was substituted for.
3420   const TemplateTypeParmType *getReplacedParameter() const {
3421     return Replaced;
3422   }
3423   
3424   bool isSugared() const { return false; }
3425   QualType desugar() const { return QualType(this, 0); }
3426   
3427   TemplateArgument getArgumentPack() const;
3428   
3429   void Profile(llvm::FoldingSetNodeID &ID);
3430   static void Profile(llvm::FoldingSetNodeID &ID,
3431                       const TemplateTypeParmType *Replaced,
3432                       const TemplateArgument &ArgPack);
3433   
3434   static bool classof(const Type *T) {
3435     return T->getTypeClass() == SubstTemplateTypeParmPack;
3436   }
3437   static bool classof(const SubstTemplateTypeParmPackType *T) { return true; }
3438 };
3439
3440 /// \brief Represents a C++0x auto type.
3441 ///
3442 /// These types are usually a placeholder for a deduced type. However, within
3443 /// templates and before the initializer is attached, there is no deduced type
3444 /// and an auto type is type-dependent and canonical.
3445 class AutoType : public Type, public llvm::FoldingSetNode {
3446   AutoType(QualType DeducedType)
3447     : Type(Auto, DeducedType.isNull() ? QualType(this, 0) : DeducedType,
3448            /*Dependent=*/DeducedType.isNull(),
3449            /*InstantiationDependent=*/DeducedType.isNull(),
3450            /*VariablyModified=*/false, /*ContainsParameterPack=*/false) {
3451     assert((DeducedType.isNull() || !DeducedType->isDependentType()) &&
3452            "deduced a dependent type for auto");
3453   }
3454
3455   friend class ASTContext;  // ASTContext creates these
3456
3457 public:
3458   bool isSugared() const { return isDeduced(); }
3459   QualType desugar() const { return getCanonicalTypeInternal(); }
3460
3461   QualType getDeducedType() const {
3462     return isDeduced() ? getCanonicalTypeInternal() : QualType();
3463   }
3464   bool isDeduced() const {
3465     return !isDependentType();
3466   }
3467
3468   void Profile(llvm::FoldingSetNodeID &ID) {
3469     Profile(ID, getDeducedType());
3470   }
3471
3472   static void Profile(llvm::FoldingSetNodeID &ID,
3473                       QualType Deduced) {
3474     ID.AddPointer(Deduced.getAsOpaquePtr());
3475   }
3476
3477   static bool classof(const Type *T) {
3478     return T->getTypeClass() == Auto;
3479   }
3480   static bool classof(const AutoType *T) { return true; }
3481 };
3482
3483 /// \brief Represents a type template specialization; the template
3484 /// must be a class template, a type alias template, or a template
3485 /// template parameter.  A template which cannot be resolved to one of
3486 /// these, e.g. because it is written with a dependent scope
3487 /// specifier, is instead represented as a
3488 /// @c DependentTemplateSpecializationType.
3489 ///
3490 /// A non-dependent template specialization type is always "sugar",
3491 /// typically for a @c RecordType.  For example, a class template
3492 /// specialization type of @c vector<int> will refer to a tag type for
3493 /// the instantiation @c std::vector<int, std::allocator<int>>
3494 ///
3495 /// Template specializations are dependent if either the template or
3496 /// any of the template arguments are dependent, in which case the
3497 /// type may also be canonical.
3498 ///
3499 /// Instances of this type are allocated with a trailing array of
3500 /// TemplateArguments, followed by a QualType representing the
3501 /// non-canonical aliased type when the template is a type alias
3502 /// template.
3503 class TemplateSpecializationType
3504   : public Type, public llvm::FoldingSetNode {
3505   /// \brief The name of the template being specialized.  This is
3506   /// either a TemplateName::Template (in which case it is a
3507   /// ClassTemplateDecl*, a TemplateTemplateParmDecl*, or a
3508   /// TypeAliasTemplateDecl*), a
3509   /// TemplateName::SubstTemplateTemplateParmPack, or a
3510   /// TemplateName::SubstTemplateTemplateParm (in which case the
3511   /// replacement must, recursively, be one of these).
3512   TemplateName Template;
3513
3514   /// \brief - The number of template arguments named in this class
3515   /// template specialization.
3516   unsigned NumArgs;
3517
3518   TemplateSpecializationType(TemplateName T,
3519                              const TemplateArgument *Args,
3520                              unsigned NumArgs, QualType Canon,
3521                              QualType Aliased);
3522
3523   friend class ASTContext;  // ASTContext creates these
3524
3525 public:
3526   /// \brief Determine whether any of the given template arguments are
3527   /// dependent.
3528   static bool anyDependentTemplateArguments(const TemplateArgument *Args,
3529                                             unsigned NumArgs,
3530                                             bool &InstantiationDependent);
3531
3532   static bool anyDependentTemplateArguments(const TemplateArgumentLoc *Args,
3533                                             unsigned NumArgs,
3534                                             bool &InstantiationDependent);
3535
3536   static bool anyDependentTemplateArguments(const TemplateArgumentListInfo &,
3537                                             bool &InstantiationDependent);
3538
3539   /// \brief Print a template argument list, including the '<' and '>'
3540   /// enclosing the template arguments.
3541   static std::string PrintTemplateArgumentList(const TemplateArgument *Args,
3542                                                unsigned NumArgs,
3543                                                const PrintingPolicy &Policy,
3544                                                bool SkipBrackets = false);
3545
3546   static std::string PrintTemplateArgumentList(const TemplateArgumentLoc *Args,
3547                                                unsigned NumArgs,
3548                                                const PrintingPolicy &Policy);
3549
3550   static std::string PrintTemplateArgumentList(const TemplateArgumentListInfo &,
3551                                                const PrintingPolicy &Policy);
3552
3553   /// True if this template specialization type matches a current
3554   /// instantiation in the context in which it is found.
3555   bool isCurrentInstantiation() const {
3556     return isa<InjectedClassNameType>(getCanonicalTypeInternal());
3557   }
3558
3559   /// True if this template specialization type is for a type alias
3560   /// template.
3561   bool isTypeAlias() const;
3562   /// Get the aliased type, if this is a specialization of a type alias
3563   /// template.
3564   QualType getAliasedType() const {
3565     assert(isTypeAlias() && "not a type alias template specialization");
3566     return *reinterpret_cast<const QualType*>(end());
3567   }
3568
3569   typedef const TemplateArgument * iterator;
3570
3571   iterator begin() const { return getArgs(); }
3572   iterator end() const; // defined inline in TemplateBase.h
3573
3574   /// \brief Retrieve the name of the template that we are specializing.
3575   TemplateName getTemplateName() const { return Template; }
3576
3577   /// \brief Retrieve the template arguments.
3578   const TemplateArgument *getArgs() const {
3579     return reinterpret_cast<const TemplateArgument *>(this + 1);
3580   }
3581
3582   /// \brief Retrieve the number of template arguments.
3583   unsigned getNumArgs() const { return NumArgs; }
3584
3585   /// \brief Retrieve a specific template argument as a type.
3586   /// \precondition @c isArgType(Arg)
3587   const TemplateArgument &getArg(unsigned Idx) const; // in TemplateBase.h
3588
3589   bool isSugared() const {
3590     return !isDependentType() || isCurrentInstantiation() || isTypeAlias();
3591   }
3592   QualType desugar() const { return getCanonicalTypeInternal(); }
3593
3594   void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Ctx) {
3595     Profile(ID, Template, getArgs(), NumArgs, Ctx);
3596     if (isTypeAlias())
3597       getAliasedType().Profile(ID);
3598   }
3599
3600   static void Profile(llvm::FoldingSetNodeID &ID, TemplateName T,
3601                       const TemplateArgument *Args,
3602                       unsigned NumArgs,
3603                       const ASTContext &Context);
3604
3605   static bool classof(const Type *T) {
3606     return T->getTypeClass() == TemplateSpecialization;
3607   }
3608   static bool classof(const TemplateSpecializationType *T) { return true; }
3609 };
3610
3611 /// \brief The injected class name of a C++ class template or class
3612 /// template partial specialization.  Used to record that a type was
3613 /// spelled with a bare identifier rather than as a template-id; the
3614 /// equivalent for non-templated classes is just RecordType.
3615 ///
3616 /// Injected class name types are always dependent.  Template
3617 /// instantiation turns these into RecordTypes.
3618 ///
3619 /// Injected class name types are always canonical.  This works
3620 /// because it is impossible to compare an injected class name type
3621 /// with the corresponding non-injected template type, for the same
3622 /// reason that it is impossible to directly compare template
3623 /// parameters from different dependent contexts: injected class name
3624 /// types can only occur within the scope of a particular templated
3625 /// declaration, and within that scope every template specialization
3626 /// will canonicalize to the injected class name (when appropriate
3627 /// according to the rules of the language).
3628 class InjectedClassNameType : public Type {
3629   CXXRecordDecl *Decl;
3630
3631   /// The template specialization which this type represents.
3632   /// For example, in
3633   ///   template <class T> class A { ... };
3634   /// this is A<T>, whereas in
3635   ///   template <class X, class Y> class A<B<X,Y> > { ... };
3636   /// this is A<B<X,Y> >.
3637   ///
3638   /// It is always unqualified, always a template specialization type,
3639   /// and always dependent.
3640   QualType InjectedType;
3641
3642   friend class ASTContext; // ASTContext creates these.
3643   friend class ASTReader; // FIXME: ASTContext::getInjectedClassNameType is not
3644                           // currently suitable for AST reading, too much
3645                           // interdependencies.
3646   InjectedClassNameType(CXXRecordDecl *D, QualType TST)
3647     : Type(InjectedClassName, QualType(), /*Dependent=*/true,
3648            /*InstantiationDependent=*/true,
3649            /*VariablyModified=*/false, 
3650            /*ContainsUnexpandedParameterPack=*/false),
3651       Decl(D), InjectedType(TST) {
3652     assert(isa<TemplateSpecializationType>(TST));
3653     assert(!TST.hasQualifiers());
3654     assert(TST->isDependentType());
3655   }
3656
3657 public:
3658   QualType getInjectedSpecializationType() const { return InjectedType; }
3659   const TemplateSpecializationType *getInjectedTST() const {
3660     return cast<TemplateSpecializationType>(InjectedType.getTypePtr());
3661   }
3662
3663   CXXRecordDecl *getDecl() const;
3664
3665   bool isSugared() const { return false; }
3666   QualType desugar() const { return QualType(this, 0); }
3667
3668   static bool classof(const Type *T) {
3669     return T->getTypeClass() == InjectedClassName;
3670   }
3671   static bool classof(const InjectedClassNameType *T) { return true; }
3672 };
3673
3674 /// \brief The kind of a tag type.
3675 enum TagTypeKind {
3676   /// \brief The "struct" keyword.
3677   TTK_Struct,
3678   /// \brief The "union" keyword.
3679   TTK_Union,
3680   /// \brief The "class" keyword.
3681   TTK_Class,
3682   /// \brief The "enum" keyword.
3683   TTK_Enum
3684 };
3685
3686 /// \brief The elaboration keyword that precedes a qualified type name or
3687 /// introduces an elaborated-type-specifier.
3688 enum ElaboratedTypeKeyword {
3689   /// \brief The "struct" keyword introduces the elaborated-type-specifier.
3690   ETK_Struct,
3691   /// \brief The "union" keyword introduces the elaborated-type-specifier.
3692   ETK_Union,
3693   /// \brief The "class" keyword introduces the elaborated-type-specifier.
3694   ETK_Class,
3695   /// \brief The "enum" keyword introduces the elaborated-type-specifier.
3696   ETK_Enum,
3697   /// \brief The "typename" keyword precedes the qualified type name, e.g.,
3698   /// \c typename T::type.
3699   ETK_Typename,
3700   /// \brief No keyword precedes the qualified type name.
3701   ETK_None
3702 };
3703
3704 /// A helper class for Type nodes having an ElaboratedTypeKeyword.
3705 /// The keyword in stored in the free bits of the base class.
3706 /// Also provides a few static helpers for converting and printing
3707 /// elaborated type keyword and tag type kind enumerations.
3708 class TypeWithKeyword : public Type {
3709 protected:
3710   TypeWithKeyword(ElaboratedTypeKeyword Keyword, TypeClass tc,
3711                   QualType Canonical, bool Dependent, 
3712                   bool InstantiationDependent, bool VariablyModified, 
3713                   bool ContainsUnexpandedParameterPack)
3714   : Type(tc, Canonical, Dependent, InstantiationDependent, VariablyModified, 
3715          ContainsUnexpandedParameterPack) {
3716     TypeWithKeywordBits.Keyword = Keyword;
3717   }
3718
3719 public:
3720   ElaboratedTypeKeyword getKeyword() const {
3721     return static_cast<ElaboratedTypeKeyword>(TypeWithKeywordBits.Keyword);
3722   }
3723
3724   /// getKeywordForTypeSpec - Converts a type specifier (DeclSpec::TST)
3725   /// into an elaborated type keyword.
3726   static ElaboratedTypeKeyword getKeywordForTypeSpec(unsigned TypeSpec);
3727
3728   /// getTagTypeKindForTypeSpec - Converts a type specifier (DeclSpec::TST)
3729   /// into a tag type kind.  It is an error to provide a type specifier
3730   /// which *isn't* a tag kind here.
3731   static TagTypeKind getTagTypeKindForTypeSpec(unsigned TypeSpec);
3732
3733   /// getKeywordForTagDeclKind - Converts a TagTypeKind into an
3734   /// elaborated type keyword.
3735   static ElaboratedTypeKeyword getKeywordForTagTypeKind(TagTypeKind Tag);
3736
3737   /// getTagTypeKindForKeyword - Converts an elaborated type keyword into
3738   // a TagTypeKind. It is an error to provide an elaborated type keyword
3739   /// which *isn't* a tag kind here.
3740   static TagTypeKind getTagTypeKindForKeyword(ElaboratedTypeKeyword Keyword);
3741
3742   static bool KeywordIsTagTypeKind(ElaboratedTypeKeyword Keyword);
3743
3744   static const char *getKeywordName(ElaboratedTypeKeyword Keyword);
3745
3746   static const char *getTagTypeKindName(TagTypeKind Kind) {
3747     return getKeywordName(getKeywordForTagTypeKind(Kind));
3748   }
3749
3750   class CannotCastToThisType {};
3751   static CannotCastToThisType classof(const Type *);
3752 };
3753
3754 /// \brief Represents a type that was referred to using an elaborated type
3755 /// keyword, e.g., struct S, or via a qualified name, e.g., N::M::type,
3756 /// or both.
3757 ///
3758 /// This type is used to keep track of a type name as written in the
3759 /// source code, including tag keywords and any nested-name-specifiers.
3760 /// The type itself is always "sugar", used to express what was written
3761 /// in the source code but containing no additional semantic information.
3762 class ElaboratedType : public TypeWithKeyword, public llvm::FoldingSetNode {
3763
3764   /// \brief The nested name specifier containing the qualifier.
3765   NestedNameSpecifier *NNS;
3766
3767   /// \brief The type that this qualified name refers to.
3768   QualType NamedType;
3769
3770   ElaboratedType(ElaboratedTypeKeyword Keyword, NestedNameSpecifier *NNS,
3771                  QualType NamedType, QualType CanonType)
3772     : TypeWithKeyword(Keyword, Elaborated, CanonType,
3773                       NamedType->isDependentType(),
3774                       NamedType->isInstantiationDependentType(),
3775                       NamedType->isVariablyModifiedType(),
3776                       NamedType->containsUnexpandedParameterPack()),
3777       NNS(NNS), NamedType(NamedType) {
3778     assert(!(Keyword == ETK_None && NNS == 0) &&
3779            "ElaboratedType cannot have elaborated type keyword "
3780            "and name qualifier both null.");
3781   }
3782
3783   friend class ASTContext;  // ASTContext creates these
3784
3785 public:
3786   ~ElaboratedType();
3787
3788   /// \brief Retrieve the qualification on this type.
3789   NestedNameSpecifier *getQualifier() const { return NNS; }
3790
3791   /// \brief Retrieve the type named by the qualified-id.
3792   QualType getNamedType() const { return NamedType; }
3793
3794   /// \brief Remove a single level of sugar.
3795   QualType desugar() const { return getNamedType(); }
3796
3797   /// \brief Returns whether this type directly provides sugar.
3798   bool isSugared() const { return true; }
3799
3800   void Profile(llvm::FoldingSetNodeID &ID) {
3801     Profile(ID, getKeyword(), NNS, NamedType);
3802   }
3803
3804   static void Profile(llvm::FoldingSetNodeID &ID, ElaboratedTypeKeyword Keyword,
3805                       NestedNameSpecifier *NNS, QualType NamedType) {
3806     ID.AddInteger(Keyword);
3807     ID.AddPointer(NNS);
3808     NamedType.Profile(ID);
3809   }
3810
3811   static bool classof(const Type *T) {
3812     return T->getTypeClass() == Elaborated;
3813   }
3814   static bool classof(const ElaboratedType *T) { return true; }
3815 };
3816
3817 /// \brief Represents a qualified type name for which the type name is
3818 /// dependent. 
3819 ///
3820 /// DependentNameType represents a class of dependent types that involve a 
3821 /// dependent nested-name-specifier (e.g., "T::") followed by a (dependent) 
3822 /// name of a type. The DependentNameType may start with a "typename" (for a
3823 /// typename-specifier), "class", "struct", "union", or "enum" (for a 
3824 /// dependent elaborated-type-specifier), or nothing (in contexts where we
3825 /// know that we must be referring to a type, e.g., in a base class specifier).
3826 class DependentNameType : public TypeWithKeyword, public llvm::FoldingSetNode {
3827
3828   /// \brief The nested name specifier containing the qualifier.
3829   NestedNameSpecifier *NNS;
3830
3831   /// \brief The type that this typename specifier refers to.
3832   const IdentifierInfo *Name;
3833
3834   DependentNameType(ElaboratedTypeKeyword Keyword, NestedNameSpecifier *NNS, 
3835                     const IdentifierInfo *Name, QualType CanonType)
3836     : TypeWithKeyword(Keyword, DependentName, CanonType, /*Dependent=*/true,
3837                       /*InstantiationDependent=*/true,
3838                       /*VariablyModified=*/false,
3839                       NNS->containsUnexpandedParameterPack()),
3840       NNS(NNS), Name(Name) {
3841     assert(NNS->isDependent() &&
3842            "DependentNameType requires a dependent nested-name-specifier");
3843   }
3844
3845   friend class ASTContext;  // ASTContext creates these
3846
3847 public:
3848   /// \brief Retrieve the qualification on this type.
3849   NestedNameSpecifier *getQualifier() const { return NNS; }
3850
3851   /// \brief Retrieve the type named by the typename specifier as an
3852   /// identifier.
3853   ///
3854   /// This routine will return a non-NULL identifier pointer when the
3855   /// form of the original typename was terminated by an identifier,
3856   /// e.g., "typename T::type".
3857   const IdentifierInfo *getIdentifier() const {
3858     return Name;
3859   }
3860
3861   bool isSugared() const { return false; }
3862   QualType desugar() const { return QualType(this, 0); }
3863
3864   void Profile(llvm::FoldingSetNodeID &ID) {
3865     Profile(ID, getKeyword(), NNS, Name);
3866   }
3867
3868   static void Profile(llvm::FoldingSetNodeID &ID, ElaboratedTypeKeyword Keyword,
3869                       NestedNameSpecifier *NNS, const IdentifierInfo *Name) {
3870     ID.AddInteger(Keyword);
3871     ID.AddPointer(NNS);
3872     ID.AddPointer(Name);
3873   }
3874
3875   static bool classof(const Type *T) {
3876     return T->getTypeClass() == DependentName;
3877   }
3878   static bool classof(const DependentNameType *T) { return true; }
3879 };
3880
3881 /// DependentTemplateSpecializationType - Represents a template
3882 /// specialization type whose template cannot be resolved, e.g.
3883 ///   A<T>::template B<T>
3884 class DependentTemplateSpecializationType :
3885   public TypeWithKeyword, public llvm::FoldingSetNode {
3886
3887   /// \brief The nested name specifier containing the qualifier.
3888   NestedNameSpecifier *NNS;
3889
3890   /// \brief The identifier of the template.
3891   const IdentifierInfo *Name;
3892
3893   /// \brief - The number of template arguments named in this class
3894   /// template specialization.
3895   unsigned NumArgs;
3896
3897   const TemplateArgument *getArgBuffer() const {
3898     return reinterpret_cast<const TemplateArgument*>(this+1);
3899   }
3900   TemplateArgument *getArgBuffer() {
3901     return reinterpret_cast<TemplateArgument*>(this+1);
3902   }
3903
3904   DependentTemplateSpecializationType(ElaboratedTypeKeyword Keyword,
3905                                       NestedNameSpecifier *NNS,
3906                                       const IdentifierInfo *Name,
3907                                       unsigned NumArgs,
3908                                       const TemplateArgument *Args,
3909                                       QualType Canon);
3910
3911   friend class ASTContext;  // ASTContext creates these
3912
3913 public:
3914   NestedNameSpecifier *getQualifier() const { return NNS; }
3915   const IdentifierInfo *getIdentifier() const { return Name; }
3916
3917   /// \brief Retrieve the template arguments.
3918   const TemplateArgument *getArgs() const {
3919     return getArgBuffer();
3920   }
3921
3922   /// \brief Retrieve the number of template arguments.
3923   unsigned getNumArgs() const { return NumArgs; }
3924
3925   const TemplateArgument &getArg(unsigned Idx) const; // in TemplateBase.h
3926
3927   typedef const TemplateArgument * iterator;
3928   iterator begin() const { return getArgs(); }
3929   iterator end() const; // inline in TemplateBase.h
3930
3931   bool isSugared() const { return false; }
3932   QualType desugar() const { return QualType(this, 0); }
3933
3934   void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context) {
3935     Profile(ID, Context, getKeyword(), NNS, Name, NumArgs, getArgs());
3936   }
3937
3938   static void Profile(llvm::FoldingSetNodeID &ID,
3939                       const ASTContext &Context,
3940                       ElaboratedTypeKeyword Keyword,
3941                       NestedNameSpecifier *Qualifier,
3942                       const IdentifierInfo *Name,
3943                       unsigned NumArgs,
3944                       const TemplateArgument *Args);
3945
3946   static bool classof(const Type *T) {
3947     return T->getTypeClass() == DependentTemplateSpecialization;
3948   }
3949   static bool classof(const DependentTemplateSpecializationType *T) {
3950     return true;
3951   }  
3952 };
3953
3954 /// \brief Represents a pack expansion of types.
3955 ///
3956 /// Pack expansions are part of C++0x variadic templates. A pack
3957 /// expansion contains a pattern, which itself contains one or more
3958 /// "unexpanded" parameter packs. When instantiated, a pack expansion
3959 /// produces a series of types, each instantiated from the pattern of
3960 /// the expansion, where the Ith instantiation of the pattern uses the
3961 /// Ith arguments bound to each of the unexpanded parameter packs. The
3962 /// pack expansion is considered to "expand" these unexpanded
3963 /// parameter packs.
3964 ///
3965 /// \code
3966 /// template<typename ...Types> struct tuple;
3967 ///
3968 /// template<typename ...Types> 
3969 /// struct tuple_of_references {
3970 ///   typedef tuple<Types&...> type;
3971 /// };
3972 /// \endcode
3973 ///
3974 /// Here, the pack expansion \c Types&... is represented via a
3975 /// PackExpansionType whose pattern is Types&.
3976 class PackExpansionType : public Type, public llvm::FoldingSetNode {
3977   /// \brief The pattern of the pack expansion.
3978   QualType Pattern;
3979
3980   /// \brief The number of expansions that this pack expansion will
3981   /// generate when substituted (+1), or indicates that 
3982   ///
3983   /// This field will only have a non-zero value when some of the parameter 
3984   /// packs that occur within the pattern have been substituted but others have 
3985   /// not.
3986   unsigned NumExpansions;
3987   
3988   PackExpansionType(QualType Pattern, QualType Canon,
3989                     llvm::Optional<unsigned> NumExpansions)
3990     : Type(PackExpansion, Canon, /*Dependent=*/true,
3991            /*InstantiationDependent=*/true,
3992            /*VariableModified=*/Pattern->isVariablyModifiedType(),
3993            /*ContainsUnexpandedParameterPack=*/false),
3994       Pattern(Pattern), 
3995       NumExpansions(NumExpansions? *NumExpansions + 1: 0) { }
3996
3997   friend class ASTContext;  // ASTContext creates these
3998   
3999 public:
4000   /// \brief Retrieve the pattern of this pack expansion, which is the
4001   /// type that will be repeatedly instantiated when instantiating the
4002   /// pack expansion itself.
4003   QualType getPattern() const { return Pattern; }
4004
4005   /// \brief Retrieve the number of expansions that this pack expansion will
4006   /// generate, if known.
4007   llvm::Optional<unsigned> getNumExpansions() const {
4008     if (NumExpansions)
4009       return NumExpansions - 1;
4010     
4011     return llvm::Optional<unsigned>();
4012   }
4013   
4014   bool isSugared() const { return false; }
4015   QualType desugar() const { return QualType(this, 0); }
4016
4017   void Profile(llvm::FoldingSetNodeID &ID) {
4018     Profile(ID, getPattern(), getNumExpansions());
4019   }
4020
4021   static void Profile(llvm::FoldingSetNodeID &ID, QualType Pattern,
4022                       llvm::Optional<unsigned> NumExpansions) {
4023     ID.AddPointer(Pattern.getAsOpaquePtr());
4024     ID.AddBoolean(NumExpansions);
4025     if (NumExpansions)
4026       ID.AddInteger(*NumExpansions);
4027   }
4028
4029   static bool classof(const Type *T) {
4030     return T->getTypeClass() == PackExpansion;
4031   }
4032   static bool classof(const PackExpansionType *T) {
4033     return true;
4034   }  
4035 };
4036
4037 /// ObjCObjectType - Represents a class type in Objective C.
4038 /// Every Objective C type is a combination of a base type and a
4039 /// list of protocols.
4040 ///
4041 /// Given the following declarations:
4042 ///   @class C;
4043 ///   @protocol P;
4044 ///
4045 /// 'C' is an ObjCInterfaceType C.  It is sugar for an ObjCObjectType
4046 /// with base C and no protocols.
4047 ///
4048 /// 'C<P>' is an ObjCObjectType with base C and protocol list [P].
4049 ///
4050 /// 'id' is a TypedefType which is sugar for an ObjCPointerType whose
4051 /// pointee is an ObjCObjectType with base BuiltinType::ObjCIdType
4052 /// and no protocols.
4053 ///
4054 /// 'id<P>' is an ObjCPointerType whose pointee is an ObjCObjecType
4055 /// with base BuiltinType::ObjCIdType and protocol list [P].  Eventually
4056 /// this should get its own sugar class to better represent the source.
4057 class ObjCObjectType : public Type {
4058   // ObjCObjectType.NumProtocols - the number of protocols stored
4059   // after the ObjCObjectPointerType node.
4060   //
4061   // These protocols are those written directly on the type.  If
4062   // protocol qualifiers ever become additive, the iterators will need
4063   // to get kindof complicated.
4064   //
4065   // In the canonical object type, these are sorted alphabetically
4066   // and uniqued.
4067
4068   /// Either a BuiltinType or an InterfaceType or sugar for either.
4069   QualType BaseType;
4070
4071   ObjCProtocolDecl * const *getProtocolStorage() const {
4072     return const_cast<ObjCObjectType*>(this)->getProtocolStorage();
4073   }
4074
4075   ObjCProtocolDecl **getProtocolStorage();
4076
4077 protected:
4078   ObjCObjectType(QualType Canonical, QualType Base, 
4079                  ObjCProtocolDecl * const *Protocols, unsigned NumProtocols);
4080
4081   enum Nonce_ObjCInterface { Nonce_ObjCInterface };
4082   ObjCObjectType(enum Nonce_ObjCInterface)
4083         : Type(ObjCInterface, QualType(), false, false, false, false),
4084       BaseType(QualType(this_(), 0)) {
4085     ObjCObjectTypeBits.NumProtocols = 0;
4086   }
4087
4088 public:
4089   /// getBaseType - Gets the base type of this object type.  This is
4090   /// always (possibly sugar for) one of:
4091   ///  - the 'id' builtin type (as opposed to the 'id' type visible to the
4092   ///    user, which is a typedef for an ObjCPointerType)
4093   ///  - the 'Class' builtin type (same caveat)
4094   ///  - an ObjCObjectType (currently always an ObjCInterfaceType)
4095   QualType getBaseType() const { return BaseType; }
4096
4097   bool isObjCId() const {
4098     return getBaseType()->isSpecificBuiltinType(BuiltinType::ObjCId);
4099   }
4100   bool isObjCClass() const {
4101     return getBaseType()->isSpecificBuiltinType(BuiltinType::ObjCClass);
4102   }
4103   bool isObjCUnqualifiedId() const { return qual_empty() && isObjCId(); }
4104   bool isObjCUnqualifiedClass() const { return qual_empty() && isObjCClass(); }
4105   bool isObjCUnqualifiedIdOrClass() const {
4106     if (!qual_empty()) return false;
4107     if (const BuiltinType *T = getBaseType()->getAs<BuiltinType>())
4108       return T->getKind() == BuiltinType::ObjCId ||
4109              T->getKind() == BuiltinType::ObjCClass;
4110     return false;
4111   }
4112   bool isObjCQualifiedId() const { return !qual_empty() && isObjCId(); }
4113   bool isObjCQualifiedClass() const { return !qual_empty() && isObjCClass(); }
4114
4115   /// Gets the interface declaration for this object type, if the base type
4116   /// really is an interface.
4117   ObjCInterfaceDecl *getInterface() const;
4118
4119   typedef ObjCProtocolDecl * const *qual_iterator;
4120
4121   qual_iterator qual_begin() const { return getProtocolStorage(); }
4122   qual_iterator qual_end() const { return qual_begin() + getNumProtocols(); }
4123
4124   bool qual_empty() const { return getNumProtocols() == 0; }
4125
4126   /// getNumProtocols - Return the number of qualifying protocols in this
4127   /// interface type, or 0 if there are none.
4128   unsigned getNumProtocols() const { return ObjCObjectTypeBits.NumProtocols; }
4129
4130   /// \brief Fetch a protocol by index.
4131   ObjCProtocolDecl *getProtocol(unsigned I) const {
4132     assert(I < getNumProtocols() && "Out-of-range protocol access");
4133     return qual_begin()[I];
4134   }
4135   
4136   bool isSugared() const { return false; }
4137   QualType desugar() const { return QualType(this, 0); }
4138
4139   static bool classof(const Type *T) {
4140     return T->getTypeClass() == ObjCObject ||
4141            T->getTypeClass() == ObjCInterface;
4142   }
4143   static bool classof(const ObjCObjectType *) { return true; }
4144 };
4145
4146 /// ObjCObjectTypeImpl - A class providing a concrete implementation
4147 /// of ObjCObjectType, so as to not increase the footprint of
4148 /// ObjCInterfaceType.  Code outside of ASTContext and the core type
4149 /// system should not reference this type.
4150 class ObjCObjectTypeImpl : public ObjCObjectType, public llvm::FoldingSetNode {
4151   friend class ASTContext;
4152
4153   // If anyone adds fields here, ObjCObjectType::getProtocolStorage()
4154   // will need to be modified.
4155
4156   ObjCObjectTypeImpl(QualType Canonical, QualType Base, 
4157                      ObjCProtocolDecl * const *Protocols,
4158                      unsigned NumProtocols)
4159     : ObjCObjectType(Canonical, Base, Protocols, NumProtocols) {}
4160
4161 public:
4162   void Profile(llvm::FoldingSetNodeID &ID);
4163   static void Profile(llvm::FoldingSetNodeID &ID,
4164                       QualType Base,
4165                       ObjCProtocolDecl *const *protocols, 
4166                       unsigned NumProtocols);  
4167 };
4168
4169 inline ObjCProtocolDecl **ObjCObjectType::getProtocolStorage() {
4170   return reinterpret_cast<ObjCProtocolDecl**>(
4171             static_cast<ObjCObjectTypeImpl*>(this) + 1);
4172 }
4173
4174 /// ObjCInterfaceType - Interfaces are the core concept in Objective-C for
4175 /// object oriented design.  They basically correspond to C++ classes.  There
4176 /// are two kinds of interface types, normal interfaces like "NSString" and
4177 /// qualified interfaces, which are qualified with a protocol list like
4178 /// "NSString<NSCopyable, NSAmazing>".
4179 ///
4180 /// ObjCInterfaceType guarantees the following properties when considered
4181 /// as a subtype of its superclass, ObjCObjectType:
4182 ///   - There are no protocol qualifiers.  To reinforce this, code which
4183 ///     tries to invoke the protocol methods via an ObjCInterfaceType will
4184 ///     fail to compile.
4185 ///   - It is its own base type.  That is, if T is an ObjCInterfaceType*,
4186 ///     T->getBaseType() == QualType(T, 0).
4187 class ObjCInterfaceType : public ObjCObjectType {
4188   ObjCInterfaceDecl *Decl;
4189
4190   ObjCInterfaceType(const ObjCInterfaceDecl *D)
4191     : ObjCObjectType(Nonce_ObjCInterface),
4192       Decl(const_cast<ObjCInterfaceDecl*>(D)) {}
4193   friend class ASTContext;  // ASTContext creates these.
4194
4195 public:
4196   /// getDecl - Get the declaration of this interface.
4197   ObjCInterfaceDecl *getDecl() const { return Decl; }
4198
4199   bool isSugared() const { return false; }
4200   QualType desugar() const { return QualType(this, 0); }
4201
4202   static bool classof(const Type *T) {
4203     return T->getTypeClass() == ObjCInterface;
4204   }
4205   static bool classof(const ObjCInterfaceType *) { return true; }
4206
4207   // Nonsense to "hide" certain members of ObjCObjectType within this
4208   // class.  People asking for protocols on an ObjCInterfaceType are
4209   // not going to get what they want: ObjCInterfaceTypes are
4210   // guaranteed to have no protocols.
4211   enum {
4212     qual_iterator,
4213     qual_begin,
4214     qual_end,
4215     getNumProtocols,
4216     getProtocol
4217   };
4218 };
4219
4220 inline ObjCInterfaceDecl *ObjCObjectType::getInterface() const {
4221   if (const ObjCInterfaceType *T =
4222         getBaseType()->getAs<ObjCInterfaceType>())
4223     return T->getDecl();
4224   return 0;
4225 }
4226
4227 /// ObjCObjectPointerType - Used to represent a pointer to an
4228 /// Objective C object.  These are constructed from pointer
4229 /// declarators when the pointee type is an ObjCObjectType (or sugar
4230 /// for one).  In addition, the 'id' and 'Class' types are typedefs
4231 /// for these, and the protocol-qualified types 'id<P>' and 'Class<P>'
4232 /// are translated into these.
4233 ///
4234 /// Pointers to pointers to Objective C objects are still PointerTypes;
4235 /// only the first level of pointer gets it own type implementation.
4236 class ObjCObjectPointerType : public Type, public llvm::FoldingSetNode {
4237   QualType PointeeType;
4238
4239   ObjCObjectPointerType(QualType Canonical, QualType Pointee)
4240     : Type(ObjCObjectPointer, Canonical, false, false, false, false),
4241       PointeeType(Pointee) {}
4242   friend class ASTContext;  // ASTContext creates these.
4243
4244 public:
4245   /// getPointeeType - Gets the type pointed to by this ObjC pointer.
4246   /// The result will always be an ObjCObjectType or sugar thereof.
4247   QualType getPointeeType() const { return PointeeType; }
4248
4249   /// getObjCObjectType - Gets the type pointed to by this ObjC
4250   /// pointer.  This method always returns non-null.
4251   ///
4252   /// This method is equivalent to getPointeeType() except that
4253   /// it discards any typedefs (or other sugar) between this
4254   /// type and the "outermost" object type.  So for:
4255   ///   @class A; @protocol P; @protocol Q;
4256   ///   typedef A<P> AP;
4257   ///   typedef A A1;
4258   ///   typedef A1<P> A1P;
4259   ///   typedef A1P<Q> A1PQ;
4260   /// For 'A*', getObjectType() will return 'A'.
4261   /// For 'A<P>*', getObjectType() will return 'A<P>'.
4262   /// For 'AP*', getObjectType() will return 'A<P>'.
4263   /// For 'A1*', getObjectType() will return 'A'.
4264   /// For 'A1<P>*', getObjectType() will return 'A1<P>'.
4265   /// For 'A1P*', getObjectType() will return 'A1<P>'.
4266   /// For 'A1PQ*', getObjectType() will return 'A1<Q>', because
4267   ///   adding protocols to a protocol-qualified base discards the
4268   ///   old qualifiers (for now).  But if it didn't, getObjectType()
4269   ///   would return 'A1P<Q>' (and we'd have to make iterating over
4270   ///   qualifiers more complicated).
4271   const ObjCObjectType *getObjectType() const {
4272     return PointeeType->castAs<ObjCObjectType>();
4273   }
4274
4275   /// getInterfaceType - If this pointer points to an Objective C
4276   /// @interface type, gets the type for that interface.  Any protocol
4277   /// qualifiers on the interface are ignored.
4278   ///
4279   /// \return null if the base type for this pointer is 'id' or 'Class'
4280   const ObjCInterfaceType *getInterfaceType() const {
4281     return getObjectType()->getBaseType()->getAs<ObjCInterfaceType>();
4282   }
4283
4284   /// getInterfaceDecl - If this pointer points to an Objective @interface
4285   /// type, gets the declaration for that interface.
4286   ///
4287   /// \return null if the base type for this pointer is 'id' or 'Class'
4288   ObjCInterfaceDecl *getInterfaceDecl() const {
4289     return getObjectType()->getInterface();
4290   }
4291
4292   /// isObjCIdType - True if this is equivalent to the 'id' type, i.e. if
4293   /// its object type is the primitive 'id' type with no protocols.
4294   bool isObjCIdType() const {
4295     return getObjectType()->isObjCUnqualifiedId();
4296   }
4297
4298   /// isObjCClassType - True if this is equivalent to the 'Class' type,
4299   /// i.e. if its object tive is the primitive 'Class' type with no protocols.
4300   bool isObjCClassType() const {
4301     return getObjectType()->isObjCUnqualifiedClass();
4302   }
4303   
4304   /// isObjCQualifiedIdType - True if this is equivalent to 'id<P>' for some
4305   /// non-empty set of protocols.
4306   bool isObjCQualifiedIdType() const {
4307     return getObjectType()->isObjCQualifiedId();
4308   }
4309
4310   /// isObjCQualifiedClassType - True if this is equivalent to 'Class<P>' for
4311   /// some non-empty set of protocols.
4312   bool isObjCQualifiedClassType() const {
4313     return getObjectType()->isObjCQualifiedClass();
4314   }
4315
4316   /// An iterator over the qualifiers on the object type.  Provided
4317   /// for convenience.  This will always iterate over the full set of
4318   /// protocols on a type, not just those provided directly.
4319   typedef ObjCObjectType::qual_iterator qual_iterator;
4320
4321   qual_iterator qual_begin() const {
4322     return getObjectType()->qual_begin();
4323   }
4324   qual_iterator qual_end() const {
4325     return getObjectType()->qual_end();
4326   }
4327   bool qual_empty() const { return getObjectType()->qual_empty(); }
4328
4329   /// getNumProtocols - Return the number of qualifying protocols on
4330   /// the object type.
4331   unsigned getNumProtocols() const {
4332     return getObjectType()->getNumProtocols();
4333   }
4334
4335   /// \brief Retrieve a qualifying protocol by index on the object
4336   /// type.
4337   ObjCProtocolDecl *getProtocol(unsigned I) const {
4338     return getObjectType()->getProtocol(I);
4339   }
4340   
4341   bool isSugared() const { return false; }
4342   QualType desugar() const { return QualType(this, 0); }
4343
4344   void Profile(llvm::FoldingSetNodeID &ID) {
4345     Profile(ID, getPointeeType());
4346   }
4347   static void Profile(llvm::FoldingSetNodeID &ID, QualType T) {
4348     ID.AddPointer(T.getAsOpaquePtr());
4349   }
4350   static bool classof(const Type *T) {
4351     return T->getTypeClass() == ObjCObjectPointer;
4352   }
4353   static bool classof(const ObjCObjectPointerType *) { return true; }
4354 };
4355
4356 class AtomicType : public Type, public llvm::FoldingSetNode {
4357   QualType ValueType;
4358
4359   AtomicType(QualType ValTy, QualType Canonical)
4360     : Type(Atomic, Canonical, ValTy->isDependentType(),
4361            ValTy->isInstantiationDependentType(),
4362            ValTy->isVariablyModifiedType(),
4363            ValTy->containsUnexpandedParameterPack()),
4364       ValueType(ValTy) {}
4365   friend class ASTContext;  // ASTContext creates these.
4366
4367   public:
4368   /// getValueType - Gets the type contained by this atomic type, i.e.
4369   /// the type returned by performing an atomic load of this atomic type.
4370   QualType getValueType() const { return ValueType; }
4371
4372   bool isSugared() const { return false; }
4373   QualType desugar() const { return QualType(this, 0); }
4374
4375   void Profile(llvm::FoldingSetNodeID &ID) {
4376     Profile(ID, getValueType());
4377   }
4378   static void Profile(llvm::FoldingSetNodeID &ID, QualType T) {
4379     ID.AddPointer(T.getAsOpaquePtr());
4380   }
4381   static bool classof(const Type *T) {
4382     return T->getTypeClass() == Atomic;
4383   }
4384   static bool classof(const AtomicType *) { return true; }
4385 };
4386
4387 /// A qualifier set is used to build a set of qualifiers.
4388 class QualifierCollector : public Qualifiers {
4389 public:
4390   QualifierCollector(Qualifiers Qs = Qualifiers()) : Qualifiers(Qs) {}
4391
4392   /// Collect any qualifiers on the given type and return an
4393   /// unqualified type.  The qualifiers are assumed to be consistent
4394   /// with those already in the type.
4395   const Type *strip(QualType type) {
4396     addFastQualifiers(type.getLocalFastQualifiers());
4397     if (!type.hasLocalNonFastQualifiers())
4398       return type.getTypePtrUnsafe();
4399       
4400     const ExtQuals *extQuals = type.getExtQualsUnsafe();
4401     addConsistentQualifiers(extQuals->getQualifiers());
4402     return extQuals->getBaseType();
4403   }
4404
4405   /// Apply the collected qualifiers to the given type.
4406   QualType apply(const ASTContext &Context, QualType QT) const;
4407
4408   /// Apply the collected qualifiers to the given type.
4409   QualType apply(const ASTContext &Context, const Type* T) const;
4410 };
4411
4412
4413 // Inline function definitions.
4414
4415 inline const Type *QualType::getTypePtr() const {
4416   return getCommonPtr()->BaseType;
4417 }
4418
4419 inline const Type *QualType::getTypePtrOrNull() const {
4420   return (isNull() ? 0 : getCommonPtr()->BaseType);
4421 }
4422
4423 inline SplitQualType QualType::split() const {
4424   if (!hasLocalNonFastQualifiers())
4425     return SplitQualType(getTypePtrUnsafe(),
4426                          Qualifiers::fromFastMask(getLocalFastQualifiers()));
4427
4428   const ExtQuals *eq = getExtQualsUnsafe();
4429   Qualifiers qs = eq->getQualifiers();
4430   qs.addFastQualifiers(getLocalFastQualifiers());
4431   return SplitQualType(eq->getBaseType(), qs);
4432 }
4433
4434 inline Qualifiers QualType::getLocalQualifiers() const {
4435   Qualifiers Quals;
4436   if (hasLocalNonFastQualifiers())
4437     Quals = getExtQualsUnsafe()->getQualifiers();
4438   Quals.addFastQualifiers(getLocalFastQualifiers());
4439   return Quals;
4440 }
4441
4442 inline Qualifiers QualType::getQualifiers() const {
4443   Qualifiers quals = getCommonPtr()->CanonicalType.getLocalQualifiers();
4444   quals.addFastQualifiers(getLocalFastQualifiers());
4445   return quals;
4446 }
4447
4448 inline unsigned QualType::getCVRQualifiers() const {
4449   unsigned cvr = getCommonPtr()->CanonicalType.getLocalCVRQualifiers();
4450   cvr |= getLocalCVRQualifiers();
4451   return cvr;
4452 }
4453
4454 inline QualType QualType::getCanonicalType() const {
4455   QualType canon = getCommonPtr()->CanonicalType;
4456   return canon.withFastQualifiers(getLocalFastQualifiers());
4457 }
4458
4459 inline bool QualType::isCanonical() const {
4460   return getTypePtr()->isCanonicalUnqualified();
4461 }
4462
4463 inline bool QualType::isCanonicalAsParam() const {
4464   if (!isCanonical()) return false;
4465   if (hasLocalQualifiers()) return false;
4466   
4467   const Type *T = getTypePtr();
4468   if (T->isVariablyModifiedType() && T->hasSizedVLAType())
4469     return false;
4470
4471   return !isa<FunctionType>(T) && !isa<ArrayType>(T);
4472 }
4473
4474 inline bool QualType::isConstQualified() const {
4475   return isLocalConstQualified() || 
4476          getCommonPtr()->CanonicalType.isLocalConstQualified();
4477 }
4478
4479 inline bool QualType::isRestrictQualified() const {
4480   return isLocalRestrictQualified() || 
4481          getCommonPtr()->CanonicalType.isLocalRestrictQualified();
4482 }
4483
4484
4485 inline bool QualType::isVolatileQualified() const {
4486   return isLocalVolatileQualified() || 
4487          getCommonPtr()->CanonicalType.isLocalVolatileQualified();
4488 }
4489   
4490 inline bool QualType::hasQualifiers() const {
4491   return hasLocalQualifiers() ||
4492          getCommonPtr()->CanonicalType.hasLocalQualifiers();
4493 }
4494
4495 inline QualType QualType::getUnqualifiedType() const {
4496   if (!getTypePtr()->getCanonicalTypeInternal().hasLocalQualifiers())
4497     return QualType(getTypePtr(), 0);
4498
4499   return QualType(getSplitUnqualifiedTypeImpl(*this).first, 0);
4500 }
4501
4502 inline SplitQualType QualType::getSplitUnqualifiedType() const {
4503   if (!getTypePtr()->getCanonicalTypeInternal().hasLocalQualifiers())
4504     return split();
4505
4506   return getSplitUnqualifiedTypeImpl(*this);
4507 }
4508   
4509 inline void QualType::removeLocalConst() {
4510   removeLocalFastQualifiers(Qualifiers::Const);
4511 }
4512
4513 inline void QualType::removeLocalRestrict() {
4514   removeLocalFastQualifiers(Qualifiers::Restrict);
4515 }
4516
4517 inline void QualType::removeLocalVolatile() {
4518   removeLocalFastQualifiers(Qualifiers::Volatile);
4519 }
4520
4521 inline void QualType::removeLocalCVRQualifiers(unsigned Mask) {
4522   assert(!(Mask & ~Qualifiers::CVRMask) && "mask has non-CVR bits");
4523   assert((int)Qualifiers::CVRMask == (int)Qualifiers::FastMask);
4524
4525   // Fast path: we don't need to touch the slow qualifiers.
4526   removeLocalFastQualifiers(Mask);
4527 }
4528
4529 /// getAddressSpace - Return the address space of this type.
4530 inline unsigned QualType::getAddressSpace() const {
4531   return getQualifiers().getAddressSpace();
4532 }
4533
4534 /// getObjCGCAttr - Return the gc attribute of this type.
4535 inline Qualifiers::GC QualType::getObjCGCAttr() const {
4536   return getQualifiers().getObjCGCAttr();
4537 }
4538
4539 inline FunctionType::ExtInfo getFunctionExtInfo(const Type &t) {
4540   if (const PointerType *PT = t.getAs<PointerType>()) {
4541     if (const FunctionType *FT = PT->getPointeeType()->getAs<FunctionType>())
4542       return FT->getExtInfo();
4543   } else if (const FunctionType *FT = t.getAs<FunctionType>())
4544     return FT->getExtInfo();
4545
4546   return FunctionType::ExtInfo();
4547 }
4548
4549 inline FunctionType::ExtInfo getFunctionExtInfo(QualType t) {
4550   return getFunctionExtInfo(*t);
4551 }
4552
4553 /// isMoreQualifiedThan - Determine whether this type is more
4554 /// qualified than the Other type. For example, "const volatile int"
4555 /// is more qualified than "const int", "volatile int", and
4556 /// "int". However, it is not more qualified than "const volatile
4557 /// int".
4558 inline bool QualType::isMoreQualifiedThan(QualType other) const {
4559   Qualifiers myQuals = getQualifiers();
4560   Qualifiers otherQuals = other.getQualifiers();
4561   return (myQuals != otherQuals && myQuals.compatiblyIncludes(otherQuals));
4562 }
4563
4564 /// isAtLeastAsQualifiedAs - Determine whether this type is at last
4565 /// as qualified as the Other type. For example, "const volatile
4566 /// int" is at least as qualified as "const int", "volatile int",
4567 /// "int", and "const volatile int".
4568 inline bool QualType::isAtLeastAsQualifiedAs(QualType other) const {
4569   return getQualifiers().compatiblyIncludes(other.getQualifiers());
4570 }
4571
4572 /// getNonReferenceType - If Type is a reference type (e.g., const
4573 /// int&), returns the type that the reference refers to ("const
4574 /// int"). Otherwise, returns the type itself. This routine is used
4575 /// throughout Sema to implement C++ 5p6:
4576 ///
4577 ///   If an expression initially has the type "reference to T" (8.3.2,
4578 ///   8.5.3), the type is adjusted to "T" prior to any further
4579 ///   analysis, the expression designates the object or function
4580 ///   denoted by the reference, and the expression is an lvalue.
4581 inline QualType QualType::getNonReferenceType() const {
4582   if (const ReferenceType *RefType = (*this)->getAs<ReferenceType>())
4583     return RefType->getPointeeType();
4584   else
4585     return *this;
4586 }
4587
4588 inline bool QualType::isCForbiddenLValueType() const {
4589   return ((getTypePtr()->isVoidType() && !hasQualifiers()) ||
4590           getTypePtr()->isFunctionType());
4591 }
4592
4593 /// \brief Tests whether the type is categorized as a fundamental type.
4594 ///
4595 /// \returns True for types specified in C++0x [basic.fundamental].
4596 inline bool Type::isFundamentalType() const {
4597   return isVoidType() ||
4598          // FIXME: It's really annoying that we don't have an
4599          // 'isArithmeticType()' which agrees with the standard definition.
4600          (isArithmeticType() && !isEnumeralType());
4601 }
4602
4603 /// \brief Tests whether the type is categorized as a compound type.
4604 ///
4605 /// \returns True for types specified in C++0x [basic.compound].
4606 inline bool Type::isCompoundType() const {
4607   // C++0x [basic.compound]p1:
4608   //   Compound types can be constructed in the following ways:
4609   //    -- arrays of objects of a given type [...];
4610   return isArrayType() ||
4611   //    -- functions, which have parameters of given types [...];
4612          isFunctionType() ||
4613   //    -- pointers to void or objects or functions [...];
4614          isPointerType() ||
4615   //    -- references to objects or functions of a given type. [...]
4616          isReferenceType() ||
4617   //    -- classes containing a sequence of objects of various types, [...];
4618          isRecordType() ||
4619   //    -- unions, which ar classes capable of containing objects of different types at different times;
4620          isUnionType() ||
4621   //    -- enumerations, which comprise a set of named constant values. [...];
4622          isEnumeralType() ||
4623   //    -- pointers to non-static class members, [...].
4624          isMemberPointerType();
4625 }
4626
4627 inline bool Type::isFunctionType() const {
4628   return isa<FunctionType>(CanonicalType);
4629 }
4630 inline bool Type::isPointerType() const {
4631   return isa<PointerType>(CanonicalType);
4632 }
4633 inline bool Type::isAnyPointerType() const {
4634   return isPointerType() || isObjCObjectPointerType();
4635 }
4636 inline bool Type::isBlockPointerType() const {
4637   return isa<BlockPointerType>(CanonicalType);
4638 }
4639 inline bool Type::isReferenceType() const {
4640   return isa<ReferenceType>(CanonicalType);
4641 }
4642 inline bool Type::isLValueReferenceType() const {
4643   return isa<LValueReferenceType>(CanonicalType);
4644 }
4645 inline bool Type::isRValueReferenceType() const {
4646   return isa<RValueReferenceType>(CanonicalType);
4647 }
4648 inline bool Type::isFunctionPointerType() const {
4649   if (const PointerType *T = getAs<PointerType>())
4650     return T->getPointeeType()->isFunctionType();
4651   else
4652     return false;
4653 }
4654 inline bool Type::isMemberPointerType() const {
4655   return isa<MemberPointerType>(CanonicalType);
4656 }
4657 inline bool Type::isMemberFunctionPointerType() const {
4658   if (const MemberPointerType* T = getAs<MemberPointerType>())
4659     return T->isMemberFunctionPointer();
4660   else
4661     return false;
4662 }
4663 inline bool Type::isMemberDataPointerType() const {
4664   if (const MemberPointerType* T = getAs<MemberPointerType>())
4665     return T->isMemberDataPointer();
4666   else
4667     return false;
4668 }
4669 inline bool Type::isArrayType() const {
4670   return isa<ArrayType>(CanonicalType);
4671 }
4672 inline bool Type::isConstantArrayType() const {
4673   return isa<ConstantArrayType>(CanonicalType);
4674 }
4675 inline bool Type::isIncompleteArrayType() const {
4676   return isa<IncompleteArrayType>(CanonicalType);
4677 }
4678 inline bool Type::isVariableArrayType() const {
4679   return isa<VariableArrayType>(CanonicalType);
4680 }
4681 inline bool Type::isDependentSizedArrayType() const {
4682   return isa<DependentSizedArrayType>(CanonicalType);
4683 }
4684 inline bool Type::isBuiltinType() const {
4685   return isa<BuiltinType>(CanonicalType);
4686 }
4687 inline bool Type::isRecordType() const {
4688   return isa<RecordType>(CanonicalType);
4689 }
4690 inline bool Type::isEnumeralType() const {
4691   return isa<EnumType>(CanonicalType);
4692 }
4693 inline bool Type::isAnyComplexType() const {
4694   return isa<ComplexType>(CanonicalType);
4695 }
4696 inline bool Type::isVectorType() const {
4697   return isa<VectorType>(CanonicalType);
4698 }
4699 inline bool Type::isExtVectorType() const {
4700   return isa<ExtVectorType>(CanonicalType);
4701 }
4702 inline bool Type::isObjCObjectPointerType() const {
4703   return isa<ObjCObjectPointerType>(CanonicalType);
4704 }
4705 inline bool Type::isObjCObjectType() const {
4706   return isa<ObjCObjectType>(CanonicalType);
4707 }
4708 inline bool Type::isObjCObjectOrInterfaceType() const {
4709   return isa<ObjCInterfaceType>(CanonicalType) || 
4710     isa<ObjCObjectType>(CanonicalType);
4711 }
4712 inline bool Type::isAtomicType() const {
4713   return isa<AtomicType>(CanonicalType);
4714 }
4715
4716 inline bool Type::isObjCQualifiedIdType() const {
4717   if (const ObjCObjectPointerType *OPT = getAs<ObjCObjectPointerType>())
4718     return OPT->isObjCQualifiedIdType();
4719   return false;
4720 }
4721 inline bool Type::isObjCQualifiedClassType() const {
4722   if (const ObjCObjectPointerType *OPT = getAs<ObjCObjectPointerType>())
4723     return OPT->isObjCQualifiedClassType();
4724   return false;
4725 }
4726 inline bool Type::isObjCIdType() const {
4727   if (const ObjCObjectPointerType *OPT = getAs<ObjCObjectPointerType>())
4728     return OPT->isObjCIdType();
4729   return false;
4730 }
4731 inline bool Type::isObjCClassType() const {
4732   if (const ObjCObjectPointerType *OPT = getAs<ObjCObjectPointerType>())
4733     return OPT->isObjCClassType();
4734   return false;
4735 }
4736 inline bool Type::isObjCSelType() const {
4737   if (const PointerType *OPT = getAs<PointerType>())
4738     return OPT->getPointeeType()->isSpecificBuiltinType(BuiltinType::ObjCSel);
4739   return false;
4740 }
4741 inline bool Type::isObjCBuiltinType() const {
4742   return isObjCIdType() || isObjCClassType() || isObjCSelType();
4743 }
4744 inline bool Type::isTemplateTypeParmType() const {
4745   return isa<TemplateTypeParmType>(CanonicalType);
4746 }
4747
4748 inline bool Type::isSpecificBuiltinType(unsigned K) const {
4749   if (const BuiltinType *BT = getAs<BuiltinType>())
4750     if (BT->getKind() == (BuiltinType::Kind) K)
4751       return true;
4752   return false;
4753 }
4754
4755 inline bool Type::isPlaceholderType() const {
4756   if (const BuiltinType *BT = dyn_cast<BuiltinType>(this))
4757     return BT->isPlaceholderType();
4758   return false;
4759 }
4760
4761 inline const BuiltinType *Type::getAsPlaceholderType() const {
4762   if (const BuiltinType *BT = dyn_cast<BuiltinType>(this))
4763     if (BT->isPlaceholderType())
4764       return BT;
4765   return 0;
4766 }
4767
4768 inline bool Type::isSpecificPlaceholderType(unsigned K) const {
4769   if (const BuiltinType *BT = dyn_cast<BuiltinType>(this))
4770     return (BT->getKind() == (BuiltinType::Kind) K);
4771   return false;
4772 }
4773
4774 /// \brief Determines whether this is a type for which one can define
4775 /// an overloaded operator.
4776 inline bool Type::isOverloadableType() const {
4777   return isDependentType() || isRecordType() || isEnumeralType();
4778 }
4779
4780 /// \brief Determines whether this type can decay to a pointer type.
4781 inline bool Type::canDecayToPointerType() const {
4782   return isFunctionType() || isArrayType();
4783 }
4784
4785 inline bool Type::hasPointerRepresentation() const {
4786   return (isPointerType() || isReferenceType() || isBlockPointerType() ||
4787           isObjCObjectPointerType() || isNullPtrType());
4788 }
4789
4790 inline bool Type::hasObjCPointerRepresentation() const {
4791   return isObjCObjectPointerType();
4792 }
4793
4794 inline const Type *Type::getBaseElementTypeUnsafe() const {
4795   const Type *type = this;
4796   while (const ArrayType *arrayType = type->getAsArrayTypeUnsafe())
4797     type = arrayType->getElementType().getTypePtr();
4798   return type;
4799 }
4800
4801 /// Insertion operator for diagnostics.  This allows sending QualType's into a
4802 /// diagnostic with <<.
4803 inline const DiagnosticBuilder &operator<<(const DiagnosticBuilder &DB,
4804                                            QualType T) {
4805   DB.AddTaggedVal(reinterpret_cast<intptr_t>(T.getAsOpaquePtr()),
4806                   DiagnosticsEngine::ak_qualtype);
4807   return DB;
4808 }
4809
4810 /// Insertion operator for partial diagnostics.  This allows sending QualType's
4811 /// into a diagnostic with <<.
4812 inline const PartialDiagnostic &operator<<(const PartialDiagnostic &PD,
4813                                            QualType T) {
4814   PD.AddTaggedVal(reinterpret_cast<intptr_t>(T.getAsOpaquePtr()),
4815                   DiagnosticsEngine::ak_qualtype);
4816   return PD;
4817 }
4818
4819 // Helper class template that is used by Type::getAs to ensure that one does
4820 // not try to look through a qualified type to get to an array type.
4821 template<typename T,
4822          bool isArrayType = (llvm::is_same<T, ArrayType>::value ||
4823                              llvm::is_base_of<ArrayType, T>::value)>
4824 struct ArrayType_cannot_be_used_with_getAs { };
4825   
4826 template<typename T>
4827 struct ArrayType_cannot_be_used_with_getAs<T, true>;
4828   
4829 /// Member-template getAs<specific type>'.
4830 template <typename T> const T *Type::getAs() const {
4831   ArrayType_cannot_be_used_with_getAs<T> at;
4832   (void)at;
4833   
4834   // If this is directly a T type, return it.
4835   if (const T *Ty = dyn_cast<T>(this))
4836     return Ty;
4837
4838   // If the canonical form of this type isn't the right kind, reject it.
4839   if (!isa<T>(CanonicalType))
4840     return 0;
4841
4842   // If this is a typedef for the type, strip the typedef off without
4843   // losing all typedef information.
4844   return cast<T>(getUnqualifiedDesugaredType());
4845 }
4846
4847 inline const ArrayType *Type::getAsArrayTypeUnsafe() const {
4848   // If this is directly an array type, return it.
4849   if (const ArrayType *arr = dyn_cast<ArrayType>(this))
4850     return arr;
4851
4852   // If the canonical form of this type isn't the right kind, reject it.
4853   if (!isa<ArrayType>(CanonicalType))
4854     return 0;
4855
4856   // If this is a typedef for the type, strip the typedef off without
4857   // losing all typedef information.
4858   return cast<ArrayType>(getUnqualifiedDesugaredType());
4859 }
4860
4861 template <typename T> const T *Type::castAs() const {
4862   ArrayType_cannot_be_used_with_getAs<T> at;
4863   (void) at;
4864
4865   assert(isa<T>(CanonicalType));
4866   if (const T *ty = dyn_cast<T>(this)) return ty;
4867   return cast<T>(getUnqualifiedDesugaredType());
4868 }
4869
4870 inline const ArrayType *Type::castAsArrayTypeUnsafe() const {
4871   assert(isa<ArrayType>(CanonicalType));
4872   if (const ArrayType *arr = dyn_cast<ArrayType>(this)) return arr;
4873   return cast<ArrayType>(getUnqualifiedDesugaredType());
4874 }
4875
4876 }  // end namespace clang
4877
4878 #endif