xref: /llvm-project/clang/lib/AST/ByteCode/InterpFrame.cpp (revision 733a92d7bced7119986a93a1b4e1c760f92b9583)
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 
23 using namespace clang;
24 using namespace clang::interp;
25 
26 InterpFrame::InterpFrame(InterpState &S, const Function *Func,
27                          InterpFrame *Caller, CodePtr RetPC, unsigned ArgSize)
28     : Caller(Caller), S(S), Depth(Caller ? Caller->Depth + 1 : 0), Func(Func),
29       RetPC(RetPC), ArgSize(ArgSize), Args(static_cast<char *>(S.Stk.top())),
30       FrameOffset(S.Stk.size()) {
31   if (!Func)
32     return;
33 
34   unsigned FrameSize = Func->getFrameSize();
35   if (FrameSize == 0)
36     return;
37 
38   Locals = std::make_unique<char[]>(FrameSize);
39   for (auto &Scope : Func->scopes()) {
40     for (auto &Local : Scope.locals()) {
41       new (localBlock(Local.Offset)) Block(S.Ctx.getEvalID(), Local.Desc);
42       // Note that we are NOT calling invokeCtor() here, since that is done
43       // via the InitScope op.
44       new (localInlineDesc(Local.Offset)) InlineDescriptor(Local.Desc);
45     }
46   }
47 }
48 
49 InterpFrame::InterpFrame(InterpState &S, const Function *Func, CodePtr RetPC,
50                          unsigned VarArgSize)
51     : InterpFrame(S, Func, S.Current, RetPC, Func->getArgSize() + VarArgSize) {
52   // As per our calling convention, the this pointer is
53   // part of the ArgSize.
54   // If the function has RVO, the RVO pointer is first.
55   // If the fuction has a This pointer, that one is next.
56   // Then follow the actual arguments (but those are handled
57   // in getParamPointer()).
58   if (Func->hasRVO())
59     RVOPtr = stackRef<Pointer>(0);
60 
61   if (Func->hasThisPointer()) {
62     if (Func->hasRVO())
63       This = stackRef<Pointer>(sizeof(Pointer));
64     else
65       This = stackRef<Pointer>(0);
66   }
67 }
68 
69 InterpFrame::~InterpFrame() {
70   for (auto &Param : Params)
71     S.deallocate(reinterpret_cast<Block *>(Param.second.get()));
72 
73   // When destroying the InterpFrame, call the Dtor for all block
74   // that haven't been destroyed via a destroy() op yet.
75   // This happens when the execution is interruped midway-through.
76   if (Func) {
77     for (auto &Scope : Func->scopes()) {
78       for (auto &Local : Scope.locals()) {
79         S.deallocate(localBlock(Local.Offset));
80       }
81     }
82   }
83 }
84 
85 void InterpFrame::initScope(unsigned Idx) {
86   if (!Func)
87     return;
88   for (auto &Local : Func->getScope(Idx).locals()) {
89     localBlock(Local.Offset)->invokeCtor();
90   }
91 }
92 
93 void InterpFrame::destroy(unsigned Idx) {
94   for (auto &Local : Func->getScope(Idx).locals()) {
95     S.deallocate(localBlock(Local.Offset));
96   }
97 }
98 
99 void InterpFrame::popArgs() {
100   for (PrimType Ty : Func->args_reverse())
101     TYPE_SWITCH(Ty, S.Stk.discard<T>());
102 }
103 
104 template <typename T>
105 static void print(llvm::raw_ostream &OS, const T &V, ASTContext &ASTCtx,
106                   QualType Ty) {
107   V.toAPValue(ASTCtx).printPretty(OS, ASTCtx, Ty);
108 }
109 
110 void InterpFrame::describe(llvm::raw_ostream &OS) const {
111   // We create frames for builtin functions as well, but we can't reliably
112   // diagnose them. The 'in call to' diagnostics for them add no value to the
113   // user _and_ it doesn't generally work since the argument types don't always
114   // match the function prototype. Just ignore them.
115   // Similarly, for lambda static invokers, we would just print __invoke().
116   if (const auto *F = getFunction();
117       F && (F->isBuiltin() || F->isLambdaStaticInvoker()))
118     return;
119 
120   const Expr *CallExpr = Caller->getExpr(getRetPC());
121   const FunctionDecl *F = getCallee();
122   bool IsMemberCall = isa<CXXMethodDecl>(F) && !isa<CXXConstructorDecl>(F) &&
123                       cast<CXXMethodDecl>(F)->isImplicitObjectMemberFunction();
124   if (Func->hasThisPointer() && IsMemberCall) {
125     if (const auto *MCE = dyn_cast_if_present<CXXMemberCallExpr>(CallExpr)) {
126       const Expr *Object = MCE->getImplicitObjectArgument();
127       Object->printPretty(OS, /*Helper=*/nullptr,
128                           S.getASTContext().getPrintingPolicy(),
129                           /*Indentation=*/0);
130       if (Object->getType()->isPointerType())
131         OS << "->";
132       else
133         OS << ".";
134     } else if (const auto *OCE =
135                    dyn_cast_if_present<CXXOperatorCallExpr>(CallExpr)) {
136       OCE->getArg(0)->printPretty(OS, /*Helper=*/nullptr,
137                                   S.getASTContext().getPrintingPolicy(),
138                                   /*Indentation=*/0);
139       OS << ".";
140     } else if (const auto *M = dyn_cast<CXXMethodDecl>(F)) {
141       print(OS, This, S.getASTContext(),
142             S.getASTContext().getLValueReferenceType(
143                 S.getASTContext().getRecordType(M->getParent())));
144       OS << ".";
145     }
146   }
147 
148   F->getNameForDiagnostic(OS, S.getASTContext().getPrintingPolicy(),
149                           /*Qualified=*/false);
150   OS << '(';
151   unsigned Off = 0;
152 
153   Off += Func->hasRVO() ? primSize(PT_Ptr) : 0;
154   Off += Func->hasThisPointer() ? primSize(PT_Ptr) : 0;
155 
156   for (unsigned I = 0, N = F->getNumParams(); I < N; ++I) {
157     QualType Ty = F->getParamDecl(I)->getType();
158 
159     PrimType PrimTy = S.Ctx.classify(Ty).value_or(PT_Ptr);
160 
161     TYPE_SWITCH(PrimTy, print(OS, stackRef<T>(Off), S.getASTContext(), Ty));
162     Off += align(primSize(PrimTy));
163     if (I + 1 != N)
164       OS << ", ";
165   }
166   OS << ")";
167 }
168 
169 Frame *InterpFrame::getCaller() const {
170   if (Caller->Caller)
171     return Caller;
172   return S.getSplitFrame();
173 }
174 
175 SourceRange InterpFrame::getCallRange() const {
176   if (!Caller->Func) {
177     if (SourceRange NullRange = S.getRange(nullptr, {}); NullRange.isValid())
178       return NullRange;
179     return S.EvalLocation;
180   }
181   return S.getRange(Caller->Func, RetPC - sizeof(uintptr_t));
182 }
183 
184 const FunctionDecl *InterpFrame::getCallee() const {
185   if (!Func)
186     return nullptr;
187   return Func->getDecl();
188 }
189 
190 Pointer InterpFrame::getLocalPointer(unsigned Offset) const {
191   assert(Offset < Func->getFrameSize() && "Invalid local offset.");
192   return Pointer(localBlock(Offset));
193 }
194 
195 Pointer InterpFrame::getParamPointer(unsigned Off) {
196   // Return the block if it was created previously.
197   if (auto Pt = Params.find(Off); Pt != Params.end())
198     return Pointer(reinterpret_cast<Block *>(Pt->second.get()));
199 
200   // Allocate memory to store the parameter and the block metadata.
201   const auto &Desc = Func->getParamDescriptor(Off);
202   size_t BlockSize = sizeof(Block) + Desc.second->getAllocSize();
203   auto Memory = std::make_unique<char[]>(BlockSize);
204   auto *B = new (Memory.get()) Block(S.Ctx.getEvalID(), Desc.second);
205   B->invokeCtor();
206 
207   // Copy the initial value.
208   TYPE_SWITCH(Desc.first, new (B->data()) T(stackRef<T>(Off)));
209 
210   // Record the param.
211   Params.insert({Off, std::move(Memory)});
212   return Pointer(B);
213 }
214 
215 SourceInfo InterpFrame::getSource(CodePtr PC) const {
216   // Implicitly created functions don't have any code we could point at,
217   // so return the call site.
218   if (Func && (!Func->hasBody() || Func->getDecl()->isImplicit()) && Caller)
219     return Caller->getSource(RetPC);
220 
221   return S.getSource(Func, PC);
222 }
223 
224 const Expr *InterpFrame::getExpr(CodePtr PC) const {
225   if (Func && (!Func->hasBody() || Func->getDecl()->isImplicit()) && Caller)
226     return Caller->getExpr(RetPC);
227 
228   return S.getExpr(Func, PC);
229 }
230 
231 SourceLocation InterpFrame::getLocation(CodePtr PC) const {
232   if (Func && (!Func->hasBody() || Func->getDecl()->isImplicit()) && Caller)
233     return Caller->getLocation(RetPC);
234 
235   return S.getLocation(Func, PC);
236 }
237 
238 SourceRange InterpFrame::getRange(CodePtr PC) const {
239   if (Func && (!Func->hasBody() || Func->getDecl()->isImplicit()) && Caller)
240     return Caller->getRange(RetPC);
241 
242   return S.getRange(Func, PC);
243 }
244