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