clang 23.0.0git
Pointer.cpp
Go to the documentation of this file.
1//===--- Pointer.cpp - Types for the constexpr VM ---------------*- 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#include "Pointer.h"
10#include "Boolean.h"
11#include "Char.h"
12#include "Context.h"
13#include "Floating.h"
14#include "Function.h"
15#include "InitMap.h"
16#include "Integral.h"
17#include "InterpBlock.h"
18#include "MemberPointer.h"
19#include "PrimType.h"
20#include "Record.h"
21#include "clang/AST/Expr.h"
22#include "clang/AST/ExprCXX.h"
24
25using namespace clang;
26using namespace clang::interp;
27
29 : Pointer(Pointee, Pointee->getDescriptor()->getMetadataSize(),
30 Pointee->getDescriptor()->getMetadataSize()) {}
31
32Pointer::Pointer(Block *Pointee, uint64_t BaseAndOffset)
33 : Pointer(Pointee, BaseAndOffset, BaseAndOffset) {}
34
35Pointer::Pointer(Block *Pointee, unsigned Base, uint64_t Offset)
36 : Offset(Offset), StorageKind(Storage::Block) {
37 assert(Pointee);
38 assert((Base == RootPtrMark || Base % alignof(void *) == 0) && "wrong base");
39 assert(Base >= Pointee->getDescriptor()->getMetadataSize());
40
41 BS = {Pointee, Base, nullptr, nullptr};
42 Pointee->addPointer(this);
43}
44
46 : Offset(P.Offset), StorageKind(P.StorageKind) {
47 switch (StorageKind) {
48 case Storage::Int:
49 Int = P.Int;
50 break;
51 case Storage::Block:
52 BS = P.BS;
53 if (BS.Pointee)
54 BS.Pointee->addPointer(this);
55 break;
56 case Storage::Fn:
57 Fn = P.Fn;
58 break;
59 case Storage::Typeid:
60 Typeid = P.Typeid;
61 break;
62 }
63}
64
65Pointer::Pointer(Pointer &&P) : Offset(P.Offset), StorageKind(P.StorageKind) {
66 switch (StorageKind) {
67 case Storage::Int:
68 Int = P.Int;
69 break;
70 case Storage::Block:
71 BS = P.BS;
72 if (BS.Pointee)
73 BS.Pointee->replacePointer(&P, this);
74 break;
75 case Storage::Fn:
76 Fn = P.Fn;
77 break;
78 case Storage::Typeid:
79 Typeid = P.Typeid;
80 break;
81 }
82}
83
85 if (!isBlockPointer())
86 return;
87
88 if (Block *Pointee = BS.Pointee) {
89 Pointee->removePointer(this);
90 BS.Pointee = nullptr;
91 Pointee->cleanup();
92 }
93}
94
96 // If the current storage type is Block, we need to remove
97 // this pointer from the block.
98 if (isBlockPointer()) {
99 if (P.isBlockPointer() && this->block() == P.block()) {
100 Offset = P.Offset;
101 BS.Base = P.BS.Base;
102 return *this;
103 }
104
105 if (Block *Pointee = BS.Pointee) {
106 Pointee->removePointer(this);
107 BS.Pointee = nullptr;
108 Pointee->cleanup();
109 }
110 }
111
112 StorageKind = P.StorageKind;
113 Offset = P.Offset;
114
115 switch (StorageKind) {
116 case Storage::Int:
117 Int = P.Int;
118 break;
119 case Storage::Block:
120 BS = P.BS;
121
122 if (BS.Pointee)
123 BS.Pointee->addPointer(this);
124 break;
125 case Storage::Fn:
126 Fn = P.Fn;
127 break;
128 case Storage::Typeid:
129 Typeid = P.Typeid;
130 }
131 return *this;
132}
133
135 // If the current storage type is Block, we need to remove
136 // this pointer from the block.
137 if (isBlockPointer()) {
138 if (P.isBlockPointer() && this->block() == P.block()) {
139 Offset = P.Offset;
140 BS.Base = P.BS.Base;
141 return *this;
142 }
143
144 if (Block *Pointee = BS.Pointee) {
145 Pointee->removePointer(this);
146 BS.Pointee = nullptr;
147 Pointee->cleanup();
148 }
149 }
150
151 StorageKind = P.StorageKind;
152 Offset = P.Offset;
153
154 switch (StorageKind) {
155 case Storage::Int:
156 Int = P.Int;
157 break;
158 case Storage::Block:
159 BS = P.BS;
160
161 if (BS.Pointee)
162 BS.Pointee->addPointer(this);
163 break;
164 case Storage::Fn:
165 Fn = P.Fn;
166 break;
167 case Storage::Typeid:
168 Typeid = P.Typeid;
169 }
170 return *this;
171}
172
175
176 if (isZero())
177 return APValue(static_cast<const Expr *>(nullptr), CharUnits::Zero(), Path,
178 /*IsOnePastEnd=*/false, /*IsNullPtr=*/true);
179 if (isIntegralPointer())
180 return APValue(static_cast<const Expr *>(nullptr),
182 Path,
183 /*IsOnePastEnd=*/false, /*IsNullPtr=*/false);
184 if (isFunctionPointer()) {
186 if (const FunctionDecl *FD = FP.Func->getDecl())
187 return APValue(FD, CharUnits::fromQuantity(Offset), {},
188 /*OnePastTheEnd=*/false, /*IsNull=*/false);
189 return APValue(FP.Func->getExpr(), CharUnits::fromQuantity(Offset), {},
190 /*OnePastTheEnd=*/false, /*IsNull=*/false);
191 }
192
193 if (isTypeidPointer()) {
196 TypeInfo, QualType(Typeid.TypeInfoType, 0)),
197 CharUnits::Zero(), {},
198 /*OnePastTheEnd=*/false, /*IsNull=*/false);
199 }
200
201 // Build the lvalue base from the block.
202 const Descriptor *Desc = getDeclDesc();
204 if (const auto *VD = Desc->asValueDecl())
205 Base = VD;
206 else if (const auto *E = Desc->asExpr()) {
207 if (block()->isDynamic()) {
208 QualType AllocatedType = getDeclPtr().getFieldDesc()->getDataType(ASTCtx);
209 DynamicAllocLValue DA(*block()->DynAllocId);
210 Base = APValue::LValueBase::getDynamicAlloc(DA, AllocatedType);
211 } else {
212 Base = E;
213 }
214 } else
215 llvm_unreachable("Invalid allocation type");
216
217 if (isUnknownSizeArray())
218 return APValue(Base, CharUnits::Zero(), Path,
219 /*IsOnePastEnd=*/isOnePastEnd(), /*IsNullPtr=*/false);
220
221 CharUnits Offset = CharUnits::Zero();
222
223 auto getFieldOffset = [&](const FieldDecl *FD) -> CharUnits {
224 // This shouldn't happen, but if it does, don't crash inside
225 // getASTRecordLayout.
226 if (FD->getParent()->isInvalidDecl())
227 return CharUnits::Zero();
228 const ASTRecordLayout &Layout = ASTCtx.getASTRecordLayout(FD->getParent());
229 unsigned FieldIndex = FD->getFieldIndex();
230 return ASTCtx.toCharUnitsFromBits(Layout.getFieldOffset(FieldIndex));
231 };
232
233 bool UsePath = true;
234 if (const ValueDecl *VD = getDeclDesc()->asValueDecl();
235 VD && VD->getType()->isReferenceType())
236 UsePath = false;
237
238 // Build the path into the object.
239 bool OnePastEnd = isOnePastEnd() && !isZeroSizeArray();
240 Pointer Ptr = *this;
241 while (Ptr.isField() || Ptr.isArrayElement()) {
242
243 if (Ptr.isArrayRoot()) {
244 // An array root may still be an array element itself.
245 if (Ptr.isArrayElement()) {
246 Ptr = Ptr.expand();
247 const Descriptor *Desc = Ptr.getFieldDesc();
248 unsigned Index = Ptr.getIndex();
249 QualType ElemType = Desc->getElemQualType();
250 Offset += (Index * ASTCtx.getTypeSizeInChars(ElemType));
251 if (Ptr.getArray().getFieldDesc()->IsArray)
252 Path.push_back(APValue::LValuePathEntry::ArrayIndex(Index));
253 Ptr = Ptr.getArray();
254 } else {
255 const Descriptor *Desc = Ptr.getFieldDesc();
256 const auto *Dcl = Desc->asDecl();
257 Path.push_back(APValue::LValuePathEntry({Dcl, /*IsVirtual=*/false}));
258
259 if (const auto *FD = dyn_cast_if_present<FieldDecl>(Dcl))
260 Offset += getFieldOffset(FD);
261
262 Ptr = Ptr.getBase();
263 }
264 } else if (Ptr.isArrayElement()) {
265 Ptr = Ptr.expand();
266 const Descriptor *Desc = Ptr.getFieldDesc();
267 unsigned Index;
268 if (Ptr.isOnePastEnd()) {
269 Index = Ptr.getArray().getNumElems();
270 OnePastEnd = false;
271 } else
272 Index = Ptr.getIndex();
273
274 QualType ElemType = Desc->getElemQualType();
275 if (const auto *RD = ElemType->getAsRecordDecl();
276 RD && !RD->getDefinition()) {
277 // Ignore this for the offset.
278 } else {
279 Offset += (Index * ASTCtx.getTypeSizeInChars(ElemType));
280 }
281 if (Ptr.getArray().getFieldDesc()->IsArray)
282 Path.push_back(APValue::LValuePathEntry::ArrayIndex(Index));
283 Ptr = Ptr.getArray();
284 } else {
285 const Descriptor *Desc = Ptr.getFieldDesc();
286
287 // Create a path entry for the field.
288 if (const auto *BaseOrMember = Desc->asDecl()) {
289 bool IsVirtual = false;
290 if (const auto *FD = dyn_cast<FieldDecl>(BaseOrMember)) {
291 Ptr = Ptr.getBase();
292 Offset += getFieldOffset(FD);
293 } else if (const auto *RD = dyn_cast<CXXRecordDecl>(BaseOrMember)) {
294 IsVirtual = Ptr.isVirtualBaseClass();
295 Ptr = Ptr.getBase();
296 const Record *BaseRecord = Ptr.getRecord();
297
298 const ASTRecordLayout &Layout = ASTCtx.getASTRecordLayout(
299 cast<CXXRecordDecl>(BaseRecord->getDecl()));
300 if (IsVirtual)
301 Offset += Layout.getVBaseClassOffset(RD);
302 else
303 Offset += Layout.getBaseClassOffset(RD);
304
305 } else {
306 Ptr = Ptr.getBase();
307 }
308 Path.push_back(APValue::LValuePathEntry({BaseOrMember, IsVirtual}));
309 continue;
310 }
311 llvm_unreachable("Invalid field type");
312 }
313 }
314
315 // We assemble the LValuePath starting from the innermost pointer to the
316 // outermost one. SO in a.b.c, the first element in Path will refer to
317 // the field 'c', while later code expects it to refer to 'a'.
318 // Just invert the order of the elements.
319 std::reverse(Path.begin(), Path.end());
320
321 if (UsePath)
322 return APValue(Base, Offset, Path, OnePastEnd);
323
324 return APValue(Base, Offset, APValue::NoLValuePath());
325}
326
327void Pointer::print(llvm::raw_ostream &OS) const {
328 switch (StorageKind) {
329 case Storage::Block: {
330 const Block *B = BS.Pointee;
331 OS << "(Block) " << B << " {";
332
333 if (isRoot())
334 OS << "rootptr(" << BS.Base << "), ";
335 else
336 OS << BS.Base << ", ";
337
338 if (isElementPastEnd())
339 OS << "pastend, ";
340 else
341 OS << Offset << ", ";
342
343 if (B)
344 OS << B->getSize();
345 else
346 OS << "nullptr";
347 OS << "}";
348 } break;
349 case Storage::Int:
350 OS << "(Int) {";
351 OS << Int.Value << " + " << Offset << ", " << Int.Desc;
352 OS << "}";
353 break;
354 case Storage::Fn:
355 OS << "(Fn) { " << Fn.Func << " + " << Offset << " }";
356 break;
357 case Storage::Typeid:
358 OS << "(Typeid) { " << (const void *)asTypeidPointer().TypePtr << ", "
359 << (const void *)asTypeidPointer().TypeInfoType << " + " << Offset
360 << "}";
361 }
362}
363
364/// Compute an offset that can be used to compare the pointer to another one
365/// with the same base. To get accurate results, we basically _have to_ compute
366/// the lvalue offset using the ASTRecordLayout.
367///
368/// FIXME: We're still mixing values from the record layout with our internal
369/// offsets, which will inevitably lead to cryptic errors.
371 switch (StorageKind) {
372 case Storage::Int:
373 return Int.Value + Offset;
374 case Storage::Block:
375 // See below.
376 break;
377 case Storage::Fn:
379 case Storage::Typeid:
380 return reinterpret_cast<uintptr_t>(asTypeidPointer().TypePtr) + Offset;
381 }
382
383 size_t Result = 0;
384 Pointer P = *this;
385 while (true) {
386 if (P.isVirtualBaseClass()) {
387 Result += getInlineDesc()->Offset;
388 P = P.getBase();
389 continue;
390 }
391
392 if (P.isBaseClass()) {
393 if (P.getRecord()->getNumVirtualBases() > 0)
394 Result += P.getInlineDesc()->Offset;
395 P = P.getBase();
396 continue;
397 }
398 if (P.isArrayElement()) {
399 P = P.expand();
400 Result += (P.getIndex() * P.elemSize());
401 P = P.getArray();
402 continue;
403 }
404
405 if (P.isRoot()) {
406 if (P.isOnePastEnd())
407 Result +=
409 break;
410 }
411
412 assert(P.getField());
413 const Record *R = P.getBase().getRecord();
414 assert(R);
415
416 const ASTRecordLayout &Layout = ASTCtx.getASTRecordLayout(R->getDecl());
417 Result += ASTCtx
420 .getQuantity();
421
422 if (P.isOnePastEnd())
423 Result +=
425
426 P = P.getBase();
427 if (P.isRoot())
428 break;
429 }
430 return Result;
431}
432
433std::string Pointer::toDiagnosticString(const ASTContext &Ctx) const {
434 if (isZero())
435 return "nullptr";
436
437 if (isIntegralPointer())
438 return (Twine("&(") + Twine(asIntPointer().Value + Offset) + ")").str();
439
440 return toAPValue(Ctx).getAsString(Ctx, getType());
441}
442
444 if (!isBlockPointer())
445 return true;
446
447 if (isRoot() && BS.Base == sizeof(GlobalInlineDescriptor) &&
448 Offset == BS.Base) {
449 const auto &GD = block()->getBlockDesc<GlobalInlineDescriptor>();
451 }
452
453 assert(BS.Pointee && "Cannot check if null pointer was initialized");
454 const Descriptor *Desc = getFieldDesc();
455 assert(Desc);
456 if (Desc->isPrimitiveArray())
458
459 if (asBlockPointer().Base == 0)
460 return true;
461 // Field has its bit in an inline descriptor.
462 return getInlineDesc()->IsInitialized;
463}
464
465bool Pointer::isElementInitialized(unsigned Index) const {
466 if (!isBlockPointer())
467 return true;
468
469 const Descriptor *Desc = getFieldDesc();
470 assert(Desc);
471
472 if (isStatic() && BS.Base == 0)
473 return true;
474
475 if (isRoot() && BS.Base == sizeof(GlobalInlineDescriptor) &&
476 Offset == BS.Base) {
477 const auto &GD = block()->getBlockDesc<GlobalInlineDescriptor>();
479 }
480
481 if (Desc->isPrimitiveArray()) {
482 InitMapPtr IM = getInitMap();
483
484 if (IM.allInitialized())
485 return true;
486
487 if (!IM.hasInitMap())
488 return false;
489 return IM->isElementInitialized(Index);
490 }
491 return isInitialized();
492}
493
494bool Pointer::isElementAlive(unsigned Index) const {
495 assert(getFieldDesc()->isPrimitiveArray());
496
497 InitMapPtr &IM = getInitMap();
498 if (!IM.hasInitMap())
499 return true;
500
501 if (IM.allInitialized())
502 return true;
503
504 return IM->isElementAlive(Index);
505}
506
508
510
512 if (!isBlockPointer())
513 return;
514 if (BS.Base < sizeof(InlineDescriptor))
515 return;
516
517 if (inArray() && !isArrayRoot()) {
518 assert(L == Lifetime::Started || L == Lifetime::Ended);
519 const Descriptor *Desc = getFieldDesc();
520 InitMapPtr &IM = getInitMap();
521 if (!IM.hasInitMap())
522 IM.setInitMap(new InitMap(Desc->getNumElems(), IM.allInitialized()));
523
524 if (L == Lifetime::Ended)
526 else if (L == Lifetime::Started)
528 assert(isArrayRoot() || (this->getLifetime() == L));
529 return;
530 }
531
532 getInlineDesc()->LifeState = L;
533}
534
536 if (!isBlockPointer())
537 return;
538
539 assert(BS.Pointee && "Cannot initialize null pointer");
540
541 if (isRoot() && BS.Base == sizeof(GlobalInlineDescriptor) &&
542 Offset == BS.Base) {
543 auto &GD = BS.Pointee->getBlockDesc<GlobalInlineDescriptor>();
545 return;
546 }
547
548 const Descriptor *Desc = getFieldDesc();
549 assert(Desc);
550 if (Desc->isPrimitiveArray()) {
551 if (Desc->getNumElems() != 0)
553 return;
554 }
555
556 // Field has its bit in an inline descriptor.
557 assert(BS.Base != 0 && "Only composite fields can be initialised");
558 getInlineDesc()->IsInitialized = true;
559}
560
561void Pointer::initializeElement(unsigned Index) const {
562 // Primitive global arrays don't have an initmap.
563 if (isStatic() && BS.Base == 0)
564 return;
565
566 assert(Index < getFieldDesc()->getNumElems());
567
568 InitMapPtr &IM = getInitMap();
569 if (IM.allInitialized())
570 return;
571
572 if (!IM.hasInitMap()) {
573 const Descriptor *Desc = getFieldDesc();
574 IM.setInitMap(new InitMap(Desc->getNumElems()));
575 }
576 assert(IM.hasInitMap());
577
578 if (IM->initializeElement(Index))
580}
581
583 assert(getFieldDesc()->isPrimitiveArray());
584 assert(isArrayRoot());
585
586 getInitMap().noteAllInitialized();
587}
588
590 assert(getFieldDesc()->isPrimitiveArray());
591 assert(isArrayRoot());
592
593 if (isStatic() && BS.Base == 0)
594 return true;
595
596 if (isRoot() && BS.Base == sizeof(GlobalInlineDescriptor) &&
597 Offset == BS.Base) {
598 const auto &GD = block()->getBlockDesc<GlobalInlineDescriptor>();
600 }
601
602 InitMapPtr IM = getInitMap();
603 return IM.allInitialized();
604}
605
607 assert(getFieldDesc()->isPrimitiveArray());
608 assert(isArrayRoot());
609
610 if (isStatic() && BS.Base == 0)
611 return true;
612
613 if (isRoot() && BS.Base == sizeof(GlobalInlineDescriptor) &&
614 Offset == BS.Base) {
615 const auto &GD = block()->getBlockDesc<GlobalInlineDescriptor>();
617 }
618
619 InitMapPtr &IM = getInitMap();
620 return IM.allInitialized() || (IM.hasInitMap() && IM->allElementsAlive());
621}
622
623void Pointer::activate() const {
624 // Field has its bit in an inline descriptor.
625 assert(BS.Base != 0 && "Only composite fields can be activated");
626
627 if (isRoot() && BS.Base == sizeof(GlobalInlineDescriptor))
628 return;
629 if (!getInlineDesc()->InUnion)
630 return;
631
633 activate = [&activate](Pointer &P) -> void {
634 P.getInlineDesc()->IsActive = true;
635 if (const Record *R = P.getRecord(); R && !R->isUnion()) {
636 for (const Record::Field &F : R->fields()) {
637 Pointer FieldPtr = P.atField(F.Offset);
638 if (!FieldPtr.getInlineDesc()->IsActive)
639 activate(FieldPtr);
640 }
641 // FIXME: Bases?
642 }
643 };
644
646 deactivate = [&deactivate](Pointer &P) -> void {
647 P.getInlineDesc()->IsActive = false;
648
649 if (const Record *R = P.getRecord()) {
650 for (const Record::Field &F : R->fields()) {
651 Pointer FieldPtr = P.atField(F.Offset);
652 if (FieldPtr.getInlineDesc()->IsActive)
653 deactivate(FieldPtr);
654 }
655 // FIXME: Bases?
656 }
657 };
658
659 Pointer B = *this;
660 // Primitive array elements can't be activated individually, so
661 // look at the array root instead.
663 B = B.getArray();
664
665 while (!B.isRoot() && B.inUnion()) {
666 activate(B);
667
668 // When walking up the pointer chain, deactivate
669 // all union child pointers that aren't on our path.
670 Pointer Cur = B;
671 B = B.getBase();
672 if (const Record *BR = B.getRecord(); BR && BR->isUnion()) {
673 for (const Record::Field &F : BR->fields()) {
674 Pointer FieldPtr = B.atField(F.Offset);
675 if (FieldPtr != Cur)
676 deactivate(FieldPtr);
677 }
678 }
679 }
680}
681
683 // TODO: this only appears in constructors, so nothing to deactivate.
684}
685
686bool Pointer::hasSameBase(const Pointer &A, const Pointer &B) {
687 // Two null pointers always have the same base.
688 if (A.isZero() && B.isZero())
689 return true;
690
692 return true;
694 return true;
695 if (A.isTypeidPointer() && B.isTypeidPointer())
696 return true;
697
698 if (A.StorageKind != B.StorageKind)
699 return false;
700
702}
703
704bool Pointer::pointToSameBlock(const Pointer &A, const Pointer &B) {
705 if (!A.isBlockPointer() || !B.isBlockPointer())
706 return false;
707 return A.block() == B.block();
708}
709
710bool Pointer::hasSameArray(const Pointer &A, const Pointer &B) {
711 return hasSameBase(A, B) && A.BS.Base == B.BS.Base &&
713}
714
716 if (isZero() || !isBlockPointer())
717 return false;
718
719 if (block()->isDynamic())
720 return false;
721
722 const Expr *E = block()->getDescriptor()->asExpr();
724}
725
727 if (isZero() || !isBlockPointer())
728 return false;
729
730 if (block()->isDynamic())
731 return false;
732
733 const Expr *E = block()->getDescriptor()->asExpr();
734 return isa_and_nonnull<StringLiteral>(E);
735}
736
738 if (isZero() || !isBlockPointer())
739 return false;
740
741 if (const Expr *E = BS.Pointee->getDescriptor()->asExpr())
742 return isa<AddrLabelExpr>(E);
743 return false;
744}
745
746std::optional<std::pair<Pointer, Pointer>>
748 if (!A.isBlockPointer() || !B.isBlockPointer())
749 return std::nullopt;
750
752 return std::nullopt;
753 if (A.isRoot() && B.isRoot())
754 return std::nullopt;
755
756 if (A == B)
757 return std::make_pair(A, B);
758
759 auto getBase = [](const Pointer &P) -> Pointer {
760 if (P.isArrayElement())
761 return P.expand().getArray();
762 return P.getBase();
763 };
764
765 Pointer IterA = A;
766 Pointer IterB = B;
767 Pointer CurA = IterA;
768 Pointer CurB = IterB;
769 for (;;) {
770 if (IterA.asBlockPointer().Base > IterB.asBlockPointer().Base) {
771 CurA = IterA;
772 IterA = getBase(IterA);
773 } else {
774 CurB = IterB;
775 IterB = getBase(IterB);
776 }
777
778 if (IterA == IterB)
779 return std::make_pair(CurA, CurB);
780
781 if (IterA.isRoot() && IterB.isRoot())
782 return std::nullopt;
783 }
784
785 llvm_unreachable("The loop above should've returned.");
786}
787
788std::optional<APValue> Pointer::toRValue(const Context &Ctx,
789 QualType ResultType) const {
790 const ASTContext &ASTCtx = Ctx.getASTContext();
791 assert(!ResultType.isNull());
792 // Method to recursively traverse composites.
793 std::function<bool(QualType, const Pointer &, APValue &)> Composite;
794 Composite = [&Composite, &Ctx, &ASTCtx](QualType Ty, const Pointer &Ptr,
795 APValue &R) {
796 if (const auto *AT = Ty->getAs<AtomicType>())
797 Ty = AT->getValueType();
798
799 // Invalid pointers.
800 if (Ptr.isDummy() || !Ptr.isLive() || !Ptr.isBlockPointer() ||
801 Ptr.isPastEnd())
802 return false;
803
804 // Primitives should never end up here.
805 assert(!Ctx.canClassify(Ty));
806
807 if (const auto *RT = Ty->getAsCanonical<RecordType>()) {
808 const auto *Record = Ptr.getRecord();
809 assert(Record && "Missing record descriptor");
810
811 bool Ok = true;
812 if (RT->getDecl()->isUnion()) {
813 const FieldDecl *ActiveField = nullptr;
815 for (const auto &F : Record->fields()) {
816 const Pointer &FP = Ptr.atField(F.Offset);
817 if (FP.isActive()) {
818 const Descriptor *Desc = F.Desc;
819 if (Desc->isPrimitive()) {
820 TYPE_SWITCH(Desc->getPrimType(),
821 Value = FP.deref<T>().toAPValue(ASTCtx));
822 } else {
823 QualType FieldTy = F.Decl->getType();
824 Ok &= Composite(FieldTy, FP, Value);
825 }
826 ActiveField = FP.getFieldDesc()->asFieldDecl();
827 break;
828 }
829 }
830 R = APValue(ActiveField, Value);
831 } else {
832 unsigned NF = Record->getNumFields();
833 unsigned NB = Record->getNumBases();
834 unsigned NV = Ptr.isBaseClass() ? 0 : Record->getNumVirtualBases();
835
836 R = APValue(APValue::UninitStruct(), NB, NF);
837
838 for (unsigned I = 0; I != NF; ++I) {
839 const Record::Field *FD = Record->getField(I);
840 const Descriptor *Desc = FD->Desc;
841 const Pointer &FP = Ptr.atField(FD->Offset);
842 APValue &Value = R.getStructField(I);
843 if (Desc->isPrimitive()) {
844 TYPE_SWITCH(Desc->getPrimType(),
845 Value = FP.deref<T>().toAPValue(ASTCtx));
846 } else {
847 QualType FieldTy = FD->Decl->getType();
848 Ok &= Composite(FieldTy, FP, Value);
849 }
850 }
851
852 for (unsigned I = 0; I != NB; ++I) {
853 const Record::Base *BD = Record->getBase(I);
854 QualType BaseTy = Ctx.getASTContext().getCanonicalTagType(BD->Decl);
855 const Pointer &BP = Ptr.atField(BD->Offset);
856 Ok &= Composite(BaseTy, BP, R.getStructBase(I));
857 }
858
859 for (unsigned I = 0; I != NV; ++I) {
860 const Record::Base *VD = Record->getVirtualBase(I);
861 QualType VirtBaseTy =
862 Ctx.getASTContext().getCanonicalTagType(VD->Decl);
863 const Pointer &VP = Ptr.atField(VD->Offset);
864 Ok &= Composite(VirtBaseTy, VP, R.getStructBase(NB + I));
865 }
866 }
867 return Ok;
868 }
869
870 if (Ty->isIncompleteArrayType()) {
871 R = APValue(APValue::UninitArray(), 0, 0);
872 return true;
873 }
874
875 if (const auto *AT = Ty->getAsArrayTypeUnsafe()) {
876 const size_t NumElems = Ptr.getNumElems();
877 QualType ElemTy = AT->getElementType();
878 R = APValue(APValue::UninitArray{}, NumElems, NumElems);
879
880 bool Ok = true;
881 OptPrimType ElemT = Ctx.classify(ElemTy);
882 for (unsigned I = 0; I != NumElems; ++I) {
883 APValue &Slot = R.getArrayInitializedElt(I);
884 if (ElemT) {
885 TYPE_SWITCH(*ElemT, Slot = Ptr.elem<T>(I).toAPValue(ASTCtx));
886 } else {
887 Ok &= Composite(ElemTy, Ptr.atIndex(I).narrow(), Slot);
888 }
889 }
890 return Ok;
891 }
892
893 // Complex types.
894 if (Ty->isAnyComplexType()) {
895 const Descriptor *Desc = Ptr.getFieldDesc();
896 // Can happen via C casts.
897 if (!Desc->isPrimitiveArray())
898 return false;
899
900 PrimType ElemT = Desc->getPrimType();
901 if (isIntegerOrBoolType(ElemT)) {
902 PrimType ElemT = Desc->getPrimType();
903 INT_TYPE_SWITCH(ElemT, {
904 auto V1 = Ptr.elem<T>(0);
905 auto V2 = Ptr.elem<T>(1);
906 R = APValue(V1.toAPSInt(), V2.toAPSInt());
907 return true;
908 });
909 } else if (ElemT == PT_Float) {
910 R = APValue(Ptr.elem<Floating>(0).getAPFloat(),
911 Ptr.elem<Floating>(1).getAPFloat());
912 return true;
913 }
914 return false;
915 }
916
917 // Vector types.
918 if (const auto *VT = Ty->getAs<VectorType>()) {
919 const Descriptor *Desc = Ptr.getFieldDesc();
920 assert(Ptr.getFieldDesc()->isPrimitiveArray());
921 PrimType ElemT = Desc->getPrimType();
922
924 Values.reserve(VT->getNumElements());
925 for (unsigned I = 0; I != VT->getNumElements(); ++I) {
926 TYPE_SWITCH(ElemT,
927 { Values.push_back(Ptr.elem<T>(I).toAPValue(ASTCtx)); });
928 }
929
930 assert(Values.size() == VT->getNumElements());
931 R = APValue(Values.data(), Values.size());
932 return true;
933 }
934
935 // Constant Matrix types.
936 if (const auto *MT = Ty->getAs<ConstantMatrixType>()) {
937 assert(Ptr.getFieldDesc()->isPrimitiveArray());
938 const Descriptor *Desc = Ptr.getFieldDesc();
939 PrimType ElemT = Desc->getPrimType();
940 unsigned NumElems = MT->getNumElementsFlattened();
941
943 Values.reserve(NumElems);
944 for (unsigned I = 0; I != NumElems; ++I) {
945 TYPE_SWITCH(ElemT,
946 { Values.push_back(Ptr.elem<T>(I).toAPValue(ASTCtx)); });
947 }
948
949 R = APValue(Values.data(), MT->getNumRows(), MT->getNumColumns());
950 return true;
951 }
952
953 llvm_unreachable("invalid value to return");
954 };
955
956 // Can't return functions as rvalues.
957 if (ResultType->isFunctionType())
958 return std::nullopt;
959
960 // Invalid to read from.
961 if (isDummy() || !isLive() || isPastEnd() ||
963 return std::nullopt;
964
965 // We can return these as rvalues, but we can't deref() them.
966 if (isZero() || isIntegralPointer())
967 return toAPValue(ASTCtx);
968
969 // Just load primitive types.
970 if (OptPrimType T = Ctx.classify(ResultType)) {
971 if (!canDeref(*T))
972 return std::nullopt;
973 TYPE_SWITCH(*T, return this->deref<T>().toAPValue(ASTCtx));
974 }
975
976 // Return the composite type.
978 if (!Composite(ResultType, *this, Result))
979 return std::nullopt;
980 return Result;
981}
982
983std::optional<IntPointer> IntPointer::atOffset(const ASTContext &ASTCtx,
984 unsigned Offset) const {
985 if (!this->Desc)
986 return *this;
987 const Record *R = this->Desc->ElemRecord;
988 if (!R)
989 return *this;
990
991 const Record::Field *F = nullptr;
992 for (auto &It : R->fields()) {
993 if (It.Offset == Offset) {
994 F = &It;
995 break;
996 }
997 }
998 if (!F)
999 return *this;
1000
1001 const FieldDecl *FD = F->Decl;
1002 if (FD->getParent()->isInvalidDecl())
1003 return std::nullopt;
1004
1005 const ASTRecordLayout &Layout = ASTCtx.getASTRecordLayout(FD->getParent());
1006 unsigned FieldIndex = FD->getFieldIndex();
1007 uint64_t FieldOffset =
1008 ASTCtx.toCharUnitsFromBits(Layout.getFieldOffset(FieldIndex))
1009 .getQuantity();
1010 return IntPointer{F->Desc, this->Value + FieldOffset};
1011}
1012
1014 unsigned BaseOffset) const {
1015 if (!Desc) {
1016 assert(Value == 0);
1017 return *this;
1018 }
1019 const Record *R = Desc->ElemRecord;
1020 const Descriptor *BaseDesc = nullptr;
1021
1022 // This iterates over bases and checks for the proper offset. That's
1023 // potentially slow but this case really shouldn't happen a lot.
1024 for (const Record::Base &B : R->bases()) {
1025 if (B.Offset == BaseOffset) {
1026 BaseDesc = B.Desc;
1027 break;
1028 }
1029 }
1030 assert(BaseDesc);
1031
1032 // Adjust the offset value based on the information from the record layout.
1033 const ASTRecordLayout &Layout = ASTCtx.getASTRecordLayout(R->getDecl());
1034 CharUnits BaseLayoutOffset =
1035 Layout.getBaseClassOffset(cast<CXXRecordDecl>(BaseDesc->asDecl()));
1036
1037 return {BaseDesc, Value + BaseLayoutOffset.getQuantity()};
1038}
Defines the clang::Expr interface and subclasses for C++ expressions.
#define INT_TYPE_SWITCH(Expr, B)
Definition PrimType.h:244
#define TYPE_SWITCH(Expr, B)
Definition PrimType.h:223
static uint64_t getFieldOffset(const ASTContext &C, const FieldDecl *FD)
static LValueBase getTypeInfo(TypeInfoLValue LV, QualType TypeInfo)
Definition APValue.cpp:55
static LValueBase getDynamicAlloc(DynamicAllocLValue LV, QualType Type)
Definition APValue.cpp:47
A non-discriminated union of a base, field, or array index.
Definition APValue.h:208
static LValuePathEntry ArrayIndex(uint64_t Index)
Definition APValue.h:216
APValue - This class implements a discriminated union of [uninitialized] [APSInt] [APFloat],...
Definition APValue.h:122
std::string getAsString(const ASTContext &Ctx, QualType Ty) const
Definition APValue.cpp:988
Holds long-lived AST nodes (such as types and decls) that can be referred to throughout the semantic ...
Definition ASTContext.h:226
const ASTRecordLayout & getASTRecordLayout(const RecordDecl *D) const
Get or compute information about the layout of the specified record (struct/union/class) D,...
CharUnits getTypeSizeInChars(QualType T) const
Return the size of the specified (complete) type T, in characters.
CharUnits toCharUnitsFromBits(int64_t BitSize) const
Convert a size in bits to a size in characters.
CanQualType getCanonicalTagType(const TagDecl *TD) const
ASTRecordLayout - This class contains layout information for one RecordDecl, which is a struct/union/...
uint64_t getFieldOffset(unsigned FieldNo) const
getFieldOffset - Get the offset of the given field index, in bits.
CharUnits getBaseClassOffset(const CXXRecordDecl *Base) const
getBaseClassOffset - Get the offset, in chars, for the given base class.
CharUnits getVBaseClassOffset(const CXXRecordDecl *VBase) const
getVBaseClassOffset - Get the offset, in chars, for the given base class.
CharUnits - This is an opaque type for sizes expressed in character units.
Definition CharUnits.h:38
QuantityType getQuantity() const
getQuantity - Get the raw integer representation of this quantity.
Definition CharUnits.h:185
static CharUnits fromQuantity(QuantityType Quantity)
fromQuantity - Construct a CharUnits quantity from a raw integer type.
Definition CharUnits.h:63
static CharUnits Zero()
Zero - Construct a CharUnits quantity of zero.
Definition CharUnits.h:53
Represents a concrete matrix type with constant number of rows and columns.
Definition TypeBase.h:4437
Decl()=delete
bool isInvalidDecl() const
Definition DeclBase.h:596
Symbolic representation of a dynamic allocation.
Definition APValue.h:65
This represents one expression.
Definition Expr.h:112
Represents a member of a struct/union/class.
Definition Decl.h:3175
unsigned getFieldIndex() const
Returns the index of this field within its record, as appropriate for passing to ASTRecordLayout::get...
Definition Decl.h:3260
const RecordDecl * getParent() const
Returns the parent of this field declaration, which is the struct in which this field is defined.
Definition Decl.h:3411
Represents a function declaration or definition.
Definition Decl.h:2015
A (possibly-)qualified type.
Definition TypeBase.h:937
bool isNull() const
Return true if this QualType doesn't point to a type yet.
Definition TypeBase.h:1004
RecordDecl * getDefinition() const
Returns the RecordDecl that actually defines this struct/union/class.
Definition Decl.h:4526
Symbolic representation of typeid(T) for some type T.
Definition APValue.h:44
RecordDecl * getAsRecordDecl() const
Retrieves the RecordDecl this type refers to.
Definition Type.h:41
bool isFunctionType() const
Definition TypeBase.h:8664
Represent the declaration of a variable (in which case it is an lvalue) a function (in which case it ...
Definition Decl.h:712
QualType getType() const
Definition Decl.h:723
Represents a GCC generic vector type.
Definition TypeBase.h:4225
unsigned getSize() const
Returns the size of the block.
Definition InterpBlock.h:87
const Descriptor * getDescriptor() const
Returns the block's descriptor.
Definition InterpBlock.h:73
Holds all information required to evaluate constexpr code in a module.
Definition Context.h:47
ASTContext & getASTContext() const
Returns the AST context.
Definition Context.h:98
OptPrimType classify(QualType T) const
Classifies a type.
Definition Context.cpp:408
bool canClassify(QualType T) const
Definition Context.h:120
If a Floating is constructed from Memory, it DOES NOT OWN THAT MEMORY.
Definition Floating.h:35
APFloat getAPFloat() const
Definition Floating.h:64
const BlockExpr * getExpr() const
Definition Function.h:136
const FunctionDecl * getDecl() const
Returns the original FunctionDecl.
Definition Function.h:133
static bool hasSameBase(const Pointer &A, const Pointer &B)
Checks if two pointers are comparable.
Definition Pointer.cpp:686
void deactivate() const
Deactivates an entire strurcutre.
Definition Pointer.cpp:682
bool isInitialized() const
Checks if an object was initialized.
Definition Pointer.cpp:443
bool pointsToLabel() const
Whether this points to a block created for an AddrLabelExpr.
Definition Pointer.cpp:737
bool isStatic() const
Checks if the storage is static.
Definition Pointer.h:505
bool isDynamic() const
Checks if the storage has been dynamically allocated.
Definition Pointer.h:520
bool inUnion() const
Definition Pointer.h:413
bool isZeroSizeArray() const
Checks if the pointer is pointing to a zero-size array.
Definition Pointer.h:669
bool isElementInitialized(unsigned Index) const
Like isInitialized(), but for primitive arrays.
Definition Pointer.cpp:465
FunctionPointer Fn
Definition Pointer.h:883
bool isDummy() const
Checks if the pointer points to a dummy value.
Definition Pointer.h:562
void print(llvm::raw_ostream &OS) const
Prints the pointer.
Definition Pointer.cpp:327
int64_t getIndex() const
Returns the index into an array.
Definition Pointer.h:627
bool isActive() const
Checks if the object is active.
Definition Pointer.h:551
void startLifetime() const
Start the lifetime of this pointer.
Definition Pointer.cpp:507
bool canDeref(PrimType T) const
Checks whether the pointer can be dereferenced to the given PrimType.
Definition Pointer.h:678
Pointer atField(unsigned Off) const
Creates a pointer to a field.
Definition Pointer.h:179
T & deref() const
Dereferences the pointer, if it's live.
Definition Pointer.h:687
unsigned getNumElems() const
Returns the number of elements.
Definition Pointer.h:611
Pointer getArray() const
Returns the parent array.
Definition Pointer.h:326
bool isUnknownSizeArray() const
Checks if the structure is an array of unknown size.
Definition Pointer.h:426
void activate() const
Activats a field.
Definition Pointer.cpp:623
static std::optional< std::pair< Pointer, Pointer > > computeSplitPoint(const Pointer &A, const Pointer &B)
Definition Pointer.cpp:747
const TypeidPointer & asTypeidPointer() const
Definition Pointer.h:474
bool isIntegralPointer() const
Definition Pointer.h:480
QualType getType() const
Returns the type of the innermost field.
Definition Pointer.h:346
bool isArrayElement() const
Checks if the pointer points to an array.
Definition Pointer.h:432
void initializeAllElements() const
Initialize all elements of a primitive array at once.
Definition Pointer.cpp:582
bool pointsToStringLiteral() const
Definition Pointer.cpp:726
bool isArrayRoot() const
Whether this array refers to an array, but not to the first element.
Definition Pointer.h:405
size_t computeOffsetForComparison(const ASTContext &ASTCtx) const
Compute an integer that can be used to compare this pointer to another one.
Definition Pointer.cpp:370
bool isLive() const
Checks if the pointer is live.
Definition Pointer.h:278
bool inArray() const
Checks if the innermost field is an array.
Definition Pointer.h:408
bool isElementAlive(unsigned Index) const
Definition Pointer.cpp:494
bool pointsToLiteral() const
Whether this points to a block that's been created for a "literal lvalue", i.e.
Definition Pointer.cpp:715
bool allElementsAlive() const
Definition Pointer.cpp:606
Pointer getBase() const
Returns a pointer to the object of which this pointer is a field.
Definition Pointer.h:317
void setLifeState(Lifetime L) const
Definition Pointer.cpp:511
bool isTypeidPointer() const
Definition Pointer.h:482
std::string toDiagnosticString(const ASTContext &Ctx) const
Converts the pointer to a string usable in diagnostics.
Definition Pointer.cpp:433
bool isZero() const
Checks if the pointer is null.
Definition Pointer.h:264
Pointer & operator=(const Pointer &P)
Definition Pointer.cpp:95
const IntPointer & asIntPointer() const
Definition Pointer.h:466
bool isRoot() const
Pointer points directly to a block.
Definition Pointer.h:448
const Descriptor * getDeclDesc() const
Accessor for information about the declaration site.
Definition Pointer.h:292
static bool pointToSameBlock(const Pointer &A, const Pointer &B)
Checks if both given pointers point to the same block.
Definition Pointer.cpp:704
APValue toAPValue(const ASTContext &ASTCtx) const
Converts the pointer to an APValue.
Definition Pointer.cpp:173
bool isOnePastEnd() const
Checks if the index is one past end.
Definition Pointer.h:644
static bool hasSameArray(const Pointer &A, const Pointer &B)
Checks if two pointers can be subtracted.
Definition Pointer.cpp:710
uint64_t getIntegerRepresentation() const
Definition Pointer.h:149
bool isPastEnd() const
Checks if the pointer points past the end of the object.
Definition Pointer.h:658
const FieldDecl * getField() const
Returns the field information.
Definition Pointer.h:492
Pointer expand() const
Expands a pointer to the containing array, undoing narrowing.
Definition Pointer.h:229
friend class Block
Definition Pointer.h:843
bool isElementPastEnd() const
Checks if the pointer is an out-of-bounds element pointer.
Definition Pointer.h:666
bool isBlockPointer() const
Definition Pointer.h:479
BlockPointer BS
Definition Pointer.h:882
TypeidPointer Typeid
Definition Pointer.h:884
std::optional< APValue > toRValue(const Context &Ctx, QualType ResultType) const
Converts the pointer to an APValue that is an rvalue.
Definition Pointer.cpp:788
const FunctionPointer & asFunctionPointer() const
Definition Pointer.h:470
bool allElementsInitialized() const
Definition Pointer.cpp:589
const Block * block() const
Definition Pointer.h:617
bool isFunctionPointer() const
Definition Pointer.h:481
void endLifetime() const
Ends the lifetime of the pointer.
Definition Pointer.cpp:509
Pointer getDeclPtr() const
Definition Pointer.h:366
const Descriptor * getFieldDesc() const
Accessors for information about the innermost field.
Definition Pointer.h:336
bool isVirtualBaseClass() const
Definition Pointer.h:558
bool isBaseClass() const
Checks if a structure is a base class.
Definition Pointer.h:557
size_t elemSize() const
Returns the element size of the innermost field.
Definition Pointer.h:369
Lifetime getLifetime() const
Definition Pointer.h:761
const BlockPointer & asBlockPointer() const
Definition Pointer.h:462
void initialize() const
Initializes a field.
Definition Pointer.cpp:535
bool isField() const
Checks if the item is a field in an object.
Definition Pointer.h:284
void initializeElement(unsigned Index) const
Initialized the given element of a primitive array.
Definition Pointer.cpp:561
const Record * getRecord() const
Returns the record descriptor of a class.
Definition Pointer.h:485
Structure/Class descriptor.
Definition Record.h:25
const RecordDecl * getDecl() const
Returns the underlying declaration.
Definition Record.h:65
bool isUnion() const
Checks if the record is a union.
Definition Record.h:69
const Field * getField(unsigned I) const
Definition Record.h:95
unsigned getNumBases() const
Definition Record.h:106
const Base * getBase(unsigned I) const
Definition Record.h:107
const Base * getVirtualBase(unsigned I) const
Definition Record.h:122
unsigned getNumFields() const
Definition Record.h:94
unsigned getNumVirtualBases() const
Definition Record.h:121
llvm::iterator_range< const_field_iter > fields() const
Definition Record.h:90
constexpr bool isIntegerOrBoolType(PrimType T)
Definition PrimType.h:52
PrimType
Enumeration of the primitive types of the VM.
Definition PrimType.h:34
The JSON file list parser is used to communicate input to InstallAPI.
bool isa(CodeGen::Address addr)
Definition Address.h:330
@ Result
The result type of a method or function.
Definition TypeBase.h:905
U cast(CodeGen::Address addr)
Definition Address.h:327
int const char * function
Definition c++config.h:31
__UINTPTR_TYPE__ uintptr_t
An unsigned integer type with the property that any valid pointer to void can be converted to this ty...
unsigned Base
Start of the current subfield.
Definition Pointer.h:40
Block * Pointee
The block the pointer is pointing to.
Definition Pointer.h:38
Describes a memory block created by an allocation site.
Definition Descriptor.h:122
unsigned getNumElems() const
Returns the number of elements stored in the block.
Definition Descriptor.h:259
bool isPrimitive() const
Checks if the descriptor is of a primitive.
Definition Descriptor.h:273
QualType getElemQualType() const
const ValueDecl * asValueDecl() const
Definition Descriptor.h:215
QualType getType() const
const Decl * asDecl() const
Definition Descriptor.h:211
unsigned getMetadataSize() const
Returns the size of the metadata.
Definition Descriptor.h:256
QualType getDataType(const ASTContext &Ctx) const
const bool IsArray
Flag indicating if the block is an array.
Definition Descriptor.h:168
bool isPrimitiveArray() const
Checks if the descriptor is of an array of primitives.
Definition Descriptor.h:264
const FieldDecl * asFieldDecl() const
Definition Descriptor.h:223
PrimType getPrimType() const
Definition Descriptor.h:241
const Expr * asExpr() const
Definition Descriptor.h:212
const Function * Func
Definition Pointer.h:57
Descriptor used for global variables.
Definition Descriptor.h:50
A pointer-sized struct we use to allocate into data storage.
Definition InitMap.h:79
bool hasInitMap() const
Definition InitMap.h:88
bool allInitialized() const
Are all elements in the array already initialized?
Definition InitMap.h:92
void setInitMap(const InitMap *IM)
Definition InitMap.h:94
Bitfield tracking the initialisation status of elements of primitive arrays.
Definition InitMap.h:22
void startElementLifetime(unsigned I)
Definition InitMap.cpp:32
void endElementLifetime(unsigned I)
Definition InitMap.cpp:45
bool allElementsAlive() const
Definition InitMap.h:58
bool isElementInitialized(unsigned I) const
Checks if an element was initialized.
Definition InitMap.cpp:23
bool initializeElement(unsigned I)
Initializes an element. Returns true when object if fully initialized.
Definition InitMap.cpp:13
bool isElementAlive(unsigned I) const
Definition InitMap.h:52
Inline descriptor embedded in structures and arrays.
Definition Descriptor.h:67
unsigned IsActive
Flag indicating if the field is the active member of a union.
Definition Descriptor.h:89
unsigned Offset
Offset inside the structure/array.
Definition Descriptor.h:69
std::optional< IntPointer > atOffset(const ASTContext &ASTCtx, unsigned Offset) const
Definition Pointer.cpp:983
IntPointer baseCast(const ASTContext &ASTCtx, unsigned BaseOffset) const
Definition Pointer.cpp:1013
const Descriptor * Desc
Definition Pointer.h:48
const Type * TypeInfoType
Definition Pointer.h:62