1#![allow(unsafe_code)]
3
4use std::sync::Arc;
5
6use crate::{Chunk, Fault, Value, Vm, VmResult};
7
8use super::compiler::TraceCompiler;
9use super::exit::{ExitReason, JitReturn};
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#[derive(Debug, Clone, Copy, PartialEq, Eq)]
17pub enum SyncSlotsResult {
18 Ok,
19 Deopt,
21 Unavailable,
23}
24
25#[derive(Clone, Copy)]
30struct EntryTags {
31 as_bool: [u64; 4],
32 as_unit: [u64; 4],
33}
34
35impl EntryTags {
36 const INT: Self = Self {
37 as_bool: [0; 4],
38 as_unit: [0; 4],
39 };
40
41 fn from_vm(vm: &Vm) -> Self {
42 let mut tags = Self::INT;
43 let Some(regs) = vm.top_registers() else {
44 return tags;
45 };
46 for (index, value) in regs.iter().enumerate() {
47 if index >= 256 {
48 break;
49 }
50 let bit = 1u64 << (index % 64);
51 let word = index / 64;
52 match value {
53 Value::Bool(_) => tags.as_bool[word] |= bit,
54 Value::Unit => tags.as_unit[word] |= bit,
55 _ => {}
56 }
57 }
58 tags
59 }
60}
61
62fn try_jit_step(vm: &mut Vm, ctx: &mut JitContext, budget: u32) -> Option<VmResult> {
64 if !Arc::ptr_eq(&ctx.chunk, &vm.chunk_arc()) {
65 return None;
66 }
67 let pc = vm.current_pc()?;
68 let function = vm.current_function();
69 let register_count = vm.current_num_registers()?;
70
71 let mut slots = vec![0i64; slot_capacity(vm)];
72 match sync_slots_from_vm(vm, &mut slots) {
73 SyncSlotsResult::Ok => {}
74 SyncSlotsResult::Deopt | SyncSlotsResult::Unavailable => return None,
75 }
76
77 let key = TraceKey {
78 function,
79 entry_pc: pc as u32,
80 };
81 let exit = try_run_hot_tagged(
82 ctx,
83 vm.chunk_arc().as_ref(),
84 key,
85 &mut HotCall {
86 slots: &mut slots,
87 budget,
88 register_count,
89 metrics: None,
90 tags: EntryTags::from_vm(vm),
91 },
92 )?;
93 match apply_exit_tagged(vm, &slots, exit) {
94 Ok(Some(result)) => Some(result),
95 Ok(None) => None,
96 Err(fault) => Some(VmResult::Trap(fault)),
97 }
98}
99
100fn try_jit_step_runtime(
101 vm: &mut Vm,
102 runtime: &JitRuntime,
103 budget: u32,
104 metrics: Option<&crate::scheduler::RuntimeMetrics>,
105) -> Option<VmResult> {
106 if !runtime.matches_chunk(&vm.chunk_arc()) {
107 return None;
108 }
109 let pc = vm.current_pc()?;
110 let function = vm.current_function();
111 let register_count = vm.current_num_registers()?;
112
113 let mut slots = vec![0i64; slot_capacity(vm)];
114 match sync_slots_from_vm(vm, &mut slots) {
115 SyncSlotsResult::Ok => {}
116 SyncSlotsResult::Deopt => {
117 if let Some(m) = metrics {
118 crate::scheduler::RuntimeMetrics::inc(&m.jit_deopts);
119 }
120 return None;
121 }
122 SyncSlotsResult::Unavailable => return None,
123 }
124
125 let key = TraceKey {
126 function,
127 entry_pc: pc as u32,
128 };
129 let exit = try_run_hot_runtime_tagged(
130 runtime,
131 vm.chunk_arc().as_ref(),
132 key,
133 &mut HotCall {
134 slots: &mut slots,
135 budget,
136 register_count,
137 metrics,
138 tags: EntryTags::from_vm(vm),
139 },
140 )?;
141 match apply_exit_tagged(vm, &slots, exit) {
142 Ok(Some(result)) => Some(result),
143 Ok(None) => None,
144 Err(fault) => Some(VmResult::Trap(fault)),
145 }
146}
147
148pub fn run_vm_with_jit(vm: &mut Vm, budget: u32, ctx: &mut JitContext) -> VmResult {
151 run_vm_with_jit_loop(vm, budget, |vm, remaining| try_jit_step(vm, ctx, remaining))
152}
153
154pub fn run_vm_with_jit_runtime(
156 vm: &mut Vm,
157 budget: u32,
158 runtime: &JitRuntime,
159 metrics: Option<&crate::scheduler::RuntimeMetrics>,
160) -> VmResult {
161 run_vm_with_jit_loop(vm, budget, |vm, remaining| {
162 try_jit_step_runtime(vm, runtime, remaining, metrics)
163 })
164}
165
166fn run_vm_with_jit_loop(
167 vm: &mut Vm,
168 budget: u32,
169 mut try_step: impl FnMut(&mut Vm, u32) -> Option<VmResult>,
170) -> VmResult {
171 let mut remaining = budget;
172 while remaining > 0 {
173 if let Some(result) = try_step(vm, remaining) {
174 return result;
175 }
176 match vm.run(1) {
177 VmResult::Yield => {
178 remaining -= 1;
179 }
180 other => return other,
181 }
182 }
183 VmResult::Yield
184}
185
186fn slot_capacity(vm: &Vm) -> usize {
187 let chunk = vm.chunk_arc();
188 let max_in_chunk = chunk
189 .functions
190 .iter()
191 .map(|f| f.num_registers as usize)
192 .max();
193 match (max_in_chunk, vm.current_num_registers()) {
194 (Some(max_regs), Some(current)) => max_regs.max(current as usize),
195 (Some(max_regs), None) => max_regs,
196 (None, Some(current)) => current as usize,
197 (None, None) => 0,
198 }
199}
200
201pub fn run_compiled_trace(
206 entry: super::frame::JitEntry,
207 slots: &mut [i64],
208 pc: u32,
209 budget: u32,
210 function: u32,
211 register_count: u32,
212) -> JitReturn {
213 run_compiled_trace_with_tags(
214 entry,
215 slots,
216 pc,
217 budget,
218 function,
219 register_count,
220 EntryTags::INT,
221 )
222}
223
224fn run_compiled_trace_with_tags(
225 entry: super::frame::JitEntry,
226 slots: &mut [i64],
227 pc: u32,
228 budget: u32,
229 function: u32,
230 register_count: u32,
231 tags: EntryTags,
232) -> JitReturn {
233 let mut call_stack = [JitCallRecord {
234 return_pc: 0,
235 return_function: 0,
236 dest_reg: 0,
237 caller_register_count: 0,
238 }; MAX_JIT_CALL_DEPTH];
239 let mut frame = JitFrame {
240 slots: slots.as_mut_ptr(),
241 register_count,
242 pc,
243 budget,
244 function,
245 exit_kind: 0,
246 return_reg: 0,
247 call_depth: 0,
248 call_stack: call_stack.as_mut_ptr(),
249 written: [0; 4],
250 as_bool: [0; 4],
251 as_unit: [0; 4],
252 entry_as_bool: tags.as_bool,
253 entry_as_unit: tags.as_unit,
254 };
255 unsafe { (entry)(&mut frame) };
256 JitReturn {
257 kind: frame.exit_kind,
258 pc: frame.pc,
259 return_reg: frame.return_reg,
260 written: frame.written,
261 as_bool: frame.as_bool,
262 as_unit: frame.as_unit,
263 }
264}
265
266pub fn run_compiled_trace_ref(
268 trace: &CompiledTrace,
269 slots: &mut [i64],
270 pc: u32,
271 budget: u32,
272 function: u32,
273 register_count: u32,
274) -> JitReturn {
275 run_compiled_trace(trace.entry, slots, pc, budget, function, register_count)
276}
277
278struct HotCall<'a> {
279 slots: &'a mut [i64],
280 budget: u32,
281 register_count: u8,
282 metrics: Option<&'a crate::scheduler::RuntimeMetrics>,
283 tags: EntryTags,
284}
285
286pub fn try_run_hot(
289 ctx: &mut JitContext,
290 chunk: &Chunk,
291 key: TraceKey,
292 slots: &mut [i64],
293 budget: u32,
294 register_count: u8,
295 metrics: Option<&crate::scheduler::RuntimeMetrics>,
296) -> Option<ExitReason> {
297 try_run_hot_tagged(
298 ctx,
299 chunk,
300 key,
301 &mut HotCall {
302 slots,
303 budget,
304 register_count,
305 metrics,
306 tags: EntryTags::INT,
307 },
308 )
309 .map(JitReturn::into_reason)
310}
311
312fn try_run_hot_tagged(
313 ctx: &mut JitContext,
314 chunk: &Chunk,
315 key: TraceKey,
316 call: &mut HotCall<'_>,
317) -> Option<JitReturn> {
318 if ctx.cache.get(&key).is_none() {
319 if !ctx.hot.hit(key, ctx.hot_threshold) {
320 if let Some(m) = call.metrics {
321 crate::scheduler::RuntimeMetrics::inc(&m.jit_misses);
322 }
323 return None;
324 }
325 let mut compiler = TraceCompiler::new(ctx.module_mut());
326 match compiler.compile_trace(chunk, key) {
327 Ok(compiled) => {
328 ctx.cache.insert(key, compiled);
329 if let Some(m) = call.metrics {
330 crate::scheduler::RuntimeMetrics::inc(&m.jit_compiles);
331 }
332 }
333 Err(_) => {
334 if let Some(m) = call.metrics {
335 crate::scheduler::RuntimeMetrics::inc(&m.jit_compile_failures);
336 }
337 return None;
338 }
339 }
340 }
341 let trace = ctx.cache.get(&key)?;
342 if let Some(m) = call.metrics {
343 crate::scheduler::RuntimeMetrics::inc(&m.jit_executions);
344 }
345 Some(run_compiled_trace_with_tags(
346 trace.entry,
347 call.slots,
348 key.entry_pc,
349 call.budget,
350 key.function,
351 u32::from(call.register_count),
352 call.tags,
353 ))
354}
355
356pub fn try_run_hot_runtime(
358 runtime: &JitRuntime,
359 chunk: &Chunk,
360 key: TraceKey,
361 slots: &mut [i64],
362 budget: u32,
363 register_count: u8,
364 metrics: Option<&crate::scheduler::RuntimeMetrics>,
365) -> Option<ExitReason> {
366 try_run_hot_runtime_tagged(
367 runtime,
368 chunk,
369 key,
370 &mut HotCall {
371 slots,
372 budget,
373 register_count,
374 metrics,
375 tags: EntryTags::INT,
376 },
377 )
378 .map(JitReturn::into_reason)
379}
380
381fn try_run_hot_runtime_tagged(
382 runtime: &JitRuntime,
383 chunk: &Chunk,
384 key: TraceKey,
385 call: &mut HotCall<'_>,
386) -> Option<JitReturn> {
387 if let Some(copy) = runtime.get_trace(&key) {
388 if let Some(m) = call.metrics {
389 crate::scheduler::RuntimeMetrics::inc(&m.jit_executions);
390 }
391 return Some(run_compiled_trace_with_tags(
392 copy.entry,
393 call.slots,
394 key.entry_pc,
395 call.budget,
396 key.function,
397 u32::from(call.register_count),
398 call.tags,
399 ));
400 }
401
402 if !runtime.record_hot_hit(key) {
403 if let Some(m) = call.metrics {
404 crate::scheduler::RuntimeMetrics::inc(&m.jit_misses);
405 }
406 return None;
407 }
408
409 if runtime.get_trace(&key).is_some() {
411 return try_run_hot_runtime_tagged(runtime, chunk, key, call);
412 }
413
414 let compiled =
415 match with_jit_module(|module| TraceCompiler::new(module).compile_trace(chunk, key)) {
416 Ok(trace) => trace,
417 Err(_) => {
418 if let Some(m) = call.metrics {
419 crate::scheduler::RuntimeMetrics::inc(&m.jit_compile_failures);
420 }
421 return None;
422 }
423 };
424
425 runtime.insert_trace(key, compiled);
426 if let Some(m) = call.metrics {
427 crate::scheduler::RuntimeMetrics::inc(&m.jit_compiles);
428 }
429
430 try_run_hot_runtime_tagged(runtime, chunk, key, call)
431}
432
433fn tag_bit(words: &[u64; 4], reg: usize) -> bool {
434 if reg >= 256 {
435 return false;
436 }
437 words[reg / 64] & (1u64 << (reg % 64)) != 0
438}
439
440fn sync_slots_tagged(vm: &mut Vm, slots: &[i64], ret: &JitReturn) -> Result<(), Fault> {
444 let Some(regs) = vm.top_registers_mut() else {
445 return Err(Fault::Invariant("empty frame stack while syncing slots"));
446 };
447 for (index, reg) in regs.iter_mut().enumerate() {
448 if !tag_bit(&ret.written, index) {
449 continue;
450 }
451 let Some(slot) = slots.get(index).copied() else {
452 continue;
453 };
454 *reg = if tag_bit(&ret.as_unit, index) {
455 Value::Unit
456 } else if tag_bit(&ret.as_bool, index) {
457 Value::Bool(slot != 0)
458 } else {
459 Value::Int(slot)
460 };
461 }
462 Ok(())
463}
464
465fn apply_exit_tagged(
466 vm: &mut Vm,
467 slots: &[i64],
468 ret: JitReturn,
469) -> Result<Option<VmResult>, Fault> {
470 match ret.kind {
471 super::exit::JIT_RETURN => {
472 sync_slots_tagged(vm, slots, &ret)?;
473 let return_reg = ret.return_reg as u8;
474 let value = match vm
475 .top_registers()
476 .and_then(|regs| regs.get(usize::from(return_reg)))
477 {
478 Some(v) => v.clone(),
479 None => {
480 let frame_size = match vm.current_num_registers() {
481 Some(n) => n,
482 None => 0,
483 };
484 return Err(Fault::RegisterOutOfRange {
485 reg: return_reg,
486 frame_size,
487 });
488 }
489 };
490 let pc = vm
491 .current_pc()
492 .ok_or(Fault::Invariant("empty frame stack while running"))?;
493 vm.set_pc(pc.saturating_add(1));
494 vm.return_value(value)
495 }
496 super::exit::JIT_TRAP => {
497 vm.set_pc(ret.pc as usize);
498 Ok(Some(VmResult::Trap(Fault::DivideByZero)))
499 }
500 super::exit::JIT_BUDGET => {
501 vm.set_pc(ret.pc as usize);
502 sync_slots_tagged(vm, slots, &ret)?;
503 Ok(None)
504 }
505 super::exit::JIT_CONTINUE | super::exit::JIT_EFFECT => {
506 vm.set_pc(ret.pc as usize);
507 sync_slots_tagged(vm, slots, &ret)?;
508 Ok(None)
509 }
510 _ => {
511 vm.set_pc(ret.pc as usize);
512 Ok(None)
513 }
514 }
515}
516
517pub fn apply_exit_to_vm(
520 vm: &mut Vm,
521 slots: &[i64],
522 exit: ExitReason,
523) -> Result<Option<VmResult>, Fault> {
524 match exit {
525 ExitReason::Return { return_reg } => {
526 let value = Value::Int(slots[return_reg as usize]);
527 vm.set_register(return_reg, value.clone())?;
528 let pc = vm
529 .current_pc()
530 .ok_or(Fault::Invariant("empty frame stack while running"))?;
531 vm.set_pc(pc.saturating_add(1));
532 vm.return_value(value)
533 }
534 ExitReason::Trap { pc } => {
535 vm.set_pc(pc as usize);
536 Ok(Some(VmResult::Trap(Fault::DivideByZero)))
537 }
538 ExitReason::Budget { pc } => {
539 vm.set_pc(pc as usize);
540 sync_slots_to_vm(vm, slots)?;
541 Ok(None)
542 }
543 ExitReason::Continue { pc } | ExitReason::Effect { pc } | ExitReason::Deopt { pc } => {
544 vm.set_pc(pc as usize);
545 if matches!(
546 exit,
547 ExitReason::Continue { .. } | ExitReason::Effect { .. }
548 ) {
549 sync_slots_to_vm(vm, slots)?;
550 }
551 Ok(None)
552 }
553 }
554}
555
556pub fn sync_slots_from_vm(vm: &Vm, slots: &mut [i64]) -> SyncSlotsResult {
558 let Some(regs) = vm.top_registers() else {
559 return SyncSlotsResult::Unavailable;
560 };
561 for (slot, value) in slots.iter_mut().zip(regs.iter()) {
562 match value {
563 Value::Int(i) => *slot = *i,
564 Value::Bool(b) => *slot = i64::from(*b),
565 Value::Unit => *slot = 0,
566 _ => return SyncSlotsResult::Deopt,
567 }
568 }
569 SyncSlotsResult::Ok
570}
571
572pub fn sync_slots_to_vm(vm: &mut Vm, slots: &[i64]) -> Result<(), Fault> {
574 let Some(regs) = vm.top_registers_mut() else {
575 return Err(Fault::Invariant("empty frame stack while syncing slots"));
576 };
577 for (reg, slot) in regs.iter_mut().zip(slots.iter()) {
578 *reg = Value::Int(*slot);
579 }
580 Ok(())
581}
582
583pub const fn hot_threshold() -> u32 {
585 HOT_THRESHOLD
586}
587
588pub fn force_compile(
590 ctx: &mut JitContext,
591 chunk: &Chunk,
592 key: TraceKey,
593) -> Result<(), super::error::CompileError> {
594 if ctx.cache.get(&key).is_none() {
595 let mut compiler = TraceCompiler::new(ctx.module_mut());
596 let compiled = compiler.compile_trace(chunk, key)?;
597 ctx.cache.insert(key, compiled);
598 }
599 Ok(())
600}
601
602#[cfg(test)]
603mod tests {
604 use std::sync::Arc;
605
606 use crate::{
607 bytecode::builder::ChunkBuilder, FlowOutcome, NativeTable, Opcode, Runtime, Value, Vm,
608 VmResult,
609 };
610
611 use super::*;
612 use crate::jit::trace::{JitContext, TraceKey};
613
614 type TestResult = Result<(), Box<dyn std::error::Error>>;
615
616 fn add_chunk() -> std::sync::Arc<crate::Chunk> {
617 let mut b = ChunkBuilder::new("jit-add");
618 b.begin_function("main", 0, 3);
619 b.emit_load_imm(0, 41);
620 b.emit_load_imm(1, 1);
621 b.emit_binop(Opcode::Add, 2, 0, 1);
622 b.emit_return(2);
623 Arc::new(b.finish())
624 }
625
626 #[test]
627 fn run_vm_with_jit_completes_scalar_add() -> TestResult {
628 let chunk = add_chunk();
629 let mut ctx = JitContext::new(chunk.clone())?;
630 let key = TraceKey {
631 function: 0,
632 entry_pc: 0,
633 };
634 force_compile(&mut ctx, &chunk, key)?;
635
636 let mut vm = Vm::new(chunk, NativeTable::empty(), 0, &[])?;
637 let result = run_vm_with_jit(&mut vm, 10_000, &mut ctx);
638 assert!(matches!(result, VmResult::Complete(Value::Int(42))));
639 Ok(())
640 }
641
642 #[test]
643 fn native_trace_computes_42() -> TestResult {
644 let chunk = add_chunk();
645 let mut ctx = JitContext::new(chunk.clone())?;
646 let key = TraceKey {
647 function: 0,
648 entry_pc: 0,
649 };
650 force_compile(&mut ctx, &chunk, key)?;
651 let trace = ctx
652 .cache
653 .get(&key)
654 .ok_or("trace missing after force_compile")?;
655 let mut slots = vec![0i64; 3];
656 let ret = run_compiled_trace_ref(trace, &mut slots, 0, 10_000, 0, 3);
657 let exit = ret.into_reason();
658 assert!(matches!(exit, ExitReason::Return { return_reg: 2 }));
659 assert_eq!(slots[2], 42);
660 Ok(())
661 }
662
663 #[test]
664 fn jit_matches_interpreter_on_scalar_add() -> TestResult {
665 let chunk = add_chunk();
666 let rt = Runtime::new((*chunk).clone())?;
667 let interp = rt.spawn(0, &[])?.join();
668 rt.shutdown();
669 assert!(matches!(interp, FlowOutcome::Completed(Value::Int(42))));
670
671 let mut ctx = JitContext::new(chunk.clone())?;
672 let key = TraceKey {
673 function: 0,
674 entry_pc: 0,
675 };
676 let mut slots = vec![0i64; 3];
677 force_compile(&mut ctx, &chunk, key)?;
678 let trace = ctx
679 .cache
680 .get(&key)
681 .ok_or("trace missing after force_compile")?;
682 let exit = run_compiled_trace_ref(trace, &mut slots, 0, 10_000, 0, 3).into_reason();
683 assert!(matches!(exit, ExitReason::Return { return_reg: 2 }));
684 assert_eq!(slots[2], 42);
685
686 let mut vm = Vm::new(chunk, NativeTable::empty(), 0, &[])?;
687 if let Some(result) = apply_exit_to_vm(&mut vm, &slots, exit)? {
688 assert!(matches!(result, VmResult::Complete(Value::Int(42))));
689 } else {
690 return Err("expected Completed(42)".into());
691 }
692 Ok(())
693 }
694
695 #[test]
696 fn div_by_zero_returns_trap_exit() -> TestResult {
697 let mut b = ChunkBuilder::new("jit-div0");
698 b.begin_function("main", 0, 3);
699 b.emit_load_imm(0, 1);
700 b.emit_load_imm(1, 0);
701 b.emit_binop(Opcode::Div, 2, 0, 1);
702 b.emit_return(2);
703 let chunk = Arc::new(b.finish());
704
705 let mut ctx = JitContext::new(chunk.clone())?;
706 let key = TraceKey {
707 function: 0,
708 entry_pc: 0,
709 };
710 force_compile(&mut ctx, &chunk, key)?;
711 let trace = ctx
712 .cache
713 .get(&key)
714 .ok_or("trace missing after force_compile")?;
715 let mut slots = vec![0i64; 3];
716 let ret = run_compiled_trace_ref(trace, &mut slots, 0, 10_000, 0, 3);
717 assert!(matches!(ret.into_reason(), ExitReason::Trap { .. }));
718 Ok(())
719 }
720
721 #[test]
722 fn sync_slots_deopts_on_float() -> TestResult {
723 let chunk = add_chunk();
724 let mut vm = Vm::new(chunk, NativeTable::empty(), 0, &[])?;
725 vm.set_register(0, Value::Float(1.0))?;
726 let mut slots = vec![0i64; 3];
727 assert_eq!(sync_slots_from_vm(&vm, &mut slots), SyncSlotsResult::Deopt);
728 Ok(())
729 }
730
731 #[test]
732 fn runtime_path_compiles_and_runs() -> TestResult {
733 let chunk = add_chunk();
734 let runtime = JitRuntime::new(chunk.clone(), 1);
735 let key = TraceKey {
736 function: 0,
737 entry_pc: 0,
738 };
739 let mut slots = vec![0i64; 3];
740 let exit = try_run_hot_runtime(&runtime, &chunk, key, &mut slots, 10_000, 3, None)
741 .ok_or("expected jit execution")?;
742 assert!(matches!(exit, ExitReason::Return { return_reg: 2 }));
743 assert_eq!(slots[2], 42);
744 Ok(())
745 }
746
747 #[test]
748 fn budget_exit_when_exhausted_mid_trace() -> TestResult {
749 let mut b = ChunkBuilder::new("jit-budget");
750 b.begin_function("main", 0, 1);
751 b.emit_load_imm(0, 1);
752 b.emit_load_imm(0, 2);
753 b.emit_load_imm(0, 3);
754 b.emit_return(0);
755 let chunk = Arc::new(b.finish());
756
757 let mut ctx = JitContext::new(chunk.clone())?;
758 let key = TraceKey {
759 function: 0,
760 entry_pc: 0,
761 };
762 force_compile(&mut ctx, &chunk, key)?;
763 let trace = ctx
764 .cache
765 .get(&key)
766 .ok_or("trace missing after force_compile")?;
767 let mut slots = vec![0i64; 1];
768 let ret = run_compiled_trace_ref(trace, &mut slots, 0, 2, 0, 1);
769 assert!(matches!(ret.into_reason(), ExitReason::Budget { pc: 2 }));
770 Ok(())
771 }
772
773 #[test]
774 fn interleaved_jit_compiles_mid_quantum() -> TestResult {
775 let mut b = ChunkBuilder::new("jit-interleave");
776 b.begin_function("main", 0, 2);
777 b.emit_load_imm(0, 0);
778 let head = b.new_label();
779 b.bind_label(head);
780 b.emit_load_imm(1, 1);
781 b.emit_binop(Opcode::Add, 0, 0, 1);
782 b.emit_load_imm(1, 100);
783 b.emit_binop(Opcode::Lt, 1, 0, 1);
784 let done = b.new_label();
785 b.emit_branch(1, done);
786 b.emit_jump(head);
787 b.bind_label(done);
788 b.emit_return(0);
789 let chunk = Arc::new(b.finish());
790 let head_pc = chunk.functions[0].entry + 1;
791
792 let mut ctx = JitContext::new(chunk.clone())?;
793 ctx.hot_threshold = 2;
794 let mut vm = Vm::new(chunk, NativeTable::empty(), 0, &[])?;
795 let result = run_vm_with_jit(&mut vm, 10_000, &mut ctx);
796 assert!(matches!(result, VmResult::Complete(Value::Int(100))));
797 assert!(ctx
798 .cache
799 .get(&TraceKey {
800 function: 0,
801 entry_pc: head_pc,
802 })
803 .is_some());
804 Ok(())
805 }
806
807 #[test]
808 fn reload_chunk_invalidates_jit_cache() -> TestResult {
809 let chunk = add_chunk();
810 let runtime = JitRuntime::new(chunk.clone(), 1);
811 let key = TraceKey {
812 function: 0,
813 entry_pc: 0,
814 };
815 let mut slots = vec![0i64; 3];
816 let exit = try_run_hot_runtime(&runtime, &chunk, key, &mut slots, 10_000, 3, None)
817 .ok_or("expected jit execution")?;
818 assert!(matches!(exit, ExitReason::Return { .. }));
819
820 let mut b = ChunkBuilder::new("other");
821 b.begin_function("main", 0, 1);
822 b.emit_load_imm(0, 1);
823 b.emit_return(0);
824 runtime.reload(Arc::new(b.finish()));
825 assert!(runtime.get_trace(&key).is_none());
826 Ok(())
827 }
828
829 #[test]
832 fn budget_exit_publishes_assigned_regs_and_keeps_unit() -> TestResult {
833 let mut b = ChunkBuilder::new("jit-budget");
834 b.begin_function("main", 0, 2);
835 b.emit_load_imm(0, 41);
836 b.emit_load_imm(1, 1);
837 b.emit_return(0);
838 let chunk = Arc::new(b.finish());
839 let mut ctx = JitContext::new(chunk.clone())?;
840 let key = TraceKey {
841 function: 0,
842 entry_pc: 0,
843 };
844 force_compile(&mut ctx, &chunk, key)?;
845 let trace = ctx
846 .cache
847 .get(&key)
848 .ok_or("trace missing after force_compile")?;
849 let mut slots = vec![0i64; 2];
850 let ret = run_compiled_trace_ref(trace, &mut slots, 0, 1, 0, 2);
851 assert!(matches!(ret.into_reason(), ExitReason::Budget { pc: 1 }));
852 let mut vm = Vm::new(chunk, NativeTable::empty(), 0, &[])?;
853 apply_exit_tagged(&mut vm, &slots, ret)?;
854 let regs = vm.top_registers().ok_or("no frame")?;
855 assert!(matches!(regs.first(), Some(&Value::Int(41))));
856 assert!(matches!(regs.get(1), Some(&Value::Unit)));
857 Ok(())
858 }
859
860 #[test]
861 fn jit_call_does_not_clobber_the_caller_frame() -> TestResult {
862 let mut b = ChunkBuilder::new("jit-call-frames");
863 b.begin_function("callee", 0, 3);
864 b.emit_load_imm(2, 99);
865 b.emit_load_imm(0, 1);
866 b.emit_return(0);
867 let main = b.begin_function("main", 0, 3);
868 b.emit_load_imm(2, 7);
869 b.emit_call(0, 0, 0);
870 b.emit_return(2);
871 let chunk = Arc::new(b.finish());
872 let mut ctx = JitContext::new(chunk.clone())?;
873 let entry = chunk.functions[main as usize].entry;
874 force_compile(
875 &mut ctx,
876 &chunk,
877 TraceKey {
878 function: main,
879 entry_pc: entry,
880 },
881 )?;
882 let mut vm = Vm::new(chunk, NativeTable::empty(), main, &[])?;
883 let result = run_vm_with_jit(&mut vm, 10_000, &mut ctx);
884 assert!(matches!(result, VmResult::Complete(Value::Int(7))));
885 Ok(())
886 }
887
888 #[test]
889 fn move_keeps_bool_unit_and_a_later_int() -> TestResult {
890 let mut b = ChunkBuilder::new("jit-move-tags");
891 b.begin_function("cmp", 0, 4);
892 b.emit_load_imm(0, 1);
893 b.emit_load_imm(1, 1);
894 b.emit_binop(Opcode::Eq, 2, 0, 1);
895 b.emit_move(3, 2);
896 b.emit_return(3);
897 let moved_bool = b.begin_function("moved-bool", 1, 2);
898 b.emit_move(1, 0);
899 b.emit_return(1);
900 let moved_false = b.begin_function("moved-false", 1, 2);
901 b.emit_move(1, 0);
902 b.emit_return(1);
903 let moved_unit = b.begin_function("moved-unit", 0, 2);
904 b.emit_move(1, 0);
905 b.emit_return(1);
906 let overwritten = b.begin_function("overwritten", 1, 2);
907 b.emit_load_imm(0, 5);
908 let cont = b.new_label();
909 b.emit_jump(cont);
910 b.bind_label(cont);
911 b.emit_move(1, 0);
912 b.emit_return(1);
913 let chunk = Arc::new(b.finish());
914 let mut ctx = JitContext::new(chunk.clone())?;
915
916 let run = |ctx: &mut JitContext, function: u32, args: &[Value]| -> TestResult {
917 let entry = chunk.functions[function as usize].entry;
918 force_compile(
919 ctx,
920 &chunk,
921 TraceKey {
922 function,
923 entry_pc: entry,
924 },
925 )?;
926 let mut vm = Vm::new(chunk.clone(), NativeTable::empty(), function, args)?;
927 let result = run_vm_with_jit(&mut vm, 10_000, ctx);
928 match (function, result) {
929 (_, VmResult::Complete(Value::Bool(true))) if function == 0 => Ok(()),
930 (_, VmResult::Complete(Value::Bool(true))) if function == moved_bool => Ok(()),
931 (_, VmResult::Complete(Value::Bool(false))) if function == moved_false => Ok(()),
932 (_, VmResult::Complete(Value::Unit)) if function == moved_unit => Ok(()),
933 (_, VmResult::Complete(Value::Int(5))) if function == overwritten => Ok(()),
934 (_, other) => Err(format!("function {function} finished as {other:?}").into()),
935 }
936 };
937
938 run(&mut ctx, 0, &[])?;
939 run(&mut ctx, moved_bool, &[Value::Bool(true)])?;
940 run(&mut ctx, moved_false, &[Value::Bool(false)])?;
941 run(&mut ctx, moved_unit, &[])?;
942 run(&mut ctx, overwritten, &[Value::Bool(true)])?;
943 Ok(())
944 }
945}