clang 23.0.0git
InterpFrame.cpp
Go to the documentation of this file.
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 "Function.h"
12#include "InterpStack.h"
13#include "InterpState.h"
14#include "MemberPointer.h"
15#include "Pointer.h"
16#include "PrimType.h"
17#include "Program.h"
19#include "clang/AST/DeclCXX.h"
20#include "clang/AST/ExprCXX.h"
21
22using namespace clang;
23using namespace clang::interp;
24
26 : Caller(nullptr), S(S), Depth(0), Func(nullptr), RetPC(CodePtr()),
27 ArgSize(0), Args(nullptr), FrameOffset(0) {}
28
30 InterpFrame *Caller, CodePtr RetPC, unsigned ArgSize)
31 : Caller(Caller), S(S), Depth(Caller ? Caller->Depth + 1 : 0), Func(Func),
32 RetPC(RetPC), ArgSize(ArgSize), Args(static_cast<char *>(S.Stk.top())),
33 FrameOffset(S.Stk.size()) {
34 if (!Func)
35 return;
36
37 unsigned FrameSize = Func->getFrameSize();
38 if (FrameSize == 0)
39 return;
40
41 Locals = std::make_unique<char[]>(FrameSize);
42 for (auto &Scope : Func->scopes()) {
43 for (auto &Local : Scope.locals()) {
44 new (localBlock(Local.Offset)) Block(S.Ctx.getEvalID(), Local.Desc);
45 // Note that we are NOT calling invokeCtor() here, since that is done
46 // via the InitScope op.
47 new (localInlineDesc(Local.Offset)) InlineDescriptor(Local.Desc);
48 }
49 }
50}
51
53 unsigned VarArgSize)
54 : InterpFrame(S, Func, S.Current, RetPC, Func->getArgSize() + VarArgSize) {
55 // As per our calling convention, the this pointer is
56 // part of the ArgSize.
57 // If the function has RVO, the RVO pointer is first.
58 // If the fuction has a This pointer, that one is next.
59 // Then follow the actual arguments (but those are handled
60 // in getParamPointer()).
61 if (Func->hasRVO()) {
62 // RVO pointer offset is always 0.
63 }
64
65 if (Func->hasThisPointer())
66 ThisPointerOffset = Func->hasRVO() ? sizeof(Pointer) : 0;
67}
68
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.
77}
78
80 if (!Func)
81 return;
82 for (auto &Scope : Func->scopes()) {
83 for (auto &Local : Scope.locals()) {
84 S.deallocate(localBlock(Local.Offset));
85 }
86 }
87}
88
89void InterpFrame::initScope(unsigned Idx) {
90 if (!Func)
91 return;
92
93 for (auto &Local : Func->getScope(Idx).locals()) {
94 localBlock(Local.Offset)->invokeCtor();
95 }
96}
97
98void InterpFrame::enableLocal(unsigned Idx) {
99 assert(Func);
100
101 // FIXME: This is a little dirty, but to avoid adding a flag to
102 // InlineDescriptor that's only ever useful on the toplevel of local
103 // variables, we reuse the IsActive flag for the enabled state. We should
104 // probably use a different struct than InlineDescriptor for the block-level
105 // inline descriptor of local varaibles.
106 localInlineDesc(Idx)->IsActive = true;
107}
108
109void InterpFrame::destroy(unsigned Idx) {
110 for (auto &Local : Func->getScope(Idx).locals_reverse()) {
111 S.deallocate(localBlock(Local.Offset));
112 }
113}
114
115template <typename T>
116static void print(llvm::raw_ostream &OS, const T &V, ASTContext &ASTCtx,
117 QualType Ty) {
118 if constexpr (std::is_same_v<Pointer, T>) {
119 if (Ty->isPointerOrReferenceType())
120 V.toAPValue(ASTCtx).printPretty(OS, ASTCtx, Ty);
121 else {
122 if (std::optional<APValue> RValue = V.toRValue(ASTCtx, Ty))
123 RValue->printPretty(OS, ASTCtx, Ty);
124 else
125 OS << "...";
126 }
127 } else {
128 V.toAPValue(ASTCtx).printPretty(OS, ASTCtx, Ty);
129 }
130}
131
132static bool shouldSkipInBacktrace(const Function *F) {
133 if (F->isLambdaStaticInvoker())
134 return true;
135
136 const FunctionDecl *FD = F->getDecl();
137 if (FD->getDeclName().getCXXOverloadedOperator() == OO_New ||
138 FD->getDeclName().getCXXOverloadedOperator() == OO_Array_New)
139 return true;
140
141 if (const auto *MD = dyn_cast<CXXMethodDecl>(FD);
142 MD && MD->getParent()->isAnonymousStructOrUnion())
143 return true;
144
145 if (const auto *Ctor = dyn_cast<CXXConstructorDecl>(FD);
146 Ctor && Ctor->isDefaulted() && Ctor->isTrivial() &&
147 Ctor->isCopyOrMoveConstructor() && Ctor->inits().empty())
148 return true;
149
150 return false;
151}
152
153void InterpFrame::describe(llvm::raw_ostream &OS) const {
154 assert(Func);
155 // For lambda static invokers, we would just print __invoke().
156 if (shouldSkipInBacktrace(Func))
157 return;
158
159 const Expr *CallExpr = Caller->getExpr(getRetPC());
160 const FunctionDecl *F = getCallee();
161
162 bool IsMemberCall = false;
163 bool ExplicitInstanceParam = false;
164 if (const auto *MD = dyn_cast<CXXMethodDecl>(F)) {
165 IsMemberCall = !isa<CXXConstructorDecl>(MD) && !MD->isStatic();
166 ExplicitInstanceParam = MD->isExplicitObjectMemberFunction();
167 }
168
169 if (Func->hasThisPointer() && IsMemberCall) {
170 if (const auto *MCE = dyn_cast_if_present<CXXMemberCallExpr>(CallExpr)) {
171 const Expr *Object = MCE->getImplicitObjectArgument();
172 Object->printPretty(OS, /*Helper=*/nullptr,
173 S.getASTContext().getPrintingPolicy(),
174 /*Indentation=*/0);
175 if (Object->getType()->isPointerType())
176 OS << "->";
177 else
178 OS << ".";
179 } else if (const auto *OCE =
180 dyn_cast_if_present<CXXOperatorCallExpr>(CallExpr)) {
181 OCE->getArg(0)->printPretty(OS, /*Helper=*/nullptr,
182 S.getASTContext().getPrintingPolicy(),
183 /*Indentation=*/0);
184 OS << ".";
185 } else if (const auto *M = dyn_cast<CXXMethodDecl>(F)) {
186 print(OS, getThis(), S.getASTContext(),
187 S.getASTContext().getLValueReferenceType(
188 S.getASTContext().getCanonicalTagType(M->getParent())));
189 OS << ".";
190 }
191 }
192
193 F->getNameForDiagnostic(OS, S.getASTContext().getPrintingPolicy(),
194 /*Qualified=*/false);
195 OS << '(';
196 unsigned Off = 0;
197
198 Off += Func->hasRVO() ? primSize(PT_Ptr) : 0;
199 Off += Func->hasThisPointer() ? primSize(PT_Ptr) : 0;
200 llvm::ListSeparator Comma;
201 for (const ParmVarDecl *Param :
202 F->parameters().slice(ExplicitInstanceParam)) {
203 OS << Comma;
204 QualType Ty = Param->getType();
205 PrimType PrimTy = S.Ctx.classify(Ty).value_or(PT_Ptr);
206
207 TYPE_SWITCH(PrimTy, print(OS, stackRef<T>(Off), S.getASTContext(), Ty));
208 Off += align(primSize(PrimTy));
209 }
210 OS << ")";
211}
212
214 if (!Caller->Func) {
215 if (SourceRange NullRange = S.getRange(nullptr, {}); NullRange.isValid())
216 return NullRange;
217 return S.EvalLocation;
218 }
219
220 // Move up to the frame that has a valid location for the caller.
221 for (const InterpFrame *C = this; C; C = C->Caller) {
222 if (!C->RetPC)
223 continue;
224 SourceRange CallRange =
225 S.getRange(C->Caller->Func, C->RetPC - sizeof(uintptr_t));
226 if (CallRange.isValid())
227 return CallRange;
228 }
229 return S.EvalLocation;
230}
231
233 if (!Func)
234 return nullptr;
235 return Func->getDecl();
236}
237
238Pointer InterpFrame::getLocalPointer(unsigned Offset) const {
239 assert(Offset < Func->getFrameSize() && "Invalid local offset.");
240 return Pointer(localBlock(Offset));
241}
242
243Block *InterpFrame::getLocalBlock(unsigned Offset) const {
244 return localBlock(Offset);
245}
246
248 // Return the block if it was created previously.
249 if (auto Pt = Params.find(Off); Pt != Params.end())
250 return Pointer(reinterpret_cast<Block *>(Pt->second.get()));
251
252 assert(!isBottomFrame());
253
254 // Allocate memory to store the parameter and the block metadata.
255 const auto &Desc = Func->getParamDescriptor(Off);
256 size_t BlockSize = sizeof(Block) + Desc.second->getAllocSize();
257 auto Memory = std::make_unique<char[]>(BlockSize);
258 auto *B = new (Memory.get()) Block(S.Ctx.getEvalID(), Desc.second);
259 B->invokeCtor();
260
261 // Copy the initial value.
262 TYPE_SWITCH(Desc.first, new (B->data()) T(stackRef<T>(Off)));
263
264 // Record the param.
265 Params.insert({Off, std::move(Memory)});
266 return Pointer(B);
267}
268
269static bool funcHasUsableBody(const Function *F) {
270 assert(F);
271
272 if (F->isConstructor() || F->isDestructor())
273 return true;
274
275 return !F->getDecl()->isImplicit();
276}
277
279 // Implicitly created functions don't have any code we could point at,
280 // so return the call site.
281 if (Func && !funcHasUsableBody(Func) && Caller)
282 return Caller->getSource(RetPC);
283
284 // Similarly, if the resulting source location is invalid anyway,
285 // point to the caller instead.
286 SourceInfo Result = S.getSource(Func, PC);
287 if (Result.getLoc().isInvalid() && Caller)
288 return Caller->getSource(RetPC);
289 return Result;
290}
291
293 if (Func && !funcHasUsableBody(Func) && Caller)
294 return Caller->getExpr(RetPC);
295
296 return S.getExpr(Func, PC);
297}
298
300 if (Func && !funcHasUsableBody(Func) && Caller)
301 return Caller->getLocation(RetPC);
302
303 return S.getLocation(Func, PC);
304}
305
307 if (Func && !funcHasUsableBody(Func) && Caller)
308 return Caller->getRange(RetPC);
309
310 return S.getRange(Func, PC);
311}
312
314 if (!Func)
315 return false;
316 for (const DeclContext *DC = Func->getDecl(); DC; DC = DC->getParent())
317 if (DC->isStdNamespace())
318 return true;
319
320 return false;
321}
Defines the clang::ASTContext interface.
#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 void print(llvm::raw_ostream &OS, const T &V, ASTContext &ASTCtx, QualType Ty)
static bool shouldSkipInBacktrace(const Function *F)
static bool funcHasUsableBody(const Function *F)
#define TYPE_SWITCH(Expr, B)
Definition PrimType.h:211
Holds long-lived AST nodes (such as types and decls) that can be referred to throughout the semantic ...
Definition ASTContext.h:220
CallExpr - Represents a function call (C99 6.5.2.2, C++ [expr.call]).
Definition Expr.h:2943
DeclContext - This is used only as base class of specific decl types that can act as declaration cont...
Definition DeclBase.h:1449
DeclContext * getParent()
getParent - Returns the containing DeclContext.
Definition DeclBase.h:2109
OverloadedOperatorKind getCXXOverloadedOperator() const
If this name is the name of an overloadable operator in C++ (e.g., operator+), retrieve the kind of o...
This represents one expression.
Definition Expr.h:112
Represents a function declaration or definition.
Definition Decl.h:2000
ArrayRef< ParmVarDecl * > parameters() const
Definition Decl.h:2774
void getNameForDiagnostic(raw_ostream &OS, const PrintingPolicy &Policy, bool Qualified) const override
Appends a human-readable name for this declaration into the given stream.
Definition Decl.cpp:3125
DeclarationName getDeclName() const
Get the actual, stored name of the declaration, which may be a special name.
Definition Decl.h:340
Represents a parameter to a function.
Definition Decl.h:1790
A (possibly-)qualified type.
Definition TypeBase.h:937
Encodes a location in the source.
A trivial tuple used to represent a source range.
bool isPointerOrReferenceType() const
Definition TypeBase.h:8533
A memory block, either on the stack or in the heap.
Definition InterpBlock.h:44
Pointer into the code segment.
Definition Source.h:30
Bytecode function.
Definition Function.h:88
InterpFrame(InterpState &S)
Bottom Frame.
const Expr * getExpr(CodePtr PC) const
InterpFrame * Caller
The frame of the previous function.
Definition InterpFrame.h:30
SourceInfo getSource(CodePtr PC) const
Map a location to a source.
CodePtr getRetPC() const
Returns the return address of the frame.
void enableLocal(unsigned Idx)
Block * getLocalBlock(unsigned Offset) const
SourceLocation getLocation(CodePtr PC) const
~InterpFrame()
Destroys the frame, killing all live pointers to stack slots.
const Pointer & getThis() const
Returns the 'this' pointer.
SourceRange getRange(CodePtr PC) const
Pointer getLocalPointer(unsigned Offset) const
Returns a pointer to a local variables.
void destroy(unsigned Idx)
Invokes the destructors for a scope.
Pointer getParamPointer(unsigned Offset)
Returns a pointer to an argument - lazily creates a block.
const FunctionDecl * getCallee() const override
Returns the caller.
void initScope(unsigned Idx)
SourceRange getCallRange() const override
Returns the location of the call to the frame.
void describe(llvm::raw_ostream &OS) const override
Describes the frame with arguments for diagnostic purposes.
Interpreter context.
Definition InterpState.h:36
A pointer to a memory block, live or dead.
Definition Pointer.h:93
Describes a scope block.
Definition Function.h:36
llvm::iterator_range< LocalVectorTy::const_iterator > locals() const
Definition Function.h:52
Describes the statement/declaration an opcode was generated from.
Definition Source.h:74
constexpr size_t align(size_t Size)
Aligns a size to the pointer alignment.
Definition PrimType.h:189
PrimType
Enumeration of the primitive types of the VM.
Definition PrimType.h:34
size_t primSize(PrimType Type)
Returns the size of a primitive type in bytes.
Definition PrimType.cpp:23
The JSON file list parser is used to communicate input to InstallAPI.
bool isa(CodeGen::Address addr)
Definition Address.h:330
if(T->getSizeExpr()) TRY_TO(TraverseStmt(const_cast< Expr * >(T -> getSizeExpr())))
nullptr
This class represents a compute construct, representing a 'Kind' of ‘parallel’, 'serial',...
@ Result
The result type of a method or function.
Definition TypeBase.h:905
const FunctionProtoType * T
__UINTPTR_TYPE__ uintptr_t
An unsigned integer type with the property that any valid pointer to void can be converted to this ty...
Inline descriptor embedded in structures and arrays.
Definition Descriptor.h:66