logicaffeine_compile/vm/wasm/func.rs
1//! Per-function WebAssembly lowering: a region of VM bytecode (`&[Op]`, a register machine)
2//! → a WebAssembly function (a stack machine with i64 locals).
3//!
4//! ## Control flow
5//!
6//! VM bytecode uses absolute jumps; WebAssembly has only *structured* control flow. The
7//! lowering splits the region into basic blocks and emits the standard **dispatch loop**:
8//! a `loop` wrapping `block`s nested one-per-basic-block, with a `br_table` on a "next
9//! block" local at the bottom. Each block runs its arithmetic, then sets the next-block
10//! index and re-dispatches (`br` to the loop) — or `return`s. This translates *any*
11//! reducible (and irreducible) control flow correctly, not just recognized patterns.
12//!
13//! ## Eligibility (Phase 6 deopt-at-concurrency, mirrored)
14//!
15//! Only integer regions are emitted: const/move/arith/compare/jump/return. Any op outside
16//! that set — every concurrency / channel / networking op included — makes
17//! [`compile_region_to_wasm`] return `None`, so the region stays on the bytecode tier (a
18//! yield-free emitted module by construction, exactly like the native backend's deny-list).
19//!
20//! This is the byte emitter both the browser WASM-JIT tier (`super::region_jit`) and the
21//! direct AOT backend consume; it depends only on [`super::encode`], not on the `wasm-jit`
22//! feature.
23
24use super::cfg::{assemble_dispatch_loop, goto_block, Blocks};
25use super::encode::*;
26use crate::vm::instruction::{CompiledProgram, Constant, Op};
27
28/// Whether a region op is WASM-JIT-eligible (the integer fragment). Everything else —
29/// notably every concurrency / channel / networking op — is rejected so the region stays
30/// on the bytecode tier.
31fn is_supported(op: &Op) -> bool {
32 matches!(
33 op,
34 Op::LoadConst { .. }
35 | Op::Move { .. }
36 | Op::Add { .. }
37 | Op::Sub { .. }
38 | Op::Mul { .. }
39 | Op::Div { .. }
40 | Op::Mod { .. }
41 | Op::BitXor { .. }
42 | Op::BitAnd { .. }
43 | Op::BitOr { .. }
44 | Op::Shl { .. }
45 | Op::Shr { .. }
46 | Op::Lt { .. }
47 | Op::Gt { .. }
48 | Op::LtEq { .. }
49 | Op::GtEq { .. }
50 | Op::Eq { .. }
51 | Op::NotEq { .. }
52 | Op::Jump { .. }
53 | Op::JumpIfFalse { .. }
54 | Op::JumpIfTrue { .. }
55 | Op::Return { .. }
56 | Op::ReturnNothing
57 )
58}
59
60/// Lower an integer region to a WebAssembly module exporting one function `f` of
61/// `num_params` `i64` parameters returning `i64`. VM registers map 1:1 to WASM locals
62/// (`0..num_params` params, `num_params..num_regs` declared i64 locals); one extra i32
63/// local at index `num_regs` is the dispatch "next block" index.
64///
65/// Returns `None` — the region stays on the bytecode tier — for any op outside the integer
66/// fragment (control flow, calls, and *all* concurrency / channel / networking ops), a
67/// non-`Int` constant, an out-of-range jump target, or a region without a reachable
68/// `Return`.
69pub fn compile_region_to_wasm(
70 ops: &[Op],
71 constants: &[Constant],
72 num_params: u32,
73 num_regs: u32,
74) -> Option<Vec<u8>> {
75 let n = ops.len();
76 if n == 0 {
77 return None;
78 }
79
80 // ---- 1. Eligibility: the integer fragment, and a reachable `Return` ----
81 let mut has_return = false;
82 for op in ops {
83 if !is_supported(op) {
84 return None;
85 }
86 if matches!(op, Op::Return { .. }) {
87 has_return = true;
88 }
89 }
90 if !has_return {
91 return None;
92 }
93
94 let blocks = Blocks::new(ops)?;
95 let num_blocks = blocks.num_blocks();
96 let pc_local = num_regs; // the dispatch "next block" index lives just past the registers
97
98 // ---- 2. Emit each block's body + terminator ----
99 let mut blocks_code: Vec<Vec<u8>> = Vec::with_capacity(num_blocks);
100 for k in 0..num_blocks {
101 let start = blocks.start(k);
102 let end = blocks.end(k);
103 let mut code = Vec::new();
104 let mut terminated = false;
105 for pc in start..end {
106 match ops[pc] {
107 Op::LoadConst { dst, idx } => {
108 let v = match constants.get(idx as usize)? {
109 Constant::Int(x) => *x,
110 _ => return None,
111 };
112 code.push(0x42); // i64.const
113 leb_i64(&mut code, v);
114 local_set(&mut code, dst as u32);
115 }
116 Op::Move { dst, src } => {
117 local_get(&mut code, src as u32);
118 local_set(&mut code, dst as u32);
119 }
120 // Add/Sub/Mul are CHECKED: they trap on signed overflow so the task falls
121 // back to the VM (which promotes to BigInt) — never a silent wrap. This keeps
122 // every tier in sync on the EXACT-integer contract.
123 Op::Add { dst, lhs, rhs } => emit_checked_addsub(&mut code, false, dst, lhs, rhs),
124 Op::Sub { dst, lhs, rhs } => emit_checked_addsub(&mut code, true, dst, lhs, rhs),
125 Op::Mul { dst, lhs, rhs } => emit_checked_mul(&mut code, dst, lhs, rhs),
126 // Div/Mod already trap on their edge cases (div-by-zero, i64::MIN / -1) in WASM
127 // → host error → VM fallback, so no extra guard is needed.
128 Op::Div { dst, lhs, rhs } => arith(&mut code, 0x7F, dst, lhs, rhs), // i64.div_s
129 Op::Mod { dst, lhs, rhs } => arith(&mut code, 0x81, dst, lhs, rhs), // i64.rem_s
130 // Bitwise / shift: pure wrapping, no overflow concern. The VM masks the shift
131 // count mod 64 (`wrapping_shl`/`wrapping_shr`); WASM's i64.shl/shr_s do the
132 // same, and shr is ARITHMETIC (signed) to match `wrapping_shr` on i64.
133 Op::BitXor { dst, lhs, rhs } => arith(&mut code, 0x85, dst, lhs, rhs), // i64.xor
134 Op::BitAnd { dst, lhs, rhs } => arith(&mut code, 0x83, dst, lhs, rhs), // i64.and
135 Op::BitOr { dst, lhs, rhs } => arith(&mut code, 0x84, dst, lhs, rhs), // i64.or
136 Op::Shl { dst, lhs, rhs } => arith(&mut code, 0x86, dst, lhs, rhs), // i64.shl
137 Op::Shr { dst, lhs, rhs } => arith(&mut code, 0x87, dst, lhs, rhs), // i64.shr_s
138 Op::Lt { dst, lhs, rhs } => compare(&mut code, 0x53, dst, lhs, rhs), // i64.lt_s
139 Op::Gt { dst, lhs, rhs } => compare(&mut code, 0x55, dst, lhs, rhs), // i64.gt_s
140 Op::LtEq { dst, lhs, rhs } => compare(&mut code, 0x57, dst, lhs, rhs), // i64.le_s
141 Op::GtEq { dst, lhs, rhs } => compare(&mut code, 0x59, dst, lhs, rhs), // i64.ge_s
142 Op::Eq { dst, lhs, rhs } => compare(&mut code, 0x51, dst, lhs, rhs), // i64.eq
143 Op::NotEq { dst, lhs, rhs } => compare(&mut code, 0x52, dst, lhs, rhs), // i64.ne
144 Op::Jump { target } => {
145 goto_block(&mut code, pc_local, &blocks, k, blocks.block_of(target));
146 terminated = true;
147 break;
148 }
149 Op::JumpIfFalse { cond, target } => {
150 emit_cond_jump(
151 &mut code,
152 cond,
153 true,
154 blocks.block_of(target),
155 blocks.block_of(pc + 1),
156 pc_local,
157 blocks.br_loop(k),
158 );
159 terminated = true;
160 break;
161 }
162 Op::JumpIfTrue { cond, target } => {
163 emit_cond_jump(
164 &mut code,
165 cond,
166 false,
167 blocks.block_of(target),
168 blocks.block_of(pc + 1),
169 pc_local,
170 blocks.br_loop(k),
171 );
172 terminated = true;
173 break;
174 }
175 Op::Return { src } => {
176 local_get(&mut code, src as u32);
177 code.push(0x0F); // return
178 terminated = true;
179 break;
180 }
181 Op::ReturnNothing => {
182 // The compiler appends a `ReturnNothing` after a value `Return` as a
183 // fallthrough safety terminator. For an i64-returning function it is
184 // unreachable; encode it as a trap so any (erroneous) reachable path
185 // diverges from the VM and is caught by the differential.
186 code.push(0x00); // unreachable
187 terminated = true;
188 break;
189 }
190 _ => return None,
191 }
192 }
193 if !terminated {
194 // Fell off the block end into the next block: set next, re-dispatch.
195 goto_block(&mut code, pc_local, &blocks, k, blocks.block_of(end));
196 }
197 blocks_code.push(code);
198 }
199
200 // ---- 3. Assemble the function body: dispatch loop ----
201 let mut body = assemble_dispatch_loop(pc_local, &blocks_code);
202 body.push(0x00); // unreachable (only reached via $exit / default — never on a Return path)
203 body.push(0x0B); // end function
204
205 // ---- 4. Module sections ----
206 let mut module = vec![0x00, 0x61, 0x73, 0x6D, 0x01, 0x00, 0x00, 0x00];
207
208 let mut ty = Vec::new();
209 leb_u32(&mut ty, 1);
210 ty.push(0x60);
211 leb_u32(&mut ty, num_params);
212 for _ in 0..num_params {
213 ty.push(I64);
214 }
215 leb_u32(&mut ty, 1);
216 ty.push(I64);
217 section(&mut module, 1, &ty);
218
219 let mut func = Vec::new();
220 leb_u32(&mut func, 1);
221 leb_u32(&mut func, 0);
222 section(&mut module, 3, &func);
223
224 let mut export = Vec::new();
225 leb_u32(&mut export, 1);
226 leb_u32(&mut export, 1);
227 export.push(b'f');
228 export.push(0x00);
229 leb_u32(&mut export, 0);
230 section(&mut module, 7, &export);
231
232 // Code section: locals = (num_regs - num_params) i64 + one i32 (the dispatch index).
233 let num_i64_locals = num_regs.saturating_sub(num_params);
234 let mut entry = Vec::new();
235 leb_u32(&mut entry, if num_i64_locals > 0 { 2 } else { 1 }); // local groups
236 if num_i64_locals > 0 {
237 leb_u32(&mut entry, num_i64_locals);
238 entry.push(I64);
239 }
240 leb_u32(&mut entry, 1);
241 entry.push(I32);
242 entry.extend_from_slice(&body);
243 let mut code_sec = Vec::new();
244 leb_u32(&mut code_sec, 1);
245 leb_u32(&mut code_sec, entry.len() as u32);
246 code_sec.extend_from_slice(&entry);
247 section(&mut module, 10, &code_sec);
248
249 Some(module)
250}
251
252/// Lower function `fi` of a compiled program to a WebAssembly module — the integration
253/// entry the VM's tier-up uses. A function's body lives in the shared `program.code` from
254/// its `entry_pc` until the next function's entry (or the program end), with **absolute**
255/// jump targets; this extracts that slice and rebases every jump into the region-local
256/// 0-based space [`compile_region_to_wasm`] expects. Returns `None` (stay on bytecode) if
257/// the body leaves the integer fragment or a jump escapes the function.
258pub fn compile_function_to_wasm(program: &CompiledProgram, fi: usize) -> Option<Vec<u8>> {
259 let f = program.functions.get(fi)?;
260 // The emitted module returns an i64 that `WasmTier::on_call`'s caller boxes as an `Int`.
261 // That is only sound when the function actually returns an Int — a `Bool`-returning
262 // function (a comparison result) would be mis-boxed as `Int(1)` instead of `Bool(true)`
263 // (`Show` would print `1`, not `true`), and `Float` rides different bits. So tier ONLY
264 // declared-`Int` returns; everything else (Bool / Float / inferred-`None`) deopts to the
265 // VM, which types the result correctly. Keeps every tier in sync on return types.
266 if f.ret_kind != Some(crate::vm::native_tier::SlotKind::Int) {
267 return None;
268 }
269 let entry = f.entry_pc;
270 // The function spans [entry, next_entry) — functions are concatenated after Main.
271 let end = program
272 .functions
273 .iter()
274 .map(|g| g.entry_pc)
275 .filter(|&e| e > entry)
276 .min()
277 .unwrap_or(program.code.len());
278 if entry >= end || end > program.code.len() {
279 return None;
280 }
281 let rebase = |t: usize| -> Option<usize> {
282 if t >= entry && t < end {
283 Some(t - entry)
284 } else {
285 None // a jump out of the function body — not a self-contained region
286 }
287 };
288 let mut region: Vec<Op> = Vec::with_capacity(end - entry);
289 for &op in &program.code[entry..end] {
290 region.push(match op {
291 Op::Jump { target } => Op::Jump {
292 target: rebase(target)?,
293 },
294 Op::JumpIfFalse { cond, target } => Op::JumpIfFalse {
295 cond,
296 target: rebase(target)?,
297 },
298 Op::JumpIfTrue { cond, target } => Op::JumpIfTrue {
299 cond,
300 target: rebase(target)?,
301 },
302 other => other,
303 });
304 }
305 compile_region_to_wasm(
306 ®ion,
307 &program.constants,
308 f.param_count as u32,
309 f.register_count as u32,
310 )
311}
312
313#[cfg(all(test, feature = "wasm-jit", not(target_arch = "wasm32")))]
314#[path = "../../../../logicaffeine_tests/unit/logicaffeine_compile/vm/wasm/func/tests.rs"]
315mod tests;