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 assert(VD);
55 assert(Init);
56 this->CheckFullyInitialized = CheckFullyInitialized;
57 S.EvaluatingDecl = VD;
58 S.setEvalLocation(VD->getLocation());
59 EvalResult.setSource(VD);
60
61 QualType T = VD->getType();
62 this->ConvertResultToRValue = !Init->isGLValue() && !T->isPointerType() &&
63 !T->isObjCObjectPointerType();
64 EvalResult.setSource(VD);
65
66 if (!this->visitDeclAndReturn(VD, Init, S.inConstantContext()))
67 EvalResult.setInvalid();
68
69 S.EvaluatingDecl = nullptr;
70 updateGlobalTemporaries();
71 return std::move(this->EvalResult);
72}
73
75 PtrCallback PtrCB) {
76
77 S.setEvalLocation(E->getExprLoc());
78 this->ConvertResultToRValue = false;
79 this->CheckFullyInitialized = false;
80 this->PtrCB = PtrCB;
81 EvalResult.setSource(E);
82
83 if (!this->visitExpr(E, /*DestroyToplevelScope=*/true)) {
84 // EvalResult may already have a result set, but something failed
85 // after that (e.g. evaluating destructors).
86 EvalResult.setInvalid();
87 }
88
89 return std::move(this->EvalResult);
90}
91
92bool EvalEmitter::interpretCall(const FunctionDecl *FD, const Expr *E) {
93 // Add parameters to the parameter map. The values in the ParamOffset don't
94 // matter in this case as reading from them can't ever work.
95 for (const ParmVarDecl *PD : FD->parameters()) {
96 this->Params.insert({PD, {0, false}});
97 }
98
99 return this->visitExpr(E, /*DestroyToplevelScope=*/false);
100}
101
102void EvalEmitter::emitLabel(LabelTy Label) { CurrentLabel = Label; }
103
105
107 // Allocate memory for a local.
108 auto Memory = std::make_unique<char[]>(sizeof(Block) + D->getAllocSize());
109 auto *B = new (Memory.get()) Block(Ctx.getEvalID(), D, /*isStatic=*/false);
110 B->invokeCtor();
111
112 // Initialize local variable inline descriptor.
113 InlineDescriptor &Desc = *reinterpret_cast<InlineDescriptor *>(B->rawData());
114 Desc.Desc = D;
115 Desc.Offset = sizeof(InlineDescriptor);
116 Desc.IsActive = true;
117 Desc.IsBase = false;
118 Desc.IsFieldMutable = false;
119 Desc.IsConst = false;
120 Desc.IsInitialized = false;
121
122 // Register the local.
123 unsigned Off = Locals.size();
124 Locals.push_back(std::move(Memory));
125 return {Off, D};
126}
127
128bool EvalEmitter::jumpTrue(const LabelTy &Label) {
129 if (isActive()) {
130 if (S.Stk.pop<bool>())
131 ActiveLabel = Label;
132 }
133 return true;
134}
135
136bool EvalEmitter::jumpFalse(const LabelTy &Label) {
137 if (isActive()) {
138 if (!S.Stk.pop<bool>())
139 ActiveLabel = Label;
140 }
141 return true;
142}
143
144bool EvalEmitter::jump(const LabelTy &Label) {
145 if (isActive())
146 CurrentLabel = ActiveLabel = Label;
147 return true;
148}
149
151 if (isActive())
152 ActiveLabel = Label;
153 CurrentLabel = Label;
154 return true;
155}
156
157bool EvalEmitter::speculate(const CallExpr *E, const LabelTy &EndLabel) {
158 size_t StackSizeBefore = S.Stk.size();
159 const Expr *Arg = E->getArg(0);
160 if (!this->visit(Arg)) {
161 S.Stk.clearTo(StackSizeBefore);
162
163 if (S.inConstantContext() || Arg->HasSideEffects(S.getASTContext()))
164 return this->emitBool(false, E);
165 return Invalid(S, OpPC);
166 }
167
168 PrimType T = Ctx.classify(Arg->getType()).value_or(PT_Ptr);
169 if (T == PT_Ptr) {
170 const auto &Ptr = S.Stk.pop<Pointer>();
171 return this->emitBool(CheckBCPResult(S, Ptr), E);
172 }
173
174 // Otherwise, this is fine!
175 if (!this->emitPop(T, E))
176 return false;
177 return this->emitBool(true, E);
178}
179
180template <PrimType OpType> bool EvalEmitter::emitRet(SourceInfo Info) {
181 if (!isActive())
182 return true;
183
184 using T = typename PrimConv<OpType>::T;
185 EvalResult.takeValue(S.Stk.pop<T>().toAPValue(Ctx.getASTContext()));
186 return true;
187}
188
189template <> bool EvalEmitter::emitRet<PT_Ptr>(SourceInfo Info) {
190 if (!isActive())
191 return true;
192
193 const Pointer &Ptr = S.Stk.pop<Pointer>();
194
195 if (Ptr.isFunctionPointer()) {
196 EvalResult.takeValue(Ptr.toAPValue(Ctx.getASTContext()));
197 return true;
198 }
199
200 // If we're returning a raw pointer, call our callback.
201 if (this->PtrCB)
202 return (*this->PtrCB)(Ptr);
203
204 if (!EvalResult.checkReturnValue(S, Ctx, Ptr, Info))
205 return false;
206 if (CheckFullyInitialized && !EvalResult.checkFullyInitialized(S, Ptr))
207 return false;
208
209 // Implicitly convert lvalue to rvalue, if requested.
210 if (ConvertResultToRValue) {
211 if (!Ptr.isZero() && !Ptr.isDereferencable())
212 return false;
213
214 if (Ptr.pointsToStringLiteral() && Ptr.isArrayRoot())
215 return false;
216
217 if (!Ptr.isZero() && !CheckFinalLoad(S, OpPC, Ptr))
218 return false;
219
220 // Never allow reading from a non-const pointer, unless the memory
221 // has been created in this evaluation.
222 if (!Ptr.isZero() && !Ptr.isConst() && Ptr.isBlockPointer() &&
223 Ptr.block()->getEvalID() != Ctx.getEvalID())
224 return false;
225
226 if (std::optional<APValue> V =
227 Ptr.toRValue(Ctx, EvalResult.getSourceType())) {
228 EvalResult.takeValue(std::move(*V));
229 } else {
230 return false;
231 }
232 } else {
233 // If this is pointing to a local variable, just return
234 // the result, even if the pointer is dead.
235 // This will later be diagnosed by CheckLValueConstantExpression.
236 if (Ptr.isBlockPointer() && !Ptr.block()->isStatic()) {
237 EvalResult.takeValue(Ptr.toAPValue(Ctx.getASTContext()));
238 return true;
239 }
240
241 if (!Ptr.isLive() && !Ptr.isTemporary())
242 return false;
243
244 EvalResult.takeValue(Ptr.toAPValue(Ctx.getASTContext()));
245 }
246
247 return true;
248}
249
250bool EvalEmitter::emitRetVoid(SourceInfo Info) {
251 EvalResult.setValid();
252 return true;
253}
254
255bool EvalEmitter::emitRetValue(SourceInfo Info) {
256 const auto &Ptr = S.Stk.pop<Pointer>();
257
258 if (!EvalResult.checkReturnValue(S, Ctx, Ptr, Info))
259 return false;
260 if (CheckFullyInitialized && !EvalResult.checkFullyInitialized(S, Ptr))
261 return false;
262
263 if (std::optional<APValue> APV =
264 Ptr.toRValue(S.getASTContext(), EvalResult.getSourceType())) {
265 EvalResult.takeValue(std::move(*APV));
266 return true;
267 }
268
269 EvalResult.setInvalid();
270 return false;
271}
272
273bool EvalEmitter::emitGetPtrLocal(uint32_t I, SourceInfo Info) {
274 if (!isActive())
275 return true;
276
277 Block *B = getLocal(I);
278 S.Stk.push<Pointer>(B, sizeof(InlineDescriptor));
279 return true;
280}
281
282template <PrimType OpType>
283bool EvalEmitter::emitGetLocal(uint32_t I, SourceInfo Info) {
284 if (!isActive())
285 return true;
286
287 using T = typename PrimConv<OpType>::T;
288
289 Block *B = getLocal(I);
290
291 if (!CheckLocalLoad(S, OpPC, B))
292 return false;
293
294 S.Stk.push<T>(*reinterpret_cast<T *>(B->data()));
295 return true;
296}
297
298template <PrimType OpType>
299bool EvalEmitter::emitSetLocal(uint32_t I, SourceInfo Info) {
300 if (!isActive())
301 return true;
302
303 using T = typename PrimConv<OpType>::T;
304
305 Block *B = getLocal(I);
306 *reinterpret_cast<T *>(B->data()) = S.Stk.pop<T>();
307 InlineDescriptor &Desc = *reinterpret_cast<InlineDescriptor *>(B->rawData());
308 Desc.IsInitialized = true;
309
310 return true;
311}
312
313bool EvalEmitter::emitDestroy(uint32_t I, SourceInfo Info) {
314 if (!isActive())
315 return true;
316
317 for (auto &Local : Descriptors[I]) {
318 Block *B = getLocal(Local.Offset);
319 S.deallocate(B);
320 }
321
322 return true;
323}
324
325/// Global temporaries (LifetimeExtendedTemporary) carry their value
326/// around as an APValue, which codegen accesses.
327/// We set their value once when creating them, but we don't update it
328/// afterwards when code changes it later.
329/// This is what we do here.
330void EvalEmitter::updateGlobalTemporaries() {
331 for (const auto &[E, Temp] : S.SeenGlobalTemporaries) {
332 UnsignedOrNone GlobalIndex = P.getGlobal(E);
333 assert(GlobalIndex);
334 const Pointer &Ptr = P.getPtrGlobal(*GlobalIndex);
335 APValue *Cached = Temp->getOrCreateValue(true);
336 if (OptPrimType T = Ctx.classify(E->getType())) {
337 TYPE_SWITCH(*T,
338 { *Cached = Ptr.deref<T>().toAPValue(Ctx.getASTContext()); });
339 } else {
340 if (std::optional<APValue> APV =
341 Ptr.toRValue(Ctx, Temp->getTemporaryExpr()->getType()))
342 *Cached = *APV;
343 }
344 }
345 S.SeenGlobalTemporaries.clear();
346}
347
348//===----------------------------------------------------------------------===//
349// Opcode evaluators
350//===----------------------------------------------------------------------===//
351
352#define GET_EVAL_IMPL
353#include "Opcodes.inc"
354#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:2877
Expr * getArg(unsigned Arg)
getArg - Return the specified argument.
Definition Expr.h:3081
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:666
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:719
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