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