Skip to main content

byteflow/jit/
dispatch.rs

1//! Execute compiled traces and map exits back to VM state.
2#![allow(unsafe_code)]
3
4use std::sync::Arc;
5
6use crate::{Chunk, Fault, Opcode, Value, Vm, VmResult};
7
8use super::compiler::TraceCompiler;
9use super::exit::{ExitReason, JitReturn, JIT_BUDGET, JIT_DEOPT};
10use super::frame::{JitCallRecord, JitFrame, MAX_JIT_CALL_DEPTH};
11use super::module_local::with_jit_module;
12use super::runtime::JitRuntime;
13use super::trace::{CompiledTrace, JitContext, TraceKey, HOT_THRESHOLD};
14
15/// Result of copying VM registers into JIT shadow slots.
16#[derive(Debug, Clone, Copy, PartialEq, Eq)]
17pub enum SyncSlotsResult {
18    Ok,
19    /// Every register is `Float`, `Bool`, or `Unit`, and at least one is
20    /// `Float`. Slots hold IEEE bits.
21    Float,
22    /// A register held a type this specialization cannot guard.
23    Deopt,
24    /// Frame unavailable.
25    Unavailable,
26}
27
28/// Tags of the active frame at the moment a trace is entered.
29///
30/// The public slot runners pass [`EntryTags::INT`]: every inherited `Move`
31/// writes an `Int`. The VM runners fill the real `Bool` and `Unit` bits.
32#[derive(Clone, Copy)]
33struct EntryTags {
34    as_bool: [u64; 4],
35    as_unit: [u64; 4],
36    as_float: [u64; 4],
37}
38
39impl EntryTags {
40    const INT: Self = Self {
41        as_bool: [0; 4],
42        as_unit: [0; 4],
43        as_float: [0; 4],
44    };
45
46    fn from_vm(vm: &Vm) -> Self {
47        let mut tags = Self::INT;
48        let Some(regs) = vm.top_registers() else {
49            return tags;
50        };
51        for (index, value) in regs.iter().enumerate() {
52            if index >= 256 {
53                break;
54            }
55            let bit = 1u64 << (index % 64);
56            let word = index / 64;
57            match value {
58                Value::Bool(_) => tags.as_bool[word] |= bit,
59                Value::Unit => tags.as_unit[word] |= bit,
60                Value::Float(_) => tags.as_float[word] |= bit,
61                _ => {}
62            }
63        }
64        tags
65    }
66}
67
68/// Attempt one native trace at the current `(function, pc)`.
69fn try_jit_step(vm: &mut Vm, ctx: &mut JitContext, budget: u32) -> JitProbe {
70    if !Arc::ptr_eq(&ctx.chunk, &vm.chunk_arc()) {
71        return JitProbe::Miss;
72    }
73    let Some(pc) = vm.current_pc() else {
74        return JitProbe::Miss;
75    };
76    let function = vm.current_function();
77    let Some(register_count) = vm.current_num_registers() else {
78        return JitProbe::Miss;
79    };
80
81    let mut slots = vec![0i64; slot_capacity(vm)];
82    let floats = match sync_slots_from_vm(vm, &mut slots) {
83        SyncSlotsResult::Ok => false,
84        SyncSlotsResult::Float => true,
85        SyncSlotsResult::Deopt | SyncSlotsResult::Unavailable => return JitProbe::Miss,
86    };
87
88    let key = TraceKey {
89        function,
90        entry_pc: pc as u32,
91        floats,
92    };
93    let Some((exit, spent, unwind)) = try_run_hot_tagged(
94        ctx,
95        vm.chunk_arc().as_ref(),
96        key,
97        &mut HotCall {
98            slots: &mut slots,
99            budget,
100            register_count,
101            metrics: None,
102            tags: EntryTags::from_vm(vm),
103        },
104    ) else {
105        return JitProbe::Miss;
106    };
107    finish_probe(vm, &slots, exit, spent, unwind)
108}
109
110fn try_jit_step_runtime(
111    vm: &mut Vm,
112    runtime: &JitRuntime,
113    budget: u32,
114    metrics: Option<&crate::scheduler::RuntimeMetrics>,
115) -> JitProbe {
116    if !runtime.matches_chunk(&vm.chunk_arc()) {
117        return JitProbe::Miss;
118    }
119    let Some(pc) = vm.current_pc() else {
120        return JitProbe::Miss;
121    };
122    let function = vm.current_function();
123    let Some(register_count) = vm.current_num_registers() else {
124        return JitProbe::Miss;
125    };
126
127    let mut slots = vec![0i64; slot_capacity(vm)];
128    let floats = match sync_slots_from_vm(vm, &mut slots) {
129        SyncSlotsResult::Ok => false,
130        SyncSlotsResult::Float => true,
131        SyncSlotsResult::Deopt => {
132            if let Some(m) = metrics {
133                crate::scheduler::RuntimeMetrics::inc(&m.jit_deopts);
134            }
135            return JitProbe::Miss;
136        }
137        SyncSlotsResult::Unavailable => return JitProbe::Miss,
138    };
139
140    let key = TraceKey {
141        function,
142        entry_pc: pc as u32,
143        floats,
144    };
145    let Some((exit, spent, unwind)) = try_run_hot_runtime_tagged(
146        runtime,
147        vm.chunk_arc().as_ref(),
148        key,
149        &mut HotCall {
150            slots: &mut slots,
151            budget,
152            register_count,
153            metrics,
154            tags: EntryTags::from_vm(vm),
155        },
156    ) else {
157        return JitProbe::Miss;
158    };
159    finish_probe(vm, &slots, exit, spent, unwind)
160}
161
162/// What one probe of the current `pc` did.
163enum JitProbe {
164    /// No compiled trace ran. The interpreter executes this instruction.
165    Miss,
166    /// A trace ran `spent` instructions. `stop` ends the quantum. `None`
167    /// means the interpreter still has to execute the instruction now at `pc`
168    /// (an effect the trace refused, or the instruction after a side exit).
169    Hit { spent: u32, stop: Option<VmResult> },
170}
171
172fn finish_probe(
173    vm: &mut Vm,
174    slots: &[i64],
175    exit: JitReturn,
176    spent: u32,
177    unwind: Option<JitUnwind>,
178) -> JitProbe {
179    if let Some(unwind) = unwind {
180        return match install_unwind(vm, slots, &exit, &unwind) {
181            Ok(()) => match exit.kind {
182                super::exit::JIT_TRAP => JitProbe::Hit {
183                    spent,
184                    stop: Some(VmResult::Trap(Fault::DivideByZero)),
185                },
186                JIT_BUDGET => JitProbe::Hit {
187                    spent,
188                    stop: Some(VmResult::Yield),
189                },
190                super::exit::JIT_RETURN => JitProbe::Hit {
191                    spent,
192                    stop: Some(VmResult::Trap(Fault::Invariant(
193                        "jit return left a call stack installed",
194                    ))),
195                },
196                _ => JitProbe::Hit { spent, stop: None },
197            },
198            Err(fault) => JitProbe::Hit {
199                spent,
200                stop: Some(VmResult::Trap(fault)),
201            },
202        };
203    }
204    let kind = exit.kind;
205    match apply_exit_tagged(vm, slots, exit) {
206        Ok(Some(result)) => JitProbe::Hit {
207            spent,
208            stop: Some(result),
209        },
210        Ok(None) if kind == JIT_BUDGET => JitProbe::Hit {
211            spent,
212            stop: Some(VmResult::Yield),
213        },
214        Ok(None) if kind == JIT_DEOPT => JitProbe::Miss,
215        Ok(None) => JitProbe::Hit { spent, stop: None },
216        Err(fault) => JitProbe::Hit {
217            spent,
218            stop: Some(VmResult::Trap(fault)),
219        },
220    }
221}
222
223/// Run at most `budget` instructions, retrying compiled traces after each
224/// interpreter step when a site becomes hot.
225pub fn run_vm_with_jit(vm: &mut Vm, budget: u32, ctx: &mut JitContext) -> VmResult {
226    run_vm_with_jit_loop(vm, budget, |vm, remaining| try_jit_step(vm, ctx, remaining))
227}
228
229/// Runtime path: shared cache, per-thread compilation module.
230pub fn run_vm_with_jit_runtime(
231    vm: &mut Vm,
232    budget: u32,
233    runtime: &JitRuntime,
234    metrics: Option<&crate::scheduler::RuntimeMetrics>,
235) -> VmResult {
236    run_vm_with_jit_loop(vm, budget, |vm, remaining| {
237        try_jit_step_runtime(vm, runtime, remaining, metrics)
238    })
239}
240
241fn run_vm_with_jit_loop(
242    vm: &mut Vm,
243    budget: u32,
244    mut try_step: impl FnMut(&mut Vm, u32) -> JitProbe,
245) -> VmResult {
246    let mut remaining = budget;
247    while remaining > 0 {
248        match try_step(vm, remaining) {
249            JitProbe::Hit { spent, stop } => {
250                let spent = spent.min(remaining);
251                vm.record_instructions(u64::from(spent));
252                remaining -= spent;
253                if let Some(result) = stop {
254                    return result;
255                }
256                if remaining == 0 {
257                    break;
258                }
259            }
260            JitProbe::Miss => {}
261        }
262        // `vm.run(1)` returns `Yield` both when its one-instruction slice
263        // ends and when the bytecode itself executes `Yield`. Only the
264        // opcode hands the flow back to the scheduler; the slice end stays
265        // inside this quantum.
266        let pc_before = vm.current_pc();
267        match vm.run(1) {
268            VmResult::Yield if explicit_yield(vm, pc_before) => return VmResult::Yield,
269            VmResult::Yield => {
270                remaining -= 1;
271            }
272            other => return other,
273        }
274    }
275    VmResult::Yield
276}
277
278/// `true` when the instruction just interpreted was `Opcode::Yield`.
279///
280/// `fetch` advances the pc before the opcode runs, so the executed word is
281/// the one at `pc_before`, not the pc the VM holds now.
282fn explicit_yield(vm: &Vm, pc_before: Option<usize>) -> bool {
283    let Some(pc) = pc_before else {
284        return false;
285    };
286    vm.chunk_arc()
287        .code
288        .get(pc)
289        .is_some_and(|instr| instr.op == Opcode::Yield)
290}
291
292fn slot_capacity(vm: &Vm) -> usize {
293    let chunk = vm.chunk_arc();
294    let max_in_chunk = chunk
295        .functions
296        .iter()
297        .map(|f| f.num_registers as usize)
298        .max();
299    match (max_in_chunk, vm.current_num_registers()) {
300        (Some(max_regs), Some(current)) => max_regs.max(current as usize),
301        (Some(max_regs), None) => max_regs,
302        (None, Some(current)) => current as usize,
303        (None, None) => 0,
304    }
305}
306
307/// Run a compiled trace against the shadow slot table.
308///
309/// Inherited `Move`s are written back as `Int`. The VM entry path records
310/// the real `Bool` and `Unit` bits before calling the trace.
311pub fn run_compiled_trace(
312    entry: super::frame::JitEntry,
313    slots: &mut [i64],
314    pc: u32,
315    budget: u32,
316    function: u32,
317    register_count: u32,
318) -> JitReturn {
319    run_compiled_trace_with_tags(
320        entry,
321        slots,
322        pc,
323        budget,
324        function,
325        register_count,
326        EntryTags::INT,
327    )
328    .0
329}
330
331fn run_compiled_trace_with_tags(
332    entry: super::frame::JitEntry,
333    slots: &mut [i64],
334    pc: u32,
335    budget: u32,
336    function: u32,
337    register_count: u32,
338    tags: EntryTags,
339) -> (JitReturn, u32, Option<JitUnwind>) {
340    let mut call_stack = [JitCallRecord {
341        return_pc: 0,
342        return_function: 0,
343        dest_reg: 0,
344        caller_register_count: 0,
345        written: [0; 4],
346        as_bool: [0; 4],
347        as_unit: [0; 4],
348    }; MAX_JIT_CALL_DEPTH];
349    let stride = slots.len();
350    let mut spill = vec![0i64; stride.saturating_mul(MAX_JIT_CALL_DEPTH)];
351    let mut frame = JitFrame {
352        slots: slots.as_mut_ptr(),
353        register_count,
354        pc,
355        budget,
356        function,
357        exit_kind: 0,
358        return_reg: 0,
359        call_depth: 0,
360        call_stack: call_stack.as_mut_ptr(),
361        spill: spill.as_mut_ptr(),
362        spill_stride: stride as u32,
363        written: [0; 4],
364        as_bool: [0; 4],
365        as_unit: [0; 4],
366        entry_as_bool: tags.as_bool,
367        entry_as_unit: tags.as_unit,
368        as_float: [0; 4],
369        entry_as_float: tags.as_float,
370    };
371    unsafe { (entry)(&mut frame) };
372    let spent = budget.saturating_sub(frame.budget);
373    let ret = JitReturn {
374        kind: frame.exit_kind,
375        pc: frame.pc,
376        return_reg: frame.return_reg,
377        written: frame.written,
378        as_bool: frame.as_bool,
379        as_unit: frame.as_unit,
380        as_float: frame.as_float,
381    };
382    let depth = frame.call_depth as usize;
383    let unwind = if depth == 0 || depth > call_stack.len() {
384        None
385    } else {
386        let stride = slots.len();
387        let spill_len = stride.saturating_mul(depth);
388        let spill_len = spill_len.min(spill.len());
389        Some(JitUnwind {
390            records: call_stack[..depth].to_vec(),
391            spill: spill[..spill_len].to_vec(),
392            stride,
393            function: frame.function,
394            register_count: frame.register_count,
395        })
396    };
397    (ret, spent, unwind)
398}
399
400/// Frames a trace left on its private call stack. Index 0 is the VM frame
401/// that entered the trace. The live slots are the frame after these records.
402struct JitUnwind {
403    records: Vec<JitCallRecord>,
404    spill: Vec<i64>,
405    stride: usize,
406    function: u32,
407    register_count: u32,
408}
409
410fn install_unwind(
411    vm: &mut Vm,
412    slots: &[i64],
413    ret: &JitReturn,
414    unwind: &JitUnwind,
415) -> Result<(), Fault> {
416    let Some(caller) = unwind.records.first() else {
417        return Err(Fault::Invariant("jit unwind without a caller"));
418    };
419    let mut frames = Vec::with_capacity(unwind.records.len());
420    for index in 1..unwind.records.len() {
421        let rec = &unwind.records[index];
422        let dest = dest_reg(unwind.records[index - 1].dest_reg)?;
423        frames.push(suspended(unwind, index, rec, dest)?);
424    }
425    let dest = dest_reg(
426        unwind
427            .records
428            .last()
429            .ok_or(Fault::Invariant("jit unwind without a caller"))?
430            .dest_reg,
431    )?;
432    frames.push(live_frame(slots, ret, unwind, dest)?);
433    let window = spill_window(unwind, 0)?;
434    let updates = written_updates(
435        window,
436        caller.caller_register_count as usize,
437        &caller.written,
438        &caller.as_bool,
439        &caller.as_unit,
440        &[0; 4],
441    );
442    vm.install_jit_frames(caller.return_pc as usize, &updates, frames)
443}
444
445fn suspended(
446    unwind: &JitUnwind,
447    index: usize,
448    rec: &JitCallRecord,
449    dest: u8,
450) -> Result<(u32, u8, usize, Vec<Value>), Fault> {
451    let count = register_len(rec.caller_register_count)?;
452    let window = spill_window(unwind, index)?;
453    let registers = frame_values(
454        window,
455        count,
456        &rec.written,
457        &rec.as_bool,
458        &rec.as_unit,
459        &[0; 4],
460    );
461    Ok((rec.return_function, dest, rec.return_pc as usize, registers))
462}
463
464fn live_frame(
465    slots: &[i64],
466    ret: &JitReturn,
467    unwind: &JitUnwind,
468    dest: u8,
469) -> Result<(u32, u8, usize, Vec<Value>), Fault> {
470    let count = register_len(unwind.register_count)?;
471    let registers = frame_values(
472        slots,
473        count,
474        &ret.written,
475        &ret.as_bool,
476        &ret.as_unit,
477        &ret.as_float,
478    );
479    Ok((unwind.function, dest, ret.pc as usize, registers))
480}
481
482fn spill_window(unwind: &JitUnwind, index: usize) -> Result<&[i64], Fault> {
483    let start = index
484        .checked_mul(unwind.stride)
485        .ok_or(Fault::Invariant("jit spill index overflow"))?;
486    let end = start
487        .checked_add(unwind.stride)
488        .ok_or(Fault::Invariant("jit spill index overflow"))?;
489    unwind
490        .spill
491        .get(start..end)
492        .ok_or(Fault::Invariant("jit spill is shorter than its call stack"))
493}
494
495fn dest_reg(raw: u32) -> Result<u8, Fault> {
496    u8::try_from(raw).map_err(|_| Fault::Invariant("jit dest register does not fit"))
497}
498
499fn register_len(raw: u32) -> Result<usize, Fault> {
500    let count = usize::try_from(raw).map_err(|_| Fault::Invariant("jit register count"))?;
501    if count > usize::from(u8::MAX) {
502        return Err(Fault::Invariant("jit frame is wider than a register file"));
503    }
504    Ok(count)
505}
506
507fn written_updates(
508    window: &[i64],
509    count: usize,
510    written: &[u64; 4],
511    as_bool: &[u64; 4],
512    as_unit: &[u64; 4],
513    as_float: &[u64; 4],
514) -> Vec<(u8, Value)> {
515    let mut out = Vec::new();
516    for index in 0..count.min(window.len()).min(256) {
517        if !tag_bit(written, index) {
518            continue;
519        }
520        let Some(reg) = u8::try_from(index).ok() else {
521            break;
522        };
523        let Some(bits) = window.get(index).copied() else {
524            break;
525        };
526        out.push((reg, tagged_value(bits, index, as_bool, as_unit, as_float)));
527    }
528    out
529}
530
531fn frame_values(
532    window: &[i64],
533    count: usize,
534    written: &[u64; 4],
535    as_bool: &[u64; 4],
536    as_unit: &[u64; 4],
537    as_float: &[u64; 4],
538) -> Vec<Value> {
539    let mut registers = vec![Value::Unit; count];
540    for (index, reg) in registers.iter_mut().enumerate() {
541        if !tag_bit(written, index) {
542            continue;
543        }
544        let Some(bits) = window.get(index).copied() else {
545            continue;
546        };
547        *reg = tagged_value(bits, index, as_bool, as_unit, as_float);
548    }
549    registers
550}
551
552fn tagged_value(
553    bits: i64,
554    index: usize,
555    as_bool: &[u64; 4],
556    as_unit: &[u64; 4],
557    as_float: &[u64; 4],
558) -> Value {
559    if tag_bit(as_unit, index) {
560        Value::Unit
561    } else if tag_bit(as_bool, index) {
562        Value::Bool(bits != 0)
563    } else if tag_bit(as_float, index) {
564        Value::Float(f64::from_bits(bits as u64))
565    } else {
566        Value::Int(bits)
567    }
568}
569
570/// Run a cached trace by reference.
571pub fn run_compiled_trace_ref(
572    trace: &CompiledTrace,
573    slots: &mut [i64],
574    pc: u32,
575    budget: u32,
576    function: u32,
577    register_count: u32,
578) -> JitReturn {
579    run_compiled_trace(trace.entry, slots, pc, budget, function, register_count)
580}
581
582struct HotCall<'a> {
583    slots: &'a mut [i64],
584    budget: u32,
585    register_count: u8,
586    metrics: Option<&'a crate::scheduler::RuntimeMetrics>,
587    tags: EntryTags,
588}
589
590/// Compile `key` if needed and execute once. Returns `None` when compilation
591/// fails (caller should fall back to the interpreter).
592pub fn try_run_hot(
593    ctx: &mut JitContext,
594    chunk: &Chunk,
595    key: TraceKey,
596    slots: &mut [i64],
597    budget: u32,
598    register_count: u8,
599    metrics: Option<&crate::scheduler::RuntimeMetrics>,
600) -> Option<ExitReason> {
601    try_run_hot_tagged(
602        ctx,
603        chunk,
604        key,
605        &mut HotCall {
606            slots,
607            budget,
608            register_count,
609            metrics,
610            tags: EntryTags::INT,
611        },
612    )
613    .and_then(|(ret, _, unwind)| {
614        if unwind.is_some() {
615            None
616        } else {
617            Some(ret.into_reason())
618        }
619    })
620}
621
622fn try_run_hot_tagged(
623    ctx: &mut JitContext,
624    chunk: &Chunk,
625    key: TraceKey,
626    call: &mut HotCall<'_>,
627) -> Option<(JitReturn, u32, Option<JitUnwind>)> {
628    if ctx.cache.get(&key).is_none() {
629        if !ctx.hot.hit(key, ctx.hot_threshold) {
630            if let Some(m) = call.metrics {
631                crate::scheduler::RuntimeMetrics::inc(&m.jit_misses);
632            }
633            return None;
634        }
635        let mut compiler = TraceCompiler::new(ctx.module_mut());
636        match compiler.compile_trace(chunk, key) {
637            Ok(compiled) => {
638                ctx.cache.insert(key, compiled);
639                if let Some(m) = call.metrics {
640                    crate::scheduler::RuntimeMetrics::inc(&m.jit_compiles);
641                }
642            }
643            Err(_) => {
644                if let Some(m) = call.metrics {
645                    crate::scheduler::RuntimeMetrics::inc(&m.jit_compile_failures);
646                }
647                return None;
648            }
649        }
650    }
651    let trace = ctx.cache.get(&key)?;
652    if let Some(m) = call.metrics {
653        crate::scheduler::RuntimeMetrics::inc(&m.jit_executions);
654    }
655    Some(run_compiled_trace_with_tags(
656        trace.entry,
657        call.slots,
658        key.entry_pc,
659        call.budget,
660        key.function,
661        u32::from(call.register_count),
662        call.tags,
663    ))
664}
665
666/// Shared-runtime variant (no global lock during execution).
667pub fn try_run_hot_runtime(
668    runtime: &JitRuntime,
669    chunk: &Chunk,
670    key: TraceKey,
671    slots: &mut [i64],
672    budget: u32,
673    register_count: u8,
674    metrics: Option<&crate::scheduler::RuntimeMetrics>,
675) -> Option<ExitReason> {
676    try_run_hot_runtime_tagged(
677        runtime,
678        chunk,
679        key,
680        &mut HotCall {
681            slots,
682            budget,
683            register_count,
684            metrics,
685            tags: EntryTags::INT,
686        },
687    )
688    .and_then(|(ret, _, unwind)| {
689        if unwind.is_some() {
690            None
691        } else {
692            Some(ret.into_reason())
693        }
694    })
695}
696
697fn try_run_hot_runtime_tagged(
698    runtime: &JitRuntime,
699    chunk: &Chunk,
700    key: TraceKey,
701    call: &mut HotCall<'_>,
702) -> Option<(JitReturn, u32, Option<JitUnwind>)> {
703    if let Some(copy) = runtime.get_trace(&key) {
704        if let Some(m) = call.metrics {
705            crate::scheduler::RuntimeMetrics::inc(&m.jit_executions);
706        }
707        return Some(run_compiled_trace_with_tags(
708            copy.entry,
709            call.slots,
710            key.entry_pc,
711            call.budget,
712            key.function,
713            u32::from(call.register_count),
714            call.tags,
715        ));
716    }
717
718    if !runtime.record_hot_hit(key) {
719        if let Some(m) = call.metrics {
720            crate::scheduler::RuntimeMetrics::inc(&m.jit_misses);
721        }
722        return None;
723    }
724
725    // Double-checked compile after hot threshold.
726    if runtime.get_trace(&key).is_some() {
727        return try_run_hot_runtime_tagged(runtime, chunk, key, call);
728    }
729
730    let compiled =
731        match with_jit_module(|module| TraceCompiler::new(module).compile_trace(chunk, key)) {
732            Ok(trace) => trace,
733            Err(_) => {
734                if let Some(m) = call.metrics {
735                    crate::scheduler::RuntimeMetrics::inc(&m.jit_compile_failures);
736                }
737                return None;
738            }
739        };
740
741    runtime.insert_trace(key, compiled);
742    if let Some(m) = call.metrics {
743        crate::scheduler::RuntimeMetrics::inc(&m.jit_compiles);
744    }
745
746    try_run_hot_runtime_tagged(runtime, chunk, key, call)
747}
748
749fn tag_bit(words: &[u64; 4], reg: usize) -> bool {
750    if reg >= 256 {
751        return false;
752    }
753    words[reg / 64] & (1u64 << (reg % 64)) != 0
754}
755
756/// Write back only registers the trace assigned. Untouched `Unit` / `Bool`
757/// values stay as they were. A `Move` of either tag is written back as that
758/// tag. Comparison results come back as `Bool`.
759fn sync_slots_tagged(vm: &mut Vm, slots: &[i64], ret: &JitReturn) -> Result<(), Fault> {
760    let Some(regs) = vm.top_registers_mut() else {
761        return Err(Fault::Invariant("empty frame stack while syncing slots"));
762    };
763    for (index, reg) in regs.iter_mut().enumerate() {
764        if !tag_bit(&ret.written, index) {
765            continue;
766        }
767        let Some(slot) = slots.get(index).copied() else {
768            continue;
769        };
770        *reg = if tag_bit(&ret.as_unit, index) {
771            Value::Unit
772        } else if tag_bit(&ret.as_bool, index) {
773            Value::Bool(slot != 0)
774        } else if tag_bit(&ret.as_float, index) {
775            Value::Float(f64::from_bits(slot as u64))
776        } else {
777            Value::Int(slot)
778        };
779    }
780    Ok(())
781}
782
783fn apply_exit_tagged(
784    vm: &mut Vm,
785    slots: &[i64],
786    ret: JitReturn,
787) -> Result<Option<VmResult>, Fault> {
788    match ret.kind {
789        super::exit::JIT_RETURN => {
790            sync_slots_tagged(vm, slots, &ret)?;
791            let return_reg = ret.return_reg as u8;
792            let value = match vm
793                .top_registers()
794                .and_then(|regs| regs.get(usize::from(return_reg)))
795            {
796                Some(v) => v.clone(),
797                None => {
798                    let frame_size = match vm.current_num_registers() {
799                        Some(n) => n,
800                        None => 0,
801                    };
802                    return Err(Fault::RegisterOutOfRange {
803                        reg: return_reg,
804                        frame_size,
805                    });
806                }
807            };
808            let pc = vm
809                .current_pc()
810                .ok_or(Fault::Invariant("empty frame stack while running"))?;
811            vm.set_pc(pc.saturating_add(1));
812            vm.return_value(value)
813        }
814        super::exit::JIT_TRAP => {
815            vm.set_pc(ret.pc as usize);
816            Ok(Some(VmResult::Trap(Fault::DivideByZero)))
817        }
818        super::exit::JIT_BUDGET => {
819            vm.set_pc(ret.pc as usize);
820            sync_slots_tagged(vm, slots, &ret)?;
821            Ok(None)
822        }
823        super::exit::JIT_CONTINUE | super::exit::JIT_EFFECT => {
824            vm.set_pc(ret.pc as usize);
825            sync_slots_tagged(vm, slots, &ret)?;
826            Ok(None)
827        }
828        _ => {
829            vm.set_pc(ret.pc as usize);
830            Ok(None)
831        }
832    }
833}
834
835/// Apply a native trace exit to a live [`Vm`], producing an optional early
836/// [`VmResult`] when the trace finished the flow.
837pub fn apply_exit_to_vm(
838    vm: &mut Vm,
839    slots: &[i64],
840    exit: ExitReason,
841) -> Result<Option<VmResult>, Fault> {
842    match exit {
843        ExitReason::Return { return_reg } => {
844            let Some(bits) = slots.get(usize::from(return_reg)).copied() else {
845                return Err(Fault::RegisterOutOfRange {
846                    reg: return_reg,
847                    frame_size: u8::try_from(slots.len()).unwrap_or(u8::MAX),
848                });
849            };
850            let value = Value::Int(bits);
851            vm.set_register(return_reg, value.clone())?;
852            let pc = vm
853                .current_pc()
854                .ok_or(Fault::Invariant("empty frame stack while running"))?;
855            vm.set_pc(pc.saturating_add(1));
856            vm.return_value(value)
857        }
858        ExitReason::Trap { pc } => {
859            vm.set_pc(pc as usize);
860            Ok(Some(VmResult::Trap(Fault::DivideByZero)))
861        }
862        ExitReason::Budget { pc } => {
863            vm.set_pc(pc as usize);
864            sync_slots_to_vm(vm, slots)?;
865            Ok(None)
866        }
867        ExitReason::Continue { pc } | ExitReason::Effect { pc } | ExitReason::Deopt { pc } => {
868            vm.set_pc(pc as usize);
869            if matches!(
870                exit,
871                ExitReason::Continue { .. } | ExitReason::Effect { .. }
872            ) {
873                sync_slots_to_vm(vm, slots)?;
874            }
875            Ok(None)
876        }
877    }
878}
879
880/// Copy int-compatible registers from the VM into JIT shadow slots.
881pub fn sync_slots_from_vm(vm: &Vm, slots: &mut [i64]) -> SyncSlotsResult {
882    let Some(regs) = vm.top_registers() else {
883        return SyncSlotsResult::Unavailable;
884    };
885    let mut saw_float = false;
886    let mut saw_int = false;
887    for value in regs.iter().take(slots.len()) {
888        match value {
889            Value::Int(_) => saw_int = true,
890            Value::Float(_) => saw_float = true,
891            Value::Bool(_) | Value::Unit => {}
892            _ => return SyncSlotsResult::Deopt,
893        }
894    }
895    if saw_int && saw_float {
896        return SyncSlotsResult::Deopt;
897    }
898    for (slot, value) in slots.iter_mut().zip(regs.iter()) {
899        *slot = match value {
900            Value::Int(i) => *i,
901            Value::Bool(b) => i64::from(*b),
902            Value::Unit => 0,
903            Value::Float(n) => n.to_bits() as i64,
904            _ => 0,
905        };
906    }
907    if saw_float {
908        SyncSlotsResult::Float
909    } else {
910        SyncSlotsResult::Ok
911    }
912}
913
914/// Write JIT shadow slots back into the active VM register file.
915pub fn sync_slots_to_vm(vm: &mut Vm, slots: &[i64]) -> Result<(), Fault> {
916    let Some(regs) = vm.top_registers_mut() else {
917        return Err(Fault::Invariant("empty frame stack while syncing slots"));
918    };
919    for (reg, slot) in regs.iter_mut().zip(slots.iter()) {
920        *reg = Value::Int(*slot);
921    }
922    Ok(())
923}
924
925/// Threshold at which a `(function, pc)` pair becomes a compilation candidate.
926pub const fn hot_threshold() -> u32 {
927    HOT_THRESHOLD
928}
929
930/// Force-compile a trace (tests / benchmarks).
931pub fn force_compile(
932    ctx: &mut JitContext,
933    chunk: &Chunk,
934    key: TraceKey,
935) -> Result<(), super::error::CompileError> {
936    if ctx.cache.get(&key).is_none() {
937        let mut compiler = TraceCompiler::new(ctx.module_mut());
938        let compiled = compiler.compile_trace(chunk, key)?;
939        ctx.cache.insert(key, compiled);
940    }
941    Ok(())
942}
943
944#[cfg(test)]
945mod tests {
946    use std::sync::Arc;
947
948    use crate::{
949        bytecode::builder::ChunkBuilder, FlowOutcome, NativeTable, Opcode, Runtime, Value, Vm,
950        VmResult,
951    };
952
953    use super::*;
954    use crate::jit::trace::{JitContext, TraceKey};
955
956    type TestResult = Result<(), Box<dyn std::error::Error>>;
957
958    fn add_chunk() -> std::sync::Arc<crate::Chunk> {
959        let mut b = ChunkBuilder::new("jit-add");
960        b.begin_function("main", 0, 3);
961        b.emit_load_imm(0, 41);
962        b.emit_load_imm(1, 1);
963        b.emit_binop(Opcode::Add, 2, 0, 1);
964        b.emit_return(2);
965        Arc::new(b.finish())
966    }
967
968    #[test]
969    fn run_vm_with_jit_completes_scalar_add() -> TestResult {
970        let chunk = add_chunk();
971        let mut ctx = JitContext::new(chunk.clone())?;
972        let key = TraceKey {
973            function: 0,
974            entry_pc: 0,
975
976            floats: false,
977        };
978        force_compile(&mut ctx, &chunk, key)?;
979
980        let mut vm = Vm::new(chunk, NativeTable::empty(), 0, &[])?;
981        let result = run_vm_with_jit(&mut vm, 10_000, &mut ctx);
982        assert!(matches!(result, VmResult::Complete(Value::Int(42))));
983        Ok(())
984    }
985
986    #[test]
987    fn native_trace_computes_42() -> TestResult {
988        let chunk = add_chunk();
989        let mut ctx = JitContext::new(chunk.clone())?;
990        let key = TraceKey {
991            function: 0,
992            entry_pc: 0,
993
994            floats: false,
995        };
996        force_compile(&mut ctx, &chunk, key)?;
997        let trace = ctx
998            .cache
999            .get(&key)
1000            .ok_or("trace missing after force_compile")?;
1001        let mut slots = vec![0i64; 3];
1002        let ret = run_compiled_trace_ref(trace, &mut slots, 0, 10_000, 0, 3);
1003        let exit = ret.into_reason();
1004        assert!(matches!(exit, ExitReason::Return { return_reg: 2 }));
1005        assert_eq!(slots[2], 42);
1006        Ok(())
1007    }
1008
1009    #[test]
1010    fn mul_imm_eq_imm_and_shifts_match_the_interpreter() -> TestResult {
1011        let mut b = ChunkBuilder::new("jit-bits");
1012        b.begin_function("main", 0, 4);
1013        b.emit_load_imm(0, 6);
1014        b.emit_mul_imm(1, 0, 7);
1015        b.emit_load_imm(2, 1);
1016        b.emit_bit_binop(Opcode::Shl, 3, 1, 2);
1017        b.emit_bit_binop(Opcode::Shr, 1, 3, 2);
1018        b.emit_return(1);
1019        let chunk = Arc::new(b.finish());
1020        let mut interpreted = Vm::new(chunk.clone(), NativeTable::empty(), 0, &[])?;
1021        assert!(matches!(
1022            interpreted.run(20),
1023            VmResult::Complete(Value::Int(42))
1024        ));
1025        let mut ctx = JitContext::new(chunk.clone())?;
1026        let key = TraceKey {
1027            function: 0,
1028            entry_pc: 0,
1029            floats: false,
1030        };
1031        force_compile(&mut ctx, &chunk, key)?;
1032        let mut vm = Vm::new(chunk, NativeTable::empty(), 0, &[])?;
1033        let result = run_vm_with_jit(&mut vm, 20, &mut ctx);
1034        assert!(matches!(result, VmResult::Complete(Value::Int(42))));
1035
1036        let mut b = ChunkBuilder::new("jit-eq-imm");
1037        b.begin_function("main", 0, 2);
1038        b.emit_load_imm(0, 42);
1039        b.emit_eq_imm(1, 0, 42);
1040        b.emit_le_imm(0, 0, 41);
1041        b.emit_return(1);
1042        let chunk = Arc::new(b.finish());
1043        let mut interpreted = Vm::new(chunk.clone(), NativeTable::empty(), 0, &[])?;
1044        assert!(matches!(
1045            interpreted.run(20),
1046            VmResult::Complete(Value::Bool(true))
1047        ));
1048        let mut ctx = JitContext::new(chunk.clone())?;
1049        force_compile(&mut ctx, &chunk, key)?;
1050        let mut vm = Vm::new(chunk, NativeTable::empty(), 0, &[])?;
1051        let result = run_vm_with_jit(&mut vm, 20, &mut ctx);
1052        assert!(matches!(result, VmResult::Complete(Value::Bool(true))));
1053        Ok(())
1054    }
1055
1056    #[test]
1057    fn jit_matches_interpreter_on_scalar_add() -> TestResult {
1058        let chunk = add_chunk();
1059        let rt = Runtime::new((*chunk).clone())?;
1060        let interp = rt.spawn(0, &[])?.join();
1061        rt.shutdown();
1062        assert!(matches!(interp, FlowOutcome::Completed(Value::Int(42))));
1063
1064        let mut ctx = JitContext::new(chunk.clone())?;
1065        let key = TraceKey {
1066            function: 0,
1067            entry_pc: 0,
1068
1069            floats: false,
1070        };
1071        let mut slots = vec![0i64; 3];
1072        force_compile(&mut ctx, &chunk, key)?;
1073        let trace = ctx
1074            .cache
1075            .get(&key)
1076            .ok_or("trace missing after force_compile")?;
1077        let exit = run_compiled_trace_ref(trace, &mut slots, 0, 10_000, 0, 3).into_reason();
1078        assert!(matches!(exit, ExitReason::Return { return_reg: 2 }));
1079        assert_eq!(slots[2], 42);
1080
1081        let mut vm = Vm::new(chunk, NativeTable::empty(), 0, &[])?;
1082        if let Some(result) = apply_exit_to_vm(&mut vm, &slots, exit)? {
1083            assert!(matches!(result, VmResult::Complete(Value::Int(42))));
1084        } else {
1085            return Err("expected Completed(42)".into());
1086        }
1087        Ok(())
1088    }
1089
1090    #[test]
1091    fn div_by_zero_returns_trap_exit() -> TestResult {
1092        let mut b = ChunkBuilder::new("jit-div0");
1093        b.begin_function("main", 0, 3);
1094        b.emit_load_imm(0, 1);
1095        b.emit_load_imm(1, 0);
1096        b.emit_binop(Opcode::Div, 2, 0, 1);
1097        b.emit_return(2);
1098        let chunk = Arc::new(b.finish());
1099
1100        let mut ctx = JitContext::new(chunk.clone())?;
1101        let key = TraceKey {
1102            function: 0,
1103            entry_pc: 0,
1104
1105            floats: false,
1106        };
1107        force_compile(&mut ctx, &chunk, key)?;
1108        let trace = ctx
1109            .cache
1110            .get(&key)
1111            .ok_or("trace missing after force_compile")?;
1112        let mut slots = vec![0i64; 3];
1113        let ret = run_compiled_trace_ref(trace, &mut slots, 0, 10_000, 0, 3);
1114        assert!(matches!(ret.into_reason(), ExitReason::Trap { .. }));
1115        Ok(())
1116    }
1117
1118    #[test]
1119    fn div_and_mod_of_i64_min_wrap_instead_of_aborting() -> TestResult {
1120        let mut b = ChunkBuilder::new("jit-div-overflow");
1121        b.begin_function("div", 0, 3);
1122        let min = b.const_(Value::Int(i64::MIN));
1123        let neg = b.const_(Value::Int(-1));
1124        b.emit_load_const(0, min);
1125        b.emit_load_const(1, neg);
1126        b.emit_binop(Opcode::Div, 2, 0, 1);
1127        b.emit_return(2);
1128        let rem = b.begin_function("rem", 0, 3);
1129        let min = b.const_(Value::Int(i64::MIN));
1130        let neg = b.const_(Value::Int(-1));
1131        b.emit_load_const(0, min);
1132        b.emit_load_const(1, neg);
1133        b.emit_binop(Opcode::Mod, 2, 0, 1);
1134        b.emit_return(2);
1135        let chunk = Arc::new(b.finish());
1136        let mut ctx = JitContext::new(chunk.clone())?;
1137
1138        for (function, expect) in [(0, i64::MIN), (rem, 0)] {
1139            let entry = chunk.functions[function as usize].entry;
1140            force_compile(
1141                &mut ctx,
1142                &chunk,
1143                TraceKey {
1144                    function,
1145                    entry_pc: entry,
1146
1147                    floats: false,
1148                },
1149            )?;
1150            let mut vm = Vm::new(chunk.clone(), NativeTable::empty(), function, &[])?;
1151            let result = run_vm_with_jit(&mut vm, 10_000, &mut ctx);
1152            match result {
1153                VmResult::Complete(Value::Int(n)) if n == expect => {}
1154                other => {
1155                    return Err(format!("function {function} finished as {other:?}").into());
1156                }
1157            }
1158        }
1159        Ok(())
1160    }
1161
1162    #[test]
1163    fn sync_slots_accepts_a_float_register() -> TestResult {
1164        let chunk = add_chunk();
1165        let mut vm = Vm::new(chunk, NativeTable::empty(), 0, &[])?;
1166        vm.set_register(0, Value::Float(1.0))?;
1167        let mut slots = vec![0i64; 3];
1168        assert_eq!(sync_slots_from_vm(&vm, &mut slots), SyncSlotsResult::Float);
1169        assert_eq!(f64::from_bits(slots[0] as u64), 1.0);
1170        Ok(())
1171    }
1172
1173    #[test]
1174    fn float_trace_matches_the_interpreter() -> TestResult {
1175        let mut b = ChunkBuilder::new("jit-float");
1176        let zero = b.const_(Value::Float(0.0));
1177        let one = b.const_(Value::Float(1.0));
1178        let limit = b.const_(Value::Float(4.0));
1179        b.begin_function("main", 0, 4);
1180        b.emit_load_const(0, zero);
1181        b.emit_load_const(1, one);
1182        b.emit_load_const(2, limit);
1183        let head = b.new_label();
1184        let done = b.new_label();
1185        b.bind_label(head);
1186        b.emit_binop(Opcode::Add, 0, 0, 1);
1187        b.emit_binop(Opcode::Lt, 3, 0, 2);
1188        b.emit_branch(3, done);
1189        b.emit_jump(head);
1190        b.bind_label(done);
1191        b.emit_return(0);
1192        let chunk = Arc::new(b.finish());
1193        let mut plain = Vm::new(Arc::clone(&chunk), NativeTable::empty(), 0, &[])?;
1194        let interpreted = plain.run(100);
1195        let mut ctx = JitContext::new(Arc::clone(&chunk))?;
1196        ctx.hot_threshold = 1;
1197        let mut vm = Vm::new(chunk, NativeTable::empty(), 0, &[])?;
1198        let compiled = run_vm_with_jit(&mut vm, 100, &mut ctx);
1199        if !ctx.cache.has_float_trace() {
1200            return Err("float add loop was not compiled".into());
1201        }
1202        match (interpreted, compiled) {
1203            (VmResult::Complete(Value::Float(a)), VmResult::Complete(Value::Float(b)))
1204                if a == b && a == 4.0 =>
1205            {
1206                Ok(())
1207            }
1208            (left, right) => Err(format!("float trace {right:?} interpreter {left:?}").into()),
1209        }
1210    }
1211
1212    fn run_float_chunk(
1213        chunk: Arc<Chunk>,
1214        budget: u32,
1215    ) -> Result<(VmResult, VmResult, JitContext), Box<dyn std::error::Error>> {
1216        let mut plain = Vm::new(Arc::clone(&chunk), NativeTable::empty(), 0, &[])?;
1217        let interpreted = plain.run(budget);
1218        let mut ctx = JitContext::new(Arc::clone(&chunk))?;
1219        ctx.hot_threshold = 1;
1220        let mut vm = Vm::new(chunk, NativeTable::empty(), 0, &[])?;
1221        let compiled = run_vm_with_jit(&mut vm, budget, &mut ctx);
1222        Ok((interpreted, compiled, ctx))
1223    }
1224
1225    #[test]
1226    fn float_trace_edges_match_the_interpreter() -> TestResult {
1227        let mut nan_lt = ChunkBuilder::new("jit-nan-lt");
1228        let nan = nan_lt.const_(Value::Float(f64::NAN));
1229        let zero = nan_lt.const_(Value::Float(0.0));
1230        nan_lt.begin_function("main", 0, 3);
1231        nan_lt.emit_load_const(0, nan);
1232        nan_lt.emit_load_const(1, zero);
1233        let head = nan_lt.new_label();
1234        nan_lt.bind_label(head);
1235        nan_lt.emit_binop(Opcode::Lt, 2, 0, 1);
1236        nan_lt.emit_return(2);
1237        let nan_chunk = Arc::new(nan_lt.finish());
1238        let (interpreted, compiled, ctx) = run_float_chunk(Arc::clone(&nan_chunk), 20)?;
1239        if !ctx.cache.has_float_trace() {
1240            return Err("NaN comparison was not compiled".into());
1241        }
1242        match (interpreted, compiled) {
1243            (VmResult::Complete(Value::Bool(false)), VmResult::Complete(Value::Bool(false))) => {}
1244            (left, right) => {
1245                return Err(format!("nan lt {right:?} interpreter {left:?}").into());
1246            }
1247        }
1248
1249        let mut inf_add = ChunkBuilder::new("jit-inf-add");
1250        let pos = inf_add.const_(Value::Float(f64::INFINITY));
1251        let neg = inf_add.const_(Value::Float(f64::NEG_INFINITY));
1252        inf_add.begin_function("main", 0, 3);
1253        inf_add.emit_load_const(0, pos);
1254        inf_add.emit_load_const(1, neg);
1255        let head = inf_add.new_label();
1256        inf_add.bind_label(head);
1257        inf_add.emit_binop(Opcode::Add, 2, 0, 1);
1258        inf_add.emit_return(2);
1259        let inf_chunk = Arc::new(inf_add.finish());
1260        let (interpreted, compiled, ctx) = run_float_chunk(Arc::clone(&inf_chunk), 20)?;
1261        if !ctx.cache.has_float_trace() {
1262            return Err("infinity add was not compiled".into());
1263        }
1264        match (interpreted, compiled) {
1265            (VmResult::Complete(Value::Float(a)), VmResult::Complete(Value::Float(b)))
1266                if a.is_nan() && b.is_nan() => {}
1267            (left, right) => {
1268                return Err(format!("inf add {right:?} interpreter {left:?}").into());
1269            }
1270        }
1271
1272        let mut zeros = ChunkBuilder::new("jit-signed-zero");
1273        let neg_zero = zeros.const_(Value::Float(-0.0));
1274        zeros.begin_function("main", 0, 1);
1275        zeros.emit_load_const(0, neg_zero);
1276        let head = zeros.new_label();
1277        zeros.bind_label(head);
1278        zeros.emit_add_imm(0, 0, 0);
1279        zeros.emit_return(0);
1280        let zero_chunk = Arc::new(zeros.finish());
1281        let (interpreted, compiled, ctx) = run_float_chunk(Arc::clone(&zero_chunk), 20)?;
1282        if !ctx.cache.has_float_trace() {
1283            return Err("signed-zero add was not compiled".into());
1284        }
1285        match (interpreted, compiled) {
1286            (VmResult::Complete(Value::Float(a)), VmResult::Complete(Value::Float(b)))
1287                if a.to_bits() == 0.0f64.to_bits() && b.to_bits() == 0.0f64.to_bits() => {}
1288            (left, right) => {
1289                return Err(format!("signed zero {right:?} interpreter {left:?}").into());
1290            }
1291        }
1292
1293        let mut countdown = ChunkBuilder::new("jit-sub-imm");
1294        let start = countdown.const_(Value::Float(4.0));
1295        countdown.begin_function("main", 0, 2);
1296        countdown.emit_load_const(0, start);
1297        let head = countdown.new_label();
1298        let body = countdown.new_label();
1299        let done = countdown.new_label();
1300        countdown.bind_label(head);
1301        countdown.emit_lt_imm(1, 0, 1);
1302        countdown.emit_branch(1, body);
1303        countdown.emit_jump(done);
1304        countdown.bind_label(body);
1305        countdown.emit_sub_imm(0, 0, 1);
1306        countdown.emit_jump(head);
1307        countdown.bind_label(done);
1308        countdown.emit_return(0);
1309        let sub_chunk = Arc::new(countdown.finish());
1310        let (interpreted, compiled, ctx) = run_float_chunk(Arc::clone(&sub_chunk), 40)?;
1311        if !ctx.cache.has_float_trace() {
1312            return Err("float SubImm loop was not compiled".into());
1313        }
1314        match (interpreted, compiled) {
1315            (VmResult::Complete(Value::Float(a)), VmResult::Complete(Value::Float(b)))
1316                if a == 0.0 && b == 0.0 =>
1317            {
1318                Ok(())
1319            }
1320            (left, right) => Err(format!("sub imm {right:?} interpreter {left:?}").into()),
1321        }
1322    }
1323
1324    #[test]
1325    fn runtime_path_compiles_and_runs() -> TestResult {
1326        let chunk = add_chunk();
1327        let runtime = JitRuntime::new(chunk.clone(), 1);
1328        let key = TraceKey {
1329            function: 0,
1330            entry_pc: 0,
1331
1332            floats: false,
1333        };
1334        let mut slots = vec![0i64; 3];
1335        let exit = try_run_hot_runtime(&runtime, &chunk, key, &mut slots, 10_000, 3, None)
1336            .ok_or("expected jit execution")?;
1337        assert!(matches!(exit, ExitReason::Return { return_reg: 2 }));
1338        assert_eq!(slots[2], 42);
1339        Ok(())
1340    }
1341
1342    #[test]
1343    fn budget_exit_when_exhausted_mid_trace() -> TestResult {
1344        let mut b = ChunkBuilder::new("jit-budget");
1345        b.begin_function("main", 0, 1);
1346        b.emit_load_imm(0, 1);
1347        b.emit_load_imm(0, 2);
1348        b.emit_load_imm(0, 3);
1349        b.emit_return(0);
1350        let chunk = Arc::new(b.finish());
1351
1352        let mut ctx = JitContext::new(chunk.clone())?;
1353        let key = TraceKey {
1354            function: 0,
1355            entry_pc: 0,
1356
1357            floats: false,
1358        };
1359        force_compile(&mut ctx, &chunk, key)?;
1360        let trace = ctx
1361            .cache
1362            .get(&key)
1363            .ok_or("trace missing after force_compile")?;
1364        let mut slots = vec![0i64; 1];
1365        let ret = run_compiled_trace_ref(trace, &mut slots, 0, 2, 0, 1);
1366        assert!(matches!(ret.into_reason(), ExitReason::Budget { pc: 2 }));
1367        Ok(())
1368    }
1369
1370    #[test]
1371    fn explicit_yield_stops_the_quantum() -> TestResult {
1372        let mut b = ChunkBuilder::new("jit-yield");
1373        b.begin_function("main", 0, 1);
1374        b.emit_load_imm(0, 1);
1375        b.emit_yield();
1376        b.emit_load_imm(0, 2);
1377        b.emit_return(0);
1378        let chunk = Arc::new(b.finish());
1379
1380        let mut ctx = JitContext::new(Arc::clone(&chunk))?;
1381        ctx.hot_threshold = u32::MAX;
1382        let mut vm = Vm::new(Arc::clone(&chunk), NativeTable::empty(), 0, &[])?;
1383        let first = run_vm_with_jit(&mut vm, 100, &mut ctx);
1384        if !matches!(first, VmResult::Yield) {
1385            return Err(format!("yield was swallowed, got {first:?}").into());
1386        }
1387        match vm.top_registers().and_then(|regs| regs.first().cloned()) {
1388            Some(Value::Int(1)) => {}
1389            other => return Err(format!("register after yield is {other:?}").into()),
1390        }
1391        let second = run_vm_with_jit(&mut vm, 100, &mut ctx);
1392        if !matches!(second, VmResult::Complete(Value::Int(2))) {
1393            return Err(format!("resume after yield finished as {second:?}").into());
1394        }
1395
1396        force_compile(
1397            &mut ctx,
1398            &chunk,
1399            TraceKey {
1400                function: 0,
1401                entry_pc: 0,
1402                floats: false,
1403            },
1404        )?;
1405        let mut compiled = Vm::new(chunk, NativeTable::empty(), 0, &[])?;
1406        let stopped = run_vm_with_jit(&mut compiled, 100, &mut ctx);
1407        if !matches!(stopped, VmResult::Yield) {
1408            return Err(format!("compiled prefix ran through yield, got {stopped:?}").into());
1409        }
1410        match compiled
1411            .top_registers()
1412            .and_then(|regs| regs.first().cloned())
1413        {
1414            Some(Value::Int(1)) => Ok(()),
1415            other => Err(format!("compiled prefix left {other:?}").into()),
1416        }
1417    }
1418
1419    #[test]
1420    fn budget_end_still_runs_the_rest_of_the_quantum() -> TestResult {
1421        let mut b = ChunkBuilder::new("jit-budget-step");
1422        b.begin_function("main", 0, 1);
1423        b.emit_load_imm(0, 1);
1424        b.emit_load_imm(0, 2);
1425        b.emit_load_imm(0, 3);
1426        b.emit_return(0);
1427        let chunk = Arc::new(b.finish());
1428        let mut ctx = JitContext::new(Arc::clone(&chunk))?;
1429        ctx.hot_threshold = u32::MAX;
1430        let mut vm = Vm::new(chunk, NativeTable::empty(), 0, &[])?;
1431        let result = run_vm_with_jit(&mut vm, 2, &mut ctx);
1432        if !matches!(result, VmResult::Yield) {
1433            return Err(format!("budget 2 finished as {result:?}").into());
1434        }
1435        if vm.instructions_executed() != 2 {
1436            return Err(format!("ran {} instructions", vm.instructions_executed()).into());
1437        }
1438        match vm.top_registers().and_then(|regs| regs.first().cloned()) {
1439            Some(Value::Int(2)) => Ok(()),
1440            other => Err(format!("expected the second load, got {other:?}").into()),
1441        }
1442    }
1443
1444    #[test]
1445    fn compiled_trace_counts_the_instructions_it_ran() -> TestResult {
1446        let mut b = ChunkBuilder::new("jit-count");
1447        b.begin_function("main", 0, 1);
1448        b.emit_load_imm(0, 1);
1449        b.emit_load_imm(0, 2);
1450        b.emit_load_imm(0, 3);
1451        b.emit_return(0);
1452        let chunk = Arc::new(b.finish());
1453        let mut ctx = JitContext::new(chunk.clone())?;
1454        force_compile(
1455            &mut ctx,
1456            &chunk,
1457            TraceKey {
1458                function: 0,
1459                entry_pc: 0,
1460                floats: false,
1461            },
1462        )?;
1463        let mut vm = Vm::new(chunk, NativeTable::empty(), 0, &[])?;
1464        let result = run_vm_with_jit(&mut vm, 10, &mut ctx);
1465        assert!(matches!(result, VmResult::Complete(Value::Int(3))));
1466        assert_eq!(vm.instructions_executed(), 4);
1467        Ok(())
1468    }
1469
1470    #[test]
1471    fn interleaved_jit_compiles_mid_quantum() -> TestResult {
1472        let mut b = ChunkBuilder::new("jit-interleave");
1473        b.begin_function("main", 0, 2);
1474        b.emit_load_imm(0, 0);
1475        let head = b.new_label();
1476        b.bind_label(head);
1477        b.emit_load_imm(1, 1);
1478        b.emit_binop(Opcode::Add, 0, 0, 1);
1479        b.emit_load_imm(1, 100);
1480        b.emit_binop(Opcode::Lt, 1, 0, 1);
1481        let done = b.new_label();
1482        b.emit_branch(1, done);
1483        b.emit_jump(head);
1484        b.bind_label(done);
1485        b.emit_return(0);
1486        let chunk = Arc::new(b.finish());
1487        let head_pc = chunk.functions[0].entry + 1;
1488
1489        let mut ctx = JitContext::new(chunk.clone())?;
1490        ctx.hot_threshold = 2;
1491        let mut vm = Vm::new(chunk, NativeTable::empty(), 0, &[])?;
1492        let result = run_vm_with_jit(&mut vm, 10_000, &mut ctx);
1493        assert!(matches!(result, VmResult::Complete(Value::Int(100))));
1494        assert!(ctx
1495            .cache
1496            .get(&TraceKey {
1497                function: 0,
1498                entry_pc: head_pc,
1499
1500                floats: false,
1501            })
1502            .is_some());
1503        Ok(())
1504    }
1505
1506    #[test]
1507    fn reload_chunk_invalidates_jit_cache() -> TestResult {
1508        let chunk = add_chunk();
1509        let runtime = JitRuntime::new(chunk.clone(), 1);
1510        let key = TraceKey {
1511            function: 0,
1512            entry_pc: 0,
1513
1514            floats: false,
1515        };
1516        let mut slots = vec![0i64; 3];
1517        let exit = try_run_hot_runtime(&runtime, &chunk, key, &mut slots, 10_000, 3, None)
1518            .ok_or("expected jit execution")?;
1519        assert!(matches!(exit, ExitReason::Return { .. }));
1520
1521        let mut b = ChunkBuilder::new("other");
1522        b.begin_function("main", 0, 1);
1523        b.emit_load_imm(0, 1);
1524        b.emit_return(0);
1525        runtime.reload(Arc::new(b.finish()));
1526        assert!(runtime.get_trace(&key).is_none());
1527        Ok(())
1528    }
1529
1530    /// Budget expiry used to resume past instructions whose results existed
1531    /// only in SSA, and writeback turned every untouched `Unit` into `Int(0)`.
1532    #[test]
1533    fn budget_exit_publishes_assigned_regs_and_keeps_unit() -> TestResult {
1534        let mut b = ChunkBuilder::new("jit-budget");
1535        b.begin_function("main", 0, 2);
1536        b.emit_load_imm(0, 41);
1537        b.emit_load_imm(1, 1);
1538        b.emit_return(0);
1539        let chunk = Arc::new(b.finish());
1540        let mut ctx = JitContext::new(chunk.clone())?;
1541        let key = TraceKey {
1542            function: 0,
1543            entry_pc: 0,
1544
1545            floats: false,
1546        };
1547        force_compile(&mut ctx, &chunk, key)?;
1548        let trace = ctx
1549            .cache
1550            .get(&key)
1551            .ok_or("trace missing after force_compile")?;
1552        let mut slots = vec![0i64; 2];
1553        let ret = run_compiled_trace_ref(trace, &mut slots, 0, 1, 0, 2);
1554        assert!(matches!(ret.into_reason(), ExitReason::Budget { pc: 1 }));
1555        let mut vm = Vm::new(chunk, NativeTable::empty(), 0, &[])?;
1556        apply_exit_tagged(&mut vm, &slots, ret)?;
1557        let regs = vm.top_registers().ok_or("no frame")?;
1558        assert!(matches!(regs.first(), Some(&Value::Int(41))));
1559        assert!(matches!(regs.get(1), Some(&Value::Unit)));
1560        Ok(())
1561    }
1562
1563    #[test]
1564    fn jit_call_does_not_clobber_the_caller_frame() -> TestResult {
1565        let mut b = ChunkBuilder::new("jit-call-frames");
1566        b.begin_function("callee", 0, 3);
1567        b.emit_load_imm(2, 99);
1568        b.emit_load_imm(0, 1);
1569        b.emit_return(0);
1570        let main = b.begin_function("main", 0, 3);
1571        b.emit_load_imm(2, 7);
1572        b.emit_call(0, 0, 0);
1573        b.emit_return(2);
1574        let chunk = Arc::new(b.finish());
1575        let mut ctx = JitContext::new(chunk.clone())?;
1576        let entry = chunk.functions[main as usize].entry;
1577        force_compile(
1578            &mut ctx,
1579            &chunk,
1580            TraceKey {
1581                function: main,
1582                entry_pc: entry,
1583
1584                floats: false,
1585            },
1586        )?;
1587        let mut vm = Vm::new(chunk, NativeTable::empty(), main, &[])?;
1588        let result = run_vm_with_jit(&mut vm, 10_000, &mut ctx);
1589        assert!(matches!(result, VmResult::Complete(Value::Int(7))));
1590        Ok(())
1591    }
1592
1593    #[test]
1594    fn move_keeps_bool_unit_and_a_later_int() -> TestResult {
1595        let mut b = ChunkBuilder::new("jit-move-tags");
1596        b.begin_function("cmp", 0, 4);
1597        b.emit_load_imm(0, 1);
1598        b.emit_load_imm(1, 1);
1599        b.emit_binop(Opcode::Eq, 2, 0, 1);
1600        b.emit_move(3, 2);
1601        b.emit_return(3);
1602        let moved_bool = b.begin_function("moved-bool", 1, 2);
1603        b.emit_move(1, 0);
1604        b.emit_return(1);
1605        let moved_false = b.begin_function("moved-false", 1, 2);
1606        b.emit_move(1, 0);
1607        b.emit_return(1);
1608        let moved_unit = b.begin_function("moved-unit", 0, 2);
1609        b.emit_move(1, 0);
1610        b.emit_return(1);
1611        let overwritten = b.begin_function("overwritten", 1, 2);
1612        b.emit_load_imm(0, 5);
1613        let cont = b.new_label();
1614        b.emit_jump(cont);
1615        b.bind_label(cont);
1616        b.emit_move(1, 0);
1617        b.emit_return(1);
1618        let chunk = Arc::new(b.finish());
1619        let mut ctx = JitContext::new(chunk.clone())?;
1620
1621        let run = |ctx: &mut JitContext, function: u32, args: &[Value]| -> TestResult {
1622            let entry = chunk.functions[function as usize].entry;
1623            force_compile(
1624                ctx,
1625                &chunk,
1626                TraceKey {
1627                    function,
1628                    entry_pc: entry,
1629
1630                    floats: false,
1631                },
1632            )?;
1633            let mut vm = Vm::new(chunk.clone(), NativeTable::empty(), function, args)?;
1634            let result = run_vm_with_jit(&mut vm, 10_000, ctx);
1635            match (function, result) {
1636                (_, VmResult::Complete(Value::Bool(true))) if function == 0 => Ok(()),
1637                (_, VmResult::Complete(Value::Bool(true))) if function == moved_bool => Ok(()),
1638                (_, VmResult::Complete(Value::Bool(false))) if function == moved_false => Ok(()),
1639                (_, VmResult::Complete(Value::Unit)) if function == moved_unit => Ok(()),
1640                (_, VmResult::Complete(Value::Int(5))) if function == overwritten => Ok(()),
1641                (_, other) => Err(format!("function {function} finished as {other:?}").into()),
1642            }
1643        };
1644
1645        run(&mut ctx, 0, &[])?;
1646        run(&mut ctx, moved_bool, &[Value::Bool(true)])?;
1647        run(&mut ctx, moved_false, &[Value::Bool(false)])?;
1648        run(&mut ctx, moved_unit, &[])?;
1649        run(&mut ctx, overwritten, &[Value::Bool(true)])?;
1650        Ok(())
1651    }
1652
1653    #[test]
1654    fn leaf_call_stays_in_the_trace() -> TestResult {
1655        let mut b = ChunkBuilder::new("jit-call");
1656        let add1 = b.begin_function("add1", 1, 2);
1657        b.emit_load_imm(1, 1);
1658        b.emit_binop(Opcode::Add, 0, 0, 1);
1659        b.emit_return(0);
1660        let main = b.begin_function("main", 0, 1);
1661        b.emit_load_imm(0, 41);
1662        b.emit_call(0, add1, 1);
1663        b.emit_return(0);
1664        let chunk = Arc::new(b.finish());
1665        let mut ctx = JitContext::new(chunk.clone())?;
1666        let entry = chunk.functions[main as usize].entry;
1667        let key = TraceKey {
1668            function: main,
1669            entry_pc: entry,
1670
1671            floats: false,
1672        };
1673        force_compile(&mut ctx, &chunk, key)?;
1674        let trace = ctx
1675            .cache
1676            .get(&key)
1677            .ok_or("trace missing after force_compile")?;
1678        let mut slots = vec![0i64; 2];
1679        let exit = run_compiled_trace_ref(trace, &mut slots, entry, 10_000, main, 1).into_reason();
1680        match exit {
1681            ExitReason::Return { return_reg: 0 } => {}
1682            other => return Err(format!("call left the trace: {other:?}").into()),
1683        }
1684        if slots[0] != 42 {
1685            return Err(format!("leaf call produced {}", slots[0]).into());
1686        }
1687        Ok(())
1688    }
1689
1690    #[test]
1691    fn leaf_call_keeps_bool_unit_and_a_high_dest() -> TestResult {
1692        let mut b = ChunkBuilder::new("jit-call-tags");
1693        let is_true = b.begin_function("is-true", 0, 2);
1694        b.emit_load_imm(0, 1);
1695        b.emit_load_imm(1, 1);
1696        b.emit_binop(Opcode::Eq, 0, 0, 1);
1697        b.emit_return(0);
1698        let blank = b.begin_function("blank", 0, 1);
1699        b.emit_return(0);
1700        let moved = b.begin_function("moved", 1, 2);
1701        b.emit_move(1, 0);
1702        b.emit_return(1);
1703        let add1 = b.begin_function("add1", 1, 2);
1704        b.emit_load_imm(1, 1);
1705        b.emit_binop(Opcode::Add, 0, 0, 1);
1706        b.emit_return(0);
1707
1708        let main_bool = b.begin_function("main-bool", 0, 1);
1709        b.emit_call(0, is_true, 0);
1710        b.emit_return(0);
1711        let main_unit = b.begin_function("main-unit", 0, 1);
1712        b.emit_load_imm(0, 9);
1713        b.emit_call(0, blank, 0);
1714        b.emit_return(0);
1715        let main_moved = b.begin_function("main-moved", 1, 1);
1716        b.emit_call(0, moved, 1);
1717        b.emit_return(0);
1718        let main_high = b.begin_function("main-high", 0, 17);
1719        b.emit_load_imm(16, 41);
1720        b.emit_call(16, add1, 1);
1721        b.emit_return(16);
1722        let chunk = Arc::new(b.finish());
1723        let mut ctx = JitContext::new(chunk.clone())?;
1724
1725        let run = |ctx: &mut JitContext,
1726                   function: u32,
1727                   args: &[Value]|
1728         -> Result<VmResult, Box<dyn std::error::Error>> {
1729            let entry = chunk.functions[function as usize].entry;
1730            force_compile(
1731                ctx,
1732                &chunk,
1733                TraceKey {
1734                    function,
1735                    entry_pc: entry,
1736
1737                    floats: false,
1738                },
1739            )?;
1740            let mut vm = Vm::new(chunk.clone(), NativeTable::empty(), function, args)?;
1741            Ok(run_vm_with_jit(&mut vm, 10_000, ctx))
1742        };
1743
1744        match run(&mut ctx, main_bool, &[])? {
1745            VmResult::Complete(Value::Bool(true)) => {}
1746            other => return Err(format!("bool leaf finished as {other:?}").into()),
1747        }
1748        match run(&mut ctx, main_unit, &[])? {
1749            VmResult::Complete(Value::Unit) => {}
1750            other => return Err(format!("unread leaf finished as {other:?}").into()),
1751        }
1752        match run(&mut ctx, main_moved, &[Value::Bool(false)])? {
1753            VmResult::Complete(Value::Bool(false)) => {}
1754            other => return Err(format!("bool arg finished as {other:?}").into()),
1755        }
1756        match run(&mut ctx, main_high, &[])? {
1757            VmResult::Complete(Value::Int(42)) => {}
1758            other => return Err(format!("r16 dest finished as {other:?}").into()),
1759        }
1760        Ok(())
1761    }
1762}