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