1mod instructions;
2
3extern crate alloc;
4
5use alloc::fmt;
6use core::mem::ManuallyDrop;
7use cranelift::prelude::*;
8use cranelift_jit::{JITBuilder, JITModule};
9use cranelift_module::{FuncId, Linkage, Module, ModuleError};
10use instructions::FunctionCompiler;
11use rustpython_compiler_core::bytecode;
12
13#[derive(Debug, thiserror::Error)]
14#[non_exhaustive]
15pub enum JitCompileError {
16 #[error("function can't be jitted")]
17 NotSupported,
18 #[error("bad bytecode")]
19 BadBytecode,
20 #[error("error while compiling to machine code: {0}")]
21 CraneliftError(Box<ModuleError>),
22}
23
24impl From<ModuleError> for JitCompileError {
25 fn from(err: ModuleError) -> Self {
26 Self::CraneliftError(Box::new(err))
27 }
28}
29
30#[derive(Debug, thiserror::Error, Eq, PartialEq)]
31#[non_exhaustive]
32pub enum JitArgumentError {
33 #[error("argument is of wrong type")]
34 ArgumentTypeMismatch,
35 #[error("wrong number of arguments")]
36 WrongNumberOfArguments,
37}
38
39struct Jit {
40 builder_context: FunctionBuilderContext,
41 ctx: codegen::Context,
42 module: JITModule,
43}
44
45impl Jit {
46 fn new() -> Self {
47 let builder = JITBuilder::new(cranelift_module::default_libcall_names())
48 .expect("Failed to build JITBuilder");
49 let module = JITModule::new(builder);
50 Self {
51 builder_context: FunctionBuilderContext::new(),
52 ctx: module.make_context(),
53 module,
54 }
55 }
56
57 fn build_function<C: bytecode::Constant>(
58 &mut self,
59 bytecode: &bytecode::CodeObject<C>,
60 args: &[JitType],
61 ret: Option<JitType>,
62 ) -> Result<(FuncId, JitSig), JitCompileError> {
63 for arg in args {
64 let arg = arg.to_cranelift().ok_or(JitCompileError::NotSupported)?;
65 self.ctx.func.signature.params.push(AbiParam::new(arg));
66 }
67
68 if let Some(ret) = ret.as_ref().and_then(JitType::to_cranelift) {
69 self.ctx.func.signature.returns.push(AbiParam::new(ret));
70 }
71
72 let id = self.module.declare_function(
73 &format!("jit_{}", bytecode.obj_name.as_ref()),
74 Linkage::Export,
75 &self.ctx.func.signature,
76 )?;
77
78 let func_ref = self.module.declare_func_in_func(id, &mut self.ctx.func);
79
80 let mut builder = FunctionBuilder::new(&mut self.ctx.func, &mut self.builder_context);
81 let entry_block = builder.create_block();
82 builder.append_block_params_for_function_params(entry_block);
83 builder.switch_to_block(entry_block);
84
85 let sig = {
86 let mut compiler = FunctionCompiler::new(
87 &mut builder,
88 bytecode.varnames.len(),
89 args,
90 ret,
91 entry_block,
92 );
93
94 compiler.compile(func_ref, bytecode)?;
95
96 compiler.sig
97 };
98
99 builder.seal_all_blocks();
100 builder.finalize(self.module.target_config());
101
102 self.module.define_function(id, &mut self.ctx)?;
103
104 self.module.clear_context(&mut self.ctx);
105
106 Ok((id, sig))
107 }
108}
109
110pub fn compile<C: bytecode::Constant>(
111 bytecode: &bytecode::CodeObject<C>,
112 args: &[JitType],
113 ret: Option<JitType>,
114) -> Result<CompiledCode, JitCompileError> {
115 let mut jit = Jit::new();
116
117 let (id, sig) = jit.build_function(bytecode, args, ret)?;
118
119 jit.module.finalize_definitions()?;
120
121 let code = jit.module.get_finalized_function(id);
122 Ok(CompiledCode {
123 sig,
124 code,
125 module: ManuallyDrop::new(jit.module),
126 })
127}
128
129pub struct CompiledCode {
130 sig: JitSig,
131 code: *const u8,
132 module: ManuallyDrop<JITModule>,
133}
134
135impl CompiledCode {
136 pub fn args_builder(&self) -> ArgsBuilder<'_> {
137 ArgsBuilder::new(self)
138 }
139
140 pub fn invoke(&self, args: &[AbiValue]) -> Result<Option<AbiValue>, JitArgumentError> {
141 if self.sig.args.len() != args.len() {
142 return Err(JitArgumentError::WrongNumberOfArguments);
143 }
144
145 let cif_args = self
146 .sig
147 .args
148 .iter()
149 .zip(args.iter())
150 .map(|(ty, val)| type_check(ty, val).map(|_| val))
151 .map(|v| v.map(AbiValue::to_libffi_arg))
152 .collect::<Result<Vec<_>, _>>()?;
153 Ok(unsafe { self.invoke_raw(&cif_args) })
154 }
155
156 unsafe fn invoke_raw(&self, cif_args: &[libffi::middle::Arg<'_>]) -> Option<AbiValue> {
157 unsafe {
158 let cif = self.sig.to_cif();
159 let value = cif.call::<UnTypedAbiValue>(
160 libffi::middle::CodePtr::from_ptr(self.code as *const _),
161 cif_args,
162 );
163 match self.sig.ret.as_ref() {
164 Some(JitType::None) | None => None,
165 Some(ty) => Some(value.to_typed(ty)),
166 }
167 }
168 }
169}
170
171struct JitSig {
172 args: Vec<JitType>,
173 ret: Option<JitType>,
174}
175
176impl JitSig {
177 fn to_cif(&self) -> libffi::middle::Cif {
178 let ret = match self.ret {
179 Some(ref ty) => ty.to_libffi(),
180 None => libffi::middle::Type::void(),
181 };
182 libffi::middle::Cif::new(self.args.iter().map(JitType::to_libffi), ret)
183 }
184}
185
186#[derive(Debug, Clone, PartialEq, Eq)]
187#[non_exhaustive]
188pub enum JitType {
189 Int,
190 Float,
191 Bool,
192 None,
193}
194
195impl JitType {
196 fn to_cranelift(&self) -> Option<types::Type> {
197 match self {
198 Self::Int => Some(types::I64),
199 Self::Float => Some(types::F64),
200 Self::Bool => Some(types::I8),
201 Self::None => None,
202 }
203 }
204
205 fn to_libffi(&self) -> libffi::middle::Type {
206 match self {
207 Self::Int => libffi::middle::Type::i64(),
208 Self::Float => libffi::middle::Type::f64(),
209 Self::Bool => libffi::middle::Type::u8(),
210 Self::None => libffi::middle::Type::void(),
211 }
212 }
213}
214
215#[derive(Debug, Clone, PartialEq)]
216#[non_exhaustive]
217pub enum AbiValue {
218 Float(f64),
219 Int(i64),
220 Bool(bool),
221}
222
223impl AbiValue {
224 fn to_libffi_arg(&self) -> libffi::middle::Arg<'_> {
225 match self {
226 Self::Int(i) => libffi::middle::Arg::new(i),
227 Self::Float(f) => libffi::middle::Arg::new(f),
228 Self::Bool(b) => libffi::middle::Arg::new(b),
229 }
230 }
231}
232
233impl From<i64> for AbiValue {
234 fn from(i: i64) -> Self {
235 Self::Int(i)
236 }
237}
238
239impl From<f64> for AbiValue {
240 fn from(f: f64) -> Self {
241 Self::Float(f)
242 }
243}
244
245impl From<bool> for AbiValue {
246 fn from(b: bool) -> Self {
247 Self::Bool(b)
248 }
249}
250
251impl TryFrom<AbiValue> for i64 {
252 type Error = ();
253
254 fn try_from(value: AbiValue) -> Result<Self, Self::Error> {
255 match value {
256 AbiValue::Int(i) => Ok(i),
257 _ => Err(()),
258 }
259 }
260}
261
262impl TryFrom<AbiValue> for f64 {
263 type Error = ();
264
265 fn try_from(value: AbiValue) -> Result<Self, Self::Error> {
266 match value {
267 AbiValue::Float(f) => Ok(f),
268 _ => Err(()),
269 }
270 }
271}
272
273impl TryFrom<AbiValue> for bool {
274 type Error = ();
275
276 fn try_from(value: AbiValue) -> Result<Self, Self::Error> {
277 match value {
278 AbiValue::Bool(b) => Ok(b),
279 _ => Err(()),
280 }
281 }
282}
283
284fn type_check(ty: &JitType, val: &AbiValue) -> Result<(), JitArgumentError> {
285 match (ty, val) {
286 (JitType::Int, AbiValue::Int(_))
287 | (JitType::Float, AbiValue::Float(_))
288 | (JitType::Bool, AbiValue::Bool(_)) => Ok(()),
289 _ => Err(JitArgumentError::ArgumentTypeMismatch),
290 }
291}
292
293#[derive(Copy, Clone)]
294union UnTypedAbiValue {
295 float: f64,
296 int: i64,
297 boolean: u8,
298 _void: (),
299}
300
301impl UnTypedAbiValue {
302 unsafe fn to_typed(self, ty: &JitType) -> AbiValue {
303 unsafe {
304 match ty {
305 JitType::Int => AbiValue::Int(self.int),
306 JitType::Float => AbiValue::Float(self.float),
307 JitType::Bool => AbiValue::Bool(self.boolean != 0),
308 JitType::None => unreachable!("None has no ABI value"),
309 }
310 }
311 }
312}
313
314unsafe impl Send for CompiledCode {}
317unsafe impl Sync for CompiledCode {}
318
319impl Drop for CompiledCode {
320 fn drop(&mut self) {
321 unsafe { ManuallyDrop::take(&mut self.module).free_memory() }
323 }
324}
325
326impl fmt::Debug for CompiledCode {
327 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
328 f.write_str("[compiled code]")
329 }
330}
331
332pub struct ArgsBuilder<'a> {
333 values: Vec<Option<AbiValue>>,
334 code: &'a CompiledCode,
335}
336
337impl<'a> ArgsBuilder<'a> {
338 #[must_use]
339 fn new(code: &'a CompiledCode) -> Self {
340 Self {
341 values: vec![None; code.sig.args.len()],
342 code,
343 }
344 }
345
346 pub fn set(&mut self, idx: usize, value: AbiValue) -> Result<(), JitArgumentError> {
347 type_check(&self.code.sig.args[idx], &value).map(|_| {
348 self.values[idx] = Some(value);
349 })
350 }
351
352 #[must_use]
353 pub fn is_set(&self, idx: usize) -> bool {
354 self.values[idx].is_some()
355 }
356
357 #[must_use]
358 pub fn into_args(self) -> Option<Args<'a>> {
359 if self.values.iter().any(|v| v.is_none()) {
361 return None;
362 }
363 Some(Args {
364 values: self.values.into_iter().map(|v| v.unwrap()).collect(),
365 code: self.code,
366 })
367 }
368}
369
370pub struct Args<'a> {
371 values: Vec<AbiValue>,
372 code: &'a CompiledCode,
373}
374
375impl Args<'_> {
376 #[must_use]
377 pub fn invoke(&self) -> Option<AbiValue> {
378 let cif_args: Vec<_> = self.values.iter().map(AbiValue::to_libffi_arg).collect();
379 unsafe { self.code.invoke_raw(&cif_args) }
380 }
381}