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

source code of clang/include/clang/AST/Type.h