1 //! This module provides a set of primitives that allow implementing an incremental cache on top of 2 //! Cranelift, making it possible to reuse previous compiled artifacts for functions that have been 3 //! compiled previously. 4 //! 5 //! This set of operation is experimental and can be enabled using the Cargo feature 6 //! `incremental-cache`. 7 //! 8 //! This can bring speedups in different cases: change-code-and-immediately-recompile iterations 9 //! get faster, modules sharing lots of code can reuse each other's artifacts, etc. 10 //! 11 //! The three main primitives are the following: 12 //! - `compute_cache_key` is used to compute the cache key associated to a `Function`. This is 13 //! basically the content of the function, modulo a few things the caching system is resilient to. 14 //! - `serialize_compiled` is used to serialize the result of a compilation, so it can be reused 15 //! later on by... 16 //! - `try_finish_recompile`, which reads binary blobs serialized with `serialize_compiled`, 17 //! re-creating the compilation artifact from those. 18 //! 19 //! The `CacheStore` trait and `Context::compile_with_cache` method are provided as 20 //! high-level, easy-to-use facilities to make use of that cache, and show an example of how to use 21 //! the above three primitives to form a full incremental caching system. 22 23 use core::fmt; 24 25 use crate::alloc::string::String; 26 use crate::alloc::vec::Vec; 27 use crate::ir::function::{FunctionStencil, VersionMarker}; 28 use crate::ir::Function; 29 use crate::machinst::{CompiledCode, CompiledCodeStencil}; 30 use crate::result::CompileResult; 31 use crate::{isa::TargetIsa, timing}; 32 use crate::{trace, CompileError, Context}; 33 use alloc::borrow::{Cow, ToOwned as _}; 34 use alloc::string::ToString as _; 35 36 impl Context { 37 /// Compile the function, as in `compile`, but tries to reuse compiled artifacts from former 38 /// compilations using the provided cache store. 39 pub fn compile_with_cache( 40 &mut self, 41 isa: &dyn TargetIsa, 42 cache_store: &mut dyn CacheKvStore, 43 ) -> CompileResult<(&CompiledCode, bool)> { 44 let cache_key_hash = { 45 let _tt = timing::try_incremental_cache(); 46 47 let cache_key_hash = compute_cache_key(isa, &mut self.func); 48 49 if let Some(blob) = cache_store.get(&cache_key_hash.0) { 50 match try_finish_recompile(&self.func, &blob) { 51 Ok(compiled_code) => { 52 let info = compiled_code.code_info(); 53 54 if isa.flags().enable_incremental_compilation_cache_checks() { 55 let actual_result = self.compile(isa)?; 56 assert_eq!(*actual_result, compiled_code); 57 assert_eq!(actual_result.code_info(), info); 58 // no need to set `compiled_code` here, it's set by `compile()`. 59 return Ok((actual_result, true)); 60 } 61 62 let compiled_code = self.compiled_code.insert(compiled_code); 63 return Ok((compiled_code, true)); 64 } 65 Err(err) => { 66 trace!("error when finishing recompilation: {err}"); 67 } 68 } 69 } 70 71 cache_key_hash 72 }; 73 74 let stencil = self.compile_stencil(isa).map_err(|err| CompileError { 75 inner: err, 76 func: &self.func, 77 })?; 78 79 let stencil = { 80 let _tt = timing::store_incremental_cache(); 81 let (stencil, res) = serialize_compiled(stencil); 82 if let Ok(blob) = res { 83 cache_store.insert(&cache_key_hash.0, blob); 84 } 85 stencil 86 }; 87 88 let compiled_code = self 89 .compiled_code 90 .insert(stencil.apply_params(&self.func.params)); 91 92 Ok((compiled_code, false)) 93 } 94 } 95 96 /// Backing storage for an incremental compilation cache, when enabled. 97 pub trait CacheKvStore { 98 /// Given a cache key hash, retrieves the associated opaque serialized data. 99 fn get(&self, key: &[u8]) -> Option<Cow<[u8]>>; 100 101 /// Given a new cache key and a serialized blob obtained from `serialize_compiled`, stores it 102 /// in the cache store. 103 fn insert(&mut self, key: &[u8], val: Vec<u8>); 104 } 105 106 /// Hashed `CachedKey`, to use as an identifier when looking up whether a function has already been 107 /// compiled or not. 108 #[derive(Clone, Hash, PartialEq, Eq)] 109 pub struct CacheKeyHash([u8; 32]); 110 111 impl std::fmt::Display for CacheKeyHash { 112 fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { 113 write!(f, "CacheKeyHash:{:?}", self.0) 114 } 115 } 116 117 #[derive(serde::Serialize, serde::Deserialize)] 118 struct CachedFunc { 119 stencil: CompiledCodeStencil, 120 version_marker: VersionMarker, 121 } 122 123 /// Key for caching a single function's compilation. 124 /// 125 /// If two functions get the same `CacheKey`, then we can reuse the compiled artifacts, modulo some 126 /// fixups. 127 /// 128 /// Note: the key will be invalidated across different versions of cranelift, as the 129 /// `FunctionStencil` contains a `VersionMarker` itself. 130 #[derive(Hash)] 131 struct CacheKey<'a> { 132 stencil: &'a FunctionStencil, 133 parameters: CompileParameters, 134 } 135 136 #[derive(Clone, PartialEq, Hash, serde::Serialize, serde::Deserialize)] 137 struct CompileParameters { 138 isa: String, 139 triple: String, 140 flags: String, 141 isa_flags: Vec<String>, 142 } 143 144 impl CompileParameters { 145 fn from_isa(isa: &dyn TargetIsa) -> Self { 146 Self { 147 isa: isa.name().to_owned(), 148 triple: isa.triple().to_string(), 149 flags: isa.flags().to_string(), 150 isa_flags: isa 151 .isa_flags() 152 .into_iter() 153 .map(|v| v.value_string()) 154 .collect(), 155 } 156 } 157 } 158 159 impl<'a> CacheKey<'a> { 160 /// Creates a new cache store key for a function. 161 /// 162 /// This is a bit expensive to compute, so it should be cached and reused as much as possible. 163 fn new(isa: &dyn TargetIsa, f: &'a mut Function) -> Self { 164 // Make sure the blocks and instructions are sequenced the same way as we might 165 // have serialized them earlier. This is the symmetric of what's done in 166 // `try_load`. 167 f.stencil.layout.full_renumber(); 168 CacheKey { 169 stencil: &f.stencil, 170 parameters: CompileParameters::from_isa(isa), 171 } 172 } 173 } 174 175 /// Compute a cache key, and hash it on your behalf. 176 /// 177 /// Since computing the `CacheKey` is a bit expensive, it should be done as least as possible. 178 pub fn compute_cache_key(isa: &dyn TargetIsa, func: &mut Function) -> CacheKeyHash { 179 use core::hash::{Hash as _, Hasher}; 180 use sha2::Digest as _; 181 182 struct Sha256Hasher(sha2::Sha256); 183 184 impl Hasher for Sha256Hasher { 185 fn finish(&self) -> u64 { 186 panic!("Sha256Hasher doesn't support finish!"); 187 } 188 fn write(&mut self, bytes: &[u8]) { 189 self.0.update(bytes); 190 } 191 } 192 193 let cache_key = CacheKey::new(isa, func); 194 195 let mut hasher = Sha256Hasher(sha2::Sha256::new()); 196 cache_key.hash(&mut hasher); 197 let hash: [u8; 32] = hasher.0.finalize().into(); 198 199 CacheKeyHash(hash) 200 } 201 202 /// Given a function that's been successfully compiled, serialize it to a blob that the caller may 203 /// store somewhere for future use by `try_finish_recompile`. 204 /// 205 /// As this function requires ownership on the `CompiledCodeStencil`, it gives it back at the end 206 /// of the function call. The value is left untouched. 207 pub fn serialize_compiled( 208 result: CompiledCodeStencil, 209 ) -> (CompiledCodeStencil, Result<Vec<u8>, bincode::Error>) { 210 let cached = CachedFunc { 211 stencil: result, 212 version_marker: VersionMarker, 213 }; 214 let result = bincode::serialize(&cached); 215 (cached.stencil, result) 216 } 217 218 /// An error returned when recompiling failed. 219 #[derive(Debug)] 220 pub enum RecompileError { 221 /// The version embedded in the cache entry isn't the same as cranelift's current version. 222 VersionMismatch, 223 /// An error occurred while deserializing the cache entry. 224 Deserialize(bincode::Error), 225 } 226 227 impl fmt::Display for RecompileError { 228 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { 229 match self { 230 RecompileError::VersionMismatch => write!(f, "cranelift version mismatch",), 231 RecompileError::Deserialize(err) => { 232 write!(f, "bincode failed during deserialization: {err}") 233 } 234 } 235 } 236 } 237 238 /// Given a function that's been precompiled and its entry in the caching storage, try to shortcut 239 /// compilation of the given function. 240 /// 241 /// Precondition: the bytes must have retrieved from a cache store entry which hash value 242 /// is strictly the same as the `Function`'s computed hash retrieved from `compute_cache_key`. 243 pub fn try_finish_recompile(func: &Function, bytes: &[u8]) -> Result<CompiledCode, RecompileError> { 244 match bincode::deserialize::<CachedFunc>(bytes) { 245 Ok(result) => { 246 if result.version_marker != func.stencil.version_marker { 247 Err(RecompileError::VersionMismatch) 248 } else { 249 Ok(result.stencil.apply_params(&func.params)) 250 } 251 } 252 Err(err) => Err(RecompileError::Deserialize(err)), 253 } 254 } 255