1//===--- InterpFrame.cpp - Call Frame implementation 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 "InterpFrame.h"
10#include "Boolean.h"
11#include "Char.h"
12#include "Function.h"
13#include "InterpStack.h"
14#include "InterpState.h"
15#include "MemberPointer.h"
16#include "Pointer.h"
17#include "PrimType.h"
18#include "clang/AST/ASTContext.h"
19#include "clang/AST/DeclCXX.h"
20#include "clang/AST/ExprCXX.h"
21
22using namespace clang;
23using namespace clang::interp;
24
25InterpFrame::InterpFrame(InterpState &S)
26 : Caller(nullptr), S(S), Func(nullptr), RetPC(CodePtr()), Args(nullptr),
27 ArgSize(0) {}
28
29InterpFrame::InterpFrame(InterpState &S, const Function *Func,
30 InterpFrame *Caller, CodePtr RetPC, unsigned ArgSize)
31 : Caller(Caller), S(S), Func(Func), RetPC(RetPC),
32 Args(static_cast<char *>(S.Stk.top())), ArgSize(ArgSize) {
33 assert(Func);
34#ifndef NDEBUG
35 FrameOffset = S.Stk.size();
36#endif
37
38 FuncFlags |= Func->hasRVO() * HasRVOFlag;
39 FuncFlags |= Func->hasThisPointer() * HasThisFlag;
40
41 // Initialize argument blocks.
42 for (unsigned I = 0, N = Func->getNumWrittenParams(); I != N; ++I)
43 new (argBlock(Index: I))
44 Block(S.EvalID, Func->getParamDescriptor(Index: I).Desc, Block::None);
45
46 if (Func->getFrameSize() == 0)
47 return;
48
49 for (auto &Scope : Func->scopes()) {
50 for (auto &Local : Scope.locals()) {
51 Block *B = localBlock(Offset: Local.Offset);
52 new (B) Block(S.EvalID, Local.Desc, Block::Local);
53 // Note that we are NOT calling invokeCtor() here, since that is done
54 // lazily when accessing the local.
55 }
56 }
57}
58
59InterpFrame::InterpFrame(InterpState &S, const Function *Func, CodePtr RetPC,
60 unsigned VarArgSize)
61 : InterpFrame(S, Func, S.Current, RetPC, Func->getArgSize() + VarArgSize) {
62 // As per our calling convention, the this pointer is
63 // part of the ArgSize.
64 // If the function has RVO, the RVO pointer is first.
65 // If the fuction has a This pointer, that one is next.
66 // Then follow the actual arguments (but those are handled
67 // in getParamPointer()).
68}
69
70InterpFrame::~InterpFrame() {
71 if (!Func)
72 return;
73
74 // De-initialize all argument blocks.
75 for (unsigned I = 0, N = Func->getNumWrittenParams(); I != N; ++I)
76 S.deallocate(B: argBlock(Index: I));
77
78 // When destroying the InterpFrame, call the Dtor for all blocks
79 // that haven't been destroyed via a destroy() op yet.
80 // This happens when the execution is interruped midway-through.
81 for (auto &Scope : Func->scopes()) {
82 for (auto &Local : Scope.locals()) {
83 Block *B = localBlock(Offset: Local.Offset);
84 if (B->isInitialized())
85 S.deallocate(B);
86 }
87 }
88}
89
90void InterpFrame::enableLocal(unsigned Offset) {
91 assert(Func);
92 getLocalBlock(Offset)->getBlockDesc<LocalInlineDescriptor>().IsEnabled = true;
93}
94
95void InterpFrame::destroy(unsigned Idx) {
96 for (auto &Local : Func->getScope(Idx).locals_reverse()) {
97 Block *B = localBlock(Offset: Local.Offset);
98 if (B->isInitialized())
99 S.deallocate(B);
100 }
101}
102
103template <typename T>
104static void print(llvm::raw_ostream &OS, const T &V, const Context &Ctx,
105 QualType Ty) {
106 if constexpr (std::is_same_v<Pointer, T>) {
107 if (Ty->isPointerOrReferenceType())
108 V.toAPValue(Ctx.getASTContext()).printPretty(OS, Ctx.getASTContext(), Ty);
109 else {
110 if (std::optional<APValue> RValue = V.toRValue(Ctx, Ty))
111 RValue->printPretty(OS, Ctx: Ctx.getASTContext(), Ty);
112 else
113 OS << "...";
114 }
115 } else {
116 V.toAPValue(Ctx.getASTContext()).printPretty(OS, Ctx.getASTContext(), Ty);
117 }
118}
119
120static bool shouldSkipInBacktrace(const Function *F) {
121 if (F->isLambdaStaticInvoker())
122 return true;
123
124 const FunctionDecl *FD = F->getDecl();
125 if (FD->getDeclName().getCXXOverloadedOperator() == OO_New ||
126 FD->getDeclName().getCXXOverloadedOperator() == OO_Array_New)
127 return true;
128
129 if (const auto *MD = dyn_cast<CXXMethodDecl>(Val: FD);
130 MD && MD->getParent()->isAnonymousStructOrUnion())
131 return true;
132
133 return false;
134}
135
136void InterpFrame::describe(llvm::raw_ostream &OS) const {
137 assert(Func);
138 // For lambda static invokers, we would just print __invoke().
139 if (shouldSkipInBacktrace(F: Func))
140 return;
141
142 const ASTContext &ASTCtx = S.getASTContext();
143 const Expr *CallExpr = Caller->getExpr(PC: getRetOpPC());
144 const FunctionDecl *F = Func->getDecl();
145 auto PrintingPolicy = ASTCtx.getPrintingPolicy();
146 PrintingPolicy.SuppressLambdaBody = true;
147
148 bool IsMemberCall = false;
149 bool ExplicitInstanceParam = false;
150 if (const auto *MD = dyn_cast<CXXMethodDecl>(Val: F)) {
151 IsMemberCall = !isa<CXXConstructorDecl>(Val: MD) && !MD->isStatic();
152 ExplicitInstanceParam = MD->isExplicitObjectMemberFunction();
153 }
154
155 if (Func->hasThisPointer() && IsMemberCall) {
156 if (const auto *MCE = dyn_cast_if_present<CXXMemberCallExpr>(Val: CallExpr)) {
157 const Expr *Object = MCE->getImplicitObjectArgument();
158 Object->printPretty(OS, /*Helper=*/nullptr,
159 Policy: PrintingPolicy,
160 /*Indentation=*/0);
161 if (Object->getType()->isPointerType())
162 OS << "->";
163 else
164 OS << '.';
165 } else if (const auto *OCE =
166 dyn_cast_if_present<CXXOperatorCallExpr>(Val: CallExpr)) {
167 OCE->getArg(Arg: 0)->printPretty(OS, /*Helper=*/nullptr,
168 Policy: PrintingPolicy,
169 /*Indentation=*/0);
170 OS << '.';
171 } else if (const auto *M = dyn_cast<CXXMethodDecl>(Val: F)) {
172 print(OS, V: getThis(), Ctx: S.getContext(),
173 Ty: ASTCtx.getLValueReferenceType(
174 T: ASTCtx.getCanonicalTagType(TD: M->getParent())));
175 OS << '.';
176 }
177 }
178
179 F->getNameForDiagnostic(OS, Policy: PrintingPolicy, /*Qualified=*/false);
180 OS << '(';
181 unsigned Off = 0;
182 unsigned ParamIndex = ExplicitInstanceParam;
183 Off += Func->hasRVO() ? primSize(Type: PT_Ptr) : 0;
184 Off += Func->hasThisPointer() ? primSize(Type: PT_Ptr) : 0;
185 llvm::ListSeparator Comma;
186 for (const ParmVarDecl *Param :
187 F->parameters().slice(N: ExplicitInstanceParam)) {
188 OS << Comma;
189 PrimType PrimT = Func->getParamDescriptor(Index: ParamIndex).T;
190 TYPE_SWITCH(PrimT,
191 print(OS, stackRef<T>(Off), S.getContext(), Param->getType()));
192 Off += align(Size: primSize(Type: PrimT));
193 ++ParamIndex;
194 }
195 OS << ')';
196}
197
198SourceRange InterpFrame::getCallRange() const {
199 if (!Caller->Func) {
200 if (SourceRange NullRange = S.getSource(PC: {}).getRange(); NullRange.isValid())
201 return NullRange;
202
203 return S.EvalLocation;
204 }
205
206 // Move up to the frame that has a valid location for the caller.
207 for (const InterpFrame *C = this; C; C = C->Caller) {
208 if (!C->RetPC)
209 continue;
210 SourceRange CallRange =
211 C->Caller->Func->getSource(PC: C->getRetOpPC()).getRange();
212 if (CallRange.isValid())
213 return CallRange;
214 }
215 return S.EvalLocation;
216}
217
218const FunctionDecl *InterpFrame::getCallee() const {
219 if (!Func)
220 return nullptr;
221 return Func->getDecl();
222}
223
224Pointer InterpFrame::getParamPointer(unsigned Index) {
225 assert(!isBottomFrame());
226
227 Block *B = argBlock(Index);
228
229 // Copy the initial value.
230 if (!B->isInitialized()) {
231 unsigned ByteOffset = Func->getParamDescriptor(Index).Offset;
232 assert(B->getDescriptor()->isPrimitive());
233 B->invokeCtor();
234 TYPE_SWITCH(B->getDescriptor()->getPrimType(),
235 new (B->data()) T(stackRef<T>(ByteOffset)));
236 assert(B->isInitialized());
237 }
238
239 return Pointer(B);
240}
241
242static bool funcHasUsableBody(const Function *F) {
243 assert(F);
244
245 if (F->isConstructor() || F->isDestructor())
246 return true;
247
248 return !F->getDecl()->isImplicit();
249}
250
251SourceInfo InterpFrame::getSource(CodePtr PC) const {
252 if (!Func)
253 return S.getSource(PC);
254
255 // Implicitly created functions don't have any code we could point at,
256 // so return the call site.
257 if (Func && !funcHasUsableBody(F: Func) && Caller)
258 return Caller->getSource(PC: getRetOpPC());
259
260 // If we have a frame for an invalid function, check the caller.
261 // This happens for the fake function frame we create in TrivialCopy.
262 if (Func && !Func->isValid())
263 return Caller->getSource(PC: getRetOpPC());
264
265 // Similarly, if the resulting source location is invalid anyway,
266 // point to the caller instead.
267 SourceInfo Result = Func->getSource(PC);
268 if (Result.getLoc().isInvalid() && Caller)
269 return Caller->getSource(PC: getRetOpPC());
270
271 return Result;
272}
273
274bool InterpFrame::isStdFunction() const {
275 if (!Func)
276 return false;
277 for (const DeclContext *DC = Func->getDecl(); DC; DC = DC->getParent())
278 if (DC->isStdNamespace())
279 return true;
280
281 return false;
282}
283