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