]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - include/clang/AST/Type.h
Vendor import of clang trunk r338150:
[FreeBSD/FreeBSD.git] / 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 TagDecl that this type refers to, either
2021   /// because the type is a TagType or because it is the injected-class-name
2022   /// type of a class template or class template partial specialization.
2023   TagDecl *getAsTagDecl() const;
2024
2025   /// If this is a pointer or reference to a RecordType, return the
2026   /// CXXRecordDecl that the type refers to.
2027   ///
2028   /// If this is not a pointer or reference, or the type being pointed to does
2029   /// not refer to a CXXRecordDecl, returns NULL.
2030   const CXXRecordDecl *getPointeeCXXRecordDecl() const;
2031
2032   /// Get the DeducedType whose type will be deduced for a variable with
2033   /// an initializer of this type. This looks through declarators like pointer
2034   /// types, but not through decltype or typedefs.
2035   DeducedType *getContainedDeducedType() const;
2036
2037   /// Get the AutoType whose type will be deduced for a variable with
2038   /// an initializer of this type. This looks through declarators like pointer
2039   /// types, but not through decltype or typedefs.
2040   AutoType *getContainedAutoType() const {
2041     return dyn_cast_or_null<AutoType>(getContainedDeducedType());
2042   }
2043
2044   /// Determine whether this type was written with a leading 'auto'
2045   /// corresponding to a trailing return type (possibly for a nested
2046   /// function type within a pointer to function type or similar).
2047   bool hasAutoForTrailingReturnType() const;
2048
2049   /// Member-template getAs<specific type>'.  Look through sugar for
2050   /// an instance of \<specific type>.   This scheme will eventually
2051   /// replace the specific getAsXXXX methods above.
2052   ///
2053   /// There are some specializations of this member template listed
2054   /// immediately following this class.
2055   template <typename T> const T *getAs() const;
2056
2057   /// Member-template getAsAdjusted<specific type>. Look through specific kinds
2058   /// of sugar (parens, attributes, etc) for an instance of \<specific type>.
2059   /// This is used when you need to walk over sugar nodes that represent some
2060   /// kind of type adjustment from a type that was written as a \<specific type>
2061   /// to another type that is still canonically a \<specific type>.
2062   template <typename T> const T *getAsAdjusted() const;
2063
2064   /// A variant of getAs<> for array types which silently discards
2065   /// qualifiers from the outermost type.
2066   const ArrayType *getAsArrayTypeUnsafe() const;
2067
2068   /// Member-template castAs<specific type>.  Look through sugar for
2069   /// the underlying instance of \<specific type>.
2070   ///
2071   /// This method has the same relationship to getAs<T> as cast<T> has
2072   /// to dyn_cast<T>; which is to say, the underlying type *must*
2073   /// have the intended type, and this method will never return null.
2074   template <typename T> const T *castAs() const;
2075
2076   /// A variant of castAs<> for array type which silently discards
2077   /// qualifiers from the outermost type.
2078   const ArrayType *castAsArrayTypeUnsafe() const;
2079
2080   /// Get the base element type of this type, potentially discarding type
2081   /// qualifiers.  This should never be used when type qualifiers
2082   /// are meaningful.
2083   const Type *getBaseElementTypeUnsafe() const;
2084
2085   /// If this is an array type, return the element type of the array,
2086   /// potentially with type qualifiers missing.
2087   /// This should never be used when type qualifiers are meaningful.
2088   const Type *getArrayElementTypeNoTypeQual() const;
2089
2090   /// If this is a pointer type, return the pointee type.
2091   /// If this is an array type, return the array element type.
2092   /// This should never be used when type qualifiers are meaningful.
2093   const Type *getPointeeOrArrayElementType() const;
2094
2095   /// If this is a pointer, ObjC object pointer, or block
2096   /// pointer, this returns the respective pointee.
2097   QualType getPointeeType() const;
2098
2099   /// Return the specified type with any "sugar" removed from the type,
2100   /// removing any typedefs, typeofs, etc., as well as any qualifiers.
2101   const Type *getUnqualifiedDesugaredType() const;
2102
2103   /// More type predicates useful for type checking/promotion
2104   bool isPromotableIntegerType() const; // C99 6.3.1.1p2
2105
2106   /// Return true if this is an integer type that is
2107   /// signed, according to C99 6.2.5p4 [char, signed char, short, int, long..],
2108   /// or an enum decl which has a signed representation.
2109   bool isSignedIntegerType() const;
2110
2111   /// Return true if this is an integer type that is
2112   /// unsigned, according to C99 6.2.5p6 [which returns true for _Bool],
2113   /// or an enum decl which has an unsigned representation.
2114   bool isUnsignedIntegerType() const;
2115
2116   /// Determines whether this is an integer type that is signed or an
2117   /// enumeration types whose underlying type is a signed integer type.
2118   bool isSignedIntegerOrEnumerationType() const;
2119
2120   /// Determines whether this is an integer type that is unsigned or an
2121   /// enumeration types whose underlying type is a unsigned integer type.
2122   bool isUnsignedIntegerOrEnumerationType() const;
2123
2124   /// Return true if this is a fixed point type according to
2125   /// ISO/IEC JTC1 SC22 WG14 N1169.
2126   bool isFixedPointType() const;
2127
2128   /// Return true if this is a saturated fixed point type according to
2129   /// ISO/IEC JTC1 SC22 WG14 N1169. This type can be signed or unsigned.
2130   bool isSaturatedFixedPointType() const;
2131
2132   /// Return true if this is a saturated fixed point type according to
2133   /// ISO/IEC JTC1 SC22 WG14 N1169. This type can be signed or unsigned.
2134   bool isUnsaturatedFixedPointType() const;
2135
2136   /// Return true if this is a fixed point type that is signed according
2137   /// to ISO/IEC JTC1 SC22 WG14 N1169. This type can also be saturated.
2138   bool isSignedFixedPointType() const;
2139
2140   /// Return true if this is a fixed point type that is unsigned according
2141   /// to ISO/IEC JTC1 SC22 WG14 N1169. This type can also be saturated.
2142   bool isUnsignedFixedPointType() const;
2143
2144   /// Return true if this is not a variable sized type,
2145   /// according to the rules of C99 6.7.5p3.  It is not legal to call this on
2146   /// incomplete types.
2147   bool isConstantSizeType() const;
2148
2149   /// Returns true if this type can be represented by some
2150   /// set of type specifiers.
2151   bool isSpecifierType() const;
2152
2153   /// Determine the linkage of this type.
2154   Linkage getLinkage() const;
2155
2156   /// Determine the visibility of this type.
2157   Visibility getVisibility() const {
2158     return getLinkageAndVisibility().getVisibility();
2159   }
2160
2161   /// Return true if the visibility was explicitly set is the code.
2162   bool isVisibilityExplicit() const {
2163     return getLinkageAndVisibility().isVisibilityExplicit();
2164   }
2165
2166   /// Determine the linkage and visibility of this type.
2167   LinkageInfo getLinkageAndVisibility() const;
2168
2169   /// True if the computed linkage is valid. Used for consistency
2170   /// checking. Should always return true.
2171   bool isLinkageValid() const;
2172
2173   /// Determine the nullability of the given type.
2174   ///
2175   /// Note that nullability is only captured as sugar within the type
2176   /// system, not as part of the canonical type, so nullability will
2177   /// be lost by canonicalization and desugaring.
2178   Optional<NullabilityKind> getNullability(const ASTContext &context) const;
2179
2180   /// Determine whether the given type can have a nullability
2181   /// specifier applied to it, i.e., if it is any kind of pointer type.
2182   ///
2183   /// \param ResultIfUnknown The value to return if we don't yet know whether
2184   ///        this type can have nullability because it is dependent.
2185   bool canHaveNullability(bool ResultIfUnknown = true) const;
2186
2187   /// Retrieve the set of substitutions required when accessing a member
2188   /// of the Objective-C receiver type that is declared in the given context.
2189   ///
2190   /// \c *this is the type of the object we're operating on, e.g., the
2191   /// receiver for a message send or the base of a property access, and is
2192   /// expected to be of some object or object pointer type.
2193   ///
2194   /// \param dc The declaration context for which we are building up a
2195   /// substitution mapping, which should be an Objective-C class, extension,
2196   /// category, or method within.
2197   ///
2198   /// \returns an array of type arguments that can be substituted for
2199   /// the type parameters of the given declaration context in any type described
2200   /// within that context, or an empty optional to indicate that no
2201   /// substitution is required.
2202   Optional<ArrayRef<QualType>>
2203   getObjCSubstitutions(const DeclContext *dc) const;
2204
2205   /// Determines if this is an ObjC interface type that may accept type
2206   /// parameters.
2207   bool acceptsObjCTypeParams() const;
2208
2209   const char *getTypeClassName() const;
2210
2211   QualType getCanonicalTypeInternal() const {
2212     return CanonicalType;
2213   }
2214
2215   CanQualType getCanonicalTypeUnqualified() const; // in CanonicalType.h
2216   void dump() const;
2217   void dump(llvm::raw_ostream &OS) const;
2218 };
2219
2220 /// This will check for a TypedefType by removing any existing sugar
2221 /// until it reaches a TypedefType or a non-sugared type.
2222 template <> const TypedefType *Type::getAs() const;
2223
2224 /// This will check for a TemplateSpecializationType by removing any
2225 /// existing sugar until it reaches a TemplateSpecializationType or a
2226 /// non-sugared type.
2227 template <> const TemplateSpecializationType *Type::getAs() const;
2228
2229 /// This will check for an AttributedType by removing any existing sugar
2230 /// until it reaches an AttributedType or a non-sugared type.
2231 template <> const AttributedType *Type::getAs() const;
2232
2233 // We can do canonical leaf types faster, because we don't have to
2234 // worry about preserving child type decoration.
2235 #define TYPE(Class, Base)
2236 #define LEAF_TYPE(Class) \
2237 template <> inline const Class##Type *Type::getAs() const { \
2238   return dyn_cast<Class##Type>(CanonicalType); \
2239 } \
2240 template <> inline const Class##Type *Type::castAs() const { \
2241   return cast<Class##Type>(CanonicalType); \
2242 }
2243 #include "clang/AST/TypeNodes.def"
2244
2245 /// This class is used for builtin types like 'int'.  Builtin
2246 /// types are always canonical and have a literal name field.
2247 class BuiltinType : public Type {
2248 public:
2249   enum Kind {
2250 // OpenCL image types
2251 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) Id,
2252 #include "clang/Basic/OpenCLImageTypes.def"
2253 // All other builtin types
2254 #define BUILTIN_TYPE(Id, SingletonId) Id,
2255 #define LAST_BUILTIN_TYPE(Id) LastKind = Id
2256 #include "clang/AST/BuiltinTypes.def"
2257   };
2258
2259 private:
2260   friend class ASTContext; // ASTContext creates these.
2261
2262   BuiltinType(Kind K)
2263       : Type(Builtin, QualType(), /*Dependent=*/(K == Dependent),
2264              /*InstantiationDependent=*/(K == Dependent),
2265              /*VariablyModified=*/false,
2266              /*Unexpanded parameter pack=*/false) {
2267     BuiltinTypeBits.Kind = K;
2268   }
2269
2270 public:
2271   Kind getKind() const { return static_cast<Kind>(BuiltinTypeBits.Kind); }
2272   StringRef getName(const PrintingPolicy &Policy) const;
2273
2274   const char *getNameAsCString(const PrintingPolicy &Policy) const {
2275     // The StringRef is null-terminated.
2276     StringRef str = getName(Policy);
2277     assert(!str.empty() && str.data()[str.size()] == '\0');
2278     return str.data();
2279   }
2280
2281   bool isSugared() const { return false; }
2282   QualType desugar() const { return QualType(this, 0); }
2283
2284   bool isInteger() const {
2285     return getKind() >= Bool && getKind() <= Int128;
2286   }
2287
2288   bool isSignedInteger() const {
2289     return getKind() >= Char_S && getKind() <= Int128;
2290   }
2291
2292   bool isUnsignedInteger() const {
2293     return getKind() >= Bool && getKind() <= UInt128;
2294   }
2295
2296   bool isFloatingPoint() const {
2297     return getKind() >= Half && getKind() <= Float128;
2298   }
2299
2300   /// Determines whether the given kind corresponds to a placeholder type.
2301   static bool isPlaceholderTypeKind(Kind K) {
2302     return K >= Overload;
2303   }
2304
2305   /// Determines whether this type is a placeholder type, i.e. a type
2306   /// which cannot appear in arbitrary positions in a fully-formed
2307   /// expression.
2308   bool isPlaceholderType() const {
2309     return isPlaceholderTypeKind(getKind());
2310   }
2311
2312   /// Determines whether this type is a placeholder type other than
2313   /// Overload.  Most placeholder types require only syntactic
2314   /// information about their context in order to be resolved (e.g.
2315   /// whether it is a call expression), which means they can (and
2316   /// should) be resolved in an earlier "phase" of analysis.
2317   /// Overload expressions sometimes pick up further information
2318   /// from their context, like whether the context expects a
2319   /// specific function-pointer type, and so frequently need
2320   /// special treatment.
2321   bool isNonOverloadPlaceholderType() const {
2322     return getKind() > Overload;
2323   }
2324
2325   static bool classof(const Type *T) { return T->getTypeClass() == Builtin; }
2326 };
2327
2328 /// Complex values, per C99 6.2.5p11.  This supports the C99 complex
2329 /// types (_Complex float etc) as well as the GCC integer complex extensions.
2330 class ComplexType : public Type, public llvm::FoldingSetNode {
2331   friend class ASTContext; // ASTContext creates these.
2332
2333   QualType ElementType;
2334
2335   ComplexType(QualType Element, QualType CanonicalPtr)
2336       : Type(Complex, CanonicalPtr, Element->isDependentType(),
2337              Element->isInstantiationDependentType(),
2338              Element->isVariablyModifiedType(),
2339              Element->containsUnexpandedParameterPack()),
2340         ElementType(Element) {}
2341
2342 public:
2343   QualType getElementType() const { return ElementType; }
2344
2345   bool isSugared() const { return false; }
2346   QualType desugar() const { return QualType(this, 0); }
2347
2348   void Profile(llvm::FoldingSetNodeID &ID) {
2349     Profile(ID, getElementType());
2350   }
2351
2352   static void Profile(llvm::FoldingSetNodeID &ID, QualType Element) {
2353     ID.AddPointer(Element.getAsOpaquePtr());
2354   }
2355
2356   static bool classof(const Type *T) { return T->getTypeClass() == Complex; }
2357 };
2358
2359 /// Sugar for parentheses used when specifying types.
2360 class ParenType : public Type, public llvm::FoldingSetNode {
2361   friend class ASTContext; // ASTContext creates these.
2362
2363   QualType Inner;
2364
2365   ParenType(QualType InnerType, QualType CanonType)
2366       : Type(Paren, CanonType, InnerType->isDependentType(),
2367              InnerType->isInstantiationDependentType(),
2368              InnerType->isVariablyModifiedType(),
2369              InnerType->containsUnexpandedParameterPack()),
2370         Inner(InnerType) {}
2371
2372 public:
2373   QualType getInnerType() const { return Inner; }
2374
2375   bool isSugared() const { return true; }
2376   QualType desugar() const { return getInnerType(); }
2377
2378   void Profile(llvm::FoldingSetNodeID &ID) {
2379     Profile(ID, getInnerType());
2380   }
2381
2382   static void Profile(llvm::FoldingSetNodeID &ID, QualType Inner) {
2383     Inner.Profile(ID);
2384   }
2385
2386   static bool classof(const Type *T) { return T->getTypeClass() == Paren; }
2387 };
2388
2389 /// PointerType - C99 6.7.5.1 - Pointer Declarators.
2390 class PointerType : public Type, public llvm::FoldingSetNode {
2391   friend class ASTContext; // ASTContext creates these.
2392
2393   QualType PointeeType;
2394
2395   PointerType(QualType Pointee, QualType CanonicalPtr)
2396       : Type(Pointer, CanonicalPtr, Pointee->isDependentType(),
2397              Pointee->isInstantiationDependentType(),
2398              Pointee->isVariablyModifiedType(),
2399              Pointee->containsUnexpandedParameterPack()),
2400         PointeeType(Pointee) {}
2401
2402 public:
2403   QualType getPointeeType() const { return PointeeType; }
2404
2405   /// Returns true if address spaces of pointers overlap.
2406   /// OpenCL v2.0 defines conversion rules for pointers to different
2407   /// address spaces (OpenCLC v2.0 s6.5.5) and notion of overlapping
2408   /// address spaces.
2409   /// CL1.1 or CL1.2:
2410   ///   address spaces overlap iff they are they same.
2411   /// CL2.0 adds:
2412   ///   __generic overlaps with any address space except for __constant.
2413   bool isAddressSpaceOverlapping(const PointerType &other) const {
2414     Qualifiers thisQuals = PointeeType.getQualifiers();
2415     Qualifiers otherQuals = other.getPointeeType().getQualifiers();
2416     // Address spaces overlap if at least one of them is a superset of another
2417     return thisQuals.isAddressSpaceSupersetOf(otherQuals) ||
2418            otherQuals.isAddressSpaceSupersetOf(thisQuals);
2419   }
2420
2421   bool isSugared() const { return false; }
2422   QualType desugar() const { return QualType(this, 0); }
2423
2424   void Profile(llvm::FoldingSetNodeID &ID) {
2425     Profile(ID, getPointeeType());
2426   }
2427
2428   static void Profile(llvm::FoldingSetNodeID &ID, QualType Pointee) {
2429     ID.AddPointer(Pointee.getAsOpaquePtr());
2430   }
2431
2432   static bool classof(const Type *T) { return T->getTypeClass() == Pointer; }
2433 };
2434
2435 /// Represents a type which was implicitly adjusted by the semantic
2436 /// engine for arbitrary reasons.  For example, array and function types can
2437 /// decay, and function types can have their calling conventions adjusted.
2438 class AdjustedType : public Type, public llvm::FoldingSetNode {
2439   QualType OriginalTy;
2440   QualType AdjustedTy;
2441
2442 protected:
2443   friend class ASTContext; // ASTContext creates these.
2444
2445   AdjustedType(TypeClass TC, QualType OriginalTy, QualType AdjustedTy,
2446                QualType CanonicalPtr)
2447       : Type(TC, CanonicalPtr, OriginalTy->isDependentType(),
2448              OriginalTy->isInstantiationDependentType(),
2449              OriginalTy->isVariablyModifiedType(),
2450              OriginalTy->containsUnexpandedParameterPack()),
2451         OriginalTy(OriginalTy), AdjustedTy(AdjustedTy) {}
2452
2453 public:
2454   QualType getOriginalType() const { return OriginalTy; }
2455   QualType getAdjustedType() const { return AdjustedTy; }
2456
2457   bool isSugared() const { return true; }
2458   QualType desugar() const { return AdjustedTy; }
2459
2460   void Profile(llvm::FoldingSetNodeID &ID) {
2461     Profile(ID, OriginalTy, AdjustedTy);
2462   }
2463
2464   static void Profile(llvm::FoldingSetNodeID &ID, QualType Orig, QualType New) {
2465     ID.AddPointer(Orig.getAsOpaquePtr());
2466     ID.AddPointer(New.getAsOpaquePtr());
2467   }
2468
2469   static bool classof(const Type *T) {
2470     return T->getTypeClass() == Adjusted || T->getTypeClass() == Decayed;
2471   }
2472 };
2473
2474 /// Represents a pointer type decayed from an array or function type.
2475 class DecayedType : public AdjustedType {
2476   friend class ASTContext; // ASTContext creates these.
2477
2478   inline
2479   DecayedType(QualType OriginalType, QualType Decayed, QualType Canonical);
2480
2481 public:
2482   QualType getDecayedType() const { return getAdjustedType(); }
2483
2484   inline QualType getPointeeType() const;
2485
2486   static bool classof(const Type *T) { return T->getTypeClass() == Decayed; }
2487 };
2488
2489 /// Pointer to a block type.
2490 /// This type is to represent types syntactically represented as
2491 /// "void (^)(int)", etc. Pointee is required to always be a function type.
2492 class BlockPointerType : public Type, public llvm::FoldingSetNode {
2493   friend class ASTContext; // ASTContext creates these.
2494
2495   // Block is some kind of pointer type
2496   QualType PointeeType;
2497
2498   BlockPointerType(QualType Pointee, QualType CanonicalCls)
2499       : Type(BlockPointer, CanonicalCls, Pointee->isDependentType(),
2500              Pointee->isInstantiationDependentType(),
2501              Pointee->isVariablyModifiedType(),
2502              Pointee->containsUnexpandedParameterPack()),
2503         PointeeType(Pointee) {}
2504
2505 public:
2506   // Get the pointee type. Pointee is required to always be a function type.
2507   QualType getPointeeType() const { return PointeeType; }
2508
2509   bool isSugared() const { return false; }
2510   QualType desugar() const { return QualType(this, 0); }
2511
2512   void Profile(llvm::FoldingSetNodeID &ID) {
2513       Profile(ID, getPointeeType());
2514   }
2515
2516   static void Profile(llvm::FoldingSetNodeID &ID, QualType Pointee) {
2517       ID.AddPointer(Pointee.getAsOpaquePtr());
2518   }
2519
2520   static bool classof(const Type *T) {
2521     return T->getTypeClass() == BlockPointer;
2522   }
2523 };
2524
2525 /// Base for LValueReferenceType and RValueReferenceType
2526 class ReferenceType : public Type, public llvm::FoldingSetNode {
2527   QualType PointeeType;
2528
2529 protected:
2530   ReferenceType(TypeClass tc, QualType Referencee, QualType CanonicalRef,
2531                 bool SpelledAsLValue)
2532       : Type(tc, CanonicalRef, Referencee->isDependentType(),
2533              Referencee->isInstantiationDependentType(),
2534              Referencee->isVariablyModifiedType(),
2535              Referencee->containsUnexpandedParameterPack()),
2536         PointeeType(Referencee) {
2537     ReferenceTypeBits.SpelledAsLValue = SpelledAsLValue;
2538     ReferenceTypeBits.InnerRef = Referencee->isReferenceType();
2539   }
2540
2541 public:
2542   bool isSpelledAsLValue() const { return ReferenceTypeBits.SpelledAsLValue; }
2543   bool isInnerRef() const { return ReferenceTypeBits.InnerRef; }
2544
2545   QualType getPointeeTypeAsWritten() const { return PointeeType; }
2546
2547   QualType getPointeeType() const {
2548     // FIXME: this might strip inner qualifiers; okay?
2549     const ReferenceType *T = this;
2550     while (T->isInnerRef())
2551       T = T->PointeeType->castAs<ReferenceType>();
2552     return T->PointeeType;
2553   }
2554
2555   void Profile(llvm::FoldingSetNodeID &ID) {
2556     Profile(ID, PointeeType, isSpelledAsLValue());
2557   }
2558
2559   static void Profile(llvm::FoldingSetNodeID &ID,
2560                       QualType Referencee,
2561                       bool SpelledAsLValue) {
2562     ID.AddPointer(Referencee.getAsOpaquePtr());
2563     ID.AddBoolean(SpelledAsLValue);
2564   }
2565
2566   static bool classof(const Type *T) {
2567     return T->getTypeClass() == LValueReference ||
2568            T->getTypeClass() == RValueReference;
2569   }
2570 };
2571
2572 /// An lvalue reference type, per C++11 [dcl.ref].
2573 class LValueReferenceType : public ReferenceType {
2574   friend class ASTContext; // ASTContext creates these
2575
2576   LValueReferenceType(QualType Referencee, QualType CanonicalRef,
2577                       bool SpelledAsLValue)
2578       : ReferenceType(LValueReference, Referencee, CanonicalRef,
2579                       SpelledAsLValue) {}
2580
2581 public:
2582   bool isSugared() const { return false; }
2583   QualType desugar() const { return QualType(this, 0); }
2584
2585   static bool classof(const Type *T) {
2586     return T->getTypeClass() == LValueReference;
2587   }
2588 };
2589
2590 /// An rvalue reference type, per C++11 [dcl.ref].
2591 class RValueReferenceType : public ReferenceType {
2592   friend class ASTContext; // ASTContext creates these
2593
2594   RValueReferenceType(QualType Referencee, QualType CanonicalRef)
2595        : ReferenceType(RValueReference, Referencee, CanonicalRef, false) {}
2596
2597 public:
2598   bool isSugared() const { return false; }
2599   QualType desugar() const { return QualType(this, 0); }
2600
2601   static bool classof(const Type *T) {
2602     return T->getTypeClass() == RValueReference;
2603   }
2604 };
2605
2606 /// A pointer to member type per C++ 8.3.3 - Pointers to members.
2607 ///
2608 /// This includes both pointers to data members and pointer to member functions.
2609 class MemberPointerType : public Type, public llvm::FoldingSetNode {
2610   friend class ASTContext; // ASTContext creates these.
2611
2612   QualType PointeeType;
2613
2614   /// The class of which the pointee is a member. Must ultimately be a
2615   /// RecordType, but could be a typedef or a template parameter too.
2616   const Type *Class;
2617
2618   MemberPointerType(QualType Pointee, const Type *Cls, QualType CanonicalPtr)
2619       : Type(MemberPointer, CanonicalPtr,
2620              Cls->isDependentType() || Pointee->isDependentType(),
2621              (Cls->isInstantiationDependentType() ||
2622               Pointee->isInstantiationDependentType()),
2623              Pointee->isVariablyModifiedType(),
2624              (Cls->containsUnexpandedParameterPack() ||
2625               Pointee->containsUnexpandedParameterPack())),
2626              PointeeType(Pointee), Class(Cls) {}
2627
2628 public:
2629   QualType getPointeeType() const { return PointeeType; }
2630
2631   /// Returns true if the member type (i.e. the pointee type) is a
2632   /// function type rather than a data-member type.
2633   bool isMemberFunctionPointer() const {
2634     return PointeeType->isFunctionProtoType();
2635   }
2636
2637   /// Returns true if the member type (i.e. the pointee type) is a
2638   /// data type rather than a function type.
2639   bool isMemberDataPointer() const {
2640     return !PointeeType->isFunctionProtoType();
2641   }
2642
2643   const Type *getClass() const { return Class; }
2644   CXXRecordDecl *getMostRecentCXXRecordDecl() const;
2645
2646   bool isSugared() const { return false; }
2647   QualType desugar() const { return QualType(this, 0); }
2648
2649   void Profile(llvm::FoldingSetNodeID &ID) {
2650     Profile(ID, getPointeeType(), getClass());
2651   }
2652
2653   static void Profile(llvm::FoldingSetNodeID &ID, QualType Pointee,
2654                       const Type *Class) {
2655     ID.AddPointer(Pointee.getAsOpaquePtr());
2656     ID.AddPointer(Class);
2657   }
2658
2659   static bool classof(const Type *T) {
2660     return T->getTypeClass() == MemberPointer;
2661   }
2662 };
2663
2664 /// Represents an array type, per C99 6.7.5.2 - Array Declarators.
2665 class ArrayType : public Type, public llvm::FoldingSetNode {
2666 public:
2667   /// Capture whether this is a normal array (e.g. int X[4])
2668   /// an array with a static size (e.g. int X[static 4]), or an array
2669   /// with a star size (e.g. int X[*]).
2670   /// 'static' is only allowed on function parameters.
2671   enum ArraySizeModifier {
2672     Normal, Static, Star
2673   };
2674
2675 private:
2676   /// The element type of the array.
2677   QualType ElementType;
2678
2679 protected:
2680   friend class ASTContext; // ASTContext creates these.
2681
2682   // C++ [temp.dep.type]p1:
2683   //   A type is dependent if it is...
2684   //     - an array type constructed from any dependent type or whose
2685   //       size is specified by a constant expression that is
2686   //       value-dependent,
2687   ArrayType(TypeClass tc, QualType et, QualType can,
2688             ArraySizeModifier sm, unsigned tq,
2689             bool ContainsUnexpandedParameterPack)
2690       : Type(tc, can, et->isDependentType() || tc == DependentSizedArray,
2691              et->isInstantiationDependentType() || tc == DependentSizedArray,
2692              (tc == VariableArray || et->isVariablyModifiedType()),
2693              ContainsUnexpandedParameterPack),
2694         ElementType(et) {
2695     ArrayTypeBits.IndexTypeQuals = tq;
2696     ArrayTypeBits.SizeModifier = sm;
2697   }
2698
2699 public:
2700   QualType getElementType() const { return ElementType; }
2701
2702   ArraySizeModifier getSizeModifier() const {
2703     return ArraySizeModifier(ArrayTypeBits.SizeModifier);
2704   }
2705
2706   Qualifiers getIndexTypeQualifiers() const {
2707     return Qualifiers::fromCVRMask(getIndexTypeCVRQualifiers());
2708   }
2709
2710   unsigned getIndexTypeCVRQualifiers() const {
2711     return ArrayTypeBits.IndexTypeQuals;
2712   }
2713
2714   static bool classof(const Type *T) {
2715     return T->getTypeClass() == ConstantArray ||
2716            T->getTypeClass() == VariableArray ||
2717            T->getTypeClass() == IncompleteArray ||
2718            T->getTypeClass() == DependentSizedArray;
2719   }
2720 };
2721
2722 /// Represents the canonical version of C arrays with a specified constant size.
2723 /// For example, the canonical type for 'int A[4 + 4*100]' is a
2724 /// ConstantArrayType where the element type is 'int' and the size is 404.
2725 class ConstantArrayType : public ArrayType {
2726   llvm::APInt Size; // Allows us to unique the type.
2727
2728   ConstantArrayType(QualType et, QualType can, const llvm::APInt &size,
2729                     ArraySizeModifier sm, unsigned tq)
2730       : ArrayType(ConstantArray, et, can, sm, tq,
2731                   et->containsUnexpandedParameterPack()),
2732         Size(size) {}
2733
2734 protected:
2735   friend class ASTContext; // ASTContext creates these.
2736
2737   ConstantArrayType(TypeClass tc, QualType et, QualType can,
2738                     const llvm::APInt &size, ArraySizeModifier sm, unsigned tq)
2739       : ArrayType(tc, et, can, sm, tq, et->containsUnexpandedParameterPack()),
2740         Size(size) {}
2741
2742 public:
2743   const llvm::APInt &getSize() const { return Size; }
2744   bool isSugared() const { return false; }
2745   QualType desugar() const { return QualType(this, 0); }
2746
2747   /// Determine the number of bits required to address a member of
2748   // an array with the given element type and number of elements.
2749   static unsigned getNumAddressingBits(const ASTContext &Context,
2750                                        QualType ElementType,
2751                                        const llvm::APInt &NumElements);
2752
2753   /// Determine the maximum number of active bits that an array's size
2754   /// can require, which limits the maximum size of the array.
2755   static unsigned getMaxSizeBits(const ASTContext &Context);
2756
2757   void Profile(llvm::FoldingSetNodeID &ID) {
2758     Profile(ID, getElementType(), getSize(),
2759             getSizeModifier(), getIndexTypeCVRQualifiers());
2760   }
2761
2762   static void Profile(llvm::FoldingSetNodeID &ID, QualType ET,
2763                       const llvm::APInt &ArraySize, ArraySizeModifier SizeMod,
2764                       unsigned TypeQuals) {
2765     ID.AddPointer(ET.getAsOpaquePtr());
2766     ID.AddInteger(ArraySize.getZExtValue());
2767     ID.AddInteger(SizeMod);
2768     ID.AddInteger(TypeQuals);
2769   }
2770
2771   static bool classof(const Type *T) {
2772     return T->getTypeClass() == ConstantArray;
2773   }
2774 };
2775
2776 /// Represents a C array with an unspecified size.  For example 'int A[]' has
2777 /// an IncompleteArrayType where the element type is 'int' and the size is
2778 /// unspecified.
2779 class IncompleteArrayType : public ArrayType {
2780   friend class ASTContext; // ASTContext creates these.
2781
2782   IncompleteArrayType(QualType et, QualType can,
2783                       ArraySizeModifier sm, unsigned tq)
2784       : ArrayType(IncompleteArray, et, can, sm, tq,
2785                   et->containsUnexpandedParameterPack()) {}
2786
2787 public:
2788   friend class StmtIteratorBase;
2789
2790   bool isSugared() const { return false; }
2791   QualType desugar() const { return QualType(this, 0); }
2792
2793   static bool classof(const Type *T) {
2794     return T->getTypeClass() == IncompleteArray;
2795   }
2796
2797   void Profile(llvm::FoldingSetNodeID &ID) {
2798     Profile(ID, getElementType(), getSizeModifier(),
2799             getIndexTypeCVRQualifiers());
2800   }
2801
2802   static void Profile(llvm::FoldingSetNodeID &ID, QualType ET,
2803                       ArraySizeModifier SizeMod, unsigned TypeQuals) {
2804     ID.AddPointer(ET.getAsOpaquePtr());
2805     ID.AddInteger(SizeMod);
2806     ID.AddInteger(TypeQuals);
2807   }
2808 };
2809
2810 /// Represents a C array with a specified size that is not an
2811 /// integer-constant-expression.  For example, 'int s[x+foo()]'.
2812 /// Since the size expression is an arbitrary expression, we store it as such.
2813 ///
2814 /// Note: VariableArrayType's aren't uniqued (since the expressions aren't) and
2815 /// should not be: two lexically equivalent variable array types could mean
2816 /// different things, for example, these variables do not have the same type
2817 /// dynamically:
2818 ///
2819 /// void foo(int x) {
2820 ///   int Y[x];
2821 ///   ++x;
2822 ///   int Z[x];
2823 /// }
2824 class VariableArrayType : public ArrayType {
2825   friend class ASTContext; // ASTContext creates these.
2826
2827   /// An assignment-expression. VLA's are only permitted within
2828   /// a function block.
2829   Stmt *SizeExpr;
2830
2831   /// The range spanned by the left and right array brackets.
2832   SourceRange Brackets;
2833
2834   VariableArrayType(QualType et, QualType can, Expr *e,
2835                     ArraySizeModifier sm, unsigned tq,
2836                     SourceRange brackets)
2837       : ArrayType(VariableArray, et, can, sm, tq,
2838                   et->containsUnexpandedParameterPack()),
2839         SizeExpr((Stmt*) e), Brackets(brackets) {}
2840
2841 public:
2842   friend class StmtIteratorBase;
2843
2844   Expr *getSizeExpr() const {
2845     // We use C-style casts instead of cast<> here because we do not wish
2846     // to have a dependency of Type.h on Stmt.h/Expr.h.
2847     return (Expr*) SizeExpr;
2848   }
2849
2850   SourceRange getBracketsRange() const { return Brackets; }
2851   SourceLocation getLBracketLoc() const { return Brackets.getBegin(); }
2852   SourceLocation getRBracketLoc() const { return Brackets.getEnd(); }
2853
2854   bool isSugared() const { return false; }
2855   QualType desugar() const { return QualType(this, 0); }
2856
2857   static bool classof(const Type *T) {
2858     return T->getTypeClass() == VariableArray;
2859   }
2860
2861   void Profile(llvm::FoldingSetNodeID &ID) {
2862     llvm_unreachable("Cannot unique VariableArrayTypes.");
2863   }
2864 };
2865
2866 /// Represents an array type in C++ whose size is a value-dependent expression.
2867 ///
2868 /// For example:
2869 /// \code
2870 /// template<typename T, int Size>
2871 /// class array {
2872 ///   T data[Size];
2873 /// };
2874 /// \endcode
2875 ///
2876 /// For these types, we won't actually know what the array bound is
2877 /// until template instantiation occurs, at which point this will
2878 /// become either a ConstantArrayType or a VariableArrayType.
2879 class DependentSizedArrayType : public ArrayType {
2880   friend class ASTContext; // ASTContext creates these.
2881
2882   const ASTContext &Context;
2883
2884   /// An assignment expression that will instantiate to the
2885   /// size of the array.
2886   ///
2887   /// The expression itself might be null, in which case the array
2888   /// type will have its size deduced from an initializer.
2889   Stmt *SizeExpr;
2890
2891   /// The range spanned by the left and right array brackets.
2892   SourceRange Brackets;
2893
2894   DependentSizedArrayType(const ASTContext &Context, QualType et, QualType can,
2895                           Expr *e, ArraySizeModifier sm, unsigned tq,
2896                           SourceRange brackets);
2897
2898 public:
2899   friend class StmtIteratorBase;
2900
2901   Expr *getSizeExpr() const {
2902     // We use C-style casts instead of cast<> here because we do not wish
2903     // to have a dependency of Type.h on Stmt.h/Expr.h.
2904     return (Expr*) SizeExpr;
2905   }
2906
2907   SourceRange getBracketsRange() const { return Brackets; }
2908   SourceLocation getLBracketLoc() const { return Brackets.getBegin(); }
2909   SourceLocation getRBracketLoc() const { return Brackets.getEnd(); }
2910
2911   bool isSugared() const { return false; }
2912   QualType desugar() const { return QualType(this, 0); }
2913
2914   static bool classof(const Type *T) {
2915     return T->getTypeClass() == DependentSizedArray;
2916   }
2917
2918   void Profile(llvm::FoldingSetNodeID &ID) {
2919     Profile(ID, Context, getElementType(),
2920             getSizeModifier(), getIndexTypeCVRQualifiers(), getSizeExpr());
2921   }
2922
2923   static void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context,
2924                       QualType ET, ArraySizeModifier SizeMod,
2925                       unsigned TypeQuals, Expr *E);
2926 };
2927
2928 /// Represents an extended address space qualifier where the input address space
2929 /// value is dependent. Non-dependent address spaces are not represented with a 
2930 /// special Type subclass; they are stored on an ExtQuals node as part of a QualType.
2931 ///
2932 /// For example:
2933 /// \code
2934 /// template<typename T, int AddrSpace>
2935 /// class AddressSpace {
2936 ///   typedef T __attribute__((address_space(AddrSpace))) type;
2937 /// }
2938 /// \endcode
2939 class DependentAddressSpaceType : public Type, public llvm::FoldingSetNode {
2940   friend class ASTContext;
2941
2942   const ASTContext &Context;
2943   Expr *AddrSpaceExpr;
2944   QualType PointeeType;
2945   SourceLocation loc;
2946
2947   DependentAddressSpaceType(const ASTContext &Context, QualType PointeeType,
2948                             QualType can, Expr *AddrSpaceExpr, 
2949                             SourceLocation loc);
2950
2951 public:
2952   Expr *getAddrSpaceExpr() const { return AddrSpaceExpr; }
2953   QualType getPointeeType() const { return PointeeType; }
2954   SourceLocation getAttributeLoc() const { return loc; }
2955
2956   bool isSugared() const { return false; }
2957   QualType desugar() const { return QualType(this, 0); }
2958
2959   static bool classof(const Type *T) {
2960     return T->getTypeClass() == DependentAddressSpace;
2961   }
2962
2963   void Profile(llvm::FoldingSetNodeID &ID) {
2964     Profile(ID, Context, getPointeeType(), getAddrSpaceExpr());
2965   }
2966
2967   static void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context,
2968                       QualType PointeeType, Expr *AddrSpaceExpr);
2969 };
2970
2971 /// Represents an extended vector type where either the type or size is
2972 /// dependent.
2973 ///
2974 /// For example:
2975 /// \code
2976 /// template<typename T, int Size>
2977 /// class vector {
2978 ///   typedef T __attribute__((ext_vector_type(Size))) type;
2979 /// }
2980 /// \endcode
2981 class DependentSizedExtVectorType : public Type, public llvm::FoldingSetNode {
2982   friend class ASTContext;
2983
2984   const ASTContext &Context;
2985   Expr *SizeExpr;
2986
2987   /// The element type of the array.
2988   QualType ElementType;
2989
2990   SourceLocation loc;
2991
2992   DependentSizedExtVectorType(const ASTContext &Context, QualType ElementType,
2993                               QualType can, Expr *SizeExpr, SourceLocation loc);
2994
2995 public:
2996   Expr *getSizeExpr() const { return SizeExpr; }
2997   QualType getElementType() const { return ElementType; }
2998   SourceLocation getAttributeLoc() const { return loc; }
2999
3000   bool isSugared() const { return false; }
3001   QualType desugar() const { return QualType(this, 0); }
3002
3003   static bool classof(const Type *T) {
3004     return T->getTypeClass() == DependentSizedExtVector;
3005   }
3006
3007   void Profile(llvm::FoldingSetNodeID &ID) {
3008     Profile(ID, Context, getElementType(), getSizeExpr());
3009   }
3010
3011   static void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context,
3012                       QualType ElementType, Expr *SizeExpr);
3013 };
3014
3015
3016 /// Represents a GCC generic vector type. This type is created using
3017 /// __attribute__((vector_size(n)), where "n" specifies the vector size in
3018 /// bytes; or from an Altivec __vector or vector declaration.
3019 /// Since the constructor takes the number of vector elements, the
3020 /// client is responsible for converting the size into the number of elements.
3021 class VectorType : public Type, public llvm::FoldingSetNode {
3022 public:
3023   enum VectorKind {
3024     /// not a target-specific vector type
3025     GenericVector,
3026
3027     /// is AltiVec vector
3028     AltiVecVector,
3029
3030     /// is AltiVec 'vector Pixel'
3031     AltiVecPixel,
3032
3033     /// is AltiVec 'vector bool ...'
3034     AltiVecBool,
3035
3036     /// is ARM Neon vector
3037     NeonVector,
3038
3039     /// is ARM Neon polynomial vector
3040     NeonPolyVector
3041   };
3042
3043 protected:
3044   friend class ASTContext; // ASTContext creates these.
3045
3046   /// The element type of the vector.
3047   QualType ElementType;
3048
3049   VectorType(QualType vecType, unsigned nElements, QualType canonType,
3050              VectorKind vecKind);
3051
3052   VectorType(TypeClass tc, QualType vecType, unsigned nElements,
3053              QualType canonType, VectorKind vecKind);
3054
3055 public:
3056   QualType getElementType() const { return ElementType; }
3057   unsigned getNumElements() const { return VectorTypeBits.NumElements; }
3058
3059   static bool isVectorSizeTooLarge(unsigned NumElements) {
3060     return NumElements > VectorTypeBitfields::MaxNumElements;
3061   }
3062
3063   bool isSugared() const { return false; }
3064   QualType desugar() const { return QualType(this, 0); }
3065
3066   VectorKind getVectorKind() const {
3067     return VectorKind(VectorTypeBits.VecKind);
3068   }
3069
3070   void Profile(llvm::FoldingSetNodeID &ID) {
3071     Profile(ID, getElementType(), getNumElements(),
3072             getTypeClass(), getVectorKind());
3073   }
3074
3075   static void Profile(llvm::FoldingSetNodeID &ID, QualType ElementType,
3076                       unsigned NumElements, TypeClass TypeClass,
3077                       VectorKind VecKind) {
3078     ID.AddPointer(ElementType.getAsOpaquePtr());
3079     ID.AddInteger(NumElements);
3080     ID.AddInteger(TypeClass);
3081     ID.AddInteger(VecKind);
3082   }
3083
3084   static bool classof(const Type *T) {
3085     return T->getTypeClass() == Vector || T->getTypeClass() == ExtVector;
3086   }
3087 };
3088
3089 /// Represents a vector type where either the type or size is dependent.
3090 ////
3091 /// For example:
3092 /// \code
3093 /// template<typename T, int Size>
3094 /// class vector {
3095 ///   typedef T __attribute__((vector_size(Size))) type;
3096 /// }
3097 /// \endcode
3098 class DependentVectorType : public Type, public llvm::FoldingSetNode {
3099   friend class ASTContext;
3100
3101   const ASTContext &Context;
3102   QualType ElementType;
3103   Expr *SizeExpr;
3104   SourceLocation Loc;
3105
3106   DependentVectorType(const ASTContext &Context, QualType ElementType,
3107                            QualType CanonType, Expr *SizeExpr,
3108                            SourceLocation Loc, VectorType::VectorKind vecKind);
3109
3110 public:
3111   Expr *getSizeExpr() const { return SizeExpr; }
3112   QualType getElementType() const { return ElementType; }
3113   SourceLocation getAttributeLoc() const { return Loc; }
3114   VectorType::VectorKind getVectorKind() const {
3115     return VectorType::VectorKind(VectorTypeBits.VecKind);
3116   }
3117
3118   bool isSugared() const { return false; }
3119   QualType desugar() const { return QualType(this, 0); }
3120
3121   static bool classof(const Type *T) {
3122     return T->getTypeClass() == DependentVector;
3123   }
3124
3125   void Profile(llvm::FoldingSetNodeID &ID) {
3126     Profile(ID, Context, getElementType(), getSizeExpr(), getVectorKind());
3127   }
3128
3129   static void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context,
3130                       QualType ElementType, const Expr *SizeExpr,
3131                       VectorType::VectorKind VecKind);
3132 };
3133
3134 /// ExtVectorType - Extended vector type. This type is created using
3135 /// __attribute__((ext_vector_type(n)), where "n" is the number of elements.
3136 /// Unlike vector_size, ext_vector_type is only allowed on typedef's. This
3137 /// class enables syntactic extensions, like Vector Components for accessing
3138 /// points (as .xyzw), colors (as .rgba), and textures (modeled after OpenGL
3139 /// Shading Language).
3140 class ExtVectorType : public VectorType {
3141   friend class ASTContext; // ASTContext creates these.
3142
3143   ExtVectorType(QualType vecType, unsigned nElements, QualType canonType)
3144       : VectorType(ExtVector, vecType, nElements, canonType, GenericVector) {}
3145
3146 public:
3147   static int getPointAccessorIdx(char c) {
3148     switch (c) {
3149     default: return -1;
3150     case 'x': case 'r': return 0;
3151     case 'y': case 'g': return 1;
3152     case 'z': case 'b': return 2;
3153     case 'w': case 'a': return 3;
3154     }
3155   }
3156
3157   static int getNumericAccessorIdx(char c) {
3158     switch (c) {
3159       default: return -1;
3160       case '0': return 0;
3161       case '1': return 1;
3162       case '2': return 2;
3163       case '3': return 3;
3164       case '4': return 4;
3165       case '5': return 5;
3166       case '6': return 6;
3167       case '7': return 7;
3168       case '8': return 8;
3169       case '9': return 9;
3170       case 'A':
3171       case 'a': return 10;
3172       case 'B':
3173       case 'b': return 11;
3174       case 'C':
3175       case 'c': return 12;
3176       case 'D':
3177       case 'd': return 13;
3178       case 'E':
3179       case 'e': return 14;
3180       case 'F':
3181       case 'f': return 15;
3182     }
3183   }
3184
3185   static int getAccessorIdx(char c, bool isNumericAccessor) {
3186     if (isNumericAccessor)
3187       return getNumericAccessorIdx(c);
3188     else
3189       return getPointAccessorIdx(c);
3190   }
3191
3192   bool isAccessorWithinNumElements(char c, bool isNumericAccessor) const {
3193     if (int idx = getAccessorIdx(c, isNumericAccessor)+1)
3194       return unsigned(idx-1) < getNumElements();
3195     return false;
3196   }
3197
3198   bool isSugared() const { return false; }
3199   QualType desugar() const { return QualType(this, 0); }
3200
3201   static bool classof(const Type *T) {
3202     return T->getTypeClass() == ExtVector;
3203   }
3204 };
3205
3206 /// FunctionType - C99 6.7.5.3 - Function Declarators.  This is the common base
3207 /// class of FunctionNoProtoType and FunctionProtoType.
3208 class FunctionType : public Type {
3209   // The type returned by the function.
3210   QualType ResultType;
3211
3212 public:
3213   /// A class which abstracts out some details necessary for
3214   /// making a call.
3215   ///
3216   /// It is not actually used directly for storing this information in
3217   /// a FunctionType, although FunctionType does currently use the
3218   /// same bit-pattern.
3219   ///
3220   // If you add a field (say Foo), other than the obvious places (both,
3221   // constructors, compile failures), what you need to update is
3222   // * Operator==
3223   // * getFoo
3224   // * withFoo
3225   // * functionType. Add Foo, getFoo.
3226   // * ASTContext::getFooType
3227   // * ASTContext::mergeFunctionTypes
3228   // * FunctionNoProtoType::Profile
3229   // * FunctionProtoType::Profile
3230   // * TypePrinter::PrintFunctionProto
3231   // * AST read and write
3232   // * Codegen
3233   class ExtInfo {
3234     friend class FunctionType;
3235
3236     // Feel free to rearrange or add bits, but if you go over 12,
3237     // you'll need to adjust both the Bits field below and
3238     // Type::FunctionTypeBitfields.
3239
3240     //   |  CC  |noreturn|produces|nocallersavedregs|regparm|nocfcheck|
3241     //   |0 .. 4|   5    |    6   |       7         |8 .. 10|    11   |
3242     //
3243     // regparm is either 0 (no regparm attribute) or the regparm value+1.
3244     enum { CallConvMask = 0x1F };
3245     enum { NoReturnMask = 0x20 };
3246     enum { ProducesResultMask = 0x40 };
3247     enum { NoCallerSavedRegsMask = 0x80 };
3248     enum { NoCfCheckMask = 0x800 };
3249     enum {
3250       RegParmMask = ~(CallConvMask | NoReturnMask | ProducesResultMask |
3251                       NoCallerSavedRegsMask | NoCfCheckMask),
3252       RegParmOffset = 8
3253     }; // Assumed to be the last field
3254     uint16_t Bits = CC_C;
3255
3256     ExtInfo(unsigned Bits) : Bits(static_cast<uint16_t>(Bits)) {}
3257
3258    public:
3259      // Constructor with no defaults. Use this when you know that you
3260      // have all the elements (when reading an AST file for example).
3261      ExtInfo(bool noReturn, bool hasRegParm, unsigned regParm, CallingConv cc,
3262              bool producesResult, bool noCallerSavedRegs, bool NoCfCheck) {
3263        assert((!hasRegParm || regParm < 7) && "Invalid regparm value");
3264        Bits = ((unsigned)cc) | (noReturn ? NoReturnMask : 0) |
3265               (producesResult ? ProducesResultMask : 0) |
3266               (noCallerSavedRegs ? NoCallerSavedRegsMask : 0) |
3267               (hasRegParm ? ((regParm + 1) << RegParmOffset) : 0) | 
3268               (NoCfCheck ? NoCfCheckMask : 0);
3269     }
3270
3271     // Constructor with all defaults. Use when for example creating a
3272     // function known to use defaults.
3273     ExtInfo() = default;
3274
3275     // Constructor with just the calling convention, which is an important part
3276     // of the canonical type.
3277     ExtInfo(CallingConv CC) : Bits(CC) {}
3278
3279     bool getNoReturn() const { return Bits & NoReturnMask; }
3280     bool getProducesResult() const { return Bits & ProducesResultMask; }
3281     bool getNoCallerSavedRegs() const { return Bits & NoCallerSavedRegsMask; }
3282     bool getNoCfCheck() const { return Bits & NoCfCheckMask; }
3283     bool getHasRegParm() const { return (Bits >> RegParmOffset) != 0; }
3284
3285     unsigned getRegParm() const {
3286       unsigned RegParm = (Bits & RegParmMask) >> RegParmOffset;
3287       if (RegParm > 0)
3288         --RegParm;
3289       return RegParm;
3290     }
3291
3292     CallingConv getCC() const { return CallingConv(Bits & CallConvMask); }
3293
3294     bool operator==(ExtInfo Other) const {
3295       return Bits == Other.Bits;
3296     }
3297     bool operator!=(ExtInfo Other) const {
3298       return Bits != Other.Bits;
3299     }
3300
3301     // Note that we don't have setters. That is by design, use
3302     // the following with methods instead of mutating these objects.
3303
3304     ExtInfo withNoReturn(bool noReturn) const {
3305       if (noReturn)
3306         return ExtInfo(Bits | NoReturnMask);
3307       else
3308         return ExtInfo(Bits & ~NoReturnMask);
3309     }
3310
3311     ExtInfo withProducesResult(bool producesResult) const {
3312       if (producesResult)
3313         return ExtInfo(Bits | ProducesResultMask);
3314       else
3315         return ExtInfo(Bits & ~ProducesResultMask);
3316     }
3317
3318     ExtInfo withNoCallerSavedRegs(bool noCallerSavedRegs) const {
3319       if (noCallerSavedRegs)
3320         return ExtInfo(Bits | NoCallerSavedRegsMask);
3321       else
3322         return ExtInfo(Bits & ~NoCallerSavedRegsMask);
3323     }
3324
3325     ExtInfo withNoCfCheck(bool noCfCheck) const {
3326       if (noCfCheck)
3327         return ExtInfo(Bits | NoCfCheckMask);
3328       else
3329         return ExtInfo(Bits & ~NoCfCheckMask);
3330     }
3331
3332     ExtInfo withRegParm(unsigned RegParm) const {
3333       assert(RegParm < 7 && "Invalid regparm value");
3334       return ExtInfo((Bits & ~RegParmMask) |
3335                      ((RegParm + 1) << RegParmOffset));
3336     }
3337
3338     ExtInfo withCallingConv(CallingConv cc) const {
3339       return ExtInfo((Bits & ~CallConvMask) | (unsigned) cc);
3340     }
3341
3342     void Profile(llvm::FoldingSetNodeID &ID) const {
3343       ID.AddInteger(Bits);
3344     }
3345   };
3346
3347 protected:
3348   FunctionType(TypeClass tc, QualType res,
3349                QualType Canonical, bool Dependent,
3350                bool InstantiationDependent,
3351                bool VariablyModified, bool ContainsUnexpandedParameterPack,
3352                ExtInfo Info)
3353       : Type(tc, Canonical, Dependent, InstantiationDependent, VariablyModified,
3354              ContainsUnexpandedParameterPack),
3355         ResultType(res) {
3356     FunctionTypeBits.ExtInfo = Info.Bits;
3357   }
3358
3359   unsigned getTypeQuals() const { return FunctionTypeBits.TypeQuals; }
3360
3361 public:
3362   QualType getReturnType() const { return ResultType; }
3363
3364   bool getHasRegParm() const { return getExtInfo().getHasRegParm(); }
3365   unsigned getRegParmType() const { return getExtInfo().getRegParm(); }
3366
3367   /// Determine whether this function type includes the GNU noreturn
3368   /// attribute. The C++11 [[noreturn]] attribute does not affect the function
3369   /// type.
3370   bool getNoReturnAttr() const { return getExtInfo().getNoReturn(); }
3371
3372   CallingConv getCallConv() const { return getExtInfo().getCC(); }
3373   ExtInfo getExtInfo() const { return ExtInfo(FunctionTypeBits.ExtInfo); }
3374   bool isConst() const { return getTypeQuals() & Qualifiers::Const; }
3375   bool isVolatile() const { return getTypeQuals() & Qualifiers::Volatile; }
3376   bool isRestrict() const { return getTypeQuals() & Qualifiers::Restrict; }
3377
3378   /// Determine the type of an expression that calls a function of
3379   /// this type.
3380   QualType getCallResultType(const ASTContext &Context) const {
3381     return getReturnType().getNonLValueExprType(Context);
3382   }
3383
3384   static StringRef getNameForCallConv(CallingConv CC);
3385
3386   static bool classof(const Type *T) {
3387     return T->getTypeClass() == FunctionNoProto ||
3388            T->getTypeClass() == FunctionProto;
3389   }
3390 };
3391
3392 /// Represents a K&R-style 'int foo()' function, which has
3393 /// no information available about its arguments.
3394 class FunctionNoProtoType : public FunctionType, public llvm::FoldingSetNode {
3395   friend class ASTContext; // ASTContext creates these.
3396
3397   FunctionNoProtoType(QualType Result, QualType Canonical, ExtInfo Info)
3398       : FunctionType(FunctionNoProto, Result, Canonical,
3399                      /*Dependent=*/false, /*InstantiationDependent=*/false,
3400                      Result->isVariablyModifiedType(),
3401                      /*ContainsUnexpandedParameterPack=*/false, Info) {}
3402
3403 public:
3404   // No additional state past what FunctionType provides.
3405
3406   bool isSugared() const { return false; }
3407   QualType desugar() const { return QualType(this, 0); }
3408
3409   void Profile(llvm::FoldingSetNodeID &ID) {
3410     Profile(ID, getReturnType(), getExtInfo());
3411   }
3412
3413   static void Profile(llvm::FoldingSetNodeID &ID, QualType ResultType,
3414                       ExtInfo Info) {
3415     Info.Profile(ID);
3416     ID.AddPointer(ResultType.getAsOpaquePtr());
3417   }
3418
3419   static bool classof(const Type *T) {
3420     return T->getTypeClass() == FunctionNoProto;
3421   }
3422 };
3423
3424 /// Represents a prototype with parameter type info, e.g.
3425 /// 'int foo(int)' or 'int foo(void)'.  'void' is represented as having no
3426 /// parameters, not as having a single void parameter. Such a type can have an
3427 /// exception specification, but this specification is not part of the canonical
3428 /// type.
3429 class FunctionProtoType : public FunctionType, public llvm::FoldingSetNode {
3430 public:
3431   /// Interesting information about a specific parameter that can't simply
3432   /// be reflected in parameter's type.
3433   ///
3434   /// It makes sense to model language features this way when there's some
3435   /// sort of parameter-specific override (such as an attribute) that
3436   /// affects how the function is called.  For example, the ARC ns_consumed
3437   /// attribute changes whether a parameter is passed at +0 (the default)
3438   /// or +1 (ns_consumed).  This must be reflected in the function type,
3439   /// but isn't really a change to the parameter type.
3440   ///
3441   /// One serious disadvantage of modelling language features this way is
3442   /// that they generally do not work with language features that attempt
3443   /// to destructure types.  For example, template argument deduction will
3444   /// not be able to match a parameter declared as
3445   ///   T (*)(U)
3446   /// against an argument of type
3447   ///   void (*)(__attribute__((ns_consumed)) id)
3448   /// because the substitution of T=void, U=id into the former will
3449   /// not produce the latter.
3450   class ExtParameterInfo {
3451     enum {
3452       ABIMask         = 0x0F,
3453       IsConsumed      = 0x10,
3454       HasPassObjSize  = 0x20,
3455       IsNoEscape      = 0x40,
3456     };
3457     unsigned char Data = 0;
3458
3459   public:
3460     ExtParameterInfo() = default;
3461
3462     /// Return the ABI treatment of this parameter.
3463     ParameterABI getABI() const {
3464       return ParameterABI(Data & ABIMask);
3465     }
3466     ExtParameterInfo withABI(ParameterABI kind) const {
3467       ExtParameterInfo copy = *this;
3468       copy.Data = (copy.Data & ~ABIMask) | unsigned(kind);
3469       return copy;
3470     }
3471
3472     /// Is this parameter considered "consumed" by Objective-C ARC?
3473     /// Consumed parameters must have retainable object type.
3474     bool isConsumed() const {
3475       return (Data & IsConsumed);
3476     }
3477     ExtParameterInfo withIsConsumed(bool consumed) const {
3478       ExtParameterInfo copy = *this;
3479       if (consumed) {
3480         copy.Data |= IsConsumed;
3481       } else {
3482         copy.Data &= ~IsConsumed;
3483       }
3484       return copy;
3485     }
3486
3487     bool hasPassObjectSize() const {
3488       return Data & HasPassObjSize;
3489     }
3490     ExtParameterInfo withHasPassObjectSize() const {
3491       ExtParameterInfo Copy = *this;
3492       Copy.Data |= HasPassObjSize;
3493       return Copy;
3494     }
3495
3496     bool isNoEscape() const {
3497       return Data & IsNoEscape;
3498     }
3499
3500     ExtParameterInfo withIsNoEscape(bool NoEscape) const {
3501       ExtParameterInfo Copy = *this;
3502       if (NoEscape)
3503         Copy.Data |= IsNoEscape;
3504       else
3505         Copy.Data &= ~IsNoEscape;
3506       return Copy;
3507     }
3508
3509     unsigned char getOpaqueValue() const { return Data; }
3510     static ExtParameterInfo getFromOpaqueValue(unsigned char data) {
3511       ExtParameterInfo result;
3512       result.Data = data;
3513       return result;
3514     }
3515
3516     friend bool operator==(ExtParameterInfo lhs, ExtParameterInfo rhs) {
3517       return lhs.Data == rhs.Data;
3518     }
3519     friend bool operator!=(ExtParameterInfo lhs, ExtParameterInfo rhs) {
3520       return lhs.Data != rhs.Data;
3521     }
3522   };
3523
3524   struct ExceptionSpecInfo {
3525     /// The kind of exception specification this is.
3526     ExceptionSpecificationType Type = EST_None;
3527
3528     /// Explicitly-specified list of exception types.
3529     ArrayRef<QualType> Exceptions;
3530
3531     /// Noexcept expression, if this is a computed noexcept specification.
3532     Expr *NoexceptExpr = nullptr;
3533
3534     /// The function whose exception specification this is, for
3535     /// EST_Unevaluated and EST_Uninstantiated.
3536     FunctionDecl *SourceDecl = nullptr;
3537
3538     /// The function template whose exception specification this is instantiated
3539     /// from, for EST_Uninstantiated.
3540     FunctionDecl *SourceTemplate = nullptr;
3541
3542     ExceptionSpecInfo() = default;
3543
3544     ExceptionSpecInfo(ExceptionSpecificationType EST) : Type(EST) {}
3545   };
3546
3547   /// Extra information about a function prototype.
3548   struct ExtProtoInfo {
3549     FunctionType::ExtInfo ExtInfo;
3550     bool Variadic : 1;
3551     bool HasTrailingReturn : 1;
3552     unsigned char TypeQuals = 0;
3553     RefQualifierKind RefQualifier = RQ_None;
3554     ExceptionSpecInfo ExceptionSpec;
3555     const ExtParameterInfo *ExtParameterInfos = nullptr;
3556
3557     ExtProtoInfo()
3558         : Variadic(false), HasTrailingReturn(false) {}
3559
3560     ExtProtoInfo(CallingConv CC)
3561         : ExtInfo(CC), Variadic(false), HasTrailingReturn(false) {}
3562
3563     ExtProtoInfo withExceptionSpec(const ExceptionSpecInfo &O) {
3564       ExtProtoInfo Result(*this);
3565       Result.ExceptionSpec = O;
3566       return Result;
3567     }
3568   };
3569
3570 private:
3571   friend class ASTContext; // ASTContext creates these.
3572
3573   /// Determine whether there are any argument types that
3574   /// contain an unexpanded parameter pack.
3575   static bool containsAnyUnexpandedParameterPack(const QualType *ArgArray,
3576                                                  unsigned numArgs) {
3577     for (unsigned Idx = 0; Idx < numArgs; ++Idx)
3578       if (ArgArray[Idx]->containsUnexpandedParameterPack())
3579         return true;
3580
3581     return false;
3582   }
3583
3584   FunctionProtoType(QualType result, ArrayRef<QualType> params,
3585                     QualType canonical, const ExtProtoInfo &epi);
3586
3587   /// The number of parameters this function has, not counting '...'.
3588   unsigned NumParams : 15;
3589
3590   /// The number of types in the exception spec, if any.
3591   unsigned NumExceptions : 9;
3592
3593   /// The type of exception specification this function has.
3594   unsigned ExceptionSpecType : 4;
3595
3596   /// Whether this function has extended parameter information.
3597   unsigned HasExtParameterInfos : 1;
3598
3599   /// Whether the function is variadic.
3600   unsigned Variadic : 1;
3601
3602   /// Whether this function has a trailing return type.
3603   unsigned HasTrailingReturn : 1;
3604
3605   // ParamInfo - There is an variable size array after the class in memory that
3606   // holds the parameter types.
3607
3608   // Exceptions - There is another variable size array after ArgInfo that
3609   // holds the exception types.
3610
3611   // NoexceptExpr - Instead of Exceptions, there may be a single Expr* pointing
3612   // to the expression in the noexcept() specifier.
3613
3614   // ExceptionSpecDecl, ExceptionSpecTemplate - Instead of Exceptions, there may
3615   // be a pair of FunctionDecl* pointing to the function which should be used to
3616   // instantiate this function type's exception specification, and the function
3617   // from which it should be instantiated.
3618
3619   // ExtParameterInfos - A variable size array, following the exception
3620   // specification and of length NumParams, holding an ExtParameterInfo
3621   // for each of the parameters.  This only appears if HasExtParameterInfos
3622   // is true.
3623
3624   const ExtParameterInfo *getExtParameterInfosBuffer() const {
3625     assert(hasExtParameterInfos());
3626
3627     // Find the end of the exception specification.
3628     const auto *ptr = reinterpret_cast<const char *>(exception_begin());
3629     ptr += getExceptionSpecSize();
3630
3631     return reinterpret_cast<const ExtParameterInfo *>(ptr);
3632   }
3633
3634   static size_t getExceptionSpecSize(ExceptionSpecificationType EST,
3635                                      unsigned NumExceptions) {
3636     switch (EST) {
3637     case EST_None:
3638     case EST_DynamicNone:
3639     case EST_MSAny:
3640     case EST_BasicNoexcept:
3641     case EST_Unparsed:
3642       return 0;
3643
3644     case EST_Dynamic:
3645       return NumExceptions * sizeof(QualType);
3646
3647     case EST_DependentNoexcept:
3648     case EST_NoexceptFalse:
3649     case EST_NoexceptTrue:
3650       return sizeof(Expr *);
3651
3652     case EST_Uninstantiated:
3653       return 2 * sizeof(FunctionDecl *);
3654
3655     case EST_Unevaluated:
3656       return sizeof(FunctionDecl *);
3657     }
3658     llvm_unreachable("bad exception specification kind");
3659   }
3660   size_t getExceptionSpecSize() const {
3661     return getExceptionSpecSize(getExceptionSpecType(), getNumExceptions());
3662   }
3663
3664 public:
3665   unsigned getNumParams() const { return NumParams; }
3666
3667   QualType getParamType(unsigned i) const {
3668     assert(i < NumParams && "invalid parameter index");
3669     return param_type_begin()[i];
3670   }
3671
3672   ArrayRef<QualType> getParamTypes() const {
3673     return llvm::makeArrayRef(param_type_begin(), param_type_end());
3674   }
3675
3676   ExtProtoInfo getExtProtoInfo() const {
3677     ExtProtoInfo EPI;
3678     EPI.ExtInfo = getExtInfo();
3679     EPI.Variadic = isVariadic();
3680     EPI.HasTrailingReturn = hasTrailingReturn();
3681     EPI.ExceptionSpec.Type = getExceptionSpecType();
3682     EPI.TypeQuals = static_cast<unsigned char>(getTypeQuals());
3683     EPI.RefQualifier = getRefQualifier();
3684     if (EPI.ExceptionSpec.Type == EST_Dynamic) {
3685       EPI.ExceptionSpec.Exceptions = exceptions();
3686     } else if (isComputedNoexcept(EPI.ExceptionSpec.Type)) {
3687       EPI.ExceptionSpec.NoexceptExpr = getNoexceptExpr();
3688     } else if (EPI.ExceptionSpec.Type == EST_Uninstantiated) {
3689       EPI.ExceptionSpec.SourceDecl = getExceptionSpecDecl();
3690       EPI.ExceptionSpec.SourceTemplate = getExceptionSpecTemplate();
3691     } else if (EPI.ExceptionSpec.Type == EST_Unevaluated) {
3692       EPI.ExceptionSpec.SourceDecl = getExceptionSpecDecl();
3693     }
3694     if (hasExtParameterInfos())
3695       EPI.ExtParameterInfos = getExtParameterInfosBuffer();
3696     return EPI;
3697   }
3698
3699   /// Get the kind of exception specification on this function.
3700   ExceptionSpecificationType getExceptionSpecType() const {
3701     return static_cast<ExceptionSpecificationType>(ExceptionSpecType);
3702   }
3703
3704   /// Return whether this function has any kind of exception spec.
3705   bool hasExceptionSpec() const {
3706     return getExceptionSpecType() != EST_None;
3707   }
3708
3709   /// Return whether this function has a dynamic (throw) exception spec.
3710   bool hasDynamicExceptionSpec() const {
3711     return isDynamicExceptionSpec(getExceptionSpecType());
3712   }
3713
3714   /// Return whether this function has a noexcept exception spec.
3715   bool hasNoexceptExceptionSpec() const {
3716     return isNoexceptExceptionSpec(getExceptionSpecType());
3717   }
3718
3719   /// Return whether this function has a dependent exception spec.
3720   bool hasDependentExceptionSpec() const;
3721
3722   /// Return whether this function has an instantiation-dependent exception
3723   /// spec.
3724   bool hasInstantiationDependentExceptionSpec() const;
3725
3726   unsigned getNumExceptions() const { return NumExceptions; }
3727   QualType getExceptionType(unsigned i) const {
3728     assert(i < NumExceptions && "Invalid exception number!");
3729     return exception_begin()[i];
3730   }
3731   Expr *getNoexceptExpr() const {
3732     if (!isComputedNoexcept(getExceptionSpecType()))
3733       return nullptr;
3734     // NoexceptExpr sits where the arguments end.
3735     return *reinterpret_cast<Expr *const *>(param_type_end());
3736   }
3737
3738   /// If this function type has an exception specification which hasn't
3739   /// been determined yet (either because it has not been evaluated or because
3740   /// it has not been instantiated), this is the function whose exception
3741   /// specification is represented by this type.
3742   FunctionDecl *getExceptionSpecDecl() const {
3743     if (getExceptionSpecType() != EST_Uninstantiated &&
3744         getExceptionSpecType() != EST_Unevaluated)
3745       return nullptr;
3746     return reinterpret_cast<FunctionDecl *const *>(param_type_end())[0];
3747   }
3748
3749   /// If this function type has an uninstantiated exception
3750   /// specification, this is the function whose exception specification
3751   /// should be instantiated to find the exception specification for
3752   /// this type.
3753   FunctionDecl *getExceptionSpecTemplate() const {
3754     if (getExceptionSpecType() != EST_Uninstantiated)
3755       return nullptr;
3756     return reinterpret_cast<FunctionDecl *const *>(param_type_end())[1];
3757   }
3758
3759   /// Determine whether this function type has a non-throwing exception
3760   /// specification.
3761   CanThrowResult canThrow() const;
3762
3763   /// Determine whether this function type has a non-throwing exception
3764   /// specification. If this depends on template arguments, returns
3765   /// \c ResultIfDependent.
3766   bool isNothrow(bool ResultIfDependent = false) const {
3767     return ResultIfDependent ? canThrow() != CT_Can
3768                              : canThrow() == CT_Cannot;
3769   }
3770
3771   bool isVariadic() const { return Variadic; }
3772
3773   /// Determines whether this function prototype contains a
3774   /// parameter pack at the end.
3775   ///
3776   /// A function template whose last parameter is a parameter pack can be
3777   /// called with an arbitrary number of arguments, much like a variadic
3778   /// function.
3779   bool isTemplateVariadic() const;
3780
3781   bool hasTrailingReturn() const { return HasTrailingReturn; }
3782
3783   unsigned getTypeQuals() const { return FunctionType::getTypeQuals(); }
3784
3785   /// Retrieve the ref-qualifier associated with this function type.
3786   RefQualifierKind getRefQualifier() const {
3787     return static_cast<RefQualifierKind>(FunctionTypeBits.RefQualifier);
3788   }
3789
3790   using param_type_iterator = const QualType *;
3791   using param_type_range = llvm::iterator_range<param_type_iterator>;
3792
3793   param_type_range param_types() const {
3794     return param_type_range(param_type_begin(), param_type_end());
3795   }
3796
3797   param_type_iterator param_type_begin() const {
3798     return reinterpret_cast<const QualType *>(this+1);
3799   }
3800
3801   param_type_iterator param_type_end() const {
3802     return param_type_begin() + NumParams;
3803   }
3804
3805   using exception_iterator = const QualType *;
3806
3807   ArrayRef<QualType> exceptions() const {
3808     return llvm::makeArrayRef(exception_begin(), exception_end());
3809   }
3810
3811   exception_iterator exception_begin() const {
3812     // exceptions begin where arguments end
3813     return param_type_end();
3814   }
3815
3816   exception_iterator exception_end() const {
3817     if (getExceptionSpecType() != EST_Dynamic)
3818       return exception_begin();
3819     return exception_begin() + NumExceptions;
3820   }
3821
3822   /// Is there any interesting extra information for any of the parameters
3823   /// of this function type?
3824   bool hasExtParameterInfos() const { return HasExtParameterInfos; }
3825   ArrayRef<ExtParameterInfo> getExtParameterInfos() const {
3826     assert(hasExtParameterInfos());
3827     return ArrayRef<ExtParameterInfo>(getExtParameterInfosBuffer(),
3828                                       getNumParams());
3829   }
3830
3831   /// Return a pointer to the beginning of the array of extra parameter
3832   /// information, if present, or else null if none of the parameters
3833   /// carry it.  This is equivalent to getExtProtoInfo().ExtParameterInfos.
3834   const ExtParameterInfo *getExtParameterInfosOrNull() const {
3835     if (!hasExtParameterInfos())
3836       return nullptr;
3837     return getExtParameterInfosBuffer();
3838   }
3839
3840   ExtParameterInfo getExtParameterInfo(unsigned I) const {
3841     assert(I < getNumParams() && "parameter index out of range");
3842     if (hasExtParameterInfos())
3843       return getExtParameterInfosBuffer()[I];
3844     return ExtParameterInfo();
3845   }
3846
3847   ParameterABI getParameterABI(unsigned I) const {
3848     assert(I < getNumParams() && "parameter index out of range");
3849     if (hasExtParameterInfos())
3850       return getExtParameterInfosBuffer()[I].getABI();
3851     return ParameterABI::Ordinary;
3852   }
3853
3854   bool isParamConsumed(unsigned I) const {
3855     assert(I < getNumParams() && "parameter index out of range");
3856     if (hasExtParameterInfos())
3857       return getExtParameterInfosBuffer()[I].isConsumed();
3858     return false;
3859   }
3860
3861   bool isSugared() const { return false; }
3862   QualType desugar() const { return QualType(this, 0); }
3863
3864   void printExceptionSpecification(raw_ostream &OS,
3865                                    const PrintingPolicy &Policy) const;
3866
3867   static bool classof(const Type *T) {
3868     return T->getTypeClass() == FunctionProto;
3869   }
3870
3871   void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Ctx);
3872   static void Profile(llvm::FoldingSetNodeID &ID, QualType Result,
3873                       param_type_iterator ArgTys, unsigned NumArgs,
3874                       const ExtProtoInfo &EPI, const ASTContext &Context,
3875                       bool Canonical);
3876 };
3877
3878 /// Represents the dependent type named by a dependently-scoped
3879 /// typename using declaration, e.g.
3880 ///   using typename Base<T>::foo;
3881 ///
3882 /// Template instantiation turns these into the underlying type.
3883 class UnresolvedUsingType : public Type {
3884   friend class ASTContext; // ASTContext creates these.
3885
3886   UnresolvedUsingTypenameDecl *Decl;
3887
3888   UnresolvedUsingType(const UnresolvedUsingTypenameDecl *D)
3889       : Type(UnresolvedUsing, QualType(), true, true, false,
3890              /*ContainsUnexpandedParameterPack=*/false),
3891         Decl(const_cast<UnresolvedUsingTypenameDecl*>(D)) {}
3892
3893 public:
3894   UnresolvedUsingTypenameDecl *getDecl() const { return Decl; }
3895
3896   bool isSugared() const { return false; }
3897   QualType desugar() const { return QualType(this, 0); }
3898
3899   static bool classof(const Type *T) {
3900     return T->getTypeClass() == UnresolvedUsing;
3901   }
3902
3903   void Profile(llvm::FoldingSetNodeID &ID) {
3904     return Profile(ID, Decl);
3905   }
3906
3907   static void Profile(llvm::FoldingSetNodeID &ID,
3908                       UnresolvedUsingTypenameDecl *D) {
3909     ID.AddPointer(D);
3910   }
3911 };
3912
3913 class TypedefType : public Type {
3914   TypedefNameDecl *Decl;
3915
3916 protected:
3917   friend class ASTContext; // ASTContext creates these.
3918
3919   TypedefType(TypeClass tc, const TypedefNameDecl *D, QualType can)
3920       : Type(tc, can, can->isDependentType(),
3921              can->isInstantiationDependentType(),
3922              can->isVariablyModifiedType(),
3923              /*ContainsUnexpandedParameterPack=*/false),
3924         Decl(const_cast<TypedefNameDecl*>(D)) {
3925     assert(!isa<TypedefType>(can) && "Invalid canonical type");
3926   }
3927
3928 public:
3929   TypedefNameDecl *getDecl() const { return Decl; }
3930
3931   bool isSugared() const { return true; }
3932   QualType desugar() const;
3933
3934   static bool classof(const Type *T) { return T->getTypeClass() == Typedef; }
3935 };
3936
3937 /// Represents a `typeof` (or __typeof__) expression (a GCC extension).
3938 class TypeOfExprType : public Type {
3939   Expr *TOExpr;
3940
3941 protected:
3942   friend class ASTContext; // ASTContext creates these.
3943
3944   TypeOfExprType(Expr *E, QualType can = QualType());
3945
3946 public:
3947   Expr *getUnderlyingExpr() const { return TOExpr; }
3948
3949   /// Remove a single level of sugar.
3950   QualType desugar() const;
3951
3952   /// Returns whether this type directly provides sugar.
3953   bool isSugared() const;
3954
3955   static bool classof(const Type *T) { return T->getTypeClass() == TypeOfExpr; }
3956 };
3957
3958 /// Internal representation of canonical, dependent
3959 /// `typeof(expr)` types.
3960 ///
3961 /// This class is used internally by the ASTContext to manage
3962 /// canonical, dependent types, only. Clients will only see instances
3963 /// of this class via TypeOfExprType nodes.
3964 class DependentTypeOfExprType
3965   : public TypeOfExprType, public llvm::FoldingSetNode {
3966   const ASTContext &Context;
3967
3968 public:
3969   DependentTypeOfExprType(const ASTContext &Context, Expr *E)
3970       : TypeOfExprType(E), Context(Context) {}
3971
3972   void Profile(llvm::FoldingSetNodeID &ID) {
3973     Profile(ID, Context, getUnderlyingExpr());
3974   }
3975
3976   static void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context,
3977                       Expr *E);
3978 };
3979
3980 /// Represents `typeof(type)`, a GCC extension.
3981 class TypeOfType : public Type {
3982   friend class ASTContext; // ASTContext creates these.
3983
3984   QualType TOType;
3985
3986   TypeOfType(QualType T, QualType can)
3987       : Type(TypeOf, can, T->isDependentType(),
3988              T->isInstantiationDependentType(),
3989              T->isVariablyModifiedType(),
3990              T->containsUnexpandedParameterPack()),
3991         TOType(T) {
3992     assert(!isa<TypedefType>(can) && "Invalid canonical type");
3993   }
3994
3995 public:
3996   QualType getUnderlyingType() const { return TOType; }
3997
3998   /// Remove a single level of sugar.
3999   QualType desugar() const { return getUnderlyingType(); }
4000
4001   /// Returns whether this type directly provides sugar.
4002   bool isSugared() const { return true; }
4003
4004   static bool classof(const Type *T) { return T->getTypeClass() == TypeOf; }
4005 };
4006
4007 /// Represents the type `decltype(expr)` (C++11).
4008 class DecltypeType : public Type {
4009   Expr *E;
4010   QualType UnderlyingType;
4011
4012 protected:
4013   friend class ASTContext; // ASTContext creates these.
4014
4015   DecltypeType(Expr *E, QualType underlyingType, QualType can = QualType());
4016
4017 public:
4018   Expr *getUnderlyingExpr() const { return E; }
4019   QualType getUnderlyingType() const { return UnderlyingType; }
4020
4021   /// Remove a single level of sugar.
4022   QualType desugar() const;
4023
4024   /// Returns whether this type directly provides sugar.
4025   bool isSugared() const;
4026
4027   static bool classof(const Type *T) { return T->getTypeClass() == Decltype; }
4028 };
4029
4030 /// Internal representation of canonical, dependent
4031 /// decltype(expr) types.
4032 ///
4033 /// This class is used internally by the ASTContext to manage
4034 /// canonical, dependent types, only. Clients will only see instances
4035 /// of this class via DecltypeType nodes.
4036 class DependentDecltypeType : public DecltypeType, public llvm::FoldingSetNode {
4037   const ASTContext &Context;
4038
4039 public:
4040   DependentDecltypeType(const ASTContext &Context, Expr *E);
4041
4042   void Profile(llvm::FoldingSetNodeID &ID) {
4043     Profile(ID, Context, getUnderlyingExpr());
4044   }
4045
4046   static void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context,
4047                       Expr *E);
4048 };
4049
4050 /// A unary type transform, which is a type constructed from another.
4051 class UnaryTransformType : public Type {
4052 public:
4053   enum UTTKind {
4054     EnumUnderlyingType
4055   };
4056
4057 private:
4058   /// The untransformed type.
4059   QualType BaseType;
4060
4061   /// The transformed type if not dependent, otherwise the same as BaseType.
4062   QualType UnderlyingType;
4063
4064   UTTKind UKind;
4065
4066 protected:
4067   friend class ASTContext;
4068
4069   UnaryTransformType(QualType BaseTy, QualType UnderlyingTy, UTTKind UKind,
4070                      QualType CanonicalTy);
4071
4072 public:
4073   bool isSugared() const { return !isDependentType(); }
4074   QualType desugar() const { return UnderlyingType; }
4075
4076   QualType getUnderlyingType() const { return UnderlyingType; }
4077   QualType getBaseType() const { return BaseType; }
4078
4079   UTTKind getUTTKind() const { return UKind; }
4080
4081   static bool classof(const Type *T) {
4082     return T->getTypeClass() == UnaryTransform;
4083   }
4084 };
4085
4086 /// Internal representation of canonical, dependent
4087 /// __underlying_type(type) types.
4088 ///
4089 /// This class is used internally by the ASTContext to manage
4090 /// canonical, dependent types, only. Clients will only see instances
4091 /// of this class via UnaryTransformType nodes.
4092 class DependentUnaryTransformType : public UnaryTransformType,
4093                                     public llvm::FoldingSetNode {
4094 public:
4095   DependentUnaryTransformType(const ASTContext &C, QualType BaseType,
4096                               UTTKind UKind);
4097
4098   void Profile(llvm::FoldingSetNodeID &ID) {
4099     Profile(ID, getBaseType(), getUTTKind());
4100   }
4101
4102   static void Profile(llvm::FoldingSetNodeID &ID, QualType BaseType,
4103                       UTTKind UKind) {
4104     ID.AddPointer(BaseType.getAsOpaquePtr());
4105     ID.AddInteger((unsigned)UKind);
4106   }
4107 };
4108
4109 class TagType : public Type {
4110   friend class ASTReader;
4111
4112   /// Stores the TagDecl associated with this type. The decl may point to any
4113   /// TagDecl that declares the entity.
4114   TagDecl *decl;
4115
4116 protected:
4117   TagType(TypeClass TC, const TagDecl *D, QualType can);
4118
4119 public:
4120   TagDecl *getDecl() const;
4121
4122   /// Determines whether this type is in the process of being defined.
4123   bool isBeingDefined() const;
4124
4125   static bool classof(const Type *T) {
4126     return T->getTypeClass() >= TagFirst && T->getTypeClass() <= TagLast;
4127   }
4128 };
4129
4130 /// A helper class that allows the use of isa/cast/dyncast
4131 /// to detect TagType objects of structs/unions/classes.
4132 class RecordType : public TagType {
4133 protected:
4134   friend class ASTContext; // ASTContext creates these.
4135
4136   explicit RecordType(const RecordDecl *D)
4137       : TagType(Record, reinterpret_cast<const TagDecl*>(D), QualType()) {}
4138   explicit RecordType(TypeClass TC, RecordDecl *D)
4139       : TagType(TC, reinterpret_cast<const TagDecl*>(D), QualType()) {}
4140
4141 public:
4142   RecordDecl *getDecl() const {
4143     return reinterpret_cast<RecordDecl*>(TagType::getDecl());
4144   }
4145
4146   /// Recursively check all fields in the record for const-ness. If any field
4147   /// is declared const, return true. Otherwise, return false.
4148   bool hasConstFields() const;
4149
4150   bool isSugared() const { return false; }
4151   QualType desugar() const { return QualType(this, 0); }
4152
4153   static bool classof(const Type *T) { return T->getTypeClass() == Record; }
4154 };
4155
4156 /// A helper class that allows the use of isa/cast/dyncast
4157 /// to detect TagType objects of enums.
4158 class EnumType : public TagType {
4159   friend class ASTContext; // ASTContext creates these.
4160
4161   explicit EnumType(const EnumDecl *D)
4162       : TagType(Enum, reinterpret_cast<const TagDecl*>(D), QualType()) {}
4163
4164 public:
4165   EnumDecl *getDecl() const {
4166     return reinterpret_cast<EnumDecl*>(TagType::getDecl());
4167   }
4168
4169   bool isSugared() const { return false; }
4170   QualType desugar() const { return QualType(this, 0); }
4171
4172   static bool classof(const Type *T) { return T->getTypeClass() == Enum; }
4173 };
4174
4175 /// An attributed type is a type to which a type attribute has been applied.
4176 ///
4177 /// The "modified type" is the fully-sugared type to which the attributed
4178 /// type was applied; generally it is not canonically equivalent to the
4179 /// attributed type. The "equivalent type" is the minimally-desugared type
4180 /// which the type is canonically equivalent to.
4181 ///
4182 /// For example, in the following attributed type:
4183 ///     int32_t __attribute__((vector_size(16)))
4184 ///   - the modified type is the TypedefType for int32_t
4185 ///   - the equivalent type is VectorType(16, int32_t)
4186 ///   - the canonical type is VectorType(16, int)
4187 class AttributedType : public Type, public llvm::FoldingSetNode {
4188 public:
4189   // It is really silly to have yet another attribute-kind enum, but
4190   // clang::attr::Kind doesn't currently cover the pure type attrs.
4191   enum Kind {
4192     // Expression operand.
4193     attr_address_space,
4194     attr_regparm,
4195     attr_vector_size,
4196     attr_neon_vector_type,
4197     attr_neon_polyvector_type,
4198
4199     FirstExprOperandKind = attr_address_space,
4200     LastExprOperandKind = attr_neon_polyvector_type,
4201
4202     // Enumerated operand (string or keyword).
4203     attr_objc_gc,
4204     attr_objc_ownership,
4205     attr_pcs,
4206     attr_pcs_vfp,
4207
4208     FirstEnumOperandKind = attr_objc_gc,
4209     LastEnumOperandKind = attr_pcs_vfp,
4210
4211     // No operand.
4212     attr_noreturn,
4213     attr_nocf_check,
4214     attr_cdecl,
4215     attr_fastcall,
4216     attr_stdcall,
4217     attr_thiscall,
4218     attr_regcall,
4219     attr_pascal,
4220     attr_swiftcall,
4221     attr_vectorcall,
4222     attr_inteloclbicc,
4223     attr_ms_abi,
4224     attr_sysv_abi,
4225     attr_preserve_most,
4226     attr_preserve_all,
4227     attr_ptr32,
4228     attr_ptr64,
4229     attr_sptr,
4230     attr_uptr,
4231     attr_nonnull,
4232     attr_ns_returns_retained,
4233     attr_nullable,
4234     attr_null_unspecified,
4235     attr_objc_kindof,
4236     attr_objc_inert_unsafe_unretained,
4237   };
4238
4239 private:
4240   friend class ASTContext; // ASTContext creates these
4241
4242   QualType ModifiedType;
4243   QualType EquivalentType;
4244
4245   AttributedType(QualType canon, Kind attrKind, QualType modified,
4246                  QualType equivalent)
4247       : Type(Attributed, canon, equivalent->isDependentType(),
4248              equivalent->isInstantiationDependentType(),
4249              equivalent->isVariablyModifiedType(),
4250              equivalent->containsUnexpandedParameterPack()),
4251         ModifiedType(modified), EquivalentType(equivalent) {
4252     AttributedTypeBits.AttrKind = attrKind;
4253   }
4254
4255 public:
4256   Kind getAttrKind() const {
4257     return static_cast<Kind>(AttributedTypeBits.AttrKind);
4258   }
4259
4260   QualType getModifiedType() const { return ModifiedType; }
4261   QualType getEquivalentType() const { return EquivalentType; }
4262
4263   bool isSugared() const { return true; }
4264   QualType desugar() const { return getEquivalentType(); }
4265
4266   /// Does this attribute behave like a type qualifier?
4267   ///
4268   /// A type qualifier adjusts a type to provide specialized rules for
4269   /// a specific object, like the standard const and volatile qualifiers.
4270   /// This includes attributes controlling things like nullability,
4271   /// address spaces, and ARC ownership.  The value of the object is still
4272   /// largely described by the modified type.
4273   ///
4274   /// In contrast, many type attributes "rewrite" their modified type to
4275   /// produce a fundamentally different type, not necessarily related in any
4276   /// formalizable way to the original type.  For example, calling convention
4277   /// and vector attributes are not simple type qualifiers.
4278   ///
4279   /// Type qualifiers are often, but not always, reflected in the canonical
4280   /// type.
4281   bool isQualifier() const;
4282
4283   bool isMSTypeSpec() const;
4284
4285   bool isCallingConv() const;
4286
4287   llvm::Optional<NullabilityKind> getImmediateNullability() const;
4288
4289   /// Retrieve the attribute kind corresponding to the given
4290   /// nullability kind.
4291   static Kind getNullabilityAttrKind(NullabilityKind kind) {
4292     switch (kind) {
4293     case NullabilityKind::NonNull:
4294       return attr_nonnull;
4295
4296     case NullabilityKind::Nullable:
4297       return attr_nullable;
4298
4299     case NullabilityKind::Unspecified:
4300       return attr_null_unspecified;
4301     }
4302     llvm_unreachable("Unknown nullability kind.");
4303   }
4304
4305   /// Strip off the top-level nullability annotation on the given
4306   /// type, if it's there.
4307   ///
4308   /// \param T The type to strip. If the type is exactly an
4309   /// AttributedType specifying nullability (without looking through
4310   /// type sugar), the nullability is returned and this type changed
4311   /// to the underlying modified type.
4312   ///
4313   /// \returns the top-level nullability, if present.
4314   static Optional<NullabilityKind> stripOuterNullability(QualType &T);
4315
4316   void Profile(llvm::FoldingSetNodeID &ID) {
4317     Profile(ID, getAttrKind(), ModifiedType, EquivalentType);
4318   }
4319
4320   static void Profile(llvm::FoldingSetNodeID &ID, Kind attrKind,
4321                       QualType modified, QualType equivalent) {
4322     ID.AddInteger(attrKind);
4323     ID.AddPointer(modified.getAsOpaquePtr());
4324     ID.AddPointer(equivalent.getAsOpaquePtr());
4325   }
4326
4327   static bool classof(const Type *T) {
4328     return T->getTypeClass() == Attributed;
4329   }
4330 };
4331
4332 class TemplateTypeParmType : public Type, public llvm::FoldingSetNode {
4333   friend class ASTContext; // ASTContext creates these
4334
4335   // Helper data collector for canonical types.
4336   struct CanonicalTTPTInfo {
4337     unsigned Depth : 15;
4338     unsigned ParameterPack : 1;
4339     unsigned Index : 16;
4340   };
4341
4342   union {
4343     // Info for the canonical type.
4344     CanonicalTTPTInfo CanTTPTInfo;
4345
4346     // Info for the non-canonical type.
4347     TemplateTypeParmDecl *TTPDecl;
4348   };
4349
4350   /// Build a non-canonical type.
4351   TemplateTypeParmType(TemplateTypeParmDecl *TTPDecl, QualType Canon)
4352       : Type(TemplateTypeParm, Canon, /*Dependent=*/true,
4353              /*InstantiationDependent=*/true,
4354              /*VariablyModified=*/false,
4355              Canon->containsUnexpandedParameterPack()),
4356         TTPDecl(TTPDecl) {}
4357
4358   /// Build the canonical type.
4359   TemplateTypeParmType(unsigned D, unsigned I, bool PP)
4360       : Type(TemplateTypeParm, QualType(this, 0),
4361              /*Dependent=*/true,
4362              /*InstantiationDependent=*/true,
4363              /*VariablyModified=*/false, PP) {
4364     CanTTPTInfo.Depth = D;
4365     CanTTPTInfo.Index = I;
4366     CanTTPTInfo.ParameterPack = PP;
4367   }
4368
4369   const CanonicalTTPTInfo& getCanTTPTInfo() const {
4370     QualType Can = getCanonicalTypeInternal();
4371     return Can->castAs<TemplateTypeParmType>()->CanTTPTInfo;
4372   }
4373
4374 public:
4375   unsigned getDepth() const { return getCanTTPTInfo().Depth; }
4376   unsigned getIndex() const { return getCanTTPTInfo().Index; }
4377   bool isParameterPack() const { return getCanTTPTInfo().ParameterPack; }
4378
4379   TemplateTypeParmDecl *getDecl() const {
4380     return isCanonicalUnqualified() ? nullptr : TTPDecl;
4381   }
4382
4383   IdentifierInfo *getIdentifier() const;
4384
4385   bool isSugared() const { return false; }
4386   QualType desugar() const { return QualType(this, 0); }
4387
4388   void Profile(llvm::FoldingSetNodeID &ID) {
4389     Profile(ID, getDepth(), getIndex(), isParameterPack(), getDecl());
4390   }
4391
4392   static void Profile(llvm::FoldingSetNodeID &ID, unsigned Depth,
4393                       unsigned Index, bool ParameterPack,
4394                       TemplateTypeParmDecl *TTPDecl) {
4395     ID.AddInteger(Depth);
4396     ID.AddInteger(Index);
4397     ID.AddBoolean(ParameterPack);
4398     ID.AddPointer(TTPDecl);
4399   }
4400
4401   static bool classof(const Type *T) {
4402     return T->getTypeClass() == TemplateTypeParm;
4403   }
4404 };
4405
4406 /// Represents the result of substituting a type for a template
4407 /// type parameter.
4408 ///
4409 /// Within an instantiated template, all template type parameters have
4410 /// been replaced with these.  They are used solely to record that a
4411 /// type was originally written as a template type parameter;
4412 /// therefore they are never canonical.
4413 class SubstTemplateTypeParmType : public Type, public llvm::FoldingSetNode {
4414   friend class ASTContext;
4415
4416   // The original type parameter.
4417   const TemplateTypeParmType *Replaced;
4418
4419   SubstTemplateTypeParmType(const TemplateTypeParmType *Param, QualType Canon)
4420       : Type(SubstTemplateTypeParm, Canon, Canon->isDependentType(),
4421              Canon->isInstantiationDependentType(),
4422              Canon->isVariablyModifiedType(),
4423              Canon->containsUnexpandedParameterPack()),
4424         Replaced(Param) {}
4425
4426 public:
4427   /// Gets the template parameter that was substituted for.
4428   const TemplateTypeParmType *getReplacedParameter() const {
4429     return Replaced;
4430   }
4431
4432   /// Gets the type that was substituted for the template
4433   /// parameter.
4434   QualType getReplacementType() const {
4435     return getCanonicalTypeInternal();
4436   }
4437
4438   bool isSugared() const { return true; }
4439   QualType desugar() const { return getReplacementType(); }
4440
4441   void Profile(llvm::FoldingSetNodeID &ID) {
4442     Profile(ID, getReplacedParameter(), getReplacementType());
4443   }
4444
4445   static void Profile(llvm::FoldingSetNodeID &ID,
4446                       const TemplateTypeParmType *Replaced,
4447                       QualType Replacement) {
4448     ID.AddPointer(Replaced);
4449     ID.AddPointer(Replacement.getAsOpaquePtr());
4450   }
4451
4452   static bool classof(const Type *T) {
4453     return T->getTypeClass() == SubstTemplateTypeParm;
4454   }
4455 };
4456
4457 /// Represents the result of substituting a set of types for a template
4458 /// type parameter pack.
4459 ///
4460 /// When a pack expansion in the source code contains multiple parameter packs
4461 /// and those parameter packs correspond to different levels of template
4462 /// parameter lists, this type node is used to represent a template type
4463 /// parameter pack from an outer level, which has already had its argument pack
4464 /// substituted but that still lives within a pack expansion that itself
4465 /// could not be instantiated. When actually performing a substitution into
4466 /// that pack expansion (e.g., when all template parameters have corresponding
4467 /// arguments), this type will be replaced with the \c SubstTemplateTypeParmType
4468 /// at the current pack substitution index.
4469 class SubstTemplateTypeParmPackType : public Type, public llvm::FoldingSetNode {
4470   friend class ASTContext;
4471
4472   /// The original type parameter.
4473   const TemplateTypeParmType *Replaced;
4474
4475   /// A pointer to the set of template arguments that this
4476   /// parameter pack is instantiated with.
4477   const TemplateArgument *Arguments;
4478
4479   /// The number of template arguments in \c Arguments.
4480   unsigned NumArguments;
4481
4482   SubstTemplateTypeParmPackType(const TemplateTypeParmType *Param,
4483                                 QualType Canon,
4484                                 const TemplateArgument &ArgPack);
4485
4486 public:
4487   IdentifierInfo *getIdentifier() const { return Replaced->getIdentifier(); }
4488
4489   /// Gets the template parameter that was substituted for.
4490   const TemplateTypeParmType *getReplacedParameter() const {
4491     return Replaced;
4492   }
4493
4494   bool isSugared() const { return false; }
4495   QualType desugar() const { return QualType(this, 0); }
4496
4497   TemplateArgument getArgumentPack() const;
4498
4499   void Profile(llvm::FoldingSetNodeID &ID);
4500   static void Profile(llvm::FoldingSetNodeID &ID,
4501                       const TemplateTypeParmType *Replaced,
4502                       const TemplateArgument &ArgPack);
4503
4504   static bool classof(const Type *T) {
4505     return T->getTypeClass() == SubstTemplateTypeParmPack;
4506   }
4507 };
4508
4509 /// Common base class for placeholders for types that get replaced by
4510 /// placeholder type deduction: C++11 auto, C++14 decltype(auto), C++17 deduced
4511 /// class template types, and (eventually) constrained type names from the C++
4512 /// Concepts TS.
4513 ///
4514 /// These types are usually a placeholder for a deduced type. However, before
4515 /// the initializer is attached, or (usually) if the initializer is
4516 /// type-dependent, there is no deduced type and the type is canonical. In
4517 /// the latter case, it is also a dependent type.
4518 class DeducedType : public Type {
4519 protected:
4520   DeducedType(TypeClass TC, QualType DeducedAsType, bool IsDependent,
4521               bool IsInstantiationDependent, bool ContainsParameterPack)
4522       : Type(TC,
4523              // FIXME: Retain the sugared deduced type?
4524              DeducedAsType.isNull() ? QualType(this, 0)
4525                                     : DeducedAsType.getCanonicalType(),
4526              IsDependent, IsInstantiationDependent,
4527              /*VariablyModified=*/false, ContainsParameterPack) {
4528     if (!DeducedAsType.isNull()) {
4529       if (DeducedAsType->isDependentType())
4530         setDependent();
4531       if (DeducedAsType->isInstantiationDependentType())
4532         setInstantiationDependent();
4533       if (DeducedAsType->containsUnexpandedParameterPack())
4534         setContainsUnexpandedParameterPack();
4535     }
4536   }
4537
4538 public:
4539   bool isSugared() const { return !isCanonicalUnqualified(); }
4540   QualType desugar() const { return getCanonicalTypeInternal(); }
4541
4542   /// Get the type deduced for this placeholder type, or null if it's
4543   /// either not been deduced or was deduced to a dependent type.
4544   QualType getDeducedType() const {
4545     return !isCanonicalUnqualified() ? getCanonicalTypeInternal() : QualType();
4546   }
4547   bool isDeduced() const {
4548     return !isCanonicalUnqualified() || isDependentType();
4549   }
4550
4551   static bool classof(const Type *T) {
4552     return T->getTypeClass() == Auto ||
4553            T->getTypeClass() == DeducedTemplateSpecialization;
4554   }
4555 };
4556
4557 /// Represents a C++11 auto or C++14 decltype(auto) type.
4558 class AutoType : public DeducedType, public llvm::FoldingSetNode {
4559   friend class ASTContext; // ASTContext creates these
4560
4561   AutoType(QualType DeducedAsType, AutoTypeKeyword Keyword,
4562            bool IsDeducedAsDependent)
4563       : DeducedType(Auto, DeducedAsType, IsDeducedAsDependent,
4564                     IsDeducedAsDependent, /*ContainsPack=*/false) {
4565     AutoTypeBits.Keyword = (unsigned)Keyword;
4566   }
4567
4568 public:
4569   bool isDecltypeAuto() const {
4570     return getKeyword() == AutoTypeKeyword::DecltypeAuto;
4571   }
4572
4573   AutoTypeKeyword getKeyword() const {
4574     return (AutoTypeKeyword)AutoTypeBits.Keyword;
4575   }
4576
4577   void Profile(llvm::FoldingSetNodeID &ID) {
4578     Profile(ID, getDeducedType(), getKeyword(), isDependentType());
4579   }
4580
4581   static void Profile(llvm::FoldingSetNodeID &ID, QualType Deduced,
4582                       AutoTypeKeyword Keyword, bool IsDependent) {
4583     ID.AddPointer(Deduced.getAsOpaquePtr());
4584     ID.AddInteger((unsigned)Keyword);
4585     ID.AddBoolean(IsDependent);
4586   }
4587
4588   static bool classof(const Type *T) {
4589     return T->getTypeClass() == Auto;
4590   }
4591 };
4592
4593 /// Represents a C++17 deduced template specialization type.
4594 class DeducedTemplateSpecializationType : public DeducedType,
4595                                           public llvm::FoldingSetNode {
4596   friend class ASTContext; // ASTContext creates these
4597
4598   /// The name of the template whose arguments will be deduced.
4599   TemplateName Template;
4600
4601   DeducedTemplateSpecializationType(TemplateName Template,
4602                                     QualType DeducedAsType,
4603                                     bool IsDeducedAsDependent)
4604       : DeducedType(DeducedTemplateSpecialization, DeducedAsType,
4605                     IsDeducedAsDependent || Template.isDependent(),
4606                     IsDeducedAsDependent || Template.isInstantiationDependent(),
4607                     Template.containsUnexpandedParameterPack()),
4608         Template(Template) {}
4609
4610 public:
4611   /// Retrieve the name of the template that we are deducing.
4612   TemplateName getTemplateName() const { return Template;}
4613
4614   void Profile(llvm::FoldingSetNodeID &ID) {
4615     Profile(ID, getTemplateName(), getDeducedType(), isDependentType());
4616   }
4617
4618   static void Profile(llvm::FoldingSetNodeID &ID, TemplateName Template,
4619                       QualType Deduced, bool IsDependent) {
4620     Template.Profile(ID);
4621     ID.AddPointer(Deduced.getAsOpaquePtr());
4622     ID.AddBoolean(IsDependent);
4623   }
4624
4625   static bool classof(const Type *T) {
4626     return T->getTypeClass() == DeducedTemplateSpecialization;
4627   }
4628 };
4629
4630 /// Represents a type template specialization; the template
4631 /// must be a class template, a type alias template, or a template
4632 /// template parameter.  A template which cannot be resolved to one of
4633 /// these, e.g. because it is written with a dependent scope
4634 /// specifier, is instead represented as a
4635 /// @c DependentTemplateSpecializationType.
4636 ///
4637 /// A non-dependent template specialization type is always "sugar",
4638 /// typically for a \c RecordType.  For example, a class template
4639 /// specialization type of \c vector<int> will refer to a tag type for
4640 /// the instantiation \c std::vector<int, std::allocator<int>>
4641 ///
4642 /// Template specializations are dependent if either the template or
4643 /// any of the template arguments are dependent, in which case the
4644 /// type may also be canonical.
4645 ///
4646 /// Instances of this type are allocated with a trailing array of
4647 /// TemplateArguments, followed by a QualType representing the
4648 /// non-canonical aliased type when the template is a type alias
4649 /// template.
4650 class alignas(8) TemplateSpecializationType
4651     : public Type,
4652       public llvm::FoldingSetNode {
4653   friend class ASTContext; // ASTContext creates these
4654
4655   /// The name of the template being specialized.  This is
4656   /// either a TemplateName::Template (in which case it is a
4657   /// ClassTemplateDecl*, a TemplateTemplateParmDecl*, or a
4658   /// TypeAliasTemplateDecl*), a
4659   /// TemplateName::SubstTemplateTemplateParmPack, or a
4660   /// TemplateName::SubstTemplateTemplateParm (in which case the
4661   /// replacement must, recursively, be one of these).
4662   TemplateName Template;
4663
4664   /// The number of template arguments named in this class template
4665   /// specialization.
4666   unsigned NumArgs : 31;
4667
4668   /// Whether this template specialization type is a substituted type alias.
4669   unsigned TypeAlias : 1;
4670
4671   TemplateSpecializationType(TemplateName T,
4672                              ArrayRef<TemplateArgument> Args,
4673                              QualType Canon,
4674                              QualType Aliased);
4675
4676 public:
4677   /// Determine whether any of the given template arguments are dependent.
4678   static bool anyDependentTemplateArguments(ArrayRef<TemplateArgumentLoc> Args,
4679                                             bool &InstantiationDependent);
4680
4681   static bool anyDependentTemplateArguments(const TemplateArgumentListInfo &,
4682                                             bool &InstantiationDependent);
4683
4684   /// True if this template specialization type matches a current
4685   /// instantiation in the context in which it is found.
4686   bool isCurrentInstantiation() const {
4687     return isa<InjectedClassNameType>(getCanonicalTypeInternal());
4688   }
4689
4690   /// Determine if this template specialization type is for a type alias
4691   /// template that has been substituted.
4692   ///
4693   /// Nearly every template specialization type whose template is an alias
4694   /// template will be substituted. However, this is not the case when
4695   /// the specialization contains a pack expansion but the template alias
4696   /// does not have a corresponding parameter pack, e.g.,
4697   ///
4698   /// \code
4699   /// template<typename T, typename U, typename V> struct S;
4700   /// template<typename T, typename U> using A = S<T, int, U>;
4701   /// template<typename... Ts> struct X {
4702   ///   typedef A<Ts...> type; // not a type alias
4703   /// };
4704   /// \endcode
4705   bool isTypeAlias() const { return TypeAlias; }
4706
4707   /// Get the aliased type, if this is a specialization of a type alias
4708   /// template.
4709   QualType getAliasedType() const {
4710     assert(isTypeAlias() && "not a type alias template specialization");
4711     return *reinterpret_cast<const QualType*>(end());
4712   }
4713
4714   using iterator = const TemplateArgument *;
4715
4716   iterator begin() const { return getArgs(); }
4717   iterator end() const; // defined inline in TemplateBase.h
4718
4719   /// Retrieve the name of the template that we are specializing.
4720   TemplateName getTemplateName() const { return Template; }
4721
4722   /// Retrieve the template arguments.
4723   const TemplateArgument *getArgs() const {
4724     return reinterpret_cast<const TemplateArgument *>(this + 1);
4725   }
4726
4727   /// Retrieve the number of template arguments.
4728   unsigned getNumArgs() const { return NumArgs; }
4729
4730   /// Retrieve a specific template argument as a type.
4731   /// \pre \c isArgType(Arg)
4732   const TemplateArgument &getArg(unsigned Idx) const; // in TemplateBase.h
4733
4734   ArrayRef<TemplateArgument> template_arguments() const {
4735     return {getArgs(), NumArgs};
4736   }
4737
4738   bool isSugared() const {
4739     return !isDependentType() || isCurrentInstantiation() || isTypeAlias();
4740   }
4741
4742   QualType desugar() const { return getCanonicalTypeInternal(); }
4743
4744   void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Ctx) {
4745     Profile(ID, Template, template_arguments(), Ctx);
4746     if (isTypeAlias())
4747       getAliasedType().Profile(ID);
4748   }
4749
4750   static void Profile(llvm::FoldingSetNodeID &ID, TemplateName T,
4751                       ArrayRef<TemplateArgument> Args,
4752                       const ASTContext &Context);
4753
4754   static bool classof(const Type *T) {
4755     return T->getTypeClass() == TemplateSpecialization;
4756   }
4757 };
4758
4759 /// Print a template argument list, including the '<' and '>'
4760 /// enclosing the template arguments.
4761 void printTemplateArgumentList(raw_ostream &OS,
4762                                ArrayRef<TemplateArgument> Args,
4763                                const PrintingPolicy &Policy);
4764
4765 void printTemplateArgumentList(raw_ostream &OS,
4766                                ArrayRef<TemplateArgumentLoc> Args,
4767                                const PrintingPolicy &Policy);
4768
4769 void printTemplateArgumentList(raw_ostream &OS,
4770                                const TemplateArgumentListInfo &Args,
4771                                const PrintingPolicy &Policy);
4772
4773 /// The injected class name of a C++ class template or class
4774 /// template partial specialization.  Used to record that a type was
4775 /// spelled with a bare identifier rather than as a template-id; the
4776 /// equivalent for non-templated classes is just RecordType.
4777 ///
4778 /// Injected class name types are always dependent.  Template
4779 /// instantiation turns these into RecordTypes.
4780 ///
4781 /// Injected class name types are always canonical.  This works
4782 /// because it is impossible to compare an injected class name type
4783 /// with the corresponding non-injected template type, for the same
4784 /// reason that it is impossible to directly compare template
4785 /// parameters from different dependent contexts: injected class name
4786 /// types can only occur within the scope of a particular templated
4787 /// declaration, and within that scope every template specialization
4788 /// will canonicalize to the injected class name (when appropriate
4789 /// according to the rules of the language).
4790 class InjectedClassNameType : public Type {
4791   friend class ASTContext; // ASTContext creates these.
4792   friend class ASTNodeImporter;
4793   friend class ASTReader; // FIXME: ASTContext::getInjectedClassNameType is not
4794                           // currently suitable for AST reading, too much
4795                           // interdependencies.
4796
4797   CXXRecordDecl *Decl;
4798
4799   /// The template specialization which this type represents.
4800   /// For example, in
4801   ///   template <class T> class A { ... };
4802   /// this is A<T>, whereas in
4803   ///   template <class X, class Y> class A<B<X,Y> > { ... };
4804   /// this is A<B<X,Y> >.
4805   ///
4806   /// It is always unqualified, always a template specialization type,
4807   /// and always dependent.
4808   QualType InjectedType;
4809
4810   InjectedClassNameType(CXXRecordDecl *D, QualType TST)
4811       : Type(InjectedClassName, QualType(), /*Dependent=*/true,
4812              /*InstantiationDependent=*/true,
4813              /*VariablyModified=*/false,
4814              /*ContainsUnexpandedParameterPack=*/false),
4815         Decl(D), InjectedType(TST) {
4816     assert(isa<TemplateSpecializationType>(TST));
4817     assert(!TST.hasQualifiers());
4818     assert(TST->isDependentType());
4819   }
4820
4821 public:
4822   QualType getInjectedSpecializationType() const { return InjectedType; }
4823
4824   const TemplateSpecializationType *getInjectedTST() const {
4825     return cast<TemplateSpecializationType>(InjectedType.getTypePtr());
4826   }
4827
4828   TemplateName getTemplateName() const {
4829     return getInjectedTST()->getTemplateName();
4830   }
4831
4832   CXXRecordDecl *getDecl() const;
4833
4834   bool isSugared() const { return false; }
4835   QualType desugar() const { return QualType(this, 0); }
4836
4837   static bool classof(const Type *T) {
4838     return T->getTypeClass() == InjectedClassName;
4839   }
4840 };
4841
4842 /// The kind of a tag type.
4843 enum TagTypeKind {
4844   /// The "struct" keyword.
4845   TTK_Struct,
4846
4847   /// The "__interface" keyword.
4848   TTK_Interface,
4849
4850   /// The "union" keyword.
4851   TTK_Union,
4852
4853   /// The "class" keyword.
4854   TTK_Class,
4855
4856   /// The "enum" keyword.
4857   TTK_Enum
4858 };
4859
4860 /// The elaboration keyword that precedes a qualified type name or
4861 /// introduces an elaborated-type-specifier.
4862 enum ElaboratedTypeKeyword {
4863   /// The "struct" keyword introduces the elaborated-type-specifier.
4864   ETK_Struct,
4865
4866   /// The "__interface" keyword introduces the elaborated-type-specifier.
4867   ETK_Interface,
4868
4869   /// The "union" keyword introduces the elaborated-type-specifier.
4870   ETK_Union,
4871
4872   /// The "class" keyword introduces the elaborated-type-specifier.
4873   ETK_Class,
4874
4875   /// The "enum" keyword introduces the elaborated-type-specifier.
4876   ETK_Enum,
4877
4878   /// The "typename" keyword precedes the qualified type name, e.g.,
4879   /// \c typename T::type.
4880   ETK_Typename,
4881
4882   /// No keyword precedes the qualified type name.
4883   ETK_None
4884 };
4885
4886 /// A helper class for Type nodes having an ElaboratedTypeKeyword.
4887 /// The keyword in stored in the free bits of the base class.
4888 /// Also provides a few static helpers for converting and printing
4889 /// elaborated type keyword and tag type kind enumerations.
4890 class TypeWithKeyword : public Type {
4891 protected:
4892   TypeWithKeyword(ElaboratedTypeKeyword Keyword, TypeClass tc,
4893                   QualType Canonical, bool Dependent,
4894                   bool InstantiationDependent, bool VariablyModified,
4895                   bool ContainsUnexpandedParameterPack)
4896       : Type(tc, Canonical, Dependent, InstantiationDependent, VariablyModified,
4897              ContainsUnexpandedParameterPack) {
4898     TypeWithKeywordBits.Keyword = Keyword;
4899   }
4900
4901 public:
4902   ElaboratedTypeKeyword getKeyword() const {
4903     return static_cast<ElaboratedTypeKeyword>(TypeWithKeywordBits.Keyword);
4904   }
4905
4906   /// Converts a type specifier (DeclSpec::TST) into an elaborated type keyword.
4907   static ElaboratedTypeKeyword getKeywordForTypeSpec(unsigned TypeSpec);
4908
4909   /// Converts a type specifier (DeclSpec::TST) into a tag type kind.
4910   /// It is an error to provide a type specifier which *isn't* a tag kind here.
4911   static TagTypeKind getTagTypeKindForTypeSpec(unsigned TypeSpec);
4912
4913   /// Converts a TagTypeKind into an elaborated type keyword.
4914   static ElaboratedTypeKeyword getKeywordForTagTypeKind(TagTypeKind Tag);
4915
4916   /// Converts an elaborated type keyword into a TagTypeKind.
4917   /// It is an error to provide an elaborated type keyword
4918   /// which *isn't* a tag kind here.
4919   static TagTypeKind getTagTypeKindForKeyword(ElaboratedTypeKeyword Keyword);
4920
4921   static bool KeywordIsTagTypeKind(ElaboratedTypeKeyword Keyword);
4922
4923   static StringRef getKeywordName(ElaboratedTypeKeyword Keyword);
4924
4925   static StringRef getTagTypeKindName(TagTypeKind Kind) {
4926     return getKeywordName(getKeywordForTagTypeKind(Kind));
4927   }
4928
4929   class CannotCastToThisType {};
4930   static CannotCastToThisType classof(const Type *);
4931 };
4932
4933 /// Represents a type that was referred to using an elaborated type
4934 /// keyword, e.g., struct S, or via a qualified name, e.g., N::M::type,
4935 /// or both.
4936 ///
4937 /// This type is used to keep track of a type name as written in the
4938 /// source code, including tag keywords and any nested-name-specifiers.
4939 /// The type itself is always "sugar", used to express what was written
4940 /// in the source code but containing no additional semantic information.
4941 class ElaboratedType : public TypeWithKeyword, public llvm::FoldingSetNode {
4942   friend class ASTContext; // ASTContext creates these
4943
4944   /// The nested name specifier containing the qualifier.
4945   NestedNameSpecifier *NNS;
4946
4947   /// The type that this qualified name refers to.
4948   QualType NamedType;
4949
4950   /// The (re)declaration of this tag type owned by this occurrence, or nullptr
4951   /// if none.
4952   TagDecl *OwnedTagDecl;
4953
4954   ElaboratedType(ElaboratedTypeKeyword Keyword, NestedNameSpecifier *NNS,
4955                  QualType NamedType, QualType CanonType, TagDecl *OwnedTagDecl)
4956     : TypeWithKeyword(Keyword, Elaborated, CanonType,
4957                       NamedType->isDependentType(),
4958                       NamedType->isInstantiationDependentType(),
4959                       NamedType->isVariablyModifiedType(),
4960                       NamedType->containsUnexpandedParameterPack()),
4961       NNS(NNS), NamedType(NamedType), OwnedTagDecl(OwnedTagDecl) {
4962     assert(!(Keyword == ETK_None && NNS == nullptr) &&
4963            "ElaboratedType cannot have elaborated type keyword "
4964            "and name qualifier both null.");
4965   }
4966
4967 public:
4968   ~ElaboratedType();
4969
4970   /// Retrieve the qualification on this type.
4971   NestedNameSpecifier *getQualifier() const { return NNS; }
4972
4973   /// Retrieve the type named by the qualified-id.
4974   QualType getNamedType() const { return NamedType; }
4975
4976   /// Remove a single level of sugar.
4977   QualType desugar() const { return getNamedType(); }
4978
4979   /// Returns whether this type directly provides sugar.
4980   bool isSugared() const { return true; }
4981
4982   /// Return the (re)declaration of this type owned by this occurrence of this
4983   /// type, or nullptr if none.
4984   TagDecl *getOwnedTagDecl() const { return OwnedTagDecl; }
4985
4986   void Profile(llvm::FoldingSetNodeID &ID) {
4987     Profile(ID, getKeyword(), NNS, NamedType, OwnedTagDecl);
4988   }
4989
4990   static void Profile(llvm::FoldingSetNodeID &ID, ElaboratedTypeKeyword Keyword,
4991                       NestedNameSpecifier *NNS, QualType NamedType,
4992                       TagDecl *OwnedTagDecl) {
4993     ID.AddInteger(Keyword);
4994     ID.AddPointer(NNS);
4995     NamedType.Profile(ID);
4996     ID.AddPointer(OwnedTagDecl);
4997   }
4998
4999   static bool classof(const Type *T) {
5000     return T->getTypeClass() == Elaborated;
5001   }
5002 };
5003
5004 /// Represents a qualified type name for which the type name is
5005 /// dependent.
5006 ///
5007 /// DependentNameType represents a class of dependent types that involve a
5008 /// possibly dependent nested-name-specifier (e.g., "T::") followed by a
5009 /// name of a type. The DependentNameType may start with a "typename" (for a
5010 /// typename-specifier), "class", "struct", "union", or "enum" (for a
5011 /// dependent elaborated-type-specifier), or nothing (in contexts where we
5012 /// know that we must be referring to a type, e.g., in a base class specifier).
5013 /// Typically the nested-name-specifier is dependent, but in MSVC compatibility
5014 /// mode, this type is used with non-dependent names to delay name lookup until
5015 /// instantiation.
5016 class DependentNameType : public TypeWithKeyword, public llvm::FoldingSetNode {
5017   friend class ASTContext; // ASTContext creates these
5018
5019   /// The nested name specifier containing the qualifier.
5020   NestedNameSpecifier *NNS;
5021
5022   /// The type that this typename specifier refers to.
5023   const IdentifierInfo *Name;
5024
5025   DependentNameType(ElaboratedTypeKeyword Keyword, NestedNameSpecifier *NNS,
5026                     const IdentifierInfo *Name, QualType CanonType)
5027       : TypeWithKeyword(Keyword, DependentName, CanonType, /*Dependent=*/true,
5028                         /*InstantiationDependent=*/true,
5029                         /*VariablyModified=*/false,
5030                         NNS->containsUnexpandedParameterPack()),
5031         NNS(NNS), Name(Name) {}
5032
5033 public:
5034   /// Retrieve the qualification on this type.
5035   NestedNameSpecifier *getQualifier() const { return NNS; }
5036
5037   /// Retrieve the type named by the typename specifier as an identifier.
5038   ///
5039   /// This routine will return a non-NULL identifier pointer when the
5040   /// form of the original typename was terminated by an identifier,
5041   /// e.g., "typename T::type".
5042   const IdentifierInfo *getIdentifier() const {
5043     return Name;
5044   }
5045
5046   bool isSugared() const { return false; }
5047   QualType desugar() const { return QualType(this, 0); }
5048
5049   void Profile(llvm::FoldingSetNodeID &ID) {
5050     Profile(ID, getKeyword(), NNS, Name);
5051   }
5052
5053   static void Profile(llvm::FoldingSetNodeID &ID, ElaboratedTypeKeyword Keyword,
5054                       NestedNameSpecifier *NNS, const IdentifierInfo *Name) {
5055     ID.AddInteger(Keyword);
5056     ID.AddPointer(NNS);
5057     ID.AddPointer(Name);
5058   }
5059
5060   static bool classof(const Type *T) {
5061     return T->getTypeClass() == DependentName;
5062   }
5063 };
5064
5065 /// Represents a template specialization type whose template cannot be
5066 /// resolved, e.g.
5067 ///   A<T>::template B<T>
5068 class alignas(8) DependentTemplateSpecializationType
5069     : public TypeWithKeyword,
5070       public llvm::FoldingSetNode {
5071   friend class ASTContext; // ASTContext creates these
5072
5073   /// The nested name specifier containing the qualifier.
5074   NestedNameSpecifier *NNS;
5075
5076   /// The identifier of the template.
5077   const IdentifierInfo *Name;
5078
5079   /// The number of template arguments named in this class template
5080   /// specialization.
5081   unsigned NumArgs;
5082
5083   DependentTemplateSpecializationType(ElaboratedTypeKeyword Keyword,
5084                                       NestedNameSpecifier *NNS,
5085                                       const IdentifierInfo *Name,
5086                                       ArrayRef<TemplateArgument> Args,
5087                                       QualType Canon);
5088
5089   const TemplateArgument *getArgBuffer() const {
5090     return reinterpret_cast<const TemplateArgument*>(this+1);
5091   }
5092
5093   TemplateArgument *getArgBuffer() {
5094     return reinterpret_cast<TemplateArgument*>(this+1);
5095   }
5096
5097 public:
5098   NestedNameSpecifier *getQualifier() const { return NNS; }
5099   const IdentifierInfo *getIdentifier() const { return Name; }
5100
5101   /// Retrieve the template arguments.
5102   const TemplateArgument *getArgs() const {
5103     return getArgBuffer();
5104   }
5105
5106   /// Retrieve the number of template arguments.
5107   unsigned getNumArgs() const { return NumArgs; }
5108
5109   const TemplateArgument &getArg(unsigned Idx) const; // in TemplateBase.h
5110
5111   ArrayRef<TemplateArgument> template_arguments() const {
5112     return {getArgs(), NumArgs};
5113   }
5114
5115   using iterator = const TemplateArgument *;
5116
5117   iterator begin() const { return getArgs(); }
5118   iterator end() const; // inline in TemplateBase.h
5119
5120   bool isSugared() const { return false; }
5121   QualType desugar() const { return QualType(this, 0); }
5122
5123   void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context) {
5124     Profile(ID, Context, getKeyword(), NNS, Name, {getArgs(), NumArgs});
5125   }
5126
5127   static void Profile(llvm::FoldingSetNodeID &ID,
5128                       const ASTContext &Context,
5129                       ElaboratedTypeKeyword Keyword,
5130                       NestedNameSpecifier *Qualifier,
5131                       const IdentifierInfo *Name,
5132                       ArrayRef<TemplateArgument> Args);
5133
5134   static bool classof(const Type *T) {
5135     return T->getTypeClass() == DependentTemplateSpecialization;
5136   }
5137 };
5138
5139 /// Represents a pack expansion of types.
5140 ///
5141 /// Pack expansions are part of C++11 variadic templates. A pack
5142 /// expansion contains a pattern, which itself contains one or more
5143 /// "unexpanded" parameter packs. When instantiated, a pack expansion
5144 /// produces a series of types, each instantiated from the pattern of
5145 /// the expansion, where the Ith instantiation of the pattern uses the
5146 /// Ith arguments bound to each of the unexpanded parameter packs. The
5147 /// pack expansion is considered to "expand" these unexpanded
5148 /// parameter packs.
5149 ///
5150 /// \code
5151 /// template<typename ...Types> struct tuple;
5152 ///
5153 /// template<typename ...Types>
5154 /// struct tuple_of_references {
5155 ///   typedef tuple<Types&...> type;
5156 /// };
5157 /// \endcode
5158 ///
5159 /// Here, the pack expansion \c Types&... is represented via a
5160 /// PackExpansionType whose pattern is Types&.
5161 class PackExpansionType : public Type, public llvm::FoldingSetNode {
5162   friend class ASTContext; // ASTContext creates these
5163
5164   /// The pattern of the pack expansion.
5165   QualType Pattern;
5166
5167   /// The number of expansions that this pack expansion will
5168   /// generate when substituted (+1), or indicates that
5169   ///
5170   /// This field will only have a non-zero value when some of the parameter
5171   /// packs that occur within the pattern have been substituted but others have
5172   /// not.
5173   unsigned NumExpansions;
5174
5175   PackExpansionType(QualType Pattern, QualType Canon,
5176                     Optional<unsigned> NumExpansions)
5177       : Type(PackExpansion, Canon, /*Dependent=*/Pattern->isDependentType(),
5178              /*InstantiationDependent=*/true,
5179              /*VariablyModified=*/Pattern->isVariablyModifiedType(),
5180              /*ContainsUnexpandedParameterPack=*/false),
5181         Pattern(Pattern),
5182         NumExpansions(NumExpansions ? *NumExpansions + 1 : 0) {}
5183
5184 public:
5185   /// Retrieve the pattern of this pack expansion, which is the
5186   /// type that will be repeatedly instantiated when instantiating the
5187   /// pack expansion itself.
5188   QualType getPattern() const { return Pattern; }
5189
5190   /// Retrieve the number of expansions that this pack expansion will
5191   /// generate, if known.
5192   Optional<unsigned> getNumExpansions() const {
5193     if (NumExpansions)
5194       return NumExpansions - 1;
5195
5196     return None;
5197   }
5198
5199   bool isSugared() const { return !Pattern->isDependentType(); }
5200   QualType desugar() const { return isSugared() ? Pattern : QualType(this, 0); }
5201
5202   void Profile(llvm::FoldingSetNodeID &ID) {
5203     Profile(ID, getPattern(), getNumExpansions());
5204   }
5205
5206   static void Profile(llvm::FoldingSetNodeID &ID, QualType Pattern,
5207                       Optional<unsigned> NumExpansions) {
5208     ID.AddPointer(Pattern.getAsOpaquePtr());
5209     ID.AddBoolean(NumExpansions.hasValue());
5210     if (NumExpansions)
5211       ID.AddInteger(*NumExpansions);
5212   }
5213
5214   static bool classof(const Type *T) {
5215     return T->getTypeClass() == PackExpansion;
5216   }
5217 };
5218
5219 /// This class wraps the list of protocol qualifiers. For types that can
5220 /// take ObjC protocol qualifers, they can subclass this class.
5221 template <class T>
5222 class ObjCProtocolQualifiers {
5223 protected:
5224   ObjCProtocolQualifiers() = default;
5225
5226   ObjCProtocolDecl * const *getProtocolStorage() const {
5227     return const_cast<ObjCProtocolQualifiers*>(this)->getProtocolStorage();
5228   }
5229
5230   ObjCProtocolDecl **getProtocolStorage() {
5231     return static_cast<T*>(this)->getProtocolStorageImpl();
5232   }
5233
5234   void setNumProtocols(unsigned N) {
5235     static_cast<T*>(this)->setNumProtocolsImpl(N);
5236   }
5237
5238   void initialize(ArrayRef<ObjCProtocolDecl *> protocols) {
5239     setNumProtocols(protocols.size());
5240     assert(getNumProtocols() == protocols.size() &&
5241            "bitfield overflow in protocol count");
5242     if (!protocols.empty())
5243       memcpy(getProtocolStorage(), protocols.data(),
5244              protocols.size() * sizeof(ObjCProtocolDecl*));
5245   }
5246
5247 public:
5248   using qual_iterator = ObjCProtocolDecl * const *;
5249   using qual_range = llvm::iterator_range<qual_iterator>;
5250
5251   qual_range quals() const { return qual_range(qual_begin(), qual_end()); }
5252   qual_iterator qual_begin() const { return getProtocolStorage(); }
5253   qual_iterator qual_end() const { return qual_begin() + getNumProtocols(); }
5254
5255   bool qual_empty() const { return getNumProtocols() == 0; }
5256
5257   /// Return the number of qualifying protocols in this type, or 0 if
5258   /// there are none.
5259   unsigned getNumProtocols() const {
5260     return static_cast<const T*>(this)->getNumProtocolsImpl();
5261   }
5262
5263   /// Fetch a protocol by index.
5264   ObjCProtocolDecl *getProtocol(unsigned I) const {
5265     assert(I < getNumProtocols() && "Out-of-range protocol access");
5266     return qual_begin()[I];
5267   }
5268
5269   /// Retrieve all of the protocol qualifiers.
5270   ArrayRef<ObjCProtocolDecl *> getProtocols() const {
5271     return ArrayRef<ObjCProtocolDecl *>(qual_begin(), getNumProtocols());
5272   }
5273 };
5274
5275 /// Represents a type parameter type in Objective C. It can take
5276 /// a list of protocols.
5277 class ObjCTypeParamType : public Type,
5278                           public ObjCProtocolQualifiers<ObjCTypeParamType>,
5279                           public llvm::FoldingSetNode {
5280   friend class ASTContext;
5281   friend class ObjCProtocolQualifiers<ObjCTypeParamType>;
5282
5283   /// The number of protocols stored on this type.
5284   unsigned NumProtocols : 6;
5285
5286   ObjCTypeParamDecl *OTPDecl;
5287
5288   /// The protocols are stored after the ObjCTypeParamType node. In the
5289   /// canonical type, the list of protocols are sorted alphabetically
5290   /// and uniqued.
5291   ObjCProtocolDecl **getProtocolStorageImpl();
5292
5293   /// Return the number of qualifying protocols in this interface type,
5294   /// or 0 if there are none.
5295   unsigned getNumProtocolsImpl() const {
5296     return NumProtocols;
5297   }
5298
5299   void setNumProtocolsImpl(unsigned N) {
5300     NumProtocols = N;
5301   }
5302
5303   ObjCTypeParamType(const ObjCTypeParamDecl *D,
5304                     QualType can,
5305                     ArrayRef<ObjCProtocolDecl *> protocols);
5306
5307 public:
5308   bool isSugared() const { return true; }
5309   QualType desugar() const { return getCanonicalTypeInternal(); }
5310
5311   static bool classof(const Type *T) {
5312     return T->getTypeClass() == ObjCTypeParam;
5313   }
5314
5315   void Profile(llvm::FoldingSetNodeID &ID);
5316   static void Profile(llvm::FoldingSetNodeID &ID,
5317                       const ObjCTypeParamDecl *OTPDecl,
5318                       ArrayRef<ObjCProtocolDecl *> protocols);
5319
5320   ObjCTypeParamDecl *getDecl() const { return OTPDecl; }
5321 };
5322
5323 /// Represents a class type in Objective C.
5324 ///
5325 /// Every Objective C type is a combination of a base type, a set of
5326 /// type arguments (optional, for parameterized classes) and a list of
5327 /// protocols.
5328 ///
5329 /// Given the following declarations:
5330 /// \code
5331 ///   \@class C<T>;
5332 ///   \@protocol P;
5333 /// \endcode
5334 ///
5335 /// 'C' is an ObjCInterfaceType C.  It is sugar for an ObjCObjectType
5336 /// with base C and no protocols.
5337 ///
5338 /// 'C<P>' is an unspecialized ObjCObjectType with base C and protocol list [P].
5339 /// 'C<C*>' is a specialized ObjCObjectType with type arguments 'C*' and no 
5340 /// protocol list.
5341 /// 'C<C*><P>' is a specialized ObjCObjectType with base C, type arguments 'C*',
5342 /// and protocol list [P].
5343 ///
5344 /// 'id' is a TypedefType which is sugar for an ObjCObjectPointerType whose
5345 /// pointee is an ObjCObjectType with base BuiltinType::ObjCIdType
5346 /// and no protocols.
5347 ///
5348 /// 'id<P>' is an ObjCObjectPointerType whose pointee is an ObjCObjectType
5349 /// with base BuiltinType::ObjCIdType and protocol list [P].  Eventually
5350 /// this should get its own sugar class to better represent the source.
5351 class ObjCObjectType : public Type,
5352                        public ObjCProtocolQualifiers<ObjCObjectType> {
5353   friend class ObjCProtocolQualifiers<ObjCObjectType>;
5354
5355   // ObjCObjectType.NumTypeArgs - the number of type arguments stored
5356   // after the ObjCObjectPointerType node.
5357   // ObjCObjectType.NumProtocols - the number of protocols stored
5358   // after the type arguments of ObjCObjectPointerType node.
5359   //
5360   // These protocols are those written directly on the type.  If
5361   // protocol qualifiers ever become additive, the iterators will need
5362   // to get kindof complicated.
5363   //
5364   // In the canonical object type, these are sorted alphabetically
5365   // and uniqued.
5366
5367   /// Either a BuiltinType or an InterfaceType or sugar for either.
5368   QualType BaseType;
5369
5370   /// Cached superclass type.
5371   mutable llvm::PointerIntPair<const ObjCObjectType *, 1, bool>
5372     CachedSuperClassType;
5373
5374   QualType *getTypeArgStorage();
5375   const QualType *getTypeArgStorage() const {
5376     return const_cast<ObjCObjectType *>(this)->getTypeArgStorage();
5377   }
5378
5379   ObjCProtocolDecl **getProtocolStorageImpl();
5380   /// Return the number of qualifying protocols in this interface type,
5381   /// or 0 if there are none.
5382   unsigned getNumProtocolsImpl() const {
5383     return ObjCObjectTypeBits.NumProtocols;
5384   }
5385   void setNumProtocolsImpl(unsigned N) {
5386     ObjCObjectTypeBits.NumProtocols = N;
5387   }
5388
5389 protected:
5390   enum Nonce_ObjCInterface { Nonce_ObjCInterface };
5391
5392   ObjCObjectType(QualType Canonical, QualType Base,
5393                  ArrayRef<QualType> typeArgs,
5394                  ArrayRef<ObjCProtocolDecl *> protocols,
5395                  bool isKindOf);
5396
5397   ObjCObjectType(enum Nonce_ObjCInterface)
5398         : Type(ObjCInterface, QualType(), false, false, false, false),
5399           BaseType(QualType(this_(), 0)) {
5400     ObjCObjectTypeBits.NumProtocols = 0;
5401     ObjCObjectTypeBits.NumTypeArgs = 0;
5402     ObjCObjectTypeBits.IsKindOf = 0;
5403   }
5404
5405   void computeSuperClassTypeSlow() const;
5406
5407 public:
5408   /// Gets the base type of this object type.  This is always (possibly
5409   /// sugar for) one of:
5410   ///  - the 'id' builtin type (as opposed to the 'id' type visible to the
5411   ///    user, which is a typedef for an ObjCObjectPointerType)
5412   ///  - the 'Class' builtin type (same caveat)
5413   ///  - an ObjCObjectType (currently always an ObjCInterfaceType)
5414   QualType getBaseType() const { return BaseType; }
5415
5416   bool isObjCId() const {
5417     return getBaseType()->isSpecificBuiltinType(BuiltinType::ObjCId);
5418   }
5419
5420   bool isObjCClass() const {
5421     return getBaseType()->isSpecificBuiltinType(BuiltinType::ObjCClass);
5422   }
5423
5424   bool isObjCUnqualifiedId() const { return qual_empty() && isObjCId(); }
5425   bool isObjCUnqualifiedClass() const { return qual_empty() && isObjCClass(); }
5426   bool isObjCUnqualifiedIdOrClass() const {
5427     if (!qual_empty()) return false;
5428     if (const BuiltinType *T = getBaseType()->getAs<BuiltinType>())
5429       return T->getKind() == BuiltinType::ObjCId ||
5430              T->getKind() == BuiltinType::ObjCClass;
5431     return false;
5432   }
5433   bool isObjCQualifiedId() const { return !qual_empty() && isObjCId(); }
5434   bool isObjCQualifiedClass() const { return !qual_empty() && isObjCClass(); }
5435
5436   /// Gets the interface declaration for this object type, if the base type
5437   /// really is an interface.
5438   ObjCInterfaceDecl *getInterface() const;
5439
5440   /// Determine whether this object type is "specialized", meaning
5441   /// that it has type arguments.
5442   bool isSpecialized() const;
5443
5444   /// Determine whether this object type was written with type arguments.
5445   bool isSpecializedAsWritten() const {
5446     return ObjCObjectTypeBits.NumTypeArgs > 0;
5447   }
5448
5449   /// Determine whether this object type is "unspecialized", meaning
5450   /// that it has no type arguments.
5451   bool isUnspecialized() const { return !isSpecialized(); }
5452
5453   /// Determine whether this object type is "unspecialized" as
5454   /// written, meaning that it has no type arguments.
5455   bool isUnspecializedAsWritten() const { return !isSpecializedAsWritten(); }
5456
5457   /// Retrieve the type arguments of this object type (semantically).
5458   ArrayRef<QualType> getTypeArgs() const;
5459
5460   /// Retrieve the type arguments of this object type as they were
5461   /// written.
5462   ArrayRef<QualType> getTypeArgsAsWritten() const {
5463     return llvm::makeArrayRef(getTypeArgStorage(),
5464                               ObjCObjectTypeBits.NumTypeArgs);
5465   }
5466
5467   /// Whether this is a "__kindof" type as written.
5468   bool isKindOfTypeAsWritten() const { return ObjCObjectTypeBits.IsKindOf; }
5469
5470   /// Whether this ia a "__kindof" type (semantically).
5471   bool isKindOfType() const;
5472
5473   /// Retrieve the type of the superclass of this object type.
5474   ///
5475   /// This operation substitutes any type arguments into the
5476   /// superclass of the current class type, potentially producing a
5477   /// specialization of the superclass type. Produces a null type if
5478   /// there is no superclass.
5479   QualType getSuperClassType() const {
5480     if (!CachedSuperClassType.getInt())
5481       computeSuperClassTypeSlow();
5482
5483     assert(CachedSuperClassType.getInt() && "Superclass not set?");
5484     return QualType(CachedSuperClassType.getPointer(), 0);
5485   }
5486
5487   /// Strip off the Objective-C "kindof" type and (with it) any
5488   /// protocol qualifiers.
5489   QualType stripObjCKindOfTypeAndQuals(const ASTContext &ctx) const;
5490
5491   bool isSugared() const { return false; }
5492   QualType desugar() const { return QualType(this, 0); }
5493
5494   static bool classof(const Type *T) {
5495     return T->getTypeClass() == ObjCObject ||
5496            T->getTypeClass() == ObjCInterface;
5497   }
5498 };
5499
5500 /// A class providing a concrete implementation
5501 /// of ObjCObjectType, so as to not increase the footprint of
5502 /// ObjCInterfaceType.  Code outside of ASTContext and the core type
5503 /// system should not reference this type.
5504 class ObjCObjectTypeImpl : public ObjCObjectType, public llvm::FoldingSetNode {
5505   friend class ASTContext;
5506
5507   // If anyone adds fields here, ObjCObjectType::getProtocolStorage()
5508   // will need to be modified.
5509
5510   ObjCObjectTypeImpl(QualType Canonical, QualType Base,
5511                      ArrayRef<QualType> typeArgs,
5512                      ArrayRef<ObjCProtocolDecl *> protocols,
5513                      bool isKindOf)
5514       : ObjCObjectType(Canonical, Base, typeArgs, protocols, isKindOf) {}
5515
5516 public:
5517   void Profile(llvm::FoldingSetNodeID &ID);
5518   static void Profile(llvm::FoldingSetNodeID &ID,
5519                       QualType Base,
5520                       ArrayRef<QualType> typeArgs,
5521                       ArrayRef<ObjCProtocolDecl *> protocols,
5522                       bool isKindOf);
5523 };
5524
5525 inline QualType *ObjCObjectType::getTypeArgStorage() {
5526   return reinterpret_cast<QualType *>(static_cast<ObjCObjectTypeImpl*>(this)+1);
5527 }
5528
5529 inline ObjCProtocolDecl **ObjCObjectType::getProtocolStorageImpl() {
5530     return reinterpret_cast<ObjCProtocolDecl**>(
5531              getTypeArgStorage() + ObjCObjectTypeBits.NumTypeArgs);
5532 }
5533
5534 inline ObjCProtocolDecl **ObjCTypeParamType::getProtocolStorageImpl() {
5535     return reinterpret_cast<ObjCProtocolDecl**>(
5536              static_cast<ObjCTypeParamType*>(this)+1);
5537 }
5538
5539 /// Interfaces are the core concept in Objective-C for object oriented design.
5540 /// They basically correspond to C++ classes.  There are two kinds of interface
5541 /// types: normal interfaces like `NSString`, and qualified interfaces, which
5542 /// are qualified with a protocol list like `NSString<NSCopyable, NSAmazing>`.
5543 ///
5544 /// ObjCInterfaceType guarantees the following properties when considered
5545 /// as a subtype of its superclass, ObjCObjectType:
5546 ///   - There are no protocol qualifiers.  To reinforce this, code which
5547 ///     tries to invoke the protocol methods via an ObjCInterfaceType will
5548 ///     fail to compile.
5549 ///   - It is its own base type.  That is, if T is an ObjCInterfaceType*,
5550 ///     T->getBaseType() == QualType(T, 0).
5551 class ObjCInterfaceType : public ObjCObjectType {
5552   friend class ASTContext; // ASTContext creates these.
5553   friend class ASTReader;
5554   friend class ObjCInterfaceDecl;
5555
5556   mutable ObjCInterfaceDecl *Decl;
5557
5558   ObjCInterfaceType(const ObjCInterfaceDecl *D)
5559       : ObjCObjectType(Nonce_ObjCInterface),
5560         Decl(const_cast<ObjCInterfaceDecl*>(D)) {}
5561
5562 public:
5563   /// Get the declaration of this interface.
5564   ObjCInterfaceDecl *getDecl() const { return Decl; }
5565
5566   bool isSugared() const { return false; }
5567   QualType desugar() const { return QualType(this, 0); }
5568
5569   static bool classof(const Type *T) {
5570     return T->getTypeClass() == ObjCInterface;
5571   }
5572
5573   // Nonsense to "hide" certain members of ObjCObjectType within this
5574   // class.  People asking for protocols on an ObjCInterfaceType are
5575   // not going to get what they want: ObjCInterfaceTypes are
5576   // guaranteed to have no protocols.
5577   enum {
5578     qual_iterator,
5579     qual_begin,
5580     qual_end,
5581     getNumProtocols,
5582     getProtocol
5583   };
5584 };
5585
5586 inline ObjCInterfaceDecl *ObjCObjectType::getInterface() const {
5587   QualType baseType = getBaseType();
5588   while (const auto *ObjT = baseType->getAs<ObjCObjectType>()) {
5589     if (const auto *T = dyn_cast<ObjCInterfaceType>(ObjT))
5590       return T->getDecl();
5591
5592     baseType = ObjT->getBaseType();
5593   }
5594
5595   return nullptr;
5596 }
5597
5598 /// Represents a pointer to an Objective C object.
5599 ///
5600 /// These are constructed from pointer declarators when the pointee type is
5601 /// an ObjCObjectType (or sugar for one).  In addition, the 'id' and 'Class'
5602 /// types are typedefs for these, and the protocol-qualified types 'id<P>'
5603 /// and 'Class<P>' are translated into these.
5604 ///
5605 /// Pointers to pointers to Objective C objects are still PointerTypes;
5606 /// only the first level of pointer gets it own type implementation.
5607 class ObjCObjectPointerType : public Type, public llvm::FoldingSetNode {
5608   friend class ASTContext; // ASTContext creates these.
5609
5610   QualType PointeeType;
5611
5612   ObjCObjectPointerType(QualType Canonical, QualType Pointee)
5613       : Type(ObjCObjectPointer, Canonical,
5614              Pointee->isDependentType(),
5615              Pointee->isInstantiationDependentType(),
5616              Pointee->isVariablyModifiedType(),
5617              Pointee->containsUnexpandedParameterPack()),
5618         PointeeType(Pointee) {}
5619
5620 public:
5621   /// Gets the type pointed to by this ObjC pointer.
5622   /// The result will always be an ObjCObjectType or sugar thereof.
5623   QualType getPointeeType() const { return PointeeType; }
5624
5625   /// Gets the type pointed to by this ObjC pointer.  Always returns non-null.
5626   ///
5627   /// This method is equivalent to getPointeeType() except that
5628   /// it discards any typedefs (or other sugar) between this
5629   /// type and the "outermost" object type.  So for:
5630   /// \code
5631   ///   \@class A; \@protocol P; \@protocol Q;
5632   ///   typedef A<P> AP;
5633   ///   typedef A A1;
5634   ///   typedef A1<P> A1P;
5635   ///   typedef A1P<Q> A1PQ;
5636   /// \endcode
5637   /// For 'A*', getObjectType() will return 'A'.
5638   /// For 'A<P>*', getObjectType() will return 'A<P>'.
5639   /// For 'AP*', getObjectType() will return 'A<P>'.
5640   /// For 'A1*', getObjectType() will return 'A'.
5641   /// For 'A1<P>*', getObjectType() will return 'A1<P>'.
5642   /// For 'A1P*', getObjectType() will return 'A1<P>'.
5643   /// For 'A1PQ*', getObjectType() will return 'A1<Q>', because
5644   ///   adding protocols to a protocol-qualified base discards the
5645   ///   old qualifiers (for now).  But if it didn't, getObjectType()
5646   ///   would return 'A1P<Q>' (and we'd have to make iterating over
5647   ///   qualifiers more complicated).
5648   const ObjCObjectType *getObjectType() const {
5649     return PointeeType->castAs<ObjCObjectType>();
5650   }
5651
5652   /// If this pointer points to an Objective C
5653   /// \@interface type, gets the type for that interface.  Any protocol
5654   /// qualifiers on the interface are ignored.
5655   ///
5656   /// \return null if the base type for this pointer is 'id' or 'Class'
5657   const ObjCInterfaceType *getInterfaceType() const;
5658
5659   /// If this pointer points to an Objective \@interface
5660   /// type, gets the declaration for that interface.
5661   ///
5662   /// \return null if the base type for this pointer is 'id' or 'Class'
5663   ObjCInterfaceDecl *getInterfaceDecl() const {
5664     return getObjectType()->getInterface();
5665   }
5666
5667   /// True if this is equivalent to the 'id' type, i.e. if
5668   /// its object type is the primitive 'id' type with no protocols.
5669   bool isObjCIdType() const {
5670     return getObjectType()->isObjCUnqualifiedId();
5671   }
5672
5673   /// True if this is equivalent to the 'Class' type,
5674   /// i.e. if its object tive is the primitive 'Class' type with no protocols.
5675   bool isObjCClassType() const {
5676     return getObjectType()->isObjCUnqualifiedClass();
5677   }
5678
5679   /// True if this is equivalent to the 'id' or 'Class' type,
5680   bool isObjCIdOrClassType() const {
5681     return getObjectType()->isObjCUnqualifiedIdOrClass();
5682   }
5683
5684   /// True if this is equivalent to 'id<P>' for some non-empty set of
5685   /// protocols.
5686   bool isObjCQualifiedIdType() const {
5687     return getObjectType()->isObjCQualifiedId();
5688   }
5689
5690   /// True if this is equivalent to 'Class<P>' for some non-empty set of
5691   /// protocols.
5692   bool isObjCQualifiedClassType() const {
5693     return getObjectType()->isObjCQualifiedClass();
5694   }
5695
5696   /// Whether this is a "__kindof" type.
5697   bool isKindOfType() const { return getObjectType()->isKindOfType(); }
5698
5699   /// Whether this type is specialized, meaning that it has type arguments.
5700   bool isSpecialized() const { return getObjectType()->isSpecialized(); }
5701
5702   /// Whether this type is specialized, meaning that it has type arguments.
5703   bool isSpecializedAsWritten() const {
5704     return getObjectType()->isSpecializedAsWritten();
5705   }
5706
5707   /// Whether this type is unspecialized, meaning that is has no type arguments.
5708   bool isUnspecialized() const { return getObjectType()->isUnspecialized(); }
5709
5710   /// Determine whether this object type is "unspecialized" as
5711   /// written, meaning that it has no type arguments.
5712   bool isUnspecializedAsWritten() const { return !isSpecializedAsWritten(); }
5713
5714   /// Retrieve the type arguments for this type.
5715   ArrayRef<QualType> getTypeArgs() const {
5716     return getObjectType()->getTypeArgs();
5717   }
5718
5719   /// Retrieve the type arguments for this type.
5720   ArrayRef<QualType> getTypeArgsAsWritten() const {
5721     return getObjectType()->getTypeArgsAsWritten();
5722   }
5723
5724   /// An iterator over the qualifiers on the object type.  Provided
5725   /// for convenience.  This will always iterate over the full set of
5726   /// protocols on a type, not just those provided directly.
5727   using qual_iterator = ObjCObjectType::qual_iterator;
5728   using qual_range = llvm::iterator_range<qual_iterator>;
5729
5730   qual_range quals() const { return qual_range(qual_begin(), qual_end()); }
5731
5732   qual_iterator qual_begin() const {
5733     return getObjectType()->qual_begin();
5734   }
5735
5736   qual_iterator qual_end() const {
5737     return getObjectType()->qual_end();
5738   }
5739
5740   bool qual_empty() const { return getObjectType()->qual_empty(); }
5741
5742   /// Return the number of qualifying protocols on the object type.
5743   unsigned getNumProtocols() const {
5744     return getObjectType()->getNumProtocols();
5745   }
5746
5747   /// Retrieve a qualifying protocol by index on the object type.
5748   ObjCProtocolDecl *getProtocol(unsigned I) const {
5749     return getObjectType()->getProtocol(I);
5750   }
5751
5752   bool isSugared() const { return false; }
5753   QualType desugar() const { return QualType(this, 0); }
5754
5755   /// Retrieve the type of the superclass of this object pointer type.
5756   ///
5757   /// This operation substitutes any type arguments into the
5758   /// superclass of the current class type, potentially producing a
5759   /// pointer to a specialization of the superclass type. Produces a
5760   /// null type if there is no superclass.
5761   QualType getSuperClassType() const;
5762
5763   /// Strip off the Objective-C "kindof" type and (with it) any
5764   /// protocol qualifiers.
5765   const ObjCObjectPointerType *stripObjCKindOfTypeAndQuals(
5766                                  const ASTContext &ctx) const;
5767
5768   void Profile(llvm::FoldingSetNodeID &ID) {
5769     Profile(ID, getPointeeType());
5770   }
5771
5772   static void Profile(llvm::FoldingSetNodeID &ID, QualType T) {
5773     ID.AddPointer(T.getAsOpaquePtr());
5774   }
5775
5776   static bool classof(const Type *T) {
5777     return T->getTypeClass() == ObjCObjectPointer;
5778   }
5779 };
5780
5781 class AtomicType : public Type, public llvm::FoldingSetNode {
5782   friend class ASTContext; // ASTContext creates these.
5783
5784   QualType ValueType;
5785
5786   AtomicType(QualType ValTy, QualType Canonical)
5787       : Type(Atomic, Canonical, ValTy->isDependentType(),
5788              ValTy->isInstantiationDependentType(),
5789              ValTy->isVariablyModifiedType(),
5790              ValTy->containsUnexpandedParameterPack()),
5791         ValueType(ValTy) {}
5792
5793 public:
5794   /// Gets the type contained by this atomic type, i.e.
5795   /// the type returned by performing an atomic load of this atomic type.
5796   QualType getValueType() const { return ValueType; }
5797
5798   bool isSugared() const { return false; }
5799   QualType desugar() const { return QualType(this, 0); }
5800
5801   void Profile(llvm::FoldingSetNodeID &ID) {
5802     Profile(ID, getValueType());
5803   }
5804
5805   static void Profile(llvm::FoldingSetNodeID &ID, QualType T) {
5806     ID.AddPointer(T.getAsOpaquePtr());
5807   }
5808
5809   static bool classof(const Type *T) {
5810     return T->getTypeClass() == Atomic;
5811   }
5812 };
5813
5814 /// PipeType - OpenCL20.
5815 class PipeType : public Type, public llvm::FoldingSetNode {
5816   friend class ASTContext; // ASTContext creates these.
5817
5818   QualType ElementType;
5819   bool isRead;
5820
5821   PipeType(QualType elemType, QualType CanonicalPtr, bool isRead)
5822       : Type(Pipe, CanonicalPtr, elemType->isDependentType(),
5823              elemType->isInstantiationDependentType(),
5824              elemType->isVariablyModifiedType(),
5825              elemType->containsUnexpandedParameterPack()),
5826         ElementType(elemType), isRead(isRead) {}
5827
5828 public:
5829   QualType getElementType() const { return ElementType; }
5830
5831   bool isSugared() const { return false; }
5832
5833   QualType desugar() const { return QualType(this, 0); }
5834
5835   void Profile(llvm::FoldingSetNodeID &ID) {
5836     Profile(ID, getElementType(), isReadOnly());
5837   }
5838
5839   static void Profile(llvm::FoldingSetNodeID &ID, QualType T, bool isRead) {
5840     ID.AddPointer(T.getAsOpaquePtr());
5841     ID.AddBoolean(isRead);
5842   }
5843
5844   static bool classof(const Type *T) {
5845     return T->getTypeClass() == Pipe;
5846   }
5847
5848   bool isReadOnly() const { return isRead; }
5849 };
5850
5851 /// A qualifier set is used to build a set of qualifiers.
5852 class QualifierCollector : public Qualifiers {
5853 public:
5854   QualifierCollector(Qualifiers Qs = Qualifiers()) : Qualifiers(Qs) {}
5855
5856   /// Collect any qualifiers on the given type and return an
5857   /// unqualified type.  The qualifiers are assumed to be consistent
5858   /// with those already in the type.
5859   const Type *strip(QualType type) {
5860     addFastQualifiers(type.getLocalFastQualifiers());
5861     if (!type.hasLocalNonFastQualifiers())
5862       return type.getTypePtrUnsafe();
5863
5864     const ExtQuals *extQuals = type.getExtQualsUnsafe();
5865     addConsistentQualifiers(extQuals->getQualifiers());
5866     return extQuals->getBaseType();
5867   }
5868
5869   /// Apply the collected qualifiers to the given type.
5870   QualType apply(const ASTContext &Context, QualType QT) const;
5871
5872   /// Apply the collected qualifiers to the given type.
5873   QualType apply(const ASTContext &Context, const Type* T) const;
5874 };
5875
5876 // Inline function definitions.
5877
5878 inline SplitQualType SplitQualType::getSingleStepDesugaredType() const {
5879   SplitQualType desugar =
5880     Ty->getLocallyUnqualifiedSingleStepDesugaredType().split();
5881   desugar.Quals.addConsistentQualifiers(Quals);
5882   return desugar;
5883 }
5884
5885 inline const Type *QualType::getTypePtr() const {
5886   return getCommonPtr()->BaseType;
5887 }
5888
5889 inline const Type *QualType::getTypePtrOrNull() const {
5890   return (isNull() ? nullptr : getCommonPtr()->BaseType);
5891 }
5892
5893 inline SplitQualType QualType::split() const {
5894   if (!hasLocalNonFastQualifiers())
5895     return SplitQualType(getTypePtrUnsafe(),
5896                          Qualifiers::fromFastMask(getLocalFastQualifiers()));
5897
5898   const ExtQuals *eq = getExtQualsUnsafe();
5899   Qualifiers qs = eq->getQualifiers();
5900   qs.addFastQualifiers(getLocalFastQualifiers());
5901   return SplitQualType(eq->getBaseType(), qs);
5902 }
5903
5904 inline Qualifiers QualType::getLocalQualifiers() const {
5905   Qualifiers Quals;
5906   if (hasLocalNonFastQualifiers())
5907     Quals = getExtQualsUnsafe()->getQualifiers();
5908   Quals.addFastQualifiers(getLocalFastQualifiers());
5909   return Quals;
5910 }
5911
5912 inline Qualifiers QualType::getQualifiers() const {
5913   Qualifiers quals = getCommonPtr()->CanonicalType.getLocalQualifiers();
5914   quals.addFastQualifiers(getLocalFastQualifiers());
5915   return quals;
5916 }
5917
5918 inline unsigned QualType::getCVRQualifiers() const {
5919   unsigned cvr = getCommonPtr()->CanonicalType.getLocalCVRQualifiers();
5920   cvr |= getLocalCVRQualifiers();
5921   return cvr;
5922 }
5923
5924 inline QualType QualType::getCanonicalType() const {
5925   QualType canon = getCommonPtr()->CanonicalType;
5926   return canon.withFastQualifiers(getLocalFastQualifiers());
5927 }
5928
5929 inline bool QualType::isCanonical() const {
5930   return getTypePtr()->isCanonicalUnqualified();
5931 }
5932
5933 inline bool QualType::isCanonicalAsParam() const {
5934   if (!isCanonical()) return false;
5935   if (hasLocalQualifiers()) return false;
5936
5937   const Type *T = getTypePtr();
5938   if (T->isVariablyModifiedType() && T->hasSizedVLAType())
5939     return false;
5940
5941   return !isa<FunctionType>(T) && !isa<ArrayType>(T);
5942 }
5943
5944 inline bool QualType::isConstQualified() const {
5945   return isLocalConstQualified() ||
5946          getCommonPtr()->CanonicalType.isLocalConstQualified();
5947 }
5948
5949 inline bool QualType::isRestrictQualified() const {
5950   return isLocalRestrictQualified() ||
5951          getCommonPtr()->CanonicalType.isLocalRestrictQualified();
5952 }
5953
5954
5955 inline bool QualType::isVolatileQualified() const {
5956   return isLocalVolatileQualified() ||
5957          getCommonPtr()->CanonicalType.isLocalVolatileQualified();
5958 }
5959
5960 inline bool QualType::hasQualifiers() const {
5961   return hasLocalQualifiers() ||
5962          getCommonPtr()->CanonicalType.hasLocalQualifiers();
5963 }
5964
5965 inline QualType QualType::getUnqualifiedType() const {
5966   if (!getTypePtr()->getCanonicalTypeInternal().hasLocalQualifiers())
5967     return QualType(getTypePtr(), 0);
5968
5969   return QualType(getSplitUnqualifiedTypeImpl(*this).Ty, 0);
5970 }
5971   
5972 inline SplitQualType QualType::getSplitUnqualifiedType() const {
5973   if (!getTypePtr()->getCanonicalTypeInternal().hasLocalQualifiers())
5974     return split();
5975
5976   return getSplitUnqualifiedTypeImpl(*this);
5977 }
5978
5979 inline void QualType::removeLocalConst() {
5980   removeLocalFastQualifiers(Qualifiers::Const);
5981 }
5982
5983 inline void QualType::removeLocalRestrict() {
5984   removeLocalFastQualifiers(Qualifiers::Restrict);
5985 }
5986
5987 inline void QualType::removeLocalVolatile() {
5988   removeLocalFastQualifiers(Qualifiers::Volatile);
5989 }
5990
5991 inline void QualType::removeLocalCVRQualifiers(unsigned Mask) {
5992   assert(!(Mask & ~Qualifiers::CVRMask) && "mask has non-CVR bits");
5993   static_assert((int)Qualifiers::CVRMask == (int)Qualifiers::FastMask,
5994                 "Fast bits differ from CVR bits!");
5995
5996   // Fast path: we don't need to touch the slow qualifiers.
5997   removeLocalFastQualifiers(Mask);
5998 }
5999
6000 /// Return the address space of this type.
6001 inline LangAS QualType::getAddressSpace() const {
6002   return getQualifiers().getAddressSpace();
6003 }
6004
6005 /// Return the gc attribute of this type.
6006 inline Qualifiers::GC QualType::getObjCGCAttr() const {
6007   return getQualifiers().getObjCGCAttr();
6008 }
6009
6010 inline FunctionType::ExtInfo getFunctionExtInfo(const Type &t) {
6011   if (const auto *PT = t.getAs<PointerType>()) {
6012     if (const auto *FT = PT->getPointeeType()->getAs<FunctionType>())
6013       return FT->getExtInfo();
6014   } else if (const auto *FT = t.getAs<FunctionType>())
6015     return FT->getExtInfo();
6016
6017   return FunctionType::ExtInfo();
6018 }
6019
6020 inline FunctionType::ExtInfo getFunctionExtInfo(QualType t) {
6021   return getFunctionExtInfo(*t);
6022 }
6023
6024 /// Determine whether this type is more
6025 /// qualified than the Other type. For example, "const volatile int"
6026 /// is more qualified than "const int", "volatile int", and
6027 /// "int". However, it is not more qualified than "const volatile
6028 /// int".
6029 inline bool QualType::isMoreQualifiedThan(QualType other) const {
6030   Qualifiers MyQuals = getQualifiers();
6031   Qualifiers OtherQuals = other.getQualifiers();
6032   return (MyQuals != OtherQuals && MyQuals.compatiblyIncludes(OtherQuals));
6033 }
6034
6035 /// Determine whether this type is at last
6036 /// as qualified as the Other type. For example, "const volatile
6037 /// int" is at least as qualified as "const int", "volatile int",
6038 /// "int", and "const volatile int".
6039 inline bool QualType::isAtLeastAsQualifiedAs(QualType other) const {
6040   Qualifiers OtherQuals = other.getQualifiers();
6041
6042   // Ignore __unaligned qualifier if this type is a void.
6043   if (getUnqualifiedType()->isVoidType())
6044     OtherQuals.removeUnaligned();
6045
6046   return getQualifiers().compatiblyIncludes(OtherQuals);
6047 }
6048
6049 /// If Type is a reference type (e.g., const
6050 /// int&), returns the type that the reference refers to ("const
6051 /// int"). Otherwise, returns the type itself. This routine is used
6052 /// throughout Sema to implement C++ 5p6:
6053 ///
6054 ///   If an expression initially has the type "reference to T" (8.3.2,
6055 ///   8.5.3), the type is adjusted to "T" prior to any further
6056 ///   analysis, the expression designates the object or function
6057 ///   denoted by the reference, and the expression is an lvalue.
6058 inline QualType QualType::getNonReferenceType() const {
6059   if (const auto *RefType = (*this)->getAs<ReferenceType>())
6060     return RefType->getPointeeType();
6061   else
6062     return *this;
6063 }
6064
6065 inline bool QualType::isCForbiddenLValueType() const {
6066   return ((getTypePtr()->isVoidType() && !hasQualifiers()) ||
6067           getTypePtr()->isFunctionType());
6068 }
6069
6070 /// Tests whether the type is categorized as a fundamental type.
6071 ///
6072 /// \returns True for types specified in C++0x [basic.fundamental].
6073 inline bool Type::isFundamentalType() const {
6074   return isVoidType() ||
6075          // FIXME: It's really annoying that we don't have an
6076          // 'isArithmeticType()' which agrees with the standard definition.
6077          (isArithmeticType() && !isEnumeralType());
6078 }
6079
6080 /// Tests whether the type is categorized as a compound type.
6081 ///
6082 /// \returns True for types specified in C++0x [basic.compound].
6083 inline bool Type::isCompoundType() const {
6084   // C++0x [basic.compound]p1:
6085   //   Compound types can be constructed in the following ways:
6086   //    -- arrays of objects of a given type [...];
6087   return isArrayType() ||
6088   //    -- functions, which have parameters of given types [...];
6089          isFunctionType() ||
6090   //    -- pointers to void or objects or functions [...];
6091          isPointerType() ||
6092   //    -- references to objects or functions of a given type. [...]
6093          isReferenceType() ||
6094   //    -- classes containing a sequence of objects of various types, [...];
6095          isRecordType() ||
6096   //    -- unions, which are classes capable of containing objects of different
6097   //               types at different times;
6098          isUnionType() ||
6099   //    -- enumerations, which comprise a set of named constant values. [...];
6100          isEnumeralType() ||
6101   //    -- pointers to non-static class members, [...].
6102          isMemberPointerType();
6103 }
6104
6105 inline bool Type::isFunctionType() const {
6106   return isa<FunctionType>(CanonicalType);
6107 }
6108
6109 inline bool Type::isPointerType() const {
6110   return isa<PointerType>(CanonicalType);
6111 }
6112
6113 inline bool Type::isAnyPointerType() const {
6114   return isPointerType() || isObjCObjectPointerType();
6115 }
6116
6117 inline bool Type::isBlockPointerType() const {
6118   return isa<BlockPointerType>(CanonicalType);
6119 }
6120
6121 inline bool Type::isReferenceType() const {
6122   return isa<ReferenceType>(CanonicalType);
6123 }
6124
6125 inline bool Type::isLValueReferenceType() const {
6126   return isa<LValueReferenceType>(CanonicalType);
6127 }
6128
6129 inline bool Type::isRValueReferenceType() const {
6130   return isa<RValueReferenceType>(CanonicalType);
6131 }
6132
6133 inline bool Type::isFunctionPointerType() const {
6134   if (const auto *T = getAs<PointerType>())
6135     return T->getPointeeType()->isFunctionType();
6136   else
6137     return false;
6138 }
6139
6140 inline bool Type::isMemberPointerType() const {
6141   return isa<MemberPointerType>(CanonicalType);
6142 }
6143
6144 inline bool Type::isMemberFunctionPointerType() const {
6145   if (const auto *T = getAs<MemberPointerType>())
6146     return T->isMemberFunctionPointer();
6147   else
6148     return false;
6149 }
6150
6151 inline bool Type::isMemberDataPointerType() const {
6152   if (const auto *T = getAs<MemberPointerType>())
6153     return T->isMemberDataPointer();
6154   else
6155     return false;
6156 }
6157
6158 inline bool Type::isArrayType() const {
6159   return isa<ArrayType>(CanonicalType);
6160 }
6161
6162 inline bool Type::isConstantArrayType() const {
6163   return isa<ConstantArrayType>(CanonicalType);
6164 }
6165
6166 inline bool Type::isIncompleteArrayType() const {
6167   return isa<IncompleteArrayType>(CanonicalType);
6168 }
6169
6170 inline bool Type::isVariableArrayType() const {
6171   return isa<VariableArrayType>(CanonicalType);
6172 }
6173
6174 inline bool Type::isDependentSizedArrayType() const {
6175   return isa<DependentSizedArrayType>(CanonicalType);
6176 }
6177
6178 inline bool Type::isBuiltinType() const {
6179   return isa<BuiltinType>(CanonicalType);
6180 }
6181
6182 inline bool Type::isRecordType() const {
6183   return isa<RecordType>(CanonicalType);
6184 }
6185
6186 inline bool Type::isEnumeralType() const {
6187   return isa<EnumType>(CanonicalType);
6188 }
6189
6190 inline bool Type::isAnyComplexType() const {
6191   return isa<ComplexType>(CanonicalType);
6192 }
6193
6194 inline bool Type::isVectorType() const {
6195   return isa<VectorType>(CanonicalType);
6196 }
6197
6198 inline bool Type::isExtVectorType() const {
6199   return isa<ExtVectorType>(CanonicalType);
6200 }
6201
6202 inline bool Type::isDependentAddressSpaceType() const {
6203   return isa<DependentAddressSpaceType>(CanonicalType);
6204 }
6205
6206 inline bool Type::isObjCObjectPointerType() const {
6207   return isa<ObjCObjectPointerType>(CanonicalType);
6208 }
6209
6210 inline bool Type::isObjCObjectType() const {
6211   return isa<ObjCObjectType>(CanonicalType);
6212 }
6213
6214 inline bool Type::isObjCObjectOrInterfaceType() const {
6215   return isa<ObjCInterfaceType>(CanonicalType) ||
6216     isa<ObjCObjectType>(CanonicalType);
6217 }
6218
6219 inline bool Type::isAtomicType() const {
6220   return isa<AtomicType>(CanonicalType);
6221 }
6222
6223 inline bool Type::isObjCQualifiedIdType() const {
6224   if (const auto *OPT = getAs<ObjCObjectPointerType>())
6225     return OPT->isObjCQualifiedIdType();
6226   return false;
6227 }
6228
6229 inline bool Type::isObjCQualifiedClassType() const {
6230   if (const auto *OPT = getAs<ObjCObjectPointerType>())
6231     return OPT->isObjCQualifiedClassType();
6232   return false;
6233 }
6234
6235 inline bool Type::isObjCIdType() const {
6236   if (const auto *OPT = getAs<ObjCObjectPointerType>())
6237     return OPT->isObjCIdType();
6238   return false;
6239 }
6240
6241 inline bool Type::isObjCClassType() const {
6242   if (const auto *OPT = getAs<ObjCObjectPointerType>())
6243     return OPT->isObjCClassType();
6244   return false;
6245 }
6246
6247 inline bool Type::isObjCSelType() const {
6248   if (const auto *OPT = getAs<PointerType>())
6249     return OPT->getPointeeType()->isSpecificBuiltinType(BuiltinType::ObjCSel);
6250   return false;
6251 }
6252
6253 inline bool Type::isObjCBuiltinType() const {
6254   return isObjCIdType() || isObjCClassType() || isObjCSelType();
6255 }
6256
6257 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
6258   inline bool Type::is##Id##Type() const { \
6259     return isSpecificBuiltinType(BuiltinType::Id); \
6260   }
6261 #include "clang/Basic/OpenCLImageTypes.def"
6262
6263 inline bool Type::isSamplerT() const {
6264   return isSpecificBuiltinType(BuiltinType::OCLSampler);
6265 }
6266
6267 inline bool Type::isEventT() const {
6268   return isSpecificBuiltinType(BuiltinType::OCLEvent);
6269 }
6270
6271 inline bool Type::isClkEventT() const {
6272   return isSpecificBuiltinType(BuiltinType::OCLClkEvent);
6273 }
6274
6275 inline bool Type::isQueueT() const {
6276   return isSpecificBuiltinType(BuiltinType::OCLQueue);
6277 }
6278
6279 inline bool Type::isReserveIDT() const {
6280   return isSpecificBuiltinType(BuiltinType::OCLReserveID);
6281 }
6282
6283 inline bool Type::isImageType() const {
6284 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) is##Id##Type() ||
6285   return
6286 #include "clang/Basic/OpenCLImageTypes.def"
6287       false; // end boolean or operation
6288 }
6289
6290 inline bool Type::isPipeType() const {
6291   return isa<PipeType>(CanonicalType);
6292 }
6293
6294 inline bool Type::isOpenCLSpecificType() const {
6295   return isSamplerT() || isEventT() || isImageType() || isClkEventT() ||
6296          isQueueT() || isReserveIDT() || isPipeType();
6297 }
6298
6299 inline bool Type::isTemplateTypeParmType() const {
6300   return isa<TemplateTypeParmType>(CanonicalType);
6301 }
6302
6303 inline bool Type::isSpecificBuiltinType(unsigned K) const {
6304   if (const BuiltinType *BT = getAs<BuiltinType>())
6305     if (BT->getKind() == (BuiltinType::Kind) K)
6306       return true;
6307   return false;
6308 }
6309
6310 inline bool Type::isPlaceholderType() const {
6311   if (const auto *BT = dyn_cast<BuiltinType>(this))
6312     return BT->isPlaceholderType();
6313   return false;
6314 }
6315
6316 inline const BuiltinType *Type::getAsPlaceholderType() const {
6317   if (const auto *BT = dyn_cast<BuiltinType>(this))
6318     if (BT->isPlaceholderType())
6319       return BT;
6320   return nullptr;
6321 }
6322
6323 inline bool Type::isSpecificPlaceholderType(unsigned K) const {
6324   assert(BuiltinType::isPlaceholderTypeKind((BuiltinType::Kind) K));
6325   if (const auto *BT = dyn_cast<BuiltinType>(this))
6326     return (BT->getKind() == (BuiltinType::Kind) K);
6327   return false;
6328 }
6329
6330 inline bool Type::isNonOverloadPlaceholderType() const {
6331   if (const auto *BT = dyn_cast<BuiltinType>(this))
6332     return BT->isNonOverloadPlaceholderType();
6333   return false;
6334 }
6335
6336 inline bool Type::isVoidType() const {
6337   if (const auto *BT = dyn_cast<BuiltinType>(CanonicalType))
6338     return BT->getKind() == BuiltinType::Void;
6339   return false;
6340 }
6341
6342 inline bool Type::isHalfType() const {
6343   if (const auto *BT = dyn_cast<BuiltinType>(CanonicalType))
6344     return BT->getKind() == BuiltinType::Half;
6345   // FIXME: Should we allow complex __fp16? Probably not.
6346   return false;
6347 }
6348
6349 inline bool Type::isFloat16Type() const {
6350   if (const auto *BT = dyn_cast<BuiltinType>(CanonicalType))
6351     return BT->getKind() == BuiltinType::Float16;
6352   return false;
6353 }
6354
6355 inline bool Type::isFloat128Type() const {
6356   if (const auto *BT = dyn_cast<BuiltinType>(CanonicalType))
6357     return BT->getKind() == BuiltinType::Float128;
6358   return false;
6359 }
6360
6361 inline bool Type::isNullPtrType() const {
6362   if (const auto *BT = getAs<BuiltinType>())
6363     return BT->getKind() == BuiltinType::NullPtr;
6364   return false;
6365 }
6366
6367 bool IsEnumDeclComplete(EnumDecl *);
6368 bool IsEnumDeclScoped(EnumDecl *);
6369
6370 inline bool Type::isIntegerType() const {
6371   if (const auto *BT = dyn_cast<BuiltinType>(CanonicalType))
6372     return BT->getKind() >= BuiltinType::Bool &&
6373            BT->getKind() <= BuiltinType::Int128;
6374   if (const EnumType *ET = dyn_cast<EnumType>(CanonicalType)) {
6375     // Incomplete enum types are not treated as integer types.
6376     // FIXME: In C++, enum types are never integer types.
6377     return IsEnumDeclComplete(ET->getDecl()) &&
6378       !IsEnumDeclScoped(ET->getDecl());
6379   }
6380   return false;
6381 }
6382
6383 inline bool Type::isFixedPointType() const {
6384   if (const auto *BT = dyn_cast<BuiltinType>(CanonicalType)) {
6385     return BT->getKind() >= BuiltinType::ShortAccum &&
6386            BT->getKind() <= BuiltinType::SatULongFract;
6387   }
6388   return false;
6389 }
6390
6391 inline bool Type::isSaturatedFixedPointType() const {
6392   if (const auto *BT = dyn_cast<BuiltinType>(CanonicalType)) {
6393     return BT->getKind() >= BuiltinType::SatShortAccum &&
6394            BT->getKind() <= BuiltinType::SatULongFract;
6395   }
6396   return false;
6397 }
6398
6399 inline bool Type::isUnsaturatedFixedPointType() const {
6400   return isFixedPointType() && !isSaturatedFixedPointType();
6401 }
6402
6403 inline bool Type::isSignedFixedPointType() const {
6404   if (const auto *BT = dyn_cast<BuiltinType>(CanonicalType)) {
6405     return ((BT->getKind() >= BuiltinType::ShortAccum &&
6406              BT->getKind() <= BuiltinType::LongAccum) ||
6407             (BT->getKind() >= BuiltinType::ShortFract &&
6408              BT->getKind() <= BuiltinType::LongFract) ||
6409             (BT->getKind() >= BuiltinType::SatShortAccum &&
6410              BT->getKind() <= BuiltinType::SatLongAccum) ||
6411             (BT->getKind() >= BuiltinType::SatShortFract &&
6412              BT->getKind() <= BuiltinType::SatLongFract));
6413   }
6414   return false;
6415 }
6416
6417 inline bool Type::isUnsignedFixedPointType() const {
6418   return isFixedPointType() && !isSignedFixedPointType();
6419 }
6420
6421 inline bool Type::isScalarType() const {
6422   if (const auto *BT = dyn_cast<BuiltinType>(CanonicalType))
6423     return BT->getKind() > BuiltinType::Void &&
6424            BT->getKind() <= BuiltinType::NullPtr;
6425   if (const EnumType *ET = dyn_cast<EnumType>(CanonicalType))
6426     // Enums are scalar types, but only if they are defined.  Incomplete enums
6427     // are not treated as scalar types.
6428     return IsEnumDeclComplete(ET->getDecl());
6429   return isa<PointerType>(CanonicalType) ||
6430          isa<BlockPointerType>(CanonicalType) ||
6431          isa<MemberPointerType>(CanonicalType) ||
6432          isa<ComplexType>(CanonicalType) ||
6433          isa<ObjCObjectPointerType>(CanonicalType);
6434 }
6435
6436 inline bool Type::isIntegralOrEnumerationType() const {
6437   if (const auto *BT = dyn_cast<BuiltinType>(CanonicalType))
6438     return BT->getKind() >= BuiltinType::Bool &&
6439            BT->getKind() <= BuiltinType::Int128;
6440
6441   // Check for a complete enum type; incomplete enum types are not properly an
6442   // enumeration type in the sense required here.
6443   if (const auto *ET = dyn_cast<EnumType>(CanonicalType))
6444     return IsEnumDeclComplete(ET->getDecl());
6445
6446   return false;  
6447 }
6448
6449 inline bool Type::isBooleanType() const {
6450   if (const auto *BT = dyn_cast<BuiltinType>(CanonicalType))
6451     return BT->getKind() == BuiltinType::Bool;
6452   return false;
6453 }
6454
6455 inline bool Type::isUndeducedType() const {
6456   auto *DT = getContainedDeducedType();
6457   return DT && !DT->isDeduced();
6458 }
6459
6460 /// Determines whether this is a type for which one can define
6461 /// an overloaded operator.
6462 inline bool Type::isOverloadableType() const {
6463   return isDependentType() || isRecordType() || isEnumeralType();
6464 }
6465
6466 /// Determines whether this type can decay to a pointer type.
6467 inline bool Type::canDecayToPointerType() const {
6468   return isFunctionType() || isArrayType();
6469 }
6470
6471 inline bool Type::hasPointerRepresentation() const {
6472   return (isPointerType() || isReferenceType() || isBlockPointerType() ||
6473           isObjCObjectPointerType() || isNullPtrType());
6474 }
6475
6476 inline bool Type::hasObjCPointerRepresentation() const {
6477   return isObjCObjectPointerType();
6478 }
6479
6480 inline const Type *Type::getBaseElementTypeUnsafe() const {
6481   const Type *type = this;
6482   while (const ArrayType *arrayType = type->getAsArrayTypeUnsafe())
6483     type = arrayType->getElementType().getTypePtr();
6484   return type;
6485 }
6486
6487 inline const Type *Type::getPointeeOrArrayElementType() const {
6488   const Type *type = this;
6489   if (type->isAnyPointerType())
6490     return type->getPointeeType().getTypePtr();
6491   else if (type->isArrayType())
6492     return type->getBaseElementTypeUnsafe();
6493   return type;
6494 }
6495
6496 /// Insertion operator for diagnostics.  This allows sending QualType's into a
6497 /// diagnostic with <<.
6498 inline const DiagnosticBuilder &operator<<(const DiagnosticBuilder &DB,
6499                                            QualType T) {
6500   DB.AddTaggedVal(reinterpret_cast<intptr_t>(T.getAsOpaquePtr()),
6501                   DiagnosticsEngine::ak_qualtype);
6502   return DB;
6503 }
6504
6505 /// Insertion operator for partial diagnostics.  This allows sending QualType's
6506 /// into a diagnostic with <<.
6507 inline const PartialDiagnostic &operator<<(const PartialDiagnostic &PD,
6508                                            QualType T) {
6509   PD.AddTaggedVal(reinterpret_cast<intptr_t>(T.getAsOpaquePtr()),
6510                   DiagnosticsEngine::ak_qualtype);
6511   return PD;
6512 }
6513
6514 // Helper class template that is used by Type::getAs to ensure that one does
6515 // not try to look through a qualified type to get to an array type.
6516 template <typename T>
6517 using TypeIsArrayType =
6518     std::integral_constant<bool, std::is_same<T, ArrayType>::value ||
6519                                      std::is_base_of<ArrayType, T>::value>;
6520
6521 // Member-template getAs<specific type>'.
6522 template <typename T> const T *Type::getAs() const {
6523   static_assert(!TypeIsArrayType<T>::value,
6524                 "ArrayType cannot be used with getAs!");
6525
6526   // If this is directly a T type, return it.
6527   if (const auto *Ty = dyn_cast<T>(this))
6528     return Ty;
6529
6530   // If the canonical form of this type isn't the right kind, reject it.
6531   if (!isa<T>(CanonicalType))
6532     return nullptr;
6533
6534   // If this is a typedef for the type, strip the typedef off without
6535   // losing all typedef information.
6536   return cast<T>(getUnqualifiedDesugaredType());
6537 }
6538
6539 template <typename T> const T *Type::getAsAdjusted() const {
6540   static_assert(!TypeIsArrayType<T>::value, "ArrayType cannot be used with getAsAdjusted!");
6541
6542   // If this is directly a T type, return it.
6543   if (const auto *Ty = dyn_cast<T>(this))
6544     return Ty;
6545
6546   // If the canonical form of this type isn't the right kind, reject it.
6547   if (!isa<T>(CanonicalType))
6548     return nullptr;
6549
6550   // Strip off type adjustments that do not modify the underlying nature of the
6551   // type.
6552   const Type *Ty = this;
6553   while (Ty) {
6554     if (const auto *A = dyn_cast<AttributedType>(Ty))
6555       Ty = A->getModifiedType().getTypePtr();
6556     else if (const auto *E = dyn_cast<ElaboratedType>(Ty))
6557       Ty = E->desugar().getTypePtr();
6558     else if (const auto *P = dyn_cast<ParenType>(Ty))
6559       Ty = P->desugar().getTypePtr();
6560     else if (const auto *A = dyn_cast<AdjustedType>(Ty))
6561       Ty = A->desugar().getTypePtr();
6562     else
6563       break;
6564   }
6565
6566   // Just because the canonical type is correct does not mean we can use cast<>,
6567   // since we may not have stripped off all the sugar down to the base type.
6568   return dyn_cast<T>(Ty);
6569 }
6570
6571 inline const ArrayType *Type::getAsArrayTypeUnsafe() const {
6572   // If this is directly an array type, return it.
6573   if (const auto *arr = dyn_cast<ArrayType>(this))
6574     return arr;
6575
6576   // If the canonical form of this type isn't the right kind, reject it.
6577   if (!isa<ArrayType>(CanonicalType))
6578     return nullptr;
6579
6580   // If this is a typedef for the type, strip the typedef off without
6581   // losing all typedef information.
6582   return cast<ArrayType>(getUnqualifiedDesugaredType());
6583 }
6584
6585 template <typename T> const T *Type::castAs() const {
6586   static_assert(!TypeIsArrayType<T>::value,
6587                 "ArrayType cannot be used with castAs!");
6588
6589   if (const auto *ty = dyn_cast<T>(this)) return ty;
6590   assert(isa<T>(CanonicalType));
6591   return cast<T>(getUnqualifiedDesugaredType());
6592 }
6593
6594 inline const ArrayType *Type::castAsArrayTypeUnsafe() const {
6595   assert(isa<ArrayType>(CanonicalType));
6596   if (const auto *arr = dyn_cast<ArrayType>(this)) return arr;
6597   return cast<ArrayType>(getUnqualifiedDesugaredType());
6598 }
6599
6600 DecayedType::DecayedType(QualType OriginalType, QualType DecayedPtr,
6601                          QualType CanonicalPtr)
6602     : AdjustedType(Decayed, OriginalType, DecayedPtr, CanonicalPtr) {
6603 #ifndef NDEBUG
6604   QualType Adjusted = getAdjustedType();
6605   (void)AttributedType::stripOuterNullability(Adjusted);
6606   assert(isa<PointerType>(Adjusted));
6607 #endif
6608 }
6609
6610 QualType DecayedType::getPointeeType() const {
6611   QualType Decayed = getDecayedType();
6612   (void)AttributedType::stripOuterNullability(Decayed);
6613   return cast<PointerType>(Decayed)->getPointeeType();
6614 }
6615
6616 // Get the decimal string representation of a fixed point type, represented
6617 // as a scaled integer.
6618 void FixedPointValueToString(SmallVectorImpl<char> &Str,
6619                              const llvm::APSInt &Val,
6620                              unsigned Scale, unsigned Radix);
6621
6622 } // namespace clang
6623
6624 #endif // LLVM_CLANG_AST_TYPE_H