Support Func imports with zero shims (#839)

* Move `Func` to its own file

* Support `Func` imports with zero shims

This commit extends the `Func` type in the `wasmtime` crate with static
`wrap*` constructors. The goal of these constructors is to create a
`Func` type which has zero shims associated with it, creating as small
of a layer as possible between wasm code and calling imported Rust code.

This is achieved by creating an `extern "C"` shim function which matches
the ABI of what Cranelift will generate, and then the host function is
passed directly into an `InstanceHandle` to get called later. This also
enables enough inlining opportunities that LLVM will be able to see all
functions and inline everything to the point where your function is
called immediately from wasm, no questions asked.
This commit is contained in:
Alex Crichton
2020-02-04 14:32:35 -06:00
committed by GitHub
parent e09231e33f
commit 1bfca842b0
11 changed files with 631 additions and 190 deletions

View File

@@ -1,19 +1,8 @@
//! Translation of hello example
use anyhow::{ensure, Context as _, Result};
use std::rc::Rc;
use wasmtime::*;
struct HelloCallback;
impl Callable for HelloCallback {
fn call(&self, _params: &[Val], _results: &mut [Val]) -> Result<(), Trap> {
println!("Calling back...");
println!("> Hello World!");
Ok(())
}
}
fn main() -> Result<()> {
// Configure the initial compilation environment, creating the global
// `Store` structure. Note that you can also tweak configuration settings
@@ -34,8 +23,10 @@ fn main() -> Result<()> {
// Here we handle the imports of the module, which in this case is our
// `HelloCallback` type and its associated implementation of `Callback.
println!("Creating callback...");
let hello_type = FuncType::new(Box::new([]), Box::new([]));
let hello_func = Func::new(&store, hello_type, Rc::new(HelloCallback));
let hello_func = Func::wrap0(&store, || {
println!("Calling back...");
println!("> Hello World!");
});
// Once we've got that all set up we can then move to the instantiation
// phase, pairing together a compiled module as well as a set of imports.