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: register_count as u8,
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: register_count as u8,
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),
301        (Some(max_regs), None) => max_regs,
302        (None, Some(current)) => current,
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.cache.is_failed(&key) {
630            return None;
631        }
632        if !ctx.hot.hit(key, ctx.hot_threshold) {
633            if let Some(m) = call.metrics {
634                crate::scheduler::RuntimeMetrics::inc(&m.jit_misses);
635            }
636            return None;
637        }
638        let mut compiler = TraceCompiler::new(ctx.module_mut());
639        match compiler.compile_trace(chunk, key) {
640            Ok(compiled) => {
641                ctx.cache.insert(key, compiled);
642                if let Some(m) = call.metrics {
643                    crate::scheduler::RuntimeMetrics::inc(&m.jit_compiles);
644                }
645            }
646            Err(_) => {
647                ctx.cache.mark_failed(key);
648                if let Some(m) = call.metrics {
649                    crate::scheduler::RuntimeMetrics::inc(&m.jit_compile_failures);
650                }
651                return None;
652            }
653        }
654    }
655    let trace = ctx.cache.get(&key)?;
656    if let Some(m) = call.metrics {
657        crate::scheduler::RuntimeMetrics::inc(&m.jit_executions);
658    }
659    Some(run_compiled_trace_with_tags(
660        trace.entry,
661        call.slots,
662        key.entry_pc,
663        call.budget,
664        key.function,
665        u32::from(call.register_count),
666        call.tags,
667    ))
668}
669
670/// Shared-runtime variant (no global lock during execution).
671pub fn try_run_hot_runtime(
672    runtime: &JitRuntime,
673    chunk: &Chunk,
674    key: TraceKey,
675    slots: &mut [i64],
676    budget: u32,
677    register_count: u8,
678    metrics: Option<&crate::scheduler::RuntimeMetrics>,
679) -> Option<ExitReason> {
680    try_run_hot_runtime_tagged(
681        runtime,
682        chunk,
683        key,
684        &mut HotCall {
685            slots,
686            budget,
687            register_count,
688            metrics,
689            tags: EntryTags::INT,
690        },
691    )
692    .and_then(|(ret, _, unwind)| {
693        if unwind.is_some() {
694            None
695        } else {
696            Some(ret.into_reason())
697        }
698    })
699}
700
701fn try_run_hot_runtime_tagged(
702    runtime: &JitRuntime,
703    chunk: &Chunk,
704    key: TraceKey,
705    call: &mut HotCall<'_>,
706) -> Option<(JitReturn, u32, Option<JitUnwind>)> {
707    if runtime.is_failed(&key) {
708        return None;
709    }
710
711    if let Some(copy) = runtime.get_trace(&key) {
712        if let Some(m) = call.metrics {
713            crate::scheduler::RuntimeMetrics::inc(&m.jit_executions);
714        }
715        return Some(run_compiled_trace_with_tags(
716            copy.entry,
717            call.slots,
718            key.entry_pc,
719            call.budget,
720            key.function,
721            u32::from(call.register_count),
722            call.tags,
723        ));
724    }
725
726    if !runtime.record_hot_hit(key) {
727        if let Some(m) = call.metrics {
728            crate::scheduler::RuntimeMetrics::inc(&m.jit_misses);
729        }
730        return None;
731    }
732
733    // Double-checked compile after hot threshold.
734    if runtime.get_trace(&key).is_some() {
735        return try_run_hot_runtime_tagged(runtime, chunk, key, call);
736    }
737
738    let compiled =
739        match with_jit_module(|module| TraceCompiler::new(module).compile_trace(chunk, key)) {
740            Ok(trace) => trace,
741            Err(_) => {
742                runtime.mark_failed(key);
743                if let Some(m) = call.metrics {
744                    crate::scheduler::RuntimeMetrics::inc(&m.jit_compile_failures);
745                }
746                return None;
747            }
748        };
749
750    runtime.insert_trace(key, compiled);
751    if let Some(m) = call.metrics {
752        crate::scheduler::RuntimeMetrics::inc(&m.jit_compiles);
753    }
754
755    try_run_hot_runtime_tagged(runtime, chunk, key, call)
756}
757
758fn tag_bit(words: &[u64; 4], reg: usize) -> bool {
759    if reg >= 256 {
760        return false;
761    }
762    words[reg / 64] & (1u64 << (reg % 64)) != 0
763}
764
765/// Write back only registers the trace assigned. Untouched `Unit` / `Bool`
766/// values stay as they were. A `Move` of either tag is written back as that
767/// tag. Comparison results come back as `Bool`.
768fn sync_slots_tagged(vm: &mut Vm, slots: &[i64], ret: &JitReturn) -> Result<(), Fault> {
769    let Some(regs) = vm.top_registers_mut() else {
770        return Err(Fault::Invariant("empty frame stack while syncing slots"));
771    };
772    for (index, reg) in regs.iter_mut().enumerate() {
773        if !tag_bit(&ret.written, index) {
774            continue;
775        }
776        let Some(slot) = slots.get(index).copied() else {
777            continue;
778        };
779        *reg = if tag_bit(&ret.as_unit, index) {
780            Value::Unit
781        } else if tag_bit(&ret.as_bool, index) {
782            Value::Bool(slot != 0)
783        } else if tag_bit(&ret.as_float, index) {
784            Value::Float(f64::from_bits(slot as u64))
785        } else {
786            Value::Int(slot)
787        };
788    }
789    Ok(())
790}
791
792fn apply_exit_tagged(
793    vm: &mut Vm,
794    slots: &[i64],
795    ret: JitReturn,
796) -> Result<Option<VmResult>, Fault> {
797    match ret.kind {
798        super::exit::JIT_RETURN => {
799            sync_slots_tagged(vm, slots, &ret)?;
800            let return_reg = ret.return_reg as u8;
801            let value = match vm
802                .top_registers()
803                .and_then(|regs| regs.get(usize::from(return_reg)))
804            {
805                Some(v) => v.clone(),
806                None => {
807                    let frame_size = match vm.current_num_registers() {
808                        Some(n) => n as u8,
809                        None => 0,
810                    };
811                    return Err(Fault::RegisterOutOfRange {
812                        reg: return_reg,
813                        frame_size,
814                    });
815                }
816            };
817            let pc = vm
818                .current_pc()
819                .ok_or(Fault::Invariant("empty frame stack while running"))?;
820            vm.set_pc(pc.saturating_add(1));
821            vm.return_value(value)
822        }
823        super::exit::JIT_TRAP => {
824            vm.set_pc(ret.pc as usize);
825            Ok(Some(VmResult::Trap(Fault::DivideByZero)))
826        }
827        super::exit::JIT_BUDGET => {
828            vm.set_pc(ret.pc as usize);
829            sync_slots_tagged(vm, slots, &ret)?;
830            Ok(None)
831        }
832        super::exit::JIT_CONTINUE | super::exit::JIT_EFFECT => {
833            vm.set_pc(ret.pc as usize);
834            sync_slots_tagged(vm, slots, &ret)?;
835            Ok(None)
836        }
837        _ => {
838            vm.set_pc(ret.pc as usize);
839            Ok(None)
840        }
841    }
842}
843
844/// Apply a native trace exit to a live [`Vm`], producing an optional early
845/// [`VmResult`] when the trace finished the flow.
846pub fn apply_exit_to_vm(
847    vm: &mut Vm,
848    slots: &[i64],
849    exit: ExitReason,
850) -> Result<Option<VmResult>, Fault> {
851    match exit {
852        ExitReason::Return { return_reg } => {
853            let Some(bits) = slots.get(usize::from(return_reg)).copied() else {
854                return Err(Fault::RegisterOutOfRange {
855                    reg: return_reg,
856                    frame_size: u8::try_from(slots.len()).unwrap_or(u8::MAX),
857                });
858            };
859            let value = Value::Int(bits);
860            vm.set_register(return_reg, value.clone())?;
861            let pc = vm
862                .current_pc()
863                .ok_or(Fault::Invariant("empty frame stack while running"))?;
864            vm.set_pc(pc.saturating_add(1));
865            vm.return_value(value)
866        }
867        ExitReason::Trap { pc } => {
868            vm.set_pc(pc as usize);
869            Ok(Some(VmResult::Trap(Fault::DivideByZero)))
870        }
871        ExitReason::Budget { pc } => {
872            vm.set_pc(pc as usize);
873            sync_slots_to_vm(vm, slots)?;
874            Ok(None)
875        }
876        ExitReason::Continue { pc } | ExitReason::Effect { pc } | ExitReason::Deopt { pc } => {
877            vm.set_pc(pc as usize);
878            if matches!(
879                exit,
880                ExitReason::Continue { .. } | ExitReason::Effect { .. }
881            ) {
882                sync_slots_to_vm(vm, slots)?;
883            }
884            Ok(None)
885        }
886    }
887}
888
889/// Copy int-compatible registers from the VM into JIT shadow slots.
890pub fn sync_slots_from_vm(vm: &Vm, slots: &mut [i64]) -> SyncSlotsResult {
891    let Some(regs) = vm.top_registers() else {
892        return SyncSlotsResult::Unavailable;
893    };
894    let mut saw_float = false;
895    let mut saw_int = false;
896    for value in regs.iter().take(slots.len()) {
897        match value {
898            Value::Int(_) => saw_int = true,
899            Value::Float(_) => saw_float = true,
900            Value::Bool(_) | Value::Unit => {}
901            _ => return SyncSlotsResult::Deopt,
902        }
903    }
904    if saw_int && saw_float {
905        return SyncSlotsResult::Deopt;
906    }
907    for (slot, value) in slots.iter_mut().zip(regs.iter()) {
908        *slot = match value {
909            Value::Int(i) => *i,
910            Value::Bool(b) => i64::from(*b),
911            Value::Unit => 0,
912            Value::Float(n) => n.to_bits() as i64,
913            _ => 0,
914        };
915    }
916    if saw_float {
917        SyncSlotsResult::Float
918    } else {
919        SyncSlotsResult::Ok
920    }
921}
922
923/// Write JIT shadow slots back into the active VM register file.
924pub fn sync_slots_to_vm(vm: &mut Vm, slots: &[i64]) -> Result<(), Fault> {
925    let Some(regs) = vm.top_registers_mut() else {
926        return Err(Fault::Invariant("empty frame stack while syncing slots"));
927    };
928    for (reg, slot) in regs.iter_mut().zip(slots.iter()) {
929        *reg = Value::Int(*slot);
930    }
931    Ok(())
932}
933
934/// Threshold at which a `(function, pc)` pair becomes a compilation candidate.
935pub const fn hot_threshold() -> u32 {
936    HOT_THRESHOLD
937}
938
939/// Force-compile a trace (tests / benchmarks).
940pub fn force_compile(
941    ctx: &mut JitContext,
942    chunk: &Chunk,
943    key: TraceKey,
944) -> Result<(), super::error::CompileError> {
945    if ctx.cache.get(&key).is_none() {
946        let mut compiler = TraceCompiler::new(ctx.module_mut());
947        let compiled = compiler.compile_trace(chunk, key)?;
948        ctx.cache.insert(key, compiled);
949    }
950    Ok(())
951}
952
953#[cfg(test)]
954mod tests {
955    use std::sync::Arc;
956
957    use crate::{
958        bytecode::builder::ChunkBuilder, FlowOutcome, NativeTable, Opcode, Runtime, Value, Vm,
959        VmResult,
960    };
961
962    use super::*;
963    use crate::jit::trace::{JitContext, TraceKey};
964
965    type TestResult = Result<(), Box<dyn std::error::Error>>;
966
967    fn add_chunk() -> std::sync::Arc<crate::Chunk> {
968        let mut b = ChunkBuilder::new("jit-add");
969        b.begin_function("main", 0, 3);
970        b.emit_load_imm(0, 41);
971        b.emit_load_imm(1, 1);
972        b.emit_binop(Opcode::Add, 2, 0, 1);
973        b.emit_return(2);
974        Arc::new(b.finish())
975    }
976
977    #[test]
978    fn run_vm_with_jit_completes_scalar_add() -> TestResult {
979        let chunk = add_chunk();
980        let mut ctx = JitContext::new(chunk.clone())?;
981        let key = TraceKey {
982            function: 0,
983            entry_pc: 0,
984
985            floats: false,
986        };
987        force_compile(&mut ctx, &chunk, key)?;
988
989        let mut vm = Vm::new(chunk, NativeTable::empty(), 0, &[])?;
990        let result = run_vm_with_jit(&mut vm, 10_000, &mut ctx);
991        assert!(matches!(result, VmResult::Complete(Value::Int(42))));
992        Ok(())
993    }
994
995    #[test]
996    fn native_trace_computes_42() -> TestResult {
997        let chunk = add_chunk();
998        let mut ctx = JitContext::new(chunk.clone())?;
999        let key = TraceKey {
1000            function: 0,
1001            entry_pc: 0,
1002
1003            floats: false,
1004        };
1005        force_compile(&mut ctx, &chunk, key)?;
1006        let trace = ctx
1007            .cache
1008            .get(&key)
1009            .ok_or("trace missing after force_compile")?;
1010        let mut slots = vec![0i64; 3];
1011        let ret = run_compiled_trace_ref(trace, &mut slots, 0, 10_000, 0, 3);
1012        let exit = ret.into_reason();
1013        assert!(matches!(exit, ExitReason::Return { return_reg: 2 }));
1014        assert_eq!(slots[2], 42);
1015        Ok(())
1016    }
1017
1018    #[test]
1019    fn mul_imm_eq_imm_and_shifts_match_the_interpreter() -> TestResult {
1020        let mut b = ChunkBuilder::new("jit-bits");
1021        b.begin_function("main", 0, 4);
1022        b.emit_load_imm(0, 6);
1023        b.emit_mul_imm(1, 0, 7);
1024        b.emit_load_imm(2, 1);
1025        b.emit_bit_binop(Opcode::Shl, 3, 1, 2);
1026        b.emit_bit_binop(Opcode::Shr, 1, 3, 2);
1027        b.emit_return(1);
1028        let chunk = Arc::new(b.finish());
1029        let mut interpreted = Vm::new(chunk.clone(), NativeTable::empty(), 0, &[])?;
1030        assert!(matches!(
1031            interpreted.run(20),
1032            VmResult::Complete(Value::Int(42))
1033        ));
1034        let mut ctx = JitContext::new(chunk.clone())?;
1035        let key = TraceKey {
1036            function: 0,
1037            entry_pc: 0,
1038            floats: false,
1039        };
1040        force_compile(&mut ctx, &chunk, key)?;
1041        let mut vm = Vm::new(chunk, NativeTable::empty(), 0, &[])?;
1042        let result = run_vm_with_jit(&mut vm, 20, &mut ctx);
1043        assert!(matches!(result, VmResult::Complete(Value::Int(42))));
1044
1045        let mut b = ChunkBuilder::new("jit-eq-imm");
1046        b.begin_function("main", 0, 2);
1047        b.emit_load_imm(0, 42);
1048        b.emit_eq_imm(1, 0, 42);
1049        b.emit_le_imm(0, 0, 41);
1050        b.emit_return(1);
1051        let chunk = Arc::new(b.finish());
1052        let mut interpreted = Vm::new(chunk.clone(), NativeTable::empty(), 0, &[])?;
1053        assert!(matches!(
1054            interpreted.run(20),
1055            VmResult::Complete(Value::Bool(true))
1056        ));
1057        let mut ctx = JitContext::new(chunk.clone())?;
1058        force_compile(&mut ctx, &chunk, key)?;
1059        let mut vm = Vm::new(chunk, NativeTable::empty(), 0, &[])?;
1060        let result = run_vm_with_jit(&mut vm, 20, &mut ctx);
1061        assert!(matches!(result, VmResult::Complete(Value::Bool(true))));
1062        Ok(())
1063    }
1064
1065    #[test]
1066    fn jit_matches_interpreter_on_scalar_add() -> TestResult {
1067        let chunk = add_chunk();
1068        let rt = Runtime::new((*chunk).clone())?;
1069        let interp = rt.spawn(0, &[])?.join();
1070        rt.shutdown();
1071        assert!(matches!(interp, FlowOutcome::Completed(Value::Int(42))));
1072
1073        let mut ctx = JitContext::new(chunk.clone())?;
1074        let key = TraceKey {
1075            function: 0,
1076            entry_pc: 0,
1077
1078            floats: false,
1079        };
1080        let mut slots = vec![0i64; 3];
1081        force_compile(&mut ctx, &chunk, key)?;
1082        let trace = ctx
1083            .cache
1084            .get(&key)
1085            .ok_or("trace missing after force_compile")?;
1086        let exit = run_compiled_trace_ref(trace, &mut slots, 0, 10_000, 0, 3).into_reason();
1087        assert!(matches!(exit, ExitReason::Return { return_reg: 2 }));
1088        assert_eq!(slots[2], 42);
1089
1090        let mut vm = Vm::new(chunk, NativeTable::empty(), 0, &[])?;
1091        if let Some(result) = apply_exit_to_vm(&mut vm, &slots, exit)? {
1092            assert!(matches!(result, VmResult::Complete(Value::Int(42))));
1093        } else {
1094            return Err("expected Completed(42)".into());
1095        }
1096        Ok(())
1097    }
1098
1099    #[test]
1100    fn div_by_zero_returns_trap_exit() -> TestResult {
1101        let mut b = ChunkBuilder::new("jit-div0");
1102        b.begin_function("main", 0, 3);
1103        b.emit_load_imm(0, 1);
1104        b.emit_load_imm(1, 0);
1105        b.emit_binop(Opcode::Div, 2, 0, 1);
1106        b.emit_return(2);
1107        let chunk = Arc::new(b.finish());
1108
1109        let mut ctx = JitContext::new(chunk.clone())?;
1110        let key = TraceKey {
1111            function: 0,
1112            entry_pc: 0,
1113
1114            floats: false,
1115        };
1116        force_compile(&mut ctx, &chunk, key)?;
1117        let trace = ctx
1118            .cache
1119            .get(&key)
1120            .ok_or("trace missing after force_compile")?;
1121        let mut slots = vec![0i64; 3];
1122        let ret = run_compiled_trace_ref(trace, &mut slots, 0, 10_000, 0, 3);
1123        assert!(matches!(ret.into_reason(), ExitReason::Trap { .. }));
1124        Ok(())
1125    }
1126
1127    #[test]
1128    fn div_and_mod_of_i64_min_wrap_instead_of_aborting() -> TestResult {
1129        let mut b = ChunkBuilder::new("jit-div-overflow");
1130        b.begin_function("div", 0, 3);
1131        let min = b.const_(Value::Int(i64::MIN));
1132        let neg = b.const_(Value::Int(-1));
1133        b.emit_load_const(0, min);
1134        b.emit_load_const(1, neg);
1135        b.emit_binop(Opcode::Div, 2, 0, 1);
1136        b.emit_return(2);
1137        let rem = b.begin_function("rem", 0, 3);
1138        let min = b.const_(Value::Int(i64::MIN));
1139        let neg = b.const_(Value::Int(-1));
1140        b.emit_load_const(0, min);
1141        b.emit_load_const(1, neg);
1142        b.emit_binop(Opcode::Mod, 2, 0, 1);
1143        b.emit_return(2);
1144        let chunk = Arc::new(b.finish());
1145        let mut ctx = JitContext::new(chunk.clone())?;
1146
1147        for (function, expect) in [(0, i64::MIN), (rem, 0)] {
1148            let entry = chunk.functions[function as usize].entry;
1149            force_compile(
1150                &mut ctx,
1151                &chunk,
1152                TraceKey {
1153                    function,
1154                    entry_pc: entry,
1155
1156                    floats: false,
1157                },
1158            )?;
1159            let mut vm = Vm::new(chunk.clone(), NativeTable::empty(), function, &[])?;
1160            let result = run_vm_with_jit(&mut vm, 10_000, &mut ctx);
1161            match result {
1162                VmResult::Complete(Value::Int(n)) if n == expect => {}
1163                other => {
1164                    return Err(format!("function {function} finished as {other:?}").into());
1165                }
1166            }
1167        }
1168        Ok(())
1169    }
1170
1171    #[test]
1172    fn sync_slots_accepts_a_float_register() -> TestResult {
1173        let chunk = add_chunk();
1174        let mut vm = Vm::new(chunk, NativeTable::empty(), 0, &[])?;
1175        vm.set_register(0, Value::Float(1.0))?;
1176        let mut slots = vec![0i64; 3];
1177        assert_eq!(sync_slots_from_vm(&vm, &mut slots), SyncSlotsResult::Float);
1178        assert_eq!(f64::from_bits(slots[0] as u64), 1.0);
1179        Ok(())
1180    }
1181
1182    #[test]
1183    fn float_trace_matches_the_interpreter() -> TestResult {
1184        let mut b = ChunkBuilder::new("jit-float");
1185        let zero = b.const_(Value::Float(0.0));
1186        let one = b.const_(Value::Float(1.0));
1187        let limit = b.const_(Value::Float(4.0));
1188        b.begin_function("main", 0, 4);
1189        b.emit_load_const(0, zero);
1190        b.emit_load_const(1, one);
1191        b.emit_load_const(2, limit);
1192        let head = b.new_label();
1193        let done = b.new_label();
1194        b.bind_label(head);
1195        b.emit_binop(Opcode::Add, 0, 0, 1);
1196        b.emit_binop(Opcode::Lt, 3, 0, 2);
1197        b.emit_branch(3, done);
1198        b.emit_jump(head);
1199        b.bind_label(done);
1200        b.emit_return(0);
1201        let chunk = Arc::new(b.finish());
1202        let mut plain = Vm::new(Arc::clone(&chunk), NativeTable::empty(), 0, &[])?;
1203        let interpreted = plain.run(100);
1204        let mut ctx = JitContext::new(Arc::clone(&chunk))?;
1205        ctx.hot_threshold = 1;
1206        let mut vm = Vm::new(chunk, NativeTable::empty(), 0, &[])?;
1207        let compiled = run_vm_with_jit(&mut vm, 100, &mut ctx);
1208        if !ctx.cache.has_float_trace() {
1209            return Err("float add loop was not compiled".into());
1210        }
1211        match (interpreted, compiled) {
1212            (VmResult::Complete(Value::Float(a)), VmResult::Complete(Value::Float(b)))
1213                if a == b && a == 4.0 =>
1214            {
1215                Ok(())
1216            }
1217            (left, right) => Err(format!("float trace {right:?} interpreter {left:?}").into()),
1218        }
1219    }
1220
1221    fn run_float_chunk(
1222        chunk: Arc<Chunk>,
1223        budget: u32,
1224    ) -> Result<(VmResult, VmResult, JitContext), Box<dyn std::error::Error>> {
1225        let mut plain = Vm::new(Arc::clone(&chunk), NativeTable::empty(), 0, &[])?;
1226        let interpreted = plain.run(budget);
1227        let mut ctx = JitContext::new(Arc::clone(&chunk))?;
1228        ctx.hot_threshold = 1;
1229        let mut vm = Vm::new(chunk, NativeTable::empty(), 0, &[])?;
1230        let compiled = run_vm_with_jit(&mut vm, budget, &mut ctx);
1231        Ok((interpreted, compiled, ctx))
1232    }
1233
1234    #[test]
1235    fn float_trace_edges_match_the_interpreter() -> TestResult {
1236        let mut nan_lt = ChunkBuilder::new("jit-nan-lt");
1237        let nan = nan_lt.const_(Value::Float(f64::NAN));
1238        let zero = nan_lt.const_(Value::Float(0.0));
1239        nan_lt.begin_function("main", 0, 3);
1240        nan_lt.emit_load_const(0, nan);
1241        nan_lt.emit_load_const(1, zero);
1242        let head = nan_lt.new_label();
1243        nan_lt.bind_label(head);
1244        nan_lt.emit_binop(Opcode::Lt, 2, 0, 1);
1245        nan_lt.emit_return(2);
1246        let nan_chunk = Arc::new(nan_lt.finish());
1247        let (interpreted, compiled, ctx) = run_float_chunk(Arc::clone(&nan_chunk), 20)?;
1248        if !ctx.cache.has_float_trace() {
1249            return Err("NaN comparison was not compiled".into());
1250        }
1251        match (interpreted, compiled) {
1252            (VmResult::Complete(Value::Bool(false)), VmResult::Complete(Value::Bool(false))) => {}
1253            (left, right) => {
1254                return Err(format!("nan lt {right:?} interpreter {left:?}").into());
1255            }
1256        }
1257
1258        let mut inf_add = ChunkBuilder::new("jit-inf-add");
1259        let pos = inf_add.const_(Value::Float(f64::INFINITY));
1260        let neg = inf_add.const_(Value::Float(f64::NEG_INFINITY));
1261        inf_add.begin_function("main", 0, 3);
1262        inf_add.emit_load_const(0, pos);
1263        inf_add.emit_load_const(1, neg);
1264        let head = inf_add.new_label();
1265        inf_add.bind_label(head);
1266        inf_add.emit_binop(Opcode::Add, 2, 0, 1);
1267        inf_add.emit_return(2);
1268        let inf_chunk = Arc::new(inf_add.finish());
1269        let (interpreted, compiled, ctx) = run_float_chunk(Arc::clone(&inf_chunk), 20)?;
1270        if !ctx.cache.has_float_trace() {
1271            return Err("infinity add was not compiled".into());
1272        }
1273        match (interpreted, compiled) {
1274            (VmResult::Complete(Value::Float(a)), VmResult::Complete(Value::Float(b)))
1275                if a.is_nan() && b.is_nan() => {}
1276            (left, right) => {
1277                return Err(format!("inf add {right:?} interpreter {left:?}").into());
1278            }
1279        }
1280
1281        let mut zeros = ChunkBuilder::new("jit-signed-zero");
1282        let neg_zero = zeros.const_(Value::Float(-0.0));
1283        zeros.begin_function("main", 0, 1);
1284        zeros.emit_load_const(0, neg_zero);
1285        let head = zeros.new_label();
1286        zeros.bind_label(head);
1287        zeros.emit_add_imm(0, 0, 0);
1288        zeros.emit_return(0);
1289        let zero_chunk = Arc::new(zeros.finish());
1290        let (interpreted, compiled, ctx) = run_float_chunk(Arc::clone(&zero_chunk), 20)?;
1291        if !ctx.cache.has_float_trace() {
1292            return Err("signed-zero add was not compiled".into());
1293        }
1294        match (interpreted, compiled) {
1295            (VmResult::Complete(Value::Float(a)), VmResult::Complete(Value::Float(b)))
1296                if a.to_bits() == 0.0f64.to_bits() && b.to_bits() == 0.0f64.to_bits() => {}
1297            (left, right) => {
1298                return Err(format!("signed zero {right:?} interpreter {left:?}").into());
1299            }
1300        }
1301
1302        let mut countdown = ChunkBuilder::new("jit-sub-imm");
1303        let start = countdown.const_(Value::Float(4.0));
1304        countdown.begin_function("main", 0, 2);
1305        countdown.emit_load_const(0, start);
1306        let head = countdown.new_label();
1307        let body = countdown.new_label();
1308        let done = countdown.new_label();
1309        countdown.bind_label(head);
1310        countdown.emit_lt_imm(1, 0, 1);
1311        countdown.emit_branch(1, body);
1312        countdown.emit_jump(done);
1313        countdown.bind_label(body);
1314        countdown.emit_sub_imm(0, 0, 1);
1315        countdown.emit_jump(head);
1316        countdown.bind_label(done);
1317        countdown.emit_return(0);
1318        let sub_chunk = Arc::new(countdown.finish());
1319        let (interpreted, compiled, ctx) = run_float_chunk(Arc::clone(&sub_chunk), 40)?;
1320        if !ctx.cache.has_float_trace() {
1321            return Err("float SubImm loop was not compiled".into());
1322        }
1323        match (interpreted, compiled) {
1324            (VmResult::Complete(Value::Float(a)), VmResult::Complete(Value::Float(b)))
1325                if a == 0.0 && b == 0.0 =>
1326            {
1327                Ok(())
1328            }
1329            (left, right) => Err(format!("sub imm {right:?} interpreter {left:?}").into()),
1330        }
1331    }
1332
1333    #[test]
1334    fn runtime_path_compiles_and_runs() -> TestResult {
1335        let chunk = add_chunk();
1336        let runtime = JitRuntime::new(chunk.clone(), 1);
1337        let key = TraceKey {
1338            function: 0,
1339            entry_pc: 0,
1340
1341            floats: false,
1342        };
1343        let mut slots = vec![0i64; 3];
1344        let exit = try_run_hot_runtime(&runtime, &chunk, key, &mut slots, 10_000, 3, None)
1345            .ok_or("expected jit execution")?;
1346        assert!(matches!(exit, ExitReason::Return { return_reg: 2 }));
1347        assert_eq!(slots[2], 42);
1348        Ok(())
1349    }
1350
1351    #[test]
1352    fn budget_exit_when_exhausted_mid_trace() -> TestResult {
1353        let mut b = ChunkBuilder::new("jit-budget");
1354        b.begin_function("main", 0, 1);
1355        b.emit_load_imm(0, 1);
1356        b.emit_load_imm(0, 2);
1357        b.emit_load_imm(0, 3);
1358        b.emit_return(0);
1359        let chunk = Arc::new(b.finish());
1360
1361        let mut ctx = JitContext::new(chunk.clone())?;
1362        let key = TraceKey {
1363            function: 0,
1364            entry_pc: 0,
1365
1366            floats: false,
1367        };
1368        force_compile(&mut ctx, &chunk, key)?;
1369        let trace = ctx
1370            .cache
1371            .get(&key)
1372            .ok_or("trace missing after force_compile")?;
1373        let mut slots = vec![0i64; 1];
1374        let ret = run_compiled_trace_ref(trace, &mut slots, 0, 2, 0, 1);
1375        assert!(matches!(ret.into_reason(), ExitReason::Budget { pc: 2 }));
1376        Ok(())
1377    }
1378
1379    #[test]
1380    fn explicit_yield_stops_the_quantum() -> TestResult {
1381        let mut b = ChunkBuilder::new("jit-yield");
1382        b.begin_function("main", 0, 1);
1383        b.emit_load_imm(0, 1);
1384        b.emit_yield();
1385        b.emit_load_imm(0, 2);
1386        b.emit_return(0);
1387        let chunk = Arc::new(b.finish());
1388
1389        let mut ctx = JitContext::new(Arc::clone(&chunk))?;
1390        ctx.hot_threshold = u32::MAX;
1391        let mut vm = Vm::new(Arc::clone(&chunk), NativeTable::empty(), 0, &[])?;
1392        let first = run_vm_with_jit(&mut vm, 100, &mut ctx);
1393        if !matches!(first, VmResult::Yield) {
1394            return Err(format!("yield was swallowed, got {first:?}").into());
1395        }
1396        match vm.top_registers().and_then(|regs| regs.first().cloned()) {
1397            Some(Value::Int(1)) => {}
1398            other => return Err(format!("register after yield is {other:?}").into()),
1399        }
1400        let second = run_vm_with_jit(&mut vm, 100, &mut ctx);
1401        if !matches!(second, VmResult::Complete(Value::Int(2))) {
1402            return Err(format!("resume after yield finished as {second:?}").into());
1403        }
1404
1405        force_compile(
1406            &mut ctx,
1407            &chunk,
1408            TraceKey {
1409                function: 0,
1410                entry_pc: 0,
1411                floats: false,
1412            },
1413        )?;
1414        let mut compiled = Vm::new(chunk, NativeTable::empty(), 0, &[])?;
1415        let stopped = run_vm_with_jit(&mut compiled, 100, &mut ctx);
1416        if !matches!(stopped, VmResult::Yield) {
1417            return Err(format!("compiled prefix ran through yield, got {stopped:?}").into());
1418        }
1419        match compiled
1420            .top_registers()
1421            .and_then(|regs| regs.first().cloned())
1422        {
1423            Some(Value::Int(1)) => Ok(()),
1424            other => Err(format!("compiled prefix left {other:?}").into()),
1425        }
1426    }
1427
1428    #[test]
1429    fn budget_end_still_runs_the_rest_of_the_quantum() -> TestResult {
1430        let mut b = ChunkBuilder::new("jit-budget-step");
1431        b.begin_function("main", 0, 1);
1432        b.emit_load_imm(0, 1);
1433        b.emit_load_imm(0, 2);
1434        b.emit_load_imm(0, 3);
1435        b.emit_return(0);
1436        let chunk = Arc::new(b.finish());
1437        let mut ctx = JitContext::new(Arc::clone(&chunk))?;
1438        ctx.hot_threshold = u32::MAX;
1439        let mut vm = Vm::new(chunk, NativeTable::empty(), 0, &[])?;
1440        let result = run_vm_with_jit(&mut vm, 2, &mut ctx);
1441        if !matches!(result, VmResult::Yield) {
1442            return Err(format!("budget 2 finished as {result:?}").into());
1443        }
1444        if vm.instructions_executed() != 2 {
1445            return Err(format!("ran {} instructions", vm.instructions_executed()).into());
1446        }
1447        match vm.top_registers().and_then(|regs| regs.first().cloned()) {
1448            Some(Value::Int(2)) => Ok(()),
1449            other => Err(format!("expected the second load, got {other:?}").into()),
1450        }
1451    }
1452
1453    #[test]
1454    fn compiled_trace_counts_the_instructions_it_ran() -> TestResult {
1455        let mut b = ChunkBuilder::new("jit-count");
1456        b.begin_function("main", 0, 1);
1457        b.emit_load_imm(0, 1);
1458        b.emit_load_imm(0, 2);
1459        b.emit_load_imm(0, 3);
1460        b.emit_return(0);
1461        let chunk = Arc::new(b.finish());
1462        let mut ctx = JitContext::new(chunk.clone())?;
1463        force_compile(
1464            &mut ctx,
1465            &chunk,
1466            TraceKey {
1467                function: 0,
1468                entry_pc: 0,
1469                floats: false,
1470            },
1471        )?;
1472        let mut vm = Vm::new(chunk, NativeTable::empty(), 0, &[])?;
1473        let result = run_vm_with_jit(&mut vm, 10, &mut ctx);
1474        assert!(matches!(result, VmResult::Complete(Value::Int(3))));
1475        assert_eq!(vm.instructions_executed(), 4);
1476        Ok(())
1477    }
1478
1479    #[test]
1480    fn interleaved_jit_compiles_mid_quantum() -> TestResult {
1481        let mut b = ChunkBuilder::new("jit-interleave");
1482        b.begin_function("main", 0, 2);
1483        b.emit_load_imm(0, 0);
1484        let head = b.new_label();
1485        b.bind_label(head);
1486        b.emit_load_imm(1, 1);
1487        b.emit_binop(Opcode::Add, 0, 0, 1);
1488        b.emit_load_imm(1, 100);
1489        b.emit_binop(Opcode::Lt, 1, 0, 1);
1490        let done = b.new_label();
1491        b.emit_branch(1, done);
1492        b.emit_jump(head);
1493        b.bind_label(done);
1494        b.emit_return(0);
1495        let chunk = Arc::new(b.finish());
1496        let head_pc = chunk.functions[0].entry + 1;
1497
1498        let mut ctx = JitContext::new(chunk.clone())?;
1499        ctx.hot_threshold = 2;
1500        let mut vm = Vm::new(chunk, NativeTable::empty(), 0, &[])?;
1501        let result = run_vm_with_jit(&mut vm, 10_000, &mut ctx);
1502        assert!(matches!(result, VmResult::Complete(Value::Int(100))));
1503        assert!(ctx
1504            .cache
1505            .get(&TraceKey {
1506                function: 0,
1507                entry_pc: head_pc,
1508
1509                floats: false,
1510            })
1511            .is_some());
1512        Ok(())
1513    }
1514
1515    #[test]
1516    fn reload_chunk_invalidates_jit_cache() -> TestResult {
1517        let chunk = add_chunk();
1518        let runtime = JitRuntime::new(chunk.clone(), 1);
1519        let key = TraceKey {
1520            function: 0,
1521            entry_pc: 0,
1522
1523            floats: false,
1524        };
1525        let mut slots = vec![0i64; 3];
1526        let exit = try_run_hot_runtime(&runtime, &chunk, key, &mut slots, 10_000, 3, None)
1527            .ok_or("expected jit execution")?;
1528        assert!(matches!(exit, ExitReason::Return { .. }));
1529
1530        let mut b = ChunkBuilder::new("other");
1531        b.begin_function("main", 0, 1);
1532        b.emit_load_imm(0, 1);
1533        b.emit_return(0);
1534        runtime.reload(Arc::new(b.finish()));
1535        assert!(runtime.get_trace(&key).is_none());
1536        Ok(())
1537    }
1538
1539    /// Budget expiry used to resume past instructions whose results existed
1540    /// only in SSA, and writeback turned every untouched `Unit` into `Int(0)`.
1541    #[test]
1542    fn budget_exit_publishes_assigned_regs_and_keeps_unit() -> TestResult {
1543        let mut b = ChunkBuilder::new("jit-budget");
1544        b.begin_function("main", 0, 2);
1545        b.emit_load_imm(0, 41);
1546        b.emit_load_imm(1, 1);
1547        b.emit_return(0);
1548        let chunk = Arc::new(b.finish());
1549        let mut ctx = JitContext::new(chunk.clone())?;
1550        let key = TraceKey {
1551            function: 0,
1552            entry_pc: 0,
1553
1554            floats: false,
1555        };
1556        force_compile(&mut ctx, &chunk, key)?;
1557        let trace = ctx
1558            .cache
1559            .get(&key)
1560            .ok_or("trace missing after force_compile")?;
1561        let mut slots = vec![0i64; 2];
1562        let ret = run_compiled_trace_ref(trace, &mut slots, 0, 1, 0, 2);
1563        assert!(matches!(ret.into_reason(), ExitReason::Budget { pc: 1 }));
1564        let mut vm = Vm::new(chunk, NativeTable::empty(), 0, &[])?;
1565        apply_exit_tagged(&mut vm, &slots, ret)?;
1566        let regs = vm.top_registers().ok_or("no frame")?;
1567        assert!(matches!(regs.first(), Some(&Value::Int(41))));
1568        assert!(matches!(regs.get(1), Some(&Value::Unit)));
1569        Ok(())
1570    }
1571
1572    #[test]
1573    fn jit_call_does_not_clobber_the_caller_frame() -> TestResult {
1574        let mut b = ChunkBuilder::new("jit-call-frames");
1575        b.begin_function("callee", 0, 3);
1576        b.emit_load_imm(2, 99);
1577        b.emit_load_imm(0, 1);
1578        b.emit_return(0);
1579        let main = b.begin_function("main", 0, 3);
1580        b.emit_load_imm(2, 7);
1581        b.emit_call(0, 0, 0);
1582        b.emit_return(2);
1583        let chunk = Arc::new(b.finish());
1584        let mut ctx = JitContext::new(chunk.clone())?;
1585        let entry = chunk.functions[main as usize].entry;
1586        force_compile(
1587            &mut ctx,
1588            &chunk,
1589            TraceKey {
1590                function: main,
1591                entry_pc: entry,
1592
1593                floats: false,
1594            },
1595        )?;
1596        let mut vm = Vm::new(chunk, NativeTable::empty(), main, &[])?;
1597        let result = run_vm_with_jit(&mut vm, 10_000, &mut ctx);
1598        assert!(matches!(result, VmResult::Complete(Value::Int(7))));
1599        Ok(())
1600    }
1601
1602    #[test]
1603    fn move_keeps_bool_unit_and_a_later_int() -> TestResult {
1604        let mut b = ChunkBuilder::new("jit-move-tags");
1605        b.begin_function("cmp", 0, 4);
1606        b.emit_load_imm(0, 1);
1607        b.emit_load_imm(1, 1);
1608        b.emit_binop(Opcode::Eq, 2, 0, 1);
1609        b.emit_move(3, 2);
1610        b.emit_return(3);
1611        let moved_bool = b.begin_function("moved-bool", 1, 2);
1612        b.emit_move(1, 0);
1613        b.emit_return(1);
1614        let moved_false = b.begin_function("moved-false", 1, 2);
1615        b.emit_move(1, 0);
1616        b.emit_return(1);
1617        let moved_unit = b.begin_function("moved-unit", 0, 2);
1618        b.emit_move(1, 0);
1619        b.emit_return(1);
1620        let overwritten = b.begin_function("overwritten", 1, 2);
1621        b.emit_load_imm(0, 5);
1622        let cont = b.new_label();
1623        b.emit_jump(cont);
1624        b.bind_label(cont);
1625        b.emit_move(1, 0);
1626        b.emit_return(1);
1627        let chunk = Arc::new(b.finish());
1628        let mut ctx = JitContext::new(chunk.clone())?;
1629
1630        let run = |ctx: &mut JitContext, function: u32, args: &[Value]| -> TestResult {
1631            let entry = chunk.functions[function as usize].entry;
1632            force_compile(
1633                ctx,
1634                &chunk,
1635                TraceKey {
1636                    function,
1637                    entry_pc: entry,
1638
1639                    floats: false,
1640                },
1641            )?;
1642            let mut vm = Vm::new(chunk.clone(), NativeTable::empty(), function, args)?;
1643            let result = run_vm_with_jit(&mut vm, 10_000, ctx);
1644            match (function, result) {
1645                (_, VmResult::Complete(Value::Bool(true))) if function == 0 => Ok(()),
1646                (_, VmResult::Complete(Value::Bool(true))) if function == moved_bool => Ok(()),
1647                (_, VmResult::Complete(Value::Bool(false))) if function == moved_false => Ok(()),
1648                (_, VmResult::Complete(Value::Unit)) if function == moved_unit => Ok(()),
1649                (_, VmResult::Complete(Value::Int(5))) if function == overwritten => Ok(()),
1650                (_, other) => Err(format!("function {function} finished as {other:?}").into()),
1651            }
1652        };
1653
1654        run(&mut ctx, 0, &[])?;
1655        run(&mut ctx, moved_bool, &[Value::Bool(true)])?;
1656        run(&mut ctx, moved_false, &[Value::Bool(false)])?;
1657        run(&mut ctx, moved_unit, &[])?;
1658        run(&mut ctx, overwritten, &[Value::Bool(true)])?;
1659        Ok(())
1660    }
1661
1662    #[test]
1663    fn leaf_call_stays_in_the_trace() -> TestResult {
1664        let mut b = ChunkBuilder::new("jit-call");
1665        let add1 = b.begin_function("add1", 1, 2);
1666        b.emit_load_imm(1, 1);
1667        b.emit_binop(Opcode::Add, 0, 0, 1);
1668        b.emit_return(0);
1669        let main = b.begin_function("main", 0, 1);
1670        b.emit_load_imm(0, 41);
1671        b.emit_call(0, add1, 1);
1672        b.emit_return(0);
1673        let chunk = Arc::new(b.finish());
1674        let mut ctx = JitContext::new(chunk.clone())?;
1675        let entry = chunk.functions[main as usize].entry;
1676        let key = TraceKey {
1677            function: main,
1678            entry_pc: entry,
1679
1680            floats: false,
1681        };
1682        force_compile(&mut ctx, &chunk, key)?;
1683        let trace = ctx
1684            .cache
1685            .get(&key)
1686            .ok_or("trace missing after force_compile")?;
1687        let mut slots = vec![0i64; 2];
1688        let exit = run_compiled_trace_ref(trace, &mut slots, entry, 10_000, main, 1).into_reason();
1689        match exit {
1690            ExitReason::Return { return_reg: 0 } => {}
1691            other => return Err(format!("call left the trace: {other:?}").into()),
1692        }
1693        if slots[0] != 42 {
1694            return Err(format!("leaf call produced {}", slots[0]).into());
1695        }
1696        Ok(())
1697    }
1698
1699    #[test]
1700    fn leaf_call_keeps_bool_unit_and_a_high_dest() -> TestResult {
1701        let mut b = ChunkBuilder::new("jit-call-tags");
1702        let is_true = b.begin_function("is-true", 0, 2);
1703        b.emit_load_imm(0, 1);
1704        b.emit_load_imm(1, 1);
1705        b.emit_binop(Opcode::Eq, 0, 0, 1);
1706        b.emit_return(0);
1707        let blank = b.begin_function("blank", 0, 1);
1708        b.emit_return(0);
1709        let moved = b.begin_function("moved", 1, 2);
1710        b.emit_move(1, 0);
1711        b.emit_return(1);
1712        let add1 = b.begin_function("add1", 1, 2);
1713        b.emit_load_imm(1, 1);
1714        b.emit_binop(Opcode::Add, 0, 0, 1);
1715        b.emit_return(0);
1716
1717        let main_bool = b.begin_function("main-bool", 0, 1);
1718        b.emit_call(0, is_true, 0);
1719        b.emit_return(0);
1720        let main_unit = b.begin_function("main-unit", 0, 1);
1721        b.emit_load_imm(0, 9);
1722        b.emit_call(0, blank, 0);
1723        b.emit_return(0);
1724        let main_moved = b.begin_function("main-moved", 1, 1);
1725        b.emit_call(0, moved, 1);
1726        b.emit_return(0);
1727        let main_high = b.begin_function("main-high", 0, 17);
1728        b.emit_load_imm(16, 41);
1729        b.emit_call(16, add1, 1);
1730        b.emit_return(16);
1731        let chunk = Arc::new(b.finish());
1732        let mut ctx = JitContext::new(chunk.clone())?;
1733
1734        let run = |ctx: &mut JitContext,
1735                   function: u32,
1736                   args: &[Value]|
1737         -> Result<VmResult, Box<dyn std::error::Error>> {
1738            let entry = chunk.functions[function as usize].entry;
1739            force_compile(
1740                ctx,
1741                &chunk,
1742                TraceKey {
1743                    function,
1744                    entry_pc: entry,
1745
1746                    floats: false,
1747                },
1748            )?;
1749            let mut vm = Vm::new(chunk.clone(), NativeTable::empty(), function, args)?;
1750            Ok(run_vm_with_jit(&mut vm, 10_000, ctx))
1751        };
1752
1753        match run(&mut ctx, main_bool, &[])? {
1754            VmResult::Complete(Value::Bool(true)) => {}
1755            other => return Err(format!("bool leaf finished as {other:?}").into()),
1756        }
1757        match run(&mut ctx, main_unit, &[])? {
1758            VmResult::Complete(Value::Unit) => {}
1759            other => return Err(format!("unread leaf finished as {other:?}").into()),
1760        }
1761        match run(&mut ctx, main_moved, &[Value::Bool(false)])? {
1762            VmResult::Complete(Value::Bool(false)) => {}
1763            other => return Err(format!("bool arg finished as {other:?}").into()),
1764        }
1765        match run(&mut ctx, main_high, &[])? {
1766            VmResult::Complete(Value::Int(42)) => {}
1767            other => return Err(format!("r16 dest finished as {other:?}").into()),
1768        }
1769        Ok(())
1770    }
1771}