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