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 "IntegralAP.h"
12#include "Interp.h"
13#include "clang/AST/DeclCXX.h"
14#include "clang/AST/ExprCXX.h"
15#include "llvm/ADT/ScopeExit.h"
16
17using namespace clang;
18using namespace clang::interp;
19
21 InterpStack &Stk)
22 : Ctx(Ctx), P(P), S(Parent, P, Stk, Ctx, this), EvalResult(&Ctx) {}
23
24/// Clean up all our resources. This needs to done in failed evaluations before
25/// we call InterpStack::clear(), because there might be a Pointer on the stack
26/// pointing into a Block in the EvalEmitter.
27void EvalEmitter::cleanup() { S.cleanup(); }
28
30 bool ConvertResultToRValue,
31 bool DestroyToplevelScope) {
32 S.setEvalLocation(E->getExprLoc());
33 this->ConvertResultToRValue = ConvertResultToRValue && !isa<ConstantExpr>(E);
34 this->CheckFullyInitialized = isa<ConstantExpr>(E) && !E->isGLValue();
35 EvalResult.setSource(E);
36
37 if (!this->visitExpr(E, DestroyToplevelScope)) {
38 // EvalResult may already have a result set, but something failed
39 // after that (e.g. evaluating destructors).
40 EvalResult.setInvalid();
41 }
42
43 return std::move(this->EvalResult);
44}
45
47 bool CheckFullyInitialized) {
48 assert(VD);
49 assert(Init);
50 this->CheckFullyInitialized = CheckFullyInitialized;
51 S.EvaluatingDecl = VD;
52 S.setEvalLocation(VD->getLocation());
53 EvalResult.setSource(VD);
54
55 QualType T = VD->getType();
56 this->ConvertResultToRValue = !Init->isGLValue() && !T->isPointerType() &&
57 !T->isObjCObjectPointerType();
58
59 if (!this->visitDeclAndReturn(VD, Init, S.inConstantContext()))
60 EvalResult.setInvalid();
61
62 S.EvaluatingDecl = nullptr;
63 updateGlobalTemporaries();
64 return std::move(this->EvalResult);
65}
66
68 const APValue &Value) {
69 assert(VD);
70 S.setEvalLocation(VD->getLocation());
71 S.EvaluatingDecl = VD;
72 S.EvalKind = EvaluationKind::Dtor;
73 EvalResult.setSource(VD);
74
75 if (!this->visitDtorCall(VD, Value))
76 EvalResult.setInvalid();
77
78 S.EvaluatingDecl = nullptr;
79 return std::move(this->EvalResult);
80}
81
83 PtrCallback PtrCB) {
84 S.setEvalLocation(E->getExprLoc());
85 this->ConvertResultToRValue = false;
86 this->CheckFullyInitialized = false;
87 this->PtrCB = PtrCB;
88 EvalResult.setSource(E);
89
90 if (!this->visitExpr(E, true)) {
91 // EvalResult may already have a result set, but something failed
92 // after that (e.g. evaluating destructors).
93 EvalResult.setInvalid();
94 }
95
96 return std::move(this->EvalResult);
97}
98
100 PtrCallback PtrCB) {
101 S.setEvalLocation(E->getExprLoc());
102 this->ConvertResultToRValue = false;
103 this->CheckFullyInitialized = false;
104 this->PtrCB = PtrCB;
105 EvalResult.setSource(E);
106
107 if (!this->visitLValueExpr(E, true))
108 EvalResult.setInvalid();
109
110 return std::move(this->EvalResult);
111}
112
114 // Add parameters to the parameter map. The values in the ParamOffset don't
115 // matter in this case as reading from them can't ever work.
116 for (const ParmVarDecl *PD : FD->parameters()) {
117 this->Params.insert({PD, {0, false}});
118 }
119
120 return this->visitExpr(E, /*DestroyToplevelScope=*/false);
121}
122
124 const FunctionDecl *Callee, ArrayRef<const Expr *> Args, const Expr *This,
125 const Expr *Condition) {
126
127 if (!this->visitWithSubstitutions(Callee, Args, This, Condition))
128 return std::nullopt;
129
130 if (EvalResult.empty() || EvalResult.isInvalid())
131 return false;
132
133 assert(!EvalResult.empty());
134 APValue Result = EvalResult.stealAPValue();
135
136 assert(Result.isInt());
137 return Result.getInt().getBoolValue();
138}
139
140void EvalEmitter::emitLabel(LabelTy Label) { CurrentLabel = Label; }
141
143
145 // Allocate memory for a local.
146 char *Memory = reinterpret_cast<char *>(
147 S.allocate(sizeof(Block) + D->getAllocSize() + Block::InlineDescMD));
148 auto *B = new (Memory) Block(Ctx.getEvalID(), D, Block::InlineDescMD,
149 /*IsStatic=*/false);
150 B->invokeCtor();
151
152 // Initialize local variable inline descriptor.
153 auto &Desc = B->getBlockDesc<InlineDescriptor>();
154 Desc.Desc = D;
155 Desc.Offset = sizeof(InlineDescriptor);
156 Desc.IsActive = false;
157 Desc.IsBase = false;
158 Desc.IsFieldMutable = false;
159 Desc.IsConst = false;
160 Desc.IsInitialized = false;
161
162 // Register the local.
163 unsigned Off = Locals.size();
164 Locals.push_back(Memory);
165 return {D, Off};
166}
167
169 if (isActive()) {
170 CurrentSource = SI;
171 if (S.Stk.pop<bool>())
172 ActiveLabel = Label;
173 }
174 return true;
175}
176
178 if (isActive()) {
179 CurrentSource = SI;
180 if (!S.Stk.pop<bool>())
181 ActiveLabel = Label;
182 }
183 return true;
184}
185
186bool EvalEmitter::jump(const LabelTy &Label, SourceInfo SI) {
187 if (isActive()) {
188 CurrentSource = SI;
189 CurrentLabel = ActiveLabel = Label;
190 }
191 return true;
192}
193
195 if (isActive())
196 ActiveLabel = Label;
197 CurrentLabel = Label;
198 return true;
199}
200
201bool EvalEmitter::speculate(const CallExpr *E, const LabelTy &EndLabel) {
202 if (!isActive())
203 return true;
204
206 auto _ = llvm::scope_exit([&]() { PopIgnoreDiags(S); });
207
208 size_t StackSizeBefore = S.Stk.size();
209 const Expr *Arg = E->getArg(0);
210 if (!this->visit(Arg)) {
211 S.Stk.clearTo(StackSizeBefore);
212
213 if (S.inConstantContext() || Arg->HasSideEffects(S.getASTContext()))
214 return this->emitBool(false, E);
215 return Invalid(S, CodePtr());
216 }
217
218 PrimType T = Ctx.classify(Arg->getType()).value_or(PT_Ptr);
219 if (T == PT_Ptr) {
220 const auto &Ptr = S.Stk.pop<Pointer>();
221 return this->emitBool(CheckBCPResult(S, Ptr), E);
222 }
223
224 // Otherwise, this is fine!
225 if (!this->emitPop(T, E))
226 return false;
227 return this->emitBool(true, E);
228}
229
230template <PrimType OpType> bool EvalEmitter::emitRet(SourceInfo Info) {
231 if (!isActive())
232 return true;
233
234 using T = typename PrimConv<OpType>::T;
235 EvalResult.takeValue(S.Stk.pop<T>().toAPValue(Ctx.getASTContext()));
236 return true;
237}
238
239template <> bool EvalEmitter::emitRet<PT_Ptr>(SourceInfo Info) {
240 if (!isActive())
241 return true;
242
243 const Pointer &Ptr = S.Stk.pop<Pointer>();
244 // If we're returning a raw pointer, call our callback.
245 if (this->PtrCB)
246 return (*this->PtrCB)(S, CodePtr(), Ptr);
247
248 if (!EvalResult.checkDynamicAllocations(S, Ptr, Info))
249 return false;
250 if (CheckFullyInitialized && !EvalResult.checkFullyInitialized(S, Ptr))
251 return false;
252
253 // Function pointers are always returned as lvalues.
254 if (Ptr.isFunctionPointer()) {
255 if (ConvertResultToRValue && Ptr.asFunctionPointer().Func->getDecl())
256 return false;
257 EvalResult.takeValue(Ptr.toAPValue(Ctx.getASTContext()));
258 return true;
259 }
260
261 // Implicitly convert lvalue to rvalue, if requested.
262 if (ConvertResultToRValue) {
263 if (Ptr.isPastEnd())
264 return false;
265
266 if (!Ptr.isZero() && !CheckFinalLoad(S, CodePtr(), Ptr))
267 return false;
268
269 // Never allow reading from a non-const pointer, unless the memory
270 // has been created in this evaluation.
271 if (!Ptr.isZero() && !Ptr.isConst() && Ptr.isBlockPointer() &&
272 Ptr.block()->getEvalID() != Ctx.getEvalID())
273 return false;
274
275 if (std::optional<APValue> V =
276 Ptr.toRValue(Ctx, EvalResult.getSourceType())) {
277 EvalResult.takeValue(std::move(*V));
278 } else {
279 return false;
280 }
281 } else {
282 // If this is pointing to a local variable, just return
283 // the result, even if the pointer is dead.
284 // This will later be diagnosed by CheckLValueConstantExpression.
285 if (Ptr.isBlockPointer() && !Ptr.block()->isStatic()) {
286 EvalResult.takeValue(Ptr.toAPValue(Ctx.getASTContext()));
287 return true;
288 }
289
290 if (!Ptr.isLive() && !Ptr.isTemporary())
291 return false;
292
293 // If the variable of this pointer is being evaluated when returning
294 // its value, mark it as constexpr-unknown.
295 APValue V = Ptr.toAPValue(Ctx.getASTContext());
296 if (const Descriptor *DeclDesc = Ptr.getDeclDesc();
297 DeclDesc && S.EvaluatingDecl &&
298 DeclDesc->asVarDecl() == S.EvaluatingDecl &&
299 S.getLangOpts().CPlusPlus23 &&
300 S.EvaluatingDecl->getType()->isReferenceType()) {
301 V.setConstexprUnknown(true);
302 }
303 EvalResult.takeValue(std::move(V));
304 }
305
306 return true;
307}
308
309bool EvalEmitter::emitRetVoid(SourceInfo Info) {
310 EvalResult.setValid();
311 return true;
312}
313
314bool EvalEmitter::emitRetValue(SourceInfo Info) {
315 const auto &Ptr = S.Stk.pop<Pointer>();
316
317 if (!EvalResult.checkDynamicAllocations(S, Ptr, Info))
318 return false;
319 if (CheckFullyInitialized && !EvalResult.checkFullyInitialized(S, Ptr))
320 return false;
321
322 if (std::optional<APValue> APV =
323 Ptr.toRValue(Ctx, EvalResult.getSourceType())) {
324 EvalResult.takeValue(std::move(*APV));
325 return true;
326 }
327
328 EvalResult.setInvalid();
329 return false;
330}
331
332bool EvalEmitter::emitGetPtrLocal(uint32_t I, SourceInfo Info) {
333 if (!isActive())
334 return true;
335
336 Block *B = getLocal(I);
337 S.Stk.push<Pointer>(B, sizeof(InlineDescriptor));
338 return true;
339}
340
341bool EvalEmitter::emitGetRefLocal(uint32_t I, SourceInfo Info) {
342 if (!isActive())
343 return true;
344
345 Block *B = getLocal(I);
346 return handleReference(S, CodePtr(), B);
347}
348
349template <PrimType OpType>
350bool EvalEmitter::emitGetLocal(uint32_t I, SourceInfo Info) {
351 if (!isActive())
352 return true;
353
354 using T = typename PrimConv<OpType>::T;
355
356 Block *B = getLocal(I);
357
358 if (!CheckLocalLoad(S, CodePtr(), B))
359 return false;
360
361 S.Stk.push<T>(B->deref<T>());
362 return true;
363}
364
365template <PrimType OpType>
366bool EvalEmitter::emitSetLocal(uint32_t I, SourceInfo Info) {
367 if (!isActive())
368 return true;
369
370 using T = typename PrimConv<OpType>::T;
371
372 Block *B = getLocal(I);
373 B->deref<T>() = S.Stk.pop<T>();
374 auto &Desc = B->getBlockDesc<InlineDescriptor>();
375 Desc.IsInitialized = true;
376 Desc.LifeState = Lifetime::Started;
377
378 return true;
379}
380
381bool EvalEmitter::emitDestroy(uint32_t I, SourceInfo Info) {
382 if (!isActive())
383 return true;
384
385 for (auto &Local : Descriptors[I]) {
386 Block *B = getLocal(Local.Offset);
387 S.deallocate(B);
388 }
389
390 return true;
391}
392
393bool EvalEmitter::emitGetLocalEnabled(uint32_t I, SourceInfo Info) {
394 if (!isActive())
395 return true;
396
397 Block *B = getLocal(I);
398 const auto &Desc = B->getBlockDesc<InlineDescriptor>();
399
400 S.Stk.push<bool>(Desc.IsActive);
401 return true;
402}
403
404bool EvalEmitter::emitEnableLocal(uint32_t I, SourceInfo Info) {
405 if (!isActive())
406 return true;
407
408 // FIXME: This is a little dirty, but to avoid adding a flag to
409 // InlineDescriptor that's only ever useful on the toplevel of local
410 // variables, we reuse the IsActive flag for the enabled state. We should
411 // probably use a different struct than InlineDescriptor for the block-level
412 // inline descriptor of local varaibles.
413 Block *B = getLocal(I);
414 auto &Desc = B->getBlockDesc<InlineDescriptor>();
415 Desc.IsActive = true;
416 return true;
417}
418
419/// Global temporaries (LifetimeExtendedTemporary) carry their value
420/// around as an APValue, which codegen accesses.
421/// We set their value once when creating them, but we don't update it
422/// afterwards when code changes it later.
423/// This is what we do here.
424void EvalEmitter::updateGlobalTemporaries() {
425 for (const auto &[E, Temp] : S.SeenGlobalTemporaries) {
426 UnsignedOrNone GlobalIndex = P.getGlobal(E);
427 assert(GlobalIndex);
428 const Pointer &Ptr = P.getPtrGlobal(*GlobalIndex);
429 APValue *Cached = Temp->getOrCreateValue(true);
430
431 QualType TempType = E->getType();
432 if (const auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E))
433 TempType = MTE->getSubExpr()->skipRValueSubobjectAdjustments()->getType();
434
435 if (OptPrimType T = Ctx.classify(TempType)) {
436 TYPE_SWITCH(*T,
437 { *Cached = Ptr.deref<T>().toAPValue(Ctx.getASTContext()); });
438 } else {
439 if (std::optional<APValue> APV = Ptr.toRValue(Ctx, TempType))
440 *Cached = *APV;
441 }
442 }
443 S.SeenGlobalTemporaries.clear();
444}
445
446//===----------------------------------------------------------------------===//
447// Opcode evaluators
448//===----------------------------------------------------------------------===//
449
450#define GET_EVAL_IMPL
451#include "Opcodes.inc"
452#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:235
APValue - This class implements a discriminated union of [uninitialized] [APSInt] [APFloat],...
Definition APValue.h:122
CallExpr - Represents a function call (C99 6.5.2.2, C++ [expr.call]).
Definition Expr.h:2987
Expr * getArg(unsigned Arg)
getArg - Return the specified argument.
Definition Expr.h:3191
SourceLocation getLocation() const
Definition DeclBase.h:447
This represents one expression.
Definition Expr.h:113
bool isGLValue() const
Definition Expr.h:288
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:3722
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:145
Represents a function declaration or definition.
Definition Decl.h:2059
ArrayRef< ParmVarDecl * > parameters() const
Definition Decl.h:2905
Represents a parameter to a function.
Definition Decl.h:1820
A (possibly-)qualified type.
Definition TypeBase.h:938
QualType getType() const
Definition Decl.h:724
Represents a variable declaration or definition.
Definition Decl.h:933
A memory block, either on the stack or in the heap.
Definition InterpBlock.h:43
const T & deref() const
static constexpr uint8_t InlineDescMD
Definition InterpBlock.h:51
Pointer into the code segment.
Definition Source.h:31
Holds all information required to evaluate constexpr code in a module.
Definition Context.h:47
ASTContext & getASTContext() const
Returns the AST context.
Definition Context.h:107
unsigned getEvalID() const
Definition Context.h:181
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)
EvaluationResult interpretExpr(const Expr *E, bool ConvertResultToRValue=false, bool DestroyToplevelScope=false)
bool jump(const LabelTy &Label, SourceInfo SI)
virtual bool visit(const Expr *E)=0
bool speculate(const CallExpr *E, const LabelTy &EndLabel)
Speculative execution.
Local createLocal(const Descriptor *D)
Callback for registering a local.
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)
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.
bool isActive() const
Since expressions can only jump forward, predicated execution is used to deal with if-else statements...
Definition EvalEmitter.h:95
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.
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::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:36
Defines the result of an evaluation.
bool checkDynamicAllocations(InterpState &S, const Pointer &Ptr, 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:531
The program contains and links the bytecode for all functions.
Definition Program.h:37
Describes the statement/declaration an opcode was generated from.
Definition Source.h:77
Interface for the VM to interact with the AST walker's context.
Definition State.h:79
bool PushIgnoreDiags(InterpState &S)
Definition Interp.h:3713
bool PopIgnoreDiags(InterpState &S)
Definition Interp.h:3725
bool handleReference(InterpState &S, CodePtr OpPC, Block *B)
Definition Interp.cpp:2830
bool CheckBCPResult(InterpState &S, const Pointer &Ptr)
Definition Interp.cpp:305
bool This(InterpState &S, CodePtr OpPC)
Definition Interp.h:3232
bool CheckFinalLoad(InterpState &S, CodePtr OpPC, const Pointer &Ptr)
This is not used by any of the opcodes directly.
Definition Interp.cpp:956
PrimType
Enumeration of the primitive types of the VM.
Definition PrimType.h:34
bool Init(InterpState &S, CodePtr OpPC)
Definition Interp.h:2413
bool CheckLocalLoad(InterpState &S, CodePtr OpPC, const Block *B)
Definition Interp.cpp:848
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.
__packed_splat4 __packed_splat2 __packed_splat8 __packed_splat4 __packed_splat2 __packed_splat4 __packed_splat2 __packed_splat8 __packed_splat4 uint32_t
Describes a memory block created by an allocation site.
Definition Descriptor.h:122
const bool IsConst
Flag indicating if the block is mutable.
Definition Descriptor.h:154
unsigned getAllocSize() const
Returns the allocated size, including metadata.
Definition Descriptor.h:237
Inline descriptor embedded in structures and arrays.
Definition Descriptor.h:67
Mapping from primitive types to their representation.
Definition PrimType.h:162
Information about a local's storage.
Definition Function.h:38