Implement AOT compilation for components (#5160)
* Pull `Module` out of `ModuleTextBuilder` This commit is the first in what will likely be a number towards preparing for serializing a compiled component to bytes, a precompiled artifact. To that end my rough plan is to merge all of the compiled artifacts for a component into one large object file instead of having lots of separate object files and lots of separate mmaps to manage. To that end I plan on eventually using `ModuleTextBuilder` to build one large text section for all core wasm modules and trampolines, meaning that `ModuleTextBuilder` is no longer specific to one module. I've extracted out functionality such as function name calculation as well as relocation resolving (now a closure passed in) in preparation for this. For now this just keeps tests passing, and the trajectory for this should become more clear over the following commits. * Remove component-specific object emission This commit removes the `ComponentCompiler::emit_obj` function in favor of `Compiler::emit_obj`, now renamed `append_code`. This involved significantly refactoring code emission to take a flat list of functions into `append_code` and the caller is responsible for weaving together various "families" of functions and un-weaving them afterwards. * Consolidate ELF parsing in `CodeMemory` This commit moves the ELF file parsing and section iteration from `CompiledModule` into `CodeMemory` so one location keeps track of section ranges and such. This is in preparation for sharing much of this code with components which needs all the same sections to get tracked but won't be using `CompiledModule`. A small side benefit from this is that the section parsing done in `CodeMemory` and `CompiledModule` is no longer duplicated. * Remove separately tracked traps in components Previously components would generate an "always trapping" function and the metadata around which pc was allowed to trap was handled manually for components. With recent refactorings the Wasmtime-standard trap section in object files is now being generated for components as well which means that can be reused instead of custom-tracking this metadata. This commit removes the manual tracking for the `always_trap` functions and plumbs the necessary bits around to make components look more like modules. * Remove a now-unnecessary `Arc` in `Module` Not expected to have any measurable impact on performance, but complexity-wise this should make it a bit easier to understand the internals since there's no longer any need to store this somewhere else than its owner's location. * Merge compilation artifacts of components This commit is a large refactoring of the component compilation process to produce a single artifact instead of multiple binary artifacts. The core wasm compilation process is refactored as well to share as much code as necessary with the component compilation process. This method of representing a compiled component necessitated a few medium-sized changes internally within Wasmtime: * A new data structure was created, `CodeObject`, which represents metadata about a single compiled artifact. This is then stored as an `Arc` within a component and a module. For `Module` this is always uniquely owned and represents a shuffling around of data from one owner to another. For a `Component`, however, this is shared amongst all loaded modules and the top-level component. * The "module registry" which is used for symbolicating backtraces and for trap information has been updated to account for a single region of loaded code holding possibly multiple modules. This involved adding a second-level `BTreeMap` for now. This will likely slow down instantiation slightly but if it poses an issue in the future this should be able to be represented with a more clever data structure. This commit additionally solves a number of longstanding issues with components such as compiling only one host-to-wasm trampoline per signature instead of possibly once-per-module. Additionally the `SignatureCollection` registration now happens once-per-component instead of once-per-module-within-a-component. * Fix compile errors from prior commits * Support AOT-compiling components This commit adds support for AOT-compiled components in the same manner as `Module`, specifically adding: * `Engine::precompile_component` * `Component::serialize` * `Component::deserialize` * `Component::deserialize_file` Internally the support for components looks quite similar to `Module`. All the prior commits to this made adding the support here (unsurprisingly) easy. Components are represented as a single object file as are modules, and the functions for each module are all piled into the same object file next to each other (as are areas such as data sections). Support was also added here to quickly differentiate compiled components vs compiled modules via the `e_flags` field in the ELF header. * Prevent serializing exported modules on components The current representation of a module within a component means that the implementation of `Module::serialize` will not work if the module is exported from a component. The reason for this is that `serialize` doesn't actually do anything and simply returns the underlying mmap as a list of bytes. The mmap, however, has `.wasmtime.info` describing component metadata as opposed to this module's metadata. While rewriting this section could be implemented it's not so easy to do so and is otherwise seen as not super important of a feature right now anyway. * Fix windows build * Fix an unused function warning * Update crates/environ/src/compilation.rs Co-authored-by: Nick Fitzgerald <fitzgen@gmail.com> Co-authored-by: Nick Fitzgerald <fitzgen@gmail.com>
This commit is contained in:
@@ -26,8 +26,7 @@ use object::write::{Object, SectionId, StandardSegment, Symbol, SymbolId, Symbol
|
||||
use object::{Architecture, SectionKind, SymbolFlags, SymbolKind, SymbolScope};
|
||||
use std::convert::TryFrom;
|
||||
use std::ops::Range;
|
||||
use wasmtime_environ::obj;
|
||||
use wasmtime_environ::{DefinedFuncIndex, Module, PrimaryMap, SignatureIndex, Trampoline};
|
||||
use wasmtime_environ::FuncIndex;
|
||||
|
||||
const TEXT_SECTION_NAME: &[u8] = b".text";
|
||||
|
||||
@@ -46,24 +45,23 @@ pub struct ModuleTextBuilder<'a> {
|
||||
obj: &'a mut Object<'static>,
|
||||
|
||||
/// The WebAssembly module we're generating code for.
|
||||
module: &'a Module,
|
||||
|
||||
text_section: SectionId,
|
||||
|
||||
unwind_info: UnwindInfoBuilder<'a>,
|
||||
|
||||
/// The corresponding symbol for each function, inserted as they're defined.
|
||||
///
|
||||
/// If an index isn't here yet then it hasn't been defined yet.
|
||||
func_symbols: PrimaryMap<DefinedFuncIndex, SymbolId>,
|
||||
|
||||
/// In-progress text section that we're using cranelift's `MachBuffer` to
|
||||
/// build to resolve relocations (calls) between functions.
|
||||
text: Box<dyn TextSectionBuilder>,
|
||||
}
|
||||
|
||||
impl<'a> ModuleTextBuilder<'a> {
|
||||
pub fn new(obj: &'a mut Object<'static>, module: &'a Module, isa: &'a dyn TargetIsa) -> Self {
|
||||
/// Creates a new builder for the text section of an executable.
|
||||
///
|
||||
/// The `.text` section will be appended to the specified `obj` along with
|
||||
/// any unwinding or such information as necessary. The `num_funcs`
|
||||
/// parameter indicates the number of times the `append_func` function will
|
||||
/// be called. The `finish` function will panic if this contract is not met.
|
||||
pub fn new(obj: &'a mut Object<'static>, isa: &'a dyn TargetIsa, num_funcs: usize) -> Self {
|
||||
// Entire code (functions and trampolines) will be placed
|
||||
// in the ".text" section.
|
||||
let text_section = obj.add_section(
|
||||
@@ -72,37 +70,40 @@ impl<'a> ModuleTextBuilder<'a> {
|
||||
SectionKind::Text,
|
||||
);
|
||||
|
||||
let num_defined = module.functions.len() - module.num_imported_funcs;
|
||||
Self {
|
||||
isa,
|
||||
obj,
|
||||
module,
|
||||
text_section,
|
||||
func_symbols: PrimaryMap::with_capacity(num_defined),
|
||||
unwind_info: Default::default(),
|
||||
text: isa.text_section_builder(num_defined as u32),
|
||||
text: isa.text_section_builder(num_funcs),
|
||||
}
|
||||
}
|
||||
|
||||
/// Appends the `func` specified named `name` to this object.
|
||||
///
|
||||
/// The `resolve_reloc_target` closure is used to resolve a relocation
|
||||
/// target to an adjacent function which has already been added or will be
|
||||
/// added to this object. The argument is the relocation target specified
|
||||
/// within `CompiledFunction` and the return value must be an index where
|
||||
/// the target will be defined by the `n`th call to `append_func`.
|
||||
///
|
||||
/// Returns the symbol associated with the function as well as the range
|
||||
/// that the function resides within the text section.
|
||||
pub fn append_func(
|
||||
&mut self,
|
||||
labeled: bool,
|
||||
name: Vec<u8>,
|
||||
name: &str,
|
||||
func: &'a CompiledFunction,
|
||||
resolve_reloc_target: impl Fn(FuncIndex) -> usize,
|
||||
) -> (SymbolId, Range<u64>) {
|
||||
let body_len = func.body.len() as u64;
|
||||
let off = self.text.append(
|
||||
labeled,
|
||||
true,
|
||||
&func.body,
|
||||
self.isa.function_alignment().max(func.info.alignment),
|
||||
self.isa.function_alignment().max(func.alignment),
|
||||
);
|
||||
|
||||
let symbol_id = self.obj.add_symbol(Symbol {
|
||||
name,
|
||||
name: name.as_bytes().to_vec(),
|
||||
value: off,
|
||||
size: body_len,
|
||||
kind: SymbolKind::Text,
|
||||
@@ -125,13 +126,11 @@ impl<'a> ModuleTextBuilder<'a> {
|
||||
// file, but if it can't handle it then we pass through the
|
||||
// relocation.
|
||||
RelocationTarget::UserFunc(index) => {
|
||||
let defined_index = self.module.defined_func_index(index).unwrap();
|
||||
if self.text.resolve_reloc(
|
||||
off + u64::from(r.offset),
|
||||
r.reloc,
|
||||
r.addend,
|
||||
defined_index.as_u32(),
|
||||
) {
|
||||
let target = resolve_reloc_target(index);
|
||||
if self
|
||||
.text
|
||||
.resolve_reloc(off + u64::from(r.offset), r.reloc, r.addend, target)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
@@ -160,31 +159,6 @@ impl<'a> ModuleTextBuilder<'a> {
|
||||
(symbol_id, off..off + body_len)
|
||||
}
|
||||
|
||||
/// Appends a function to this object file.
|
||||
///
|
||||
/// This is expected to be called in-order for ascending `index` values.
|
||||
pub fn func(&mut self, index: DefinedFuncIndex, func: &'a CompiledFunction) -> Range<u64> {
|
||||
let name = obj::func_symbol_name(self.module.func_index(index));
|
||||
let (symbol_id, range) = self.append_func(true, name.into_bytes(), func);
|
||||
assert_eq!(self.func_symbols.push(symbol_id), index);
|
||||
range
|
||||
}
|
||||
|
||||
pub fn trampoline(&mut self, sig: SignatureIndex, func: &'a CompiledFunction) -> Trampoline {
|
||||
let name = obj::trampoline_symbol_name(sig);
|
||||
let range = self.named_func(&name, func);
|
||||
Trampoline {
|
||||
signature: sig,
|
||||
start: range.start,
|
||||
length: u32::try_from(range.end - range.start).unwrap(),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn named_func(&mut self, name: &str, func: &'a CompiledFunction) -> Range<u64> {
|
||||
let (_, range) = self.append_func(false, name.as_bytes().to_vec(), func);
|
||||
range
|
||||
}
|
||||
|
||||
/// Forces "veneers" to be used for inter-function calls in the text
|
||||
/// section which means that in-bounds optimized addresses are never used.
|
||||
///
|
||||
@@ -210,7 +184,7 @@ impl<'a> ModuleTextBuilder<'a> {
|
||||
///
|
||||
/// Note that this will also write out the unwind information sections if
|
||||
/// necessary.
|
||||
pub fn finish(mut self) -> Result<PrimaryMap<DefinedFuncIndex, SymbolId>> {
|
||||
pub fn finish(mut self) {
|
||||
// Finish up the text section now that we're done adding functions.
|
||||
let text = self.text.finish();
|
||||
self.obj
|
||||
@@ -220,8 +194,6 @@ impl<'a> ModuleTextBuilder<'a> {
|
||||
// Append the unwind information for all our functions, if necessary.
|
||||
self.unwind_info
|
||||
.append_section(self.isa, self.obj, self.text_section);
|
||||
|
||||
Ok(self.func_symbols)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
Reference in New Issue
Block a user