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