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 getInlineDesc()->LifeState = Lifetime::Started;
560}
561
562void Pointer::initializeElement(unsigned Index) const {
563 // Primitive global arrays don't have an initmap.
564 if (isStatic() && BS.Base == 0)
565 return;
566
567 assert(Index < getFieldDesc()->getNumElems());
568
569 InitMapPtr &IM = getInitMap();
570 if (IM.allInitialized())
571 return;
572
573 if (!IM.hasInitMap()) {
574 const Descriptor *Desc = getFieldDesc();
575 IM.setInitMap(new InitMap(Desc->getNumElems()));
576 }
577 assert(IM.hasInitMap());
578
579 if (IM->initializeElement(Index))
581}
582
584 assert(getFieldDesc()->isPrimitiveArray());
585 assert(isArrayRoot());
586
587 getInitMap().noteAllInitialized();
588}
589
591 assert(getFieldDesc()->isPrimitiveArray());
592 assert(isArrayRoot());
593
594 if (isStatic() && BS.Base == 0)
595 return true;
596
597 if (isRoot() && BS.Base == sizeof(GlobalInlineDescriptor) &&
598 Offset == BS.Base) {
599 const auto &GD = block()->getBlockDesc<GlobalInlineDescriptor>();
601 }
602
603 InitMapPtr IM = getInitMap();
604 return IM.allInitialized();
605}
606
608 assert(getFieldDesc()->isPrimitiveArray());
609 assert(isArrayRoot());
610
611 if (isStatic() && BS.Base == 0)
612 return true;
613
614 if (isRoot() && BS.Base == sizeof(GlobalInlineDescriptor) &&
615 Offset == BS.Base) {
616 const auto &GD = block()->getBlockDesc<GlobalInlineDescriptor>();
618 }
619
620 InitMapPtr &IM = getInitMap();
621 return IM.allInitialized() || (IM.hasInitMap() && IM->allElementsAlive());
622}
623
624void Pointer::activate() const {
625 // Field has its bit in an inline descriptor.
626 assert(BS.Base != 0 && "Only composite fields can be activated");
627
628 if (isRoot() && BS.Base == sizeof(GlobalInlineDescriptor))
629 return;
630 if (!getInlineDesc()->InUnion)
631 return;
632
634 activate = [&activate](Pointer &P) -> void {
635 P.getInlineDesc()->IsActive = true;
636 P.startLifetime();
637 if (const Record *R = P.getRecord(); R && !R->isUnion()) {
638 for (const Record::Field &F : R->fields()) {
639 Pointer FieldPtr = P.atField(F.Offset);
640 if (!FieldPtr.getInlineDesc()->IsActive)
641 activate(FieldPtr);
642 }
643 // FIXME: Bases?
644 }
645 };
646
648 deactivate = [&deactivate](Pointer &P) -> void {
649 P.getInlineDesc()->IsActive = false;
650
651 if (const Record *R = P.getRecord()) {
652 for (const Record::Field &F : R->fields()) {
653 Pointer FieldPtr = P.atField(F.Offset);
654 if (FieldPtr.getInlineDesc()->IsActive)
655 deactivate(FieldPtr);
656 }
657 // FIXME: Bases?
658 }
659 };
660
661 Pointer B = *this;
662 // Primitive array elements can't be activated individually, so
663 // look at the array root instead.
665 B = B.getArray();
666
667 while (!B.isRoot() && B.inUnion()) {
668 activate(B);
669
670 // When walking up the pointer chain, deactivate
671 // all union child pointers that aren't on our path.
672 Pointer Cur = B;
673 B = B.getBase();
674 if (const Record *BR = B.getRecord(); BR && BR->isUnion()) {
675 for (const Record::Field &F : BR->fields()) {
676 Pointer FieldPtr = B.atField(F.Offset);
677 if (FieldPtr != Cur)
678 deactivate(FieldPtr);
679 }
680 }
681 }
682}
683
685 // TODO: this only appears in constructors, so nothing to deactivate.
686}
687
688bool Pointer::hasSameBase(const Pointer &A, const Pointer &B) {
689 // Two null pointers always have the same base.
690 if (A.isZero() && B.isZero())
691 return true;
692
694 return true;
696 return true;
697 if (A.isTypeidPointer() && B.isTypeidPointer())
698 return true;
699
700 if (A.StorageKind != B.StorageKind)
701 return false;
702
704}
705
706bool Pointer::pointToSameBlock(const Pointer &A, const Pointer &B) {
707 if (!A.isBlockPointer() || !B.isBlockPointer())
708 return false;
709 return A.block() == B.block();
710}
711
712bool Pointer::hasSameArray(const Pointer &A, const Pointer &B) {
713 return hasSameBase(A, B) && A.BS.Base == B.BS.Base &&
715}
716
718 if (isZero() || !isBlockPointer())
719 return false;
720
721 if (block()->isDynamic())
722 return false;
723
724 const Expr *E = block()->getDescriptor()->asExpr();
726}
727
729 if (isZero() || !isBlockPointer())
730 return false;
731
732 if (block()->isDynamic())
733 return false;
734
735 const Expr *E = block()->getDescriptor()->asExpr();
736 return isa_and_nonnull<StringLiteral>(E);
737}
738
740 if (isZero() || !isBlockPointer())
741 return false;
742
743 if (const Expr *E = BS.Pointee->getDescriptor()->asExpr())
744 return isa<AddrLabelExpr>(E);
745 return false;
746}
747
748std::optional<std::pair<Pointer, Pointer>>
750 if (!A.isBlockPointer() || !B.isBlockPointer())
751 return std::nullopt;
752
754 return std::nullopt;
755 if (A.isRoot() && B.isRoot())
756 return std::nullopt;
757
758 if (A == B)
759 return std::make_pair(A, B);
760
761 auto getBase = [](const Pointer &P) -> Pointer {
762 if (P.isArrayElement())
763 return P.expand().getArray();
764 return P.getBase();
765 };
766
767 Pointer IterA = A;
768 Pointer IterB = B;
769 Pointer CurA = IterA;
770 Pointer CurB = IterB;
771 for (;;) {
772 if (IterA.asBlockPointer().Base > IterB.asBlockPointer().Base) {
773 CurA = IterA;
774 IterA = getBase(IterA);
775 } else {
776 CurB = IterB;
777 IterB = getBase(IterB);
778 }
779
780 if (IterA == IterB)
781 return std::make_pair(CurA, CurB);
782
783 if (IterA.isRoot() && IterB.isRoot())
784 return std::nullopt;
785 }
786
787 llvm_unreachable("The loop above should've returned.");
788}
789
790std::optional<APValue> Pointer::toRValue(const Context &Ctx,
791 QualType ResultType) const {
792 const ASTContext &ASTCtx = Ctx.getASTContext();
793 assert(!ResultType.isNull());
794 // Method to recursively traverse composites.
795 std::function<bool(QualType, const Pointer &, APValue &)> Composite;
796 Composite = [&Composite, &Ctx, &ASTCtx](QualType Ty, const Pointer &Ptr,
797 APValue &R) {
798 if (const auto *AT = Ty->getAs<AtomicType>())
799 Ty = AT->getValueType();
800
801 // Invalid pointers.
802 if (Ptr.isDummy() || !Ptr.isLive() || !Ptr.isBlockPointer() ||
803 Ptr.isPastEnd())
804 return false;
805
806 // Primitives should never end up here.
807 assert(!Ctx.canClassify(Ty));
808
809 if (const auto *RT = Ty->getAsCanonical<RecordType>()) {
810 const auto *Record = Ptr.getRecord();
811 assert(Record && "Missing record descriptor");
812
813 bool Ok = true;
814 if (RT->getDecl()->isUnion()) {
815 const FieldDecl *ActiveField = nullptr;
817 for (const auto &F : Record->fields()) {
818 const Pointer &FP = Ptr.atField(F.Offset);
819 if (FP.isActive()) {
820 const Descriptor *Desc = F.Desc;
821 if (Desc->isPrimitive()) {
822 TYPE_SWITCH(Desc->getPrimType(),
823 Value = FP.deref<T>().toAPValue(ASTCtx));
824 } else {
825 QualType FieldTy = F.Decl->getType();
826 Ok &= Composite(FieldTy, FP, Value);
827 }
828 ActiveField = FP.getFieldDesc()->asFieldDecl();
829 break;
830 }
831 }
832 R = APValue(ActiveField, Value);
833 } else {
834 unsigned NF = Record->getNumFields();
835 unsigned NB = Record->getNumBases();
836 unsigned NV = Ptr.isBaseClass() ? 0 : Record->getNumVirtualBases();
837
838 R = APValue(APValue::UninitStruct(), NB, NF);
839
840 for (unsigned I = 0; I != NF; ++I) {
841 const Record::Field *FD = Record->getField(I);
842 const Descriptor *Desc = FD->Desc;
843 const Pointer &FP = Ptr.atField(FD->Offset);
844 APValue &Value = R.getStructField(I);
845 if (Desc->isPrimitive()) {
846 TYPE_SWITCH(Desc->getPrimType(),
847 Value = FP.deref<T>().toAPValue(ASTCtx));
848 } else {
849 QualType FieldTy = FD->Decl->getType();
850 Ok &= Composite(FieldTy, FP, Value);
851 }
852 }
853
854 for (unsigned I = 0; I != NB; ++I) {
855 const Record::Base *BD = Record->getBase(I);
856 QualType BaseTy = Ctx.getASTContext().getCanonicalTagType(BD->Decl);
857 const Pointer &BP = Ptr.atField(BD->Offset);
858 Ok &= Composite(BaseTy, BP, R.getStructBase(I));
859 }
860
861 for (unsigned I = 0; I != NV; ++I) {
862 const Record::Base *VD = Record->getVirtualBase(I);
863 QualType VirtBaseTy =
864 Ctx.getASTContext().getCanonicalTagType(VD->Decl);
865 const Pointer &VP = Ptr.atField(VD->Offset);
866 Ok &= Composite(VirtBaseTy, VP, R.getStructBase(NB + I));
867 }
868 }
869 return Ok;
870 }
871
872 if (Ty->isIncompleteArrayType()) {
873 R = APValue(APValue::UninitArray(), 0, 0);
874 return true;
875 }
876
877 if (const auto *AT = Ty->getAsArrayTypeUnsafe()) {
878 const size_t NumElems = Ptr.getNumElems();
879 QualType ElemTy = AT->getElementType();
880 R = APValue(APValue::UninitArray{}, NumElems, NumElems);
881
882 bool Ok = true;
883 OptPrimType ElemT = Ctx.classify(ElemTy);
884 for (unsigned I = 0; I != NumElems; ++I) {
885 APValue &Slot = R.getArrayInitializedElt(I);
886 if (ElemT) {
887 TYPE_SWITCH(*ElemT, Slot = Ptr.elem<T>(I).toAPValue(ASTCtx));
888 } else {
889 Ok &= Composite(ElemTy, Ptr.atIndex(I).narrow(), Slot);
890 }
891 }
892 return Ok;
893 }
894
895 // Complex types.
896 if (Ty->isAnyComplexType()) {
897 const Descriptor *Desc = Ptr.getFieldDesc();
898 // Can happen via C casts.
899 if (!Desc->isPrimitiveArray())
900 return false;
901
902 PrimType ElemT = Desc->getPrimType();
903 if (isIntegerOrBoolType(ElemT)) {
904 PrimType ElemT = Desc->getPrimType();
905 INT_TYPE_SWITCH(ElemT, {
906 auto V1 = Ptr.elem<T>(0);
907 auto V2 = Ptr.elem<T>(1);
908 R = APValue(V1.toAPSInt(), V2.toAPSInt());
909 return true;
910 });
911 } else if (ElemT == PT_Float) {
912 R = APValue(Ptr.elem<Floating>(0).getAPFloat(),
913 Ptr.elem<Floating>(1).getAPFloat());
914 return true;
915 }
916 return false;
917 }
918
919 // Vector types.
920 if (const auto *VT = Ty->getAs<VectorType>()) {
921 const Descriptor *Desc = Ptr.getFieldDesc();
922 assert(Ptr.getFieldDesc()->isPrimitiveArray());
923 PrimType ElemT = Desc->getPrimType();
924
926 Values.reserve(VT->getNumElements());
927 for (unsigned I = 0; I != VT->getNumElements(); ++I) {
928 TYPE_SWITCH(ElemT,
929 { Values.push_back(Ptr.elem<T>(I).toAPValue(ASTCtx)); });
930 }
931
932 assert(Values.size() == VT->getNumElements());
933 R = APValue(Values.data(), Values.size());
934 return true;
935 }
936
937 // Constant Matrix types.
938 if (const auto *MT = Ty->getAs<ConstantMatrixType>()) {
939 assert(Ptr.getFieldDesc()->isPrimitiveArray());
940 const Descriptor *Desc = Ptr.getFieldDesc();
941 PrimType ElemT = Desc->getPrimType();
942 unsigned NumElems = MT->getNumElementsFlattened();
943
945 Values.reserve(NumElems);
946 for (unsigned I = 0; I != NumElems; ++I) {
947 TYPE_SWITCH(ElemT,
948 { Values.push_back(Ptr.elem<T>(I).toAPValue(ASTCtx)); });
949 }
950
951 R = APValue(Values.data(), MT->getNumRows(), MT->getNumColumns());
952 return true;
953 }
954
955 llvm_unreachable("invalid value to return");
956 };
957
958 // Can't return functions as rvalues.
959 if (ResultType->isFunctionType())
960 return std::nullopt;
961
962 // Invalid to read from.
963 if (isDummy() || !isLive() || isPastEnd() ||
965 return std::nullopt;
966
967 // We can return these as rvalues, but we can't deref() them.
968 if (isZero() || isIntegralPointer())
969 return toAPValue(ASTCtx);
970
971 // Just load primitive types.
972 if (OptPrimType T = Ctx.classify(ResultType)) {
973 if (!canDeref(*T))
974 return std::nullopt;
975 TYPE_SWITCH(*T, return this->deref<T>().toAPValue(ASTCtx));
976 }
977
978 // Return the composite type.
980 if (!Composite(ResultType, *this, Result))
981 return std::nullopt;
982 return Result;
983}
984
985std::optional<IntPointer> IntPointer::atOffset(const ASTContext &ASTCtx,
986 unsigned Offset) const {
987 if (!this->Desc)
988 return *this;
989 const Record *R = this->Desc->ElemRecord;
990 if (!R)
991 return *this;
992
993 const Record::Field *F = nullptr;
994 for (auto &It : R->fields()) {
995 if (It.Offset == Offset) {
996 F = &It;
997 break;
998 }
999 }
1000 if (!F)
1001 return *this;
1002
1003 const FieldDecl *FD = F->Decl;
1004 if (FD->getParent()->isInvalidDecl())
1005 return std::nullopt;
1006
1007 const ASTRecordLayout &Layout = ASTCtx.getASTRecordLayout(FD->getParent());
1008 unsigned FieldIndex = FD->getFieldIndex();
1009 uint64_t FieldOffset =
1010 ASTCtx.toCharUnitsFromBits(Layout.getFieldOffset(FieldIndex))
1011 .getQuantity();
1012 return IntPointer{F->Desc, this->Value + FieldOffset};
1013}
1014
1016 unsigned BaseOffset) const {
1017 if (!Desc) {
1018 assert(Value == 0);
1019 return *this;
1020 }
1021 const Record *R = Desc->ElemRecord;
1022 const Descriptor *BaseDesc = nullptr;
1023
1024 // This iterates over bases and checks for the proper offset. That's
1025 // potentially slow but this case really shouldn't happen a lot.
1026 for (const Record::Base &B : R->bases()) {
1027 if (B.Offset == BaseOffset) {
1028 BaseDesc = B.Desc;
1029 break;
1030 }
1031 }
1032 assert(BaseDesc);
1033
1034 // Adjust the offset value based on the information from the record layout.
1035 const ASTRecordLayout &Layout = ASTCtx.getASTRecordLayout(R->getDecl());
1036 CharUnits BaseLayoutOffset =
1037 Layout.getBaseClassOffset(cast<CXXRecordDecl>(BaseDesc->asDecl()));
1038
1039 return {BaseDesc, Value + BaseLayoutOffset.getQuantity()};
1040}
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:227
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:4442
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:3178
unsigned getFieldIndex() const
Returns the index of this field within its record, as appropriate for passing to ASTRecordLayout::get...
Definition Decl.h:3263
const RecordDecl * getParent() const
Returns the parent of this field declaration, which is the struct in which this field is defined.
Definition Decl.h:3414
Represents a function declaration or definition.
Definition Decl.h:2018
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:4527
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:8669
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:4230
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:137
const FunctionDecl * getDecl() const
Returns the original FunctionDecl.
Definition Function.h:134
static bool hasSameBase(const Pointer &A, const Pointer &B)
Checks if two pointers are comparable.
Definition Pointer.cpp:688
void deactivate() const
Deactivates an entire strurcutre.
Definition Pointer.cpp:684
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:739
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:889
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:624
static std::optional< std::pair< Pointer, Pointer > > computeSplitPoint(const Pointer &A, const Pointer &B)
Definition Pointer.cpp:749
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:583
bool pointsToStringLiteral() const
Definition Pointer.cpp:728
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:717
bool allElementsAlive() const
Definition Pointer.cpp:607
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:706
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:712
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:849
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:888
TypeidPointer Typeid
Definition Pointer.h:890
std::optional< APValue > toRValue(const Context &Ctx, QualType ResultType) const
Converts the pointer to an APValue that is an rvalue.
Definition Pointer.cpp:790
const FunctionPointer & asFunctionPointer() const
Definition Pointer.h:470
bool allElementsInitialized() const
Definition Pointer.cpp:590
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:562
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:123
unsigned getNumElems() const
Returns the number of elements stored in the block.
Definition Descriptor.h:260
bool isPrimitive() const
Checks if the descriptor is of a primitive.
Definition Descriptor.h:274
QualType getElemQualType() const
const ValueDecl * asValueDecl() const
Definition Descriptor.h:216
QualType getType() const
const Decl * asDecl() const
Definition Descriptor.h:212
unsigned getMetadataSize() const
Returns the size of the metadata.
Definition Descriptor.h:257
QualType getDataType(const ASTContext &Ctx) const
const bool IsArray
Flag indicating if the block is an array.
Definition Descriptor.h:169
bool isPrimitiveArray() const
Checks if the descriptor is of an array of primitives.
Definition Descriptor.h:265
const FieldDecl * asFieldDecl() const
Definition Descriptor.h:224
PrimType getPrimType() const
Definition Descriptor.h:242
const Expr * asExpr() const
Definition Descriptor.h:213
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:68
unsigned IsActive
Flag indicating if the field is the active member of a union.
Definition Descriptor.h:90
unsigned Offset
Offset inside the structure/array.
Definition Descriptor.h:70
std::optional< IntPointer > atOffset(const ASTContext &ASTCtx, unsigned Offset) const
Definition Pointer.cpp:985
IntPointer baseCast(const ASTContext &ASTCtx, unsigned BaseOffset) const
Definition Pointer.cpp:1015
const Descriptor * Desc
Definition Pointer.h:48
const Type * TypeInfoType
Definition Pointer.h:62