Implement an incremental compilation cache for Cranelift (#4551)
This is the implementation of https://github.com/bytecodealliance/wasmtime/issues/4155, using the "inverted API" approach suggested by @cfallin (thanks!) in Cranelift, and trait object to provide a backend for an all-included experience in Wasmtime. After the suggestion of Chris, `Function` has been split into mostly two parts: - on the one hand, `FunctionStencil` contains all the fields required during compilation, and that act as a compilation cache key: if two function stencils are the same, then the result of their compilation (`CompiledCodeBase<Stencil>`) will be the same. This makes caching trivial, as the only thing to cache is the `FunctionStencil`. - on the other hand, `FunctionParameters` contain the... function parameters that are required to finalize the result of compilation into a `CompiledCode` (aka `CompiledCodeBase<Final>`) with proper final relocations etc., by applying fixups and so on. Most changes are here to accomodate those requirements, in particular that `FunctionStencil` should be `Hash`able to be used as a key in the cache: - most source locations are now relative to a base source location in the function, and as such they're encoded as `RelSourceLoc` in the `FunctionStencil`. This required changes so that there's no need to explicitly mark a `SourceLoc` as the base source location, it's automatically detected instead the first time a non-default `SourceLoc` is set. - user-defined external names in the `FunctionStencil` (aka before this patch `ExternalName::User { namespace, index }`) are now references into an external table of `UserExternalNameRef -> UserExternalName`, present in the `FunctionParameters`, and must be explicitly declared using `Function::declare_imported_user_function`. - some refactorings have been made for function names: - `ExternalName` was used as the type for a `Function`'s name; while it thus allowed `ExternalName::Libcall` in this place, this would have been quite confusing to use it there. Instead, a new enum `UserFuncName` is introduced for this name, that's either a user-defined function name (the above `UserExternalName`) or a test case name. - The future of `ExternalName` is likely to become a full reference into the `FunctionParameters`'s mapping, instead of being "either a handle for user-defined external names, or the thing itself for other variants". I'm running out of time to do this, and this is not trivial as it implies touching ISLE which I'm less familiar with. The cache computes a sha256 hash of the `FunctionStencil`, and uses this as the cache key. No equality check (using `PartialEq`) is performed in addition to the hash being the same, as we hope that this is sufficient data to avoid collisions. A basic fuzz target has been introduced that tries to do the bare minimum: - check that a function successfully compiled and cached will be also successfully reloaded from the cache, and returns the exact same function. - check that a trivial modification in the external mapping of `UserExternalNameRef -> UserExternalName` hits the cache, and that other modifications don't hit the cache. - This last check is less efficient and less likely to happen, so probably should be rethought a bit. Thanks to both @alexcrichton and @cfallin for your very useful feedback on Zulip. Some numbers show that for a large wasm module we're using internally, this is a 20% compile-time speedup, because so many `FunctionStencil`s are the same, even within a single module. For a group of modules that have a lot of code in common, we get hit rates up to 70% when they're used together. When a single function changes in a wasm module, every other function is reloaded; that's still slower than I expect (between 10% and 50% of the overall compile time), so there's likely room for improvement. Fixes #4155.
This commit is contained in:
@@ -1,3 +1,4 @@
|
||||
use codegen::ir::UserFuncName;
|
||||
use cranelift::prelude::*;
|
||||
use cranelift_codegen::settings::{self, Configurable};
|
||||
use cranelift_jit::{JITBuilder, JITModule};
|
||||
@@ -35,7 +36,8 @@ fn main() {
|
||||
.unwrap();
|
||||
|
||||
ctx.func.signature = sig_a;
|
||||
ctx.func.name = ExternalName::user(0, func_a.as_u32());
|
||||
ctx.func.name = UserFuncName::user(0, func_a.as_u32());
|
||||
|
||||
{
|
||||
let mut bcx: FunctionBuilder = FunctionBuilder::new(&mut ctx.func, &mut func_ctx);
|
||||
let block = bcx.create_block();
|
||||
@@ -53,7 +55,8 @@ fn main() {
|
||||
module.clear_context(&mut ctx);
|
||||
|
||||
ctx.func.signature = sig_b;
|
||||
ctx.func.name = ExternalName::user(0, func_b.as_u32());
|
||||
ctx.func.name = UserFuncName::user(0, func_b.as_u32());
|
||||
|
||||
{
|
||||
let mut bcx: FunctionBuilder = FunctionBuilder::new(&mut ctx.func, &mut func_ctx);
|
||||
let block = bcx.create_block();
|
||||
|
||||
@@ -8,7 +8,7 @@ use cranelift_codegen::{binemit::Reloc, CodegenError};
|
||||
use cranelift_entity::SecondaryMap;
|
||||
use cranelift_module::{
|
||||
DataContext, DataDescription, DataId, FuncId, Init, Linkage, Module, ModuleCompiledFunction,
|
||||
ModuleDeclarations, ModuleError, ModuleResult,
|
||||
ModuleDeclarations, ModuleError, ModuleExtName, ModuleReloc, ModuleResult,
|
||||
};
|
||||
use log::info;
|
||||
use std::cell::RefCell;
|
||||
@@ -275,9 +275,9 @@ impl JITModule {
|
||||
std::ptr::write(plt_ptr, plt_val);
|
||||
}
|
||||
|
||||
fn get_address(&self, name: &ir::ExternalName) -> *const u8 {
|
||||
fn get_address(&self, name: &ModuleExtName) -> *const u8 {
|
||||
match *name {
|
||||
ir::ExternalName::User { .. } => {
|
||||
ModuleExtName::User { .. } => {
|
||||
let (name, linkage) = if ModuleDeclarations::is_function(name) {
|
||||
if self.hotswap_enabled {
|
||||
return self.get_plt_address(name);
|
||||
@@ -309,12 +309,12 @@ impl JITModule {
|
||||
panic!("can't resolve symbol {}", name);
|
||||
}
|
||||
}
|
||||
ir::ExternalName::LibCall(ref libcall) => {
|
||||
ModuleExtName::LibCall(ref libcall) => {
|
||||
let sym = (self.libcall_names)(*libcall);
|
||||
self.lookup_symbol(&sym)
|
||||
.unwrap_or_else(|| panic!("can't resolve libcall {}", sym))
|
||||
}
|
||||
_ => panic!("invalid ExternalName {}", name),
|
||||
_ => panic!("invalid name"),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -326,9 +326,9 @@ impl JITModule {
|
||||
unsafe { got_entry.as_ref() }.load(Ordering::SeqCst)
|
||||
}
|
||||
|
||||
fn get_got_address(&self, name: &ir::ExternalName) -> NonNull<AtomicPtr<u8>> {
|
||||
fn get_got_address(&self, name: &ModuleExtName) -> NonNull<AtomicPtr<u8>> {
|
||||
match *name {
|
||||
ir::ExternalName::User { .. } => {
|
||||
ModuleExtName::User { .. } => {
|
||||
if ModuleDeclarations::is_function(name) {
|
||||
let func_id = FuncId::from_name(name);
|
||||
self.function_got_entries[func_id].unwrap()
|
||||
@@ -337,17 +337,17 @@ impl JITModule {
|
||||
self.data_object_got_entries[data_id].unwrap()
|
||||
}
|
||||
}
|
||||
ir::ExternalName::LibCall(ref libcall) => *self
|
||||
ModuleExtName::LibCall(ref libcall) => *self
|
||||
.libcall_got_entries
|
||||
.get(libcall)
|
||||
.unwrap_or_else(|| panic!("can't resolve libcall {}", libcall)),
|
||||
_ => panic!("invalid ExternalName {}", name),
|
||||
_ => panic!("invalid name"),
|
||||
}
|
||||
}
|
||||
|
||||
fn get_plt_address(&self, name: &ir::ExternalName) -> *const u8 {
|
||||
fn get_plt_address(&self, name: &ModuleExtName) -> *const u8 {
|
||||
match *name {
|
||||
ir::ExternalName::User { .. } => {
|
||||
ModuleExtName::User { .. } => {
|
||||
if ModuleDeclarations::is_function(name) {
|
||||
let func_id = FuncId::from_name(name);
|
||||
self.function_plt_entries[func_id]
|
||||
@@ -358,13 +358,13 @@ impl JITModule {
|
||||
unreachable!("PLT relocations can only have functions as target");
|
||||
}
|
||||
}
|
||||
ir::ExternalName::LibCall(ref libcall) => self
|
||||
ModuleExtName::LibCall(ref libcall) => self
|
||||
.libcall_plt_entries
|
||||
.get(libcall)
|
||||
.unwrap_or_else(|| panic!("can't resolve libcall {}", libcall))
|
||||
.as_ptr()
|
||||
.cast::<u8>(),
|
||||
_ => panic!("invalid ExternalName {}", name),
|
||||
_ => panic!("invalid name"),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -631,12 +631,16 @@ impl Module for JITModule {
|
||||
///
|
||||
/// TODO: Coalesce redundant decls and signatures.
|
||||
/// TODO: Look into ways to reduce the risk of using a FuncRef in the wrong function.
|
||||
fn declare_func_in_func(&self, func: FuncId, in_func: &mut ir::Function) -> ir::FuncRef {
|
||||
fn declare_func_in_func(&mut self, func: FuncId, in_func: &mut ir::Function) -> ir::FuncRef {
|
||||
let decl = self.declarations.get_function_decl(func);
|
||||
let signature = in_func.import_signature(decl.signature.clone());
|
||||
let colocated = !self.hotswap_enabled && decl.linkage.is_final();
|
||||
let user_name_ref = in_func.declare_imported_user_function(ir::UserExternalName {
|
||||
namespace: 0,
|
||||
index: func.as_u32(),
|
||||
});
|
||||
in_func.import_function(ir::ExtFuncData {
|
||||
name: ir::ExternalName::user(0, func.as_u32()),
|
||||
name: ir::ExternalName::user(user_name_ref),
|
||||
signature,
|
||||
colocated,
|
||||
})
|
||||
@@ -648,24 +652,18 @@ impl Module for JITModule {
|
||||
fn declare_data_in_func(&self, data: DataId, func: &mut ir::Function) -> ir::GlobalValue {
|
||||
let decl = self.declarations.get_data_decl(data);
|
||||
let colocated = !self.hotswap_enabled && decl.linkage.is_final();
|
||||
let user_name_ref = func.declare_imported_user_function(ir::UserExternalName {
|
||||
namespace: 1,
|
||||
index: data.as_u32(),
|
||||
});
|
||||
func.create_global_value(ir::GlobalValueData::Symbol {
|
||||
name: ir::ExternalName::user(1, data.as_u32()),
|
||||
name: ir::ExternalName::user(user_name_ref),
|
||||
offset: ir::immediates::Imm64::new(0),
|
||||
colocated,
|
||||
tls: decl.tls,
|
||||
})
|
||||
}
|
||||
|
||||
/// TODO: Same as above.
|
||||
fn declare_func_in_data(&self, func: FuncId, ctx: &mut DataContext) -> ir::FuncRef {
|
||||
ctx.import_function(ir::ExternalName::user(0, func.as_u32()))
|
||||
}
|
||||
|
||||
/// TODO: Same as above.
|
||||
fn declare_data_in_data(&self, data: DataId, ctx: &mut DataContext) -> ir::GlobalValue {
|
||||
ctx.import_global_value(ir::ExternalName::user(1, data.as_u32()))
|
||||
}
|
||||
|
||||
fn define_function(
|
||||
&mut self,
|
||||
id: FuncId,
|
||||
@@ -681,7 +679,10 @@ impl Module for JITModule {
|
||||
return Err(ModuleError::DuplicateDefinition(decl.name.to_owned()));
|
||||
}
|
||||
|
||||
let compiled_code = ctx.compile(self.isa())?;
|
||||
// work around borrow-checker to allow reuse of ctx below
|
||||
let _ = ctx.compile(self.isa())?;
|
||||
let compiled_code = ctx.compiled_code().unwrap();
|
||||
|
||||
let code_size = compiled_code.code_info().total_size;
|
||||
|
||||
let size = code_size as usize;
|
||||
@@ -696,7 +697,12 @@ impl Module for JITModule {
|
||||
mem.copy_from_slice(compiled_code.code_buffer());
|
||||
}
|
||||
|
||||
let relocs = compiled_code.buffer.relocs().to_vec();
|
||||
let relocs = compiled_code
|
||||
.buffer
|
||||
.relocs()
|
||||
.iter()
|
||||
.map(|reloc| ModuleReloc::from_mach_reloc(reloc, &ctx.func))
|
||||
.collect();
|
||||
|
||||
self.record_function_for_perf(ptr, size, &decl.name);
|
||||
self.compiled_functions[id] = Some(CompiledBlob { ptr, size, relocs });
|
||||
@@ -714,16 +720,16 @@ impl Module for JITModule {
|
||||
.unwrap()
|
||||
.perform_relocations(
|
||||
|name| match *name {
|
||||
ir::ExternalName::User { .. } => {
|
||||
ModuleExtName::User { .. } => {
|
||||
unreachable!("non GOT or PLT relocation in function {} to {}", id, name)
|
||||
}
|
||||
ir::ExternalName::LibCall(ref libcall) => self
|
||||
ModuleExtName::LibCall(ref libcall) => self
|
||||
.libcall_plt_entries
|
||||
.get(libcall)
|
||||
.unwrap_or_else(|| panic!("can't resolve libcall {}", libcall))
|
||||
.as_ptr()
|
||||
.cast::<u8>(),
|
||||
_ => panic!("invalid ExternalName {}", name),
|
||||
_ => panic!("invalid name"),
|
||||
},
|
||||
|name| self.get_got_address(name).as_ptr().cast(),
|
||||
|name| self.get_plt_address(name),
|
||||
@@ -738,6 +744,7 @@ impl Module for JITModule {
|
||||
fn define_function_bytes(
|
||||
&mut self,
|
||||
id: FuncId,
|
||||
func: &ir::Function,
|
||||
bytes: &[u8],
|
||||
relocs: &[MachReloc],
|
||||
) -> ModuleResult<ModuleCompiledFunction> {
|
||||
@@ -771,7 +778,10 @@ impl Module for JITModule {
|
||||
self.compiled_functions[id] = Some(CompiledBlob {
|
||||
ptr,
|
||||
size,
|
||||
relocs: relocs.to_vec(),
|
||||
relocs: relocs
|
||||
.iter()
|
||||
.map(|reloc| ModuleReloc::from_mach_reloc(reloc, func))
|
||||
.collect(),
|
||||
});
|
||||
|
||||
if self.isa.flags().is_pic() {
|
||||
@@ -866,6 +876,33 @@ impl Module for JITModule {
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn get_name(&self, name: &str) -> Option<cranelift_module::FuncOrDataId> {
|
||||
self.declarations().get_name(name)
|
||||
}
|
||||
|
||||
fn target_config(&self) -> cranelift_codegen::isa::TargetFrontendConfig {
|
||||
self.isa().frontend_config()
|
||||
}
|
||||
|
||||
fn make_context(&self) -> cranelift_codegen::Context {
|
||||
let mut ctx = cranelift_codegen::Context::new();
|
||||
ctx.func.signature.call_conv = self.isa().default_call_conv();
|
||||
ctx
|
||||
}
|
||||
|
||||
fn clear_context(&self, ctx: &mut cranelift_codegen::Context) {
|
||||
ctx.clear();
|
||||
ctx.func.signature.call_conv = self.isa().default_call_conv();
|
||||
}
|
||||
|
||||
fn make_signature(&self) -> ir::Signature {
|
||||
ir::Signature::new(self.isa().default_call_conv())
|
||||
}
|
||||
|
||||
fn clear_signature(&self, sig: &mut ir::Signature) {
|
||||
sig.clear(self.isa().default_call_conv());
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(not(windows))]
|
||||
|
||||
@@ -1,25 +1,25 @@
|
||||
use cranelift_codegen::binemit::Reloc;
|
||||
use cranelift_codegen::ir::ExternalName;
|
||||
use cranelift_codegen::MachReloc;
|
||||
use cranelift_module::ModuleExtName;
|
||||
use cranelift_module::ModuleReloc;
|
||||
use std::convert::TryFrom;
|
||||
|
||||
#[derive(Clone)]
|
||||
pub(crate) struct CompiledBlob {
|
||||
pub(crate) ptr: *mut u8,
|
||||
pub(crate) size: usize,
|
||||
pub(crate) relocs: Vec<MachReloc>,
|
||||
pub(crate) relocs: Vec<ModuleReloc>,
|
||||
}
|
||||
|
||||
impl CompiledBlob {
|
||||
pub(crate) fn perform_relocations(
|
||||
&self,
|
||||
get_address: impl Fn(&ExternalName) -> *const u8,
|
||||
get_got_entry: impl Fn(&ExternalName) -> *const u8,
|
||||
get_plt_entry: impl Fn(&ExternalName) -> *const u8,
|
||||
get_address: impl Fn(&ModuleExtName) -> *const u8,
|
||||
get_got_entry: impl Fn(&ModuleExtName) -> *const u8,
|
||||
get_plt_entry: impl Fn(&ModuleExtName) -> *const u8,
|
||||
) {
|
||||
use std::ptr::write_unaligned;
|
||||
|
||||
for &MachReloc {
|
||||
for &ModuleReloc {
|
||||
kind,
|
||||
offset,
|
||||
ref name,
|
||||
|
||||
@@ -48,7 +48,7 @@ fn define_simple_function(module: &mut JITModule) -> FuncId {
|
||||
.unwrap();
|
||||
|
||||
let mut ctx = Context::new();
|
||||
ctx.func = Function::with_name_signature(ExternalName::user(0, func_id.as_u32()), sig);
|
||||
ctx.func = Function::with_name_signature(UserFuncName::user(0, func_id.as_u32()), sig);
|
||||
let mut func_ctx = FunctionBuilderContext::new();
|
||||
{
|
||||
let mut bcx: FunctionBuilder = FunctionBuilder::new(&mut ctx.func, &mut func_ctx);
|
||||
@@ -91,7 +91,7 @@ fn switch_error() {
|
||||
call_conv: CallConv::SystemV,
|
||||
};
|
||||
|
||||
let mut func = Function::with_name_signature(ExternalName::user(0, 0), sig);
|
||||
let mut func = Function::with_name_signature(UserFuncName::default(), sig);
|
||||
|
||||
let mut func_ctx = FunctionBuilderContext::new();
|
||||
{
|
||||
@@ -179,7 +179,8 @@ fn libcall_function() {
|
||||
.unwrap();
|
||||
|
||||
let mut ctx = Context::new();
|
||||
ctx.func = Function::with_name_signature(ExternalName::user(0, func_id.as_u32()), sig);
|
||||
ctx.func = Function::with_name_signature(UserFuncName::user(0, func_id.as_u32()), sig);
|
||||
|
||||
let mut func_ctx = FunctionBuilderContext::new();
|
||||
{
|
||||
let mut bcx: FunctionBuilder = FunctionBuilder::new(&mut ctx.func, &mut func_ctx);
|
||||
|
||||
Reference in New Issue
Block a user