clang 24.0.0git
InterpState.h
Go to the documentation of this file.
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
33
34 const Expr *Call = nullptr;
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 {
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
58
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
96
98 if (!Alloc) {
99 if (!Allocator)
100 Allocator.emplace();
101 Alloc = std::make_unique<DynamicAllocator>(*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.
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, Align);
118 }
119 template <typename T> T *allocate(size_t Num = 1) const {
120 return static_cast<T *>(allocate(Num * sizeof(T), 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(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(llvm::APFloatBase::getSizeInBits(Sem));
138 uint64_t *Mem = (uint64_t *)this->allocate(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(Length * sizeof(CXXRecordDecl *)));
145 }
147 const PointerPathEntry *OldPP) {
148 assert(Length != 0);
149 auto *PP = reinterpret_cast<PointerPathEntry *>(
150 this->allocate(Length * sizeof(PointerPathEntry)));
151 if (OldPP)
152 std::memcpy(PP, OldPP, 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.
158 const PointerPathEntry *OldPP,
159 PointerPathEntry NewEntry) {
160 auto *PP = reinterpret_cast<PointerPathEntry *>(
161 this->allocate(NewLength * sizeof(PointerPathEntry)));
162 if (OldPP)
163 std::memcpy(PP, OldPP, 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 {
183 if (V.block() == B)
184 return true;
185 return false;
186 }
187
188 bool lifetimeStartedInEvaluation(const Block *B) const {
190 return B->getEvalID() == EvalID;
191
193 assert(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.
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(Ptr.getRootVarDecl());
208 }
209 bool checkingConstantDestruction(const VarDecl *VD) const {
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(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.
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(Current->getFunction());
238 InterpFrame *Caller = Current->Caller;
239 Current->~InterpFrame();
240 FrameAlloc.pop(CurrentSize);
241 Current = Caller;
242 --FrameDepth;
243 }
244
245private:
246 friend class EvaluationResult;
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:
266 /// Reference to the module containing all bytecode.
268 /// Temporary stack.
270 /// Interpreter Context.
272 /// Bottom function frame.
274 /// The current frame.
276 /// Source location of the evaluating expression
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
292
293 /// Things needed to do speculative execution.
295 bool PrevDiagsEmitted = false;
296#ifndef NDEBUG
297 unsigned SpeculationDepth = 0;
298#endif
299 unsigned DiagIgnoreDepth = 0;
300 std::optional<bool> ConstantContextOverride;
301
303 std::pair<const Expr *, const LifetimeExtendedTemporaryDecl *>>
305
306 /// List of blocks we're currently running either constructors or destructors
307 /// for.
309};
310
312public:
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 }
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
#define V(N, I)
Represents a C++ struct/union/class.
Definition DeclCXX.h:258
This represents one expression.
Definition Expr.h:114
A (possibly-)qualified type.
Definition TypeBase.h:938
Encodes a location in the source.
Represents a variable declaration or definition.
Definition Decl.h:934
A memory block, either on the stack or in the heap.
Definition Block.h:68
void invokeDtor()
Invokes the Destructor.
Definition Block.h:181
const Descriptor * getDescriptor() const
Returns the block's descriptor.
Definition Block.h:103
unsigned getEvalID() const
The Evaluation ID this block was created in.
Definition Block.h:132
bool hasPointers() const
Checks if the block has any live pointers.
Definition Block.h:105
Pointer into the code segment.
Definition Source.h:31
Holds all information required to evaluate constexpr code in a module.
Definition Context.h:49
Descriptor for a dead block.
Definition Block.h:249
Manages dynamic memory allocations done during bytecode interpretation.
If a Floating is constructed from Memory, it DOES NOT OWN THAT MEMORY.
Definition Floating.h:35
bool singleWord() const
Definition Floating.h:107
Allocator for function frames.
Base class for stack frames, shared between VM and walker.
Definition Frame.h:28
Bytecode function.
Definition Function.h:98
Frame storing local variables.
Definition InterpFrame.h:27
static size_t allocSize(const Function *F)
Returns the number of bytes needed to allocate an InterpFrame for the given function.
Definition InterpFrame.h:48
Stack frame storing temporaries and parameters.
Definition InterpStack.h:26
InterpStateCCOverride(InterpState &Ctx, bool Value)
Interpreter context.
Definition InterpState.h:47
SmallVectorImpl< PartialDiagnosticAt > * PrevDiags
Things needed to do speculative execution.
bool lifetimeStartedInEvaluation(const Block *B) const
unsigned getCallStackDepth() override
Definition InterpState.h:70
InterpFrame BottomFrame
Bottom function frame.
Context & getContext() const
Definition InterpState.h:93
bool initializingBlock(const Block *B) const
DynamicAllocator & getAllocator()
Definition InterpState.h:97
Context & Ctx
Interpreter Context.
InterpState(const EvalSettings &Settings, Program &P, InterpStack &Stk, FrameAllocator &FrameAlloc, Context &Ctx, SourceMapper *M=nullptr)
void * allocate(size_t Size, unsigned Align=8) const
Floating allocFloat(const llvm::fltSemantics &Sem)
const unsigned EvalID
ID identifying this evaluation.
bool noteStep(CodePtr OpPC)
Note that a step has been executed.
SourceInfo getSource(CodePtr PC) const
Delegates source mapping to the mapper.
Definition InterpState.h:91
InterpState(const InterpState &)=delete
bool stepsLeft() const override
Definition InterpState.h:71
llvm::SmallVector< std::pair< const Expr *, const LifetimeExtendedTemporaryDecl * > > SeenGlobalTemporaries
InterpFrame * allocFrame(const Function *F, Ts &&...Args)
Allocate memory and create a new InterpFrame for the given function.
InterpStack & Stk
Temporary stack.
bool maybeDiagnoseDanglingAllocations()
Diagnose any dynamic allocations that haven't been freed yet.
SourceLocation EvalLocation
Source location of the evaluating expression.
bool checkingConstantDestruction() const
Return if we're checking if a global variable has a constant destructor.
unsigned StepsLeft
Steps left during evaluation.
const VarDecl * EvaluatingDecl
Declaration we're initializing/evaluting, if any.
bool checkingConstantDestruction(const Pointer &Ptr) const
Return if we're checking if a global variable has a constant destructor and the given pointer is poin...
InterpFrame * Current
The current frame.
void enterFrame(InterpFrame *F)
Set the given frame as the current one.
PointerPathEntry * allocPointerPath(unsigned Length, const PointerPathEntry *OldPP)
const CXXRecordDecl ** allocMemberPointerPath(unsigned Length)
const Frame * getCurrentFrame() override
std::optional< bool > ConstantContextOverride
const bool InfiniteSteps
Whether infinite evaluation steps have been requested.
void deallocate(Block *B)
Deallocates a pointer.
Definition InterpState.h:75
InterpState & operator=(const InterpState &)=delete
void exitFrame()
Free resources associated with the current frame and set the caller to be the new current frame.
friend class InterpStateCCOverride
T * allocate(size_t Num=1) const
PointerPathEntry * extendPointerPath(unsigned NewLength, const PointerPathEntry *OldPP, PointerPathEntry NewEntry)
Allocate a new pointer path of Length NewLength.
llvm::SmallVector< PtrView > InitializingPtrs
List of blocks we're currently running either constructors or destructors for.
T allocAP(unsigned BitWidth)
void setEvalLocation(SourceLocation SL)
Definition InterpState.h:95
StdAllocatorCaller getStdAllocatorCaller(StringRef Name) const
bool checkingConstantDestruction(const VarDecl *VD) const
Program & P
Reference to the module containing all bytecode.
A pointer to a memory block, live or dead.
Definition Pointer.h:544
The program contains and links the bytecode for all functions.
Definition Program.h:38
Describes the statement/declaration an opcode was generated from.
Definition Source.h:77
Interface for classes which map locations to sources.
Definition Source.h:138
Expr::EvalStatus & getEvalStatus() const
Definition State.h:91
State(ASTContext &ASTCtx, SemaProxy *SProxy, Expr::EvalStatus &EvalStatus)
Definition State.h:83
Top level wrappers for InstallAPI frontend operations.
const FunctionProtoType * T
EvalStatus is a struct with detailed info about an evaluation in progress.
Definition Expr.h:623
SmallVectorImpl< PartialDiagnosticAt > * Diag
Diag - If this is non-null, it will be filled in with a stack of notes indicating why evaluation fail...
Definition Expr.h:651
const VarDecl * asVarDecl() const
Definition Descriptor.h:212