1//===-- InterpBlock.h - Allocated blocks for the interpreter -*- 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// Defines the classes describing allocated blocks.
10//
11//===----------------------------------------------------------------------===//
12
13#ifndef LLVM_CLANG_AST_INTERP_BLOCK_H
14#define LLVM_CLANG_AST_INTERP_BLOCK_H
15
16#include "Descriptor.h"
17#include "llvm/Support/raw_ostream.h"
18
19namespace clang {
20namespace interp {
21class Block;
22class DeadBlock;
23class InterpState;
24class Pointer;
25enum PrimType : uint8_t;
26
27/// A memory block, either on the stack or in the heap.
28///
29/// The storage described by the block is immediately followed by
30/// optional metadata, which is followed by the actual data.
31///
32/// Block* rawData() data()
33/// │ │ │
34/// │ │ │
35/// ▼ ▼ ▼
36/// ┌───────────────┬──────────────────┬─────────────────┐
37/// │ Block │ Metadata │ Data │
38/// │ sizeof(Block) │ MDSize │ Desc->getSize() │
39/// └───────────────┴──────────────────┴─────────────────┘
40///
41/// getSize() returns MDSize + Desc->getAllocSize().
42///
43class Block final {
44private:
45 static constexpr uint8_t ExternFlag = 1 << 0;
46 static constexpr uint8_t DeadFlag = 1 << 1;
47 static constexpr uint8_t WeakFlag = 1 << 2;
48
49public:
50 static constexpr uint8_t InlineDescMD = sizeof(InlineDescriptor);
51 static constexpr uint8_t GlobalMD = sizeof(GlobalInlineDescriptor);
52
53 /// Creates a new block.
54 Block(unsigned EvalID, UnsignedOrNone DeclID, const Descriptor *Desc,
55 unsigned MDSize = 0, bool IsStatic = false, bool IsExtern = false,
56 bool IsWeak = false)
57 : Desc(Desc), DeclID(DeclID), EvalID(EvalID), MDSize(MDSize),
58 IsStatic(IsStatic) {
59 assert(Desc);
60 AccessFlags |= (ExternFlag * IsExtern);
61 AccessFlags |= (WeakFlag * IsWeak);
62 }
63
64 Block(unsigned EvalID, const Descriptor *Desc, unsigned MDSize = 0,
65 bool IsStatic = false, bool IsExtern = false, bool IsWeak = false)
66 : Desc(Desc), EvalID(EvalID), MDSize(MDSize), IsStatic(IsStatic) {
67 assert(Desc);
68 AccessFlags |= (ExternFlag * IsExtern);
69 AccessFlags |= (WeakFlag * IsWeak);
70 }
71
72 /// Returns the block's descriptor.
73 const Descriptor *getDescriptor() const { return Desc; }
74 /// Checks if the block has any live pointers.
75 bool hasPointers() const { return Pointers; }
76 /// Checks if the block is extern.
77 bool isExtern() const { return AccessFlags & ExternFlag; }
78 /// Checks if the block has static storage duration.
79 bool isStatic() const { return IsStatic; }
80 /// Checks if the block is temporary.
81 bool isTemporary() const { return Desc->IsTemporary; }
82 bool isWeak() const { return AccessFlags & WeakFlag; }
83 bool isDynamic() const {
84 bool Result = (DynAllocId != std::nullopt);
85 assert((Result == Desc->isDynAlloc()) &&
86 "Inconsistent block/descriptor dynamic alloc state");
87 return Result;
88 }
89 bool isDead() const { return AccessFlags & DeadFlag; }
90 /// Returns the size of the block, including metadata.
91 unsigned getSize() const { return Desc->getAllocSize() + MDSize; }
92 /// Returns the size of the metadata.
93 unsigned getMetadataSize() const { return MDSize; }
94 /// Returns the declaration ID.
95 UnsignedOrNone getDeclID() const { return DeclID; }
96 /// Returns whether the data of this block has been initialized via
97 /// invoking the Ctor func.
98 bool isInitialized() const { return IsInitialized; }
99 /// The Evaluation ID this block was created in.
100 unsigned getEvalID() const { return EvalID; }
101 /// Move all pointers from this block to \param B.
102 void movePointersTo(Block *B);
103 /// Make all pointers that currently point to this block point to nullptr.
104 void removePointers();
105
106 /// Returns a pointer to the stored data.
107 /// You are allowed to read Desc->getSize() bytes from this address.
108 std::byte *data() { return rawData() + MDSize; }
109 const std::byte *data() const { return rawData() + MDSize; }
110
111 /// Returns a pointer to the raw data, including metadata.
112 /// You are allowed to read Desc->getAllocSize() bytes from this address.
113 std::byte *rawData() {
114 return reinterpret_cast<std::byte *>(this) + sizeof(Block);
115 }
116 const std::byte *rawData() const {
117 return reinterpret_cast<const std::byte *>(this) + sizeof(Block);
118 }
119
120 template <typename T> const T &deref() const {
121 return *reinterpret_cast<const T *>(data());
122 }
123 template <typename T> T &deref() { return *reinterpret_cast<T *>(data()); }
124
125 template <typename T> T &getBlockDesc() {
126 assert(sizeof(T) == MDSize);
127 return *reinterpret_cast<T *>(rawData());
128 }
129 template <typename T> const T &getBlockDesc() const {
130 return const_cast<Block *>(this)->getBlockDesc<T>();
131 }
132
133 /// Invokes the constructor.
134 void invokeCtor() {
135 assert(!IsInitialized);
136 std::memset(s: rawData(), c: 0, n: getSize());
137 invokeCtorNoMemset();
138 }
139 /// The same, but won't memset() the memory first to zero.
140 void invokeCtorNoMemset() {
141 assert(!IsInitialized);
142 if (Desc->CtorFn)
143 Desc->CtorFn(this, data(), Desc->IsConst, Desc->IsMutable,
144 Desc->IsVolatile,
145 /*isActive=*/true, /*InUnion=*/false, Desc);
146
147 IsInitialized = true;
148 }
149
150 /// Invokes the Destructor.
151 void invokeDtor() {
152 assert(IsInitialized);
153 if (Desc->DtorFn)
154 Desc->DtorFn(this, data(), Desc);
155 IsInitialized = false;
156 }
157
158 void dump() const { dump(OS&: llvm::errs()); }
159 void dump(llvm::raw_ostream &OS) const;
160
161 bool isAccessible() const { return AccessFlags == 0; }
162
163private:
164 friend class Pointer;
165 friend class DeadBlock;
166 friend class InterpState;
167 friend class DynamicAllocator;
168 friend class Program;
169
170 Block(unsigned EvalID, const Descriptor *Desc, unsigned MDSize, bool IsExtern,
171 bool IsStatic, bool IsWeak, bool IsDead)
172 : Desc(Desc), EvalID(EvalID), MDSize(MDSize), IsStatic(IsStatic) {
173 assert(Desc);
174 AccessFlags |= (ExternFlag * IsExtern);
175 AccessFlags |= (DeadFlag * IsDead);
176 AccessFlags |= (WeakFlag * IsWeak);
177 }
178
179 /// To be called by DynamicAllocator.
180 void setDynAllocId(unsigned ID) { DynAllocId = ID; }
181
182 /// Deletes a dead block at the end of its lifetime.
183 void cleanup();
184
185 /// Pointer chain management.
186 void addPointer(Pointer *P);
187 void removePointer(Pointer *P);
188 void replacePointer(Pointer *Old, Pointer *New);
189#ifndef NDEBUG
190 bool hasPointer(const Pointer *P) const;
191#endif
192
193 /// Pointer to the stack slot descriptor.
194 const Descriptor *Desc;
195 /// Start of the chain of pointers.
196 Pointer *Pointers = nullptr;
197 /// Unique identifier of the declaration.
198 UnsignedOrNone DeclID = std::nullopt;
199 const unsigned EvalID = ~0u;
200 /// Allocation ID for this dynamic allocation, if it is one.
201 UnsignedOrNone DynAllocId = std::nullopt;
202 /// AccessFlags containing IsExtern, IsDead and IsWeak bits.
203 uint8_t AccessFlags = 0;
204 /// Size of the metadata.
205 const uint8_t MDSize = 0;
206 /// Flag indicating if the block has static storage duration.
207 bool IsStatic = false;
208 /// Flag indicating if the block contents have been initialized
209 /// via invokeCtor.
210 bool IsInitialized = false;
211};
212
213/// Descriptor for a dead block.
214///
215/// Dead blocks are chained in a double-linked list to deallocate them
216/// whenever pointers become dead.
217class DeadBlock final {
218public:
219 /// Copies the block.
220 DeadBlock(DeadBlock *&Root, Block *Blk);
221
222 /// Returns a pointer to the stored data.
223 std::byte *data() { return B.data(); }
224 std::byte *rawData() { return B.rawData(); }
225
226private:
227 friend class Block;
228 friend class InterpState;
229
230 void free();
231
232 /// Root pointer of the list.
233 DeadBlock *&Root;
234 /// Previous block in the list.
235 DeadBlock *Prev;
236 /// Next block in the list.
237 DeadBlock *Next;
238
239 /// Actual block storing data and tracking pointers.
240 Block B;
241};
242
243} // namespace interp
244} // namespace clang
245
246#endif
247