Skip to main content

byteflow/jit/
trace.rs

1use std::collections::{HashMap, HashSet};
2use std::ops::Range;
3use std::sync::Arc;
4
5use cranelift_codegen::settings::Configurable;
6
7use crate::Chunk;
8
9use super::frame::JitEntry;
10
11/// Maximum instructions recorded into a single trace.
12pub const MAX_TRACE_LENGTH: usize = 256;
13
14/// How many times `(function, pc)` must run before compilation is attempted.
15pub const HOT_THRESHOLD: u32 = 1_000;
16
17#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
18pub struct TraceKey {
19    pub function: u32,
20    pub entry_pc: u32,
21    /// `true` when every live register at entry was `Float`, `Bool`, or
22    /// `Unit`. Arithmetic in the trace is IEEE `f64`, not wrapping `i64`.
23    pub floats: bool,
24}
25
26#[derive(Debug, Clone)]
27pub struct TraceSpan {
28    pub function: u32,
29    pub range: Range<u32>,
30}
31
32#[derive(Debug)]
33pub struct CompiledTrace {
34    pub span: TraceSpan,
35    pub entry: JitEntry,
36}
37
38pub struct TraceCache {
39    traces: HashMap<TraceKey, CompiledTrace>,
40    failed: HashSet<TraceKey>,
41}
42
43impl TraceCache {
44    pub fn new() -> Self {
45        Self {
46            traces: HashMap::new(),
47            failed: HashSet::new(),
48        }
49    }
50
51    pub fn get(&self, key: &TraceKey) -> Option<&CompiledTrace> {
52        self.traces.get(key)
53    }
54
55    pub fn is_failed(&self, key: &TraceKey) -> bool {
56        self.failed.contains(key)
57    }
58
59    pub fn mark_failed(&mut self, key: TraceKey) {
60        self.failed.insert(key);
61    }
62
63    pub fn insert(&mut self, key: TraceKey, trace: CompiledTrace) {
64        self.traces.insert(key, trace);
65    }
66
67    pub fn clear(&mut self) {
68        self.traces.clear();
69        self.failed.clear();
70    }
71
72    #[cfg(test)]
73    pub(crate) fn has_float_trace(&self) -> bool {
74        self.traces.keys().any(|key| key.floats)
75    }
76
77    /// `pc` lies in a trace compiled with `TraceKey::floats`.
78    #[cfg(test)]
79    pub(crate) fn float_trace_covers(&self, pc: u32) -> bool {
80        self.traces.iter().any(|(key, trace)| {
81            key.floats && trace.span.function == key.function && trace.span.range.contains(&pc)
82        })
83    }
84}
85
86impl Default for TraceCache {
87    fn default() -> Self {
88        Self::new()
89    }
90}
91
92#[derive(Default)]
93pub struct HotCounter {
94    counters: HashMap<TraceKey, u32>,
95}
96
97impl HotCounter {
98    pub fn hit(&mut self, key: TraceKey, threshold: u32) -> bool {
99        let counter = self.counters.entry(key).or_insert(0);
100        *counter = counter.saturating_add(1);
101        *counter >= threshold
102    }
103
104    pub fn reset(&mut self, key: TraceKey) {
105        self.counters.remove(&key);
106    }
107
108    pub fn clear(&mut self) {
109        self.counters.clear();
110    }
111}
112
113pub struct JitContext {
114    pub chunk: Arc<Chunk>,
115    pub cache: TraceCache,
116    pub hot: HotCounter,
117    pub hot_threshold: u32,
118    module: cranelift_jit::JITModule,
119}
120
121pub(crate) fn cranelift_flags() -> cranelift_codegen::settings::Flags {
122    let mut flag_builder = cranelift_codegen::settings::builder();
123    if !cfg!(debug_assertions) {
124        // Debug compiles stay at Cranelift's default (`none`). Release
125        // traces pay for the speed pipeline once per hot region.
126        let _ = flag_builder.set("opt_level", "speed");
127    }
128    cranelift_codegen::settings::Flags::new(flag_builder)
129}
130
131impl JitContext {
132    pub fn new(chunk: Arc<Chunk>) -> Result<Self, super::error::CompileError> {
133        let flags = cranelift_flags();
134        let isa = cranelift_native::builder()
135            .map_err(|e| super::error::CompileError::Backend(e.to_string()))?
136            .finish(flags)
137            .map_err(|e| super::error::CompileError::Backend(e.to_string()))?;
138        let builder =
139            cranelift_jit::JITBuilder::with_isa(isa, cranelift_module::default_libcall_names());
140        let module = cranelift_jit::JITModule::new(builder);
141        Ok(Self {
142            chunk,
143            cache: TraceCache::new(),
144            hot: HotCounter::default(),
145            hot_threshold: HOT_THRESHOLD,
146            module,
147        })
148    }
149
150    pub fn module_mut(&mut self) -> &mut cranelift_jit::JITModule {
151        &mut self.module
152    }
153
154    /// Drop compiled traces and hot counters after the bytecode image changes.
155    pub fn reload(&mut self, chunk: Arc<Chunk>) {
156        self.chunk = chunk;
157        self.cache.clear();
158        self.hot.clear();
159    }
160}