clang 19.0.0git
Type.h
Go to the documentation of this file.
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
27#include "clang/Basic/LLVM.h"
29#include "clang/Basic/Linkage.h"
35#include "llvm/ADT/APInt.h"
36#include "llvm/ADT/APSInt.h"
37#include "llvm/ADT/ArrayRef.h"
38#include "llvm/ADT/FoldingSet.h"
39#include "llvm/ADT/PointerIntPair.h"
40#include "llvm/ADT/PointerUnion.h"
41#include "llvm/ADT/STLForwardCompat.h"
42#include "llvm/ADT/StringRef.h"
43#include "llvm/ADT/Twine.h"
44#include "llvm/ADT/iterator_range.h"
45#include "llvm/Support/Casting.h"
46#include "llvm/Support/Compiler.h"
47#include "llvm/Support/ErrorHandling.h"
48#include "llvm/Support/PointerLikeTypeTraits.h"
49#include "llvm/Support/TrailingObjects.h"
50#include "llvm/Support/type_traits.h"
51#include <cassert>
52#include <cstddef>
53#include <cstdint>
54#include <cstring>
55#include <optional>
56#include <string>
57#include <type_traits>
58#include <utility>
59
60namespace clang {
61
62class BTFTypeTagAttr;
63class ExtQuals;
64class QualType;
65class ConceptDecl;
66class ValueDecl;
67class TagDecl;
68class TemplateParameterList;
69class Type;
70
71enum {
74};
75
76namespace serialization {
77 template <class T> class AbstractTypeReader;
78 template <class T> class AbstractTypeWriter;
79}
80
81} // namespace clang
82
83namespace llvm {
84
85 template <typename T>
87 template<>
89 static inline void *getAsVoidPointer(::clang::Type *P) { return P; }
90
91 static inline ::clang::Type *getFromVoidPointer(void *P) {
92 return static_cast< ::clang::Type*>(P);
93 }
94
95 static constexpr int NumLowBitsAvailable = clang::TypeAlignmentInBits;
96 };
97
98 template<>
100 static inline void *getAsVoidPointer(::clang::ExtQuals *P) { return P; }
101
102 static inline ::clang::ExtQuals *getFromVoidPointer(void *P) {
103 return static_cast< ::clang::ExtQuals*>(P);
104 }
105
106 static constexpr int NumLowBitsAvailable = clang::TypeAlignmentInBits;
107 };
108
109} // namespace llvm
110
111namespace clang {
112
113class ASTContext;
114template <typename> class CanQual;
115class CXXRecordDecl;
116class DeclContext;
117class EnumDecl;
118class Expr;
119class ExtQualsTypeCommonBase;
120class FunctionDecl;
121class FunctionEffectSet;
122class IdentifierInfo;
123class NamedDecl;
124class ObjCInterfaceDecl;
125class ObjCProtocolDecl;
126class ObjCTypeParamDecl;
127struct PrintingPolicy;
128class RecordDecl;
129class Stmt;
130class TagDecl;
131class TemplateArgument;
132class TemplateArgumentListInfo;
133class TemplateArgumentLoc;
134class TemplateTypeParmDecl;
135template <typename> class TreeTransform;
136class TypedefNameDecl;
137class UnresolvedUsingTypenameDecl;
138class UsingShadowDecl;
139
140using CanQualType = CanQual<Type>;
141
142// Provide forward declarations for all of the *Type classes.
143#define TYPE(Class, Base) class Class##Type;
144#include "clang/AST/TypeNodes.inc"
145
146/// Pointer-authentication qualifiers.
148 enum : uint32_t {
149 EnabledShift = 0,
150 EnabledBits = 1,
151 EnabledMask = 1 << EnabledShift,
152 AddressDiscriminatedShift = EnabledShift + EnabledBits,
153 AddressDiscriminatedBits = 1,
154 AddressDiscriminatedMask = 1 << AddressDiscriminatedShift,
155 AuthenticationModeShift =
156 AddressDiscriminatedShift + AddressDiscriminatedBits,
157 AuthenticationModeBits = 2,
158 AuthenticationModeMask = ((1 << AuthenticationModeBits) - 1)
159 << AuthenticationModeShift,
160 IsaPointerShift = AuthenticationModeShift + AuthenticationModeBits,
161 IsaPointerBits = 1,
162 IsaPointerMask = ((1 << IsaPointerBits) - 1) << IsaPointerShift,
163 AuthenticatesNullValuesShift = IsaPointerShift + IsaPointerBits,
164 AuthenticatesNullValuesBits = 1,
165 AuthenticatesNullValuesMask = ((1 << AuthenticatesNullValuesBits) - 1)
166 << AuthenticatesNullValuesShift,
167 KeyShift = AuthenticatesNullValuesShift + AuthenticatesNullValuesBits,
168 KeyBits = 10,
169 KeyMask = ((1 << KeyBits) - 1) << KeyShift,
170 DiscriminatorShift = KeyShift + KeyBits,
171 DiscriminatorBits = 16,
172 DiscriminatorMask = ((1u << DiscriminatorBits) - 1) << DiscriminatorShift,
173 };
174
175 // bits: |0 |1 |2..3 |4 |
176 // |Enabled|Address|AuthenticationMode|ISA pointer|
177 // bits: |5 |6..15| 16...31 |
178 // |AuthenticatesNull|Key |Discriminator|
179 uint32_t Data = 0;
180
181 // The following static assertions check that each of the 32 bits is present
182 // exactly in one of the constants.
183 static_assert((EnabledBits + AddressDiscriminatedBits +
184 AuthenticationModeBits + IsaPointerBits +
185 AuthenticatesNullValuesBits + KeyBits + DiscriminatorBits) ==
186 32,
187 "PointerAuthQualifier should be exactly 32 bits");
188 static_assert((EnabledMask + AddressDiscriminatedMask +
189 AuthenticationModeMask + IsaPointerMask +
190 AuthenticatesNullValuesMask + KeyMask + DiscriminatorMask) ==
191 0xFFFFFFFF,
192 "All masks should cover the entire bits");
193 static_assert((EnabledMask ^ AddressDiscriminatedMask ^
194 AuthenticationModeMask ^ IsaPointerMask ^
195 AuthenticatesNullValuesMask ^ KeyMask ^ DiscriminatorMask) ==
196 0xFFFFFFFF,
197 "All masks should cover the entire bits");
198
199 PointerAuthQualifier(unsigned Key, bool IsAddressDiscriminated,
200 unsigned ExtraDiscriminator,
201 PointerAuthenticationMode AuthenticationMode,
202 bool IsIsaPointer, bool AuthenticatesNullValues)
203 : Data(EnabledMask |
204 (IsAddressDiscriminated
205 ? llvm::to_underlying(AddressDiscriminatedMask)
206 : 0) |
207 (Key << KeyShift) |
208 (llvm::to_underlying(AuthenticationMode)
209 << AuthenticationModeShift) |
210 (ExtraDiscriminator << DiscriminatorShift) |
211 (IsIsaPointer << IsaPointerShift) |
212 (AuthenticatesNullValues << AuthenticatesNullValuesShift)) {
213 assert(Key <= KeyNoneInternal);
214 assert(ExtraDiscriminator <= MaxDiscriminator);
215 assert((Data == 0) ==
217 }
218
219public:
220 enum {
221 KeyNoneInternal = (1u << KeyBits) - 1,
222
223 /// The maximum supported pointer-authentication key.
225
226 /// The maximum supported pointer-authentication discriminator.
227 MaxDiscriminator = (1u << DiscriminatorBits) - 1
228 };
229
230public:
232
234 Create(unsigned Key, bool IsAddressDiscriminated, unsigned ExtraDiscriminator,
235 PointerAuthenticationMode AuthenticationMode, bool IsIsaPointer,
236 bool AuthenticatesNullValues) {
237 if (Key == PointerAuthKeyNone)
238 Key = KeyNoneInternal;
239 assert(Key <= KeyNoneInternal && "out-of-range key value");
240 return PointerAuthQualifier(Key, IsAddressDiscriminated, ExtraDiscriminator,
241 AuthenticationMode, IsIsaPointer,
242 AuthenticatesNullValues);
243 }
244
245 bool isPresent() const {
246 assert((Data == 0) ==
248 return Data != 0;
249 }
250
251 explicit operator bool() const { return isPresent(); }
252
253 unsigned getKey() const {
254 assert(isPresent());
255 return (Data & KeyMask) >> KeyShift;
256 }
257
258 bool hasKeyNone() const { return isPresent() && getKey() == KeyNoneInternal; }
259
261 assert(isPresent());
262 return (Data & AddressDiscriminatedMask) >> AddressDiscriminatedShift;
263 }
264
265 unsigned getExtraDiscriminator() const {
266 assert(isPresent());
267 return (Data >> DiscriminatorShift);
268 }
269
271 return PointerAuthenticationMode((Data & AuthenticationModeMask) >>
272 AuthenticationModeShift);
273 }
274
275 bool isIsaPointer() const {
276 assert(isPresent());
277 return (Data & IsaPointerMask) >> IsaPointerShift;
278 }
279
281 assert(isPresent());
282 return (Data & AuthenticatesNullValuesMask) >> AuthenticatesNullValuesShift;
283 }
284
286 return hasKeyNone() ? PointerAuthQualifier() : *this;
287 }
288
290 return Lhs.Data == Rhs.Data;
291 }
293 return Lhs.Data != Rhs.Data;
294 }
295
297 return withoutKeyNone() == Other.withoutKeyNone();
298 }
299
300 uint32_t getAsOpaqueValue() const { return Data; }
301
302 // Deserialize pointer-auth qualifiers from an opaque representation.
303 static PointerAuthQualifier fromOpaqueValue(uint32_t Opaque) {
305 Result.Data = Opaque;
306 assert((Result.Data == 0) ==
307 (Result.getAuthenticationMode() == PointerAuthenticationMode::None));
308 return Result;
309 }
310
311 void Profile(llvm::FoldingSetNodeID &ID) const { ID.AddInteger(Data); }
312};
313
314/// The collection of all-type qualifiers we support.
315/// Clang supports five independent qualifiers:
316/// * C99: const, volatile, and restrict
317/// * MS: __unaligned
318/// * Embedded C (TR18037): address spaces
319/// * Objective C: the GC attributes (none, weak, or strong)
321public:
322 enum TQ : uint64_t {
323 // NOTE: These flags must be kept in sync with DeclSpec::TQ.
324 Const = 0x1,
325 Restrict = 0x2,
326 Volatile = 0x4,
328 };
329
330 enum GC {
333 Strong
334 };
335
337 /// There is no lifetime qualification on this type.
339
340 /// This object can be modified without requiring retains or
341 /// releases.
343
344 /// Assigning into this object requires the old value to be
345 /// released and the new value to be retained. The timing of the
346 /// release of the old value is inexact: it may be moved to
347 /// immediately after the last known point where the value is
348 /// live.
350
351 /// Reading or writing from this object requires a barrier call.
353
354 /// Assigning into this object requires a lifetime extension.
356 };
357
358 enum : uint64_t {
359 /// The maximum supported address space number.
360 /// 23 bits should be enough for anyone.
361 MaxAddressSpace = 0x7fffffu,
362
363 /// The width of the "fast" qualifier mask.
365
366 /// The fast qualifier mask.
367 FastMask = (1 << FastWidth) - 1
368 };
369
370 /// Returns the common set of qualifiers while removing them from
371 /// the given sets.
373 Qualifiers Q;
375 if (LPtrAuth.isPresent() &&
377 LPtrAuth == R.getPointerAuth()) {
378 Q.setPointerAuth(LPtrAuth);
382 }
383
384 // If both are only CVR-qualified, bit operations are sufficient.
385 if (!(L.Mask & ~CVRMask) && !(R.Mask & ~CVRMask)) {
386 Q.Mask = L.Mask & R.Mask;
387 L.Mask &= ~Q.Mask;
388 R.Mask &= ~Q.Mask;
389 return Q;
390 }
391
392 unsigned CommonCRV = L.getCVRQualifiers() & R.getCVRQualifiers();
393 Q.addCVRQualifiers(CommonCRV);
394 L.removeCVRQualifiers(CommonCRV);
395 R.removeCVRQualifiers(CommonCRV);
396
397 if (L.getObjCGCAttr() == R.getObjCGCAttr()) {
401 }
402
403 if (L.getObjCLifetime() == R.getObjCLifetime()) {
407 }
408
409 if (L.getAddressSpace() == R.getAddressSpace()) {
413 }
414 return Q;
415 }
416
417 static Qualifiers fromFastMask(unsigned Mask) {
418 Qualifiers Qs;
419 Qs.addFastQualifiers(Mask);
420 return Qs;
421 }
422
423 static Qualifiers fromCVRMask(unsigned CVR) {
424 Qualifiers Qs;
425 Qs.addCVRQualifiers(CVR);
426 return Qs;
427 }
428
429 static Qualifiers fromCVRUMask(unsigned CVRU) {
430 Qualifiers Qs;
431 Qs.addCVRUQualifiers(CVRU);
432 return Qs;
433 }
434
435 // Deserialize qualifiers from an opaque representation.
436 static Qualifiers fromOpaqueValue(uint64_t opaque) {
437 Qualifiers Qs;
438 Qs.Mask = opaque;
439 return Qs;
440 }
441
442 // Serialize these qualifiers into an opaque representation.
443 uint64_t getAsOpaqueValue() const { return Mask; }
444
445 bool hasConst() const { return Mask & Const; }
446 bool hasOnlyConst() const { return Mask == Const; }
447 void removeConst() { Mask &= ~Const; }
448 void addConst() { Mask |= Const; }
450 Qualifiers Qs = *this;
451 Qs.addConst();
452 return Qs;
453 }
454
455 bool hasVolatile() const { return Mask & Volatile; }
456 bool hasOnlyVolatile() const { return Mask == Volatile; }
457 void removeVolatile() { Mask &= ~Volatile; }
458 void addVolatile() { Mask |= Volatile; }
460 Qualifiers Qs = *this;
461 Qs.addVolatile();
462 return Qs;
463 }
464
465 bool hasRestrict() const { return Mask & Restrict; }
466 bool hasOnlyRestrict() const { return Mask == Restrict; }
467 void removeRestrict() { Mask &= ~Restrict; }
468 void addRestrict() { Mask |= Restrict; }
470 Qualifiers Qs = *this;
471 Qs.addRestrict();
472 return Qs;
473 }
474
475 bool hasCVRQualifiers() const { return getCVRQualifiers(); }
476 unsigned getCVRQualifiers() const { return Mask & CVRMask; }
477 unsigned getCVRUQualifiers() const { return Mask & (CVRMask | UMask); }
478
479 void setCVRQualifiers(unsigned mask) {
480 assert(!(mask & ~CVRMask) && "bitmask contains non-CVR bits");
481 Mask = (Mask & ~CVRMask) | mask;
482 }
483 void removeCVRQualifiers(unsigned mask) {
484 assert(!(mask & ~CVRMask) && "bitmask contains non-CVR bits");
485 Mask &= ~static_cast<uint64_t>(mask);
486 }
489 }
490 void addCVRQualifiers(unsigned mask) {
491 assert(!(mask & ~CVRMask) && "bitmask contains non-CVR bits");
492 Mask |= mask;
493 }
494 void addCVRUQualifiers(unsigned mask) {
495 assert(!(mask & ~CVRMask & ~UMask) && "bitmask contains non-CVRU bits");
496 Mask |= mask;
497 }
498
499 bool hasUnaligned() const { return Mask & UMask; }
500 void setUnaligned(bool flag) {
501 Mask = (Mask & ~UMask) | (flag ? UMask : 0);
502 }
503 void removeUnaligned() { Mask &= ~UMask; }
504 void addUnaligned() { Mask |= UMask; }
505
506 bool hasObjCGCAttr() const { return Mask & GCAttrMask; }
507 GC getObjCGCAttr() const { return GC((Mask & GCAttrMask) >> GCAttrShift); }
509 Mask = (Mask & ~GCAttrMask) | (type << GCAttrShift);
510 }
513 assert(type);
515 }
517 Qualifiers qs = *this;
518 qs.removeObjCGCAttr();
519 return qs;
520 }
522 Qualifiers qs = *this;
524 return qs;
525 }
527 Qualifiers qs = *this;
529 return qs;
530 }
531
532 bool hasObjCLifetime() const { return Mask & LifetimeMask; }
534 return ObjCLifetime((Mask & LifetimeMask) >> LifetimeShift);
535 }
537 Mask = (Mask & ~LifetimeMask) | (type << LifetimeShift);
538 }
541 assert(type);
542 assert(!hasObjCLifetime());
543 Mask |= (type << LifetimeShift);
544 }
545
546 /// True if the lifetime is neither None or ExplicitNone.
548 ObjCLifetime lifetime = getObjCLifetime();
549 return (lifetime > OCL_ExplicitNone);
550 }
551
552 /// True if the lifetime is either strong or weak.
554 ObjCLifetime lifetime = getObjCLifetime();
555 return (lifetime == OCL_Strong || lifetime == OCL_Weak);
556 }
557
558 bool hasAddressSpace() const { return Mask & AddressSpaceMask; }
560 return static_cast<LangAS>(Mask >> AddressSpaceShift);
561 }
564 }
565 /// Get the address space attribute value to be printed by diagnostics.
567 auto Addr = getAddressSpace();
568 // This function is not supposed to be used with language specific
569 // address spaces. If that happens, the diagnostic message should consider
570 // printing the QualType instead of the address space value.
572 if (Addr != LangAS::Default)
573 return toTargetAddressSpace(Addr);
574 // TODO: The diagnostic messages where Addr may be 0 should be fixed
575 // since it cannot differentiate the situation where 0 denotes the default
576 // address space or user specified __attribute__((address_space(0))).
577 return 0;
578 }
580 assert((unsigned)space <= MaxAddressSpace);
581 Mask = (Mask & ~AddressSpaceMask)
582 | (((uint32_t) space) << AddressSpaceShift);
583 }
586 assert(space != LangAS::Default);
587 setAddressSpace(space);
588 }
589
590 bool hasPointerAuth() const { return Mask & PtrAuthMask; }
592 return PointerAuthQualifier::fromOpaqueValue(Mask >> PtrAuthShift);
593 }
595 Mask = (Mask & ~PtrAuthMask) |
596 (uint64_t(Q.getAsOpaqueValue()) << PtrAuthShift);
597 }
598 void removePointerAuth() { Mask &= ~PtrAuthMask; }
600 assert(Q.isPresent());
602 }
603
604 // Fast qualifiers are those that can be allocated directly
605 // on a QualType object.
606 bool hasFastQualifiers() const { return getFastQualifiers(); }
607 unsigned getFastQualifiers() const { return Mask & FastMask; }
608 void setFastQualifiers(unsigned mask) {
609 assert(!(mask & ~FastMask) && "bitmask contains non-fast qualifier bits");
610 Mask = (Mask & ~FastMask) | mask;
611 }
612 void removeFastQualifiers(unsigned mask) {
613 assert(!(mask & ~FastMask) && "bitmask contains non-fast qualifier bits");
614 Mask &= ~static_cast<uint64_t>(mask);
615 }
618 }
619 void addFastQualifiers(unsigned mask) {
620 assert(!(mask & ~FastMask) && "bitmask contains non-fast qualifier bits");
621 Mask |= mask;
622 }
623
624 /// Return true if the set contains any qualifiers which require an ExtQuals
625 /// node to be allocated.
626 bool hasNonFastQualifiers() const { return Mask & ~FastMask; }
628 Qualifiers Quals = *this;
629 Quals.setFastQualifiers(0);
630 return Quals;
631 }
632
633 /// Return true if the set contains any qualifiers.
634 bool hasQualifiers() const { return Mask; }
635 bool empty() const { return !Mask; }
636
637 /// Add the qualifiers from the given set to this set.
639 // If the other set doesn't have any non-boolean qualifiers, just
640 // bit-or it in.
641 if (!(Q.Mask & ~CVRMask))
642 Mask |= Q.Mask;
643 else {
644 Mask |= (Q.Mask & CVRMask);
645 if (Q.hasAddressSpace())
647 if (Q.hasObjCGCAttr())
649 if (Q.hasObjCLifetime())
651 if (Q.hasPointerAuth())
653 }
654 }
655
656 /// Remove the qualifiers from the given set from this set.
658 // If the other set doesn't have any non-boolean qualifiers, just
659 // bit-and the inverse in.
660 if (!(Q.Mask & ~CVRMask))
661 Mask &= ~Q.Mask;
662 else {
663 Mask &= ~(Q.Mask & CVRMask);
664 if (getObjCGCAttr() == Q.getObjCGCAttr())
666 if (getObjCLifetime() == Q.getObjCLifetime())
668 if (getAddressSpace() == Q.getAddressSpace())
670 if (getPointerAuth() == Q.getPointerAuth())
672 }
673 }
674
675 /// Add the qualifiers from the given set to this set, given that
676 /// they don't conflict.
678 assert(getAddressSpace() == qs.getAddressSpace() ||
679 !hasAddressSpace() || !qs.hasAddressSpace());
680 assert(getObjCGCAttr() == qs.getObjCGCAttr() ||
681 !hasObjCGCAttr() || !qs.hasObjCGCAttr());
682 assert(getObjCLifetime() == qs.getObjCLifetime() ||
683 !hasObjCLifetime() || !qs.hasObjCLifetime());
684 assert(!hasPointerAuth() || !qs.hasPointerAuth() ||
686 Mask |= qs.Mask;
687 }
688
689 /// Returns true if address space A is equal to or a superset of B.
690 /// OpenCL v2.0 defines conversion rules (OpenCLC v2.0 s6.5.5) and notion of
691 /// overlapping address spaces.
692 /// CL1.1 or CL1.2:
693 /// every address space is a superset of itself.
694 /// CL2.0 adds:
695 /// __generic is a superset of any address space except for __constant.
697 // Address spaces must match exactly.
698 return A == B ||
699 // Otherwise in OpenCLC v2.0 s6.5.5: every address space except
700 // for __constant can be used as __generic.
702 // We also define global_device and global_host address spaces,
703 // to distinguish global pointers allocated on host from pointers
704 // allocated on device, which are a subset of __global.
709 // Consider pointer size address spaces to be equivalent to default.
712 // Default is a superset of SYCL address spaces.
713 (A == LangAS::Default &&
717 // In HIP device compilation, any cuda address space is allowed
718 // to implicitly cast into the default address space.
719 (A == LangAS::Default &&
721 B == LangAS::cuda_shared));
722 }
723
724 /// Returns true if the address space in these qualifiers is equal to or
725 /// a superset of the address space in the argument qualifiers.
728 }
729
730 /// Determines if these qualifiers compatibly include another set.
731 /// Generally this answers the question of whether an object with the other
732 /// qualifiers can be safely used as an object with these qualifiers.
733 bool compatiblyIncludes(Qualifiers other) const {
734 return isAddressSpaceSupersetOf(other) &&
735 // ObjC GC qualifiers can match, be added, or be removed, but can't
736 // be changed.
737 (getObjCGCAttr() == other.getObjCGCAttr() || !hasObjCGCAttr() ||
738 !other.hasObjCGCAttr()) &&
739 // Pointer-auth qualifiers must match exactly.
740 getPointerAuth() == other.getPointerAuth() &&
741 // ObjC lifetime qualifiers must match exactly.
742 getObjCLifetime() == other.getObjCLifetime() &&
743 // CVR qualifiers may subset.
744 (((Mask & CVRMask) | (other.Mask & CVRMask)) == (Mask & CVRMask)) &&
745 // U qualifier may superset.
746 (!other.hasUnaligned() || hasUnaligned());
747 }
748
749 /// Determines if these qualifiers compatibly include another set of
750 /// qualifiers from the narrow perspective of Objective-C ARC lifetime.
751 ///
752 /// One set of Objective-C lifetime qualifiers compatibly includes the other
753 /// if the lifetime qualifiers match, or if both are non-__weak and the
754 /// including set also contains the 'const' qualifier, or both are non-__weak
755 /// and one is None (which can only happen in non-ARC modes).
757 if (getObjCLifetime() == other.getObjCLifetime())
758 return true;
759
760 if (getObjCLifetime() == OCL_Weak || other.getObjCLifetime() == OCL_Weak)
761 return false;
762
763 if (getObjCLifetime() == OCL_None || other.getObjCLifetime() == OCL_None)
764 return true;
765
766 return hasConst();
767 }
768
769 /// Determine whether this set of qualifiers is a strict superset of
770 /// another set of qualifiers, not considering qualifier compatibility.
772
773 bool operator==(Qualifiers Other) const { return Mask == Other.Mask; }
774 bool operator!=(Qualifiers Other) const { return Mask != Other.Mask; }
775
776 explicit operator bool() const { return hasQualifiers(); }
777
779 addQualifiers(R);
780 return *this;
781 }
782
783 // Union two qualifier sets. If an enumerated qualifier appears
784 // in both sets, use the one from the right.
786 L += R;
787 return L;
788 }
789
792 return *this;
793 }
794
795 /// Compute the difference between two qualifier sets.
797 L -= R;
798 return L;
799 }
800
801 std::string getAsString() const;
802 std::string getAsString(const PrintingPolicy &Policy) const;
803
804 static std::string getAddrSpaceAsString(LangAS AS);
805
806 bool isEmptyWhenPrinted(const PrintingPolicy &Policy) const;
807 void print(raw_ostream &OS, const PrintingPolicy &Policy,
808 bool appendSpaceIfNonEmpty = false) const;
809
810 void Profile(llvm::FoldingSetNodeID &ID) const { ID.AddInteger(Mask); }
811
812private:
813 // bits: |0 1 2|3|4 .. 5|6 .. 8|9 ... 31|32 ... 63|
814 // |C R V|U|GCAttr|Lifetime|AddressSpace| PtrAuth |
815 uint64_t Mask = 0;
816 static_assert(sizeof(PointerAuthQualifier) == sizeof(uint32_t),
817 "PointerAuthQualifier must be 32 bits");
818
819 static constexpr uint64_t UMask = 0x8;
820 static constexpr uint64_t UShift = 3;
821 static constexpr uint64_t GCAttrMask = 0x30;
822 static constexpr uint64_t GCAttrShift = 4;
823 static constexpr uint64_t LifetimeMask = 0x1C0;
824 static constexpr uint64_t LifetimeShift = 6;
825 static constexpr uint64_t AddressSpaceMask =
826 ~(CVRMask | UMask | GCAttrMask | LifetimeMask);
827 static constexpr uint64_t AddressSpaceShift = 9;
828 static constexpr uint64_t PtrAuthShift = 32;
829 static constexpr uint64_t PtrAuthMask = uint64_t(0xffffffff) << PtrAuthShift;
830};
831
833 Qualifiers Quals;
834 bool HasAtomic;
835
836public:
837 QualifiersAndAtomic() : HasAtomic(false) {}
838 QualifiersAndAtomic(Qualifiers Quals, bool HasAtomic)
839 : Quals(Quals), HasAtomic(HasAtomic) {}
840
841 operator Qualifiers() const { return Quals; }
842
843 bool hasVolatile() const { return Quals.hasVolatile(); }
844 bool hasConst() const { return Quals.hasConst(); }
845 bool hasRestrict() const { return Quals.hasRestrict(); }
846 bool hasAtomic() const { return HasAtomic; }
847
848 void addVolatile() { Quals.addVolatile(); }
849 void addConst() { Quals.addConst(); }
850 void addRestrict() { Quals.addRestrict(); }
851 void addAtomic() { HasAtomic = true; }
852
853 void removeVolatile() { Quals.removeVolatile(); }
854 void removeConst() { Quals.removeConst(); }
855 void removeRestrict() { Quals.removeRestrict(); }
856 void removeAtomic() { HasAtomic = false; }
857
859 return {Quals.withVolatile(), HasAtomic};
860 }
861 QualifiersAndAtomic withConst() { return {Quals.withConst(), HasAtomic}; }
863 return {Quals.withRestrict(), HasAtomic};
864 }
865 QualifiersAndAtomic withAtomic() { return {Quals, true}; }
866
868 Quals += RHS;
869 return *this;
870 }
871};
872
873/// A std::pair-like structure for storing a qualified type split
874/// into its local qualifiers and its locally-unqualified type.
876 /// The locally-unqualified type.
877 const Type *Ty = nullptr;
878
879 /// The local qualifiers.
881
882 SplitQualType() = default;
883 SplitQualType(const Type *ty, Qualifiers qs) : Ty(ty), Quals(qs) {}
884
885 SplitQualType getSingleStepDesugaredType() const; // end of this file
886
887 // Make std::tie work.
888 std::pair<const Type *,Qualifiers> asPair() const {
889 return std::pair<const Type *, Qualifiers>(Ty, Quals);
890 }
891
893 return a.Ty == b.Ty && a.Quals == b.Quals;
894 }
896 return a.Ty != b.Ty || a.Quals != b.Quals;
897 }
898};
899
900/// The kind of type we are substituting Objective-C type arguments into.
901///
902/// The kind of substitution affects the replacement of type parameters when
903/// no concrete type information is provided, e.g., when dealing with an
904/// unspecialized type.
906 /// An ordinary type.
907 Ordinary,
908
909 /// The result type of a method or function.
910 Result,
911
912 /// The parameter type of a method or function.
913 Parameter,
914
915 /// The type of a property.
916 Property,
917
918 /// The superclass of a type.
920};
921
922/// The kind of 'typeof' expression we're after.
923enum class TypeOfKind : uint8_t {
924 Qualified,
926};
927
928/// A (possibly-)qualified type.
929///
930/// For efficiency, we don't store CV-qualified types as nodes on their
931/// own: instead each reference to a type stores the qualifiers. This
932/// greatly reduces the number of nodes we need to allocate for types (for
933/// example we only need one for 'int', 'const int', 'volatile int',
934/// 'const volatile int', etc).
935///
936/// As an added efficiency bonus, instead of making this a pair, we
937/// just store the two bits we care about in the low bits of the
938/// pointer. To handle the packing/unpacking, we make QualType be a
939/// simple wrapper class that acts like a smart pointer. A third bit
940/// indicates whether there are extended qualifiers present, in which
941/// case the pointer points to a special structure.
942class QualType {
943 friend class QualifierCollector;
944
945 // Thankfully, these are efficiently composable.
946 llvm::PointerIntPair<llvm::PointerUnion<const Type *, const ExtQuals *>,
948
949 const ExtQuals *getExtQualsUnsafe() const {
950 return Value.getPointer().get<const ExtQuals*>();
951 }
952
953 const Type *getTypePtrUnsafe() const {
954 return Value.getPointer().get<const Type*>();
955 }
956
957 const ExtQualsTypeCommonBase *getCommonPtr() const {
958 assert(!isNull() && "Cannot retrieve a NULL type pointer");
959 auto CommonPtrVal = reinterpret_cast<uintptr_t>(Value.getOpaqueValue());
960 CommonPtrVal &= ~(uintptr_t)((1 << TypeAlignmentInBits) - 1);
961 return reinterpret_cast<ExtQualsTypeCommonBase*>(CommonPtrVal);
962 }
963
964public:
965 QualType() = default;
966 QualType(const Type *Ptr, unsigned Quals) : Value(Ptr, Quals) {}
967 QualType(const ExtQuals *Ptr, unsigned Quals) : Value(Ptr, Quals) {}
968
969 unsigned getLocalFastQualifiers() const { return Value.getInt(); }
970 void setLocalFastQualifiers(unsigned Quals) { Value.setInt(Quals); }
971
972 bool UseExcessPrecision(const ASTContext &Ctx);
973
974 /// Retrieves a pointer to the underlying (unqualified) type.
975 ///
976 /// This function requires that the type not be NULL. If the type might be
977 /// NULL, use the (slightly less efficient) \c getTypePtrOrNull().
978 const Type *getTypePtr() const;
979
980 const Type *getTypePtrOrNull() const;
981
982 /// Retrieves a pointer to the name of the base type.
984
985 /// Divides a QualType into its unqualified type and a set of local
986 /// qualifiers.
987 SplitQualType split() const;
988
989 void *getAsOpaquePtr() const { return Value.getOpaqueValue(); }
990
991 static QualType getFromOpaquePtr(const void *Ptr) {
992 QualType T;
993 T.Value.setFromOpaqueValue(const_cast<void*>(Ptr));
994 return T;
995 }
996
997 const Type &operator*() const {
998 return *getTypePtr();
999 }
1000
1001 const Type *operator->() const {
1002 return getTypePtr();
1003 }
1004
1005 bool isCanonical() const;
1006 bool isCanonicalAsParam() const;
1007
1008 /// Return true if this QualType doesn't point to a type yet.
1009 bool isNull() const {
1010 return Value.getPointer().isNull();
1011 }
1012
1013 // Determines if a type can form `T&`.
1014 bool isReferenceable() const;
1015
1016 /// Determine whether this particular QualType instance has the
1017 /// "const" qualifier set, without looking through typedefs that may have
1018 /// added "const" at a different level.
1021 }
1022
1023 /// Determine whether this type is const-qualified.
1024 bool isConstQualified() const;
1025
1031 };
1032 /// Determine whether instances of this type can be placed in immutable
1033 /// storage.
1034 /// If ExcludeCtor is true, the duration when the object's constructor runs
1035 /// will not be considered. The caller will need to verify that the object is
1036 /// not written to during its construction. ExcludeDtor works similarly.
1037 std::optional<NonConstantStorageReason>
1038 isNonConstantStorage(const ASTContext &Ctx, bool ExcludeCtor,
1039 bool ExcludeDtor);
1040
1041 bool isConstantStorage(const ASTContext &Ctx, bool ExcludeCtor,
1042 bool ExcludeDtor) {
1043 return !isNonConstantStorage(Ctx, ExcludeCtor, ExcludeDtor);
1044 }
1045
1046 /// Determine whether this particular QualType instance has the
1047 /// "restrict" qualifier set, without looking through typedefs that may have
1048 /// added "restrict" at a different level.
1051 }
1052
1053 /// Determine whether this type is restrict-qualified.
1054 bool isRestrictQualified() const;
1055
1056 /// Determine whether this particular QualType instance has the
1057 /// "volatile" qualifier set, without looking through typedefs that may have
1058 /// added "volatile" at a different level.
1061 }
1062
1063 /// Determine whether this type is volatile-qualified.
1064 bool isVolatileQualified() const;
1065
1066 /// Determine whether this particular QualType instance has any
1067 /// qualifiers, without looking through any typedefs that might add
1068 /// qualifiers at a different level.
1069 bool hasLocalQualifiers() const {
1071 }
1072
1073 /// Determine whether this type has any qualifiers.
1074 bool hasQualifiers() const;
1075
1076 /// Determine whether this particular QualType instance has any
1077 /// "non-fast" qualifiers, e.g., those that are stored in an ExtQualType
1078 /// instance.
1080 return Value.getPointer().is<const ExtQuals*>();
1081 }
1082
1083 /// Retrieve the set of qualifiers local to this particular QualType
1084 /// instance, not including any qualifiers acquired through typedefs or
1085 /// other sugar.
1087
1088 /// Retrieve the set of qualifiers applied to this type.
1089 Qualifiers getQualifiers() const;
1090
1091 /// Retrieve the set of CVR (const-volatile-restrict) qualifiers
1092 /// local to this particular QualType instance, not including any qualifiers
1093 /// acquired through typedefs or other sugar.
1094 unsigned getLocalCVRQualifiers() const {
1095 return getLocalFastQualifiers();
1096 }
1097
1098 /// Retrieve the set of CVR (const-volatile-restrict) qualifiers
1099 /// applied to this type.
1100 unsigned getCVRQualifiers() const;
1101
1102 bool isConstant(const ASTContext& Ctx) const {
1103 return QualType::isConstant(*this, Ctx);
1104 }
1105
1106 /// Determine whether this is a Plain Old Data (POD) type (C++ 3.9p10).
1107 bool isPODType(const ASTContext &Context) const;
1108
1109 /// Return true if this is a POD type according to the rules of the C++98
1110 /// standard, regardless of the current compilation's language.
1111 bool isCXX98PODType(const ASTContext &Context) const;
1112
1113 /// Return true if this is a POD type according to the more relaxed rules
1114 /// of the C++11 standard, regardless of the current compilation's language.
1115 /// (C++0x [basic.types]p9). Note that, unlike
1116 /// CXXRecordDecl::isCXX11StandardLayout, this takes DRs into account.
1117 bool isCXX11PODType(const ASTContext &Context) const;
1118
1119 /// Return true if this is a trivial type per (C++0x [basic.types]p9)
1120 bool isTrivialType(const ASTContext &Context) const;
1121
1122 /// Return true if this is a trivially copyable type (C++0x [basic.types]p9)
1123 bool isTriviallyCopyableType(const ASTContext &Context) const;
1124
1125 /// Return true if the type is safe to bitwise copy using memcpy/memmove.
1126 ///
1127 /// This is an extension in clang: bitwise cloneable types act as trivially
1128 /// copyable types, meaning their underlying bytes can be safely copied by
1129 /// memcpy or memmove. After the copy, the destination object has the same
1130 /// object representation.
1131 ///
1132 /// However, there are cases where it is not safe to copy:
1133 /// - When sanitizers, such as AddressSanitizer, add padding with poison,
1134 /// which can cause issues if those poisoned padding bits are accessed.
1135 /// - Types with Objective-C lifetimes, where specific runtime
1136 /// semantics may not be preserved during a bitwise copy.
1137 bool isBitwiseCloneableType(const ASTContext &Context) const;
1138
1139 /// Return true if this is a trivially copyable type
1140 bool isTriviallyCopyConstructibleType(const ASTContext &Context) const;
1141
1142 /// Return true if this is a trivially relocatable type.
1143 bool isTriviallyRelocatableType(const ASTContext &Context) const;
1144
1145 /// Returns true if it is a class and it might be dynamic.
1146 bool mayBeDynamicClass() const;
1147
1148 /// Returns true if it is not a class or if the class might not be dynamic.
1149 bool mayBeNotDynamicClass() const;
1150
1151 /// Returns true if it is a WebAssembly Reference Type.
1152 bool isWebAssemblyReferenceType() const;
1153
1154 /// Returns true if it is a WebAssembly Externref Type.
1155 bool isWebAssemblyExternrefType() const;
1156
1157 /// Returns true if it is a WebAssembly Funcref Type.
1158 bool isWebAssemblyFuncrefType() const;
1159
1160 // Don't promise in the API that anything besides 'const' can be
1161 // easily added.
1162
1163 /// Add the `const` type qualifier to this QualType.
1164 void addConst() {
1166 }
1169 }
1170
1171 /// Add the `volatile` type qualifier to this QualType.
1174 }
1177 }
1178
1179 /// Add the `restrict` qualifier to this QualType.
1182 }
1185 }
1186
1187 QualType withCVRQualifiers(unsigned CVR) const {
1188 return withFastQualifiers(CVR);
1189 }
1190
1191 void addFastQualifiers(unsigned TQs) {
1192 assert(!(TQs & ~Qualifiers::FastMask)
1193 && "non-fast qualifier bits set in mask!");
1194 Value.setInt(Value.getInt() | TQs);
1195 }
1196
1197 void removeLocalConst();
1198 void removeLocalVolatile();
1199 void removeLocalRestrict();
1200
1201 void removeLocalFastQualifiers() { Value.setInt(0); }
1202 void removeLocalFastQualifiers(unsigned Mask) {
1203 assert(!(Mask & ~Qualifiers::FastMask) && "mask has non-fast qualifiers");
1204 Value.setInt(Value.getInt() & ~Mask);
1205 }
1206
1207 // Creates a type with the given qualifiers in addition to any
1208 // qualifiers already on this type.
1209 QualType withFastQualifiers(unsigned TQs) const {
1210 QualType T = *this;
1211 T.addFastQualifiers(TQs);
1212 return T;
1213 }
1214
1215 // Creates a type with exactly the given fast qualifiers, removing
1216 // any existing fast qualifiers.
1219 }
1220
1221 // Removes fast qualifiers, but leaves any extended qualifiers in place.
1223 QualType T = *this;
1224 T.removeLocalFastQualifiers();
1225 return T;
1226 }
1227
1228 QualType getCanonicalType() const;
1229
1230 /// Return this type with all of the instance-specific qualifiers
1231 /// removed, but without removing any qualifiers that may have been applied
1232 /// through typedefs.
1234
1235 /// Retrieve the unqualified variant of the given type,
1236 /// removing as little sugar as possible.
1237 ///
1238 /// This routine looks through various kinds of sugar to find the
1239 /// least-desugared type that is unqualified. For example, given:
1240 ///
1241 /// \code
1242 /// typedef int Integer;
1243 /// typedef const Integer CInteger;
1244 /// typedef CInteger DifferenceType;
1245 /// \endcode
1246 ///
1247 /// Executing \c getUnqualifiedType() on the type \c DifferenceType will
1248 /// desugar until we hit the type \c Integer, which has no qualifiers on it.
1249 ///
1250 /// The resulting type might still be qualified if it's sugar for an array
1251 /// type. To strip qualifiers even from within a sugared array type, use
1252 /// ASTContext::getUnqualifiedArrayType.
1253 ///
1254 /// Note: In C, the _Atomic qualifier is special (see C23 6.2.5p32 for
1255 /// details), and it is not stripped by this function. Use
1256 /// getAtomicUnqualifiedType() to strip qualifiers including _Atomic.
1257 inline QualType getUnqualifiedType() const;
1258
1259 /// Retrieve the unqualified variant of the given type, removing as little
1260 /// sugar as possible.
1261 ///
1262 /// Like getUnqualifiedType(), but also returns the set of
1263 /// qualifiers that were built up.
1264 ///
1265 /// The resulting type might still be qualified if it's sugar for an array
1266 /// type. To strip qualifiers even from within a sugared array type, use
1267 /// ASTContext::getUnqualifiedArrayType.
1269
1270 /// Determine whether this type is more qualified than the other
1271 /// given type, requiring exact equality for non-CVR qualifiers.
1273
1274 /// Determine whether this type is at least as qualified as the other
1275 /// given type, requiring exact equality for non-CVR qualifiers.
1277
1279
1280 /// Determine the type of a (typically non-lvalue) expression with the
1281 /// specified result type.
1282 ///
1283 /// This routine should be used for expressions for which the return type is
1284 /// explicitly specified (e.g., in a cast or call) and isn't necessarily
1285 /// an lvalue. It removes a top-level reference (since there are no
1286 /// expressions of reference type) and deletes top-level cvr-qualifiers
1287 /// from non-class types (in C++) or all types (in C).
1288 QualType getNonLValueExprType(const ASTContext &Context) const;
1289
1290 /// Remove an outer pack expansion type (if any) from this type. Used as part
1291 /// of converting the type of a declaration to the type of an expression that
1292 /// references that expression. It's meaningless for an expression to have a
1293 /// pack expansion type.
1295
1296 /// Return the specified type with any "sugar" removed from
1297 /// the type. This takes off typedefs, typeof's etc. If the outer level of
1298 /// the type is already concrete, it returns it unmodified. This is similar
1299 /// to getting the canonical type, but it doesn't remove *all* typedefs. For
1300 /// example, it returns "T*" as "T*", (not as "int*"), because the pointer is
1301 /// concrete.
1302 ///
1303 /// Qualifiers are left in place.
1304 QualType getDesugaredType(const ASTContext &Context) const {
1305 return getDesugaredType(*this, Context);
1306 }
1307
1309 return getSplitDesugaredType(*this);
1310 }
1311
1312 /// Return the specified type with one level of "sugar" removed from
1313 /// the type.
1314 ///
1315 /// This routine takes off the first typedef, typeof, etc. If the outer level
1316 /// of the type is already concrete, it returns it unmodified.
1318 return getSingleStepDesugaredTypeImpl(*this, Context);
1319 }
1320
1321 /// Returns the specified type after dropping any
1322 /// outer-level parentheses.
1324 if (isa<ParenType>(*this))
1325 return QualType::IgnoreParens(*this);
1326 return *this;
1327 }
1328
1329 /// Indicate whether the specified types and qualifiers are identical.
1330 friend bool operator==(const QualType &LHS, const QualType &RHS) {
1331 return LHS.Value == RHS.Value;
1332 }
1333 friend bool operator!=(const QualType &LHS, const QualType &RHS) {
1334 return LHS.Value != RHS.Value;
1335 }
1336 friend bool operator<(const QualType &LHS, const QualType &RHS) {
1337 return LHS.Value < RHS.Value;
1338 }
1339
1340 static std::string getAsString(SplitQualType split,
1341 const PrintingPolicy &Policy) {
1342 return getAsString(split.Ty, split.Quals, Policy);
1343 }
1344 static std::string getAsString(const Type *ty, Qualifiers qs,
1345 const PrintingPolicy &Policy);
1346
1347 std::string getAsString() const;
1348 std::string getAsString(const PrintingPolicy &Policy) const;
1349
1350 void print(raw_ostream &OS, const PrintingPolicy &Policy,
1351 const Twine &PlaceHolder = Twine(),
1352 unsigned Indentation = 0) const;
1353
1354 static void print(SplitQualType split, raw_ostream &OS,
1355 const PrintingPolicy &policy, const Twine &PlaceHolder,
1356 unsigned Indentation = 0) {
1357 return print(split.Ty, split.Quals, OS, policy, PlaceHolder, Indentation);
1358 }
1359
1360 static void print(const Type *ty, Qualifiers qs,
1361 raw_ostream &OS, const PrintingPolicy &policy,
1362 const Twine &PlaceHolder,
1363 unsigned Indentation = 0);
1364
1365 void getAsStringInternal(std::string &Str,
1366 const PrintingPolicy &Policy) const;
1367
1368 static void getAsStringInternal(SplitQualType split, std::string &out,
1369 const PrintingPolicy &policy) {
1370 return getAsStringInternal(split.Ty, split.Quals, out, policy);
1371 }
1372
1373 static void getAsStringInternal(const Type *ty, Qualifiers qs,
1374 std::string &out,
1375 const PrintingPolicy &policy);
1376
1378 const QualType &T;
1379 const PrintingPolicy &Policy;
1380 const Twine &PlaceHolder;
1381 unsigned Indentation;
1382
1383 public:
1385 const Twine &PlaceHolder, unsigned Indentation)
1386 : T(T), Policy(Policy), PlaceHolder(PlaceHolder),
1387 Indentation(Indentation) {}
1388
1389 friend raw_ostream &operator<<(raw_ostream &OS,
1390 const StreamedQualTypeHelper &SQT) {
1391 SQT.T.print(OS, SQT.Policy, SQT.PlaceHolder, SQT.Indentation);
1392 return OS;
1393 }
1394 };
1395
1397 const Twine &PlaceHolder = Twine(),
1398 unsigned Indentation = 0) const {
1399 return StreamedQualTypeHelper(*this, Policy, PlaceHolder, Indentation);
1400 }
1401
1402 void dump(const char *s) const;
1403 void dump() const;
1404 void dump(llvm::raw_ostream &OS, const ASTContext &Context) const;
1405
1406 void Profile(llvm::FoldingSetNodeID &ID) const {
1407 ID.AddPointer(getAsOpaquePtr());
1408 }
1409
1410 /// Check if this type has any address space qualifier.
1411 inline bool hasAddressSpace() const;
1412
1413 /// Return the address space of this type.
1414 inline LangAS getAddressSpace() const;
1415
1416 /// Returns true if address space qualifiers overlap with T address space
1417 /// qualifiers.
1418 /// OpenCL C defines conversion rules for pointers to different address spaces
1419 /// and notion of overlapping address spaces.
1420 /// CL1.1 or CL1.2:
1421 /// address spaces overlap iff they are they same.
1422 /// OpenCL C v2.0 s6.5.5 adds:
1423 /// __generic overlaps with any address space except for __constant.
1426 Qualifiers TQ = T.getQualifiers();
1427 // Address spaces overlap if at least one of them is a superset of another
1429 }
1430
1431 /// Returns gc attribute of this type.
1432 inline Qualifiers::GC getObjCGCAttr() const;
1433
1434 /// true when Type is objc's weak.
1435 bool isObjCGCWeak() const {
1436 return getObjCGCAttr() == Qualifiers::Weak;
1437 }
1438
1439 /// true when Type is objc's strong.
1440 bool isObjCGCStrong() const {
1442 }
1443
1444 /// Returns lifetime attribute of this type.
1446 return getQualifiers().getObjCLifetime();
1447 }
1448
1451 }
1452
1455 }
1456
1457 // true when Type is objc's weak and weak is enabled but ARC isn't.
1458 bool isNonWeakInMRRWithObjCWeak(const ASTContext &Context) const;
1459
1461 return getQualifiers().getPointerAuth();
1462 }
1463
1465 /// The type does not fall into any of the following categories. Note that
1466 /// this case is zero-valued so that values of this enum can be used as a
1467 /// boolean condition for non-triviality.
1469
1470 /// The type is an Objective-C retainable pointer type that is qualified
1471 /// with the ARC __strong qualifier.
1473
1474 /// The type is an Objective-C retainable pointer type that is qualified
1475 /// with the ARC __weak qualifier.
1477
1478 /// The type is a struct containing a field whose type is not PCK_Trivial.
1481
1482 /// Functions to query basic properties of non-trivial C struct types.
1483
1484 /// Check if this is a non-trivial type that would cause a C struct
1485 /// transitively containing this type to be non-trivial to default initialize
1486 /// and return the kind.
1489
1491 /// The type does not fall into any of the following categories. Note that
1492 /// this case is zero-valued so that values of this enum can be used as a
1493 /// boolean condition for non-triviality.
1495
1496 /// The type would be trivial except that it is volatile-qualified. Types
1497 /// that fall into one of the other non-trivial cases may additionally be
1498 /// volatile-qualified.
1500
1501 /// The type is an Objective-C retainable pointer type that is qualified
1502 /// with the ARC __strong qualifier.
1504
1505 /// The type is an Objective-C retainable pointer type that is qualified
1506 /// with the ARC __weak qualifier.
1508
1509 /// The type is a struct containing a field whose type is neither
1510 /// PCK_Trivial nor PCK_VolatileTrivial.
1511 /// Note that a C++ struct type does not necessarily match this; C++ copying
1512 /// semantics are too complex to express here, in part because they depend
1513 /// on the exact constructor or assignment operator that is chosen by
1514 /// overload resolution to do the copy.
1517
1518 /// Check if this is a non-trivial type that would cause a C struct
1519 /// transitively containing this type to be non-trivial to copy and return the
1520 /// kind.
1522
1523 /// Check if this is a non-trivial type that would cause a C struct
1524 /// transitively containing this type to be non-trivial to destructively
1525 /// move and return the kind. Destructive move in this context is a C++-style
1526 /// move in which the source object is placed in a valid but unspecified state
1527 /// after it is moved, as opposed to a truly destructive move in which the
1528 /// source object is placed in an uninitialized state.
1530
1538
1539 /// Returns a nonzero value if objects of this type require
1540 /// non-trivial work to clean up after. Non-zero because it's
1541 /// conceivable that qualifiers (objc_gc(weak)?) could make
1542 /// something require destruction.
1544 return isDestructedTypeImpl(*this);
1545 }
1546
1547 /// Check if this is or contains a C union that is non-trivial to
1548 /// default-initialize, which is a union that has a member that is non-trivial
1549 /// to default-initialize. If this returns true,
1550 /// isNonTrivialToPrimitiveDefaultInitialize returns PDIK_Struct.
1552
1553 /// Check if this is or contains a C union that is non-trivial to destruct,
1554 /// which is a union that has a member that is non-trivial to destruct. If
1555 /// this returns true, isDestructedType returns DK_nontrivial_c_struct.
1557
1558 /// Check if this is or contains a C union that is non-trivial to copy, which
1559 /// is a union that has a member that is non-trivial to copy. If this returns
1560 /// true, isNonTrivialToPrimitiveCopy returns PCK_Struct.
1562
1563 /// Determine whether expressions of the given type are forbidden
1564 /// from being lvalues in C.
1565 ///
1566 /// The expression types that are forbidden to be lvalues are:
1567 /// - 'void', but not qualified void
1568 /// - function types
1569 ///
1570 /// The exact rule here is C99 6.3.2.1:
1571 /// An lvalue is an expression with an object type or an incomplete
1572 /// type other than void.
1573 bool isCForbiddenLValueType() const;
1574
1575 /// Substitute type arguments for the Objective-C type parameters used in the
1576 /// subject type.
1577 ///
1578 /// \param ctx ASTContext in which the type exists.
1579 ///
1580 /// \param typeArgs The type arguments that will be substituted for the
1581 /// Objective-C type parameters in the subject type, which are generally
1582 /// computed via \c Type::getObjCSubstitutions. If empty, the type
1583 /// parameters will be replaced with their bounds or id/Class, as appropriate
1584 /// for the context.
1585 ///
1586 /// \param context The context in which the subject type was written.
1587 ///
1588 /// \returns the resulting type.
1590 ArrayRef<QualType> typeArgs,
1591 ObjCSubstitutionContext context) const;
1592
1593 /// Substitute type arguments from an object type for the Objective-C type
1594 /// parameters used in the subject type.
1595 ///
1596 /// This operation combines the computation of type arguments for
1597 /// substitution (\c Type::getObjCSubstitutions) with the actual process of
1598 /// substitution (\c QualType::substObjCTypeArgs) for the convenience of
1599 /// callers that need to perform a single substitution in isolation.
1600 ///
1601 /// \param objectType The type of the object whose member type we're
1602 /// substituting into. For example, this might be the receiver of a message
1603 /// or the base of a property access.
1604 ///
1605 /// \param dc The declaration context from which the subject type was
1606 /// retrieved, which indicates (for example) which type parameters should
1607 /// be substituted.
1608 ///
1609 /// \param context The context in which the subject type was written.
1610 ///
1611 /// \returns the subject type after replacing all of the Objective-C type
1612 /// parameters with their corresponding arguments.
1614 const DeclContext *dc,
1615 ObjCSubstitutionContext context) const;
1616
1617 /// Strip Objective-C "__kindof" types from the given type.
1618 QualType stripObjCKindOfType(const ASTContext &ctx) const;
1619
1620 /// Remove all qualifiers including _Atomic.
1622
1623private:
1624 // These methods are implemented in a separate translation unit;
1625 // "static"-ize them to avoid creating temporary QualTypes in the
1626 // caller.
1627 static bool isConstant(QualType T, const ASTContext& Ctx);
1628 static QualType getDesugaredType(QualType T, const ASTContext &Context);
1630 static SplitQualType getSplitUnqualifiedTypeImpl(QualType type);
1631 static QualType getSingleStepDesugaredTypeImpl(QualType type,
1632 const ASTContext &C);
1634 static DestructionKind isDestructedTypeImpl(QualType type);
1635
1636 /// Check if \param RD is or contains a non-trivial C union.
1639 static bool hasNonTrivialToPrimitiveCopyCUnion(const RecordDecl *RD);
1640};
1641
1642raw_ostream &operator<<(raw_ostream &OS, QualType QT);
1643
1644} // namespace clang
1645
1646namespace llvm {
1647
1648/// Implement simplify_type for QualType, so that we can dyn_cast from QualType
1649/// to a specific Type class.
1650template<> struct simplify_type< ::clang::QualType> {
1651 using SimpleType = const ::clang::Type *;
1652
1654 return Val.getTypePtr();
1655 }
1656};
1657
1658// Teach SmallPtrSet that QualType is "basically a pointer".
1659template<>
1660struct PointerLikeTypeTraits<clang::QualType> {
1661 static inline void *getAsVoidPointer(clang::QualType P) {
1662 return P.getAsOpaquePtr();
1663 }
1664
1665 static inline clang::QualType getFromVoidPointer(void *P) {
1667 }
1668
1669 // Various qualifiers go in low bits.
1670 static constexpr int NumLowBitsAvailable = 0;
1671};
1672
1673} // namespace llvm
1674
1675namespace clang {
1676
1677/// Base class that is common to both the \c ExtQuals and \c Type
1678/// classes, which allows \c QualType to access the common fields between the
1679/// two.
1681 friend class ExtQuals;
1682 friend class QualType;
1683 friend class Type;
1684
1685 /// The "base" type of an extended qualifiers type (\c ExtQuals) or
1686 /// a self-referential pointer (for \c Type).
1687 ///
1688 /// This pointer allows an efficient mapping from a QualType to its
1689 /// underlying type pointer.
1690 const Type *const BaseType;
1691
1692 /// The canonical type of this type. A QualType.
1693 QualType CanonicalType;
1694
1695 ExtQualsTypeCommonBase(const Type *baseType, QualType canon)
1696 : BaseType(baseType), CanonicalType(canon) {}
1697};
1698
1699/// We can encode up to four bits in the low bits of a
1700/// type pointer, but there are many more type qualifiers that we want
1701/// to be able to apply to an arbitrary type. Therefore we have this
1702/// struct, intended to be heap-allocated and used by QualType to
1703/// store qualifiers.
1704///
1705/// The current design tags the 'const', 'restrict', and 'volatile' qualifiers
1706/// in three low bits on the QualType pointer; a fourth bit records whether
1707/// the pointer is an ExtQuals node. The extended qualifiers (address spaces,
1708/// Objective-C GC attributes) are much more rare.
1709class alignas(TypeAlignment) ExtQuals : public ExtQualsTypeCommonBase,
1710 public llvm::FoldingSetNode {
1711 // NOTE: changing the fast qualifiers should be straightforward as
1712 // long as you don't make 'const' non-fast.
1713 // 1. Qualifiers:
1714 // a) Modify the bitmasks (Qualifiers::TQ and DeclSpec::TQ).
1715 // Fast qualifiers must occupy the low-order bits.
1716 // b) Update Qualifiers::FastWidth and FastMask.
1717 // 2. QualType:
1718 // a) Update is{Volatile,Restrict}Qualified(), defined inline.
1719 // b) Update remove{Volatile,Restrict}, defined near the end of
1720 // this header.
1721 // 3. ASTContext:
1722 // a) Update get{Volatile,Restrict}Type.
1723
1724 /// The immutable set of qualifiers applied by this node. Always contains
1725 /// extended qualifiers.
1726 Qualifiers Quals;
1727
1728 ExtQuals *this_() { return this; }
1729
1730public:
1731 ExtQuals(const Type *baseType, QualType canon, Qualifiers quals)
1732 : ExtQualsTypeCommonBase(baseType,
1733 canon.isNull() ? QualType(this_(), 0) : canon),
1734 Quals(quals) {
1735 assert(Quals.hasNonFastQualifiers()
1736 && "ExtQuals created with no fast qualifiers");
1737 assert(!Quals.hasFastQualifiers()
1738 && "ExtQuals created with fast qualifiers");
1739 }
1740
1741 Qualifiers getQualifiers() const { return Quals; }
1742
1743 bool hasObjCGCAttr() const { return Quals.hasObjCGCAttr(); }
1744 Qualifiers::GC getObjCGCAttr() const { return Quals.getObjCGCAttr(); }
1745
1746 bool hasObjCLifetime() const { return Quals.hasObjCLifetime(); }
1748 return Quals.getObjCLifetime();
1749 }
1750
1751 bool hasAddressSpace() const { return Quals.hasAddressSpace(); }
1752 LangAS getAddressSpace() const { return Quals.getAddressSpace(); }
1753
1754 const Type *getBaseType() const { return BaseType; }
1755
1756public:
1757 void Profile(llvm::FoldingSetNodeID &ID) const {
1758 Profile(ID, getBaseType(), Quals);
1759 }
1760
1761 static void Profile(llvm::FoldingSetNodeID &ID,
1762 const Type *BaseType,
1763 Qualifiers Quals) {
1764 assert(!Quals.hasFastQualifiers() && "fast qualifiers in ExtQuals hash!");
1765 ID.AddPointer(BaseType);
1766 Quals.Profile(ID);
1767 }
1768};
1769
1770/// The kind of C++11 ref-qualifier associated with a function type.
1771/// This determines whether a member function's "this" object can be an
1772/// lvalue, rvalue, or neither.
1774 /// No ref-qualifier was provided.
1776
1777 /// An lvalue ref-qualifier was provided (\c &).
1779
1780 /// An rvalue ref-qualifier was provided (\c &&).
1781 RQ_RValue
1783
1784/// Which keyword(s) were used to create an AutoType.
1786 /// auto
1787 Auto,
1788
1789 /// decltype(auto)
1791
1792 /// __auto_type (GNU extension)
1794};
1795
1796enum class ArraySizeModifier;
1797enum class ElaboratedTypeKeyword;
1798enum class VectorKind;
1799
1800/// The base class of the type hierarchy.
1801///
1802/// A central concept with types is that each type always has a canonical
1803/// type. A canonical type is the type with any typedef names stripped out
1804/// of it or the types it references. For example, consider:
1805///
1806/// typedef int foo;
1807/// typedef foo* bar;
1808/// 'int *' 'foo *' 'bar'
1809///
1810/// There will be a Type object created for 'int'. Since int is canonical, its
1811/// CanonicalType pointer points to itself. There is also a Type for 'foo' (a
1812/// TypedefType). Its CanonicalType pointer points to the 'int' Type. Next
1813/// there is a PointerType that represents 'int*', which, like 'int', is
1814/// canonical. Finally, there is a PointerType type for 'foo*' whose canonical
1815/// type is 'int*', and there is a TypedefType for 'bar', whose canonical type
1816/// is also 'int*'.
1817///
1818/// Non-canonical types are useful for emitting diagnostics, without losing
1819/// information about typedefs being used. Canonical types are useful for type
1820/// comparisons (they allow by-pointer equality tests) and useful for reasoning
1821/// about whether something has a particular form (e.g. is a function type),
1822/// because they implicitly, recursively, strip all typedefs out of a type.
1823///
1824/// Types, once created, are immutable.
1825///
1826class alignas(TypeAlignment) Type : public ExtQualsTypeCommonBase {
1827public:
1829#define TYPE(Class, Base) Class,
1830#define LAST_TYPE(Class) TypeLast = Class
1831#define ABSTRACT_TYPE(Class, Base)
1832#include "clang/AST/TypeNodes.inc"
1833 };
1834
1835private:
1836 /// Bitfields required by the Type class.
1837 class TypeBitfields {
1838 friend class Type;
1839 template <class T> friend class TypePropertyCache;
1840
1841 /// TypeClass bitfield - Enum that specifies what subclass this belongs to.
1842 LLVM_PREFERRED_TYPE(TypeClass)
1843 unsigned TC : 8;
1844
1845 /// Store information on the type dependency.
1846 LLVM_PREFERRED_TYPE(TypeDependence)
1847 unsigned Dependence : llvm::BitWidth<TypeDependence>;
1848
1849 /// True if the cache (i.e. the bitfields here starting with
1850 /// 'Cache') is valid.
1851 LLVM_PREFERRED_TYPE(bool)
1852 mutable unsigned CacheValid : 1;
1853
1854 /// Linkage of this type.
1855 LLVM_PREFERRED_TYPE(Linkage)
1856 mutable unsigned CachedLinkage : 3;
1857
1858 /// Whether this type involves and local or unnamed types.
1859 LLVM_PREFERRED_TYPE(bool)
1860 mutable unsigned CachedLocalOrUnnamed : 1;
1861
1862 /// Whether this type comes from an AST file.
1863 LLVM_PREFERRED_TYPE(bool)
1864 mutable unsigned FromAST : 1;
1865
1866 bool isCacheValid() const {
1867 return CacheValid;
1868 }
1869
1870 Linkage getLinkage() const {
1871 assert(isCacheValid() && "getting linkage from invalid cache");
1872 return static_cast<Linkage>(CachedLinkage);
1873 }
1874
1875 bool hasLocalOrUnnamedType() const {
1876 assert(isCacheValid() && "getting linkage from invalid cache");
1877 return CachedLocalOrUnnamed;
1878 }
1879 };
1880 enum { NumTypeBits = 8 + llvm::BitWidth<TypeDependence> + 6 };
1881
1882protected:
1883 // These classes allow subclasses to somewhat cleanly pack bitfields
1884 // into Type.
1885
1887 friend class ArrayType;
1888
1889 LLVM_PREFERRED_TYPE(TypeBitfields)
1890 unsigned : NumTypeBits;
1891
1892 /// CVR qualifiers from declarations like
1893 /// 'int X[static restrict 4]'. For function parameters only.
1894 LLVM_PREFERRED_TYPE(Qualifiers)
1895 unsigned IndexTypeQuals : 3;
1896
1897 /// Storage class qualifiers from declarations like
1898 /// 'int X[static restrict 4]'. For function parameters only.
1899 LLVM_PREFERRED_TYPE(ArraySizeModifier)
1900 unsigned SizeModifier : 3;
1901 };
1902 enum { NumArrayTypeBits = NumTypeBits + 6 };
1903
1905 friend class ConstantArrayType;
1906
1907 LLVM_PREFERRED_TYPE(ArrayTypeBitfields)
1908 unsigned : NumArrayTypeBits;
1909
1910 /// Whether we have a stored size expression.
1911 LLVM_PREFERRED_TYPE(bool)
1912 unsigned HasExternalSize : 1;
1913
1914 LLVM_PREFERRED_TYPE(unsigned)
1915 unsigned SizeWidth : 5;
1916 };
1917
1919 friend class BuiltinType;
1920
1921 LLVM_PREFERRED_TYPE(TypeBitfields)
1922 unsigned : NumTypeBits;
1923
1924 /// The kind (BuiltinType::Kind) of builtin type this is.
1925 static constexpr unsigned NumOfBuiltinTypeBits = 9;
1926 unsigned Kind : NumOfBuiltinTypeBits;
1927 };
1928
1929 /// FunctionTypeBitfields store various bits belonging to FunctionProtoType.
1930 /// Only common bits are stored here. Additional uncommon bits are stored
1931 /// in a trailing object after FunctionProtoType.
1933 friend class FunctionProtoType;
1934 friend class FunctionType;
1935
1936 LLVM_PREFERRED_TYPE(TypeBitfields)
1937 unsigned : NumTypeBits;
1938
1939 /// Extra information which affects how the function is called, like
1940 /// regparm and the calling convention.
1941 LLVM_PREFERRED_TYPE(CallingConv)
1942 unsigned ExtInfo : 13;
1943
1944 /// The ref-qualifier associated with a \c FunctionProtoType.
1945 ///
1946 /// This is a value of type \c RefQualifierKind.
1947 LLVM_PREFERRED_TYPE(RefQualifierKind)
1948 unsigned RefQualifier : 2;
1949
1950 /// Used only by FunctionProtoType, put here to pack with the
1951 /// other bitfields.
1952 /// The qualifiers are part of FunctionProtoType because...
1953 ///
1954 /// C++ 8.3.5p4: The return type, the parameter type list and the
1955 /// cv-qualifier-seq, [...], are part of the function type.
1956 LLVM_PREFERRED_TYPE(Qualifiers)
1957 unsigned FastTypeQuals : Qualifiers::FastWidth;
1958 /// Whether this function has extended Qualifiers.
1959 LLVM_PREFERRED_TYPE(bool)
1960 unsigned HasExtQuals : 1;
1961
1962 /// The number of parameters this function has, not counting '...'.
1963 /// According to [implimits] 8 bits should be enough here but this is
1964 /// somewhat easy to exceed with metaprogramming and so we would like to
1965 /// keep NumParams as wide as reasonably possible.
1966 unsigned NumParams : 16;
1967
1968 /// The type of exception specification this function has.
1969 LLVM_PREFERRED_TYPE(ExceptionSpecificationType)
1970 unsigned ExceptionSpecType : 4;
1971
1972 /// Whether this function has extended parameter information.
1973 LLVM_PREFERRED_TYPE(bool)
1974 unsigned HasExtParameterInfos : 1;
1975
1976 /// Whether this function has extra bitfields for the prototype.
1977 LLVM_PREFERRED_TYPE(bool)
1978 unsigned HasExtraBitfields : 1;
1979
1980 /// Whether the function is variadic.
1981 LLVM_PREFERRED_TYPE(bool)
1982 unsigned Variadic : 1;
1983
1984 /// Whether this function has a trailing return type.
1985 LLVM_PREFERRED_TYPE(bool)
1986 unsigned HasTrailingReturn : 1;
1987 };
1988
1990 friend class ObjCObjectType;
1991
1992 LLVM_PREFERRED_TYPE(TypeBitfields)
1993 unsigned : NumTypeBits;
1994
1995 /// The number of type arguments stored directly on this object type.
1996 unsigned NumTypeArgs : 7;
1997
1998 /// The number of protocols stored directly on this object type.
1999 unsigned NumProtocols : 6;
2000
2001 /// Whether this is a "kindof" type.
2002 LLVM_PREFERRED_TYPE(bool)
2003 unsigned IsKindOf : 1;
2004 };
2005
2007 friend class ReferenceType;
2008
2009 LLVM_PREFERRED_TYPE(TypeBitfields)
2010 unsigned : NumTypeBits;
2011
2012 /// True if the type was originally spelled with an lvalue sigil.
2013 /// This is never true of rvalue references but can also be false
2014 /// on lvalue references because of C++0x [dcl.typedef]p9,
2015 /// as follows:
2016 ///
2017 /// typedef int &ref; // lvalue, spelled lvalue
2018 /// typedef int &&rvref; // rvalue
2019 /// ref &a; // lvalue, inner ref, spelled lvalue
2020 /// ref &&a; // lvalue, inner ref
2021 /// rvref &a; // lvalue, inner ref, spelled lvalue
2022 /// rvref &&a; // rvalue, inner ref
2023 LLVM_PREFERRED_TYPE(bool)
2024 unsigned SpelledAsLValue : 1;
2025
2026 /// True if the inner type is a reference type. This only happens
2027 /// in non-canonical forms.
2028 LLVM_PREFERRED_TYPE(bool)
2029 unsigned InnerRef : 1;
2030 };
2031
2033 friend class TypeWithKeyword;
2034
2035 LLVM_PREFERRED_TYPE(TypeBitfields)
2036 unsigned : NumTypeBits;
2037
2038 /// An ElaboratedTypeKeyword. 8 bits for efficient access.
2039 LLVM_PREFERRED_TYPE(ElaboratedTypeKeyword)
2040 unsigned Keyword : 8;
2041 };
2042
2043 enum { NumTypeWithKeywordBits = NumTypeBits + 8 };
2044
2046 friend class ElaboratedType;
2047
2048 LLVM_PREFERRED_TYPE(TypeWithKeywordBitfields)
2049 unsigned : NumTypeWithKeywordBits;
2050
2051 /// Whether the ElaboratedType has a trailing OwnedTagDecl.
2052 LLVM_PREFERRED_TYPE(bool)
2053 unsigned HasOwnedTagDecl : 1;
2054 };
2055
2057 friend class VectorType;
2059
2060 LLVM_PREFERRED_TYPE(TypeBitfields)
2061 unsigned : NumTypeBits;
2062
2063 /// The kind of vector, either a generic vector type or some
2064 /// target-specific vector type such as for AltiVec or Neon.
2065 LLVM_PREFERRED_TYPE(VectorKind)
2066 unsigned VecKind : 4;
2067 /// The number of elements in the vector.
2068 uint32_t NumElements;
2069 };
2070
2072 friend class AttributedType;
2073
2074 LLVM_PREFERRED_TYPE(TypeBitfields)
2075 unsigned : NumTypeBits;
2076
2077 LLVM_PREFERRED_TYPE(attr::Kind)
2078 unsigned AttrKind : 32 - NumTypeBits;
2079 };
2080
2082 friend class AutoType;
2083
2084 LLVM_PREFERRED_TYPE(TypeBitfields)
2085 unsigned : NumTypeBits;
2086
2087 /// Was this placeholder type spelled as 'auto', 'decltype(auto)',
2088 /// or '__auto_type'? AutoTypeKeyword value.
2089 LLVM_PREFERRED_TYPE(AutoTypeKeyword)
2090 unsigned Keyword : 2;
2091
2092 /// The number of template arguments in the type-constraints, which is
2093 /// expected to be able to hold at least 1024 according to [implimits].
2094 /// However as this limit is somewhat easy to hit with template
2095 /// metaprogramming we'd prefer to keep it as large as possible.
2096 /// At the moment it has been left as a non-bitfield since this type
2097 /// safely fits in 64 bits as an unsigned, so there is no reason to
2098 /// introduce the performance impact of a bitfield.
2099 unsigned NumArgs;
2100 };
2101
2103 friend class TypeOfType;
2104 friend class TypeOfExprType;
2105
2106 LLVM_PREFERRED_TYPE(TypeBitfields)
2107 unsigned : NumTypeBits;
2108 LLVM_PREFERRED_TYPE(bool)
2109 unsigned IsUnqual : 1; // If true: typeof_unqual, else: typeof
2110 };
2111
2113 friend class UsingType;
2114
2115 LLVM_PREFERRED_TYPE(TypeBitfields)
2116 unsigned : NumTypeBits;
2117
2118 /// True if the underlying type is different from the declared one.
2119 LLVM_PREFERRED_TYPE(bool)
2120 unsigned hasTypeDifferentFromDecl : 1;
2121 };
2122
2124 friend class TypedefType;
2125
2126 LLVM_PREFERRED_TYPE(TypeBitfields)
2127 unsigned : NumTypeBits;
2128
2129 /// True if the underlying type is different from the declared one.
2130 LLVM_PREFERRED_TYPE(bool)
2131 unsigned hasTypeDifferentFromDecl : 1;
2132 };
2133
2136
2137 LLVM_PREFERRED_TYPE(TypeBitfields)
2138 unsigned : NumTypeBits;
2139
2140 LLVM_PREFERRED_TYPE(bool)
2141 unsigned HasNonCanonicalUnderlyingType : 1;
2142
2143 // The index of the template parameter this substitution represents.
2144 unsigned Index : 15;
2145
2146 /// Represents the index within a pack if this represents a substitution
2147 /// from a pack expansion. This index starts at the end of the pack and
2148 /// increments towards the beginning.
2149 /// Positive non-zero number represents the index + 1.
2150 /// Zero means this is not substituted from an expansion.
2151 unsigned PackIndex : 16;
2152 };
2153
2156
2157 LLVM_PREFERRED_TYPE(TypeBitfields)
2158 unsigned : NumTypeBits;
2159
2160 // The index of the template parameter this substitution represents.
2161 unsigned Index : 16;
2162
2163 /// The number of template arguments in \c Arguments, which is
2164 /// expected to be able to hold at least 1024 according to [implimits].
2165 /// However as this limit is somewhat easy to hit with template
2166 /// metaprogramming we'd prefer to keep it as large as possible.
2167 unsigned NumArgs : 16;
2168 };
2169
2172
2173 LLVM_PREFERRED_TYPE(TypeBitfields)
2174 unsigned : NumTypeBits;
2175
2176 /// Whether this template specialization type is a substituted type alias.
2177 LLVM_PREFERRED_TYPE(bool)
2178 unsigned TypeAlias : 1;
2179
2180 /// The number of template arguments named in this class template
2181 /// specialization, which is expected to be able to hold at least 1024
2182 /// according to [implimits]. However, as this limit is somewhat easy to
2183 /// hit with template metaprogramming we'd prefer to keep it as large
2184 /// as possible. At the moment it has been left as a non-bitfield since
2185 /// this type safely fits in 64 bits as an unsigned, so there is no reason
2186 /// to introduce the performance impact of a bitfield.
2187 unsigned NumArgs;
2188 };
2189
2192
2193 LLVM_PREFERRED_TYPE(TypeWithKeywordBitfields)
2194 unsigned : NumTypeWithKeywordBits;
2195
2196 /// The number of template arguments named in this class template
2197 /// specialization, which is expected to be able to hold at least 1024
2198 /// according to [implimits]. However, as this limit is somewhat easy to
2199 /// hit with template metaprogramming we'd prefer to keep it as large
2200 /// as possible. At the moment it has been left as a non-bitfield since
2201 /// this type safely fits in 64 bits as an unsigned, so there is no reason
2202 /// to introduce the performance impact of a bitfield.
2203 unsigned NumArgs;
2204 };
2205
2207 friend class PackExpansionType;
2208
2209 LLVM_PREFERRED_TYPE(TypeBitfields)
2210 unsigned : NumTypeBits;
2211
2212 /// The number of expansions that this pack expansion will
2213 /// generate when substituted (+1), which is expected to be able to
2214 /// hold at least 1024 according to [implimits]. However, as this limit
2215 /// is somewhat easy to hit with template metaprogramming we'd prefer to
2216 /// keep it as large as possible. At the moment it has been left as a
2217 /// non-bitfield since this type safely fits in 64 bits as an unsigned, so
2218 /// there is no reason to introduce the performance impact of a bitfield.
2219 ///
2220 /// This field will only have a non-zero value when some of the parameter
2221 /// packs that occur within the pattern have been substituted but others
2222 /// have not.
2223 unsigned NumExpansions;
2224 };
2225
2228
2229 LLVM_PREFERRED_TYPE(TypeBitfields)
2230 unsigned : NumTypeBits;
2231
2232 static constexpr unsigned NumCoupledDeclsBits = 4;
2233 unsigned NumCoupledDecls : NumCoupledDeclsBits;
2234 LLVM_PREFERRED_TYPE(bool)
2235 unsigned CountInBytes : 1;
2236 LLVM_PREFERRED_TYPE(bool)
2237 unsigned OrNull : 1;
2238 };
2239 static_assert(sizeof(CountAttributedTypeBitfields) <= sizeof(unsigned));
2240
2241 union {
2242 TypeBitfields TypeBits;
2264 };
2265
2266private:
2267 template <class T> friend class TypePropertyCache;
2268
2269 /// Set whether this type comes from an AST file.
2270 void setFromAST(bool V = true) const {
2271 TypeBits.FromAST = V;
2272 }
2273
2274protected:
2275 friend class ASTContext;
2276
2279 canon.isNull() ? QualType(this_(), 0) : canon) {
2280 static_assert(sizeof(*this) <=
2281 alignof(decltype(*this)) + sizeof(ExtQualsTypeCommonBase),
2282 "changing bitfields changed sizeof(Type)!");
2283 static_assert(alignof(decltype(*this)) % TypeAlignment == 0,
2284 "Insufficient alignment!");
2285 TypeBits.TC = tc;
2286 TypeBits.Dependence = static_cast<unsigned>(Dependence);
2287 TypeBits.CacheValid = false;
2288 TypeBits.CachedLocalOrUnnamed = false;
2289 TypeBits.CachedLinkage = llvm::to_underlying(Linkage::Invalid);
2290 TypeBits.FromAST = false;
2291 }
2292
2293 // silence VC++ warning C4355: 'this' : used in base member initializer list
2294 Type *this_() { return this; }
2295
2297 TypeBits.Dependence = static_cast<unsigned>(D);
2298 }
2299
2300 void addDependence(TypeDependence D) { setDependence(getDependence() | D); }
2301
2302public:
2303 friend class ASTReader;
2304 friend class ASTWriter;
2305 template <class T> friend class serialization::AbstractTypeReader;
2306 template <class T> friend class serialization::AbstractTypeWriter;
2307
2308 Type(const Type &) = delete;
2309 Type(Type &&) = delete;
2310 Type &operator=(const Type &) = delete;
2311 Type &operator=(Type &&) = delete;
2312
2313 TypeClass getTypeClass() const { return static_cast<TypeClass>(TypeBits.TC); }
2314
2315 /// Whether this type comes from an AST file.
2316 bool isFromAST() const { return TypeBits.FromAST; }
2317
2318 /// Whether this type is or contains an unexpanded parameter
2319 /// pack, used to support C++0x variadic templates.
2320 ///
2321 /// A type that contains a parameter pack shall be expanded by the
2322 /// ellipsis operator at some point. For example, the typedef in the
2323 /// following example contains an unexpanded parameter pack 'T':
2324 ///
2325 /// \code
2326 /// template<typename ...T>
2327 /// struct X {
2328 /// typedef T* pointer_types; // ill-formed; T is a parameter pack.
2329 /// };
2330 /// \endcode
2331 ///
2332 /// Note that this routine does not specify which
2334 return getDependence() & TypeDependence::UnexpandedPack;
2335 }
2336
2337 /// Determines if this type would be canonical if it had no further
2338 /// qualification.
2340 return CanonicalType == QualType(this, 0);
2341 }
2342
2343 /// Pull a single level of sugar off of this locally-unqualified type.
2344 /// Users should generally prefer SplitQualType::getSingleStepDesugaredType()
2345 /// or QualType::getSingleStepDesugaredType(const ASTContext&).
2346 QualType getLocallyUnqualifiedSingleStepDesugaredType() const;
2347
2348 /// As an extension, we classify types as one of "sized" or "sizeless";
2349 /// every type is one or the other. Standard types are all sized;
2350 /// sizeless types are purely an extension.
2351 ///
2352 /// Sizeless types contain data with no specified size, alignment,
2353 /// or layout.
2354 bool isSizelessType() const;
2355 bool isSizelessBuiltinType() const;
2356
2357 /// Returns true for all scalable vector types.
2358 bool isSizelessVectorType() const;
2359
2360 /// Returns true for SVE scalable vector types.
2361 bool isSVESizelessBuiltinType() const;
2362
2363 /// Returns true for RVV scalable vector types.
2364 bool isRVVSizelessBuiltinType() const;
2365
2366 /// Check if this is a WebAssembly Externref Type.
2367 bool isWebAssemblyExternrefType() const;
2368
2369 /// Returns true if this is a WebAssembly table type: either an array of
2370 /// reference types, or a pointer to a reference type (which can only be
2371 /// created by array to pointer decay).
2372 bool isWebAssemblyTableType() const;
2373
2374 /// Determines if this is a sizeless type supported by the
2375 /// 'arm_sve_vector_bits' type attribute, which can be applied to a single
2376 /// SVE vector or predicate, excluding tuple types such as svint32x4_t.
2377 bool isSveVLSBuiltinType() const;
2378
2379 /// Returns the representative type for the element of an SVE builtin type.
2380 /// This is used to represent fixed-length SVE vectors created with the
2381 /// 'arm_sve_vector_bits' type attribute as VectorType.
2382 QualType getSveEltType(const ASTContext &Ctx) const;
2383
2384 /// Determines if this is a sizeless type supported by the
2385 /// 'riscv_rvv_vector_bits' type attribute, which can be applied to a single
2386 /// RVV vector or mask.
2387 bool isRVVVLSBuiltinType() const;
2388
2389 /// Returns the representative type for the element of an RVV builtin type.
2390 /// This is used to represent fixed-length RVV vectors created with the
2391 /// 'riscv_rvv_vector_bits' type attribute as VectorType.
2392 QualType getRVVEltType(const ASTContext &Ctx) const;
2393
2394 /// Returns the representative type for the element of a sizeless vector
2395 /// builtin type.
2396 QualType getSizelessVectorEltType(const ASTContext &Ctx) const;
2397
2398 /// Types are partitioned into 3 broad categories (C99 6.2.5p1):
2399 /// object types, function types, and incomplete types.
2400
2401 /// Return true if this is an incomplete type.
2402 /// A type that can describe objects, but which lacks information needed to
2403 /// determine its size (e.g. void, or a fwd declared struct). Clients of this
2404 /// routine will need to determine if the size is actually required.
2405 ///
2406 /// Def If non-null, and the type refers to some kind of declaration
2407 /// that can be completed (such as a C struct, C++ class, or Objective-C
2408 /// class), will be set to the declaration.
2409 bool isIncompleteType(NamedDecl **Def = nullptr) const;
2410
2411 /// Return true if this is an incomplete or object
2412 /// type, in other words, not a function type.
2414 return !isFunctionType();
2415 }
2416
2417 /// Determine whether this type is an object type.
2418 bool isObjectType() const {
2419 // C++ [basic.types]p8:
2420 // An object type is a (possibly cv-qualified) type that is not a
2421 // function type, not a reference type, and not a void type.
2422 return !isReferenceType() && !isFunctionType() && !isVoidType();
2423 }
2424
2425 /// Return true if this is a literal type
2426 /// (C++11 [basic.types]p10)
2427 bool isLiteralType(const ASTContext &Ctx) const;
2428
2429 /// Determine if this type is a structural type, per C++20 [temp.param]p7.
2430 bool isStructuralType() const;
2431
2432 /// Test if this type is a standard-layout type.
2433 /// (C++0x [basic.type]p9)
2434 bool isStandardLayoutType() const;
2435
2436 /// Helper methods to distinguish type categories. All type predicates
2437 /// operate on the canonical type, ignoring typedefs and qualifiers.
2438
2439 /// Returns true if the type is a builtin type.
2440 bool isBuiltinType() const;
2441
2442 /// Test for a particular builtin type.
2443 bool isSpecificBuiltinType(unsigned K) const;
2444
2445 /// Test for a type which does not represent an actual type-system type but
2446 /// is instead used as a placeholder for various convenient purposes within
2447 /// Clang. All such types are BuiltinTypes.
2448 bool isPlaceholderType() const;
2449 const BuiltinType *getAsPlaceholderType() const;
2450
2451 /// Test for a specific placeholder type.
2452 bool isSpecificPlaceholderType(unsigned K) const;
2453
2454 /// Test for a placeholder type other than Overload; see
2455 /// BuiltinType::isNonOverloadPlaceholderType.
2456 bool isNonOverloadPlaceholderType() const;
2457
2458 /// isIntegerType() does *not* include complex integers (a GCC extension).
2459 /// isComplexIntegerType() can be used to test for complex integers.
2460 bool isIntegerType() const; // C99 6.2.5p17 (int, char, bool, enum)
2461 bool isEnumeralType() const;
2462
2463 /// Determine whether this type is a scoped enumeration type.
2464 bool isScopedEnumeralType() const;
2465 bool isBooleanType() const;
2466 bool isCharType() const;
2467 bool isWideCharType() const;
2468 bool isChar8Type() const;
2469 bool isChar16Type() const;
2470 bool isChar32Type() const;
2471 bool isAnyCharacterType() const;
2472 bool isIntegralType(const ASTContext &Ctx) const;
2473
2474 /// Determine whether this type is an integral or enumeration type.
2475 bool isIntegralOrEnumerationType() const;
2476
2477 /// Determine whether this type is an integral or unscoped enumeration type.
2478 bool isIntegralOrUnscopedEnumerationType() const;
2479 bool isUnscopedEnumerationType() const;
2480
2481 /// Floating point categories.
2482 bool isRealFloatingType() const; // C99 6.2.5p10 (float, double, long double)
2483 /// isComplexType() does *not* include complex integers (a GCC extension).
2484 /// isComplexIntegerType() can be used to test for complex integers.
2485 bool isComplexType() const; // C99 6.2.5p11 (complex)
2486 bool isAnyComplexType() const; // C99 6.2.5p11 (complex) + Complex Int.
2487 bool isFloatingType() const; // C99 6.2.5p11 (real floating + complex)
2488 bool isHalfType() const; // OpenCL 6.1.1.1, NEON (IEEE 754-2008 half)
2489 bool isFloat16Type() const; // C11 extension ISO/IEC TS 18661
2490 bool isFloat32Type() const;
2491 bool isDoubleType() const;
2492 bool isBFloat16Type() const;
2493 bool isFloat128Type() const;
2494 bool isIbm128Type() const;
2495 bool isRealType() const; // C99 6.2.5p17 (real floating + integer)
2496 bool isArithmeticType() const; // C99 6.2.5p18 (integer + floating)
2497 bool isVoidType() const; // C99 6.2.5p19
2498 bool isScalarType() const; // C99 6.2.5p21 (arithmetic + pointers)
2499 bool isAggregateType() const;
2500 bool isFundamentalType() const;
2501 bool isCompoundType() const;
2502
2503 // Type Predicates: Check to see if this type is structurally the specified
2504 // type, ignoring typedefs and qualifiers.
2505 bool isFunctionType() const;
2506 bool isFunctionNoProtoType() const { return getAs<FunctionNoProtoType>(); }
2507 bool isFunctionProtoType() const { return getAs<FunctionProtoType>(); }
2508 bool isPointerType() const;
2509 bool isSignableType() const;
2510 bool isAnyPointerType() const; // Any C pointer or ObjC object pointer
2511 bool isCountAttributedType() const;
2512 bool isBlockPointerType() const;
2513 bool isVoidPointerType() const;
2514 bool isReferenceType() const;
2515 bool isLValueReferenceType() const;
2516 bool isRValueReferenceType() const;
2517 bool isObjectPointerType() const;
2518 bool isFunctionPointerType() const;
2519 bool isFunctionReferenceType() const;
2520 bool isMemberPointerType() const;
2521 bool isMemberFunctionPointerType() const;
2522 bool isMemberDataPointerType() const;
2523 bool isArrayType() const;
2524 bool isConstantArrayType() const;
2525 bool isIncompleteArrayType() const;
2526 bool isVariableArrayType() const;
2527 bool isArrayParameterType() const;
2528 bool isDependentSizedArrayType() const;
2529 bool isRecordType() const;
2530 bool isClassType() const;
2531 bool isStructureType() const;
2532 bool isStructureTypeWithFlexibleArrayMember() const;
2533 bool isObjCBoxableRecordType() const;
2534 bool isInterfaceType() const;
2535 bool isStructureOrClassType() const;
2536 bool isUnionType() const;
2537 bool isComplexIntegerType() const; // GCC _Complex integer type.
2538 bool isVectorType() const; // GCC vector type.
2539 bool isExtVectorType() const; // Extended vector type.
2540 bool isExtVectorBoolType() const; // Extended vector type with bool element.
2541 bool isSubscriptableVectorType() const;
2542 bool isMatrixType() const; // Matrix type.
2543 bool isConstantMatrixType() const; // Constant matrix type.
2544 bool isDependentAddressSpaceType() const; // value-dependent address space qualifier
2545 bool isObjCObjectPointerType() const; // pointer to ObjC object
2546 bool isObjCRetainableType() const; // ObjC object or block pointer
2547 bool isObjCLifetimeType() const; // (array of)* retainable type
2548 bool isObjCIndirectLifetimeType() const; // (pointer to)* lifetime type
2549 bool isObjCNSObjectType() const; // __attribute__((NSObject))
2550 bool isObjCIndependentClassType() const; // __attribute__((objc_independent_class))
2551 // FIXME: change this to 'raw' interface type, so we can used 'interface' type
2552 // for the common case.
2553 bool isObjCObjectType() const; // NSString or typeof(*(id)0)
2554 bool isObjCQualifiedInterfaceType() const; // NSString<foo>
2555 bool isObjCQualifiedIdType() const; // id<foo>
2556 bool isObjCQualifiedClassType() const; // Class<foo>
2557 bool isObjCObjectOrInterfaceType() const;
2558 bool isObjCIdType() const; // id
2559 bool isDecltypeType() const;
2560 /// Was this type written with the special inert-in-ARC __unsafe_unretained
2561 /// qualifier?
2562 ///
2563 /// This approximates the answer to the following question: if this
2564 /// translation unit were compiled in ARC, would this type be qualified
2565 /// with __unsafe_unretained?
2567 return hasAttr(attr::ObjCInertUnsafeUnretained);
2568 }
2569
2570 /// Whether the type is Objective-C 'id' or a __kindof type of an
2571 /// object type, e.g., __kindof NSView * or __kindof id
2572 /// <NSCopying>.
2573 ///
2574 /// \param bound Will be set to the bound on non-id subtype types,
2575 /// which will be (possibly specialized) Objective-C class type, or
2576 /// null for 'id.
2577 bool isObjCIdOrObjectKindOfType(const ASTContext &ctx,
2578 const ObjCObjectType *&bound) const;
2579
2580 bool isObjCClassType() const; // Class
2581
2582 /// Whether the type is Objective-C 'Class' or a __kindof type of an
2583 /// Class type, e.g., __kindof Class <NSCopying>.
2584 ///
2585 /// Unlike \c isObjCIdOrObjectKindOfType, there is no relevant bound
2586 /// here because Objective-C's type system cannot express "a class
2587 /// object for a subclass of NSFoo".
2588 bool isObjCClassOrClassKindOfType() const;
2589
2590 bool isBlockCompatibleObjCPointerType(ASTContext &ctx) const;
2591 bool isObjCSelType() const; // Class
2592 bool isObjCBuiltinType() const; // 'id' or 'Class'
2593 bool isObjCARCBridgableType() const;
2594 bool isCARCBridgableType() const;
2595 bool isTemplateTypeParmType() const; // C++ template type parameter
2596 bool isNullPtrType() const; // C++11 std::nullptr_t or
2597 // C23 nullptr_t
2598 bool isNothrowT() const; // C++ std::nothrow_t
2599 bool isAlignValT() const; // C++17 std::align_val_t
2600 bool isStdByteType() const; // C++17 std::byte
2601 bool isAtomicType() const; // C11 _Atomic()
2602 bool isUndeducedAutoType() const; // C++11 auto or
2603 // C++14 decltype(auto)
2604 bool isTypedefNameType() const; // typedef or alias template
2605
2606#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
2607 bool is##Id##Type() const;
2608#include "clang/Basic/OpenCLImageTypes.def"
2609
2610 bool isImageType() const; // Any OpenCL image type
2611
2612 bool isSamplerT() const; // OpenCL sampler_t
2613 bool isEventT() const; // OpenCL event_t
2614 bool isClkEventT() const; // OpenCL clk_event_t
2615 bool isQueueT() const; // OpenCL queue_t
2616 bool isReserveIDT() const; // OpenCL reserve_id_t
2617
2618#define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
2619 bool is##Id##Type() const;
2620#include "clang/Basic/OpenCLExtensionTypes.def"
2621 // Type defined in cl_intel_device_side_avc_motion_estimation OpenCL extension
2622 bool isOCLIntelSubgroupAVCType() const;
2623 bool isOCLExtOpaqueType() const; // Any OpenCL extension type
2624
2625 bool isPipeType() const; // OpenCL pipe type
2626 bool isBitIntType() const; // Bit-precise integer type
2627 bool isOpenCLSpecificType() const; // Any OpenCL specific type
2628
2629 /// Determines if this type, which must satisfy
2630 /// isObjCLifetimeType(), is implicitly __unsafe_unretained rather
2631 /// than implicitly __strong.
2632 bool isObjCARCImplicitlyUnretainedType() const;
2633
2634 /// Check if the type is the CUDA device builtin surface type.
2635 bool isCUDADeviceBuiltinSurfaceType() const;
2636 /// Check if the type is the CUDA device builtin texture type.
2637 bool isCUDADeviceBuiltinTextureType() const;
2638
2639 /// Return the implicit lifetime for this type, which must not be dependent.
2640 Qualifiers::ObjCLifetime getObjCARCImplicitLifetime() const;
2641
2652 STK_FixedPoint
2654
2655 /// Given that this is a scalar type, classify it.
2656 ScalarTypeKind getScalarTypeKind() const;
2657
2659 return static_cast<TypeDependence>(TypeBits.Dependence);
2660 }
2661
2662 /// Whether this type is an error type.
2663 bool containsErrors() const {
2664 return getDependence() & TypeDependence::Error;
2665 }
2666
2667 /// Whether this type is a dependent type, meaning that its definition
2668 /// somehow depends on a template parameter (C++ [temp.dep.type]).
2669 bool isDependentType() const {
2670 return getDependence() & TypeDependence::Dependent;
2671 }
2672
2673 /// Determine whether this type is an instantiation-dependent type,
2674 /// meaning that the type involves a template parameter (even if the
2675 /// definition does not actually depend on the type substituted for that
2676 /// template parameter).
2678 return getDependence() & TypeDependence::Instantiation;
2679 }
2680
2681 /// Determine whether this type is an undeduced type, meaning that
2682 /// it somehow involves a C++11 'auto' type or similar which has not yet been
2683 /// deduced.
2684 bool isUndeducedType() const;
2685
2686 /// Whether this type is a variably-modified type (C99 6.7.5).
2688 return getDependence() & TypeDependence::VariablyModified;
2689 }
2690
2691 /// Whether this type involves a variable-length array type
2692 /// with a definite size.
2693 bool hasSizedVLAType() const;
2694
2695 /// Whether this type is or contains a local or unnamed type.
2696 bool hasUnnamedOrLocalType() const;
2697
2698 bool isOverloadableType() const;
2699
2700 /// Determine wither this type is a C++ elaborated-type-specifier.
2701 bool isElaboratedTypeSpecifier() const;
2702
2703 bool canDecayToPointerType() const;
2704
2705 /// Whether this type is represented natively as a pointer. This includes
2706 /// pointers, references, block pointers, and Objective-C interface,
2707 /// qualified id, and qualified interface types, as well as nullptr_t.
2708 bool hasPointerRepresentation() const;
2709
2710 /// Whether this type can represent an objective pointer type for the
2711 /// purpose of GC'ability
2712 bool hasObjCPointerRepresentation() const;
2713
2714 /// Determine whether this type has an integer representation
2715 /// of some sort, e.g., it is an integer type or a vector.
2716 bool hasIntegerRepresentation() const;
2717
2718 /// Determine whether this type has an signed integer representation
2719 /// of some sort, e.g., it is an signed integer type or a vector.
2720 bool hasSignedIntegerRepresentation() const;
2721
2722 /// Determine whether this type has an unsigned integer representation
2723 /// of some sort, e.g., it is an unsigned integer type or a vector.
2724 bool hasUnsignedIntegerRepresentation() const;
2725
2726 /// Determine whether this type has a floating-point representation
2727 /// of some sort, e.g., it is a floating-point type or a vector thereof.
2728 bool hasFloatingRepresentation() const;
2729
2730 // Type Checking Functions: Check to see if this type is structurally the
2731 // specified type, ignoring typedefs and qualifiers, and return a pointer to
2732 // the best type we can.
2733 const RecordType *getAsStructureType() const;
2734 /// NOTE: getAs*ArrayType are methods on ASTContext.
2735 const RecordType *getAsUnionType() const;
2736 const ComplexType *getAsComplexIntegerType() const; // GCC complex int type.
2737 const ObjCObjectType *getAsObjCInterfaceType() const;
2738
2739 // The following is a convenience method that returns an ObjCObjectPointerType
2740 // for object declared using an interface.
2741 const ObjCObjectPointerType *getAsObjCInterfacePointerType() const;
2742 const ObjCObjectPointerType *getAsObjCQualifiedIdType() const;
2743 const ObjCObjectPointerType *getAsObjCQualifiedClassType() const;
2744 const ObjCObjectType *getAsObjCQualifiedInterfaceType() const;
2745
2746 /// Retrieves the CXXRecordDecl that this type refers to, either
2747 /// because the type is a RecordType or because it is the injected-class-name
2748 /// type of a class template or class template partial specialization.
2749 CXXRecordDecl *getAsCXXRecordDecl() const;
2750
2751 /// Retrieves the RecordDecl this type refers to.
2752 RecordDecl *getAsRecordDecl() const;
2753
2754 /// Retrieves the TagDecl that this type refers to, either
2755 /// because the type is a TagType or because it is the injected-class-name
2756 /// type of a class template or class template partial specialization.
2757 TagDecl *getAsTagDecl() const;
2758
2759 /// If this is a pointer or reference to a RecordType, return the
2760 /// CXXRecordDecl that the type refers to.
2761 ///
2762 /// If this is not a pointer or reference, or the type being pointed to does
2763 /// not refer to a CXXRecordDecl, returns NULL.
2764 const CXXRecordDecl *getPointeeCXXRecordDecl() const;
2765
2766 /// Get the DeducedType whose type will be deduced for a variable with
2767 /// an initializer of this type. This looks through declarators like pointer
2768 /// types, but not through decltype or typedefs.
2769 DeducedType *getContainedDeducedType() const;
2770
2771 /// Get the AutoType whose type will be deduced for a variable with
2772 /// an initializer of this type. This looks through declarators like pointer
2773 /// types, but not through decltype or typedefs.
2775 return dyn_cast_or_null<AutoType>(getContainedDeducedType());
2776 }
2777
2778 /// Determine whether this type was written with a leading 'auto'
2779 /// corresponding to a trailing return type (possibly for a nested
2780 /// function type within a pointer to function type or similar).
2781 bool hasAutoForTrailingReturnType() const;
2782
2783 /// Member-template getAs<specific type>'. Look through sugar for
2784 /// an instance of <specific type>. This scheme will eventually
2785 /// replace the specific getAsXXXX methods above.
2786 ///
2787 /// There are some specializations of this member template listed
2788 /// immediately following this class.
2789 template <typename T> const T *getAs() const;
2790
2791 /// Member-template getAsAdjusted<specific type>. Look through specific kinds
2792 /// of sugar (parens, attributes, etc) for an instance of <specific type>.
2793 /// This is used when you need to walk over sugar nodes that represent some
2794 /// kind of type adjustment from a type that was written as a <specific type>
2795 /// to another type that is still canonically a <specific type>.
2796 template <typename T> const T *getAsAdjusted() const;
2797
2798 /// A variant of getAs<> for array types which silently discards
2799 /// qualifiers from the outermost type.
2800 const ArrayType *getAsArrayTypeUnsafe() const;
2801
2802 /// Member-template castAs<specific type>. Look through sugar for
2803 /// the underlying instance of <specific type>.
2804 ///
2805 /// This method has the same relationship to getAs<T> as cast<T> has
2806 /// to dyn_cast<T>; which is to say, the underlying type *must*
2807 /// have the intended type, and this method will never return null.
2808 template <typename T> const T *castAs() const;
2809
2810 /// A variant of castAs<> for array type which silently discards
2811 /// qualifiers from the outermost type.
2812 const ArrayType *castAsArrayTypeUnsafe() const;
2813
2814 /// Determine whether this type had the specified attribute applied to it
2815 /// (looking through top-level type sugar).
2816 bool hasAttr(attr::Kind AK) const;
2817
2818 /// Get the base element type of this type, potentially discarding type
2819 /// qualifiers. This should never be used when type qualifiers
2820 /// are meaningful.
2821 const Type *getBaseElementTypeUnsafe() const;
2822
2823 /// If this is an array type, return the element type of the array,
2824 /// potentially with type qualifiers missing.
2825 /// This should never be used when type qualifiers are meaningful.
2826 const Type *getArrayElementTypeNoTypeQual() const;
2827
2828 /// If this is a pointer type, return the pointee type.
2829 /// If this is an array type, return the array element type.
2830 /// This should never be used when type qualifiers are meaningful.
2831 const Type *getPointeeOrArrayElementType() const;
2832
2833 /// If this is a pointer, ObjC object pointer, or block
2834 /// pointer, this returns the respective pointee.
2835 QualType getPointeeType() const;
2836
2837 /// Return the specified type with any "sugar" removed from the type,
2838 /// removing any typedefs, typeofs, etc., as well as any qualifiers.
2839 const Type *getUnqualifiedDesugaredType() const;
2840
2841 /// Return true if this is an integer type that is
2842 /// signed, according to C99 6.2.5p4 [char, signed char, short, int, long..],
2843 /// or an enum decl which has a signed representation.
2844 bool isSignedIntegerType() const;
2845
2846 /// Return true if this is an integer type that is
2847 /// unsigned, according to C99 6.2.5p6 [which returns true for _Bool],
2848 /// or an enum decl which has an unsigned representation.
2849 bool isUnsignedIntegerType() const;
2850
2851 /// Determines whether this is an integer type that is signed or an
2852 /// enumeration types whose underlying type is a signed integer type.
2853 bool isSignedIntegerOrEnumerationType() const;
2854
2855 /// Determines whether this is an integer type that is unsigned or an
2856 /// enumeration types whose underlying type is a unsigned integer type.
2857 bool isUnsignedIntegerOrEnumerationType() const;
2858
2859 /// Return true if this is a fixed point type according to
2860 /// ISO/IEC JTC1 SC22 WG14 N1169.
2861 bool isFixedPointType() const;
2862
2863 /// Return true if this is a fixed point or integer type.
2864 bool isFixedPointOrIntegerType() const;
2865
2866 /// Return true if this can be converted to (or from) a fixed point type.
2867 bool isConvertibleToFixedPointType() const;
2868
2869 /// Return true if this is a saturated fixed point type according to
2870 /// ISO/IEC JTC1 SC22 WG14 N1169. This type can be signed or unsigned.
2871 bool isSaturatedFixedPointType() const;
2872
2873 /// Return true if this is a saturated fixed point type according to
2874 /// ISO/IEC JTC1 SC22 WG14 N1169. This type can be signed or unsigned.
2875 bool isUnsaturatedFixedPointType() const;
2876
2877 /// Return true if this is a fixed point type that is signed according
2878 /// to ISO/IEC JTC1 SC22 WG14 N1169. This type can also be saturated.
2879 bool isSignedFixedPointType() const;
2880
2881 /// Return true if this is a fixed point type that is unsigned according
2882 /// to ISO/IEC JTC1 SC22 WG14 N1169. This type can also be saturated.
2883 bool isUnsignedFixedPointType() const;
2884
2885 /// Return true if this is not a variable sized type,
2886 /// according to the rules of C99 6.7.5p3. It is not legal to call this on
2887 /// incomplete types.
2888 bool isConstantSizeType() const;
2889
2890 /// Returns true if this type can be represented by some
2891 /// set of type specifiers.
2892 bool isSpecifierType() const;
2893
2894 /// Determine the linkage of this type.
2895 Linkage getLinkage() const;
2896
2897 /// Determine the visibility of this type.
2899 return getLinkageAndVisibility().getVisibility();
2900 }
2901
2902 /// Return true if the visibility was explicitly set is the code.
2904 return getLinkageAndVisibility().isVisibilityExplicit();
2905 }
2906
2907 /// Determine the linkage and visibility of this type.
2908 LinkageInfo getLinkageAndVisibility() const;
2909
2910 /// True if the computed linkage is valid. Used for consistency
2911 /// checking. Should always return true.
2912 bool isLinkageValid() const;
2913
2914 /// Determine the nullability of the given type.
2915 ///
2916 /// Note that nullability is only captured as sugar within the type
2917 /// system, not as part of the canonical type, so nullability will
2918 /// be lost by canonicalization and desugaring.
2919 std::optional<NullabilityKind> getNullability() const;
2920
2921 /// Determine whether the given type can have a nullability
2922 /// specifier applied to it, i.e., if it is any kind of pointer type.
2923 ///
2924 /// \param ResultIfUnknown The value to return if we don't yet know whether
2925 /// this type can have nullability because it is dependent.
2926 bool canHaveNullability(bool ResultIfUnknown = true) const;
2927
2928 /// Retrieve the set of substitutions required when accessing a member
2929 /// of the Objective-C receiver type that is declared in the given context.
2930 ///
2931 /// \c *this is the type of the object we're operating on, e.g., the
2932 /// receiver for a message send or the base of a property access, and is
2933 /// expected to be of some object or object pointer type.
2934 ///
2935 /// \param dc The declaration context for which we are building up a
2936 /// substitution mapping, which should be an Objective-C class, extension,
2937 /// category, or method within.
2938 ///
2939 /// \returns an array of type arguments that can be substituted for
2940 /// the type parameters of the given declaration context in any type described
2941 /// within that context, or an empty optional to indicate that no
2942 /// substitution is required.
2943 std::optional<ArrayRef<QualType>>
2944 getObjCSubstitutions(const DeclContext *dc) const;
2945
2946 /// Determines if this is an ObjC interface type that may accept type
2947 /// parameters.
2948 bool acceptsObjCTypeParams() const;
2949
2950 const char *getTypeClassName() const;
2951
2953 return CanonicalType;
2954 }
2955
2956 CanQualType getCanonicalTypeUnqualified() const; // in CanonicalType.h
2957 void dump() const;
2958 void dump(llvm::raw_ostream &OS, const ASTContext &Context) const;
2959};
2960
2961/// This will check for a TypedefType by removing any existing sugar
2962/// until it reaches a TypedefType or a non-sugared type.
2963template <> const TypedefType *Type::getAs() const;
2964template <> const UsingType *Type::getAs() const;
2965
2966/// This will check for a TemplateSpecializationType by removing any
2967/// existing sugar until it reaches a TemplateSpecializationType or a
2968/// non-sugared type.
2969template <> const TemplateSpecializationType *Type::getAs() const;
2970
2971/// This will check for an AttributedType by removing any existing sugar
2972/// until it reaches an AttributedType or a non-sugared type.
2973template <> const AttributedType *Type::getAs() const;
2974
2975/// This will check for a BoundsAttributedType by removing any existing
2976/// sugar until it reaches an BoundsAttributedType or a non-sugared type.
2977template <> const BoundsAttributedType *Type::getAs() const;
2978
2979/// This will check for a CountAttributedType by removing any existing
2980/// sugar until it reaches an CountAttributedType or a non-sugared type.
2981template <> const CountAttributedType *Type::getAs() const;
2982
2983// We can do canonical leaf types faster, because we don't have to
2984// worry about preserving child type decoration.
2985#define TYPE(Class, Base)
2986#define LEAF_TYPE(Class) \
2987template <> inline const Class##Type *Type::getAs() const { \
2988 return dyn_cast<Class##Type>(CanonicalType); \
2989} \
2990template <> inline const Class##Type *Type::castAs() const { \
2991 return cast<Class##Type>(CanonicalType); \
2992}
2993#include "clang/AST/TypeNodes.inc"
2994
2995/// This class is used for builtin types like 'int'. Builtin
2996/// types are always canonical and have a literal name field.
2997class BuiltinType : public Type {
2998public:
2999 enum Kind {
3000// OpenCL image types
3001#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) Id,
3002#include "clang/Basic/OpenCLImageTypes.def"
3003// OpenCL extension types
3004#define EXT_OPAQUE_TYPE(ExtType, Id, Ext) Id,
3005#include "clang/Basic/OpenCLExtensionTypes.def"
3006// SVE Types
3007#define SVE_TYPE(Name, Id, SingletonId) Id,
3008#include "clang/Basic/AArch64SVEACLETypes.def"
3009// PPC MMA Types
3010#define PPC_VECTOR_TYPE(Name, Id, Size) Id,
3011#include "clang/Basic/PPCTypes.def"
3012// RVV Types
3013#define RVV_TYPE(Name, Id, SingletonId) Id,
3014#include "clang/Basic/RISCVVTypes.def"
3015// WebAssembly reference types
3016#define WASM_TYPE(Name, Id, SingletonId) Id,
3017#include "clang/Basic/WebAssemblyReferenceTypes.def"
3018// AMDGPU types
3019#define AMDGPU_TYPE(Name, Id, SingletonId) Id,
3020#include "clang/Basic/AMDGPUTypes.def"
3021// All other builtin types
3022#define BUILTIN_TYPE(Id, SingletonId) Id,
3023#define LAST_BUILTIN_TYPE(Id) LastKind = Id
3024#include "clang/AST/BuiltinTypes.def"
3025 };
3026
3027private:
3028 friend class ASTContext; // ASTContext creates these.
3029
3030 BuiltinType(Kind K)
3031 : Type(Builtin, QualType(),
3032 K == Dependent ? TypeDependence::DependentInstantiation
3033 : TypeDependence::None) {
3034 static_assert(Kind::LastKind <
3035 (1 << BuiltinTypeBitfields::NumOfBuiltinTypeBits) &&
3036 "Defined builtin type exceeds the allocated space for serial "
3037 "numbering");
3038 BuiltinTypeBits.Kind = K;
3039 }
3040
3041public:
3042 Kind getKind() const { return static_cast<Kind>(BuiltinTypeBits.Kind); }
3043 StringRef getName(const PrintingPolicy &Policy) const;
3044
3045 const char *getNameAsCString(const PrintingPolicy &Policy) const {
3046 // The StringRef is null-terminated.
3047 StringRef str = getName(Policy);
3048 assert(!str.empty() && str.data()[str.size()] == '\0');
3049 return str.data();
3050 }
3051
3052 bool isSugared() const { return false; }
3053 QualType desugar() const { return QualType(this, 0); }
3054
3055 bool isInteger() const {
3056 return getKind() >= Bool && getKind() <= Int128;
3057 }
3058
3059 bool isSignedInteger() const {
3060 return getKind() >= Char_S && getKind() <= Int128;
3061 }
3062
3063 bool isUnsignedInteger() const {
3064 return getKind() >= Bool && getKind() <= UInt128;
3065 }
3066
3067 bool isFloatingPoint() const {
3068 return getKind() >= Half && getKind() <= Ibm128;
3069 }
3070
3071 bool isSVEBool() const { return getKind() == Kind::SveBool; }
3072
3073 bool isSVECount() const { return getKind() == Kind::SveCount; }
3074
3075 /// Determines whether the given kind corresponds to a placeholder type.
3077 return K >= Overload;
3078 }
3079
3080 /// Determines whether this type is a placeholder type, i.e. a type
3081 /// which cannot appear in arbitrary positions in a fully-formed
3082 /// expression.
3083 bool isPlaceholderType() const {
3084 return isPlaceholderTypeKind(getKind());
3085 }
3086
3087 /// Determines whether this type is a placeholder type other than
3088 /// Overload. Most placeholder types require only syntactic
3089 /// information about their context in order to be resolved (e.g.
3090 /// whether it is a call expression), which means they can (and
3091 /// should) be resolved in an earlier "phase" of analysis.
3092 /// Overload expressions sometimes pick up further information
3093 /// from their context, like whether the context expects a
3094 /// specific function-pointer type, and so frequently need
3095 /// special treatment.
3097 return getKind() > Overload;
3098 }
3099
3100 static bool classof(const Type *T) { return T->getTypeClass() == Builtin; }
3101};
3102
3103/// Complex values, per C99 6.2.5p11. This supports the C99 complex
3104/// types (_Complex float etc) as well as the GCC integer complex extensions.
3105class ComplexType : public Type, public llvm::FoldingSetNode {
3106 friend class ASTContext; // ASTContext creates these.
3107
3108 QualType ElementType;
3109
3110 ComplexType(QualType Element, QualType CanonicalPtr)
3111 : Type(Complex, CanonicalPtr, Element->getDependence()),
3112 ElementType(Element) {}
3113
3114public:
3115 QualType getElementType() const { return ElementType; }
3116
3117 bool isSugared() const { return false; }
3118 QualType desugar() const { return QualType(this, 0); }
3119
3120 void Profile(llvm::FoldingSetNodeID &ID) {
3121 Profile(ID, getElementType());
3122 }
3123
3124 static void Profile(llvm::FoldingSetNodeID &ID, QualType Element) {
3125 ID.AddPointer(Element.getAsOpaquePtr());
3126 }
3127
3128 static bool classof(const Type *T) { return T->getTypeClass() == Complex; }
3129};
3130
3131/// Sugar for parentheses used when specifying types.
3132class ParenType : public Type, public llvm::FoldingSetNode {
3133 friend class ASTContext; // ASTContext creates these.
3134
3135 QualType Inner;
3136
3137 ParenType(QualType InnerType, QualType CanonType)
3138 : Type(Paren, CanonType, InnerType->getDependence()), Inner(InnerType) {}
3139
3140public:
3141 QualType getInnerType() const { return Inner; }
3142
3143 bool isSugared() const { return true; }
3144 QualType desugar() const { return getInnerType(); }
3145
3146 void Profile(llvm::FoldingSetNodeID &ID) {
3147 Profile(ID, getInnerType());
3148 }
3149
3150 static void Profile(llvm::FoldingSetNodeID &ID, QualType Inner) {
3151 Inner.Profile(ID);
3152 }
3153
3154 static bool classof(const Type *T) { return T->getTypeClass() == Paren; }
3155};
3156
3157/// PointerType - C99 6.7.5.1 - Pointer Declarators.
3158class PointerType : public Type, public llvm::FoldingSetNode {
3159 friend class ASTContext; // ASTContext creates these.
3160
3161 QualType PointeeType;
3162
3163 PointerType(QualType Pointee, QualType CanonicalPtr)
3164 : Type(Pointer, CanonicalPtr, Pointee->getDependence()),
3165 PointeeType(Pointee) {}
3166
3167public:
3168 QualType getPointeeType() const { return PointeeType; }
3169
3170 bool isSugared() const { return false; }
3171 QualType desugar() const { return QualType(this, 0); }
3172
3173 void Profile(llvm::FoldingSetNodeID &ID) {
3174 Profile(ID, getPointeeType());
3175 }
3176
3177 static void Profile(llvm::FoldingSetNodeID &ID, QualType Pointee) {
3178 ID.AddPointer(Pointee.getAsOpaquePtr());
3179 }
3180
3181 static bool classof(const Type *T) { return T->getTypeClass() == Pointer; }
3182};
3183
3184/// [BoundsSafety] Represents information of declarations referenced by the
3185/// arguments of the `counted_by` attribute and the likes.
3187public:
3188 using BaseTy = llvm::PointerIntPair<ValueDecl *, 1, unsigned>;
3189
3190private:
3191 enum {
3192 DerefShift = 0,
3193 DerefMask = 1,
3194 };
3195 BaseTy Data;
3196
3197public:
3198 /// \p D is to a declaration referenced by the argument of attribute. \p Deref
3199 /// indicates whether \p D is referenced as a dereferenced form, e.g., \p
3200 /// Deref is true for `*n` in `int *__counted_by(*n)`.
3201 TypeCoupledDeclRefInfo(ValueDecl *D = nullptr, bool Deref = false);
3202
3203 bool isDeref() const;
3204 ValueDecl *getDecl() const;
3205 unsigned getInt() const;
3206 void *getOpaqueValue() const;
3207 bool operator==(const TypeCoupledDeclRefInfo &Other) const;
3208 void setFromOpaqueValue(void *V);
3209};
3210
3211/// [BoundsSafety] Represents a parent type class for CountAttributedType and
3212/// similar sugar types that will be introduced to represent a type with a
3213/// bounds attribute.
3214///
3215/// Provides a common interface to navigate declarations referred to by the
3216/// bounds expression.
3217
3218class BoundsAttributedType : public Type, public llvm::FoldingSetNode {
3219 QualType WrappedTy;
3220
3221protected:
3222 ArrayRef<TypeCoupledDeclRefInfo> Decls; // stored in trailing objects
3223
3224 BoundsAttributedType(TypeClass TC, QualType Wrapped, QualType Canon);
3225
3226public:
3227 bool isSugared() const { return true; }
3228 QualType desugar() const { return WrappedTy; }
3229
3231 using decl_range = llvm::iterator_range<decl_iterator>;
3232
3233 decl_iterator dependent_decl_begin() const { return Decls.begin(); }
3234 decl_iterator dependent_decl_end() const { return Decls.end(); }
3235
3236 unsigned getNumCoupledDecls() const { return Decls.size(); }
3237
3239 return decl_range(dependent_decl_begin(), dependent_decl_end());
3240 }
3241
3243 return {dependent_decl_begin(), dependent_decl_end()};
3244 }
3245
3246 bool referencesFieldDecls() const;
3247
3248 static bool classof(const Type *T) {
3249 // Currently, only `class CountAttributedType` inherits
3250 // `BoundsAttributedType` but the subclass will grow as we add more bounds
3251 // annotations.
3252 switch (T->getTypeClass()) {
3253 case CountAttributed:
3254 return true;
3255 default:
3256 return false;
3257 }
3258 }
3259};
3260
3261/// Represents a sugar type with `__counted_by` or `__sized_by` annotations,
3262/// including their `_or_null` variants.
3264 : public BoundsAttributedType,
3265 public llvm::TrailingObjects<CountAttributedType,
3266 TypeCoupledDeclRefInfo> {
3267 friend class ASTContext;
3268
3269 Expr *CountExpr;
3270 /// \p CountExpr represents the argument of __counted_by or the likes. \p
3271 /// CountInBytes indicates that \p CountExpr is a byte count (i.e.,
3272 /// __sized_by(_or_null)) \p OrNull means it's an or_null variant (i.e.,
3273 /// __counted_by_or_null or __sized_by_or_null) \p CoupledDecls contains the
3274 /// list of declarations referenced by \p CountExpr, which the type depends on
3275 /// for the bounds information.
3276 CountAttributedType(QualType Wrapped, QualType Canon, Expr *CountExpr,
3277 bool CountInBytes, bool OrNull,
3279
3280 unsigned numTrailingObjects(OverloadToken<TypeCoupledDeclRefInfo>) const {
3281 return CountAttributedTypeBits.NumCoupledDecls;
3282 }
3283
3284public:
3286 CountedBy = 0,
3290 };
3291
3292 Expr *getCountExpr() const { return CountExpr; }
3293 bool isCountInBytes() const { return CountAttributedTypeBits.CountInBytes; }
3294 bool isOrNull() const { return CountAttributedTypeBits.OrNull; }
3295
3297 if (isOrNull())
3298 return isCountInBytes() ? SizedByOrNull : CountedByOrNull;
3299 return isCountInBytes() ? SizedBy : CountedBy;
3300 }
3301
3302 void Profile(llvm::FoldingSetNodeID &ID) {
3303 Profile(ID, desugar(), CountExpr, isCountInBytes(), isOrNull());
3304 }
3305
3306 static void Profile(llvm::FoldingSetNodeID &ID, QualType WrappedTy,
3307 Expr *CountExpr, bool CountInBytes, bool Nullable);
3308
3309 static bool classof(const Type *T) {
3310 return T->getTypeClass() == CountAttributed;
3311 }
3312};
3313
3314/// Represents a type which was implicitly adjusted by the semantic
3315/// engine for arbitrary reasons. For example, array and function types can
3316/// decay, and function types can have their calling conventions adjusted.
3317class AdjustedType : public Type, public llvm::FoldingSetNode {
3318 QualType OriginalTy;
3319 QualType AdjustedTy;
3320
3321protected:
3322 friend class ASTContext; // ASTContext creates these.
3323
3324 AdjustedType(TypeClass TC, QualType OriginalTy, QualType AdjustedTy,
3325 QualType CanonicalPtr)
3326 : Type(TC, CanonicalPtr, OriginalTy->getDependence()),
3327 OriginalTy(OriginalTy), AdjustedTy(AdjustedTy) {}
3328
3329public:
3330 QualType getOriginalType() const { return OriginalTy; }
3331 QualType getAdjustedType() const { return AdjustedTy; }
3332
3333 bool isSugared() const { return true; }
3334 QualType desugar() const { return AdjustedTy; }
3335
3336 void Profile(llvm::FoldingSetNodeID &ID) {
3337 Profile(ID, OriginalTy, AdjustedTy);
3338 }
3339
3340 static void Profile(llvm::FoldingSetNodeID &ID, QualType Orig, QualType New) {
3341 ID.AddPointer(Orig.getAsOpaquePtr());
3342 ID.AddPointer(New.getAsOpaquePtr());
3343 }
3344
3345 static bool classof(const Type *T) {
3346 return T->getTypeClass() == Adjusted || T->getTypeClass() == Decayed;
3347 }
3348};
3349
3350/// Represents a pointer type decayed from an array or function type.
3352 friend class ASTContext; // ASTContext creates these.
3353
3354 inline
3355 DecayedType(QualType OriginalType, QualType Decayed, QualType Canonical);
3356
3357public:
3358 QualType getDecayedType() const { return getAdjustedType(); }
3359
3360 inline QualType getPointeeType() const;
3361
3362 static bool classof(const Type *T) { return T->getTypeClass() == Decayed; }
3363};
3364
3365/// Pointer to a block type.
3366/// This type is to represent types syntactically represented as
3367/// "void (^)(int)", etc. Pointee is required to always be a function type.
3368class BlockPointerType : public Type, public llvm::FoldingSetNode {
3369 friend class ASTContext; // ASTContext creates these.
3370
3371 // Block is some kind of pointer type
3372 QualType PointeeType;
3373
3374 BlockPointerType(QualType Pointee, QualType CanonicalCls)
3375 : Type(BlockPointer, CanonicalCls, Pointee->getDependence()),
3376 PointeeType(Pointee) {}
3377
3378public:
3379 // Get the pointee type. Pointee is required to always be a function type.
3380 QualType getPointeeType() const { return PointeeType; }
3381
3382 bool isSugared() const { return false; }
3383 QualType desugar() const { return QualType(this, 0); }
3384
3385 void Profile(llvm::FoldingSetNodeID &ID) {
3386 Profile(ID, getPointeeType());
3387 }
3388
3389 static void Profile(llvm::FoldingSetNodeID &ID, QualType Pointee) {
3390 ID.AddPointer(Pointee.getAsOpaquePtr());
3391 }
3392
3393 static bool classof(const Type *T) {
3394 return T->getTypeClass() == BlockPointer;
3395 }
3396};
3397
3398/// Base for LValueReferenceType and RValueReferenceType
3399class ReferenceType : public Type, public llvm::FoldingSetNode {
3400 QualType PointeeType;
3401
3402protected:
3403 ReferenceType(TypeClass tc, QualType Referencee, QualType CanonicalRef,
3404 bool SpelledAsLValue)
3405 : Type(tc, CanonicalRef, Referencee->getDependence()),
3406 PointeeType(Referencee) {
3407 ReferenceTypeBits.SpelledAsLValue = SpelledAsLValue;
3408 ReferenceTypeBits.InnerRef = Referencee->isReferenceType();
3409 }
3410
3411public:
3412 bool isSpelledAsLValue() const { return ReferenceTypeBits.SpelledAsLValue; }
3413 bool isInnerRef() const { return ReferenceTypeBits.InnerRef; }
3414
3415 QualType getPointeeTypeAsWritten() const { return PointeeType; }
3416
3418 // FIXME: this might strip inner qualifiers; okay?
3419 const ReferenceType *T = this;
3420 while (T->isInnerRef())
3421 T = T->PointeeType->castAs<ReferenceType>();
3422 return T->PointeeType;
3423 }
3424
3425 void Profile(llvm::FoldingSetNodeID &ID) {
3426 Profile(ID, PointeeType, isSpelledAsLValue());
3427 }
3428
3429 static void Profile(llvm::FoldingSetNodeID &ID,
3430 QualType Referencee,
3431 bool SpelledAsLValue) {
3432 ID.AddPointer(Referencee.getAsOpaquePtr());
3433 ID.AddBoolean(SpelledAsLValue);
3434 }
3435
3436 static bool classof(const Type *T) {
3437 return T->getTypeClass() == LValueReference ||
3438 T->getTypeClass() == RValueReference;
3439 }
3440};
3441
3442/// An lvalue reference type, per C++11 [dcl.ref].
3444 friend class ASTContext; // ASTContext creates these
3445
3446 LValueReferenceType(QualType Referencee, QualType CanonicalRef,
3447 bool SpelledAsLValue)
3448 : ReferenceType(LValueReference, Referencee, CanonicalRef,
3449 SpelledAsLValue) {}
3450
3451public:
3452 bool isSugared() const { return false; }
3453 QualType desugar() const { return QualType(this, 0); }
3454
3455 static bool classof(const Type *T) {
3456 return T->getTypeClass() == LValueReference;
3457 }
3458};
3459
3460/// An rvalue reference type, per C++11 [dcl.ref].
3462 friend class ASTContext; // ASTContext creates these
3463
3464 RValueReferenceType(QualType Referencee, QualType CanonicalRef)
3465 : ReferenceType(RValueReference, Referencee, CanonicalRef, false) {}
3466
3467public:
3468 bool isSugared() const { return false; }
3469 QualType desugar() const { return QualType(this, 0); }
3470
3471 static bool classof(const Type *T) {
3472 return T->getTypeClass() == RValueReference;
3473 }
3474};
3475
3476/// A pointer to member type per C++ 8.3.3 - Pointers to members.
3477///
3478/// This includes both pointers to data members and pointer to member functions.
3479class MemberPointerType : public Type, public llvm::FoldingSetNode {
3480 friend class ASTContext; // ASTContext creates these.
3481
3482 QualType PointeeType;
3483
3484 /// The class of which the pointee is a member. Must ultimately be a
3485 /// RecordType, but could be a typedef or a template parameter too.
3486 const Type *Class;
3487
3488 MemberPointerType(QualType Pointee, const Type *Cls, QualType CanonicalPtr)
3489 : Type(MemberPointer, CanonicalPtr,
3490 (Cls->getDependence() & ~TypeDependence::VariablyModified) |
3491 Pointee->getDependence()),
3492 PointeeType(Pointee), Class(Cls) {}
3493
3494public:
3495 QualType getPointeeType() const { return PointeeType; }
3496
3497 /// Returns true if the member type (i.e. the pointee type) is a
3498 /// function type rather than a data-member type.
3500 return PointeeType->isFunctionProtoType();
3501 }
3502
3503 /// Returns true if the member type (i.e. the pointee type) is a
3504 /// data type rather than a function type.
3505 bool isMemberDataPointer() const {
3506 return !PointeeType->isFunctionProtoType();
3507 }
3508
3509 const Type *getClass() const { return Class; }
3510 CXXRecordDecl *getMostRecentCXXRecordDecl() const;
3511
3512 bool isSugared() const { return false; }
3513 QualType desugar() const { return QualType(this, 0); }
3514
3515 void Profile(llvm::FoldingSetNodeID &ID) {
3516 Profile(ID, getPointeeType(), getClass());
3517 }
3518
3519 static void Profile(llvm::FoldingSetNodeID &ID, QualType Pointee,
3520 const Type *Class) {
3521 ID.AddPointer(Pointee.getAsOpaquePtr());
3522 ID.AddPointer(Class);
3523 }
3524
3525 static bool classof(const Type *T) {
3526 return T->getTypeClass() == MemberPointer;
3527 }
3528};
3529
3530/// Capture whether this is a normal array (e.g. int X[4])
3531/// an array with a static size (e.g. int X[static 4]), or an array
3532/// with a star size (e.g. int X[*]).
3533/// 'static' is only allowed on function parameters.
3534enum class ArraySizeModifier { Normal, Static, Star };
3535
3536/// Represents an array type, per C99 6.7.5.2 - Array Declarators.
3537class ArrayType : public Type, public llvm::FoldingSetNode {
3538private:
3539 /// The element type of the array.
3540 QualType ElementType;
3541
3542protected:
3543 friend class ASTContext; // ASTContext creates these.
3544
3546 unsigned tq, const Expr *sz = nullptr);
3547
3548public:
3549 QualType getElementType() const { return ElementType; }
3550
3552 return ArraySizeModifier(ArrayTypeBits.SizeModifier);
3553 }
3554
3556 return Qualifiers::fromCVRMask(getIndexTypeCVRQualifiers());
3557 }
3558
3559 unsigned getIndexTypeCVRQualifiers() const {
3560 return ArrayTypeBits.IndexTypeQuals;
3561 }
3562
3563 static bool classof(const Type *T) {
3564 return T->getTypeClass() == ConstantArray ||
3565 T->getTypeClass() == VariableArray ||
3566 T->getTypeClass() == IncompleteArray ||
3567 T->getTypeClass() == DependentSizedArray ||
3568 T->getTypeClass() == ArrayParameter;
3569 }
3570};
3571
3572/// Represents the canonical version of C arrays with a specified constant size.
3573/// For example, the canonical type for 'int A[4 + 4*100]' is a
3574/// ConstantArrayType where the element type is 'int' and the size is 404.
3576 friend class ASTContext; // ASTContext creates these.
3577
3578 struct ExternalSize {
3579 ExternalSize(const llvm::APInt &Sz, const Expr *SE)
3580 : Size(Sz), SizeExpr(SE) {}
3581 llvm::APInt Size; // Allows us to unique the type.
3582 const Expr *SizeExpr;
3583 };
3584
3585 union {
3586 uint64_t Size;
3587 ExternalSize *SizePtr;
3588 };
3589
3590 ConstantArrayType(QualType Et, QualType Can, uint64_t Width, uint64_t Sz,
3591 ArraySizeModifier SM, unsigned TQ)
3592 : ArrayType(ConstantArray, Et, Can, SM, TQ, nullptr), Size(Sz) {
3593 ConstantArrayTypeBits.HasExternalSize = false;
3594 ConstantArrayTypeBits.SizeWidth = Width / 8;
3595 // The in-structure size stores the size in bytes rather than bits so we
3596 // drop the three least significant bits since they're always zero anyways.
3597 assert(Width < 0xFF && "Type width in bits must be less than 8 bits");
3598 }
3599
3600 ConstantArrayType(QualType Et, QualType Can, ExternalSize *SzPtr,
3601 ArraySizeModifier SM, unsigned TQ)
3602 : ArrayType(ConstantArray, Et, Can, SM, TQ, SzPtr->SizeExpr),
3603 SizePtr(SzPtr) {
3604 ConstantArrayTypeBits.HasExternalSize = true;
3605 ConstantArrayTypeBits.SizeWidth = 0;
3606
3607 assert((SzPtr->SizeExpr == nullptr || !Can.isNull()) &&
3608 "canonical constant array should not have size expression");
3609 }
3610
3611 static ConstantArrayType *Create(const ASTContext &Ctx, QualType ET,
3612 QualType Can, const llvm::APInt &Sz,
3613 const Expr *SzExpr, ArraySizeModifier SzMod,
3614 unsigned Qual);
3615
3616protected:
3618 : ArrayType(Tc, ATy->getElementType(), Can, ATy->getSizeModifier(),
3619 ATy->getIndexTypeQualifiers().getAsOpaqueValue(), nullptr) {
3620 ConstantArrayTypeBits.HasExternalSize =
3621 ATy->ConstantArrayTypeBits.HasExternalSize;
3622 if (!ConstantArrayTypeBits.HasExternalSize) {
3623 ConstantArrayTypeBits.SizeWidth = ATy->ConstantArrayTypeBits.SizeWidth;
3624 Size = ATy->Size;
3625 } else
3626 SizePtr = ATy->SizePtr;
3627 }
3628
3629public:
3630 /// Return the constant array size as an APInt.
3631 llvm::APInt getSize() const {
3632 return ConstantArrayTypeBits.HasExternalSize
3633 ? SizePtr->Size
3634 : llvm::APInt(ConstantArrayTypeBits.SizeWidth * 8, Size);
3635 }
3636
3637 /// Return the bit width of the size type.
3638 unsigned getSizeBitWidth() const {
3639 return ConstantArrayTypeBits.HasExternalSize
3640 ? SizePtr->Size.getBitWidth()
3641 : static_cast<unsigned>(ConstantArrayTypeBits.SizeWidth * 8);
3642 }
3643
3644 /// Return true if the size is zero.
3645 bool isZeroSize() const {
3646 return ConstantArrayTypeBits.HasExternalSize ? SizePtr->Size.isZero()
3647 : 0 == Size;
3648 }
3649
3650 /// Return the size zero-extended as a uint64_t.
3651 uint64_t getZExtSize() const {
3652 return ConstantArrayTypeBits.HasExternalSize ? SizePtr->Size.getZExtValue()
3653 : Size;
3654 }
3655
3656 /// Return the size sign-extended as a uint64_t.
3657 int64_t getSExtSize() const {
3658 return ConstantArrayTypeBits.HasExternalSize ? SizePtr->Size.getSExtValue()
3659 : static_cast<int64_t>(Size);
3660 }
3661
3662 /// Return the size zero-extended to uint64_t or UINT64_MAX if the value is
3663 /// larger than UINT64_MAX.
3664 uint64_t getLimitedSize() const {
3665 return ConstantArrayTypeBits.HasExternalSize
3666 ? SizePtr->Size.getLimitedValue()
3667 : Size;
3668 }
3669
3670 /// Return a pointer to the size expression.
3671 const Expr *getSizeExpr() const {
3672 return ConstantArrayTypeBits.HasExternalSize ? SizePtr->SizeExpr : nullptr;
3673 }
3674
3675 bool isSugared() const { return false; }
3676 QualType desugar() const { return QualType(this, 0); }
3677
3678 /// Determine the number of bits required to address a member of
3679 // an array with the given element type and number of elements.
3680 static unsigned getNumAddressingBits(const ASTContext &Context,
3681 QualType ElementType,
3682 const llvm::APInt &NumElements);
3683
3684 unsigned getNumAddressingBits(const ASTContext &Context) const;
3685
3686 /// Determine the maximum number of active bits that an array's size
3687 /// can require, which limits the maximum size of the array.
3688 static unsigned getMaxSizeBits(const ASTContext &Context);
3689
3690 void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Ctx) {
3691 Profile(ID, Ctx, getElementType(), getZExtSize(), getSizeExpr(),
3692 getSizeModifier(), getIndexTypeCVRQualifiers());
3693 }
3694
3695 static void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Ctx,
3696 QualType ET, uint64_t ArraySize, const Expr *SizeExpr,
3697 ArraySizeModifier SizeMod, unsigned TypeQuals);
3698
3699 static bool classof(const Type *T) {
3700 return T->getTypeClass() == ConstantArray ||
3701 T->getTypeClass() == ArrayParameter;
3702 }
3703};
3704
3705/// Represents a constant array type that does not decay to a pointer when used
3706/// as a function parameter.
3708 friend class ASTContext; // ASTContext creates these.
3709
3711 : ConstantArrayType(ArrayParameter, ATy, CanTy) {}
3712
3713public:
3714 static bool classof(const Type *T) {
3715 return T->getTypeClass() == ArrayParameter;
3716 }
3717};
3718
3719/// Represents a C array with an unspecified size. For example 'int A[]' has
3720/// an IncompleteArrayType where the element type is 'int' and the size is
3721/// unspecified.
3723 friend class ASTContext; // ASTContext creates these.
3724
3726 ArraySizeModifier sm, unsigned tq)
3727 : ArrayType(IncompleteArray, et, can, sm, tq) {}
3728
3729public:
3730 friend class StmtIteratorBase;
3731
3732 bool isSugared() const { return false; }
3733 QualType desugar() const { return QualType(this, 0); }
3734
3735 static bool classof(const Type *T) {
3736 return T->getTypeClass() == IncompleteArray;
3737 }
3738
3739 void Profile(llvm::FoldingSetNodeID &ID) {
3740 Profile(ID, getElementType(), getSizeModifier(),
3741 getIndexTypeCVRQualifiers());
3742 }
3743
3744 static void Profile(llvm::FoldingSetNodeID &ID, QualType ET,
3745 ArraySizeModifier SizeMod, unsigned TypeQuals) {
3746 ID.AddPointer(ET.getAsOpaquePtr());
3747 ID.AddInteger(llvm::to_underlying(SizeMod));
3748 ID.AddInteger(TypeQuals);
3749 }
3750};
3751
3752/// Represents a C array with a specified size that is not an
3753/// integer-constant-expression. For example, 'int s[x+foo()]'.
3754/// Since the size expression is an arbitrary expression, we store it as such.
3755///
3756/// Note: VariableArrayType's aren't uniqued (since the expressions aren't) and
3757/// should not be: two lexically equivalent variable array types could mean
3758/// different things, for example, these variables do not have the same type
3759/// dynamically:
3760///
3761/// void foo(int x) {
3762/// int Y[x];
3763/// ++x;
3764/// int Z[x];
3765/// }
3767 friend class ASTContext; // ASTContext creates these.
3768
3769 /// An assignment-expression. VLA's are only permitted within
3770 /// a function block.
3771 Stmt *SizeExpr;
3772
3773 /// The range spanned by the left and right array brackets.
3774 SourceRange Brackets;
3775
3777 ArraySizeModifier sm, unsigned tq,
3778 SourceRange brackets)
3779 : ArrayType(VariableArray, et, can, sm, tq, e),
3780 SizeExpr((Stmt*) e), Brackets(brackets) {}
3781
3782public:
3783 friend class StmtIteratorBase;
3784
3786 // We use C-style casts instead of cast<> here because we do not wish
3787 // to have a dependency of Type.h on Stmt.h/Expr.h.
3788 return (Expr*) SizeExpr;
3789 }
3790
3791 SourceRange getBracketsRange() const { return Brackets; }
3792 SourceLocation getLBracketLoc() const { return Brackets.getBegin(); }
3793 SourceLocation getRBracketLoc() const { return Brackets.getEnd(); }
3794
3795 bool isSugared() const { return false; }
3796 QualType desugar() const { return QualType(this, 0); }
3797
3798 static bool classof(const Type *T) {
3799 return T->getTypeClass() == VariableArray;
3800 }
3801
3802 void Profile(llvm::FoldingSetNodeID &ID) {
3803 llvm_unreachable("Cannot unique VariableArrayTypes.");
3804 }
3805};
3806
3807/// Represents an array type in C++ whose size is a value-dependent expression.
3808///
3809/// For example:
3810/// \code
3811/// template<typename T, int Size>
3812/// class array {
3813/// T data[Size];
3814/// };
3815/// \endcode
3816///
3817/// For these types, we won't actually know what the array bound is
3818/// until template instantiation occurs, at which point this will
3819/// become either a ConstantArrayType or a VariableArrayType.
3821 friend class ASTContext; // ASTContext creates these.
3822
3823 /// An assignment expression that will instantiate to the
3824 /// size of the array.
3825 ///
3826 /// The expression itself might be null, in which case the array
3827 /// type will have its size deduced from an initializer.
3828 Stmt *SizeExpr;
3829
3830 /// The range spanned by the left and right array brackets.
3831 SourceRange Brackets;
3832
3834 ArraySizeModifier sm, unsigned tq,
3835 SourceRange brackets);
3836
3837public:
3838 friend class StmtIteratorBase;
3839
3841 // We use C-style casts instead of cast<> here because we do not wish
3842 // to have a dependency of Type.h on Stmt.h/Expr.h.
3843 return (Expr*) SizeExpr;
3844 }
3845
3846 SourceRange getBracketsRange() const { return Brackets; }
3847 SourceLocation getLBracketLoc() const { return Brackets.getBegin(); }
3848 SourceLocation getRBracketLoc() const { return Brackets.getEnd(); }
3849
3850 bool isSugared() const { return false; }
3851 QualType desugar() const { return QualType(this, 0); }
3852
3853 static bool classof(const Type *T) {
3854 return T->getTypeClass() == DependentSizedArray;
3855 }
3856
3857 void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context) {
3858 Profile(ID, Context, getElementType(),
3859 getSizeModifier(), getIndexTypeCVRQualifiers(), getSizeExpr());
3860 }
3861
3862 static void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context,
3863 QualType ET, ArraySizeModifier SizeMod,
3864 unsigned TypeQuals, Expr *E);
3865};
3866
3867/// Represents an extended address space qualifier where the input address space
3868/// value is dependent. Non-dependent address spaces are not represented with a
3869/// special Type subclass; they are stored on an ExtQuals node as part of a QualType.
3870///
3871/// For example:
3872/// \code
3873/// template<typename T, int AddrSpace>
3874/// class AddressSpace {
3875/// typedef T __attribute__((address_space(AddrSpace))) type;
3876/// }
3877/// \endcode
3878class DependentAddressSpaceType : public Type, public llvm::FoldingSetNode {
3879 friend class ASTContext;
3880
3881 Expr *AddrSpaceExpr;
3882 QualType PointeeType;
3883 SourceLocation loc;
3884
3886 Expr *AddrSpaceExpr, SourceLocation loc);
3887
3888public:
3889 Expr *getAddrSpaceExpr() const { return AddrSpaceExpr; }
3890 QualType getPointeeType() const { return PointeeType; }
3891 SourceLocation getAttributeLoc() const { return loc; }
3892
3893 bool isSugared() const { return false; }
3894 QualType desugar() const { return QualType(this, 0); }
3895
3896 static bool classof(const Type *T) {
3897 return T->getTypeClass() == DependentAddressSpace;
3898 }
3899
3900 void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context) {
3901 Profile(ID, Context, getPointeeType(), getAddrSpaceExpr());
3902 }
3903
3904 static void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context,
3905 QualType PointeeType, Expr *AddrSpaceExpr);
3906};
3907
3908/// Represents an extended vector type where either the type or size is
3909/// dependent.
3910///
3911/// For example:
3912/// \code
3913/// template<typename T, int Size>
3914/// class vector {
3915/// typedef T __attribute__((ext_vector_type(Size))) type;
3916/// }
3917/// \endcode
3918class DependentSizedExtVectorType : public Type, public llvm::FoldingSetNode {
3919 friend class ASTContext;
3920
3921 Expr *SizeExpr;
3922
3923 /// The element type of the array.
3924 QualType ElementType;
3925
3926 SourceLocation loc;
3927
3929 Expr *SizeExpr, SourceLocation loc);
3930
3931public:
3932 Expr *getSizeExpr() const { return SizeExpr; }
3933 QualType getElementType() const { return ElementType; }
3934 SourceLocation getAttributeLoc() const { return loc; }
3935
3936 bool isSugared() const { return false; }
3937 QualType desugar() const { return QualType(this, 0); }
3938
3939 static bool classof(const Type *T) {
3940 return T->getTypeClass() == DependentSizedExtVector;
3941 }
3942
3943 void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context) {
3944 Profile(ID, Context, getElementType(), getSizeExpr());
3945 }
3946
3947 static void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context,
3948 QualType ElementType, Expr *SizeExpr);
3949};
3950
3951enum class VectorKind {
3952 /// not a target-specific vector type
3953 Generic,
3954
3955 /// is AltiVec vector
3957
3958 /// is AltiVec 'vector Pixel'
3960
3961 /// is AltiVec 'vector bool ...'
3963
3964 /// is ARM Neon vector
3965 Neon,
3966
3967 /// is ARM Neon polynomial vector
3968 NeonPoly,
3969
3970 /// is AArch64 SVE fixed-length data vector
3972
3973 /// is AArch64 SVE fixed-length predicate vector
3975
3976 /// is RISC-V RVV fixed-length data vector
3978
3979 /// is RISC-V RVV fixed-length mask vector
3981};
3982
3983/// Represents a GCC generic vector type. This type is created using
3984/// __attribute__((vector_size(n)), where "n" specifies the vector size in
3985/// bytes; or from an Altivec __vector or vector declaration.
3986/// Since the constructor takes the number of vector elements, the
3987/// client is responsible for converting the size into the number of elements.
3988class VectorType : public Type, public llvm::FoldingSetNode {
3989protected:
3990 friend class ASTContext; // ASTContext creates these.
3991
3992 /// The element type of the vector.
3994
3995 VectorType(QualType vecType, unsigned nElements, QualType canonType,
3996 VectorKind vecKind);
3997
3998 VectorType(TypeClass tc, QualType vecType, unsigned nElements,
3999 QualType canonType, VectorKind vecKind);
4000
4001public:
4002 QualType getElementType() const { return ElementType; }
4003 unsigned getNumElements() const { return VectorTypeBits.NumElements; }
4004
4005 bool isSugared() const { return false; }
4006 QualType desugar() const { return QualType(this, 0); }
4007
4009 return VectorKind(VectorTypeBits.VecKind);
4010 }
4011
4012 void Profile(llvm::FoldingSetNodeID &ID) {
4013 Profile(ID, getElementType(), getNumElements(),
4014 getTypeClass(), getVectorKind());
4015 }
4016
4017 static void Profile(llvm::FoldingSetNodeID &ID, QualType ElementType,
4018 unsigned NumElements, TypeClass TypeClass,
4019 VectorKind VecKind) {
4020 ID.AddPointer(ElementType.getAsOpaquePtr());
4021 ID.AddInteger(NumElements);
4022 ID.AddInteger(TypeClass);
4023 ID.AddInteger(llvm::to_underlying(VecKind));
4024 }
4025
4026 static bool classof(const Type *T) {
4027 return T->getTypeClass() == Vector || T->getTypeClass() == ExtVector;
4028 }
4029};
4030
4031/// Represents a vector type where either the type or size is dependent.
4032////
4033/// For example:
4034/// \code
4035/// template<typename T, int Size>
4036/// class vector {
4037/// typedef T __attribute__((vector_size(Size))) type;
4038/// }
4039/// \endcode
4040class DependentVectorType : public Type, public llvm::FoldingSetNode {
4041 friend class ASTContext;
4042
4043 QualType ElementType;
4044 Expr *SizeExpr;
4046
4047 DependentVectorType(QualType ElementType, QualType CanonType, Expr *SizeExpr,
4048 SourceLocation Loc, VectorKind vecKind);
4049
4050public:
4051 Expr *getSizeExpr() const { return SizeExpr; }
4052 QualType getElementType() const { return ElementType; }
4055 return VectorKind(VectorTypeBits.VecKind);
4056 }
4057
4058 bool isSugared() const { return false; }
4059 QualType desugar() const { return QualType(this, 0); }
4060
4061 static bool classof(const Type *T) {
4062 return T->getTypeClass() == DependentVector;
4063 }
4064
4065 void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context) {
4066 Profile(ID, Context, getElementType(), getSizeExpr(), getVectorKind());
4067 }
4068
4069 static void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context,
4070 QualType ElementType, const Expr *SizeExpr,
4071 VectorKind VecKind);
4072};
4073
4074/// ExtVectorType - Extended vector type. This type is created using
4075/// __attribute__((ext_vector_type(n)), where "n" is the number of elements.
4076/// Unlike vector_size, ext_vector_type is only allowed on typedef's. This
4077/// class enables syntactic extensions, like Vector Components for accessing
4078/// points (as .xyzw), colors (as .rgba), and textures (modeled after OpenGL
4079/// Shading Language).
4081 friend class ASTContext; // ASTContext creates these.
4082
4083 ExtVectorType(QualType vecType, unsigned nElements, QualType canonType)
4084 : VectorType(ExtVector, vecType, nElements, canonType,
4085 VectorKind::Generic) {}
4086
4087public:
4088 static int getPointAccessorIdx(char c) {
4089 switch (c) {
4090 default: return -1;
4091 case 'x': case 'r': return 0;
4092 case 'y': case 'g': return 1;
4093 case 'z': case 'b': return 2;
4094 case 'w': case 'a': return 3;
4095 }
4096 }
4097
4098 static int getNumericAccessorIdx(char c) {
4099 switch (c) {
4100 default: return -1;
4101 case '0': return 0;
4102 case '1': return 1;
4103 case '2': return 2;
4104 case '3': return 3;
4105 case '4': return 4;
4106 case '5': return 5;
4107 case '6': return 6;
4108 case '7': return 7;
4109 case '8': return 8;
4110 case '9': return 9;
4111 case 'A':
4112 case 'a': return 10;
4113 case 'B':
4114 case 'b': return 11;
4115 case 'C':
4116 case 'c': return 12;
4117 case 'D':
4118 case 'd': return 13;
4119 case 'E':
4120 case 'e': return 14;
4121 case 'F':
4122 case 'f': return 15;
4123 }
4124 }
4125
4126 static int getAccessorIdx(char c, bool isNumericAccessor) {
4127 if (isNumericAccessor)
4128 return getNumericAccessorIdx(c);
4129 else
4130 return getPointAccessorIdx(c);
4131 }
4132
4133 bool isAccessorWithinNumElements(char c, bool isNumericAccessor) const {
4134 if (int idx = getAccessorIdx(c, isNumericAccessor)+1)
4135 return unsigned(idx-1) < getNumElements();
4136 return false;
4137 }
4138
4139 bool isSugared() const { return false; }
4140 QualType desugar() const { return QualType(this, 0); }
4141
4142 static bool classof(const Type *T) {
4143 return T->getTypeClass() == ExtVector;
4144 }
4145};
4146
4147/// Represents a matrix type, as defined in the Matrix Types clang extensions.
4148/// __attribute__((matrix_type(rows, columns))), where "rows" specifies
4149/// number of rows and "columns" specifies the number of columns.
4150class MatrixType : public Type, public llvm::FoldingSetNode {
4151protected:
4152 friend class ASTContext;
4153
4154 /// The element type of the matrix.
4156
4157 MatrixType(QualType ElementTy, QualType CanonElementTy);
4158
4159 MatrixType(TypeClass TypeClass, QualType ElementTy, QualType CanonElementTy,
4160 const Expr *RowExpr = nullptr, const Expr *ColumnExpr = nullptr);
4161
4162public:
4163 /// Returns type of the elements being stored in the matrix
4164 QualType getElementType() const { return ElementType; }
4165
4166 /// Valid elements types are the following:
4167 /// * an integer type (as in C23 6.2.5p22), but excluding enumerated types
4168 /// and _Bool
4169 /// * the standard floating types float or double
4170 /// * a half-precision floating point type, if one is supported on the target
4172 return T->isDependentType() ||
4173 (T->isRealType() && !T->isBooleanType() && !T->isEnumeralType());
4174 }
4175
4176 bool isSugared() const { return false; }
4177 QualType desugar() const { return QualType(this, 0); }
4178
4179 static bool classof(const Type *T) {
4180 return T->getTypeClass() == ConstantMatrix ||
4181 T->getTypeClass() == DependentSizedMatrix;
4182 }
4183};
4184
4185/// Represents a concrete matrix type with constant number of rows and columns
4186class ConstantMatrixType final : public MatrixType {
4187protected:
4188 friend class ASTContext;
4189
4190 /// Number of rows and columns.
4191 unsigned NumRows;
4192 unsigned NumColumns;
4193
4194 static constexpr unsigned MaxElementsPerDimension = (1 << 20) - 1;
4195
4196 ConstantMatrixType(QualType MatrixElementType, unsigned NRows,
4197 unsigned NColumns, QualType CanonElementType);
4198
4199 ConstantMatrixType(TypeClass typeClass, QualType MatrixType, unsigned NRows,
4200 unsigned NColumns, QualType CanonElementType);
4201
4202public:
4203 /// Returns the number of rows in the matrix.
4204 unsigned getNumRows() const { return NumRows; }
4205
4206 /// Returns the number of columns in the matrix.
4207 unsigned getNumColumns() const { return NumColumns; }
4208
4209 /// Returns the number of elements required to embed the matrix into a vector.
4210 unsigned getNumElementsFlattened() const {
4211 return getNumRows() * getNumColumns();
4212 }
4213
4214 /// Returns true if \p NumElements is a valid matrix dimension.
4215 static constexpr bool isDimensionValid(size_t NumElements) {
4216 return NumElements > 0 && NumElements <= MaxElementsPerDimension;
4217 }
4218
4219 /// Returns the maximum number of elements per dimension.
4220 static constexpr unsigned getMaxElementsPerDimension() {
4221 return MaxElementsPerDimension;
4222 }
4223
4224 void Profile(llvm::FoldingSetNodeID &ID) {
4225 Profile(ID, getElementType(), getNumRows(), getNumColumns(),
4226 getTypeClass());
4227 }
4228
4229 static void Profile(llvm::FoldingSetNodeID &ID, QualType ElementType,
4230 unsigned NumRows, unsigned NumColumns,
4232 ID.AddPointer(ElementType.getAsOpaquePtr());
4233 ID.AddInteger(NumRows);
4234 ID.AddInteger(NumColumns);
4235 ID.AddInteger(TypeClass);
4236 }
4237
4238 static bool classof(const Type *T) {
4239 return T->getTypeClass() == ConstantMatrix;
4240 }
4241};
4242
4243/// Represents a matrix type where the type and the number of rows and columns
4244/// is dependent on a template.
4246 friend class ASTContext;
4247
4248 Expr *RowExpr;
4249 Expr *ColumnExpr;
4250
4251 SourceLocation loc;
4252
4253 DependentSizedMatrixType(QualType ElementType, QualType CanonicalType,
4254 Expr *RowExpr, Expr *ColumnExpr, SourceLocation loc);
4255
4256public:
4257 Expr *getRowExpr() const { return RowExpr; }
4258 Expr *getColumnExpr() const { return ColumnExpr; }
4259 SourceLocation getAttributeLoc() const { return loc; }
4260
4261 static bool classof(const Type *T) {
4262 return T->getTypeClass() == DependentSizedMatrix;
4263 }
4264
4265 void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context) {
4266 Profile(ID, Context, getElementType(), getRowExpr(), getColumnExpr());
4267 }
4268
4269 static void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context,
4270 QualType ElementType, Expr *RowExpr, Expr *ColumnExpr);
4271};
4272
4273/// FunctionType - C99 6.7.5.3 - Function Declarators. This is the common base
4274/// class of FunctionNoProtoType and FunctionProtoType.
4275class FunctionType : public Type {
4276 // The type returned by the function.
4277 QualType ResultType;
4278
4279public:
4280 /// Interesting information about a specific parameter that can't simply
4281 /// be reflected in parameter's type. This is only used by FunctionProtoType
4282 /// but is in FunctionType to make this class available during the
4283 /// specification of the bases of FunctionProtoType.
4284 ///
4285 /// It makes sense to model language features this way when there's some
4286 /// sort of parameter-specific override (such as an attribute) that
4287 /// affects how the function is called. For example, the ARC ns_consumed
4288 /// attribute changes whether a parameter is passed at +0 (the default)
4289 /// or +1 (ns_consumed). This must be reflected in the function type,
4290 /// but isn't really a change to the parameter type.
4291 ///
4292 /// One serious disadvantage of modelling language features this way is
4293 /// that they generally do not work with language features that attempt
4294 /// to destructure types. For example, template argument deduction will
4295 /// not be able to match a parameter declared as
4296 /// T (*)(U)
4297 /// against an argument of type
4298 /// void (*)(__attribute__((ns_consumed)) id)
4299 /// because the substitution of T=void, U=id into the former will
4300 /// not produce the latter.
4302 enum {
4303 ABIMask = 0x0F,
4304 IsConsumed = 0x10,
4305 HasPassObjSize = 0x20,
4306 IsNoEscape = 0x40,
4307 };
4308 unsigned char Data = 0;
4309
4310 public:
4311 ExtParameterInfo() = default;
4312
4313 /// Return the ABI treatment of this parameter.
4314 ParameterABI getABI() const { return ParameterABI(Data & ABIMask); }
4316 ExtParameterInfo copy = *this;
4317 copy.Data = (copy.Data & ~ABIMask) | unsigned(kind);
4318 return copy;
4319 }
4320
4321 /// Is this parameter considered "consumed" by Objective-C ARC?
4322 /// Consumed parameters must have retainable object type.
4323 bool isConsumed() const { return (Data & IsConsumed); }
4324 ExtParameterInfo withIsConsumed(bool consumed) const {
4325 ExtParameterInfo copy = *this;
4326 if (consumed)
4327 copy.Data |= IsConsumed;
4328 else
4329 copy.Data &= ~IsConsumed;
4330 return copy;
4331 }
4332
4333 bool hasPassObjectSize() const { return Data & HasPassObjSize; }
4335 ExtParameterInfo Copy = *this;
4336 Copy.Data |= HasPassObjSize;
4337 return Copy;
4338 }
4339
4340 bool isNoEscape() const { return Data & IsNoEscape; }
4341 ExtParameterInfo withIsNoEscape(bool NoEscape) const {
4342 ExtParameterInfo Copy = *this;
4343 if (NoEscape)
4344 Copy.Data |= IsNoEscape;
4345 else
4346 Copy.Data &= ~IsNoEscape;
4347 return Copy;
4348 }
4349
4350 unsigned char getOpaqueValue() const { return Data; }
4351 static ExtParameterInfo getFromOpaqueValue(unsigned char data) {
4352 ExtParameterInfo result;
4353 result.Data = data;
4354 return result;
4355 }
4356
4358 return lhs.Data == rhs.Data;
4359 }
4360
4362 return lhs.Data != rhs.Data;
4363 }
4364 };
4365
4366 /// A class which abstracts out some details necessary for
4367 /// making a call.
4368 ///
4369 /// It is not actually used directly for storing this information in
4370 /// a FunctionType, although FunctionType does currently use the
4371 /// same bit-pattern.
4372 ///
4373 // If you add a field (say Foo), other than the obvious places (both,
4374 // constructors, compile failures), what you need to update is
4375 // * Operator==
4376 // * getFoo
4377 // * withFoo
4378 // * functionType. Add Foo, getFoo.
4379 // * ASTContext::getFooType
4380 // * ASTContext::mergeFunctionTypes
4381 // * FunctionNoProtoType::Profile
4382 // * FunctionProtoType::Profile
4383 // * TypePrinter::PrintFunctionProto
4384 // * AST read and write
4385 // * Codegen
4386 class ExtInfo {
4387 friend class FunctionType;
4388
4389 // Feel free to rearrange or add bits, but if you go over 16, you'll need to
4390 // adjust the Bits field below, and if you add bits, you'll need to adjust
4391 // Type::FunctionTypeBitfields::ExtInfo as well.
4392
4393 // | CC |noreturn|produces|nocallersavedregs|regparm|nocfcheck|cmsenscall|
4394 // |0 .. 4| 5 | 6 | 7 |8 .. 10| 11 | 12 |
4395 //
4396 // regparm is either 0 (no regparm attribute) or the regparm value+1.
4397 enum { CallConvMask = 0x1F };
4398 enum { NoReturnMask = 0x20 };
4399 enum { ProducesResultMask = 0x40 };
4400 enum { NoCallerSavedRegsMask = 0x80 };
4401 enum {
4402 RegParmMask = 0x700,
4403 RegParmOffset = 8
4404 };
4405 enum { NoCfCheckMask = 0x800 };
4406 enum { CmseNSCallMask = 0x1000 };
4407 uint16_t Bits = CC_C;
4408
4409 ExtInfo(unsigned Bits) : Bits(static_cast<uint16_t>(Bits)) {}
4410
4411 public:
4412 // Constructor with no defaults. Use this when you know that you
4413 // have all the elements (when reading an AST file for example).
4414 ExtInfo(bool noReturn, bool hasRegParm, unsigned regParm, CallingConv cc,
4415 bool producesResult, bool noCallerSavedRegs, bool NoCfCheck,
4416 bool cmseNSCall) {
4417 assert((!hasRegParm || regParm < 7) && "Invalid regparm value");
4418 Bits = ((unsigned)cc) | (noReturn ? NoReturnMask : 0) |
4419 (producesResult ? ProducesResultMask : 0) |
4420 (noCallerSavedRegs ? NoCallerSavedRegsMask : 0) |
4421 (hasRegParm ? ((regParm + 1) << RegParmOffset) : 0) |
4422 (NoCfCheck ? NoCfCheckMask : 0) |
4423 (cmseNSCall ? CmseNSCallMask : 0);
4424 }
4425
4426 // Constructor with all defaults. Use when for example creating a
4427 // function known to use defaults.
4428 ExtInfo() = default;
4429
4430 // Constructor with just the calling convention, which is an important part
4431 // of the canonical type.
4432 ExtInfo(CallingConv CC) : Bits(CC) {}
4433
4434 bool getNoReturn() const { return Bits & NoReturnMask; }
4435 bool getProducesResult() const { return Bits & ProducesResultMask; }
4436 bool getCmseNSCall() const { return Bits & CmseNSCallMask; }
4437 bool getNoCallerSavedRegs() const { return Bits & NoCallerSavedRegsMask; }
4438 bool getNoCfCheck() const { return Bits & NoCfCheckMask; }
4439 bool getHasRegParm() const { return ((Bits & RegParmMask) >> RegParmOffset) != 0; }
4440
4441 unsigned getRegParm() const {
4442 unsigned RegParm = (Bits & RegParmMask) >> RegParmOffset;
4443 if (RegParm > 0)
4444 --RegParm;
4445 return RegParm;
4446 }
4447
4448 CallingConv getCC() const { return CallingConv(Bits & CallConvMask); }
4449
4450 bool operator==(ExtInfo Other) const {
4451 return Bits == Other.Bits;
4452 }
4453 bool operator!=(ExtInfo Other) const {
4454 return Bits != Other.Bits;
4455 }
4456
4457 // Note that we don't have setters. That is by design, use
4458 // the following with methods instead of mutating these objects.
4459
4460 ExtInfo withNoReturn(bool noReturn) const {
4461 if (noReturn)
4462 return ExtInfo(Bits | NoReturnMask);
4463 else
4464 return ExtInfo(Bits & ~NoReturnMask);
4465 }
4466
4467 ExtInfo withProducesResult(bool producesResult) const {
4468 if (producesResult)
4469 return ExtInfo(Bits | ProducesResultMask);
4470 else
4471 return ExtInfo(Bits & ~ProducesResultMask);
4472 }
4473
4474 ExtInfo withCmseNSCall(bool cmseNSCall) const {
4475 if (cmseNSCall)
4476 return ExtInfo(Bits | CmseNSCallMask);
4477 else
4478 return ExtInfo(Bits & ~CmseNSCallMask);
4479 }
4480
4481 ExtInfo withNoCallerSavedRegs(bool noCallerSavedRegs) const {
4482 if (noCallerSavedRegs)
4483 return ExtInfo(Bits | NoCallerSavedRegsMask);
4484 else
4485 return ExtInfo(Bits & ~NoCallerSavedRegsMask);
4486 }
4487
4488 ExtInfo withNoCfCheck(bool noCfCheck) const {
4489 if (noCfCheck)
4490 return ExtInfo(Bits | NoCfCheckMask);
4491 else
4492 return ExtInfo(Bits & ~NoCfCheckMask);
4493 }
4494
4495 ExtInfo withRegParm(unsigned RegParm) const {
4496 assert(RegParm < 7 && "Invalid regparm value");
4497 return ExtInfo((Bits & ~RegParmMask) |
4498 ((RegParm + 1) << RegParmOffset));
4499 }
4500
4502 return ExtInfo((Bits & ~CallConvMask) | (unsigned) cc);
4503 }
4504
4505 void Profile(llvm::FoldingSetNodeID &ID) const {
4506 ID.AddInteger(Bits);
4507 }
4508 };
4509
4510 /// A simple holder for a QualType representing a type in an
4511 /// exception specification. Unfortunately needed by FunctionProtoType
4512 /// because TrailingObjects cannot handle repeated types.
4514
4515 /// A simple holder for various uncommon bits which do not fit in
4516 /// FunctionTypeBitfields. Aligned to alignof(void *) to maintain the
4517 /// alignment of subsequent objects in TrailingObjects.
4518 struct alignas(void *) FunctionTypeExtraBitfields {
4519 /// The number of types in the exception specification.
4520 /// A whole unsigned is not needed here and according to
4521 /// [implimits] 8 bits would be enough here.
4522 unsigned NumExceptionType : 10;
4523
4524 LLVM_PREFERRED_TYPE(bool)
4525 unsigned HasArmTypeAttributes : 1;
4526
4527 LLVM_PREFERRED_TYPE(bool)
4528 unsigned EffectsHaveConditions : 1;
4529 unsigned NumFunctionEffects : 4;
4530
4532 : NumExceptionType(0), HasArmTypeAttributes(false),
4533 EffectsHaveConditions(false), NumFunctionEffects(0) {}
4534 };
4535
4536 /// The AArch64 SME ACLE (Arm C/C++ Language Extensions) define a number
4537 /// of function type attributes that can be set on function types, including
4538 /// function pointers.
4540 SME_NormalFunction = 0,
4541 SME_PStateSMEnabledMask = 1 << 0,
4542 SME_PStateSMCompatibleMask = 1 << 1,
4543
4544 // Describes the value of the state using ArmStateValue.
4545 SME_ZAShift = 2,
4546 SME_ZAMask = 0b111 << SME_ZAShift,
4547 SME_ZT0Shift = 5,
4548 SME_ZT0Mask = 0b111 << SME_ZT0Shift,
4549
4550 SME_AttributeMask =
4551 0b111'111'11 // We can't support more than 8 bits because of
4552 // the bitmask in FunctionTypeExtraBitfields.
4554
4555 enum ArmStateValue : unsigned {
4556 ARM_None = 0,
4557 ARM_Preserves = 1,
4558 ARM_In = 2,
4559 ARM_Out = 3,
4560 ARM_InOut = 4,
4561 };
4562
4563 static ArmStateValue getArmZAState(unsigned AttrBits) {
4564 return (ArmStateValue)((AttrBits & SME_ZAMask) >> SME_ZAShift);
4565 }
4566
4567 static ArmStateValue getArmZT0State(unsigned AttrBits) {
4568 return (ArmStateValue)((AttrBits & SME_ZT0Mask) >> SME_ZT0Shift);
4569 }
4570
4571 /// A holder for Arm type attributes as described in the Arm C/C++
4572 /// Language extensions which are not particularly common to all
4573 /// types and therefore accounted separately from FunctionTypeBitfields.
4574 struct alignas(void *) FunctionTypeArmAttributes {
4575 /// Any AArch64 SME ACLE type attributes that need to be propagated
4576 /// on declarations and function pointers.
4578
4579 FunctionTypeArmAttributes() : AArch64SMEAttributes(SME_NormalFunction) {}
4580 };
4581
4582protected:
4585 : Type(tc, Canonical, Dependence), ResultType(res) {
4586 FunctionTypeBits.ExtInfo = Info.Bits;
4587 }
4588
4590 if (isFunctionProtoType())
4591 return Qualifiers::fromFastMask(FunctionTypeBits.FastTypeQuals);
4592
4593 return Qualifiers();
4594 }
4595
4596public:
4597 QualType getReturnType() const { return ResultType; }
4598
4599 bool getHasRegParm() const { return getExtInfo().getHasRegParm(); }
4600 unsigned getRegParmType() const { return getExtInfo().getRegParm(); }
4601
4602 /// Determine whether this function type includes the GNU noreturn
4603 /// attribute. The C++11 [[noreturn]] attribute does not affect the function
4604 /// type.
4605 bool getNoReturnAttr() const { return getExtInfo().getNoReturn(); }
4606
4607 bool getCmseNSCallAttr() const { return getExtInfo().getCmseNSCall(); }
4608 CallingConv getCallConv() const { return getExtInfo().getCC(); }
4609 ExtInfo getExtInfo() const { return ExtInfo(FunctionTypeBits.ExtInfo); }
4610
4611 static_assert((~Qualifiers::FastMask & Qualifiers::CVRMask) == 0,
4612 "Const, volatile and restrict are assumed to be a subset of "
4613 "the fast qualifiers.");
4614
4615 bool isConst() const { return getFastTypeQuals().hasConst(); }
4616 bool isVolatile() const { return getFastTypeQuals().hasVolatile(); }
4617 bool isRestrict() const { return getFastTypeQuals().hasRestrict(); }
4618
4619 /// Determine the type of an expression that calls a function of
4620 /// this type.
4621 QualType getCallResultType(const ASTContext &Context) const {
4622 return getReturnType().getNonLValueExprType(Context);
4623 }
4624
4625 static StringRef getNameForCallConv(CallingConv CC);
4626
4627 static bool classof(const Type *T) {
4628 return T->getTypeClass() == FunctionNoProto ||
4629 T->getTypeClass() == FunctionProto;
4630 }
4631};
4632
4633/// Represents a K&R-style 'int foo()' function, which has
4634/// no information available about its arguments.
4635class FunctionNoProtoType : public FunctionType, public llvm::FoldingSetNode {
4636 friend class ASTContext; // ASTContext creates these.
4637
4638 FunctionNoProtoType(QualType Result, QualType Canonical, ExtInfo Info)
4639 : FunctionType(FunctionNoProto, Result, Canonical,
4640 Result->getDependence() &
4641 ~(TypeDependence::DependentInstantiation |
4642 TypeDependence::UnexpandedPack),
4643 Info) {}
4644
4645public:
4646 // No additional state past what FunctionType provides.
4647
4648 bool isSugared() const { return false; }
4649 QualType desugar() const { return QualType(this, 0); }
4650
4651 void Profile(llvm::FoldingSetNodeID &ID) {
4652 Profile(ID, getReturnType(), getExtInfo());
4653 }
4654
4655 static void Profile(llvm::FoldingSetNodeID &ID, QualType ResultType,
4656 ExtInfo Info) {
4657 Info.Profile(ID);
4658 ID.AddPointer(ResultType.getAsOpaquePtr());
4659 }
4660
4661 static bool classof(const Type *T) {
4662 return T->getTypeClass() == FunctionNoProto;
4663 }
4664};
4665
4666// ------------------------------------------------------------------------------
4667
4668/// Represents an abstract function effect, using just an enumeration describing
4669/// its kind.
4671public:
4672 /// Identifies the particular effect.
4673 enum class Kind : uint8_t {
4674 None = 0,
4675 NonBlocking = 1,
4676 NonAllocating = 2,
4677 Blocking = 3,
4678 Allocating = 4
4679 };
4680
4681 /// Flags describing some behaviors of the effect.
4684 // Can verification inspect callees' implementations? (e.g. nonblocking:
4685 // yes, tcb+types: no). This also implies the need for 2nd-pass
4686 // verification.
4687 FE_InferrableOnCallees = 0x1,
4688
4689 // Language constructs which effects can diagnose as disallowed.
4690 FE_ExcludeThrow = 0x2,
4691 FE_ExcludeCatch = 0x4,
4692 FE_ExcludeObjCMessageSend = 0x8,
4693 FE_ExcludeStaticLocalVars = 0x10,
4694 FE_ExcludeThreadLocalVars = 0x20
4696
4697private:
4698 LLVM_PREFERRED_TYPE(Kind)
4699 unsigned FKind : 3;
4700
4701 // Expansion: for hypothetical TCB+types, there could be one Kind for TCB,
4702 // then ~16(?) bits "SubKind" to map to a specific named TCB. SubKind would
4703 // be considered for uniqueness.
4704
4705public:
4707
4708 explicit FunctionEffect(Kind K) : FKind(unsigned(K)) {}
4709
4710 /// The kind of the effect.
4711 Kind kind() const { return Kind(FKind); }
4712
4713 /// Return the opposite kind, for effects which have opposites.
4714 Kind oppositeKind() const;
4715
4716 /// For serialization.
4717 uint32_t toOpaqueInt32() const { return FKind; }
4719 return FunctionEffect(Kind(Value));
4720 }
4721
4722 /// Flags describing some behaviors of the effect.
4723 Flags flags() const {
4724 switch (kind()) {
4725 case Kind::NonBlocking:
4726 return FE_InferrableOnCallees | FE_ExcludeThrow | FE_ExcludeCatch |
4727 FE_ExcludeObjCMessageSend | FE_ExcludeStaticLocalVars |
4728 FE_ExcludeThreadLocalVars;
4729 case Kind::NonAllocating:
4730 // Same as NonBlocking, except without FE_ExcludeStaticLocalVars.
4731 return FE_InferrableOnCallees | FE_ExcludeThrow | FE_ExcludeCatch |
4732 FE_ExcludeObjCMessageSend | FE_ExcludeThreadLocalVars;
4733 case Kind::Blocking:
4734 case Kind::Allocating:
4735 return 0;
4736 case Kind::None:
4737 break;
4738 }
4739 llvm_unreachable("unknown effect kind");
4740 }
4741
4742 /// The description printed in diagnostics, e.g. 'nonblocking'.
4743 StringRef name() const;
4744
4745 /// Return true if the effect is allowed to be inferred o