clang 22.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 // For lambda static invokers, we would just print __invoke().
155 if (const auto *F = getFunction(); F && shouldSkipInBacktrace(F))
156 return;
157
158 const Expr *CallExpr = Caller->getExpr(getRetPC());
159 const FunctionDecl *F = getCallee();
160 bool IsMemberCall = isa<CXXMethodDecl>(F) && !isa<CXXConstructorDecl>(F) &&
161 cast<CXXMethodDecl>(F)->isImplicitObjectMemberFunction();
162 if (Func->hasThisPointer() && IsMemberCall) {
163 if (const auto *MCE = dyn_cast_if_present<CXXMemberCallExpr>(CallExpr)) {
164 const Expr *Object = MCE->getImplicitObjectArgument();
165 Object->printPretty(OS, /*Helper=*/nullptr,
166 S.getASTContext().getPrintingPolicy(),
167 /*Indentation=*/0);
168 if (Object->getType()->isPointerType())
169 OS << "->";
170 else
171 OS << ".";
172 } else if (const auto *OCE =
173 dyn_cast_if_present<CXXOperatorCallExpr>(CallExpr)) {
174 OCE->getArg(0)->printPretty(OS, /*Helper=*/nullptr,
175 S.getASTContext().getPrintingPolicy(),
176 /*Indentation=*/0);
177 OS << ".";
178 } else if (const auto *M = dyn_cast<CXXMethodDecl>(F)) {
179 print(OS, getThis(), S.getASTContext(),
180 S.getASTContext().getLValueReferenceType(
181 S.getASTContext().getCanonicalTagType(M->getParent())));
182 OS << ".";
183 }
184 }
185
186 F->getNameForDiagnostic(OS, S.getASTContext().getPrintingPolicy(),
187 /*Qualified=*/false);
188 OS << '(';
189 unsigned Off = 0;
190
191 Off += Func->hasRVO() ? primSize(PT_Ptr) : 0;
192 Off += Func->hasThisPointer() ? primSize(PT_Ptr) : 0;
193
194 for (unsigned I = 0, N = F->getNumParams(); I < N; ++I) {
195 QualType Ty = F->getParamDecl(I)->getType();
196
197 PrimType PrimTy = S.Ctx.classify(Ty).value_or(PT_Ptr);
198
199 TYPE_SWITCH(PrimTy, print(OS, stackRef<T>(Off), S.getASTContext(), Ty));
200 Off += align(primSize(PrimTy));
201 if (I + 1 != N)
202 OS << ", ";
203 }
204 OS << ")";
205}
206
208 if (!Caller->Func) {
209 if (SourceRange NullRange = S.getRange(nullptr, {}); NullRange.isValid())
210 return NullRange;
211 return S.EvalLocation;
212 }
213
214 // Move up to the frame that has a valid location for the caller.
215 for (const InterpFrame *C = this; C; C = C->Caller) {
216 if (!C->RetPC)
217 continue;
218 SourceRange CallRange =
219 S.getRange(C->Caller->Func, C->RetPC - sizeof(uintptr_t));
220 if (CallRange.isValid())
221 return CallRange;
222 }
223 return S.EvalLocation;
224}
225
227 if (!Func)
228 return nullptr;
229 return Func->getDecl();
230}
231
232Pointer InterpFrame::getLocalPointer(unsigned Offset) const {
233 assert(Offset < Func->getFrameSize() && "Invalid local offset.");
234 return Pointer(localBlock(Offset));
235}
236
237Block *InterpFrame::getLocalBlock(unsigned Offset) const {
238 return localBlock(Offset);
239}
240
242 // Return the block if it was created previously.
243 if (auto Pt = Params.find(Off); Pt != Params.end())
244 return Pointer(reinterpret_cast<Block *>(Pt->second.get()));
245
246 assert(!isBottomFrame());
247
248 // Allocate memory to store the parameter and the block metadata.
249 const auto &Desc = Func->getParamDescriptor(Off);
250 size_t BlockSize = sizeof(Block) + Desc.second->getAllocSize();
251 auto Memory = std::make_unique<char[]>(BlockSize);
252 auto *B = new (Memory.get()) Block(S.Ctx.getEvalID(), Desc.second);
253 B->invokeCtor();
254
255 // Copy the initial value.
256 TYPE_SWITCH(Desc.first, new (B->data()) T(stackRef<T>(Off)));
257
258 // Record the param.
259 Params.insert({Off, std::move(Memory)});
260 return Pointer(B);
261}
262
263static bool funcHasUsableBody(const Function *F) {
264 assert(F);
265
266 if (F->isConstructor() || F->isDestructor())
267 return true;
268
269 return !F->getDecl()->isImplicit();
270}
271
273 // Implicitly created functions don't have any code we could point at,
274 // so return the call site.
275 if (Func && !funcHasUsableBody(Func) && Caller)
276 return Caller->getSource(RetPC);
277
278 // Similarly, if the resulting source location is invalid anyway,
279 // point to the caller instead.
280 SourceInfo Result = S.getSource(Func, PC);
281 if (Result.getLoc().isInvalid() && Caller)
282 return Caller->getSource(RetPC);
283 return Result;
284}
285
287 if (Func && !funcHasUsableBody(Func) && Caller)
288 return Caller->getExpr(RetPC);
289
290 return S.getExpr(Func, PC);
291}
292
294 if (Func && !funcHasUsableBody(Func) && Caller)
295 return Caller->getLocation(RetPC);
296
297 return S.getLocation(Func, PC);
298}
299
301 if (Func && !funcHasUsableBody(Func) && Caller)
302 return Caller->getRange(RetPC);
303
304 return S.getRange(Func, PC);
305}
306
308 if (!Func)
309 return false;
310 for (const DeclContext *DC = Func->getDecl(); DC; DC = DC->getParent())
311 if (DC->isStdNamespace())
312 return true;
313
314 return false;
315}
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:2877
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
const ParmVarDecl * getParamDecl(unsigned i) const
Definition Decl.h:2797
unsigned getNumParams() const
Return the number of parameters this function must have based on its FunctionType.
Definition Decl.cpp:3822
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:3121
DeclarationName getDeclName() const
Get the actual, stored name of the declaration, which may be a special name.
Definition Decl.h:340
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:8519
QualType getType() const
Definition Decl.h:723
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.
const Function * getFunction() const
Returns the current function.
Definition InterpFrame.h:76
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:43
A pointer to a memory block, live or dead.
Definition Pointer.h:92
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
U cast(CodeGen::Address addr)
Definition Address.h:327
__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:67