clang 24.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 "EvalSettings.h"
12#include "IntegralAP.h"
13#include "Interp.h"
14#include "clang/AST/DeclCXX.h"
15#include "clang/AST/ExprCXX.h"
16#include "llvm/ADT/ScopeExit.h"
17
18using namespace clang;
19using namespace clang::interp;
20
23 : Ctx(Ctx), P(P), S(Settings, P, Stk, FA, Ctx, this), EvalResult(Ctx),
24 ConstexprKind(Settings.ConstexprKind) {}
25
28 : Ctx(Ctx), P(P), S(Status, P, Stk, FA, Ctx, this), EvalResult(Ctx) {}
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) && !E->isGLValue();
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
65 if (!this->visitDeclAndReturn(VD, Init, S.inConstantContext()))
66 EvalResult.setInvalid();
67
68 S.EvaluatingDecl = nullptr;
69 updateGlobalTemporaries();
70 return std::move(this->EvalResult);
71}
72
74 const APValue &Value) {
75 assert(VD);
76 S.setEvalLocation(VD->getLocation());
77 S.EvaluatingDecl = VD;
78 S.EvalKind = EvaluationKind::Dtor;
79 EvalResult.setSource(VD);
80
81 if (!this->visitDtorCall(VD, Value))
82 EvalResult.setInvalid();
83
84 S.EvaluatingDecl = nullptr;
85 return std::move(this->EvalResult);
86}
87
89 PtrCallback PtrCB) {
90 S.setEvalLocation(E->getExprLoc());
91 this->ConvertResultToRValue = false;
92 this->CheckFullyInitialized = false;
93 this->PtrCB = PtrCB;
94 EvalResult.setSource(E);
95
96 if (!this->visitExpr(E, true)) {
97 // EvalResult may already have a result set, but something failed
98 // after that (e.g. evaluating destructors).
99 EvalResult.setInvalid();
100 }
101
102 return std::move(this->EvalResult);
103}
104
106 PtrCallback PtrCB) {
107 S.setEvalLocation(E->getExprLoc());
108 this->ConvertResultToRValue = false;
109 this->CheckFullyInitialized = false;
110 this->PtrCB = PtrCB;
111 EvalResult.setSource(E);
112
113 if (!this->visitLValueExpr(E, true))
114 EvalResult.setInvalid();
115
116 return std::move(this->EvalResult);
117}
118
120 // Add parameters to the parameter map. The values in the ParamOffset don't
121 // matter in this case as reading from them can't ever work.
122 for (const ParmVarDecl *PD : FD->parameters()) {
123 this->Params.insert({PD, {0, false}});
124 }
125
126 return this->visitExpr(E, /*DestroyToplevelScope=*/false);
127}
128
130 const FunctionDecl *Callee, ArrayRef<const Expr *> Args, const Expr *This,
131 const Expr *Condition) {
132
133 if (!this->visitWithSubstitutions(Callee, Args, This, Condition))
134 return std::nullopt;
135
136 if (EvalResult.empty() || EvalResult.isInvalid())
137 return false;
138
139 assert(!EvalResult.empty());
140 APValue Result = EvalResult.stealAPValue();
141
142 assert(Result.isInt());
143 return Result.getInt().getBoolValue();
144}
145
146void EvalEmitter::emitLabel(LabelTy Label) { CurrentLabel = Label; }
147
149
151 bool IsConstexprUnknown) {
152
153 BlockFlags Flags = BlockFlags().withConstexprUnknown(IsConstexprUnknown);
154 // Allocate memory for a local.
155 char *Memory =
156 reinterpret_cast<char *>(S.allocate(Block::allocSize(D, Block::Local)));
157 auto *B = new (Memory) Block(Ctx.getEvalID(), D, Block::Local, Flags);
158 B->invokeCtor();
159
160 // Initialize local variable inline descriptor.
161 auto &Desc = B->getBlockDesc<LocalInlineDescriptor>();
162 new (&Desc) LocalInlineDescriptor();
163
164 // Register the local.
165 unsigned Off = Locals.size();
166 Locals.push_back(Memory);
167 return {D, Off};
168}
169
171 if (isActive()) {
172 CurrentSource = SI;
173 if (S.Stk.pop<bool>())
174 ActiveLabel = Label;
175 }
176 return true;
177}
178
180 if (isActive()) {
181 CurrentSource = SI;
182 if (!S.Stk.pop<bool>())
183 ActiveLabel = Label;
184 }
185 return true;
186}
187
188bool EvalEmitter::jump(const LabelTy &Label, SourceInfo SI) {
189 if (isActive()) {
190 CurrentSource = SI;
191 CurrentLabel = ActiveLabel = Label;
192 }
193 return true;
194}
195
197 if (isActive())
198 ActiveLabel = Label;
199 CurrentLabel = Label;
200 return true;
201}
202
203bool EvalEmitter::speculate(const CallExpr *E, const LabelTy &EndLabel) {
204 if (!isActive())
205 return true;
206
208 auto _ = llvm::scope_exit([&]() { PopIgnoreDiags(S); });
209
210 size_t StackSizeBefore = S.Stk.size();
211 const Expr *Arg = E->getArg(0);
212 if (!this->visit(Arg)) {
213 S.Stk.clearTo(StackSizeBefore);
214
215 if (S.inConstantContext() || Arg->HasSideEffects(S.getASTContext()))
216 return this->emitBool(false, E);
217 return Invalid(S, CodePtr());
218 }
219
220 PrimType T = Ctx.classify(Arg->getType()).value_or(PT_Ptr);
221 if (T == PT_Ptr) {
222 const auto &Ptr = S.Stk.pop<Pointer>();
223 return this->emitBool(CheckBCPResult(S, Ptr), E);
224 }
225
226 // Otherwise, this is fine!
227 if (!this->emitPop(T, E))
228 return false;
229 return this->emitBool(true, E);
230}
231
232template <PrimType OpType> bool EvalEmitter::emitRet(SourceInfo Info) {
233 if (!isActive())
234 return true;
235
236 using T = typename PrimConv<OpType>::T;
237 EvalResult.takeValue(S.Stk.pop<T>().toAPValue(Ctx.getASTContext()));
238 return true;
239}
240
241template <> bool EvalEmitter::emitRet<PT_MemberPtr>(SourceInfo Info) {
242 if (!isActive())
243 return true;
244
245 const MemberPointer &MP = S.Stk.pop<MemberPointer>();
246 if (!EvalResult.checkMemberPointer(S, MP, Info, ConstexprKind))
247 return false;
248
249 EvalResult.takeValue(MP.toAPValue(Ctx.getASTContext()));
250 return true;
251}
252
253template <> bool EvalEmitter::emitRet<PT_Ptr>(SourceInfo Info) {
254 if (!isActive())
255 return true;
256
257 const Pointer &Ptr = S.Stk.pop<Pointer>();
258 // If we're returning a raw pointer, call our callback.
259 if (this->PtrCB)
260 return (*this->PtrCB)(S, CodePtr(), Ptr);
261
262 if (!EvalResult.checkDynamicAllocations(S, Ptr, Info))
263 return false;
264
265 if (CheckFullyInitialized && !EvalResult.checkFullyInitialized(S, Ptr))
266 return false;
267
268 // Function pointers are always returned as lvalues.
269 if (Ptr.isFunctionPointer()) {
270 if (ConvertResultToRValue && Ptr.asFunctionPointer().Func->getDecl())
271 return false;
272 if (!EvalResult.checkFunctionPointer(S, Ptr, Info, ConstexprKind))
273 return false;
274
275 EvalResult.takeValue(Ptr.toAPValue(Ctx.getASTContext()));
276 return true;
277 }
278
279 // Implicitly convert lvalue to rvalue, if requested.
280 if (ConvertResultToRValue) {
281 if (!Ptr.isZero() && !CheckFinalLoad(S, CodePtr(), Ptr))
282 return false;
283
284 if (!EvalResult.checkLValueFields(S, Ptr, Info, ConstexprKind))
285 return false;
286
287 if (std::optional<APValue> V =
288 Ptr.toRValue(Ctx, EvalResult.getSourceType())) {
289 EvalResult.takeValue(std::move(*V));
290 return true;
291 }
292 return false;
293 }
294
295 // Return as lvalue.
296 if (!EvalResult.checkLValue(S, Ptr, Info, ConstexprKind))
297 return false;
298
299 if (!Ptr.isLive() && !Ptr.isTemporary())
300 return false;
301
302 if (const Descriptor *DeclDesc = Ptr.getDeclDesc();
303 DeclDesc && S.EvaluatingDecl &&
304 ((DeclDesc->asVarDecl() == S.EvaluatingDecl &&
305 S.getLangOpts().CPlusPlus23 &&
306 S.EvaluatingDecl->getType()->isReferenceType()) ||
307 Ptr.isConstexprUnknown())) {
308 S.FFDiag(Info, diag::note_constexpr_var_init_non_constant, 1)
309 << DeclDesc->asVarDecl();
310 S.Note(DeclDesc->asVarDecl()->getLocation(), diag::note_declared_at);
311
312 return false;
313 }
314
315 APValue V = Ptr.toAPValue(Ctx.getASTContext());
316 EvalResult.takeValue(std::move(V));
317 return true;
318}
319
320bool EvalEmitter::emitRetVoid(SourceInfo Info) {
321 EvalResult.setValid();
322 return true;
323}
324
325bool EvalEmitter::emitRetValue(SourceInfo Info) {
326 const auto &Ptr = S.Stk.pop<Pointer>();
327
328 if (!EvalResult.checkDynamicAllocations(S, Ptr, Info))
329 return false;
330 if (!EvalResult.checkFullyInitialized(S, Ptr))
331 return false;
332 if (!EvalResult.checkLValueFields(S, Ptr, Info, ConstexprKind))
333 return false;
334
335 if (std::optional<APValue> APV =
336 Ptr.toRValue(Ctx, EvalResult.getSourceType())) {
337 EvalResult.takeValue(std::move(*APV));
338 return true;
339 }
340
341 EvalResult.setInvalid();
342 return false;
343}
344
345bool EvalEmitter::emitGetPtrLocal(uint32_t I, SourceInfo Info) {
346 if (!isActive())
347 return true;
348
349 Block *B = getLocal(I);
350 S.Stk.push<Pointer>(B);
351 return true;
352}
353
354bool EvalEmitter::emitGetRefLocal(uint32_t I, SourceInfo Info) {
355 if (!isActive())
356 return true;
357
358 Block *B = getLocal(I);
359 return handleReference(S, CodePtr(), B);
360}
361
362template <PrimType OpType>
363bool EvalEmitter::emitGetLocal(uint32_t I, SourceInfo Info) {
364 if (!isActive())
365 return true;
366
367 using T = typename PrimConv<OpType>::T;
368
369 Block *B = getLocal(I);
370
371 if (!CheckLocalLoad(S, CodePtr(), B))
372 return false;
373
374 S.Stk.push<T>(B->deref<T>());
375 return true;
376}
377
378template <PrimType OpType>
379bool EvalEmitter::emitSetLocal(uint32_t I, SourceInfo Info) {
380 if (!isActive())
381 return true;
382
383 using T = typename PrimConv<OpType>::T;
384
385 Block *B = getLocal(I);
386 B->deref<T>() = S.Stk.pop<T>();
387 auto &Desc = B->getBlockDesc<LocalInlineDescriptor>();
388 Desc.IsInitialized = true;
389 Desc.setLifetime(Lifetime::Started);
390
391 return true;
392}
393
394bool EvalEmitter::emitDestroy(uint32_t I, SourceInfo Info) {
395 if (!isActive())
396 return true;
397
398 for (auto &Local : Descriptors[I]) {
399 Block *B = getLocal(Local.Offset);
400 S.deallocate(B);
401 }
402
403 return true;
404}
405
406bool EvalEmitter::emitGetLocalEnabled(uint32_t I, SourceInfo Info) {
407 if (!isActive())
408 return true;
409
410 Block *B = getLocal(I);
411 const auto &Desc = B->getBlockDesc<LocalInlineDescriptor>();
412
413 S.Stk.push<bool>(Desc.IsEnabled);
414 return true;
415}
416
417bool EvalEmitter::emitEnableLocal(uint32_t I, SourceInfo Info) {
418 if (!isActive())
419 return true;
420
421 Block *B = getLocal(I);
422 auto &Desc = B->getBlockDesc<LocalInlineDescriptor>();
423 Desc.IsEnabled = true;
424 return true;
425}
426
427/// Global temporaries (LifetimeExtendedTemporary) carry their value
428/// around as an APValue, which codegen accesses.
429/// We set their value once when creating them, but we don't update it
430/// afterwards when code changes it later.
431/// This is what we do here.
432void EvalEmitter::updateGlobalTemporaries() {
433 for (const auto &[E, Temp] : S.SeenGlobalTemporaries) {
434 UnsignedOrNone GlobalIndex = P.getGlobal(E);
435 assert(GlobalIndex);
436 const Pointer &Ptr = P.getPtrGlobal(*GlobalIndex);
437 APValue *Cached = Temp->getOrCreateValue(true);
438
439 QualType TempType = E->getType();
440 if (const auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E))
441 TempType = MTE->getSubExpr()->skipRValueSubobjectAdjustments()->getType();
442
443 if (OptPrimType T = Ctx.classify(TempType)) {
444 TYPE_SWITCH(*T,
445 { *Cached = Ptr.deref<T>().toAPValue(Ctx.getASTContext()); });
446 } else {
447 if (std::optional<APValue> APV = Ptr.toRValue(Ctx, TempType))
448 *Cached = *APV;
449 }
450 }
451 S.SeenGlobalTemporaries.clear();
452}
453
454//===----------------------------------------------------------------------===//
455// Opcode evaluators
456//===----------------------------------------------------------------------===//
457
458#define GET_EVAL_IMPL
459#include "Opcodes.inc"
460#undef GET_EVAL_IMPL
#define V(N, I)
Defines the C++ Decl subclasses, other than those for templates (found in DeclTemplate....
Defines the clang::Expr interface and subclasses for C++ expressions.
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:240
APValue - This class implements a discriminated union of [uninitialized] [APSInt] [APFloat],...
Definition APValue.h:158
CallExpr - Represents a function call (C99 6.5.2.2, C++ [expr.call]).
Definition Expr.h:3012
Expr * getArg(unsigned Arg)
getArg - Return the specified argument.
Definition Expr.h:3216
SourceLocation getLocation() const
Definition DeclBase.h:448
This represents one expression.
Definition Expr.h:114
bool isGLValue() const
Definition Expr.h:289
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:3728
SourceLocation getExprLoc() const LLVM_READONLY
getExprLoc - Return the preferred location for the arrow when diagnosing a problem with a generic exp...
Definition Expr.cpp:283
QualType getType() const
Definition Expr.h:146
Represents a function declaration or definition.
Definition Decl.h:2082
ArrayRef< ParmVarDecl * > parameters() const
Definition Decl.h:2947
Represents a parameter to a function.
Definition Decl.h:1832
A (possibly-)qualified type.
Definition TypeBase.h:938
QualType getType() const
Definition Decl.h:725
Represents a variable declaration or definition.
Definition Decl.h:934
static unsigned allocSize(const Descriptor *D, BlockKind K)
Number of bytes needed to allocate the block.
Definition Block.h:83
const T & deref() const
Definition Block.h:143
Pointer into the code segment.
Definition Source.h:31
Holds all information required to evaluate constexpr code in a module.
Definition Context.h:49
ASTContext & getASTContext() const
Returns the AST context.
Definition Context.h:116
llvm::DenseMap< const ParmVarDecl *, FuncParam > Params
Parameter indices.
EvaluationResult interpretDecl(const VarDecl *VD, const Expr *Init, bool CheckFullyInitialized)
EvaluationResult interpretDestructor(const VarDecl *VD, const APValue &Value)
bool jump(const LabelTy &Label, SourceInfo SI)
virtual bool visit(const Expr *E)=0
bool speculate(const CallExpr *E, const LabelTy &EndLabel)
Speculative execution.
std::optional< bool > interpretWithSubstitutions(const FunctionDecl *Callee, ArrayRef< const Expr * > Args, const Expr *This, const Expr *Condition)
virtual bool visitDtorCall(const VarDecl *VD, const APValue &Value)=0
bool jumpFalse(const LabelTy &Label, SourceInfo SI)
EvalEmitter(Context &Ctx, Program &P, const EvalSettings &Settings, InterpStack &Stk, FrameAllocator &FrameAlloc)
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.
void emitLabel(LabelTy Label)
Define a label.
EvaluationResult interpretExpr(const Expr *E)
Definition EvalEmitter.h:40
bool isActive() const
Since expressions can only jump forward, predicated execution is used to deal with if-else statements...
virtual bool visitWithSubstitutions(const FunctionDecl *Callee, ArrayRef< const Expr * > Args, const Expr *This, const Expr *Condition)=0
EvaluationResult interpretAsLValuePointer(const Expr *E, PtrCallback PtrCB)
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.
Local createLocal(const Descriptor *D, bool IsConstexprUnknown=false)
Callback for registering a local.
LabelTy getLabel()
Create a label.
EvaluationResult interpretAsPointer(const Expr *E, PtrCallback PtrCB)
Interpret the given Expr to a Pointer.
llvm::SmallVector< SmallVector< Local, 2 >, 1 > Descriptors
Local descriptors.
virtual bool emitBool(bool V, const Expr *E)=0
bool jumpTrue(const LabelTy &Label, SourceInfo SI)
Emits jumps.
virtual bool visitLValueExpr(const Expr *E, bool DestroyToplevelScope)=0
llvm::function_ref< bool(InterpState &S, CodePtr OpPC, const Pointer &)> PtrCallback
Definition EvalEmitter.h:37
Defines the result of an evaluation.
static bool checkMemberPointer(InterpState &S, const MemberPointer &MemberPtr, SourceInfo Info, ConstantExprKind ConstexprKind)
Check if the given member pointer can be returned from an evaluation.
bool checkFunctionPointer(InterpState &S, const Pointer &Ptr, SourceInfo Info, ConstantExprKind ConstexprKind) const
Check if the given function pointer can be returned from an evaluation.
bool checkDynamicAllocations(InterpState &S, const Pointer &Ptr, SourceInfo Info) const
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.
Allocator for function frames.
Stack frame storing temporaries and parameters.
Definition InterpStack.h:26
T pop()
Returns the value from the top of the stack and removes it.
Definition InterpStack.h:40
InterpStack & Stk
Temporary stack.
APValue toAPValue(const ASTContext &) const
A pointer to a memory block, live or dead.
Definition Pointer.h:547
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
bool PushIgnoreDiags(InterpState &S)
Definition Interp.h:3682
bool PopIgnoreDiags(InterpState &S)
Definition Interp.h:3694
bool handleReference(InterpState &S, CodePtr OpPC, Block *B)
Definition Interp.cpp:3059
bool CheckBCPResult(InterpState &S, const Pointer &Ptr)
Definition Interp.cpp:342
bool This(InterpState &S, CodePtr OpPC)
Definition Interp.h:3178
bool CheckFinalLoad(InterpState &S, CodePtr OpPC, const Pointer &Ptr)
This is not used by any of the opcodes directly.
Definition Interp.cpp:1037
PrimType
Enumeration of the primitive types of the VM.
Definition PrimType.h:35
bool Init(InterpState &S, CodePtr OpPC)
Definition Interp.h:2381
bool CheckLocalLoad(InterpState &S, CodePtr OpPC, const Block *B)
Definition Interp.cpp:893
Top level wrappers for InstallAPI frontend operations.
bool isa(CodeGen::Address addr)
Definition Address.h:330
@ Result
The result type of a method or function.
Definition TypeBase.h:906
OptionalUnsigned< unsigned > UnsignedOrNone
const FunctionProtoType * T
@ Off
Never emit colors regardless of the output stream.
EvalStatus is a struct with detailed info about an evaluation in progress.
Definition Expr.h:623
constexpr BlockFlags withConstexprUnknown(bool B=true) const
Definition Block.h:46
Describes a memory block created by an allocation site.
Definition Descriptor.h:126
Mapping from primitive types to their representation.
Definition PrimType.h:164
Information about a local's storage.
Definition Function.h:38