Skip to main content

byteflow/jit/
runtime.rs

1//! Shared JIT state for the M:N runtime (cache + hot counters, lock-free execution path).
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
7use std::sync::{Arc, Mutex, RwLock};
8
9use crate::Chunk;
10
11use super::trace::{HotCounter, TraceCache, TraceKey, HOT_THRESHOLD};
12use super::CompiledTrace;
13
14/// Runtime-wide JIT state: compiled traces are shared; each worker thread owns
15/// its own Cranelift module for compilation (the private `module_local` helper).
16pub struct JitRuntime {
17    chunk: RwLock<Arc<Chunk>>,
18    pub hot_threshold: u32,
19    cache: RwLock<TraceCache>,
20    hot: Mutex<HotCounter>,
21}
22
23impl JitRuntime {
24    pub fn new(chunk: Arc<Chunk>, hot_threshold: u32) -> Self {
25        Self {
26            chunk: RwLock::new(chunk),
27            hot_threshold,
28            cache: RwLock::new(TraceCache::new()),
29            hot: Mutex::new(HotCounter::default()),
30        }
31    }
32
33    pub fn with_default_threshold(chunk: Arc<Chunk>) -> Self {
34        Self::new(chunk, HOT_THRESHOLD)
35    }
36
37    /// Current bytecode image this cache was built for.
38    pub fn chunk(&self) -> Option<Arc<Chunk>> {
39        self.chunk.read().ok().map(|g| Arc::clone(&g))
40    }
41
42    /// True when `vm_chunk` is the same image as the JIT cache.
43    pub fn matches_chunk(&self, vm_chunk: &Arc<Chunk>) -> bool {
44        match self.chunk.read() {
45            Ok(guard) => Arc::ptr_eq(&guard, vm_chunk),
46            Err(_) => false,
47        }
48    }
49
50    /// Replace the bytecode image and discard stale compiled traces.
51    pub fn reload(&self, chunk: Arc<Chunk>) {
52        if let Ok(mut current) = self.chunk.write() {
53            *current = chunk;
54        }
55        if let Ok(mut cache) = self.cache.write() {
56            cache.clear();
57        }
58        if let Ok(mut hot) = self.hot.lock() {
59            hot.clear();
60        }
61    }
62
63    pub fn get_trace(&self, key: &TraceKey) -> Option<JitEntryCopy> {
64        let cache = self.cache.read().ok()?;
65        cache.get(key).map(|t| JitEntryCopy { entry: t.entry })
66    }
67
68    pub fn is_failed(&self, key: &TraceKey) -> bool {
69        self.cache
70            .read()
71            .ok()
72            .map(|c| c.is_failed(key))
73            .unwrap_or(false)
74    }
75
76    pub fn mark_failed(&self, key: TraceKey) {
77        if let Ok(mut cache) = self.cache.write() {
78            cache.mark_failed(key);
79        }
80    }
81
82    pub fn insert_trace(&self, key: TraceKey, trace: CompiledTrace) {
83        if let Ok(mut cache) = self.cache.write() {
84            cache.insert(key, trace);
85        }
86    }
87
88    pub fn record_hot_hit(&self, key: TraceKey) -> bool {
89        let Ok(mut hot) = self.hot.lock() else {
90            return false;
91        };
92        hot.hit(key, self.hot_threshold)
93    }
94}
95
96/// [`JitEntry`] is a function pointer and safe to copy out of the cache briefly.
97#[derive(Clone, Copy)]
98pub struct JitEntryCopy {
99    pub entry: super::frame::JitEntry,
100}