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.
294 lines
11 KiB
Rust
294 lines
11 KiB
Rust
//! A `Compilation` contains the compiled function bodies for a WebAssembly
|
|
//! module.
|
|
|
|
use crate::{
|
|
DefinedFuncIndex, FilePos, FunctionBodyData, ModuleTranslation, ModuleTypes, PrimaryMap,
|
|
SignatureIndex, StackMap, Tunables, WasmError, WasmFuncType,
|
|
};
|
|
use anyhow::Result;
|
|
use object::write::Object;
|
|
use object::{Architecture, BinaryFormat};
|
|
use serde::{Deserialize, Serialize};
|
|
use std::any::Any;
|
|
use std::borrow::Cow;
|
|
use std::collections::BTreeMap;
|
|
use std::fmt;
|
|
use std::sync::Arc;
|
|
use thiserror::Error;
|
|
|
|
/// Information about a function, such as trap information, address map,
|
|
/// and stack maps.
|
|
#[derive(Serialize, Deserialize, Default)]
|
|
#[allow(missing_docs)]
|
|
pub struct FunctionInfo {
|
|
pub start_srcloc: FilePos,
|
|
pub stack_maps: Vec<StackMapInformation>,
|
|
|
|
/// Offset in the text section of where this function starts.
|
|
pub start: u64,
|
|
/// The size of the compiled function, in bytes.
|
|
pub length: u32,
|
|
}
|
|
|
|
/// Information about a compiled trampoline which the host can call to enter
|
|
/// wasm.
|
|
#[derive(Serialize, Deserialize)]
|
|
#[allow(missing_docs)]
|
|
pub struct Trampoline {
|
|
/// The signature this trampoline is for
|
|
pub signature: SignatureIndex,
|
|
|
|
/// Offset in the text section of where this function starts.
|
|
pub start: u64,
|
|
/// The size of the compiled function, in bytes.
|
|
pub length: u32,
|
|
}
|
|
|
|
/// The offset within a function of a GC safepoint, and its associated stack
|
|
/// map.
|
|
#[derive(Serialize, Deserialize, Debug)]
|
|
pub struct StackMapInformation {
|
|
/// The offset of the GC safepoint within the function's native code. It is
|
|
/// relative to the beginning of the function.
|
|
pub code_offset: u32,
|
|
|
|
/// The stack map for identifying live GC refs at the GC safepoint.
|
|
pub stack_map: StackMap,
|
|
}
|
|
|
|
/// An error while compiling WebAssembly to machine code.
|
|
#[derive(Error, Debug)]
|
|
pub enum CompileError {
|
|
/// A wasm translation error occured.
|
|
#[error("WebAssembly translation error")]
|
|
Wasm(#[from] WasmError),
|
|
|
|
/// A compilation error occured.
|
|
#[error("Compilation error: {0}")]
|
|
Codegen(String),
|
|
|
|
/// A compilation error occured.
|
|
#[error("Debug info is not supported with this configuration")]
|
|
DebugInfoNotSupported,
|
|
}
|
|
|
|
/// Implementation of an incremental compilation's key/value cache store.
|
|
///
|
|
/// In theory, this could just be Cranelift's `CacheKvStore` trait, but it is not as we want to
|
|
/// make sure that wasmtime isn't too tied to Cranelift internals (and as a matter of fact, we
|
|
/// can't depend on the Cranelift trait here).
|
|
pub trait CacheStore: Send + Sync + std::fmt::Debug {
|
|
/// Try to retrieve an arbitrary cache key entry, and returns a reference to bytes that were
|
|
/// inserted via `Self::insert` before.
|
|
fn get(&self, key: &[u8]) -> Option<Cow<[u8]>>;
|
|
|
|
/// Given an arbitrary key and bytes, stores them in the cache.
|
|
///
|
|
/// Returns false when insertion in the cache failed.
|
|
fn insert(&self, key: &[u8], value: Vec<u8>) -> bool;
|
|
}
|
|
|
|
/// Abstract trait representing the ability to create a `Compiler` below.
|
|
///
|
|
/// This is used in Wasmtime to separate compiler implementations, currently
|
|
/// mostly used to separate Cranelift from Wasmtime itself.
|
|
pub trait CompilerBuilder: Send + Sync + fmt::Debug {
|
|
/// Sets the target of compilation to the target specified.
|
|
fn target(&mut self, target: target_lexicon::Triple) -> Result<()>;
|
|
|
|
/// Returns the currently configured target triple that compilation will
|
|
/// produce artifacts for.
|
|
fn triple(&self) -> &target_lexicon::Triple;
|
|
|
|
/// Compiler-specific method to configure various settings in the compiler
|
|
/// itself.
|
|
///
|
|
/// This is expected to be defined per-compiler. Compilers should return
|
|
/// errors for unknown names/values.
|
|
fn set(&mut self, name: &str, val: &str) -> Result<()>;
|
|
|
|
/// Compiler-specific method for configuring settings.
|
|
///
|
|
/// Same as [`CompilerBuilder::set`] except for enabling boolean flags.
|
|
/// Currently cranelift uses this to sometimes enable a family of settings.
|
|
fn enable(&mut self, name: &str) -> Result<()>;
|
|
|
|
/// Returns a list of all possible settings that can be configured with
|
|
/// [`CompilerBuilder::set`] and [`CompilerBuilder::enable`].
|
|
fn settings(&self) -> Vec<Setting>;
|
|
|
|
/// Enables Cranelift's incremental compilation cache, using the given `CacheStore`
|
|
/// implementation.
|
|
fn enable_incremental_compilation(&mut self, cache_store: Arc<dyn CacheStore>);
|
|
|
|
/// Builds a new [`Compiler`] object from this configuration.
|
|
fn build(&self) -> Result<Box<dyn Compiler>>;
|
|
}
|
|
|
|
/// Description of compiler settings returned by [`CompilerBuilder::settings`].
|
|
#[derive(Clone, Copy, Debug)]
|
|
pub struct Setting {
|
|
/// The name of the setting.
|
|
pub name: &'static str,
|
|
/// The description of the setting.
|
|
pub description: &'static str,
|
|
/// The kind of the setting.
|
|
pub kind: SettingKind,
|
|
/// The supported values of the setting (for enum values).
|
|
pub values: Option<&'static [&'static str]>,
|
|
}
|
|
|
|
/// Different kinds of [`Setting`] values that can be configured in a
|
|
/// [`CompilerBuilder`]
|
|
#[derive(Clone, Copy, Debug)]
|
|
pub enum SettingKind {
|
|
/// The setting is an enumeration, meaning it's one of a set of values.
|
|
Enum,
|
|
/// The setting is a number.
|
|
Num,
|
|
/// The setting is a boolean.
|
|
Bool,
|
|
/// The setting is a preset.
|
|
Preset,
|
|
}
|
|
|
|
/// An implementation of a compiler which can compile WebAssembly functions to
|
|
/// machine code and perform other miscellaneous tasks needed by the JIT runtime.
|
|
pub trait Compiler: Send + Sync {
|
|
/// Compiles the function `index` within `translation`.
|
|
///
|
|
/// The body of the function is available in `data` and configuration
|
|
/// values are also passed in via `tunables`. Type information in
|
|
/// `translation` is all relative to `types`.
|
|
fn compile_function(
|
|
&self,
|
|
translation: &ModuleTranslation<'_>,
|
|
index: DefinedFuncIndex,
|
|
data: FunctionBodyData<'_>,
|
|
tunables: &Tunables,
|
|
types: &ModuleTypes,
|
|
) -> Result<Box<dyn Any + Send>, CompileError>;
|
|
|
|
/// Creates a function of type `VMTrampoline` which will then call the
|
|
/// function pointer argument which has the `ty` type provided.
|
|
fn compile_host_to_wasm_trampoline(
|
|
&self,
|
|
ty: &WasmFuncType,
|
|
) -> Result<Box<dyn Any + Send>, CompileError>;
|
|
|
|
/// Collects the results of compilation into an in-memory object.
|
|
///
|
|
/// This function will receive the same `Box<dyn Ayn>` produced as part of
|
|
/// `compile_function`, as well as the general compilation environment with
|
|
/// the translation. THe `trampolines` argument is generated by
|
|
/// `compile_host_to_wasm_trampoline` for each of
|
|
/// `module.exported_signatures`. This method is expected to populate
|
|
/// information in the object file such as:
|
|
///
|
|
/// * Compiled code in a `.text` section
|
|
/// * Unwind information in Wasmtime-specific sections
|
|
/// * DWARF debugging information for the host, if `emit_dwarf` is `true`
|
|
/// and the compiler supports it.
|
|
/// * Relocations, if necessary, for the text section
|
|
///
|
|
/// The final result of compilation will contain more sections inserted by
|
|
/// the compiler-agnostic runtime.
|
|
///
|
|
/// This function returns information about the compiled functions (where
|
|
/// they are in the text section) along with where trampolines are located.
|
|
fn emit_obj(
|
|
&self,
|
|
module: &ModuleTranslation,
|
|
funcs: PrimaryMap<DefinedFuncIndex, Box<dyn Any + Send>>,
|
|
trampolines: Vec<Box<dyn Any + Send>>,
|
|
tunables: &Tunables,
|
|
obj: &mut Object<'static>,
|
|
) -> Result<(PrimaryMap<DefinedFuncIndex, FunctionInfo>, Vec<Trampoline>)>;
|
|
|
|
/// Inserts two functions for host-to-wasm and wasm-to-host trampolines into
|
|
/// the `obj` provided.
|
|
///
|
|
/// This will configure the same sections as `emit_obj`, but will likely be
|
|
/// much smaller. The two returned `Trampoline` structures describe where to
|
|
/// find the host-to-wasm and wasm-to-host trampolines in the text section,
|
|
/// respectively.
|
|
fn emit_trampoline_obj(
|
|
&self,
|
|
ty: &WasmFuncType,
|
|
host_fn: usize,
|
|
obj: &mut Object<'static>,
|
|
) -> Result<(Trampoline, Trampoline)>;
|
|
|
|
/// Creates a new `Object` file which is used to build the results of a
|
|
/// compilation into.
|
|
///
|
|
/// The returned object file will have an appropriate
|
|
/// architecture/endianness for `self.triple()`, but at this time it is
|
|
/// always an ELF file, regardless of target platform.
|
|
fn object(&self) -> Result<Object<'static>> {
|
|
use target_lexicon::Architecture::*;
|
|
|
|
let triple = self.triple();
|
|
Ok(Object::new(
|
|
BinaryFormat::Elf,
|
|
match triple.architecture {
|
|
X86_32(_) => Architecture::I386,
|
|
X86_64 => Architecture::X86_64,
|
|
Arm(_) => Architecture::Arm,
|
|
Aarch64(_) => Architecture::Aarch64,
|
|
S390x => Architecture::S390x,
|
|
architecture => {
|
|
anyhow::bail!("target architecture {:?} is unsupported", architecture,);
|
|
}
|
|
},
|
|
match triple.endianness().unwrap() {
|
|
target_lexicon::Endianness::Little => object::Endianness::Little,
|
|
target_lexicon::Endianness::Big => object::Endianness::Big,
|
|
},
|
|
))
|
|
}
|
|
|
|
/// Returns the target triple that this compiler is compiling for.
|
|
fn triple(&self) -> &target_lexicon::Triple;
|
|
|
|
/// Returns the alignment necessary to align values to the page size of the
|
|
/// compilation target. Note that this may be an upper-bound where the
|
|
/// alignment is larger than necessary for some platforms since it may
|
|
/// depend on the platform's runtime configuration.
|
|
fn page_size_align(&self) -> u64;
|
|
|
|
/// Returns a list of configured settings for this compiler.
|
|
fn flags(&self) -> BTreeMap<String, FlagValue>;
|
|
|
|
/// Same as [`Compiler::flags`], but ISA-specific (a cranelift-ism)
|
|
fn isa_flags(&self) -> BTreeMap<String, FlagValue>;
|
|
|
|
/// Returns a suitable compiler usable for component-related compliations.
|
|
///
|
|
/// Note that the `ComponentCompiler` trait can also be implemented for
|
|
/// `Self` in which case this function would simply return `self`.
|
|
#[cfg(feature = "component-model")]
|
|
fn component_compiler(&self) -> &dyn crate::component::ComponentCompiler;
|
|
}
|
|
|
|
/// Value of a configured setting for a [`Compiler`]
|
|
#[derive(Serialize, Deserialize, Hash, Eq, PartialEq, Debug)]
|
|
pub enum FlagValue {
|
|
/// Name of the value that has been configured for this setting.
|
|
Enum(Cow<'static, str>),
|
|
/// The numerical value of the configured settings.
|
|
Num(u8),
|
|
/// Whether the setting is on or off.
|
|
Bool(bool),
|
|
}
|
|
|
|
impl fmt::Display for FlagValue {
|
|
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
|
|
match self {
|
|
Self::Enum(v) => v.fmt(f),
|
|
Self::Num(v) => v.fmt(f),
|
|
Self::Bool(v) => v.fmt(f),
|
|
}
|
|
}
|
|
}
|