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
23void ByteCodeEmitter::compileFunc(const FunctionDecl *FuncDecl,
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(RD: ParentDecl);
45 assert(R);
46 llvm::DenseMap<const ValueDecl *, FieldDecl *> LC;
47 FieldDecl *LTC;
48
49 ParentDecl->getCaptureFields(Captures&: LC, ThisCapture&: LTC);
50
51 for (const auto &Cap : LC) {
52 unsigned Offset = R->getField(FD: Cap.second)->Offset;
53 this->LambdaCaptures[Cap.first] = {
54 .Offset: Offset, .IsPtr: Cap.second->getType()->isReferenceType()};
55 }
56 if (LTC) {
57 QualType CaptureType = R->getField(FD: LTC)->Decl->getType();
58 this->LambdaThisCapture = {.Offset: R->getField(FD: LTC)->Offset,
59 .IsPtr: 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(i: ParamIndex);
68 if (PD->isInvalidDecl())
69 IsValid = false;
70 this->Params.insert(KV: {PD, {.Index: ParamIndex, .IsPtr: Ctx.canClassify(T: PD->getType())}});
71 }
72
73 // Compile the function body.
74 if (!visitFunc(E: FuncDecl)) {
75 Func->setIsFullyCompiled(true);
76 return;
77 }
78
79 // Create scopes from descriptors.
80 llvm::SmallVector<Scope, 2> Scopes;
81 for (auto &DS : Descriptors) {
82 Scopes.emplace_back(Args: std::move(DS));
83 }
84
85 // Set the function's code.
86 Func->setCode(Source: FuncDecl, NewFrameSize: NextLocalOffset, NewCode: std::move(Code), NewSrcMap: std::move(SrcMap),
87 NewScopes: std::move(Scopes), NewHasBody: FuncDecl->hasBody(), NewIsValid: IsValid);
88 Func->setIsFullyCompiled(true);
89}
90
91Scope::Local ByteCodeEmitter::createLocal(const Descriptor *D) {
92 NextLocalOffset += sizeof(Block);
93 unsigned Location = NextLocalOffset;
94 NextLocalOffset += align(Size: Block::InlineDescMD + D->getAllocSize());
95 return {.Desc: D, .Offset: Location};
96}
97
98void ByteCodeEmitter::emitLabel(LabelTy Label) {
99 const size_t Target = Code.size();
100 LabelOffsets.insert(KV: {Label, Target});
101
102 if (auto It = LabelRelocs.find(Val: 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(Size: 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>(P: Location, V: Offset);
111 }
112 LabelRelocs.erase(I: 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(Size: sizeof(Opcode)) + align(Size: sizeof(int32_t));
120 assert(aligned(Position));
121
122 // If target is known, compute jump offset.
123 if (auto It = LabelOffsets.find(Val: Label); It != LabelOffsets.end())
124 return It->second - Position;
125
126 // Otherwise, record relocation and return dummy offset.
127 LabelRelocs[Label].push_back(Elt: Position);
128 return 0ull;
129}
130
131/// Helper to write bytecode and bail out if 32-bit offsets become invalid.
132template <typename T>
133static void emit(Program &P, llvm::SmallVectorImpl<std::byte> &Code,
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(Size: sizeof(uintptr_t));
140 else
141 Size = align(Size: 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(N: 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>
162static void emitSerialized(llvm::SmallVectorImpl<std::byte> &Code, const T &Val,
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(N: ValPos + Size);
176
177 Val.serialize(Code.data() + ValPos);
178}
179
180template <>
181void emit(Program &P, llvm::SmallVectorImpl<std::byte> &Code,
182 const Floating &Val, bool &Success) {
183 emitSerialized(Code, Val, Success);
184}
185
186template <>
187void emit(Program &P, llvm::SmallVectorImpl<std::byte> &Code,
188 const IntegralAP<false> &Val, bool &Success) {
189 emitSerialized(Code, Val, Success);
190}
191
192template <>
193void emit(Program &P, llvm::SmallVectorImpl<std::byte> &Code,
194 const IntegralAP<true> &Val, bool &Success) {
195 emitSerialized(Code, Val, Success);
196}
197
198template <>
199void emit(Program &P, llvm::SmallVectorImpl<std::byte> &Code,
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, Val: Op, Success);
211
212 SI = LocOverride.value_or(u&: SI);
213 if (SrcMap.empty() || SrcMap.back() != SI)
214 SrcMap.push(Offset: Code.size(), Info: SI);
215
216 (..., emit(P, Code, Args, Success));
217 return Success;
218}
219
220bool ByteCodeEmitter::jumpTrue(const LabelTy &Label, SourceInfo SI) {
221 return emitJt(getOffset(Label), SI);
222}
223
224bool ByteCodeEmitter::jumpFalse(const LabelTy &Label, SourceInfo SI) {
225 return emitJf(getOffset(Label), SI);
226}
227
228bool ByteCodeEmitter::jump(const LabelTy &Label, SourceInfo SI) {
229 return emitJmp(getOffset(Label), SI);
230}
231
232bool ByteCodeEmitter::fallthrough(const LabelTy &Label) {
233 emitLabel(Label);
234 return true;
235}
236
237bool ByteCodeEmitter::speculate(const CallExpr *E, const LabelTy &EndLabel) {
238 const Expr *Arg = E->getArg(Arg: 0);
239 PrimType T = Ctx.classify(T: Arg->getType()).value_or(PT: PT_Ptr);
240 if (!this->emitBCP(getOffset(Label: EndLabel), T, E))
241 return false;
242 if (!this->visit(E: 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
254