clang 24.0.0git
ByteCodeEmitter.cpp
Go to the documentation of this file.
1//===--- ByteCodeEmitter.cpp - Instruction emitter 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 "ByteCodeEmitter.h"
10#include "Context.h"
11#include "Floating.h"
12#include "IntegralAP.h"
13#include "Opcode.h"
14#include "Program.h"
15#include "clang/AST/ASTLambda.h"
16#include "clang/AST/Attr.h"
17#include "clang/AST/DeclCXX.h"
18#include <type_traits>
19
20using namespace clang;
21using namespace clang::interp;
22
24 Function *Func) {
25 assert(FuncDecl);
26 assert(Func);
27 assert(FuncDecl->isThisDeclarationADefinition());
28
29 Func->setDefined(true);
30 // Lambda static invokers are a special case that we emit custom code for.
31 bool IsEligibleForCompilation = Func->isLambdaStaticInvoker() ||
32 FuncDecl->isConstexpr() ||
33 FuncDecl->hasAttr<MSConstexprAttr>();
34
35 if (!IsEligibleForCompilation) {
36 Func->setIsFullyCompiled(true);
37 return;
38 }
39
40 // Set up lambda captures.
41 if (Func->isLambdaCallOperator()) {
42 // Set up lambda capture to closure record field mapping.
43 const CXXRecordDecl *ParentDecl = Func->getParentDecl();
44 const Record *R = P.getOrCreateRecord(ParentDecl);
45 assert(R);
46 llvm::DenseMap<const ValueDecl *, FieldDecl *> LC;
47 FieldDecl *LTC;
48
49 ParentDecl->getCaptureFields(LC, LTC);
50
51 for (const auto &Cap : LC) {
52 unsigned Offset = R->getField(Cap.second)->Offset;
53 this->LambdaCaptures[Cap.first] = {
54 Offset, Cap.second->getType()->isReferenceType()};
55 }
56 if (LTC) {
57 QualType CaptureType = R->getField(LTC)->Decl->getType();
58 this->LambdaThisCapture = {R->getField(LTC)->Offset,
59 CaptureType->isPointerOrReferenceType()};
60 }
61 }
62
63 bool IsValid = !FuncDecl->isInvalidDecl();
64 // Register parameters and their index.
65 for (unsigned ParamIndex = 0, N = Func->getNumWrittenParams();
66 ParamIndex != N; ++ParamIndex) {
67 const ParmVarDecl *PD = FuncDecl->getParamDecl(ParamIndex);
68 if (PD->isInvalidDecl())
69 IsValid = false;
70 this->Params.insert({PD, {ParamIndex, Ctx.canClassify(PD->getType())}});
71 }
72
73 // Compile the function body.
74 if (!visitFunc(FuncDecl)) {
75 Func->setIsFullyCompiled(true);
76 return;
77 }
78
79 // Create scopes from descriptors.
81 for (auto &DS : Descriptors) {
82 Scopes.emplace_back(std::move(DS));
83 }
84
85 // Set the function's code.
86 Func->setCode(FuncDecl, NextLocalOffset, std::move(Code), std::move(SrcMap),
87 std::move(Scopes), FuncDecl->hasBody(), IsValid);
88 Func->setIsFullyCompiled(true);
89}
90
92 NextLocalOffset += sizeof(Block);
93 unsigned Location = NextLocalOffset;
94 NextLocalOffset += align(Block::InlineDescMD + D->getAllocSize());
95 return {D, Location};
96}
97
99 const size_t Target = Code.size();
100 LabelOffsets.insert({Label, Target});
101
102 if (auto It = LabelRelocs.find(Label); It != LabelRelocs.end()) {
103 for (unsigned Reloc : It->second) {
104 using namespace llvm::support;
105
106 // Rewrite the operand of all jumps to this label.
107 void *Location = Code.data() + Reloc - align(sizeof(int32_t));
108 assert(aligned(Location));
109 const int32_t Offset = Target - static_cast<int64_t>(Reloc);
110 endian::write<int32_t, llvm::endianness::native>(Location, Offset);
111 }
112 LabelRelocs.erase(It);
113 }
114}
115
116int32_t ByteCodeEmitter::getOffset(LabelTy Label) {
117 // Compute the PC offset which the jump is relative to.
118 const int64_t Position =
119 Code.size() + align(sizeof(Opcode)) + align(sizeof(int32_t));
120 assert(aligned(Position));
121
122 // If target is known, compute jump offset.
123 if (auto It = LabelOffsets.find(Label); It != LabelOffsets.end())
124 return It->second - Position;
125
126 // Otherwise, record relocation and return dummy offset.
127 LabelRelocs[Label].push_back(Position);
128 return 0ull;
129}
130
131/// Helper to write bytecode and bail out if 32-bit offsets become invalid.
132template <typename T>
134 const T &Val, bool &Success) {
135 size_t ValPos = Code.size();
136 size_t Size;
137
138 if constexpr (std::is_pointer_v<T>)
139 Size = align(sizeof(uintptr_t));
140 else
141 Size = align(sizeof(T));
142
143 if (ValPos + Size > std::numeric_limits<unsigned>::max()) {
144 Success = false;
145 return;
146 }
147
148 // Access must be aligned!
149 assert(aligned(ValPos));
150 assert(aligned(ValPos + Size));
151 Code.resize_for_overwrite(ValPos + Size);
152
153 if constexpr (std::is_pointer_v<T>)
154 new (Code.data() + ValPos) uintptr_t(reinterpret_cast<uintptr_t>(Val));
155 else
156 new (Code.data() + ValPos) T(Val);
157}
158
159/// Emits a serializable value. These usually (potentially) contain
160/// heap-allocated memory and aren't trivially copyable.
161template <typename T>
163 bool &Success) {
164 size_t ValPos = Code.size();
165 size_t Size = align(Val.bytesToSerialize());
166
167 if (ValPos + Size > std::numeric_limits<unsigned>::max()) {
168 Success = false;
169 return;
170 }
171
172 // Access must be aligned!
173 assert(aligned(ValPos));
174 assert(aligned(ValPos + Size));
175 Code.resize_for_overwrite(ValPos + Size);
176
177 Val.serialize(Code.data() + ValPos);
178}
179
180template <>
182 const Floating &Val, bool &Success) {
183 emitSerialized(Code, Val, Success);
184}
185
186template <>
188 const IntegralAP<false> &Val, bool &Success) {
189 emitSerialized(Code, Val, Success);
190}
191
192template <>
194 const IntegralAP<true> &Val, bool &Success) {
195 emitSerialized(Code, Val, Success);
196}
197
198template <>
200 const FixedPoint &Val, bool &Success) {
201 emitSerialized(Code, Val, Success);
202}
203
204template <typename... Tys>
205bool ByteCodeEmitter::emitOp(Opcode Op, const Tys &...Args, SourceInfo SI) {
206 bool Success = true;
207
208 // The opcode is followed by arguments. The source info is
209 // attached to the address after the opcode.
210 emit(P, Code, Op, Success);
211
212 SI = LocOverride.value_or(SI);
213 if (SrcMap.empty() || SrcMap.back() != SI)
214 SrcMap.push(Code.size(), SI);
215
216 (..., emit(P, Code, Args, Success));
217 return Success;
218}
219
221 return emitJt(getOffset(Label), SI);
222}
223
225 return emitJf(getOffset(Label), SI);
226}
227
229 return emitJmp(getOffset(Label), SI);
230}
231
233 emitLabel(Label);
234 return true;
235}
236
237bool ByteCodeEmitter::speculate(const CallExpr *E, const LabelTy &EndLabel) {
238 const Expr *Arg = E->getArg(0);
239 PrimType T = Ctx.classify(Arg->getType()).value_or(PT_Ptr);
240 if (!this->emitBCP(getOffset(EndLabel), T, E))
241 return false;
242 if (!this->visit(Arg))
243 return false;
244 return true;
245}
246
247//===----------------------------------------------------------------------===//
248// Opcode emitters
249//===----------------------------------------------------------------------===//
250
251#define GET_LINK_IMPL
252#include "Opcodes.inc"
253#undef GET_LINK_IMPL
This file provides some common utility functions for processing Lambda related AST Constructs.
static void emitSerialized(llvm::SmallVectorImpl< std::byte > &Code, const T &Val, bool &Success)
Emits a serializable value.
static void emit(Program &P, llvm::SmallVectorImpl< std::byte > &Code, const T &Val, bool &Success)
Helper to write bytecode and bail out if 32-bit offsets become invalid.
Defines the C++ Decl subclasses, other than those for templates (found in DeclTemplate....
Represents a C++ struct/union/class.
Definition DeclCXX.h:258
void getCaptureFields(llvm::DenseMap< const ValueDecl *, FieldDecl * > &Captures, FieldDecl *&ThisCapture) const
For a closure type, retrieve the mapping from captured variables and this to the non-static data memb...
Definition DeclCXX.cpp:1792
CallExpr - Represents a function call (C99 6.5.2.2, C++ [expr.call]).
Definition Expr.h:2987
Expr * getArg(unsigned Arg)
getArg - Return the specified argument.
Definition Expr.h:3191
bool isInvalidDecl() const
Definition DeclBase.h:596
bool hasAttr() const
Definition DeclBase.h:585
This represents one expression.
Definition Expr.h:113
QualType getType() const
Definition Expr.h:145
Represents a member of a struct/union/class.
Definition Decl.h:3295
Represents a function declaration or definition.
Definition Decl.h:2059
const ParmVarDecl * getParamDecl(unsigned i) const
Definition Decl.h:2928
bool isThisDeclarationADefinition() const
Returns whether this specific declaration of the function is also a definition that does not contain ...
Definition Decl.h:2428
bool isConstexpr() const
Whether this is a (C++11) constexpr function or constexpr constructor.
Definition Decl.h:2597
bool hasBody(const FunctionDecl *&Definition) const
Returns true if the function has a body.
Definition Decl.cpp:3186
Represents a parameter to a function.
Definition Decl.h:1820
A (possibly-)qualified type.
Definition TypeBase.h:938
bool isPointerOrReferenceType() const
Definition TypeBase.h:8669
QualType getType() const
Definition Decl.h:724
A memory block, either on the stack or in the heap.
Definition InterpBlock.h:43
static constexpr uint8_t InlineDescMD
Definition InterpBlock.h:50
bool jump(const LabelTy &Label, SourceInfo SI)
void emitLabel(LabelTy Label)
Define a label.
Local createLocal(const Descriptor *D)
Callback for local registration.
ParamOffset LambdaThisCapture
Offset of the This parameter in a lambda record.
llvm::DenseMap< const ValueDecl *, ParamOffset > LambdaCaptures
Lambda captures.
bool jumpTrue(const LabelTy &Label, SourceInfo SI)
Emits jumps.
bool speculate(const CallExpr *E, const LabelTy &EndLabel)
Speculative execution.
bool fallthrough(const LabelTy &Label)
bool jumpFalse(const LabelTy &Label, SourceInfo SI)
virtual bool visitFunc(const FunctionDecl *E)=0
Methods implemented by the compiler.
std::optional< SourceInfo > LocOverride
llvm::DenseMap< const ParmVarDecl *, FuncParam > Params
Parameter indices.
virtual bool visit(const Expr *E)=0
void compileFunc(const FunctionDecl *FuncDecl, Function *Func)
Compiles the function into the module.
llvm::SmallVector< SmallVector< Local, 8 >, 2 > Descriptors
Local descriptors.
Wrapper around fixed point types.
Definition FixedPoint.h:23
If a Floating is constructed from Memory, it DOES NOT OWN THAT MEMORY.
Definition Floating.h:35
Bytecode function.
Definition Function.h:98
If an IntegralAP is constructed from Memory, it DOES NOT OWN THAT MEMORY.
Definition IntegralAP.h:36
The program contains and links the bytecode for all functions.
Definition Program.h:37
Structure/Class descriptor.
Definition Record.h:27
Describes the statement/declaration an opcode was generated from.
Definition Source.h:77
constexpr bool aligned(uintptr_t Value)
Definition PrimType.h:217
constexpr size_t align(size_t Size)
Aligns a size to the pointer alignment.
Definition PrimType.h:213
PrimType
Enumeration of the primitive types of the VM.
Definition PrimType.h:34
Top level wrappers for InstallAPI frontend operations.
@ Success
Annotation was successful.
Definition Parser.h:65
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:122
unsigned getAllocSize() const
Returns the allocated size, including metadata.
Definition Descriptor.h:237
Information about a local's storage.
Definition Function.h:38