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