clang 22.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 "Context.h"
12#include "Floating.h"
13#include "Function.h"
14#include "Integral.h"
15#include "InterpBlock.h"
16#include "MemberPointer.h"
17#include "PrimType.h"
18#include "Record.h"
19#include "clang/AST/Expr.h"
20#include "clang/AST/ExprCXX.h"
22
23using namespace clang;
24using namespace clang::interp;
25
27 : Pointer(Pointee, Pointee->getDescriptor()->getMetadataSize(),
28 Pointee->getDescriptor()->getMetadataSize()) {}
29
30Pointer::Pointer(Block *Pointee, uint64_t BaseAndOffset)
31 : Pointer(Pointee, BaseAndOffset, BaseAndOffset) {}
32
33Pointer::Pointer(Block *Pointee, unsigned Base, uint64_t Offset)
34 : Offset(Offset), StorageKind(Storage::Block) {
35 assert((Base == RootPtrMark || Base % alignof(void *) == 0) && "wrong base");
36 assert(Base >= Pointee->getDescriptor()->getMetadataSize());
37
38 BS = {Pointee, Base, nullptr, nullptr};
39
40 if (Pointee)
41 Pointee->addPointer(this);
42}
43
45 : Offset(P.Offset), StorageKind(P.StorageKind) {
46 switch (StorageKind) {
47 case Storage::Int:
48 Int = P.Int;
49 break;
50 case Storage::Block:
51 BS = P.BS;
52 if (BS.Pointee)
53 BS.Pointee->addPointer(this);
54 break;
55 case Storage::Fn:
56 Fn = P.Fn;
57 break;
58 case Storage::Typeid:
59 Typeid = P.Typeid;
60 break;
61 }
62}
63
64Pointer::Pointer(Pointer &&P) : Offset(P.Offset), StorageKind(P.StorageKind) {
65 switch (StorageKind) {
66 case Storage::Int:
67 Int = P.Int;
68 break;
69 case Storage::Block:
70 BS = P.BS;
71 if (BS.Pointee)
72 BS.Pointee->replacePointer(&P, this);
73 break;
74 case Storage::Fn:
75 Fn = P.Fn;
76 break;
77 case Storage::Typeid:
78 Typeid = P.Typeid;
79 break;
80 }
81}
82
84 if (!isBlockPointer())
85 return;
86
87 if (Block *Pointee = BS.Pointee) {
88 Pointee->removePointer(this);
89 BS.Pointee = nullptr;
90 Pointee->cleanup();
91 }
92}
93
95 // If the current storage type is Block, we need to remove
96 // this pointer from the block.
97 if (isBlockPointer()) {
98 if (P.isBlockPointer() && this->block() == P.block()) {
99 Offset = P.Offset;
100 BS.Base = P.BS.Base;
101 return *this;
102 }
103
104 if (Block *Pointee = BS.Pointee) {
105 Pointee->removePointer(this);
106 BS.Pointee = nullptr;
107 Pointee->cleanup();
108 }
109 }
110
111 StorageKind = P.StorageKind;
112 Offset = P.Offset;
113
114 switch (StorageKind) {
115 case Storage::Int:
116 Int = P.Int;
117 break;
118 case Storage::Block:
119 BS = P.BS;
120
121 if (BS.Pointee)
122 BS.Pointee->addPointer(this);
123 break;
124 case Storage::Fn:
125 Fn = P.Fn;
126 break;
127 case Storage::Typeid:
128 Typeid = P.Typeid;
129 }
130 return *this;
131}
132
134 // If the current storage type is Block, we need to remove
135 // this pointer from the block.
136 if (isBlockPointer()) {
137 if (P.isBlockPointer() && this->block() == P.block()) {
138 Offset = P.Offset;
139 BS.Base = P.BS.Base;
140 return *this;
141 }
142
143 if (Block *Pointee = BS.Pointee) {
144 Pointee->removePointer(this);
145 BS.Pointee = nullptr;
146 Pointee->cleanup();
147 }
148 }
149
150 StorageKind = P.StorageKind;
151 Offset = P.Offset;
152
153 switch (StorageKind) {
154 case Storage::Int:
155 Int = P.Int;
156 break;
157 case Storage::Block:
158 BS = P.BS;
159
160 if (BS.Pointee)
161 BS.Pointee->addPointer(this);
162 break;
163 case Storage::Fn:
164 Fn = P.Fn;
165 break;
166 case Storage::Typeid:
167 Typeid = P.Typeid;
168 }
169 return *this;
170}
171
174
175 if (isZero())
176 return APValue(static_cast<const Expr *>(nullptr), CharUnits::Zero(), Path,
177 /*IsOnePastEnd=*/false, /*IsNullPtr=*/true);
178 if (isIntegralPointer())
179 return APValue(static_cast<const Expr *>(nullptr),
181 Path,
182 /*IsOnePastEnd=*/false, /*IsNullPtr=*/false);
183 if (isFunctionPointer()) {
185 if (const FunctionDecl *FD = FP.getFunction()->getDecl())
186 return APValue(FD, CharUnits::fromQuantity(Offset), {},
187 /*OnePastTheEnd=*/false, /*IsNull=*/false);
188 return APValue(FP.getFunction()->getExpr(), CharUnits::fromQuantity(Offset),
189 {},
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().getType()->isArrayType())
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().getType()->isArrayType())
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) { " << asFunctionPointer().getFunction() << " + " << Offset
356 << " }";
357 break;
358 case Storage::Typeid:
359 OS << "(Typeid) { " << (const void *)asTypeidPointer().TypePtr << ", "
360 << (const void *)asTypeidPointer().TypeInfoType << " + " << Offset
361 << "}";
362 }
363}
364
366 switch (StorageKind) {
367 case Storage::Int:
368 return Int.Value + Offset;
369 case Storage::Block:
370 // See below.
371 break;
372 case Storage::Fn:
373 return Fn.getIntegerRepresentation() + Offset;
374 case Storage::Typeid:
375 return reinterpret_cast<uintptr_t>(asTypeidPointer().TypePtr) + Offset;
376 }
377
378 size_t Result = 0;
379 Pointer P = *this;
380 while (true) {
381
382 if (P.isVirtualBaseClass()) {
383 Result += getInlineDesc()->Offset;
384 P = P.getBase();
385 continue;
386 }
387
388 if (P.isBaseClass()) {
389 if (P.getRecord()->getNumVirtualBases() > 0)
390 Result += P.getInlineDesc()->Offset;
391 P = P.getBase();
392 continue;
393 }
394 if (P.isArrayElement()) {
395 P = P.expand();
396 Result += (P.getIndex() * P.elemSize());
397 P = P.getArray();
398 continue;
399 }
400
401 if (P.isRoot()) {
402 if (P.isOnePastEnd())
403 ++Result;
404 break;
405 }
406
407 if (const Record *R = P.getBase().getRecord(); R && R->isUnion()) {
408 if (P.isOnePastEnd())
409 ++Result;
410 // Direct child of a union - all have offset 0.
411 P = P.getBase();
412 continue;
413 }
414
415 // Fields, etc.
416 Result += P.getInlineDesc()->Offset;
417 if (P.isOnePastEnd())
418 ++Result;
419
420 P = P.getBase();
421 if (P.isRoot())
422 break;
423 }
424
425 return Result;
426}
427
428std::string Pointer::toDiagnosticString(const ASTContext &Ctx) const {
429 if (isZero())
430 return "nullptr";
431
432 if (isIntegralPointer())
433 return (Twine("&(") + Twine(asIntPointer().Value + Offset) + ")").str();
434
435 if (isFunctionPointer())
437
438 return toAPValue(Ctx).getAsString(Ctx, getType());
439}
440
442 if (!isBlockPointer())
443 return true;
444
445 if (isRoot() && BS.Base == sizeof(GlobalInlineDescriptor) &&
446 Offset == BS.Base) {
447 const auto &GD = block()->getBlockDesc<GlobalInlineDescriptor>();
449 }
450
451 assert(BS.Pointee && "Cannot check if null pointer was initialized");
452 const Descriptor *Desc = getFieldDesc();
453 assert(Desc);
454 if (Desc->isPrimitiveArray())
456
457 if (asBlockPointer().Base == 0)
458 return true;
459 // Field has its bit in an inline descriptor.
460 return getInlineDesc()->IsInitialized;
461}
462
463bool Pointer::isElementInitialized(unsigned Index) const {
464 if (!isBlockPointer())
465 return true;
466
467 const Descriptor *Desc = getFieldDesc();
468 assert(Desc);
469
470 if (isStatic() && BS.Base == 0)
471 return true;
472
473 if (isRoot() && BS.Base == sizeof(GlobalInlineDescriptor) &&
474 Offset == BS.Base) {
475 const auto &GD = block()->getBlockDesc<GlobalInlineDescriptor>();
477 }
478
479 if (Desc->isPrimitiveArray()) {
480 InitMapPtr &IM = getInitMap();
481 if (!IM)
482 return false;
483
484 if (IM->first)
485 return true;
486
487 return IM->second->isElementInitialized(Index);
488 }
489 return isInitialized();
490}
491
493 if (!isBlockPointer())
494 return;
495
496 assert(BS.Pointee && "Cannot initialize null pointer");
497
498 if (isRoot() && BS.Base == sizeof(GlobalInlineDescriptor) &&
499 Offset == BS.Base) {
500 auto &GD = BS.Pointee->getBlockDesc<GlobalInlineDescriptor>();
502 return;
503 }
504
505 const Descriptor *Desc = getFieldDesc();
506 assert(Desc);
507 if (Desc->isPrimitiveArray()) {
508 if (Desc->getNumElems() != 0)
510 return;
511 }
512
513 // Field has its bit in an inline descriptor.
514 assert(BS.Base != 0 && "Only composite fields can be initialised");
515 getInlineDesc()->IsInitialized = true;
516}
517
518void Pointer::initializeElement(unsigned Index) const {
519 // Primitive global arrays don't have an initmap.
520 if (isStatic() && BS.Base == 0)
521 return;
522
523 assert(Index < getFieldDesc()->getNumElems());
524
525 InitMapPtr &IM = getInitMap();
526 if (!IM) {
527 const Descriptor *Desc = getFieldDesc();
528 IM = std::make_pair(false, std::make_shared<InitMap>(Desc->getNumElems()));
529 }
530
531 assert(IM);
532
533 // All initialized.
534 if (IM->first)
535 return;
536
537 if (IM->second->initializeElement(Index)) {
538 IM->first = true;
539 IM->second.reset();
540 }
541}
542
544 assert(getFieldDesc()->isPrimitiveArray());
545 assert(isArrayRoot());
546
547 InitMapPtr &IM = getInitMap();
548 if (!IM) {
549 IM = std::make_pair(true, nullptr);
550 } else {
551 IM->first = true;
552 IM->second.reset();
553 }
554}
555
557 assert(getFieldDesc()->isPrimitiveArray());
558 assert(isArrayRoot());
559
560 if (isStatic() && BS.Base == 0)
561 return true;
562
563 if (isRoot() && BS.Base == sizeof(GlobalInlineDescriptor) &&
564 Offset == BS.Base) {
565 const auto &GD = block()->getBlockDesc<GlobalInlineDescriptor>();
567 }
568
569 InitMapPtr &IM = getInitMap();
570 return IM && IM->first;
571}
572
573void Pointer::activate() const {
574 // Field has its bit in an inline descriptor.
575 assert(BS.Base != 0 && "Only composite fields can be activated");
576
577 if (isRoot() && BS.Base == sizeof(GlobalInlineDescriptor))
578 return;
579 if (!getInlineDesc()->InUnion)
580 return;
581
583 activate = [&activate](Pointer &P) -> void {
584 P.getInlineDesc()->IsActive = true;
585 if (const Record *R = P.getRecord(); R && !R->isUnion()) {
586 for (const Record::Field &F : R->fields()) {
587 Pointer FieldPtr = P.atField(F.Offset);
588 if (!FieldPtr.getInlineDesc()->IsActive)
589 activate(FieldPtr);
590 }
591 // FIXME: Bases?
592 }
593 };
594
596 deactivate = [&deactivate](Pointer &P) -> void {
597 P.getInlineDesc()->IsActive = false;
598
599 if (const Record *R = P.getRecord()) {
600 for (const Record::Field &F : R->fields()) {
601 Pointer FieldPtr = P.atField(F.Offset);
602 if (FieldPtr.getInlineDesc()->IsActive)
603 deactivate(FieldPtr);
604 }
605 // FIXME: Bases?
606 }
607 };
608
609 Pointer B = *this;
610 while (!B.isRoot() && B.inUnion()) {
611 activate(B);
612
613 // When walking up the pointer chain, deactivate
614 // all union child pointers that aren't on our path.
615 Pointer Cur = B;
616 B = B.getBase();
617 if (const Record *BR = B.getRecord(); BR && BR->isUnion()) {
618 for (const Record::Field &F : BR->fields()) {
619 Pointer FieldPtr = B.atField(F.Offset);
620 if (FieldPtr != Cur)
621 deactivate(FieldPtr);
622 }
623 }
624 }
625}
626
628 // TODO: this only appears in constructors, so nothing to deactivate.
629}
630
631bool Pointer::hasSameBase(const Pointer &A, const Pointer &B) {
632 // Two null pointers always have the same base.
633 if (A.isZero() && B.isZero())
634 return true;
635
637 return true;
639 return true;
640 if (A.isTypeidPointer() && B.isTypeidPointer())
641 return true;
642
643 if (A.StorageKind != B.StorageKind)
644 return false;
645
647}
648
649bool Pointer::pointToSameBlock(const Pointer &A, const Pointer &B) {
650 if (!A.isBlockPointer() || !B.isBlockPointer())
651 return false;
652 return A.block() == B.block();
653}
654
655bool Pointer::hasSameArray(const Pointer &A, const Pointer &B) {
656 return hasSameBase(A, B) && A.BS.Base == B.BS.Base &&
658}
659
661 if (isZero() || !isBlockPointer())
662 return false;
663
664 if (block()->isDynamic())
665 return false;
666
667 const Expr *E = block()->getDescriptor()->asExpr();
669}
670
672 if (isZero() || !isBlockPointer())
673 return false;
674
675 if (block()->isDynamic())
676 return false;
677
678 const Expr *E = block()->getDescriptor()->asExpr();
679 return isa_and_nonnull<StringLiteral>(E);
680}
681
682std::optional<std::pair<Pointer, Pointer>>
684 if (!A.isBlockPointer() || !B.isBlockPointer())
685 return std::nullopt;
686
688 return std::nullopt;
689 if (A.isRoot() && B.isRoot())
690 return std::nullopt;
691
692 if (A == B)
693 return std::make_pair(A, B);
694
695 auto getBase = [](const Pointer &P) -> Pointer {
696 if (P.isArrayElement())
697 return P.expand().getArray();
698 return P.getBase();
699 };
700
701 Pointer IterA = A;
702 Pointer IterB = B;
703 Pointer CurA = IterA;
704 Pointer CurB = IterB;
705 for (;;) {
706 if (IterA.asBlockPointer().Base > IterB.asBlockPointer().Base) {
707 CurA = IterA;
708 IterA = getBase(IterA);
709 } else {
710 CurB = IterB;
711 IterB = getBase(IterB);
712 }
713
714 if (IterA == IterB)
715 return std::make_pair(CurA, CurB);
716
717 if (IterA.isRoot() && IterB.isRoot())
718 return std::nullopt;
719 }
720
721 llvm_unreachable("The loop above should've returned.");
722}
723
724std::optional<APValue> Pointer::toRValue(const Context &Ctx,
725 QualType ResultType) const {
726 const ASTContext &ASTCtx = Ctx.getASTContext();
727 assert(!ResultType.isNull());
728 // Method to recursively traverse composites.
729 std::function<bool(QualType, const Pointer &, APValue &)> Composite;
730 Composite = [&Composite, &Ctx, &ASTCtx](QualType Ty, const Pointer &Ptr,
731 APValue &R) {
732 if (const auto *AT = Ty->getAs<AtomicType>())
733 Ty = AT->getValueType();
734
735 // Invalid pointers.
736 if (Ptr.isDummy() || !Ptr.isLive() || !Ptr.isBlockPointer() ||
737 Ptr.isPastEnd())
738 return false;
739
740 // Primitive values.
741 if (OptPrimType T = Ctx.classify(Ty)) {
742 TYPE_SWITCH(*T, R = Ptr.deref<T>().toAPValue(ASTCtx));
743 return true;
744 }
745
746 if (const auto *RT = Ty->getAsCanonical<RecordType>()) {
747 const auto *Record = Ptr.getRecord();
748 assert(Record && "Missing record descriptor");
749
750 bool Ok = true;
751 if (RT->getDecl()->isUnion()) {
752 const FieldDecl *ActiveField = nullptr;
754 for (const auto &F : Record->fields()) {
755 const Pointer &FP = Ptr.atField(F.Offset);
756 QualType FieldTy = F.Decl->getType();
757 if (FP.isActive()) {
758 if (OptPrimType T = Ctx.classify(FieldTy)) {
759 TYPE_SWITCH(*T, Value = FP.deref<T>().toAPValue(ASTCtx));
760 } else {
761 Ok &= Composite(FieldTy, FP, Value);
762 }
763 ActiveField = FP.getFieldDesc()->asFieldDecl();
764 break;
765 }
766 }
767 R = APValue(ActiveField, Value);
768 } else {
769 unsigned NF = Record->getNumFields();
770 unsigned NB = Record->getNumBases();
771 unsigned NV = Ptr.isBaseClass() ? 0 : Record->getNumVirtualBases();
772
773 R = APValue(APValue::UninitStruct(), NB, NF);
774
775 for (unsigned I = 0; I < NF; ++I) {
776 const Record::Field *FD = Record->getField(I);
777 QualType FieldTy = FD->Decl->getType();
778 const Pointer &FP = Ptr.atField(FD->Offset);
779 APValue &Value = R.getStructField(I);
780
781 if (OptPrimType T = Ctx.classify(FieldTy)) {
782 TYPE_SWITCH(*T, Value = FP.deref<T>().toAPValue(ASTCtx));
783 } else {
784 Ok &= Composite(FieldTy, FP, Value);
785 }
786 }
787
788 for (unsigned I = 0; I < NB; ++I) {
789 const Record::Base *BD = Record->getBase(I);
790 QualType BaseTy = Ctx.getASTContext().getCanonicalTagType(BD->Decl);
791 const Pointer &BP = Ptr.atField(BD->Offset);
792 Ok &= Composite(BaseTy, BP, R.getStructBase(I));
793 }
794
795 for (unsigned I = 0; I < NV; ++I) {
796 const Record::Base *VD = Record->getVirtualBase(I);
797 QualType VirtBaseTy =
798 Ctx.getASTContext().getCanonicalTagType(VD->Decl);
799 const Pointer &VP = Ptr.atField(VD->Offset);
800 Ok &= Composite(VirtBaseTy, VP, R.getStructBase(NB + I));
801 }
802 }
803 return Ok;
804 }
805
806 if (Ty->isIncompleteArrayType()) {
807 R = APValue(APValue::UninitArray(), 0, 0);
808 return true;
809 }
810
811 if (const auto *AT = Ty->getAsArrayTypeUnsafe()) {
812 const size_t NumElems = Ptr.getNumElems();
813 QualType ElemTy = AT->getElementType();
814 R = APValue(APValue::UninitArray{}, NumElems, NumElems);
815
816 bool Ok = true;
817 OptPrimType ElemT = Ctx.classify(ElemTy);
818 for (unsigned I = 0; I != NumElems; ++I) {
819 APValue &Slot = R.getArrayInitializedElt(I);
820 if (ElemT) {
821 TYPE_SWITCH(*ElemT, Slot = Ptr.elem<T>(I).toAPValue(ASTCtx));
822 } else {
823 Ok &= Composite(ElemTy, Ptr.atIndex(I).narrow(), Slot);
824 }
825 }
826 return Ok;
827 }
828
829 // Complex types.
830 if (const auto *CT = Ty->getAs<ComplexType>()) {
831 // Can happen via C casts.
832 if (!Ptr.getFieldDesc()->isPrimitiveArray())
833 return false;
834
835 QualType ElemTy = CT->getElementType();
836 if (ElemTy->isIntegerType()) {
837 OptPrimType ElemT = Ctx.classify(ElemTy);
838 assert(ElemT);
839 INT_TYPE_SWITCH(*ElemT, {
840 auto V1 = Ptr.elem<T>(0);
841 auto V2 = Ptr.elem<T>(1);
842 R = APValue(V1.toAPSInt(), V2.toAPSInt());
843 return true;
844 });
845 } else if (ElemTy->isFloatingType()) {
846 R = APValue(Ptr.elem<Floating>(0).getAPFloat(),
847 Ptr.elem<Floating>(1).getAPFloat());
848 return true;
849 }
850 return false;
851 }
852
853 // Vector types.
854 if (const auto *VT = Ty->getAs<VectorType>()) {
855 assert(Ptr.getFieldDesc()->isPrimitiveArray());
856 QualType ElemTy = VT->getElementType();
857 PrimType ElemT = *Ctx.classify(ElemTy);
858
860 Values.reserve(VT->getNumElements());
861 for (unsigned I = 0; I != VT->getNumElements(); ++I) {
862 TYPE_SWITCH(ElemT,
863 { Values.push_back(Ptr.elem<T>(I).toAPValue(ASTCtx)); });
864 }
865
866 assert(Values.size() == VT->getNumElements());
867 R = APValue(Values.data(), Values.size());
868 return true;
869 }
870
871 llvm_unreachable("invalid value to return");
872 };
873
874 // Invalid to read from.
875 if (isDummy() || !isLive() || isPastEnd())
876 return std::nullopt;
877
878 // We can return these as rvalues, but we can't deref() them.
879 if (isZero() || isIntegralPointer())
880 return toAPValue(ASTCtx);
881
882 // Just load primitive types.
883 if (OptPrimType T = Ctx.classify(ResultType)) {
884 TYPE_SWITCH(*T, return this->deref<T>().toAPValue(ASTCtx));
885 }
886
887 // Return the composite type.
889 if (!Composite(ResultType, *this, Result))
890 return std::nullopt;
891 return Result;
892}
893
894std::optional<IntPointer> IntPointer::atOffset(const ASTContext &ASTCtx,
895 unsigned Offset) const {
896 if (!this->Desc)
897 return *this;
898 const Record *R = this->Desc->ElemRecord;
899 if (!R)
900 return *this;
901
902 const Record::Field *F = nullptr;
903 for (auto &It : R->fields()) {
904 if (It.Offset == Offset) {
905 F = &It;
906 break;
907 }
908 }
909 if (!F)
910 return *this;
911
912 const FieldDecl *FD = F->Decl;
913 if (FD->getParent()->isInvalidDecl())
914 return std::nullopt;
915
916 const ASTRecordLayout &Layout = ASTCtx.getASTRecordLayout(FD->getParent());
917 unsigned FieldIndex = FD->getFieldIndex();
918 uint64_t FieldOffset =
919 ASTCtx.toCharUnitsFromBits(Layout.getFieldOffset(FieldIndex))
920 .getQuantity();
921 return IntPointer{F->Desc, this->Value + FieldOffset};
922}
923
925 unsigned BaseOffset) const {
926 if (!Desc) {
927 assert(Value == 0);
928 return *this;
929 }
930 const Record *R = Desc->ElemRecord;
931 const Descriptor *BaseDesc = nullptr;
932
933 // This iterates over bases and checks for the proper offset. That's
934 // potentially slow but this case really shouldn't happen a lot.
935 for (const Record::Base &B : R->bases()) {
936 if (B.Offset == BaseOffset) {
937 BaseDesc = B.Desc;
938 break;
939 }
940 }
941 assert(BaseDesc);
942
943 // Adjust the offset value based on the information from the record layout.
944 const ASTRecordLayout &Layout = ASTCtx.getASTRecordLayout(R->getDecl());
945 CharUnits BaseLayoutOffset =
946 Layout.getBaseClassOffset(cast<CXXRecordDecl>(BaseDesc->asDecl()));
947
948 return {BaseDesc, Value + BaseLayoutOffset.getQuantity()};
949}
Defines the clang::Expr interface and subclasses for C++ expressions.
#define INT_TYPE_SWITCH(Expr, B)
Definition PrimType.h:232
#define TYPE_SWITCH(Expr, B)
Definition PrimType.h:211
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:207
static LValuePathEntry ArrayIndex(uint64_t Index)
Definition APValue.h:215
APValue - This class implements a discriminated union of [uninitialized] [APSInt] [APFloat],...
Definition APValue.h:122
APValue & getArrayInitializedElt(unsigned I)
Definition APValue.h:576
std::string getAsString(const ASTContext &Ctx, QualType Ty) const
Definition APValue.cpp:956
Holds long-lived AST nodes (such as types and decls) that can be referred to throughout the semantic ...
Definition ASTContext.h:220
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
Complex values, per C99 6.2.5p11.
Definition TypeBase.h:3275
Decl()=delete
bool isInvalidDecl() const
Definition DeclBase.h:588
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:3160
unsigned getFieldIndex() const
Returns the index of this field within its record, as appropriate for passing to ASTRecordLayout::get...
Definition Decl.h:3245
const RecordDecl * getParent() const
Returns the parent of this field declaration, which is the struct in which this field is defined.
Definition Decl.h:3396
Represents a function declaration or definition.
Definition Decl.h:2000
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:4505
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 isArrayType() const
Definition TypeBase.h:8614
bool isIntegerType() const
isIntegerType() does not include complex integers (a GCC extension).
Definition TypeBase.h:8915
bool isFloatingType() const
Definition Type.cpp:2304
Represent the declaration of a variable (in which case it is an lvalue) a function (in which case it ...
Definition Decl.h:712
Represents a GCC generic vector type.
Definition TypeBase.h:4175
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:41
ASTContext & getASTContext() const
Returns the AST context.
Definition Context.h:79
OptPrimType classify(QualType T) const
Classifies a type.
Definition Context.cpp:362
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 Function * getFunction() const
std::string toDiagnosticString(const ASTContext &Ctx) const
const BlockExpr * getExpr() const
Definition Function.h:114
const FunctionDecl * getDecl() const
Returns the original FunctionDecl.
Definition Function.h:111
static bool hasSameBase(const Pointer &A, const Pointer &B)
Checks if two pointers are comparable.
Definition Pointer.cpp:631
void deactivate() const
Deactivates an entire strurcutre.
Definition Pointer.cpp:627
bool isInitialized() const
Checks if an object was initialized.
Definition Pointer.cpp:441
bool isStatic() const
Checks if the storage is static.
Definition Pointer.h:499
bool isDynamic() const
Checks if the storage has been dynamically allocated.
Definition Pointer.h:514
bool inUnion() const
Definition Pointer.h:407
bool isZeroSizeArray() const
Checks if the pointer is pointing to a zero-size array.
Definition Pointer.h:659
bool isElementInitialized(unsigned Index) const
Like isInitialized(), but for primitive arrays.
Definition Pointer.cpp:463
FunctionPointer Fn
Definition Pointer.h:831
bool isDummy() const
Checks if the pointer points to a dummy value.
Definition Pointer.h:552
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:617
bool isActive() const
Checks if the object is active.
Definition Pointer.h:541
Pointer atField(unsigned Off) const
Creates a pointer to a field.
Definition Pointer.h:174
T & deref() const
Dereferences the pointer, if it's live.
Definition Pointer.h:668
unsigned getNumElems() const
Returns the number of elements.
Definition Pointer.h:601
Pointer getArray() const
Returns the parent array.
Definition Pointer.h:321
bool isUnknownSizeArray() const
Checks if the structure is an array of unknown size.
Definition Pointer.h:420
void activate() const
Activats a field.
Definition Pointer.cpp:573
static std::optional< std::pair< Pointer, Pointer > > computeSplitPoint(const Pointer &A, const Pointer &B)
Definition Pointer.cpp:683
const TypeidPointer & asTypeidPointer() const
Definition Pointer.h:468
bool isIntegralPointer() const
Definition Pointer.h:474
QualType getType() const
Returns the type of the innermost field.
Definition Pointer.h:341
bool isArrayElement() const
Checks if the pointer points to an array.
Definition Pointer.h:426
void initializeAllElements() const
Initialize all elements of a primitive array at once.
Definition Pointer.cpp:543
bool pointsToStringLiteral() const
Definition Pointer.cpp:671
bool isArrayRoot() const
Whether this array refers to an array, but not to the first element.
Definition Pointer.h:399
bool isLive() const
Checks if the pointer is live.
Definition Pointer.h:273
bool pointsToLiteral() const
Whether this points to a block that's been created for a "literal lvalue", i.e.
Definition Pointer.cpp:660
Pointer getBase() const
Returns a pointer to the object of which this pointer is a field.
Definition Pointer.h:312
bool isTypeidPointer() const
Definition Pointer.h:476
std::string toDiagnosticString(const ASTContext &Ctx) const
Converts the pointer to a string usable in diagnostics.
Definition Pointer.cpp:428
bool isZero() const
Checks if the pointer is null.
Definition Pointer.h:259
Pointer & operator=(const Pointer &P)
Definition Pointer.cpp:94
const IntPointer & asIntPointer() const
Definition Pointer.h:460
bool isRoot() const
Pointer points directly to a block.
Definition Pointer.h:442
const Descriptor * getDeclDesc() const
Accessor for information about the declaration site.
Definition Pointer.h:287
static bool pointToSameBlock(const Pointer &A, const Pointer &B)
Checks if both given pointers point to the same block.
Definition Pointer.cpp:649
APValue toAPValue(const ASTContext &ASTCtx) const
Converts the pointer to an APValue.
Definition Pointer.cpp:172
bool isOnePastEnd() const
Checks if the index is one past end.
Definition Pointer.h:634
static bool hasSameArray(const Pointer &A, const Pointer &B)
Checks if two pointers can be subtracted.
Definition Pointer.cpp:655
bool isPastEnd() const
Checks if the pointer points past the end of the object.
Definition Pointer.h:648
Pointer expand() const
Expands a pointer to the containing array, undoing narrowing.
Definition Pointer.h:224
friend class Block
Definition Pointer.h:790
bool isElementPastEnd() const
Checks if the pointer is an out-of-bounds element pointer.
Definition Pointer.h:656
bool isBlockPointer() const
Definition Pointer.h:473
BlockPointer BS
Definition Pointer.h:830
TypeidPointer Typeid
Definition Pointer.h:832
std::optional< APValue > toRValue(const Context &Ctx, QualType ResultType) const
Converts the pointer to an APValue that is an rvalue.
Definition Pointer.cpp:724
const FunctionPointer & asFunctionPointer() const
Definition Pointer.h:464
bool allElementsInitialized() const
Definition Pointer.cpp:556
const Block * block() const
Definition Pointer.h:607
bool isFunctionPointer() const
Definition Pointer.h:475
Pointer getDeclPtr() const
Definition Pointer.h:360
const Descriptor * getFieldDesc() const
Accessors for information about the innermost field.
Definition Pointer.h:331
bool isVirtualBaseClass() const
Definition Pointer.h:548
bool isBaseClass() const
Checks if a structure is a base class.
Definition Pointer.h:547
size_t elemSize() const
Returns the element size of the innermost field.
Definition Pointer.h:363
size_t computeOffsetForComparison() const
Compute an integer that can be used to compare this pointer to another one.
Definition Pointer.cpp:365
const BlockPointer & asBlockPointer() const
Definition Pointer.h:456
void initialize() const
Initializes a field.
Definition Pointer.cpp:492
bool isField() const
Checks if the item is a field in an object.
Definition Pointer.h:279
void initializeElement(unsigned Index) const
Initialized the given element of a primitive array.
Definition Pointer.cpp:518
const Record * getRecord() const
Returns the record descriptor of a class.
Definition Pointer.h:479
Structure/Class descriptor.
Definition Record.h:25
const RecordDecl * getDecl() const
Returns the underlying declaration.
Definition Record.h:53
bool isUnion() const
Checks if the record is a union.
Definition Record.h:57
unsigned getNumBases() const
Definition Record.h:96
const Field * getField(const FieldDecl *FD) const
Returns a field.
Definition Record.cpp:47
llvm::iterator_range< const_base_iter > bases() const
Definition Record.h:92
const Base * getVirtualBase(const RecordDecl *RD) const
Returns a virtual base descriptor.
Definition Record.cpp:65
unsigned getNumFields() const
Definition Record.h:88
unsigned getNumVirtualBases() const
Definition Record.h:107
llvm::iterator_range< const_field_iter > fields() const
Definition Record.h:84
const Base * getBase(const RecordDecl *FD) const
Returns a base descriptor.
Definition Record.cpp:53
#define bool
Definition gpuintrin.h:32
PrimType
Enumeration of the primitive types of the VM.
Definition PrimType.h:34
std::optional< std::pair< bool, std::shared_ptr< InitMap > > > InitMapPtr
Definition Descriptor.h:30
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
const FunctionProtoType * T
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:39
Block * Pointee
The block the pointer is pointing to.
Definition Pointer.h:37
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:249
QualType getElemQualType() const
const ValueDecl * asValueDecl() const
Definition Descriptor.h:214
QualType getType() const
const Decl * asDecl() const
Definition Descriptor.h:210
unsigned getMetadataSize() const
Returns the size of the metadata.
Definition Descriptor.h:246
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:254
const FieldDecl * asFieldDecl() const
Definition Descriptor.h:222
const Expr * asExpr() const
Definition Descriptor.h:211
Descriptor used for global variables.
Definition Descriptor.h:51
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:894
IntPointer baseCast(const ASTContext &ASTCtx, unsigned BaseOffset) const
Definition Pointer.cpp:924
const Descriptor * Desc
Definition Pointer.h:47
const Type * TypeInfoType
Definition Pointer.h:57