1//===--- InterpState.h - Interpreter state 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// Definition of the interpreter state and entry point.
10//
11//===----------------------------------------------------------------------===//
12
13#ifndef LLVM_CLANG_AST_INTERP_INTERPSTATE_H
14#define LLVM_CLANG_AST_INTERP_INTERPSTATE_H
15
16#include "Context.h"
17#include "DynamicAllocator.h"
18#include "Floating.h"
19#include "FrameAllocator.h"
20#include "Function.h"
21#include "InterpFrame.h"
22#include "InterpStack.h"
23#include "State.h"
24#include <limits>
25
26namespace clang {
27namespace interp {
28class Context;
29class SourceMapper;
30struct EvalSettings;
31
32struct StdAllocatorCaller {
33
34 const Expr *Call = nullptr;
35 QualType AllocType;
36 explicit operator bool() { return Call; }
37};
38
39// FIXME: Create one for the "checking potential constant expression"
40// evaluation.
41enum class EvaluationKind : uint8_t {
42 None,
43 Dtor, /// We're checking for constant destruction of a global variable.
44};
45
46/// Interpreter context.
47class InterpState final : public State {
48public:
49 InterpState(const EvalSettings &Settings, Program &P, InterpStack &Stk,
50 FrameAllocator &FrameAlloc, Context &Ctx,
51 SourceMapper *M = nullptr);
52
53 InterpState(const EvalSettings &Settings, Program &P, InterpStack &Stk,
54 FrameAllocator &FA, Context &Ctx, const Function *Func);
55
56 InterpState(Expr::EvalStatus &Status, Program &P, InterpStack &Stk,
57 FrameAllocator &FA, Context &Ctx, SourceMapper *M);
58
59 ~InterpState();
60
61 void cleanup();
62
63 InterpState(const InterpState &) = delete;
64 InterpState &operator=(const InterpState &) = delete;
65
66 bool diagnosing() const { return getEvalStatus().Diag != nullptr; }
67
68 // Stack frame accessors.
69 const Frame *getCurrentFrame() override;
70 unsigned getCallStackDepth() override { return FrameDepth + 1; }
71 bool stepsLeft() const override { return true; }
72 bool inConstantContext() const;
73
74 /// Deallocates a pointer.
75 void deallocate(Block *B) {
76 // The block might have a pointer saved in a field in its data
77 // that points to the block itself. We call the dtor first,
78 // which will destroy all the data but leave InlineDescriptors
79 // intact. If the block THEN still has pointers, we create a
80 // DeadBlock for it in deallocateWithPointers().
81 if (B->IsInitialized)
82 B->invokeDtor();
83
84 if (LLVM_LIKELY(!B->hasPointers()))
85 return;
86
87 deallocateWithPointers(B);
88 }
89
90 /// Delegates source mapping to the mapper.
91 SourceInfo getSource(CodePtr PC) const { return M->getSource(PC); }
92
93 Context &getContext() const { return Ctx; }
94
95 void setEvalLocation(SourceLocation SL) { this->EvalLocation = SL; }
96
97 DynamicAllocator &getAllocator() {
98 if (!Alloc) {
99 if (!Allocator)
100 Allocator.emplace();
101 Alloc = std::make_unique<DynamicAllocator>(args&: *Allocator);
102 }
103
104 return *Alloc;
105 }
106
107 /// Diagnose any dynamic allocations that haven't been freed yet.
108 /// Will return \c false if there were any allocations to diagnose,
109 /// \c true otherwise.
110 bool maybeDiagnoseDanglingAllocations();
111
112 StdAllocatorCaller getStdAllocatorCaller(StringRef Name) const;
113
114 void *allocate(size_t Size, unsigned Align = 8) const {
115 if (!Allocator)
116 Allocator.emplace();
117 return Allocator->Allocate(Size, Alignment: Align);
118 }
119 template <typename T> T *allocate(size_t Num = 1) const {
120 return static_cast<T *>(allocate(Size: Num * sizeof(T), Align: alignof(T)));
121 }
122
123 template <typename T> T allocAP(unsigned BitWidth) {
124 unsigned NumWords = APInt::getNumWords(BitWidth);
125 if (NumWords == 1)
126 return T(BitWidth);
127 uint64_t *Mem = (uint64_t *)this->allocate(Size: NumWords * sizeof(uint64_t));
128 // std::memset(Mem, 0, NumWords * sizeof(uint64_t)); // Debug
129 return T(Mem, BitWidth);
130 }
131
132 Floating allocFloat(const llvm::fltSemantics &Sem) {
133 if (Floating::singleWord(Sem))
134 return Floating(llvm::APFloatBase::SemanticsToEnum(Sem));
135
136 unsigned NumWords =
137 APInt::getNumWords(BitWidth: llvm::APFloatBase::getSizeInBits(Sem));
138 uint64_t *Mem = (uint64_t *)this->allocate(Size: NumWords * sizeof(uint64_t));
139 // std::memset(Mem, 0, NumWords * sizeof(uint64_t)); // Debug
140 return Floating(Mem, llvm::APFloatBase::SemanticsToEnum(Sem));
141 }
142 const CXXRecordDecl **allocMemberPointerPath(unsigned Length) {
143 return reinterpret_cast<const CXXRecordDecl **>(
144 this->allocate(Size: Length * sizeof(CXXRecordDecl *)));
145 }
146 PointerPathEntry *allocPointerPath(unsigned Length,
147 const PointerPathEntry *OldPP) {
148 assert(Length != 0);
149 auto *PP = reinterpret_cast<PointerPathEntry *>(
150 this->allocate(Size: Length * sizeof(PointerPathEntry)));
151 if (OldPP)
152 std::memcpy(dest: PP, src: OldPP, n: sizeof(PointerPathEntry) * Length);
153 return PP;
154 }
155 /// Allocate a new pointer path of Length \c NewLength.
156 /// NewLength - 1 elements are copied form \c OldPP.
157 PointerPathEntry *extendPointerPath(unsigned NewLength,
158 const PointerPathEntry *OldPP,
159 PointerPathEntry NewEntry) {
160 auto *PP = reinterpret_cast<PointerPathEntry *>(
161 this->allocate(Size: NewLength * sizeof(PointerPathEntry)));
162 if (OldPP)
163 std::memcpy(dest: PP, src: OldPP, n: sizeof(PointerPathEntry) * (NewLength - 1));
164 PP[NewLength - 1] = NewEntry;
165 return PP;
166 }
167
168 /// Note that a step has been executed. If there are no more steps remaining,
169 /// diagnoses and returns \c false.
170 bool noteStep(CodePtr OpPC) {
171 if (InfiniteSteps)
172 return true;
173
174 --StepsLeft;
175 if (LLVM_LIKELY(StepsLeft != 0))
176 return true;
177
178 return diagnoseStepLimitExceeded(OpPC);
179 }
180
181 bool initializingBlock(const Block *B) const {
182 for (PtrView V : InitializingPtrs)
183 if (V.block() == B)
184 return true;
185 return false;
186 }
187
188 bool lifetimeStartedInEvaluation(const Block *B) const {
189 if (EvalKind == EvaluationKind::None)
190 return B->getEvalID() == EvalID;
191
192 if (EvalKind == EvaluationKind::Dtor) {
193 assert(EvaluatingDecl);
194 if (B->getDescriptor()->asVarDecl() == EvaluatingDecl)
195 return EvaluatingDecl->getType().isConstQualified();
196 }
197 return false;
198 }
199
200 /// Return if we're checking if a global variable has a constant destructor.
201 bool checkingConstantDestruction() const {
202 return EvalKind == EvaluationKind::Dtor;
203 }
204 /// Return if we're checking if a global variable has a constant destructor
205 /// and the given pointer is pointing to the variable we're checking that for.
206 bool checkingConstantDestruction(const Pointer &Ptr) const {
207 return checkingConstantDestruction(VD: Ptr.getRootVarDecl());
208 }
209 bool checkingConstantDestruction(const VarDecl *VD) const {
210 return EvalKind == EvaluationKind::Dtor && VD == EvaluatingDecl;
211 }
212
213 unsigned newStringID() { return StringID++; }
214
215 /// Allocate memory and create a new InterpFrame for the given function.
216 template <typename... Ts>
217 InterpFrame *allocFrame(const Function *F, Ts &&...Args) {
218 size_t FrameSize = InterpFrame::allocSize(F);
219 assert(FrameSize < std::numeric_limits<unsigned>::max());
220 InterpFrame *NewFrame = new (FrameAlloc.reserve(Size: FrameSize))
221 InterpFrame(*this, F, std::forward<Ts>(Args)...);
222 assert(NewFrame);
223 return NewFrame;
224 }
225
226 /// Set the given frame as the current one.
227 void enterFrame(InterpFrame *F) {
228 Current = F;
229 ++FrameDepth;
230 }
231
232 /// Free resources associated with the current frame and set the caller to be
233 /// the new current frame.
234 void exitFrame() {
235 assert(Current);
236 assert(FrameDepth > 0);
237 unsigned CurrentSize = InterpFrame::allocSize(F: Current->getFunction());
238 InterpFrame *Caller = Current->Caller;
239 Current->~InterpFrame();
240 FrameAlloc.pop(FrameSize: CurrentSize);
241 Current = Caller;
242 --FrameDepth;
243 }
244
245private:
246 friend class EvaluationResult;
247 friend class InterpStateCCOverride;
248 /// Dead block chain.
249 DeadBlock *DeadBlocks = nullptr;
250 /// Reference to the offset-source mapping.
251 SourceMapper *M;
252 /// Allocator for everything else, e.g. floating-point values.
253 mutable std::optional<llvm::BumpPtrAllocator> Allocator;
254 /// Allocator used for dynamic allocations performed via the program.
255 std::unique_ptr<DynamicAllocator> Alloc;
256 /// Diagnose that we've reached the constexpr step limit.
257 bool diagnoseStepLimitExceeded(CodePtr OpPC);
258
259 FrameAllocator &FrameAlloc;
260
261 /// Deallocate a block that still has pointers pointing to it.
262 void deallocateWithPointers(Block *B);
263
264public:
265 CodePtr PC;
266 /// Reference to the module containing all bytecode.
267 Program &P;
268 /// Temporary stack.
269 InterpStack &Stk;
270 /// Interpreter Context.
271 Context &Ctx;
272 /// Bottom function frame.
273 InterpFrame BottomFrame;
274 /// The current frame.
275 InterpFrame *Current = nullptr;
276 /// Source location of the evaluating expression
277 SourceLocation EvalLocation;
278 /// Declaration we're initializing/evaluting, if any.
279 const VarDecl *EvaluatingDecl = nullptr;
280 /// Steps left during evaluation.
281 unsigned StepsLeft = 1;
282 /// Whether infinite evaluation steps have been requested. If this is false,
283 /// we use the StepsLeft value above.
284 const bool InfiniteSteps = false;
285 /// ID identifying this evaluation.
286 const unsigned EvalID;
287 unsigned FrameDepth = 0;
288
289 unsigned StringID = 0;
290
291 EvaluationKind EvalKind = EvaluationKind::None;
292
293 /// Things needed to do speculative execution.
294 SmallVectorImpl<PartialDiagnosticAt> *PrevDiags = nullptr;
295 bool PrevDiagsEmitted = false;
296#ifndef NDEBUG
297 unsigned SpeculationDepth = 0;
298#endif
299 unsigned DiagIgnoreDepth = 0;
300 std::optional<bool> ConstantContextOverride;
301
302 llvm::SmallVector<
303 std::pair<const Expr *, const LifetimeExtendedTemporaryDecl *>>
304 SeenGlobalTemporaries;
305
306 /// List of blocks we're currently running either constructors or destructors
307 /// for.
308 llvm::SmallVector<PtrView> InitializingPtrs;
309};
310
311class InterpStateCCOverride final {
312public:
313 InterpStateCCOverride(InterpState &Ctx, bool Value)
314 : Ctx(Ctx), OldCC(Ctx.ConstantContextOverride) {
315 // We only override this if the new value is true.
316 Enabled = Value;
317 if (Enabled)
318 Ctx.ConstantContextOverride = Value;
319 }
320 ~InterpStateCCOverride() {
321 if (Enabled)
322 Ctx.ConstantContextOverride = OldCC;
323 }
324
325private:
326 bool Enabled;
327 InterpState &Ctx;
328 std::optional<bool> OldCC;
329};
330
331} // namespace interp
332} // namespace clang
333
334#endif
335