Skip to main content

byteflow/jit/
trace.rs

1use std::collections::HashMap;
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}
41
42impl TraceCache {
43    pub fn new() -> Self {
44        Self {
45            traces: HashMap::new(),
46        }
47    }
48
49    pub fn get(&self, key: &TraceKey) -> Option<&CompiledTrace> {
50        self.traces.get(key)
51    }
52
53    pub fn insert(&mut self, key: TraceKey, trace: CompiledTrace) {
54        self.traces.insert(key, trace);
55    }
56
57    pub fn clear(&mut self) {
58        self.traces.clear();
59    }
60
61    #[cfg(test)]
62    pub(crate) fn has_float_trace(&self) -> bool {
63        self.traces.keys().any(|key| key.floats)
64    }
65}
66
67impl Default for TraceCache {
68    fn default() -> Self {
69        Self::new()
70    }
71}
72
73#[derive(Default)]
74pub struct HotCounter {
75    counters: HashMap<TraceKey, u32>,
76}
77
78impl HotCounter {
79    pub fn hit(&mut self, key: TraceKey, threshold: u32) -> bool {
80        let counter = self.counters.entry(key).or_insert(0);
81        *counter = counter.saturating_add(1);
82        *counter >= threshold
83    }
84
85    pub fn reset(&mut self, key: TraceKey) {
86        self.counters.remove(&key);
87    }
88
89    pub fn clear(&mut self) {
90        self.counters.clear();
91    }
92}
93
94pub struct JitContext {
95    pub chunk: Arc<Chunk>,
96    pub cache: TraceCache,
97    pub hot: HotCounter,
98    pub hot_threshold: u32,
99    module: cranelift_jit::JITModule,
100}
101
102pub(crate) fn cranelift_flags() -> cranelift_codegen::settings::Flags {
103    let mut flag_builder = cranelift_codegen::settings::builder();
104    if !cfg!(debug_assertions) {
105        // Debug compiles stay at Cranelift's default (`none`). Release
106        // traces pay for the speed pipeline once per hot region.
107        let _ = flag_builder.set("opt_level", "speed");
108    }
109    cranelift_codegen::settings::Flags::new(flag_builder)
110}
111
112impl JitContext {
113    pub fn new(chunk: Arc<Chunk>) -> Result<Self, super::error::CompileError> {
114        let flags = cranelift_flags();
115        let isa = cranelift_native::builder()
116            .map_err(|e| super::error::CompileError::Backend(e.to_string()))?
117            .finish(flags)
118            .map_err(|e| super::error::CompileError::Backend(e.to_string()))?;
119        let builder =
120            cranelift_jit::JITBuilder::with_isa(isa, cranelift_module::default_libcall_names());
121        let module = cranelift_jit::JITModule::new(builder);
122        Ok(Self {
123            chunk,
124            cache: TraceCache::new(),
125            hot: HotCounter::default(),
126            hot_threshold: HOT_THRESHOLD,
127            module,
128        })
129    }
130
131    pub fn module_mut(&mut self) -> &mut cranelift_jit::JITModule {
132        &mut self.module
133    }
134
135    /// Drop compiled traces and hot counters after the bytecode image changes.
136    pub fn reload(&mut self, chunk: Arc<Chunk>) {
137        self.chunk = chunk;
138        self.cache.clear();
139        self.hot.clear();
140    }
141}