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), IsBottom(true) {}
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()), IsBottom(!Caller) {
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 RVOPtr = stackRef<Pointer>(0);
63
64 if (Func->hasThisPointer()) {
65 if (Func->hasRVO())
66 This = stackRef<Pointer>(sizeof(Pointer));
67 else
68 This = stackRef<Pointer>(0);
69 }
70}
71
73 for (auto &Param : Params)
74 S.deallocate(reinterpret_cast<Block *>(Param.second.get()));
75
76 // When destroying the InterpFrame, call the Dtor for all block
77 // that haven't been destroyed via a destroy() op yet.
78 // This happens when the execution is interruped midway-through.
80}
81
83 if (!Func)
84 return;
85 for (auto &Scope : Func->scopes()) {
86 for (auto &Local : Scope.locals()) {
87 S.deallocate(localBlock(Local.Offset));
88 }
89 }
90}
91
92void InterpFrame::initScope(unsigned Idx) {
93 if (!Func)
94 return;
95 for (auto &Local : Func->getScope(Idx).locals()) {
96 localBlock(Local.Offset)->invokeCtor();
97 }
98}
99
100void InterpFrame::destroy(unsigned Idx) {
101 for (auto &Local : Func->getScope(Idx).locals_reverse()) {
102 S.deallocate(localBlock(Local.Offset));
103 }
104}
105
106template <typename T>
107static void print(llvm::raw_ostream &OS, const T &V, ASTContext &ASTCtx,
108 QualType Ty) {
109 if constexpr (std::is_same_v<Pointer, T>) {
110 if (Ty->isPointerOrReferenceType())
111 V.toAPValue(ASTCtx).printPretty(OS, ASTCtx, Ty);
112 else {
113 if (std::optional<APValue> RValue = V.toRValue(ASTCtx, Ty))
114 RValue->printPretty(OS, ASTCtx, Ty);
115 else
116 OS << "...";
117 }
118 } else {
119 V.toAPValue(ASTCtx).printPretty(OS, ASTCtx, Ty);
120 }
121}
122
123static bool shouldSkipInBacktrace(const Function *F) {
124 if (F->isLambdaStaticInvoker())
125 return true;
126
127 const FunctionDecl *FD = F->getDecl();
128 if (FD->getDeclName().getCXXOverloadedOperator() == OO_New ||
129 FD->getDeclName().getCXXOverloadedOperator() == OO_Array_New)
130 return true;
131
132 if (const auto *MD = dyn_cast<CXXMethodDecl>(FD);
133 MD && MD->getParent()->isAnonymousStructOrUnion())
134 return true;
135
136 if (const auto *Ctor = dyn_cast<CXXConstructorDecl>(FD);
137 Ctor && Ctor->isDefaulted() && Ctor->isTrivial() &&
138 Ctor->isCopyOrMoveConstructor() && Ctor->inits().empty())
139 return true;
140
141 return false;
142}
143
144void InterpFrame::describe(llvm::raw_ostream &OS) const {
145 // For lambda static invokers, we would just print __invoke().
146 if (const auto *F = getFunction(); F && shouldSkipInBacktrace(F))
147 return;
148
149 const Expr *CallExpr = Caller->getExpr(getRetPC());
150 const FunctionDecl *F = getCallee();
151 bool IsMemberCall = isa<CXXMethodDecl>(F) && !isa<CXXConstructorDecl>(F) &&
152 cast<CXXMethodDecl>(F)->isImplicitObjectMemberFunction();
153 if (Func->hasThisPointer() && IsMemberCall) {
154 if (const auto *MCE = dyn_cast_if_present<CXXMemberCallExpr>(CallExpr)) {
155 const Expr *Object = MCE->getImplicitObjectArgument();
156 Object->printPretty(OS, /*Helper=*/nullptr,
158 /*Indentation=*/0);
159 if (Object->getType()->isPointerType())
160 OS << "->";
161 else
162 OS << ".";
163 } else if (const auto *OCE =
164 dyn_cast_if_present<CXXOperatorCallExpr>(CallExpr)) {
165 OCE->getArg(0)->printPretty(OS, /*Helper=*/nullptr,
167 /*Indentation=*/0);
168 OS << ".";
169 } else if (const auto *M = dyn_cast<CXXMethodDecl>(F)) {
170 print(OS, This, S.getASTContext(),
172 S.getASTContext().getCanonicalTagType(M->getParent())));
173 OS << ".";
174 }
175 }
176
178 /*Qualified=*/false);
179 OS << '(';
180 unsigned Off = 0;
181
182 Off += Func->hasRVO() ? primSize(PT_Ptr) : 0;
183 Off += Func->hasThisPointer() ? primSize(PT_Ptr) : 0;
184
185 for (unsigned I = 0, N = F->getNumParams(); I < N; ++I) {
186 QualType Ty = F->getParamDecl(I)->getType();
187
188 PrimType PrimTy = S.Ctx.classify(Ty).value_or(PT_Ptr);
189
190 TYPE_SWITCH(PrimTy, print(OS, stackRef<T>(Off), S.getASTContext(), Ty));
191 Off += align(primSize(PrimTy));
192 if (I + 1 != N)
193 OS << ", ";
194 }
195 OS << ")";
196}
197
199 if (!Caller->Func) {
200 if (SourceRange NullRange = S.getRange(nullptr, {}); NullRange.isValid())
201 return NullRange;
202 return S.EvalLocation;
203 }
204
205 // Move up to the frame that has a valid location for the caller.
206 for (const InterpFrame *C = this; C; C = C->Caller) {
207 if (!C->RetPC)
208 continue;
209 SourceRange CallRange =
210 S.getRange(C->Caller->Func, C->RetPC - sizeof(uintptr_t));
211 if (CallRange.isValid())
212 return CallRange;
213 }
214 return S.EvalLocation;
215}
216
218 if (!Func)
219 return nullptr;
220 return Func->getDecl();
221}
222
223Pointer InterpFrame::getLocalPointer(unsigned Offset) const {
224 assert(Offset < Func->getFrameSize() && "Invalid local offset.");
225 return Pointer(localBlock(Offset));
226}
227
228Block *InterpFrame::getLocalBlock(unsigned Offset) const {
229 return localBlock(Offset);
230}
231
233 // Return the block if it was created previously.
234 if (auto Pt = Params.find(Off); Pt != Params.end())
235 return Pointer(reinterpret_cast<Block *>(Pt->second.get()));
236
237 // Allocate memory to store the parameter and the block metadata.
238 const auto &Desc = Func->getParamDescriptor(Off);
239 size_t BlockSize = sizeof(Block) + Desc.second->getAllocSize();
240 auto Memory = std::make_unique<char[]>(BlockSize);
241 auto *B = new (Memory.get()) Block(S.Ctx.getEvalID(), Desc.second);
242 B->invokeCtor();
243
244 // Copy the initial value.
245 TYPE_SWITCH(Desc.first, new (B->data()) T(stackRef<T>(Off)));
246
247 // Record the param.
248 Params.insert({Off, std::move(Memory)});
249 return Pointer(B);
250}
251
252static bool funcHasUsableBody(const Function *F) {
253 assert(F);
254
255 if (F->isConstructor() || F->isDestructor())
256 return true;
257
258 return !F->getDecl()->isImplicit();
259}
260
262 // Implicitly created functions don't have any code we could point at,
263 // so return the call site.
264 if (Func && !funcHasUsableBody(Func) && Caller)
265 return Caller->getSource(RetPC);
266
267 // Similarly, if the resulting source location is invalid anyway,
268 // point to the caller instead.
269 SourceInfo Result = S.getSource(Func, PC);
270 if (Result.getLoc().isInvalid() && Caller)
271 return Caller->getSource(RetPC);
272 return Result;
273}
274
276 if (Func && !funcHasUsableBody(Func) && Caller)
277 return Caller->getExpr(RetPC);
278
279 return S.getExpr(Func, PC);
280}
281
283 if (Func && !funcHasUsableBody(Func) && Caller)
284 return Caller->getLocation(RetPC);
285
286 return S.getLocation(Func, PC);
287}
288
290 if (Func && !funcHasUsableBody(Func) && Caller)
291 return Caller->getRange(RetPC);
292
293 return S.getRange(Func, PC);
294}
295
297 if (!Func)
298 return false;
299 for (const DeclContext *DC = Func->getDecl(); DC; DC = DC->getParent())
300 if (DC->isStdNamespace())
301 return true;
302
303 return false;
304}
Defines the clang::ASTContext interface.
#define V(N, I)
Definition: ASTContext.h:3597
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:207
a trap message and trap category.
Holds long-lived AST nodes (such as types and decls) that can be referred to throughout the semantic ...
Definition: ASTContext.h:188
QualType getLValueReferenceType(QualType T, bool SpelledAsLValue=true) const
Return the uniqued reference to the type for an lvalue reference to the specified type.
const clang::PrintingPolicy & getPrintingPolicy() const
Definition: ASTContext.h:793
CanQualType getCanonicalTagType(const TagDecl *TD) const
CallExpr - Represents a function call (C99 6.5.2.2, C++ [expr.call]).
Definition: Expr.h:2879
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
bool isImplicit() const
isImplicit - Indicates whether the declaration was implicitly generated by the implementation.
Definition: DeclBase.h:593
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:1999
const ParmVarDecl * getParamDecl(unsigned i) const
Definition: Decl.h:2790
unsigned getNumParams() const
Return the number of parameters this function must have based on its FunctionType.
Definition: Decl.cpp:3763
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:3117
DeclarationName getDeclName() const
Get the actual, stored name of the declaration, which may be a special name.
Definition: Decl.h:339
A (possibly-)qualified type.
Definition: TypeBase.h:937
Encodes a location in the source.
A trivial tuple used to represent a source range.
bool isValid() const
bool isPointerOrReferenceType() const
Definition: TypeBase.h:8584
QualType getType() const
Definition: Decl.h:722
A memory block, either on the stack or in the heap.
Definition: InterpBlock.h:44
void invokeCtor()
Invokes the constructor.
Definition: InterpBlock.h:123
Pointer into the code segment.
Definition: Source.h:30
OptPrimType classify(QualType T) const
Classifies a type.
Definition: Context.cpp:310
unsigned getEvalID() const
Definition: Context.h:140
Bytecode function.
Definition: Function.h:86
Scope & getScope(unsigned Idx)
Returns a specific scope.
Definition: Function.h:147
bool isDestructor() const
Checks if the function is a destructor.
Definition: Function.h:164
bool isConstructor() const
Checks if the function is a constructor.
Definition: Function.h:162
const FunctionDecl * getDecl() const
Returns the original FunctionDecl.
Definition: Function.h:109
bool hasThisPointer() const
Definition: Function.h:193
bool isLambdaStaticInvoker() const
Returns whether this function is a lambda static invoker, which we generate custom byte code for.
Definition: Function.h:172
ParamDescriptor getParamDescriptor(unsigned Offset) const
Returns a parameter descriptor.
Definition: Function.cpp:57
llvm::iterator_range< llvm::SmallVector< Scope, 2 >::const_iterator > scopes() const
Range over the scope blocks.
Definition: Function.h:135
bool hasRVO() const
Checks if the first argument is a RVO pointer.
Definition: Function.h:129
Frame storing local variables.
Definition: InterpFrame.h:26
InterpFrame(InterpState &S)
Bottom Frame.
Definition: InterpFrame.cpp:25
const Expr * getExpr(CodePtr PC) const
InterpFrame * Caller
The frame of the previous function.
Definition: InterpFrame.h:29
SourceInfo getSource(CodePtr PC) const
Map a location to a source.
CodePtr getRetPC() const
Returns the return address of the frame.
Definition: InterpFrame.h:120
Block * getLocalBlock(unsigned Offset) const
SourceLocation getLocation(CodePtr PC) const
~InterpFrame()
Destroys the frame, killing all live pointers to stack slots.
Definition: InterpFrame.cpp:72
const Function * getFunction() const
Returns the current function.
Definition: InterpFrame.h:71
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)
Definition: InterpFrame.cpp:92
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
Context & Ctx
Interpreter Context.
Definition: InterpState.h:172
ASTContext & getASTContext() const override
Definition: InterpState.h:70
SourceInfo getSource(const Function *F, CodePtr PC) const override
Delegates source mapping to the mapper.
Definition: InterpState.h:106
SourceLocation EvalLocation
Source location of the evaluating expression.
Definition: InterpState.h:178
void deallocate(Block *B)
Deallocates a pointer.
Definition: InterpState.cpp:73
PrimType value_or(PrimType PT) const
Definition: PrimType.h:68
A pointer to a memory block, live or dead.
Definition: Pointer.h:90
Describes a scope block.
Definition: Function.h:36
llvm::iterator_range< LocalVectorTy::const_iterator > locals() const
Definition: Function.h:50
llvm::iterator_range< LocalVectorTy::const_reverse_iterator > locals_reverse() const
Definition: Function.h:55
Describes the statement/declaration an opcode was generated from.
Definition: Source.h:73
SourceLocation getLocation(const Function *F, CodePtr PC) const
Returns the location from which an opcode originates.
Definition: Source.cpp:47
SourceRange getRange(const Function *F, CodePtr PC) const
Definition: Source.cpp:51
const Expr * getExpr(const Function *F, CodePtr PC) const
Returns the expression if an opcode belongs to one, null otherwise.
Definition: Source.cpp:41
constexpr size_t align(size_t Size)
Aligns a size to the pointer alignment.
Definition: PrimType.h:185
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.
@ Result
The result type of a method or function.
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...
#define true
Definition: stdbool.h:25
Inline descriptor embedded in structures and arrays.
Definition: Descriptor.h:67