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 "Floating.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 "Program.h"
19#include "clang/AST/ASTContext.h"
20#include "clang/AST/DeclCXX.h"
21#include "clang/AST/ExprCXX.h"
22
23using namespace clang;
24using namespace clang::interp;
25
26InterpFrame::InterpFrame(InterpState &S)
27 : Caller(nullptr), S(S), Depth(0), Func(nullptr), RetPC(CodePtr()),
28 ArgSize(0), Args(nullptr), FrameOffset(0), IsBottom(true) {}
29
30InterpFrame::InterpFrame(InterpState &S, const Function *Func,
31 InterpFrame *Caller, CodePtr RetPC, unsigned ArgSize)
32 : Caller(Caller), S(S), Depth(Caller ? Caller->Depth + 1 : 0), Func(Func),
33 RetPC(RetPC), ArgSize(ArgSize), Args(static_cast<char *>(S.Stk.top())),
34 FrameOffset(S.Stk.size()), IsBottom(!Caller) {
35 if (!Func)
36 return;
37
38 unsigned FrameSize = Func->getFrameSize();
39 if (FrameSize == 0)
40 return;
41
42 Locals = std::make_unique<char[]>(num: FrameSize);
43 for (auto &Scope : Func->scopes()) {
44 for (auto &Local : Scope.locals()) {
45 new (localBlock(Offset: Local.Offset)) Block(S.Ctx.getEvalID(), Local.Desc);
46 // Note that we are NOT calling invokeCtor() here, since that is done
47 // via the InitScope op.
48 new (localInlineDesc(Offset: Local.Offset)) InlineDescriptor(Local.Desc);
49 }
50 }
51}
52
53InterpFrame::InterpFrame(InterpState &S, const Function *Func, CodePtr RetPC,
54 unsigned VarArgSize)
55 : InterpFrame(S, Func, S.Current, RetPC, Func->getArgSize() + VarArgSize) {
56 // As per our calling convention, the this pointer is
57 // part of the ArgSize.
58 // If the function has RVO, the RVO pointer is first.
59 // If the fuction has a This pointer, that one is next.
60 // Then follow the actual arguments (but those are handled
61 // in getParamPointer()).
62 if (Func->hasRVO())
63 RVOPtr = stackRef<Pointer>(Offset: 0);
64
65 if (Func->hasThisPointer()) {
66 if (Func->hasRVO())
67 This = stackRef<Pointer>(Offset: sizeof(Pointer));
68 else
69 This = stackRef<Pointer>(Offset: 0);
70 }
71}
72
73InterpFrame::~InterpFrame() {
74 for (auto &Param : Params)
75 S.deallocate(B: reinterpret_cast<Block *>(Param.second.get()));
76
77 // When destroying the InterpFrame, call the Dtor for all block
78 // that haven't been destroyed via a destroy() op yet.
79 // This happens when the execution is interruped midway-through.
80 destroyScopes();
81}
82
83void InterpFrame::destroyScopes() {
84 if (!Func)
85 return;
86 for (auto &Scope : Func->scopes()) {
87 for (auto &Local : Scope.locals()) {
88 S.deallocate(B: localBlock(Offset: Local.Offset));
89 }
90 }
91}
92
93void InterpFrame::initScope(unsigned Idx) {
94 if (!Func)
95 return;
96 for (auto &Local : Func->getScope(Idx).locals()) {
97 localBlock(Offset: Local.Offset)->invokeCtor();
98 }
99}
100
101void InterpFrame::destroy(unsigned Idx) {
102 for (auto &Local : Func->getScope(Idx).locals_reverse()) {
103 S.deallocate(B: localBlock(Offset: Local.Offset));
104 }
105}
106
107template <typename T>
108static void print(llvm::raw_ostream &OS, const T &V, ASTContext &ASTCtx,
109 QualType Ty) {
110 if constexpr (std::is_same_v<Pointer, T>) {
111 if (Ty->isPointerOrReferenceType())
112 V.toAPValue(ASTCtx).printPretty(OS, ASTCtx, Ty);
113 else {
114 if (std::optional<APValue> RValue = V.toRValue(ASTCtx, Ty))
115 RValue->printPretty(OS, Ctx: ASTCtx, Ty);
116 else
117 OS << "...";
118 }
119 } else {
120 V.toAPValue(ASTCtx).printPretty(OS, ASTCtx, Ty);
121 }
122}
123
124static bool shouldSkipInBacktrace(const Function *F) {
125 if (F->isLambdaStaticInvoker())
126 return true;
127
128 const FunctionDecl *FD = F->getDecl();
129 if (FD->getDeclName().getCXXOverloadedOperator() == OO_New ||
130 FD->getDeclName().getCXXOverloadedOperator() == OO_Array_New)
131 return true;
132 return false;
133}
134
135void InterpFrame::describe(llvm::raw_ostream &OS) const {
136 // For lambda static invokers, we would just print __invoke().
137 if (const auto *F = getFunction(); F && shouldSkipInBacktrace(F))
138 return;
139
140 const Expr *CallExpr = Caller->getExpr(PC: getRetPC());
141 const FunctionDecl *F = getCallee();
142 bool IsMemberCall = isa<CXXMethodDecl>(Val: F) && !isa<CXXConstructorDecl>(Val: F) &&
143 cast<CXXMethodDecl>(Val: F)->isImplicitObjectMemberFunction();
144 if (Func->hasThisPointer() && IsMemberCall) {
145 if (const auto *MCE = dyn_cast_if_present<CXXMemberCallExpr>(Val: CallExpr)) {
146 const Expr *Object = MCE->getImplicitObjectArgument();
147 Object->printPretty(OS, /*Helper=*/nullptr,
148 S.getASTContext().getPrintingPolicy(),
149 /*Indentation=*/0);
150 if (Object->getType()->isPointerType())
151 OS << "->";
152 else
153 OS << ".";
154 } else if (const auto *OCE =
155 dyn_cast_if_present<CXXOperatorCallExpr>(Val: CallExpr)) {
156 OCE->getArg(0)->printPretty(OS, /*Helper=*/nullptr,
157 S.getASTContext().getPrintingPolicy(),
158 /*Indentation=*/0);
159 OS << ".";
160 } else if (const auto *M = dyn_cast<CXXMethodDecl>(Val: F)) {
161 print(OS, V: This, ASTCtx&: S.getASTContext(),
162 Ty: S.getASTContext().getLValueReferenceType(
163 T: S.getASTContext().getRecordType(M->getParent())));
164 OS << ".";
165 }
166 }
167
168 F->getNameForDiagnostic(OS, Policy: S.getASTContext().getPrintingPolicy(),
169 /*Qualified=*/false);
170 OS << '(';
171 unsigned Off = 0;
172
173 Off += Func->hasRVO() ? primSize(Type: PT_Ptr) : 0;
174 Off += Func->hasThisPointer() ? primSize(Type: PT_Ptr) : 0;
175
176 for (unsigned I = 0, N = F->getNumParams(); I < N; ++I) {
177 QualType Ty = F->getParamDecl(i: I)->getType();
178
179 PrimType PrimTy = S.Ctx.classify(T: Ty).value_or(u: PT_Ptr);
180
181 TYPE_SWITCH(PrimTy, print(OS, stackRef<T>(Off), S.getASTContext(), Ty));
182 Off += align(Size: primSize(Type: PrimTy));
183 if (I + 1 != N)
184 OS << ", ";
185 }
186 OS << ")";
187}
188
189Frame *InterpFrame::getCaller() const {
190 if (Caller->Caller)
191 return Caller;
192 return S.getSplitFrame();
193}
194
195SourceRange InterpFrame::getCallRange() const {
196 if (!Caller->Func) {
197 if (SourceRange NullRange = S.getRange(F: nullptr, PC: {}); NullRange.isValid())
198 return NullRange;
199 return S.EvalLocation;
200 }
201 return S.getRange(F: Caller->Func, PC: RetPC - sizeof(uintptr_t));
202}
203
204const FunctionDecl *InterpFrame::getCallee() const {
205 if (!Func)
206 return nullptr;
207 return Func->getDecl();
208}
209
210Pointer InterpFrame::getLocalPointer(unsigned Offset) const {
211 assert(Offset < Func->getFrameSize() && "Invalid local offset.");
212 return Pointer(localBlock(Offset));
213}
214
215Pointer InterpFrame::getParamPointer(unsigned Off) {
216 // Return the block if it was created previously.
217 if (auto Pt = Params.find(Val: Off); Pt != Params.end())
218 return Pointer(reinterpret_cast<Block *>(Pt->second.get()));
219
220 // Allocate memory to store the parameter and the block metadata.
221 const auto &Desc = Func->getParamDescriptor(Offset: Off);
222 size_t BlockSize = sizeof(Block) + Desc.second->getAllocSize();
223 auto Memory = std::make_unique<char[]>(num: BlockSize);
224 auto *B = new (Memory.get()) Block(S.Ctx.getEvalID(), Desc.second);
225 B->invokeCtor();
226
227 // Copy the initial value.
228 TYPE_SWITCH(Desc.first, new (B->data()) T(stackRef<T>(Off)));
229
230 // Record the param.
231 Params.insert(KV: {Off, std::move(Memory)});
232 return Pointer(B);
233}
234
235static bool funcHasUsableBody(const Function *F) {
236 assert(F);
237
238 if (F->isConstructor() || F->isDestructor())
239 return true;
240
241 return !F->getDecl()->isImplicit();
242}
243
244SourceInfo InterpFrame::getSource(CodePtr PC) const {
245 // Implicitly created functions don't have any code we could point at,
246 // so return the call site.
247 if (Func && !funcHasUsableBody(F: Func) && Caller)
248 return Caller->getSource(PC: RetPC);
249
250 // Similarly, if the resulting source location is invalid anyway,
251 // point to the caller instead.
252 SourceInfo Result = S.getSource(F: Func, PC);
253 if (Result.getLoc().isInvalid() && Caller)
254 return Caller->getSource(PC: RetPC);
255 return Result;
256}
257
258const Expr *InterpFrame::getExpr(CodePtr PC) const {
259 if (Func && !funcHasUsableBody(F: Func) && Caller)
260 return Caller->getExpr(PC: RetPC);
261
262 return S.getExpr(F: Func, PC);
263}
264
265SourceLocation InterpFrame::getLocation(CodePtr PC) const {
266 if (Func && !funcHasUsableBody(F: Func) && Caller)
267 return Caller->getLocation(PC: RetPC);
268
269 return S.getLocation(F: Func, PC);
270}
271
272SourceRange InterpFrame::getRange(CodePtr PC) const {
273 if (Func && !funcHasUsableBody(F: Func) && Caller)
274 return Caller->getRange(PC: RetPC);
275
276 return S.getRange(F: Func, PC);
277}
278
279bool InterpFrame::isStdFunction() const {
280 if (!Func)
281 return false;
282 for (const DeclContext *DC = Func->getDecl(); DC; DC = DC->getParent())
283 if (DC->isStdNamespace())
284 return true;
285
286 return false;
287}
288

source code of clang/lib/AST/ByteCode/InterpFrame.cpp