logicaffeine_compile/vm/aot_tier.rs
1//! AOT-native tier loader (HOTSWAP §Axis-3 / P15): `dlopen` a rustc-built cdylib
2//! (produced by [`crate::compile::build_native_cdylib`]) and wrap an exported
3//! `logos_native_<fn>` symbol as a [`NativeFn`] the VM dispatches through the existing
4//! `NativeSlot::Ready` path — no new dispatch, the hot-swap seam already exists.
5//!
6//! Sound subset: ALL-INT signatures (every param + the return `Int`). Those cross by
7//! value in general-purpose registers, so a single `i64` calling convention is exact.
8//! Float/Bool need per-type fn-pointer ABIs (f64 rides XMM) and are deferred — a
9//! function outside the subset simply gets no AOT fn and stays on VM+JIT (no gap).
10//!
11//! The interpreter is the only caller of the loaded symbol, and ownership of the
12//! `Library` is held for the program's lifetime (an `Arc` inside the `NativeFn`), so
13//! the code stays mapped while any call can occur.
14
15#![cfg(not(target_arch = "wasm32"))]
16
17use std::sync::atomic::{AtomicU64, Ordering};
18use std::sync::Arc;
19
20use super::native_tier::{NativeFn, NativeOutcome, NativeRet, SlotKind};
21
22/// One AOT-native function: the resolved symbol address, its arity, the `Library` it
23/// lives in (kept alive), and a call counter for observability/tests. `Send + Sync`
24/// because the address is immutable and the code is read-only once loaded.
25pub struct AotNativeFn {
26 addr: usize,
27 /// `logos_native_<fn>__failed` — reports (and clears) whether the last call stopped with a
28 /// failure the shim caught.
29 failed: usize,
30 arity: usize,
31 _lib: Arc<libloading::Library>,
32 calls: Arc<AtomicU64>,
33}
34
35// SAFETY: `addr` is an immutable code address in a mapped, read-only library kept
36// alive by `_lib`; calling it is the same on any thread (the interpreter is the sole
37// caller). `calls` is atomic.
38unsafe impl Send for AotNativeFn {}
39unsafe impl Sync for AotNativeFn {}
40
41impl AotNativeFn {
42 /// Number of times this AOT function has been invoked (observability/tests).
43 pub fn call_count(&self) -> u64 {
44 self.calls.load(Ordering::Relaxed)
45 }
46}
47
48impl NativeFn for AotNativeFn {
49 fn call(&self, args: &[i64], _pins: &[i64], _depth: usize) -> NativeOutcome {
50 self.calls.fetch_add(1, Ordering::Relaxed);
51 let a = self.addr;
52 // SAFETY: `a` is the address of a `extern "C" fn(i64..) -> i64` (the
53 // `logos_native_<fn>` shim) for an all-Int signature of this arity; the VM's
54 // entry guard already proved every `args[k]` is an `Int`.
55 let r = unsafe {
56 match self.arity {
57 0 => std::mem::transmute::<usize, extern "C" fn() -> i64>(a)(),
58 1 => std::mem::transmute::<usize, extern "C" fn(i64) -> i64>(a)(args[0]),
59 2 => std::mem::transmute::<usize, extern "C" fn(i64, i64) -> i64>(a)(
60 args[0], args[1],
61 ),
62 3 => std::mem::transmute::<usize, extern "C" fn(i64, i64, i64) -> i64>(a)(
63 args[0], args[1], args[2],
64 ),
65 4 => std::mem::transmute::<usize, extern "C" fn(i64, i64, i64, i64) -> i64>(a)(
66 args[0], args[1], args[2], args[3],
67 ),
68 // Higher arities aren't loaded yet — bail to the bytecode path.
69 _ => return NativeOutcome::Deopt,
70 }
71 };
72 // SAFETY: `failed` is the `extern "C" fn() -> i64` companion the shim exports.
73 let stopped =
74 unsafe { std::mem::transmute::<usize, extern "C" fn() -> i64>(self.failed)() } != 0;
75 if stopped {
76 // The native body stopped partway (a broken contract, `Fail with`, a zero divisor). Only
77 // effect-free functions are compiled native, so re-running the call on bytecode repeats
78 // nothing observable and raises the exact error at the exact point.
79 return NativeOutcome::Deopt;
80 }
81 NativeOutcome::Return(r)
82 }
83
84 fn ret(&self) -> NativeRet {
85 NativeRet::Scalar(SlotKind::Int)
86 }
87
88 fn entry_ptr(&self) -> i64 {
89 // AOT functions are reached via the Rust-level `NativeSlot::Ready` dispatch,
90 // NOT the FnTable stencil fast-path (whose raw-pointer ABI differs). They are
91 // never published to the FnTable, so this is unused.
92 0
93 }
94
95 fn published_regc(&self) -> i64 {
96 0
97 }
98}
99
100/// `dlopen` `path` and resolve the AOT-native `symbol` (`logos_native_<fn>`) as an
101/// all-Int function of `arity`, wrapping it as a [`NativeFn`] plus its shared call
102/// counter. Returns `None` if the library or symbol cannot be loaded (the caller then
103/// keeps the function on VM+JIT — no gap at the seam).
104pub fn load_aot_native(
105 path: &std::path::Path,
106 symbol: &str,
107 arity: usize,
108) -> Option<(Box<dyn NativeFn>, Arc<AtomicU64>)> {
109 // SAFETY: loading an arbitrary library runs its initializers; the caller supplies a
110 // path it just built (or a cache entry validated by toolchain hash).
111 let lib = unsafe { libloading::Library::new(path).ok()? };
112 // Probe the symbol exists (typed as a fn so resolution is a function lookup).
113 let addr = unsafe {
114 let sym: libloading::Symbol<'_, extern "C" fn() -> i64> =
115 lib.get(symbol.as_bytes()).ok()?;
116 (*sym) as usize
117 };
118 // The failure companion is part of the contract: a library without it could abort the host on
119 // a failure, so it is not loaded at all.
120 let failed = unsafe {
121 let sym: libloading::Symbol<'_, extern "C" fn() -> i64> =
122 lib.get(format!("{symbol}__failed").as_bytes()).ok()?;
123 (*sym) as usize
124 };
125 let calls = Arc::new(AtomicU64::new(0));
126 let nf = AotNativeFn {
127 addr,
128 failed,
129 arity,
130 _lib: Arc::new(lib),
131 calls: calls.clone(),
132 };
133 Some((Box::new(nf), calls))
134}