Skip to main content

logicaffeine_compile/vm/
fn_bytecode.rs

1//! A relocatable, self-contained per-function bytecode unit (HOTSWAP §7).
2//!
3//! A [`CompiledProgram`] holds every function body in ONE flat `code` vector with
4//! ABSOLUTE jump targets; `entry_pc` marks where each begins. [`slice_function`]
5//! lifts one function out of that vector into a [`FnBytecode`] whose jump targets are
6//! 0-relative to its own first op, carrying the frame/param/return metadata needed to
7//! run or compile it independently of the program it came from.
8//!
9//! This is the producer the Axis-1 hot-swap consumes: the WASM-portable warm-bytecode
10//! side-table (P11) installs an `FnBytecode` per function, and the OPFS tier cache
11//! (P12) serializes it. The native path (P10) feeds the same body to forge (which
12//! rebases by `entry_pc` itself, so it takes the program slice directly).
13
14#[allow(unused_imports)]
15use super::instruction::{CompiledProgram, Constant, Op};
16use super::native_tier::{ParamKind, SlotKind};
17
18/// One function lifted out of a [`CompiledProgram`]: a self-contained, relocatable
19/// body with 0-relative jump targets plus the metadata to execute or compile it.
20#[derive(Clone, Debug, serde::Serialize, serde::Deserialize)]
21#[allow(dead_code)] // consumed by P10 (native swap), P11 (warm side-table), P12 (cache)
22pub struct FnBytecode {
23    /// The function body, with every jump target rebased to be relative to `code[0]`.
24    pub code: Vec<Op>,
25    /// The constant pool the code indexes into — the program's pool, copied so the
26    /// unit is self-contained; constant indices are preserved unchanged.
27    pub constants: Vec<Constant>,
28    pub register_count: usize,
29    pub param_count: u16,
30    pub param_kinds: Vec<Option<ParamKind>>,
31    pub ret_kind: Option<SlotKind>,
32    /// Which frame registers carry a user-visible name (the region JIT's
33    /// observability map; preserved from the source function).
34    pub named_regs: Vec<bool>,
35}
36
37impl FnBytecode {
38    /// Structural self-consistency check (HOTSWAP §P12/P11 robustness). Every jump target
39    /// must land inside the body and the body must end in a control-leaving op, so an
40    /// installed body can neither fetch past the warm buffer (panic) nor fall through into
41    /// the next installed body (silent miscompile). A `slice_function` body always passes;
42    /// this rejects a corrupt / foreign / mis-decoded body so the VM declines the install
43    /// and falls back to baseline instead of trusting it. `n_funcs` bounds any `Call`
44    /// target so a body can't dispatch to a non-existent function index.
45    pub fn is_well_formed(&self, n_funcs: usize) -> bool {
46        if self.code.is_empty() {
47            return false;
48        }
49        for op in &self.code {
50            match *op {
51                Op::Jump { target }
52                | Op::JumpIfFalse { target, .. }
53                | Op::JumpIfTrue { target, .. } => {
54                    if target >= self.code.len() {
55                        return false;
56                    }
57                }
58                Op::Call { func, .. } => {
59                    if func as usize >= n_funcs {
60                        return false;
61                    }
62                }
63                _ => {}
64            }
65        }
66        matches!(
67            self.code.last(),
68            Some(Op::Return { .. } | Op::ReturnNothing | Op::Halt)
69        )
70    }
71}
72
73/// Shift one op's jump target by `delta` (signed). Only the three control-flow ops
74/// carry an absolute pc target; the `target: Reg` ops (`TestArm`/`BindArm`/…) name a
75/// register, not a pc, and are left untouched.
76pub(crate) fn rebase(op: Op, delta: isize) -> Op {
77    let shift = |t: usize| (t as isize + delta) as usize;
78    match op {
79        Op::Jump { target } => Op::Jump {
80            target: shift(target),
81        },
82        Op::JumpIfFalse { cond, target } => Op::JumpIfFalse {
83            cond,
84            target: shift(target),
85        },
86        Op::JumpIfTrue { cond, target } => Op::JumpIfTrue {
87            cond,
88            target: shift(target),
89        },
90        other => other,
91    }
92}
93
94/// Lift function `fi` out of `program` into a self-contained [`FnBytecode`] with
95/// 0-relative jumps. The body is `program.code[entry_pc..end]` (where `end` is the
96/// next function's entry, or the end of code); its absolute jump targets are rebased
97/// by `-entry_pc`, so they index into the returned `code` directly.
98#[allow(dead_code)]
99pub fn slice_function(program: &CompiledProgram, fi: usize) -> FnBytecode {
100    let f = &program.functions[fi];
101    let entry = f.entry_pc;
102    let end = program
103        .functions
104        .iter()
105        .map(|g| g.entry_pc)
106        .filter(|&e| e > entry)
107        .min()
108        .unwrap_or(program.code.len());
109    let code = program.code[entry..end]
110        .iter()
111        .map(|&op| rebase(op, -(entry as isize)))
112        .collect();
113    FnBytecode {
114        code,
115        constants: program.constants.clone(),
116        register_count: f.register_count,
117        param_count: f.param_count,
118        param_kinds: f.param_kinds.clone(),
119        ret_kind: f.ret_kind,
120        named_regs: f.named_regs.clone(),
121    }
122}
123
124#[cfg(test)]
125#[path = "../../../logicaffeine_tests/unit/logicaffeine_compile/vm/fn_bytecode/tests.rs"]
126mod tests;