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