clang 22.0.0git
EvalEmitter.cpp
Go to the documentation of this file.
1//===--- EvalEmitter.cpp - Instruction emitter for the 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 "EvalEmitter.h"
10#include "Context.h"
11#include "IntegralAP.h"
12#include "Interp.h"
13#include "clang/AST/DeclCXX.h"
14
15using namespace clang;
16using namespace clang::interp;
17
19 InterpStack &Stk)
20 : Ctx(Ctx), P(P), S(Parent, P, Stk, Ctx, this), EvalResult(&Ctx) {}
21
23 for (auto &V : Locals) {
24 Block *B = reinterpret_cast<Block *>(V.get());
25 if (B->isInitialized())
26 B->invokeDtor();
27 }
28}
29
30/// Clean up all our resources. This needs to done in failed evaluations before
31/// we call InterpStack::clear(), because there might be a Pointer on the stack
32/// pointing into a Block in the EvalEmitter.
33void EvalEmitter::cleanup() { S.cleanup(); }
34
36 bool ConvertResultToRValue,
37 bool DestroyToplevelScope) {
38 S.setEvalLocation(E->getExprLoc());
39 this->ConvertResultToRValue = ConvertResultToRValue && !isa<ConstantExpr>(E);
40 this->CheckFullyInitialized = isa<ConstantExpr>(E);
41 EvalResult.setSource(E);
42
43 if (!this->visitExpr(E, DestroyToplevelScope)) {
44 // EvalResult may already have a result set, but something failed
45 // after that (e.g. evaluating destructors).
46 EvalResult.setInvalid();
47 }
48
49 return std::move(this->EvalResult);
50}
51
53 bool CheckFullyInitialized) {
54 this->CheckFullyInitialized = CheckFullyInitialized;
55 S.EvaluatingDecl = VD;
56 S.setEvalLocation(VD->getLocation());
57 EvalResult.setSource(VD);
58
59 // FIXME: I think Init is never null.
60 if (Init) {
61 QualType T = VD->getType();
62 this->ConvertResultToRValue = !Init->isGLValue() && !T->isPointerType() &&
63 !T->isObjCObjectPointerType();
64 } else
65 this->ConvertResultToRValue = false;
66
67 EvalResult.setSource(VD);
68
69 if (!this->visitDeclAndReturn(VD, Init, S.inConstantContext()))
70 EvalResult.setInvalid();
71
72 S.EvaluatingDecl = nullptr;
73 updateGlobalTemporaries();
74 return std::move(this->EvalResult);
75}
76
78 PtrCallback PtrCB) {
79
80 S.setEvalLocation(E->getExprLoc());
81 this->ConvertResultToRValue = false;
82 this->CheckFullyInitialized = false;
83 this->PtrCB = PtrCB;
84 EvalResult.setSource(E);
85
86 if (!this->visitExpr(E, /*DestroyToplevelScope=*/true)) {
87 // EvalResult may already have a result set, but something failed
88 // after that (e.g. evaluating destructors).
89 EvalResult.setInvalid();
90 }
91
92 return std::move(this->EvalResult);
93}
94
95bool EvalEmitter::interpretCall(const FunctionDecl *FD, const Expr *E) {
96 // Add parameters to the parameter map. The values in the ParamOffset don't
97 // matter in this case as reading from them can't ever work.
98 for (const ParmVarDecl *PD : FD->parameters()) {
99 this->Params.insert({PD, {0, false}});
100 }
101
102 return this->visitExpr(E, /*DestroyToplevelScope=*/false);
103}
104
105void EvalEmitter::emitLabel(LabelTy Label) { CurrentLabel = Label; }
106
108
110 // Allocate memory for a local.
111 auto Memory = std::make_unique<char[]>(sizeof(Block) + D->getAllocSize());
112 auto *B = new (Memory.get()) Block(Ctx.getEvalID(), D, /*isStatic=*/false);
113 B->invokeCtor();
114
115 // Initialize local variable inline descriptor.
116 InlineDescriptor &Desc = *reinterpret_cast<InlineDescriptor *>(B->rawData());
117 Desc.Desc = D;
118 Desc.Offset = sizeof(InlineDescriptor);
119 Desc.IsActive = true;
120 Desc.IsBase = false;
121 Desc.IsFieldMutable = false;
122 Desc.IsConst = false;
123 Desc.IsInitialized = false;
124
125 // Register the local.
126 unsigned Off = Locals.size();
127 Locals.push_back(std::move(Memory));
128 return {Off, D};
129}
130
131bool EvalEmitter::jumpTrue(const LabelTy &Label) {
132 if (isActive()) {
133 if (S.Stk.pop<bool>())
134 ActiveLabel = Label;
135 }
136 return true;
137}
138
139bool EvalEmitter::jumpFalse(const LabelTy &Label) {
140 if (isActive()) {
141 if (!S.Stk.pop<bool>())
142 ActiveLabel = Label;
143 }
144 return true;
145}
146
147bool EvalEmitter::jump(const LabelTy &Label) {
148 if (isActive())
149 CurrentLabel = ActiveLabel = Label;
150 return true;
151}
152
154 if (isActive())
155 ActiveLabel = Label;
156 CurrentLabel = Label;
157 return true;
158}
159
160bool EvalEmitter::speculate(const CallExpr *E, const LabelTy &EndLabel) {
161 size_t StackSizeBefore = S.Stk.size();
162 const Expr *Arg = E->getArg(0);
163 if (!this->visit(Arg)) {
164 S.Stk.clearTo(StackSizeBefore);
165
166 if (S.inConstantContext() || Arg->HasSideEffects(S.getASTContext()))
167 return this->emitBool(false, E);
168 return Invalid(S, OpPC);
169 }
170
171 PrimType T = Ctx.classify(Arg->getType()).value_or(PT_Ptr);
172 if (T == PT_Ptr) {
173 const auto &Ptr = S.Stk.pop<Pointer>();
174 return this->emitBool(CheckBCPResult(S, Ptr), E);
175 }
176
177 // Otherwise, this is fine!
178 if (!this->emitPop(T, E))
179 return false;
180 return this->emitBool(true, E);
181}
182
183template <PrimType OpType> bool EvalEmitter::emitRet(const SourceInfo &Info) {
184 if (!isActive())
185 return true;
186
187 using T = typename PrimConv<OpType>::T;
188 EvalResult.takeValue(S.Stk.pop<T>().toAPValue(Ctx.getASTContext()));
189 return true;
190}
191
192template <> bool EvalEmitter::emitRet<PT_Ptr>(const SourceInfo &Info) {
193 if (!isActive())
194 return true;
195
196 const Pointer &Ptr = S.Stk.pop<Pointer>();
197
198 if (Ptr.isFunctionPointer()) {
199 EvalResult.takeValue(Ptr.toAPValue(Ctx.getASTContext()));
200 return true;
201 }
202
203 // If we're returning a raw pointer, call our callback.
204 if (this->PtrCB)
205 return (*this->PtrCB)(Ptr);
206
207 if (!EvalResult.checkReturnValue(S, Ctx, Ptr, Info))
208 return false;
209 if (CheckFullyInitialized && !EvalResult.checkFullyInitialized(S, Ptr))
210 return false;
211
212 // Implicitly convert lvalue to rvalue, if requested.
213 if (ConvertResultToRValue) {
214 if (!Ptr.isZero() && !Ptr.isDereferencable())
215 return false;
216
217 if (Ptr.pointsToStringLiteral() && Ptr.isArrayRoot())
218 return false;
219
220 if (!Ptr.isZero() && !CheckFinalLoad(S, OpPC, Ptr))
221 return false;
222
223 // Never allow reading from a non-const pointer, unless the memory
224 // has been created in this evaluation.
225 if (!Ptr.isZero() && !Ptr.isConst() && Ptr.isBlockPointer() &&
226 Ptr.block()->getEvalID() != Ctx.getEvalID())
227 return false;
228
229 if (std::optional<APValue> V =
230 Ptr.toRValue(Ctx, EvalResult.getSourceType())) {
231 EvalResult.takeValue(std::move(*V));
232 } else {
233 return false;
234 }
235 } else {
236 // If this is pointing to a local variable, just return
237 // the result, even if the pointer is dead.
238 // This will later be diagnosed by CheckLValueConstantExpression.
239 if (Ptr.isBlockPointer() && !Ptr.block()->isStatic()) {
240 EvalResult.takeValue(Ptr.toAPValue(Ctx.getASTContext()));
241 return true;
242 }
243
244 if (!Ptr.isLive() && !Ptr.isTemporary())
245 return false;
246
247 EvalResult.takeValue(Ptr.toAPValue(Ctx.getASTContext()));
248 }
249
250 return true;
251}
252
253bool EvalEmitter::emitRetVoid(const SourceInfo &Info) {
254 EvalResult.setValid();
255 return true;
256}
257
258bool EvalEmitter::emitRetValue(const SourceInfo &Info) {
259 const auto &Ptr = S.Stk.pop<Pointer>();
260
261 if (!EvalResult.checkReturnValue(S, Ctx, Ptr, Info))
262 return false;
263 if (CheckFullyInitialized && !EvalResult.checkFullyInitialized(S, Ptr))
264 return false;
265
266 if (std::optional<APValue> APV =
267 Ptr.toRValue(S.getASTContext(), EvalResult.getSourceType())) {
268 EvalResult.takeValue(std::move(*APV));
269 return true;
270 }
271
272 EvalResult.setInvalid();
273 return false;
274}
275
276bool EvalEmitter::emitGetPtrLocal(uint32_t I, const SourceInfo &Info) {
277 if (!isActive())
278 return true;
279
280 Block *B = getLocal(I);
281 S.Stk.push<Pointer>(B, sizeof(InlineDescriptor));
282 return true;
283}
284
285template <PrimType OpType>
286bool EvalEmitter::emitGetLocal(uint32_t I, const SourceInfo &Info) {
287 if (!isActive())
288 return true;
289
290 using T = typename PrimConv<OpType>::T;
291
292 Block *B = getLocal(I);
293
294 if (!CheckLocalLoad(S, OpPC, B))
295 return false;
296
297 S.Stk.push<T>(*reinterpret_cast<T *>(B->data()));
298 return true;
299}
300
301template <PrimType OpType>
302bool EvalEmitter::emitSetLocal(uint32_t I, const SourceInfo &Info) {
303 if (!isActive())
304 return true;
305
306 using T = typename PrimConv<OpType>::T;
307
308 Block *B = getLocal(I);
309 *reinterpret_cast<T *>(B->data()) = S.Stk.pop<T>();
310 InlineDescriptor &Desc = *reinterpret_cast<InlineDescriptor *>(B->rawData());
311 Desc.IsInitialized = true;
312
313 return true;
314}
315
316bool EvalEmitter::emitDestroy(uint32_t I, const SourceInfo &Info) {
317 if (!isActive())
318 return true;
319
320 for (auto &Local : Descriptors[I]) {
321 Block *B = getLocal(Local.Offset);
322 S.deallocate(B);
323 }
324
325 return true;
326}
327
328/// Global temporaries (LifetimeExtendedTemporary) carry their value
329/// around as an APValue, which codegen accesses.
330/// We set their value once when creating them, but we don't update it
331/// afterwards when code changes it later.
332/// This is what we do here.
333void EvalEmitter::updateGlobalTemporaries() {
334 for (const auto &[E, Temp] : S.SeenGlobalTemporaries) {
335 UnsignedOrNone GlobalIndex = P.getGlobal(E);
336 assert(GlobalIndex);
337 const Pointer &Ptr = P.getPtrGlobal(*GlobalIndex);
338 APValue *Cached = Temp->getOrCreateValue(true);
339 if (OptPrimType T = Ctx.classify(E->getType())) {
340 TYPE_SWITCH(*T,
341 { *Cached = Ptr.deref<T>().toAPValue(Ctx.getASTContext()); });
342 } else {
343 if (std::optional<APValue> APV =
344 Ptr.toRValue(Ctx, Temp->getTemporaryExpr()->getType()))
345 *Cached = *APV;
346 }
347 }
348 S.SeenGlobalTemporaries.clear();
349}
350
351//===----------------------------------------------------------------------===//
352// Opcode evaluators
353//===----------------------------------------------------------------------===//
354
355#define GET_EVAL_IMPL
356#include "Opcodes.inc"
357#undef GET_EVAL_IMPL
#define V(N, I)
Defines the C++ Decl subclasses, other than those for templates (found in DeclTemplate....
static bool CheckFullyInitialized(EvalInfo &Info, SourceLocation DiagLoc, QualType Type, const APValue &Value)
Check that this evaluated value is fully-initialized and can be loaded by an lvalue-to-rvalue convers...
#define TYPE_SWITCH(Expr, B)
Definition PrimType.h:207
CallExpr - Represents a function call (C99 6.5.2.2, C++ [expr.call]).
Definition Expr.h:2879
Expr * getArg(unsigned Arg)
getArg - Return the specified argument.
Definition Expr.h:3083
SourceLocation getLocation() const
Definition DeclBase.h:439
This represents one expression.
Definition Expr.h:112
bool HasSideEffects(const ASTContext &Ctx, bool IncludePossibleEffects=true) const
HasSideEffects - This routine returns true for all those expressions which have any effect other than...
Definition Expr.cpp:3624
SourceLocation getExprLoc() const LLVM_READONLY
getExprLoc - Return the preferred location for the arrow when diagnosing a problem with a generic exp...
Definition Expr.cpp:273
QualType getType() const
Definition Expr.h:144
Represents a function declaration or definition.
Definition Decl.h:1999
ArrayRef< ParmVarDecl * > parameters() const
Definition Decl.h:2771
Represents a parameter to a function.
Definition Decl.h:1789
A (possibly-)qualified type.
Definition TypeBase.h:937
QualType getType() const
Definition Decl.h:722
Represents a variable declaration or definition.
Definition Decl.h:925
A memory block, either on the stack or in the heap.
Definition InterpBlock.h:44
void invokeDtor()
Invokes the Destructor.
std::byte * data()
Returns a pointer to the stored data.
Definition InterpBlock.h:98
bool isStatic() const
Checks if the block has static storage duration.
Definition InterpBlock.h:79
std::byte * rawData()
Returns a pointer to the raw data, including metadata.
bool isInitialized() const
Returns whether the data of this block has been initialized via invoking the Ctor func.
Definition InterpBlock.h:92
unsigned getEvalID() const
The Evaluation ID this block was created in.
Definition InterpBlock.h:94
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:75
unsigned getEvalID() const
Definition Context.h:141
bool jump(const LabelTy &Label)
EvaluationResult interpretDecl(const VarDecl *VD, const Expr *Init, bool CheckFullyInitialized)
EvaluationResult interpretExpr(const Expr *E, bool ConvertResultToRValue=false, bool DestroyToplevelScope=false)
bool jumpFalse(const LabelTy &Label)
virtual bool visit(const Expr *E)=0
bool speculate(const CallExpr *E, const LabelTy &EndLabel)
Speculative execution.
Local createLocal(Descriptor *D)
Callback for registering a local.
bool interpretCall(const FunctionDecl *FD, const Expr *E)
Interpret the given expression as if it was in the body of the given function, i.e.
llvm::function_ref< bool(const Pointer &)> PtrCallback
Definition EvalEmitter.h:35
void emitLabel(LabelTy Label)
Define a label.
bool isActive() const
Since expressions can only jump forward, predicated execution is used to deal with if-else statements...
Definition EvalEmitter.h:79
virtual bool visitExpr(const Expr *E, bool DestroyToplevelScope)=0
Methods implemented by the compiler.
bool fallthrough(const LabelTy &Label)
virtual bool visitDeclAndReturn(const VarDecl *VD, const Expr *Init, bool ConstantContext)=0
void cleanup()
Clean up all resources.
LabelTy getLabel()
Create a label.
EvaluationResult interpretAsPointer(const Expr *E, PtrCallback PtrCB)
Interpret the given Expr to a Pointer.
EvalEmitter(Context &Ctx, Program &P, State &Parent, InterpStack &Stk)
llvm::DenseMap< const ParmVarDecl *, ParamOffset > Params
Parameter indices.
Definition EvalEmitter.h:93
virtual bool emitBool(bool V, const Expr *E)=0
llvm::SmallVector< SmallVector< Local, 8 >, 2 > Descriptors
Local descriptors.
Definition EvalEmitter.h:99
bool jumpTrue(const LabelTy &Label)
Emits jumps.
Defines the result of an evaluation.
bool checkReturnValue(InterpState &S, const Context &Ctx, const Pointer &Ptr, const SourceInfo &Info)
Check that none of the blocks the given pointer (transitively) points to are dynamically allocated.
bool checkFullyInitialized(InterpState &S, const Pointer &Ptr) const
Check that all subobjects of the given pointer have been initialized.
Stack frame storing temporaries and parameters.
Definition InterpStack.h:25
T pop()
Returns the value from the top of the stack and removes it.
Definition InterpStack.h:39
InterpStack & Stk
Temporary stack.
A pointer to a memory block, live or dead.
Definition Pointer.h:91
bool isConst() const
Checks if an object or a subfield is mutable.
Definition Pointer.h:554
T & deref() const
Dereferences the pointer, if it's live.
Definition Pointer.h:660
bool pointsToStringLiteral() const
Definition Pointer.cpp:658
bool isArrayRoot() const
Whether this array refers to an array, but not to the first element.
Definition Pointer.h:391
bool isLive() const
Checks if the pointer is live.
Definition Pointer.h:265
bool isZero() const
Checks if the pointer is null.
Definition Pointer.h:254
APValue toAPValue(const ASTContext &ASTCtx) const
Converts the pointer to an APValue.
Definition Pointer.cpp:167
bool isDereferencable() const
Whether this block can be read from at all.
Definition Pointer.h:694
bool isBlockPointer() const
Definition Pointer.h:465
std::optional< APValue > toRValue(const Context &Ctx, QualType ResultType) const
Converts the pointer to an APValue that is an rvalue.
Definition Pointer.cpp:711
bool isTemporary() const
Checks if the storage is temporary.
Definition Pointer.h:498
const Block * block() const
Definition Pointer.h:599
bool isFunctionPointer() const
Definition Pointer.h:467
The program contains and links the bytecode for all functions.
Definition Program.h:36
Describes the statement/declaration an opcode was generated from.
Definition Source.h:73
Interface for the VM to interact with the AST walker's context.
Definition State.h:79
bool CheckBCPResult(InterpState &S, const Pointer &Ptr)
Definition Interp.cpp:308
bool CheckFinalLoad(InterpState &S, CodePtr OpPC, const Pointer &Ptr)
This is not used by any of the opcodes directly.
Definition Interp.cpp:840
PrimType
Enumeration of the primitive types of the VM.
Definition PrimType.h:34
bool Init(InterpState &S, CodePtr OpPC)
Definition Interp.h:2098
bool CheckLocalLoad(InterpState &S, CodePtr OpPC, const Block *B)
Definition Interp.cpp:771
The JSON file list parser is used to communicate input to InstallAPI.
bool isa(CodeGen::Address addr)
Definition Address.h:330
const FunctionProtoType * T
Describes a memory block created by an allocation site.
Definition Descriptor.h:122
unsigned getAllocSize() const
Returns the allocated size, including metadata.
Definition Descriptor.h:242
Inline descriptor embedded in structures and arrays.
Definition Descriptor.h:67
unsigned IsActive
Flag indicating if the field is the active member of a union.
Definition Descriptor.h:89
unsigned IsBase
Flag indicating if the field is an embedded base class.
Definition Descriptor.h:83
unsigned Offset
Offset inside the structure/array.
Definition Descriptor.h:69
unsigned IsInitialized
For primitive fields, it indicates if the field was initialized.
Definition Descriptor.h:80
unsigned IsConst
Flag indicating if the storage is constant or not.
Definition Descriptor.h:74
unsigned IsFieldMutable
Flag indicating if the field is mutable (if in a record).
Definition Descriptor.h:95
Mapping from primitive types to their representation.
Definition PrimType.h:134
Information about a local's storage.
Definition Function.h:39