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
22using namespace clang;
23using namespace clang::interp;
24
26 InterpFrame *Caller, CodePtr RetPC, unsigned ArgSize)
27 : Caller(Caller), S(S), Depth(Caller ? Caller->Depth + 1 : 0), Func(Func),
28 RetPC(RetPC), ArgSize(ArgSize), Args(static_cast<char *>(S.Stk.top())),
29 FrameOffset(S.Stk.size()) {
30 if (!Func)
31 return;
32
33 unsigned FrameSize = Func->getFrameSize();
34 if (FrameSize == 0)
35 return;
36
37 Locals = std::make_unique<char[]>(FrameSize);
38 for (auto &Scope : Func->scopes()) {
39 for (auto &Local : Scope.locals()) {
40 Block *B =
41 new (localBlock(Local.Offset)) Block(S.Ctx.getEvalID(), Local.Desc);
42 B->invokeCtor();
43 new (localInlineDesc(Local.Offset)) InlineDescriptor(Local.Desc);
44 }
45 }
46}
47
49 unsigned VarArgSize)
50 : InterpFrame(S, Func, S.Current, RetPC, Func->getArgSize() + VarArgSize) {
51 // As per our calling convention, the this pointer is
52 // part of the ArgSize.
53 // If the function has RVO, the RVO pointer is first.
54 // If the fuction has a This pointer, that one is next.
55 // Then follow the actual arguments (but those are handled
56 // in getParamPointer()).
57 if (Func->hasRVO())
58 RVOPtr = stackRef<Pointer>(0);
59
60 if (Func->hasThisPointer()) {
61 if (Func->hasRVO())
62 This = stackRef<Pointer>(sizeof(Pointer));
63 else
64 This = stackRef<Pointer>(0);
65 }
66}
67
69 for (auto &Param : Params)
70 S.deallocate(reinterpret_cast<Block *>(Param.second.get()));
71
72 // When destroying the InterpFrame, call the Dtor for all block
73 // that haven't been destroyed via a destroy() op yet.
74 // This happens when the execution is interruped midway-through.
75 if (Func) {
76 for (auto &Scope : Func->scopes()) {
77 for (auto &Local : Scope.locals()) {
78 Block *B = localBlock(Local.Offset);
79 if (B->isInitialized())
80 B->invokeDtor();
81 }
82 }
83 }
84}
85
86void InterpFrame::destroy(unsigned Idx) {
87 for (auto &Local : Func->getScope(Idx).locals()) {
88 S.deallocate(localBlock(Local.Offset));
89 }
90}
91
93 for (PrimType Ty : Func->args_reverse())
94 TYPE_SWITCH(Ty, S.Stk.discard<T>());
95}
96
97template <typename T>
98static void print(llvm::raw_ostream &OS, const T &V, ASTContext &, QualType) {
99 OS << V;
100}
101
102template <>
103void print(llvm::raw_ostream &OS, const Pointer &P, ASTContext &Ctx,
104 QualType Ty) {
105 if (P.isZero()) {
106 OS << "nullptr";
107 return;
108 }
109
110 auto printDesc = [&OS, &Ctx](const Descriptor *Desc) {
111 if (const auto *D = Desc->asDecl()) {
112 // Subfields or named values.
113 if (const auto *VD = dyn_cast<ValueDecl>(D)) {
114 OS << *VD;
115 return;
116 }
117 // Base classes.
118 if (isa<RecordDecl>(D))
119 return;
120 }
121 // Temporary expression.
122 if (const auto *E = Desc->asExpr()) {
123 E->printPretty(OS, nullptr, Ctx.getPrintingPolicy());
124 return;
125 }
126 llvm_unreachable("Invalid descriptor type");
127 };
128
129 if (!Ty->isReferenceType())
130 OS << "&";
132 for (Pointer F = P; !F.isRoot(); ) {
133 Levels.push_back(F);
134 F = F.isArrayElement() ? F.getArray().expand() : F.getBase();
135 }
136
137 // Drop the first pointer since we print it unconditionally anyway.
138 if (!Levels.empty())
139 Levels.erase(Levels.begin());
140
141 printDesc(P.getDeclDesc());
142 for (const auto &It : Levels) {
143 if (It.inArray()) {
144 OS << "[" << It.expand().getIndex() << "]";
145 continue;
146 }
147 if (auto Index = It.getIndex()) {
148 OS << " + " << Index;
149 continue;
150 }
151 OS << ".";
152 printDesc(It.getFieldDesc());
153 }
154}
155
156void InterpFrame::describe(llvm::raw_ostream &OS) const {
157 // We create frames for builtin functions as well, but we can't reliably
158 // diagnose them. The 'in call to' diagnostics for them add no value to the
159 // user _and_ it doesn't generally work since the argument types don't always
160 // match the function prototype. Just ignore them.
161 // Similarly, for lambda static invokers, we would just print __invoke().
162 if (const auto *F = getFunction();
163 F && (F->isBuiltin() || F->isLambdaStaticInvoker()))
164 return;
165
166 const FunctionDecl *F = getCallee();
167 if (const auto *M = dyn_cast<CXXMethodDecl>(F);
168 M && M->isInstance() && !isa<CXXConstructorDecl>(F)) {
169 print(OS, This, S.getCtx(), S.getCtx().getRecordType(M->getParent()));
170 OS << "->";
171 }
172
174 /*Qualified=*/false);
175 OS << '(';
176 unsigned Off = 0;
177
178 Off += Func->hasRVO() ? primSize(PT_Ptr) : 0;
179 Off += Func->hasThisPointer() ? primSize(PT_Ptr) : 0;
180
181 for (unsigned I = 0, N = F->getNumParams(); I < N; ++I) {
182 QualType Ty = F->getParamDecl(I)->getType();
183
184 PrimType PrimTy = S.Ctx.classify(Ty).value_or(PT_Ptr);
185
186 TYPE_SWITCH(PrimTy, print(OS, stackRef<T>(Off), S.getCtx(), Ty));
187 Off += align(primSize(PrimTy));
188 if (I + 1 != N)
189 OS << ", ";
190 }
191 OS << ")";
192}
193
195 if (Caller->Caller)
196 return Caller;
197 return S.getSplitFrame();
198}
199
201 if (!Caller->Func) {
202 if (SourceRange NullRange = S.getRange(nullptr, {}); NullRange.isValid())
203 return NullRange;
204 return S.EvalLocation;
205 }
206 return S.getRange(Caller->Func, RetPC - sizeof(uintptr_t));
207}
208
210 if (!Func)
211 return nullptr;
212 return Func->getDecl();
213}
214
215Pointer InterpFrame::getLocalPointer(unsigned Offset) const {
216 assert(Offset < Func->getFrameSize() && "Invalid local offset.");
217 return Pointer(localBlock(Offset));
218}
219
221 // Return the block if it was created previously.
222 if (auto Pt = Params.find(Off); Pt != Params.end())
223 return Pointer(reinterpret_cast<Block *>(Pt->second.get()));
224
225 // Allocate memory to store the parameter and the block metadata.
226 const auto &Desc = Func->getParamDescriptor(Off);
227 size_t BlockSize = sizeof(Block) + Desc.second->getAllocSize();
228 auto Memory = std::make_unique<char[]>(BlockSize);
229 auto *B = new (Memory.get()) Block(S.Ctx.getEvalID(), Desc.second);
230 B->invokeCtor();
231
232 // Copy the initial value.
233 TYPE_SWITCH(Desc.first, new (B->data()) T(stackRef<T>(Off)));
234
235 // Record the param.
236 Params.insert({Off, std::move(Memory)});
237 return Pointer(B);
238}
239
241 // Implicitly created functions don't have any code we could point at,
242 // so return the call site.
243 if (Func && (!Func->hasBody() || Func->getDecl()->isImplicit()) && Caller)
244 return Caller->getSource(RetPC);
245
246 return S.getSource(Func, PC);
247}
248
250 if (Func && (!Func->hasBody() || Func->getDecl()->isImplicit()) && Caller)
251 return Caller->getExpr(RetPC);
252
253 return S.getExpr(Func, PC);
254}
255
257 if (Func && (!Func->hasBody() || Func->getDecl()->isImplicit()) && Caller)
258 return Caller->getLocation(RetPC);
259
260 return S.getLocation(Func, PC);
261}
262
264 if (Func && (!Func->hasBody() || Func->getDecl()->isImplicit()) && Caller)
265 return Caller->getRange(RetPC);
266
267 return S.getRange(Func, PC);
268}
Defines the clang::ASTContext interface.
#define V(N, I)
Definition: ASTContext.h:3338
StringRef P
const Decl * D
Expr * E
Defines the C++ Decl subclasses, other than those for templates (found in DeclTemplate....
static void print(llvm::raw_ostream &OS, const T &V, ASTContext &, QualType)
Definition: InterpFrame.cpp:98
#define TYPE_SWITCH(Expr, B)
Definition: PrimType.h:122
Holds long-lived AST nodes (such as types and decls) that can be referred to throughout the semantic ...
Definition: ASTContext.h:186
QualType getRecordType(const RecordDecl *Decl) const
const clang::PrintingPolicy & getPrintingPolicy() const
Definition: ASTContext.h:712
bool isImplicit() const
isImplicit - Indicates whether the declaration was implicitly generated by the implementation.
Definition: DeclBase.h:599
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:3680
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:8010
QualType getType() const
Definition: Decl.h:678
A memory block, either on the stack or in the heap.
Definition: InterpBlock.h:49
void invokeDtor()
Invokes the Destructor.
Definition: InterpBlock.h:120
void invokeCtor()
Invokes the constructor.
Definition: InterpBlock.h:110
bool isInitialized() const
Returns whether the data of this block has been initialized via invoking the Ctor func.
Definition: InterpBlock.h:83
Pointer into the code segment.
Definition: Source.h:30
std::optional< PrimType > classify(QualType T) const
Classifies a type.
Definition: Context.cpp:127
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:77
Scope & getScope(unsigned Idx)
Returns a specific scope.
Definition: Function.h:128
const FunctionDecl * getDecl() const
Returns the original FunctionDecl.
Definition: Function.h:92
bool hasBody() const
Checks if the function already has a body attached.
Definition: Function.h:174
bool hasThisPointer() const
Definition: Function.h:171
llvm::iterator_range< arg_reverse_iterator > args_reverse() const
Definition: Function.h:123
ParamDescriptor getParamDescriptor(unsigned Offset) const
Returns a parameter descriptor.
Definition: Function.cpp:30
llvm::iterator_range< llvm::SmallVector< Scope, 2 >::const_iterator > scopes() const
Range over the scope blocks.
Definition: Function.h:116
bool hasRVO() const
Checks if the first argument is a RVO pointer.
Definition: Function.h:110
Frame storing local variables.
Definition: InterpFrame.h:26
void popArgs()
Pops the arguments off the stack.
Definition: InterpFrame.cpp:92
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.
SourceLocation getLocation(CodePtr PC) const
~InterpFrame()
Destroys the frame, killing all live pointers to stack slots.
Definition: InterpFrame.cpp:68
const Function * getFunction() const
Returns the current function.
Definition: InterpFrame.h:64
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:25
void destroy(unsigned Idx)
Invokes the destructors for a scope.
Definition: InterpFrame.cpp:86
Pointer getParamPointer(unsigned Offset)
Returns a pointer to an argument - lazily creates a block.
const FunctionDecl * getCallee() const override
Returns the caller.
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:80
Describes a scope block.
Definition: Function.h:35
llvm::iterator_range< LocalVectorTy::const_iterator > locals() const
Definition: Function.h:49
Describes the statement/declaration an opcode was generated from.
Definition: Source.h:72
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:104
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:107
Inline descriptor embedded in structures and arrays.
Definition: Descriptor.h:69