clang 20.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 "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"
20#include "clang/AST/DeclCXX.h"
21#include "clang/AST/ExprCXX.h"
22
23using namespace clang;
24using namespace clang::interp;
25
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
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
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
85void 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
93void InterpFrame::destroy(unsigned Idx) {
94 for (auto &Local : Func->getScope(Idx).locals()) {
95 S.deallocate(localBlock(Local.Offset));
96 }
97}
98
100 for (PrimType Ty : Func->args_reverse())
101 TYPE_SWITCH(Ty, S.Stk.discard<T>());
102}
103
104template <typename T>
105static void print(llvm::raw_ostream &OS, const T &V, ASTContext &ASTCtx,
106 QualType Ty) {
107 V.toAPValue(ASTCtx).printPretty(OS, ASTCtx, Ty);
108}
109
110template <>
111void print(llvm::raw_ostream &OS, const Pointer &P, ASTContext &Ctx,
112 QualType Ty) {
113 if (P.isZero()) {
114 OS << "nullptr";
115 return;
116 }
117
118 auto printDesc = [&OS, &Ctx](const Descriptor *Desc) {
119 if (const auto *D = Desc->asDecl()) {
120 // Subfields or named values.
121 if (const auto *VD = dyn_cast<ValueDecl>(D)) {
122 OS << *VD;
123 return;
124 }
125 // Base classes.
126 if (isa<RecordDecl>(D))
127 return;
128 }
129 // Temporary expression.
130 if (const auto *E = Desc->asExpr()) {
131 E->printPretty(OS, nullptr, Ctx.getPrintingPolicy());
132 return;
133 }
134 llvm_unreachable("Invalid descriptor type");
135 };
136
137 if (!Ty->isReferenceType())
138 OS << "&";
140 for (Pointer F = P; !F.isRoot();) {
141 Levels.push_back(F);
142 F = F.isArrayElement() ? F.getArray().expand() : F.getBase();
143 }
144
145 // Drop the first pointer since we print it unconditionally anyway.
146 if (!Levels.empty())
147 Levels.erase(Levels.begin());
148
149 printDesc(P.getDeclDesc());
150 for (const auto &It : Levels) {
151 if (It.inArray()) {
152 OS << "[" << It.expand().getIndex() << "]";
153 continue;
154 }
155 if (auto Index = It.getIndex()) {
156 OS << " + " << Index;
157 continue;
158 }
159 OS << ".";
160 printDesc(It.getFieldDesc());
161 }
162}
163
164void InterpFrame::describe(llvm::raw_ostream &OS) const {
165 // We create frames for builtin functions as well, but we can't reliably
166 // diagnose them. The 'in call to' diagnostics for them add no value to the
167 // user _and_ it doesn't generally work since the argument types don't always
168 // match the function prototype. Just ignore them.
169 // Similarly, for lambda static invokers, we would just print __invoke().
170 if (const auto *F = getFunction();
171 F && (F->isBuiltin() || F->isLambdaStaticInvoker()))
172 return;
173
174 const Expr *CallExpr = Caller->getExpr(getRetPC());
175 const FunctionDecl *F = getCallee();
176 bool IsMemberCall = isa<CXXMethodDecl>(F) && !isa<CXXConstructorDecl>(F) &&
177 cast<CXXMethodDecl>(F)->isImplicitObjectMemberFunction();
178 if (Func->hasThisPointer() && IsMemberCall) {
179 if (const auto *MCE = dyn_cast_if_present<CXXMemberCallExpr>(CallExpr)) {
180 const Expr *Object = MCE->getImplicitObjectArgument();
181 Object->printPretty(OS, /*Helper=*/nullptr,
183 /*Indentation=*/0);
184 if (Object->getType()->isPointerType())
185 OS << "->";
186 else
187 OS << ".";
188 } else if (const auto *OCE =
189 dyn_cast_if_present<CXXOperatorCallExpr>(CallExpr)) {
190 OCE->getArg(0)->printPretty(OS, /*Helper=*/nullptr,
192 /*Indentation=*/0);
193 OS << ".";
194 } else if (const auto *M = dyn_cast<CXXMethodDecl>(F)) {
195 print(OS, This, S.getCtx(),
197 S.getCtx().getRecordType(M->getParent())));
198 OS << ".";
199 }
200 }
201
203 /*Qualified=*/false);
204 OS << '(';
205 unsigned Off = 0;
206
207 Off += Func->hasRVO() ? primSize(PT_Ptr) : 0;
208 Off += Func->hasThisPointer() ? primSize(PT_Ptr) : 0;
209
210 for (unsigned I = 0, N = F->getNumParams(); I < N; ++I) {
211 QualType Ty = F->getParamDecl(I)->getType();
212
213 PrimType PrimTy = S.Ctx.classify(Ty).value_or(PT_Ptr);
214
215 TYPE_SWITCH(PrimTy, print(OS, stackRef<T>(Off), S.getCtx(), Ty));
216 Off += align(primSize(PrimTy));
217 if (I + 1 != N)
218 OS << ", ";
219 }
220 OS << ")";
221}
222
224 if (Caller->Caller)
225 return Caller;
226 return S.getSplitFrame();
227}
228
230 if (!Caller->Func) {
231 if (SourceRange NullRange = S.getRange(nullptr, {}); NullRange.isValid())
232 return NullRange;
233 return S.EvalLocation;
234 }
235 return S.getRange(Caller->Func, RetPC - sizeof(uintptr_t));
236}
237
239 if (!Func)
240 return nullptr;
241 return Func->getDecl();
242}
243
244Pointer InterpFrame::getLocalPointer(unsigned Offset) const {
245 assert(Offset < Func->getFrameSize() && "Invalid local offset.");
246 return Pointer(localBlock(Offset));
247}
248
250 // Return the block if it was created previously.
251 if (auto Pt = Params.find(Off); Pt != Params.end())
252 return Pointer(reinterpret_cast<Block *>(Pt->second.get()));
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
270 // Implicitly created functions don't have any code we could point at,
271 // so return the call site.
272 if (Func && (!Func->hasBody() || Func->getDecl()->isImplicit()) && Caller)
273 return Caller->getSource(RetPC);
274
275 return S.getSource(Func, PC);
276}
277
279 if (Func && (!Func->hasBody() || Func->getDecl()->isImplicit()) && Caller)
280 return Caller->getExpr(RetPC);
281
282 return S.getExpr(Func, PC);
283}
284
286 if (Func && (!Func->hasBody() || Func->getDecl()->isImplicit()) && Caller)
287 return Caller->getLocation(RetPC);
288
289 return S.getLocation(Func, PC);
290}
291
293 if (Func && (!Func->hasBody() || Func->getDecl()->isImplicit()) && Caller)
294 return Caller->getRange(RetPC);
295
296 return S.getRange(Func, PC);
297}
Defines the clang::ASTContext interface.
#define V(N, I)
Definition: ASTContext.h:3341
StringRef P
const Decl * D
Expr * E
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)
#define TYPE_SWITCH(Expr, B)
Definition: PrimType.h:148
Holds long-lived AST nodes (such as types and decls) that can be referred to throughout the semantic ...
Definition: ASTContext.h:187
QualType getRecordType(const RecordDecl *Decl) const
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:713
CallExpr - Represents a function call (C99 6.5.2.2, C++ [expr.call]).
Definition: Expr.h:2830
bool isImplicit() const
isImplicit - Indicates whether the declaration was implicitly generated by the implementation.
Definition: DeclBase.h:600
This represents one expression.
Definition: Expr.h:110
Represents a function declaration or definition.
Definition: Decl.h:1932
const ParmVarDecl * getParamDecl(unsigned i) const
Definition: Decl.h:2669
unsigned getNumParams() const
Return the number of parameters this function must have based on its FunctionType.
Definition: Decl.cpp:3678
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:3069
A (possibly-)qualified type.
Definition: Type.h:941
Encodes a location in the source.
A trivial tuple used to represent a source range.
bool isValid() const
void printPretty(raw_ostream &OS, PrinterHelper *Helper, const PrintingPolicy &Policy, unsigned Indentation=0, StringRef NewlineSymbol="\n", const ASTContext *Context=nullptr) const
bool isReferenceType() const
Definition: Type.h:8021
QualType getType() const
Definition: Decl.h:678
A memory block, either on the stack or in the heap.
Definition: InterpBlock.h:49
void invokeCtor()
Invokes the constructor.
Definition: InterpBlock.h:110
Pointer into the code segment.
Definition: Source.h:30
std::optional< PrimType > classify(QualType T) const
Classifies a type.
Definition: Context.cpp:130
unsigned getEvalID() const
Definition: Context.h:112
Base class for stack frames, shared between VM and walker.
Definition: Frame.h:25
Bytecode function.
Definition: Function.h:81
Scope & getScope(unsigned Idx)
Returns a specific scope.
Definition: Function.h:134
const FunctionDecl * getDecl() const
Returns the original FunctionDecl.
Definition: Function.h:96
bool hasBody() const
Checks if the function already has a body attached.
Definition: Function.h:189
bool hasThisPointer() const
Definition: Function.h:186
llvm::iterator_range< arg_reverse_iterator > args_reverse() const
Definition: Function.h:129
ParamDescriptor getParamDescriptor(unsigned Offset) const
Returns a parameter descriptor.
Definition: Function.cpp:32
llvm::iterator_range< llvm::SmallVector< Scope, 2 >::const_iterator > scopes() const
Range over the scope blocks.
Definition: Function.h:122
bool hasRVO() const
Checks if the first argument is a RVO pointer.
Definition: Function.h:116
Frame storing local variables.
Definition: InterpFrame.h:26
void popArgs()
Pops the arguments off the stack.
Definition: InterpFrame.cpp:99
const Expr * getExpr(CodePtr PC) const
InterpFrame * Caller
The frame of the previous function.
Definition: InterpFrame.h:29
virtual SourceInfo getSource(CodePtr PC) const
Map a location to a source.
CodePtr getRetPC() const
Returns the return address of the frame.
Definition: InterpFrame.h:113
SourceLocation getLocation(CodePtr PC) const
~InterpFrame()
Destroys the frame, killing all live pointers to stack slots.
Definition: InterpFrame.cpp:69
const Function * getFunction() const
Returns the current function.
Definition: InterpFrame.h:65
SourceRange getRange(CodePtr PC) const
Pointer getLocalPointer(unsigned Offset) const
Returns a pointer to a local variables.
Frame * getCaller() const override
Returns the parent frame object.
InterpFrame(InterpState &S, const Function *Func, InterpFrame *Caller, CodePtr RetPC, unsigned ArgSize)
Creates a new frame for a method call.
Definition: InterpFrame.cpp:26
void destroy(unsigned Idx)
Invokes the destructors for a scope.
Definition: InterpFrame.cpp:93
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:85
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.
void discard()
Discards the top value from the stack.
Definition: InterpStack.h:56
Interpreter context.
Definition: InterpState.h:36
Context & Ctx
Interpreter Context.
Definition: InterpState.h:130
SourceInfo getSource(const Function *F, CodePtr PC) const override
Delegates source mapping to the mapper.
Definition: InterpState.h:94
InterpStack & Stk
Temporary stack.
Definition: InterpState.h:128
SourceLocation EvalLocation
Source location of the evaluating expression.
Definition: InterpState.h:134
void deallocate(Block *B)
Deallocates a pointer.
Definition: InterpState.cpp:60
ASTContext & getCtx() const override
Definition: InterpState.h:62
A pointer to a memory block, live or dead.
Definition: Pointer.h:82
Describes a scope block.
Definition: Function.h:36
llvm::iterator_range< LocalVectorTy::const_iterator > locals() const
Definition: Function.h:50
Describes the statement/declaration an opcode was generated from.
Definition: Source.h:77
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:126
PrimType
Enumeration of the primitive types of the VM.
Definition: PrimType.h:33
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.
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...
Describes a memory block created by an allocation site.
Definition: Descriptor.h:111
Inline descriptor embedded in structures and arrays.
Definition: Descriptor.h:69