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:
@@ -9,10 +9,108 @@ use core::cmp;
|
||||
use core::fmt::{self, Write};
|
||||
use core::str::FromStr;
|
||||
|
||||
use cranelift_entity::EntityRef as _;
|
||||
#[cfg(feature = "enable-serde")]
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
const TESTCASE_NAME_LENGTH: usize = 16;
|
||||
use super::entities::UserExternalNameRef;
|
||||
use super::function::FunctionParameters;
|
||||
|
||||
pub(crate) const TESTCASE_NAME_LENGTH: usize = 16;
|
||||
|
||||
/// An explicit name for a user-defined function, be it defined in code or in CLIF text.
|
||||
///
|
||||
/// This is used both for naming a function (for debugging purposes) and for declaring external
|
||||
/// functions. In the latter case, this becomes an `ExternalName`, which gets embedded in
|
||||
/// relocations later, etc.
|
||||
#[derive(Clone, Debug)]
|
||||
#[cfg_attr(feature = "enable-serde", derive(Serialize, Deserialize))]
|
||||
pub enum UserFuncName {
|
||||
/// A user-defined name, with semantics left to the user.
|
||||
User(UserExternalName),
|
||||
/// A name for a test case, mostly intended for Cranelift testing.
|
||||
Testcase(TestcaseName),
|
||||
}
|
||||
|
||||
impl UserFuncName {
|
||||
/// Creates a new external name from a sequence of bytes. Caller is expected
|
||||
/// to guarantee bytes are only ascii alphanumeric or `_`.
|
||||
pub fn testcase<T: AsRef<[u8]>>(v: T) -> Self {
|
||||
Self::Testcase(TestcaseName::new(v))
|
||||
}
|
||||
|
||||
/// Create a new external name from a user-defined external function reference.
|
||||
pub fn user(namespace: u32, index: u32) -> Self {
|
||||
Self::User(UserExternalName { namespace, index })
|
||||
}
|
||||
}
|
||||
|
||||
impl Default for UserFuncName {
|
||||
fn default() -> Self {
|
||||
UserFuncName::User(UserExternalName::default())
|
||||
}
|
||||
}
|
||||
|
||||
impl fmt::Display for UserFuncName {
|
||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
match self {
|
||||
UserFuncName::User(user) => user.fmt(f),
|
||||
UserFuncName::Testcase(testcase) => testcase.fmt(f),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// An external name in a user-defined symbol table.
|
||||
///
|
||||
/// Cranelift does not interpret these numbers in any way, so they can represent arbitrary values.
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Hash, Default)]
|
||||
#[cfg_attr(feature = "enable-serde", derive(Serialize, Deserialize))]
|
||||
pub struct UserExternalName {
|
||||
/// Arbitrary.
|
||||
pub namespace: u32,
|
||||
/// Arbitrary.
|
||||
pub index: u32,
|
||||
}
|
||||
|
||||
impl fmt::Display for UserExternalName {
|
||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
write!(f, "u{}:{}", self.namespace, self.index)
|
||||
}
|
||||
}
|
||||
|
||||
/// A name for a test case.
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
|
||||
#[cfg_attr(feature = "enable-serde", derive(Serialize, Deserialize))]
|
||||
pub struct TestcaseName {
|
||||
/// How many of the bytes in `ascii` are valid?
|
||||
length: u8,
|
||||
/// Ascii bytes of the name.
|
||||
ascii: [u8; TESTCASE_NAME_LENGTH],
|
||||
}
|
||||
|
||||
impl fmt::Display for TestcaseName {
|
||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
f.write_char('%')?;
|
||||
for byte in self.ascii.iter().take(self.length as usize) {
|
||||
f.write_char(*byte as char)?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
impl TestcaseName {
|
||||
pub(crate) fn new<T: AsRef<[u8]>>(v: T) -> Self {
|
||||
let vec = v.as_ref();
|
||||
let len = cmp::min(vec.len(), TESTCASE_NAME_LENGTH);
|
||||
let mut bytes = [0u8; TESTCASE_NAME_LENGTH];
|
||||
bytes[0..len].copy_from_slice(&vec[0..len]);
|
||||
|
||||
Self {
|
||||
length: len as u8,
|
||||
ascii: bytes,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The name of an external is either a reference to a user-defined symbol
|
||||
/// table, or a short sequence of ascii bytes so that test cases do not have
|
||||
@@ -25,31 +123,26 @@ const TESTCASE_NAME_LENGTH: usize = 16;
|
||||
/// External names can also serve as a primitive testing and debugging tool.
|
||||
/// In particular, many `.clif` test files use function names to identify
|
||||
/// functions.
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
|
||||
#[cfg_attr(feature = "enable-serde", derive(Serialize, Deserialize))]
|
||||
pub enum ExternalName {
|
||||
/// A name in a user-defined symbol table. Cranelift does not interpret
|
||||
/// these numbers in any way.
|
||||
User {
|
||||
/// Arbitrary.
|
||||
namespace: u32,
|
||||
/// Arbitrary.
|
||||
index: u32,
|
||||
},
|
||||
/// A reference to a name in a user-defined symbol table.
|
||||
User(UserExternalNameRef),
|
||||
/// A test case function name of up to a hardcoded amount of ascii
|
||||
/// characters. This is not intended to be used outside test cases.
|
||||
TestCase {
|
||||
/// How many of the bytes in `ascii` are valid?
|
||||
length: u8,
|
||||
/// Ascii bytes of the name.
|
||||
ascii: [u8; TESTCASE_NAME_LENGTH],
|
||||
},
|
||||
TestCase(TestcaseName),
|
||||
/// A well-known runtime library function.
|
||||
LibCall(LibCall),
|
||||
/// A well-known symbol.
|
||||
KnownSymbol(KnownSymbol),
|
||||
}
|
||||
|
||||
impl Default for ExternalName {
|
||||
fn default() -> Self {
|
||||
Self::User(UserExternalNameRef::new(0))
|
||||
}
|
||||
}
|
||||
|
||||
impl ExternalName {
|
||||
/// Creates a new external name from a sequence of bytes. Caller is expected
|
||||
/// to guarantee bytes are only ascii alphanumeric or `_`.
|
||||
@@ -60,53 +153,56 @@ impl ExternalName {
|
||||
/// # use cranelift_codegen::ir::ExternalName;
|
||||
/// // Create `ExternalName` from a string.
|
||||
/// let name = ExternalName::testcase("hello");
|
||||
/// assert_eq!(name.to_string(), "%hello");
|
||||
/// assert_eq!(name.display(None).to_string(), "%hello");
|
||||
/// ```
|
||||
pub fn testcase<T: AsRef<[u8]>>(v: T) -> Self {
|
||||
let vec = v.as_ref();
|
||||
let len = cmp::min(vec.len(), TESTCASE_NAME_LENGTH);
|
||||
let mut bytes = [0u8; TESTCASE_NAME_LENGTH];
|
||||
bytes[0..len].copy_from_slice(&vec[0..len]);
|
||||
|
||||
Self::TestCase {
|
||||
length: len as u8,
|
||||
ascii: bytes,
|
||||
}
|
||||
Self::TestCase(TestcaseName::new(v))
|
||||
}
|
||||
|
||||
/// Create a new external name from user-provided integer indices.
|
||||
/// Create a new external name from a user-defined external function reference.
|
||||
///
|
||||
/// # Examples
|
||||
/// ```rust
|
||||
/// # use cranelift_codegen::ir::ExternalName;
|
||||
/// // Create `ExternalName` from integer indices
|
||||
/// let name = ExternalName::user(123, 456);
|
||||
/// assert_eq!(name.to_string(), "u123:456");
|
||||
/// # use cranelift_codegen::ir::{ExternalName, UserExternalNameRef};
|
||||
/// let user_func_ref: UserExternalNameRef = Default::default(); // usually obtained with `Function::declare_imported_user_function()`
|
||||
/// let name = ExternalName::user(user_func_ref);
|
||||
/// assert_eq!(name.display(None).to_string(), "userextname0");
|
||||
/// ```
|
||||
pub fn user(namespace: u32, index: u32) -> Self {
|
||||
Self::User { namespace, index }
|
||||
pub fn user(func_ref: UserExternalNameRef) -> Self {
|
||||
Self::User(func_ref)
|
||||
}
|
||||
|
||||
/// Returns a display for the current `ExternalName`, with extra context to prettify the
|
||||
/// output.
|
||||
pub fn display<'a>(
|
||||
&'a self,
|
||||
params: Option<&'a FunctionParameters>,
|
||||
) -> DisplayableExternalName<'a> {
|
||||
DisplayableExternalName { name: self, params }
|
||||
}
|
||||
}
|
||||
|
||||
impl Default for ExternalName {
|
||||
fn default() -> Self {
|
||||
Self::user(0, 0)
|
||||
}
|
||||
/// An `ExternalName` that has enough context to be displayed.
|
||||
pub struct DisplayableExternalName<'a> {
|
||||
name: &'a ExternalName,
|
||||
params: Option<&'a FunctionParameters>,
|
||||
}
|
||||
|
||||
impl fmt::Display for ExternalName {
|
||||
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
|
||||
match *self {
|
||||
Self::User { namespace, index } => write!(f, "u{}:{}", namespace, index),
|
||||
Self::TestCase { length, ascii } => {
|
||||
f.write_char('%')?;
|
||||
for byte in ascii.iter().take(length as usize) {
|
||||
f.write_char(*byte as char)?;
|
||||
impl<'a> fmt::Display for DisplayableExternalName<'a> {
|
||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
match &self.name {
|
||||
ExternalName::User(func_ref) => {
|
||||
if let Some(params) = self.params {
|
||||
let name = ¶ms.user_named_funcs()[*func_ref];
|
||||
write!(f, "u{}:{}", name.namespace, name.index)
|
||||
} else {
|
||||
// Best effort.
|
||||
write!(f, "{}", *func_ref)
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
Self::LibCall(lc) => write!(f, "%{}", lc),
|
||||
Self::KnownSymbol(ks) => write!(f, "%{}", ks),
|
||||
ExternalName::TestCase(testcase) => testcase.fmt(f),
|
||||
ExternalName::LibCall(lc) => write!(f, "%{}", lc),
|
||||
ExternalName::KnownSymbol(ks) => write!(f, "%{}", ks),
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -133,33 +229,83 @@ impl FromStr for ExternalName {
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::ExternalName;
|
||||
use crate::ir::LibCall;
|
||||
use crate::ir::{
|
||||
entities::UserExternalNameRef, function::FunctionParameters, LibCall, UserExternalName,
|
||||
};
|
||||
use alloc::string::ToString;
|
||||
use core::u32;
|
||||
use cranelift_entity::EntityRef as _;
|
||||
|
||||
#[test]
|
||||
fn display_testcase() {
|
||||
assert_eq!(ExternalName::testcase("").to_string(), "%");
|
||||
assert_eq!(ExternalName::testcase("x").to_string(), "%x");
|
||||
assert_eq!(ExternalName::testcase("x_1").to_string(), "%x_1");
|
||||
assert_eq!(ExternalName::testcase("").display(None).to_string(), "%");
|
||||
assert_eq!(ExternalName::testcase("x").display(None).to_string(), "%x");
|
||||
assert_eq!(
|
||||
ExternalName::testcase("longname12345678").to_string(),
|
||||
ExternalName::testcase("x_1").display(None).to_string(),
|
||||
"%x_1"
|
||||
);
|
||||
assert_eq!(
|
||||
ExternalName::testcase("longname12345678")
|
||||
.display(None)
|
||||
.to_string(),
|
||||
"%longname12345678"
|
||||
);
|
||||
// Constructor will silently drop bytes beyond the 16th
|
||||
assert_eq!(
|
||||
ExternalName::testcase("longname123456789").to_string(),
|
||||
ExternalName::testcase("longname123456789")
|
||||
.display(None)
|
||||
.to_string(),
|
||||
"%longname12345678"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn display_user() {
|
||||
assert_eq!(ExternalName::user(0, 0).to_string(), "u0:0");
|
||||
assert_eq!(ExternalName::user(1, 1).to_string(), "u1:1");
|
||||
assert_eq!(
|
||||
ExternalName::user(u32::MAX, u32::MAX).to_string(),
|
||||
"u4294967295:4294967295"
|
||||
ExternalName::user(UserExternalNameRef::new(0))
|
||||
.display(None)
|
||||
.to_string(),
|
||||
"userextname0"
|
||||
);
|
||||
assert_eq!(
|
||||
ExternalName::user(UserExternalNameRef::new(1))
|
||||
.display(None)
|
||||
.to_string(),
|
||||
"userextname1"
|
||||
);
|
||||
assert_eq!(
|
||||
ExternalName::user(UserExternalNameRef::new((u32::MAX - 1) as _))
|
||||
.display(None)
|
||||
.to_string(),
|
||||
"userextname4294967294"
|
||||
);
|
||||
|
||||
let mut func_params = FunctionParameters::new();
|
||||
|
||||
// ref 0
|
||||
func_params.ensure_user_func_name(UserExternalName {
|
||||
namespace: 13,
|
||||
index: 37,
|
||||
});
|
||||
|
||||
// ref 1
|
||||
func_params.ensure_user_func_name(UserExternalName {
|
||||
namespace: 2,
|
||||
index: 4,
|
||||
});
|
||||
|
||||
assert_eq!(
|
||||
ExternalName::user(UserExternalNameRef::new(0))
|
||||
.display(Some(&func_params))
|
||||
.to_string(),
|
||||
"u13:37"
|
||||
);
|
||||
|
||||
assert_eq!(
|
||||
ExternalName::user(UserExternalNameRef::new(1))
|
||||
.display(Some(&func_params))
|
||||
.to_string(),
|
||||
"u2:4"
|
||||
);
|
||||
}
|
||||
|
||||
@@ -170,7 +316,9 @@ mod tests {
|
||||
Ok(ExternalName::LibCall(LibCall::FloorF32))
|
||||
);
|
||||
assert_eq!(
|
||||
ExternalName::LibCall(LibCall::FloorF32).to_string(),
|
||||
ExternalName::LibCall(LibCall::FloorF32)
|
||||
.display(None)
|
||||
.to_string(),
|
||||
"%FloorF32"
|
||||
);
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user