Skip to main content

byteflow/jit/
dispatch.rs

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