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 bool emit(llvm::SmallVectorImpl<std::byte> &Code, const T &Val) {
134 size_t ValPos = Code.size();
135 size_t Size;
136
137 if constexpr (std::is_pointer_v<T>)
138 Size = align(Size: sizeof(uintptr_t));
139 else
140 Size = align(Size: sizeof(T));
141
142 if (ValPos + Size > std::numeric_limits<unsigned>::max())
143 return false;
144
145 // Access must be aligned!
146 assert(aligned(ValPos));
147 assert(aligned(ValPos + Size));
148 Code.resize_for_overwrite(N: ValPos + Size);
149
150 if constexpr (std::is_pointer_v<T>)
151 new (Code.data() + ValPos) uintptr_t(reinterpret_cast<uintptr_t>(Val));
152 else
153 new (Code.data() + ValPos) T(Val);
154 return true;
155}
156
157/// Emits a serializable value. These usually (potentially) contain
158/// heap-allocated memory and aren't trivially copyable.
159template <typename T>
160static bool emitSerialized(llvm::SmallVectorImpl<std::byte> &Code,
161 const T &Val) {
162 size_t ValPos = Code.size();
163 size_t Size = align(Val.bytesToSerialize());
164
165 if (ValPos + Size > std::numeric_limits<unsigned>::max())
166 return false;
167
168 // Access must be aligned!
169 assert(aligned(ValPos));
170 assert(aligned(ValPos + Size));
171 Code.resize_for_overwrite(N: ValPos + Size);
172
173 Val.serialize(Code.data() + ValPos);
174 return true;
175}
176
177template <>
178bool emit(llvm::SmallVectorImpl<std::byte> &Code, const Floating &Val) {
179 return emitSerialized(Code, Val);
180}
181
182template <>
183bool emit(llvm::SmallVectorImpl<std::byte> &Code,
184 const IntegralAP<false> &Val) {
185 return emitSerialized(Code, Val);
186}
187
188template <>
189bool emit(llvm::SmallVectorImpl<std::byte> &Code, const IntegralAP<true> &Val) {
190 return emitSerialized(Code, Val);
191}
192
193template <>
194bool emit(llvm::SmallVectorImpl<std::byte> &Code, const FixedPoint &Val) {
195 return emitSerialized(Code, Val);
196}
197
198template <typename... Tys>
199bool ByteCodeEmitter::emitOp(Opcode Op, const Tys &...Args, SourceInfo SI) {
200 // The opcode is followed by arguments. The source info is
201 // attached to the address after the opcode.
202 emit(Code, Val: Op);
203
204 SI = LocOverride.value_or(u&: SI);
205 if (SrcMap.empty() || SrcMap.back() != SI)
206 SrcMap.push(Offset: Code.size(), Info: SI);
207
208 return (emit(Code, Args) && ...);
209}
210
211bool ByteCodeEmitter::jumpTrue(const LabelTy &Label, SourceInfo SI) {
212 return emitJt(getOffset(Label), SI);
213}
214
215bool ByteCodeEmitter::jumpFalse(const LabelTy &Label, SourceInfo SI) {
216 return emitJf(getOffset(Label), SI);
217}
218
219bool ByteCodeEmitter::jump(const LabelTy &Label, SourceInfo SI) {
220 return emitJmp(getOffset(Label), SI);
221}
222
223bool ByteCodeEmitter::fallthrough(const LabelTy &Label) {
224 emitLabel(Label);
225 return true;
226}
227
228bool ByteCodeEmitter::speculate(const CallExpr *E, const LabelTy &EndLabel) {
229 const Expr *Arg = E->getArg(Arg: 0);
230 PrimType T = Ctx.classify(T: Arg->getType()).value_or(PT: PT_Ptr);
231 if (!this->emitBCP(getOffset(Label: EndLabel), T, E))
232 return false;
233 if (!this->visit(E: Arg))
234 return false;
235 return true;
236}
237
238//===----------------------------------------------------------------------===//
239// Opcode emitters
240//===----------------------------------------------------------------------===//
241
242#define GET_LINK_IMPL
243#include "Opcodes.inc"
244#undef GET_LINK_IMPL
245