clang 19.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 "PrimType.h"
17#include "Record.h"
18
19using namespace clang;
20using namespace clang::interp;
21
23 : Pointer(Pointee, Pointee->getDescriptor()->getMetadataSize(),
24 Pointee->getDescriptor()->getMetadataSize()) {}
25
26Pointer::Pointer(Block *Pointee, uint64_t BaseAndOffset)
27 : Pointer(Pointee, BaseAndOffset, BaseAndOffset) {}
28
30 : Offset(P.Offset), PointeeStorage(P.PointeeStorage),
31 StorageKind(P.StorageKind) {
32
33 if (isBlockPointer() && PointeeStorage.BS.Pointee)
34 PointeeStorage.BS.Pointee->addPointer(this);
35}
36
37Pointer::Pointer(Block *Pointee, unsigned Base, uint64_t Offset)
38 : Offset(Offset), StorageKind(Storage::Block) {
39 assert((Base == RootPtrMark || Base % alignof(void *) == 0) && "wrong base");
40
41 PointeeStorage.BS = {Pointee, Base};
42
43 if (Pointee)
44 Pointee->addPointer(this);
45}
46
48 : Offset(P.Offset), PointeeStorage(P.PointeeStorage),
49 StorageKind(P.StorageKind) {
50
51 if (StorageKind == Storage::Block && PointeeStorage.BS.Pointee)
52 PointeeStorage.BS.Pointee->replacePointer(&P, this);
53}
54
57 return;
58
59 if (PointeeStorage.BS.Pointee) {
60 PointeeStorage.BS.Pointee->removePointer(this);
61 PointeeStorage.BS.Pointee->cleanup();
62 }
63}
64
66 if (!this->isIntegralPointer() || !P.isBlockPointer())
67 assert(P.StorageKind == StorageKind || (this->isZero() && P.isZero()));
68
69 bool WasBlockPointer = isBlockPointer();
70 StorageKind = P.StorageKind;
71 if (StorageKind == Storage::Block) {
72 Block *Old = PointeeStorage.BS.Pointee;
73 if (WasBlockPointer && PointeeStorage.BS.Pointee)
74 PointeeStorage.BS.Pointee->removePointer(this);
75
76 Offset = P.Offset;
77 PointeeStorage.BS = P.PointeeStorage.BS;
78
79 if (PointeeStorage.BS.Pointee)
80 PointeeStorage.BS.Pointee->addPointer(this);
81
82 if (WasBlockPointer && Old)
83 Old->cleanup();
84
85 } else if (StorageKind == Storage::Int) {
86 PointeeStorage.Int = P.PointeeStorage.Int;
87 } else {
88 assert(false && "Unhandled storage kind");
89 }
90}
91
93 if (!this->isIntegralPointer() || !P.isBlockPointer())
94 assert(P.StorageKind == StorageKind || (this->isZero() && P.isZero()));
95
96 bool WasBlockPointer = isBlockPointer();
97 StorageKind = P.StorageKind;
98 if (StorageKind == Storage::Block) {
99 Block *Old = PointeeStorage.BS.Pointee;
100 if (WasBlockPointer && PointeeStorage.BS.Pointee)
101 PointeeStorage.BS.Pointee->removePointer(this);
102
103 Offset = P.Offset;
104 PointeeStorage.BS = P.PointeeStorage.BS;
105
106 if (PointeeStorage.BS.Pointee)
107 PointeeStorage.BS.Pointee->addPointer(this);
108
109 if (WasBlockPointer && Old)
110 Old->cleanup();
111
112 } else if (StorageKind == Storage::Int) {
113 PointeeStorage.Int = P.PointeeStorage.Int;
114 } else {
115 assert(false && "Unhandled storage kind");
116 }
117}
118
121
122 if (isZero())
123 return APValue(static_cast<const Expr *>(nullptr), CharUnits::Zero(), Path,
124 /*IsOnePastEnd=*/false, /*IsNullPtr=*/true);
125 if (isIntegralPointer())
126 return APValue(static_cast<const Expr *>(nullptr),
128 Path,
129 /*IsOnePastEnd=*/false, /*IsNullPtr=*/false);
130
131 // Build the lvalue base from the block.
132 const Descriptor *Desc = getDeclDesc();
134 if (const auto *VD = Desc->asValueDecl())
135 Base = VD;
136 else if (const auto *E = Desc->asExpr())
137 Base = E;
138 else
139 llvm_unreachable("Invalid allocation type");
140
141 if (isDummy() || isUnknownSizeArray() || Desc->asExpr())
142 return APValue(Base, CharUnits::Zero(), Path,
143 /*IsOnePastEnd=*/false, /*IsNullPtr=*/false);
144
145 // TODO: compute the offset into the object.
146 CharUnits Offset = CharUnits::Zero();
147 bool IsOnePastEnd = isOnePastEnd();
148
149 // Build the path into the object.
150 Pointer Ptr = *this;
151 while (Ptr.isField() || Ptr.isArrayElement()) {
152 if (Ptr.isArrayElement()) {
153 Path.push_back(APValue::LValuePathEntry::ArrayIndex(Ptr.getIndex()));
154 Ptr = Ptr.getArray();
155 } else {
156 // TODO: figure out if base is virtual
157 bool IsVirtual = false;
158
159 // Create a path entry for the field.
160 const Descriptor *Desc = Ptr.getFieldDesc();
161 if (const auto *BaseOrMember = Desc->asDecl()) {
162 Path.push_back(APValue::LValuePathEntry({BaseOrMember, IsVirtual}));
163 Ptr = Ptr.getBase();
164 continue;
165 }
166 llvm_unreachable("Invalid field type");
167 }
168 }
169
170 // We assemble the LValuePath starting from the innermost pointer to the
171 // outermost one. SO in a.b.c, the first element in Path will refer to
172 // the field 'c', while later code expects it to refer to 'a'.
173 // Just invert the order of the elements.
174 std::reverse(Path.begin(), Path.end());
175
176 return APValue(Base, Offset, Path, IsOnePastEnd, /*IsNullPtr=*/false);
177}
178
179void Pointer::print(llvm::raw_ostream &OS) const {
180 OS << PointeeStorage.BS.Pointee << " (";
181 if (isBlockPointer()) {
182 OS << "Block) {";
183
184 if (isRoot())
185 OS << "rootptr(" << PointeeStorage.BS.Base << "), ";
186 else
187 OS << PointeeStorage.BS.Base << ", ";
188
189 if (isElementPastEnd())
190 OS << "pastend, ";
191 else
192 OS << Offset << ", ";
193
194 if (PointeeStorage.BS.Pointee)
195 OS << PointeeStorage.BS.Pointee->getSize();
196 else
197 OS << "nullptr";
198 } else {
199 OS << "Int) {";
200 OS << PointeeStorage.Int.Value << ", " << PointeeStorage.Int.Desc;
201 }
202 OS << "}";
203}
204
205std::string Pointer::toDiagnosticString(const ASTContext &Ctx) const {
206 if (isZero())
207 return "nullptr";
208
209 if (isIntegralPointer())
210 return (Twine("&(") + Twine(asIntPointer().Value + Offset) + ")").str();
211
212 return toAPValue().getAsString(Ctx, getType());
213}
214
216 if (isIntegralPointer())
217 return true;
218
219 assert(PointeeStorage.BS.Pointee &&
220 "Cannot check if null pointer was initialized");
221 const Descriptor *Desc = getFieldDesc();
222 assert(Desc);
223 if (Desc->isPrimitiveArray()) {
224 if (isStatic() && PointeeStorage.BS.Base == 0)
225 return true;
226
227 InitMapPtr &IM = getInitMap();
228
229 if (!IM)
230 return false;
231
232 if (IM->first)
233 return true;
234
235 return IM->second->isElementInitialized(getIndex());
236 }
237
238 // Field has its bit in an inline descriptor.
239 return PointeeStorage.BS.Base == 0 || getInlineDesc()->IsInitialized;
240}
241
243 if (isIntegralPointer())
244 return;
245
246 assert(PointeeStorage.BS.Pointee && "Cannot initialize null pointer");
247 const Descriptor *Desc = getFieldDesc();
248
249 assert(Desc);
250 if (Desc->isPrimitiveArray()) {
251 // Primitive global arrays don't have an initmap.
252 if (isStatic() && PointeeStorage.BS.Base == 0)
253 return;
254
255 // Nothing to do for these.
256 if (Desc->getNumElems() == 0)
257 return;
258
259 InitMapPtr &IM = getInitMap();
260 if (!IM)
261 IM =
262 std::make_pair(false, std::make_shared<InitMap>(Desc->getNumElems()));
263
264 assert(IM);
265
266 // All initialized.
267 if (IM->first)
268 return;
269
270 if (IM->second->initializeElement(getIndex())) {
271 IM->first = true;
272 IM->second.reset();
273 }
274 return;
275 }
276
277 // Field has its bit in an inline descriptor.
278 assert(PointeeStorage.BS.Base != 0 &&
279 "Only composite fields can be initialised");
280 getInlineDesc()->IsInitialized = true;
281}
282
283void Pointer::activate() const {
284 // Field has its bit in an inline descriptor.
285 assert(PointeeStorage.BS.Base != 0 &&
286 "Only composite fields can be initialised");
287 getInlineDesc()->IsActive = true;
288}
289
291 // TODO: this only appears in constructors, so nothing to deactivate.
292}
293
294bool Pointer::hasSameBase(const Pointer &A, const Pointer &B) {
295 // Two null pointers always have the same base.
296 if (A.isZero() && B.isZero())
297 return true;
298
300 return true;
301
303 return A.getSource() == B.getSource();
304
306}
307
308bool Pointer::hasSameArray(const Pointer &A, const Pointer &B) {
309 return hasSameBase(A, B) &&
310 A.PointeeStorage.BS.Base == B.PointeeStorage.BS.Base &&
312}
313
314std::optional<APValue> Pointer::toRValue(const Context &Ctx) const {
315 // Method to recursively traverse composites.
316 std::function<bool(QualType, const Pointer &, APValue &)> Composite;
317 Composite = [&Composite, &Ctx](QualType Ty, const Pointer &Ptr, APValue &R) {
318 if (const auto *AT = Ty->getAs<AtomicType>())
319 Ty = AT->getValueType();
320
321 // Invalid pointers.
322 if (Ptr.isDummy() || !Ptr.isLive() ||
323 (!Ptr.isUnknownSizeArray() && Ptr.isOnePastEnd()))
324 return false;
325
326 // Primitive values.
327 if (std::optional<PrimType> T = Ctx.classify(Ty)) {
328 TYPE_SWITCH(*T, R = Ptr.deref<T>().toAPValue());
329 return true;
330 }
331
332 if (const auto *RT = Ty->getAs<RecordType>()) {
333 const auto *Record = Ptr.getRecord();
334 assert(Record && "Missing record descriptor");
335
336 bool Ok = true;
337 if (RT->getDecl()->isUnion()) {
338 const FieldDecl *ActiveField = nullptr;
340 for (const auto &F : Record->fields()) {
341 const Pointer &FP = Ptr.atField(F.Offset);
342 QualType FieldTy = F.Decl->getType();
343 if (FP.isActive()) {
344 if (std::optional<PrimType> T = Ctx.classify(FieldTy)) {
345 TYPE_SWITCH(*T, Value = FP.deref<T>().toAPValue());
346 } else {
347 Ok &= Composite(FieldTy, FP, Value);
348 }
349 break;
350 }
351 }
352 R = APValue(ActiveField, Value);
353 } else {
354 unsigned NF = Record->getNumFields();
355 unsigned NB = Record->getNumBases();
356 unsigned NV = Ptr.isBaseClass() ? 0 : Record->getNumVirtualBases();
357
358 R = APValue(APValue::UninitStruct(), NB, NF);
359
360 for (unsigned I = 0; I < NF; ++I) {
361 const Record::Field *FD = Record->getField(I);
362 QualType FieldTy = FD->Decl->getType();
363 const Pointer &FP = Ptr.atField(FD->Offset);
364 APValue &Value = R.getStructField(I);
365
366 if (std::optional<PrimType> T = Ctx.classify(FieldTy)) {
367 TYPE_SWITCH(*T, Value = FP.deref<T>().toAPValue());
368 } else {
369 Ok &= Composite(FieldTy, FP, Value);
370 }
371 }
372
373 for (unsigned I = 0; I < NB; ++I) {
374 const Record::Base *BD = Record->getBase(I);
375 QualType BaseTy = Ctx.getASTContext().getRecordType(BD->Decl);
376 const Pointer &BP = Ptr.atField(BD->Offset);
377 Ok &= Composite(BaseTy, BP, R.getStructBase(I));
378 }
379
380 for (unsigned I = 0; I < NV; ++I) {
381 const Record::Base *VD = Record->getVirtualBase(I);
382 QualType VirtBaseTy = Ctx.getASTContext().getRecordType(VD->Decl);
383 const Pointer &VP = Ptr.atField(VD->Offset);
384 Ok &= Composite(VirtBaseTy, VP, R.getStructBase(NB + I));
385 }
386 }
387 return Ok;
388 }
389
390 if (Ty->isIncompleteArrayType()) {
391 R = APValue(APValue::UninitArray(), 0, 0);
392 return true;
393 }
394
395 if (const auto *AT = Ty->getAsArrayTypeUnsafe()) {
396 const size_t NumElems = Ptr.getNumElems();
397 QualType ElemTy = AT->getElementType();
398 R = APValue(APValue::UninitArray{}, NumElems, NumElems);
399
400 bool Ok = true;
401 for (unsigned I = 0; I < NumElems; ++I) {
402 APValue &Slot = R.getArrayInitializedElt(I);
403 const Pointer &EP = Ptr.atIndex(I);
404 if (std::optional<PrimType> T = Ctx.classify(ElemTy)) {
405 TYPE_SWITCH(*T, Slot = EP.deref<T>().toAPValue());
406 } else {
407 Ok &= Composite(ElemTy, EP.narrow(), Slot);
408 }
409 }
410 return Ok;
411 }
412
413 // Complex types.
414 if (const auto *CT = Ty->getAs<ComplexType>()) {
415 QualType ElemTy = CT->getElementType();
416
417 if (ElemTy->isIntegerType()) {
418 std::optional<PrimType> ElemT = Ctx.classify(ElemTy);
419 assert(ElemT);
420 INT_TYPE_SWITCH(*ElemT, {
421 auto V1 = Ptr.atIndex(0).deref<T>();
422 auto V2 = Ptr.atIndex(1).deref<T>();
423 R = APValue(V1.toAPSInt(), V2.toAPSInt());
424 return true;
425 });
426 } else if (ElemTy->isFloatingType()) {
427 R = APValue(Ptr.atIndex(0).deref<Floating>().getAPFloat(),
428 Ptr.atIndex(1).deref<Floating>().getAPFloat());
429 return true;
430 }
431 return false;
432 }
433
434 // Vector types.
435 if (const auto *VT = Ty->getAs<VectorType>()) {
436 assert(Ptr.getFieldDesc()->isPrimitiveArray());
437 QualType ElemTy = VT->getElementType();
438 PrimType ElemT = *Ctx.classify(ElemTy);
439
441 Values.reserve(VT->getNumElements());
442 for (unsigned I = 0; I != VT->getNumElements(); ++I) {
443 TYPE_SWITCH(ElemT, {
444 Values.push_back(Ptr.atIndex(I).deref<T>().toAPValue());
445 });
446 }
447
448 assert(Values.size() == VT->getNumElements());
449 R = APValue(Values.data(), Values.size());
450 return true;
451 }
452
453 llvm_unreachable("invalid value to return");
454 };
455
456 if (isZero())
457 return APValue(static_cast<Expr *>(nullptr), CharUnits::Zero(), {}, false,
458 true);
459
460 if (isDummy() || !isLive())
461 return std::nullopt;
462
463 // Return the composite type.
465 if (!Composite(getType(), *this, Result))
466 return std::nullopt;
467 return Result;
468}
StringRef P
#define INT_TYPE_SWITCH(Expr, B)
Definition: PrimType.h:137
#define TYPE_SWITCH(Expr, B)
Definition: PrimType.h:117
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
APValue & getArrayInitializedElt(unsigned I)
Definition: APValue.h:510
std::string getAsString(const ASTContext &Ctx, QualType Ty) const
Definition: APValue.cpp:946
Holds long-lived AST nodes (such as types and decls) that can be referred to throughout the semantic ...
Definition: ASTContext.h:182
QualType getRecordType(const RecordDecl *Decl) const
CharUnits - This is an opaque type for sizes expressed in character units.
Definition: CharUnits.h:38
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: Type.h:3086
This represents one expression.
Definition: Expr.h:110
Represents a member of a struct/union/class.
Definition: Decl.h:3057
A (possibly-)qualified type.
Definition: Type.h:940
A helper class that allows the use of isa/cast/dyncast to detect TagType objects of structs/unions/cl...
Definition: Type.h:5549
bool isIntegerType() const
isIntegerType() does not include complex integers (a GCC extension).
Definition: Type.h:7945
bool isFloatingType() const
Definition: Type.cpp:2238
Represents a GCC generic vector type.
Definition: Type.h:3969
A memory block, either on the stack or in the heap.
Definition: InterpBlock.h:49
void addPointer(Pointer *P)
Pointer chain management.
Definition: InterpBlock.cpp:19
void cleanup()
Deletes a dead block at the end of its lifetime.
Definition: InterpBlock.cpp:56
Holds all information required to evaluate constexpr code in a module.
Definition: Context.h:40
ASTContext & getASTContext() const
Returns the AST context.
Definition: Context.h:61
std::optional< PrimType > classify(QualType T) const
Classifies a type.
Definition: Context.cpp:119
const APFloat & getAPFloat() const
Definition: Floating.h:40
A pointer to a memory block, live or dead.
Definition: Pointer.h:80
static bool hasSameBase(const Pointer &A, const Pointer &B)
Checks if two pointers are comparable.
Definition: Pointer.cpp:294
Pointer narrow() const
Restricts the scope of an array element pointer.
Definition: Pointer.h:170
void deactivate() const
Deactivates an entire strurcutre.
Definition: Pointer.cpp:290
bool isInitialized() const
Checks if an object was initialized.
Definition: Pointer.cpp:215
bool isStatic() const
Checks if the storage is static.
Definition: Pointer.h:442
Pointer atIndex(uint64_t Idx) const
Offsets a pointer inside an array.
Definition: Pointer.h:137
bool isDummy() const
Checks if the pointer points to a dummy value.
Definition: Pointer.h:488
void print(llvm::raw_ostream &OS) const
Prints the pointer.
Definition: Pointer.cpp:179
int64_t getIndex() const
Returns the index into an array.
Definition: Pointer.h:531
bool isActive() const
Checks if the object is active.
Definition: Pointer.h:480
Pointer atField(unsigned Off) const
Creates a pointer to a field.
Definition: Pointer.h:154
T & deref() const
Dereferences the pointer, if it's live.
Definition: Pointer.h:566
DeclTy getSource() const
Returns the expression or declaration the pointer has been created for.
Definition: Pointer.h:276
Pointer getArray() const
Returns the parent array.
Definition: Pointer.h:294
bool isUnknownSizeArray() const
Checks if the structure is an array of unknown size.
Definition: Pointer.h:384
void activate() const
Activats a field.
Definition: Pointer.cpp:283
void operator=(const Pointer &P)
Definition: Pointer.cpp:65
bool isIntegralPointer() const
Definition: Pointer.h:420
QualType getType() const
Returns the type of the innermost field.
Definition: Pointer.h:315
bool isArrayElement() const
Checks if the pointer points to an array.
Definition: Pointer.h:390
bool isLive() const
Checks if the pointer is live.
Definition: Pointer.h:249
Pointer getBase() const
Returns a pointer to the object of which this pointer is a field.
Definition: Pointer.h:285
std::string toDiagnosticString(const ASTContext &Ctx) const
Converts the pointer to a string usable in diagnostics.
Definition: Pointer.cpp:205
bool isZero() const
Checks if the pointer is null.
Definition: Pointer.h:242
const IntPointer & asIntPointer() const
Definition: Pointer.h:415
bool isRoot() const
Pointer points directly to a block.
Definition: Pointer.h:396
const Descriptor * getDeclDesc() const
Accessor for information about the declaration site.
Definition: Pointer.h:265
bool isOnePastEnd() const
Checks if the index is one past end.
Definition: Pointer.h:552
static bool hasSameArray(const Pointer &A, const Pointer &B)
Checks if two pointers can be subtracted.
Definition: Pointer.cpp:308
bool isElementPastEnd() const
Checks if the pointer is an out-of-bounds element pointer.
Definition: Pointer.h:563
std::optional< APValue > toRValue(const Context &Ctx) const
Converts the pointer to an APValue that is an rvalue.
Definition: Pointer.cpp:314
bool isBlockPointer() const
Definition: Pointer.h:419
BlockPointer BS
Definition: Pointer.h:656
APValue toAPValue() const
Converts the pointer to an APValue.
Definition: Pointer.cpp:119
const Descriptor * getFieldDesc() const
Accessors for information about the innermost field.
Definition: Pointer.h:305
const BlockPointer & asBlockPointer() const
Definition: Pointer.h:411
void initialize() const
Initializes a field.
Definition: Pointer.cpp:242
bool isField() const
Checks if the item is a field in an object.
Definition: Pointer.h:255
Structure/Class descriptor.
Definition: Record.h:25
unsigned getNumBases() const
Definition: Record.h:89
const Field * getField(const FieldDecl *FD) const
Returns a field.
Definition: Record.cpp:39
const Base * getVirtualBase(const RecordDecl *RD) const
Returns a virtual base descriptor.
Definition: Record.cpp:59
unsigned getNumFields() const
Definition: Record.h:81
unsigned getNumVirtualBases() const
Definition: Record.h:100
llvm::iterator_range< const_field_iter > fields() const
Definition: Record.h:77
const Base * getBase(const RecordDecl *FD) const
Returns a base descriptor.
Definition: Record.cpp:45
std::optional< std::pair< bool, std::shared_ptr< InitMap > > > InitMapPtr
Definition: Descriptor.h:28
PrimType
Enumeration of the primitive types of the VM.
Definition: PrimType.h:32
The JSON file list parser is used to communicate input to InstallAPI.
@ Result
The result type of a method or function.
const FunctionProtoType * T
#define bool
Definition: stdbool.h:24
unsigned Base
Start of the current subfield.
Definition: Pointer.h:41
Block * Pointee
The block the pointer is pointing to.
Definition: Pointer.h:39
Describes a memory block created by an allocation site.
Definition: Descriptor.h:91
unsigned getNumElems() const
Returns the number of elements stored in the block.
Definition: Descriptor.h:211
const ValueDecl * asValueDecl() const
Definition: Descriptor.h:176
const Decl * asDecl() const
Definition: Descriptor.h:172
const bool IsArray
Flag indicating if the block is an array.
Definition: Descriptor.h:129
bool isPrimitiveArray() const
Checks if the descriptor is of an array of primitives.
Definition: Descriptor.h:216
const Expr * asExpr() const
Definition: Descriptor.h:173
unsigned IsActive
Flag indicating if the field is the active member of a union.
Definition: Descriptor.h:75
unsigned IsInitialized
For primitive fields, it indicates if the field was initialized.
Definition: Descriptor.h:69