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