use core::fmt;
use core::hash::{Hash, Hasher};
use crate::alloc::vec::Vec;
use crate::ir::Function;
use crate::ir::function::{FunctionStencil, VersionMarker};
use crate::machinst::{CompiledCode, CompiledCodeStencil};
use crate::result::CompileResult;
use crate::{CompileError, Context, trace};
use crate::{isa::TargetIsa, timing};
use alloc::borrow::Cow;
use cranelift_control::ControlPlane;
impl Context {
pub fn compile_with_cache(
&mut self,
isa: &dyn TargetIsa,
cache_store: &mut dyn CacheKvStore,
ctrl_plane: &mut ControlPlane,
) -> CompileResult<'_, (&CompiledCode, bool)> {
let cache_key_hash = {
let _tt = timing::try_incremental_cache();
let cache_key_hash = compute_cache_key(isa, &self.func);
if let Some(blob) = cache_store.get(&cache_key_hash.0) {
match try_finish_recompile(&self.func, &blob) {
Ok(compiled_code) => {
let info = compiled_code.code_info();
if isa.flags().enable_incremental_compilation_cache_checks() {
let actual_result = self.compile(isa, ctrl_plane)?;
assert_eq!(*actual_result, compiled_code);
assert_eq!(actual_result.code_info(), info);
return Ok((actual_result, true));
}
let compiled_code = self.compiled_code.insert(compiled_code);
return Ok((compiled_code, true));
}
Err(err) => {
trace!("error when finishing recompilation: {err}");
}
}
}
cache_key_hash
};
let stencil = self
.compile_stencil(isa, ctrl_plane)
.map_err(|err| CompileError {
inner: err,
func: &self.func,
})?;
let stencil = {
let _tt = timing::store_incremental_cache();
let (stencil, res) = serialize_compiled(stencil);
if let Ok(blob) = res {
cache_store.insert(&cache_key_hash.0, blob);
}
stencil
};
let compiled_code = self
.compiled_code
.insert(stencil.apply_params(&self.func.params));
Ok((compiled_code, false))
}
}
pub trait CacheKvStore {
fn get(&self, key: &[u8]) -> Option<Cow<'_, [u8]>>;
fn insert(&mut self, key: &[u8], val: Vec<u8>);
}
#[derive(Clone, Hash, PartialEq, Eq)]
pub struct CacheKeyHash([u8; 32]);
impl core::fmt::Display for CacheKeyHash {
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
write!(f, "CacheKeyHash:{:?}", self.0)
}
}
#[derive(serde_derive::Serialize, serde_derive::Deserialize)]
struct CachedFunc {
version_marker: VersionMarker,
stencil: CompiledCodeStencil,
}
struct CacheKey<'a> {
stencil: &'a FunctionStencil,
isa: &'a dyn TargetIsa,
}
impl<'a> Hash for CacheKey<'a> {
fn hash<H: Hasher>(&self, state: &mut H) {
self.stencil.hash(state);
self.isa.name().hash(state);
self.isa.triple().hash(state);
self.isa.flags().hash(state);
self.isa.isa_flags_hash_key().hash(state);
}
}
impl<'a> CacheKey<'a> {
fn new(isa: &'a dyn TargetIsa, f: &'a Function) -> Self {
CacheKey {
stencil: &f.stencil,
isa,
}
}
}
pub fn compute_cache_key(isa: &dyn TargetIsa, func: &Function) -> CacheKeyHash {
use core::hash::{Hash as _, Hasher};
use sha2::Digest as _;
struct Sha256Hasher(sha2::Sha256);
impl Hasher for Sha256Hasher {
fn finish(&self) -> u64 {
panic!("Sha256Hasher doesn't support finish!");
}
fn write(&mut self, bytes: &[u8]) {
self.0.update(bytes);
}
}
let cache_key = CacheKey::new(isa, func);
let mut hasher = Sha256Hasher(sha2::Sha256::new());
cache_key.hash(&mut hasher);
let hash: [u8; 32] = hasher.0.finalize().into();
CacheKeyHash(hash)
}
pub fn serialize_compiled(
result: CompiledCodeStencil,
) -> (CompiledCodeStencil, Result<Vec<u8>, postcard::Error>) {
let cached = CachedFunc {
version_marker: VersionMarker,
stencil: result,
};
let result = postcard::to_allocvec(&cached);
(cached.stencil, result)
}
#[derive(Debug)]
pub enum RecompileError {
VersionMismatch,
Deserialize(postcard::Error),
}
impl fmt::Display for RecompileError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
RecompileError::VersionMismatch => write!(f, "cranelift version mismatch",),
RecompileError::Deserialize(err) => {
write!(f, "postcard failed during deserialization: {err}")
}
}
}
}
pub fn try_finish_recompile(func: &Function, bytes: &[u8]) -> Result<CompiledCode, RecompileError> {
match postcard::from_bytes::<CachedFunc>(bytes) {
Ok(result) => {
if result.version_marker != func.stencil.version_marker {
Err(RecompileError::VersionMismatch)
} else {
Ok(result.stencil.apply_params(&func.params))
}
}
Err(err) => Err(RecompileError::Deserialize(err)),
}
}