Skip to content

Truly independent web browser

LibWasm: Turn the JIT on by default

Andreas Klingf19b99fe4261
diff --git a/Libraries/LibJS/JIT/Rust/src/asm/x86_64/extended.rs b/Libraries/LibJS/JIT/Rust/src/asm/x86_64/extended.rs
index 3eeadcb14e9..ac2d53c0042 100644
--- a/Libraries/LibJS/JIT/Rust/src/asm/x86_64/extended.rs
+++ b/Libraries/LibJS/JIT/Rust/src/asm/x86_64/extended.rs
@@ -219,6 +219,25 @@ impl Assembler {
);
}
+ /// `vaddss`/`vsubss`/... `dst, lhs, [address]` (and the `sd` forms).
+ pub fn vfloat_rrm(&mut self, op: FloatOp, precision: Precision, dst: Fpr, lhs: Fpr, address: &Address) {
+ self.vex_instruction(
+ precision.scalar_prefix(),
+ VexMap::Map0F,
+ false,
+ op as u8,
+ dst.0,
+ lhs.0,
+ Rm::Mem(*address),
+ 0,
+ );
+ }
+
+ /// `imul dst, [address]`.
+ pub fn imul_rm(&mut self, width: Width, dst: Gpr, address: &Address) {
+ self.op_rm(width, &[0x0f, 0xaf], dst.0, address);
+ }
+
/// `vroundss`/`vroundsd dst, src, src, mode`.
pub fn vround(&mut self, precision: Precision, dst: Fpr, src: Fpr, rounding: Rounding) {
let opcode = match precision {
@@ -550,6 +569,22 @@ mod tests {
"vsqrtsd xmm1, xmm2, xmm11" => |a| a.vfloat_rrr(FloatOp::Sqrt, Precision::Double, XMM1, XMM2, XMM11);
"vroundss xmm1, xmm1, xmm1, 8" => |a| a.vround(Precision::Single, XMM1, XMM1, Rounding::Nearest);
"vroundsd xmm9, xmm2, xmm2, 0xb" => |a| a.vround(Precision::Double, XMM9, XMM2, Rounding::TowardZero);
+ "vaddsd xmm1, xmm2, qword ptr [rbp-0x48]" => |a| a.vfloat_rrm(
+ FloatOp::Add,
+ Precision::Double,
+ XMM1,
+ XMM2,
+ &Address::new(RBP, -0x48)
+ );
+ "vmulss xmm9, xmm10, dword ptr [r13+8]" => |a| a.vfloat_rrm(
+ FloatOp::Mul,
+ Precision::Single,
+ XMM9,
+ XMM10,
+ &Address::new(R13, 8)
+ );
+ "imul eax, dword ptr [rbp-0x10]" => |a| a.imul_rm(W32, RAX, &Address::new(RBP, -0x10));
+ "imul r9, qword ptr [rbp-0x18]" => |a| a.imul_rm(W64, R9, &Address::new(RBP, -0x18));
"vucomiss xmm1, xmm2" => |a| a.vucomis(Precision::Single, XMM1, XMM2);
"vucomisd xmm9, xmm12" => |a| a.vucomis(Precision::Double, XMM9, XMM12);
});
diff --git a/Libraries/LibWasm/Engine/src/runtime/jit.rs b/Libraries/LibWasm/Engine/src/runtime/jit.rs
index 834a24c45e0..29114a058bd 100644
--- a/Libraries/LibWasm/Engine/src/runtime/jit.rs
+++ b/Libraries/LibWasm/Engine/src/runtime/jit.rs
@@ -23,13 +23,14 @@
//! installs finished code when the interpreter asks it again, which it does every few calls or loop iterations of a
//! function whose compile is pending.
//!
-//! `LIBWASM_JIT` configures it, as a comma-separated list: `off` (the default for now), `on` (tier up hot functions),
-//! `threshold=N` (tier up once calls and loop iterations cost N, 1000 by default), `forced` (tier up at the first call
-//! or loop), `eager` (compile every function when its module is instantiated), and `perf-map` (write
-//! `/tmp/perf-PID.map` for `perf`), `verify-ir` (check every compile's IR and register allocation), `stress-osr`
-//! (tier up at loops only, where they start, so that as many loops as can continue compiled), `sync` (compile on the
-//! thread that runs the code, as `forced` and `stress-osr` do too), and `threads=N` (the number of compile threads,
-//! one per processor core but one by default).
+//! `LIBWASM_JIT` configures it, as a comma-separated list: `off` (run everything interpreted), `on` (tier up hot
+//! functions, the default), `threshold=N` (tier up once calls and loop iterations cost N, 1000 by default), `forced`
+//! (tier up at the first call or loop), `eager` (compile every function when its module is instantiated),
+//! `perf-map` (write `/tmp/perf-PID.map` for `perf`), `verify-ir` (check every compile's IR and register allocation),
+//! `stress-osr` (tier up at loops only, where they start, so that as many loops as can continue compiled),
+//! `stress-nested-osr` (the same, at loops in other loops only), `sync` (compile on the thread that runs the code, as
+//! `forced` and `stress-osr` do too), and `threads=N` (the number of compile threads, one per processor core but one by
+//! default).
use super::ranges::RangeSet;
use super::{FunctionAddress, FunctionInstance, InstanceAddress, Store, Trap, Value};
@@ -53,6 +54,8 @@ pub struct Options {
pub verify_ir: bool,
/// Tier up at loops only, at the first iteration, so that loops continue compiled (OSR) as often as they can.
pub stress_osr: bool,
+ /// Like `stress_osr`, but only at loops in other loops, which the frame enters through the loops around them.
+ pub stress_nested_osr: bool,
/// Compile on the thread that runs the code, and run the code as soon as it is compiled.
pub sync: bool,
/// The number of compile threads, or 0 for one per processor core but one.
@@ -63,6 +66,7 @@ impl Options {
fn compile_options(self) -> libwasm_jit::Options {
libwasm_jit::Options {
verify_ir: self.verify_ir,
+ stress_nested_osr: self.stress_nested_osr,
..libwasm_jit::Options::default()
}
}
@@ -72,6 +76,7 @@ pub fn options() -> Options {
static OPTIONS: OnceLock<Options> = OnceLock::new();
*OPTIONS.get_or_init(|| {
let mut options = Options {
+ enabled: true,
threshold: DEFAULT_THRESHOLD,
..Options::default()
};
@@ -92,10 +97,11 @@ pub fn options() -> Options {
"sync" => options.sync = true,
"perf-map" => options.perf_map = true,
"verify-ir" => options.verify_ir = true,
- "stress-osr" => {
+ "stress-osr" | "stress-nested-osr" => {
options.enabled = true;
options.sync = true;
options.stress_osr = true;
+ options.stress_nested_osr = option.trim() == "stress-nested-osr";
options.threshold = 1;
}
other => {
diff --git a/Libraries/LibWasm/Engine/src/wasi.rs b/Libraries/LibWasm/Engine/src/wasi.rs
index 9c8bbd33520..218c8d0462c 100644
--- a/Libraries/LibWasm/Engine/src/wasi.rs
+++ b/Libraries/LibWasm/Engine/src/wasi.rs
@@ -705,10 +705,18 @@ mod platform {
Ok(nanoseconds_of(&time))
}
+ // NB: The libc crate does not bind getentropy() for musl, whose C library has it.
+ #[cfg(target_env = "musl")]
+ unsafe extern "C" {
+ fn getentropy(buffer: *mut libc::c_void, length: libc::size_t) -> libc::c_int;
+ }
+ #[cfg(not(target_env = "musl"))]
+ use libc::getentropy;
+
pub fn fill_with_random(bytes: &mut [u8]) -> Result<(), Errno> {
// getentropy() fills at most 256 bytes at a time.
for chunk in bytes.chunks_mut(256) {
- if unsafe { libc::getentropy(chunk.as_mut_ptr().cast(), chunk.len()) } != 0 {
+ if unsafe { getentropy(chunk.as_mut_ptr().cast(), chunk.len()) } != 0 {
return Err(last_errno());
}
}
diff --git a/Libraries/LibWasm/JIT/examples/bench_check.rs b/Libraries/LibWasm/JIT/examples/bench_check.rs
index 65516edd436..90e7865f854 100644
--- a/Libraries/LibWasm/JIT/examples/bench_check.rs
+++ b/Libraries/LibWasm/JIT/examples/bench_check.rs
@@ -115,6 +115,10 @@ fn instantiate(module: &Arc<libwasm_engine::Module>, interpreted: bool) -> Optio
}
fn main() {
+ harness::run_main(checked_main);
+}
+
+fn checked_main() {
if std::env::var_os("LIBWASM_JIT").is_none() {
// SAFETY: Nothing else runs yet.
unsafe { std::env::set_var("LIBWASM_JIT", "eager") };
diff --git a/Libraries/LibWasm/JIT/examples/compile_all.rs b/Libraries/LibWasm/JIT/examples/compile_all.rs
index b2afc889a2a..8580e1e713f 100644
--- a/Libraries/LibWasm/JIT/examples/compile_all.rs
+++ b/Libraries/LibWasm/JIT/examples/compile_all.rs
@@ -8,7 +8,7 @@
//!
//! ```text
//! compile_all [--threads N] [--runs N] [--verify] [--stress-registers] [--no-licm] [--gvn] [--quiet]
-//! [--dump-ir FUNCTION] [--dump-asm] MODULE|DIRECTORY...
+//! [--dump-ir FUNCTION [--osr PC]] [--dump-asm] MODULE|DIRECTORY...
//! ```
//!
//! A first pass finds the functions the JIT compiles; every measurement after it compiles only those, so that time
@@ -18,7 +18,7 @@
//! function per byte among those of at least 1 KiB, the cost of the smallest functions, and the nodes, stack slots
//! and moves per byte. Module decoding and validation are not included.
-use libwasm_jit::{CompileContext, CompileFailure, CompileRequest, Options, PHASES, RuntimeInfo, Stats};
+use libwasm_jit::{CompileContext, CompileRequest, Options, PHASES, RuntimeInfo, Stats};
use std::collections::BTreeMap;
use std::sync::Arc;
use std::sync::atomic::{AtomicUsize, Ordering};
@@ -61,6 +61,8 @@ struct Arguments {
runs: usize,
options: Options,
dump: Option<u32>,
+ /// With --dump-ir, the OSR compile at the loop at this module offset.
+ osr: Option<u32>,
quiet: bool,
paths: Vec<String>,
}
@@ -71,6 +73,7 @@ fn parse_arguments() -> Arguments {
runs: 3,
options: Options::default(),
dump: None,
+ osr: None,
quiet: false,
paths: Vec::new(),
};
@@ -85,6 +88,7 @@ fn parse_arguments() -> Arguments {
"--gvn" => arguments.options.gvn = true,
"--quiet" => arguments.quiet = true,
"--dump-asm" => arguments.options.dump_asm = true,
+ "--osr" => arguments.osr = Some(iterator.next().and_then(|n| n.parse().ok()).expect("--osr PC")),
"--dump-ir" => {
arguments.dump = Some(
iterator
@@ -179,19 +183,44 @@ fn main() {
options.dump_ir = !arguments.quiet;
options.stats = true;
let request = CompileRequest {
- osr: None,
+ osr: arguments.osr,
module: module.clone(),
function,
runtime: RUNTIME,
options,
};
+ // NB: The phases are the best of `--runs` compiles, the first of which also dumps.
+ let mut best = None::<Vec<u64>>;
+ for _ in 1..arguments.runs {
+ let quiet = CompileRequest {
+ osr: None,
+ module: module.clone(),
+ function,
+ runtime: RUNTIME,
+ options: Options {
+ dump_ir: false,
+ ..options
+ },
+ };
+ if let Ok(compiled) = libwasm_jit::compile(&mut context, &quiet) {
+ let ticks = compiled.stats.ticks.to_vec();
+ best = Some(match best {
+ Some(best) => best.iter().zip(&ticks).map(|(a, b)| *a.min(b)).collect(),
+ None => ticks,
+ });
+ }
+ }
match libwasm_jit::compile(&mut context, &request) {
Ok(compiled) => {
let body = &module.code[(function - first) as usize];
let bytes = f64::from(body.code.end - body.code.start);
+ let ticks = match best {
+ Some(best) => best.iter().zip(compiled.stats.ticks).map(|(a, b)| *a.min(&b)).collect(),
+ None => compiled.stats.ticks.to_vec(),
+ };
let phases = libwasm_jit::PHASES
.iter()
- .zip(compiled.stats.ticks)
+ .zip(ticks)
.map(|(phase, ticks)| format!("{phase} {:.1}", ticks as f64 / ticks_per_ns / bytes))
.collect::<Vec<_>>();
println!(
@@ -222,8 +251,7 @@ fn main() {
};
match libwasm_jit::compile(&mut context, &request) {
Ok(_) => compiled.push(first + index),
- Err(CompileFailure::Unsupported { what, .. }) => *failures.entry(what).or_default() += 1,
- Err(CompileFailure::CodeGeneration) => *failures.entry("code generation failed").or_default() += 1,
+ Err(failure) => *failures.entry(failure.reason()).or_default() += 1,
}
}
let size = |function: u32| {
diff --git a/Libraries/LibWasm/JIT/examples/run_kernel.rs b/Libraries/LibWasm/JIT/examples/run_kernel.rs
index 6e9b6e9c96d..cd2cc6f2e8d 100644
--- a/Libraries/LibWasm/JIT/examples/run_kernel.rs
+++ b/Libraries/LibWasm/JIT/examples/run_kernel.rs
@@ -37,6 +37,10 @@ fn parse(argument: &str) -> Value {
}
fn main() {
+ harness::run_main(checked_main);
+}
+
+fn checked_main() {
let mut arguments = std::env::args().skip(1);
let path = arguments.next().expect("MODULE");
let function: u32 = arguments
diff --git a/Libraries/LibWasm/JIT/examples/smith_check.rs b/Libraries/LibWasm/JIT/examples/smith_check.rs
index 01ae2cdb938..329b165328e 100644
--- a/Libraries/LibWasm/JIT/examples/smith_check.rs
+++ b/Libraries/LibWasm/JIT/examples/smith_check.rs
@@ -150,6 +150,10 @@ struct Totals {
}
fn main() {
+ harness::run_main(checked_main);
+}
+
+fn checked_main() {
let mut count = 100;
let mut seed = 1u64;
let mut keep = None;
@@ -273,10 +277,7 @@ fn main() {
totals.compiled += compiled.entries[first..].iter().filter(|entry| **entry != 0).count();
totals.runnable += compiled.runnable[first..].iter().filter(|runnable| **runnable).count();
for failure in compiled.failures.iter().flatten() {
- let what = match failure {
- libwasm_jit::CompileFailure::Unsupported { what, .. } => *what,
- libwasm_jit::CompileFailure::CodeGeneration => "code generation",
- };
+ let what = failure.reason();
*totals.unsupported.entry(what).or_default() += 1;
}
let mut exports = interpreted
diff --git a/Libraries/LibWasm/JIT/examples/spec_check.rs b/Libraries/LibWasm/JIT/examples/spec_check.rs
index d3ba7afee1a..7028ea9f210 100644
--- a/Libraries/LibWasm/JIT/examples/spec_check.rs
+++ b/Libraries/LibWasm/JIT/examples/spec_check.rs
@@ -8,22 +8,33 @@
//! with the interpreter (see `tests/harness/script.rs`).
//!
//! ```text
-//! spec_check [--verbose] [--stress-registers] [--no-licm] [--gvn] [--runtime] DIRECTORY|SCRIPT.json...
+//! spec_check [--verbose] [--stress-registers] [--no-licm] [--gvn] [--runtime] [--dump FILE] DIRECTORY|SCRIPT.json...
//! ```
+//!
+//! `--dump FILE` writes what the interpreter did in every action to FILE, which should be the same on every
+//! architecture: with `--runtime` and `LIBWASM_JIT=off`, comparing the files of two architectures checks one's
+//! interpreter against the other's.
#[path = "../tests/harness/mod.rs"]
mod harness;
fn main() {
+ harness::run_main(checked_main);
+}
+
+fn checked_main() {
let mut verbose = false;
let mut runtime = false;
let mut paths = Vec::new();
+ let mut dump_path = None;
+ let mut arguments = std::env::args().skip(1);
let mut options = libwasm_jit::Options {
verify_ir: true,
..Default::default()
};
- for argument in std::env::args().skip(1) {
+ while let Some(argument) = arguments.next() {
match argument.as_str() {
+ "--dump" => dump_path = arguments.next(),
"--verbose" => verbose = true,
"--stress-registers" => options.stress_registers = true,
"--no-licm" => options.no_licm = true,
@@ -36,7 +47,19 @@ fn main() {
// SAFETY: Nothing else runs yet.
unsafe { std::env::set_var("LIBWASM_JIT", "eager") };
}
- let totals = harness::script::run(&paths, verbose, options, runtime);
+ let mut dump = dump_path.map(|path| {
+ std::io::BufWriter::new(std::fs::File::create(&path).unwrap_or_else(|error| panic!("create {path}: {error}")))
+ });
+ let totals = harness::script::run_with_dump(
+ &paths,
+ verbose,
+ options,
+ runtime,
+ dump.as_mut().map(|dump| dump as &mut dyn std::io::Write),
+ );
+ if let Some(mut dump) = dump {
+ std::io::Write::flush(&mut dump).expect("write the dump");
+ }
println!(
"{} scripts, {} modules, {} functions: {} compiled, {} runnable, {} exercised; {} cases, {} failures, {} reached uncompiled code",
totals.scripts,
diff --git a/Libraries/LibWasm/JIT/src/builder/calls.rs b/Libraries/LibWasm/JIT/src/builder/calls.rs
index 2cec530b953..a37a782fae2 100644
--- a/Libraries/LibWasm/JIT/src/builder/calls.rs
+++ b/Libraries/LibWasm/JIT/src/builder/calls.rs
@@ -11,8 +11,7 @@
//! the callee's instance, found from its header, and that instance's memory base. Host functions have no instance;
//! they get the caller's, through which their stub finds the runtime.
-use super::{Builder, instance_offset, ir_type, unsupported};
-use crate::CompileFailure;
+use super::{Builder, instance_offset, ir_type};
use crate::ir::{Func, NONE, Node, Op, Type, Value};
use libwasm_module::Module;
use libwasm_module::abi::{InstanceData, TRAP_NULL_REFERENCE, TRAP_UNDEFINED_ELEMENT, TRAP_UNINITIALIZED_ELEMENT};
@@ -70,14 +69,7 @@ impl Builder {
self.instance_pointer(func, offset_of!(InstanceData, functions), function, Type::Ref)
}
- pub(super) fn call(
- &mut self,
- func: &mut Func,
- module: &Module,
- function: u32,
- kind: CallKind,
- pc: usize,
- ) -> Result<(), CompileFailure> {
+ pub(super) fn call(&mut self, func: &mut Func, module: &Module, function: u32, kind: CallKind) {
let ty = module.function_type(function).expect("functions have function types");
let header = self.instance_pointer(func, offset_of!(InstanceData, functions), function, Type::Pointer);
let (instance, memory_base) = if function < module.imported_function_count {
@@ -85,7 +77,7 @@ impl Builder {
} else {
(self.instance, self.memory_base)
};
- self.emit_call(func, ty, [header, instance, memory_base], function, kind, pc)
+ self.emit_call(func, ty, [header, instance, memory_base], function, kind);
}
pub(super) fn call_indirect(
@@ -95,8 +87,7 @@ impl Builder {
type_index: u32,
table: u32,
kind: CallKind,
- pc: usize,
- ) -> Result<(), CompileFailure> {
+ ) {
let ty = module.types[type_index as usize]
.as_func()
.expect("call_indirect has a function type");
@@ -122,17 +113,10 @@ impl Builder {
),
);
let (instance, memory_base) = self.callee_instance(func, element);
- self.emit_call(func, ty, [element, instance, memory_base], NONE, kind, pc)
+ self.emit_call(func, ty, [element, instance, memory_base], NONE, kind);
}
- pub(super) fn call_ref(
- &mut self,
- func: &mut Func,
- module: &Module,
- type_index: u32,
- kind: CallKind,
- pc: usize,
- ) -> Result<(), CompileFailure> {
+ pub(super) fn call_ref(&mut self, func: &mut Func, module: &Module, type_index: u32, kind: CallKind) {
let ty = module.types[type_index as usize]
.as_func()
.expect("call_ref has a function type");
@@ -142,7 +126,7 @@ impl Builder {
Node::new(Op::CheckNull, Type::None, TRAP_NULL_REFERENCE as u8, [reference, 0, 0]),
);
let (instance, memory_base) = self.callee_instance(func, reference);
- self.emit_call(func, ty, [reference, instance, memory_base], NONE, kind, pc)
+ self.emit_call(func, ty, [reference, instance, memory_base], NONE, kind);
}
/// The instance and memory base a call of the function whose header is `header` passes.
@@ -170,11 +154,7 @@ impl Builder {
[header, instance, memory_base]: [Value; 3],
function: u32,
kind: CallKind,
- pc: usize,
- ) -> Result<(), CompileFailure> {
- if ty.results.iter().chain(&ty.params).any(|ty| ir_type(*ty).is_none()) {
- return unsupported(pc, "a call with values of a type the JIT does not compile");
- }
+ ) {
let argument_count = ty.params.len();
let start = func.operands.len() as u32;
func.operands.extend_from_slice(&[header, instance, memory_base]);
@@ -201,7 +181,7 @@ impl Builder {
&[],
);
self.set_unreachable();
- return Ok(());
+ return;
}
let call = Self::append(func, node);
if !ty.results.is_empty() {
@@ -214,6 +194,5 @@ impl Builder {
}
self.call_epoch += 1;
self.check_exception(func, call);
- Ok(())
}
}
diff --git a/Libraries/LibWasm/JIT/src/builder/mod.rs b/Libraries/LibWasm/JIT/src/builder/mod.rs
index 0152e0a5394..60d25ccd4a4 100644
--- a/Libraries/LibWasm/JIT/src/builder/mod.rs
+++ b/Libraries/LibWasm/JIT/src/builder/mod.rs
@@ -31,7 +31,6 @@ mod memories;
mod simd;
mod tables;
-use crate::CompileFailure;
use crate::decode::{BlockType, Decoder, Instruction};
use crate::ir::{BlockId, Func, IntCondition, LoadKind, Loop, NONE, Node, Op, Type, Value};
use crate::ir::{FLAG_IMMUTABLE, FloatCondition};
@@ -200,33 +199,54 @@ pub struct Builder {
defined: u32,
}
-/// An OSR compile: the function as a continuation of an interpreter frame at an outermost loop.
+/// An OSR compile: the function as a continuation of an interpreter frame at a loop.
///
/// Its only parameter is the frame's fp. Its entry block branches, on a constant, to a block that loads the frame's
-/// locals and operand stack and jumps to the loop's header, and to the function's code as it starts, which never
-/// runs. That keeps the entry block dominating everything. At the loop's header, every value on the operand stack
-/// becomes a phi of the two ways in, and the back edges.
+/// locals and operand stack and jumps to the header of the outermost loop around the frame's position, and to the
+/// function's code as it starts, which never runs. That keeps the entry block dominating everything. Every loop
+/// entered this way has a second way in, from the frame, besides its entry and back edges, and every value on the
+/// operand stack at its header becomes a phi of them.
+///
+/// A loop in other loops is entered through them, so that each loop keeps a single header: each loop around it starts
+/// with a branch on a flag (a local of its own, which only the way in from the frame sets), which goes from the header
+/// to the next loop in, through a block that loads the operand stack at that loop from the frame.
#[derive(Default)]
struct Osr {
/// The module offset of the loop instruction.
pc: u32,
/// The types of the operand stack at the loop, from bottom to top, parameters included.
stack_types: Vec<Type>,
- /// While probing: whether the loop was found, reachable and in no other loop.
+ /// The module offsets of the loops around it, outermost first, and how many of them have been entered.
+ around: Vec<u32>,
+ entered: usize,
+ /// While probing: whether the loop was found and reachable, and the loops open where the probe is.
found: bool,
probing: bool,
- /// The block that loads the frame, the slot of its jump to the header, and the values it loaded from the
- /// operand stack.
+ open_loops: Vec<u32>,
+ /// The frame's fp, and the local that flags the way in from the frame (see above).
+ frame: Value,
+ flag: u32,
+ /// The block that jumps to the next loop to enter from the frame, the slot of that jump, and the values the
+ /// operand stack has at that loop's header, from the frame.
block: BlockId,
slot: u32,
stack: Vec<Value>,
+ /// The loops entered from the frame.
+ entries: Vec<OsrEntry>,
+}
+
+/// A loop an OSR compile enters from the frame: its index, the indices of its entry edge and its edge from the frame,
+/// and the phis of the values below its parameters (phi, value from the entry, value from the frame).
+struct OsrEntry {
loop_index: u32,
entry_edge: u32,
edge: u32,
- /// The phis of the values below the loop's parameters: (phi, value from the start, value from the frame).
below: Vec<(Value, Value, Value)>,
}
+/// Where an OSR compile enters a function: the types of the operand stack at the loop, and the loops around it.
+pub type OsrEntryPoint = (Vec<Type>, Vec<u32>);
+
/// The fp offset of the local slot `local` of an interpreter frame.
fn frame_local_offset(local: u32) -> i32 {
8 * local as i32
@@ -236,10 +256,6 @@ fn key(block: BlockId, local: u32) -> u64 {
(u64::from(block) << 32) | u64::from(local)
}
-fn unsupported<T>(pc: usize, what: &'static str) -> Result<T, CompileFailure> {
- Err(CompileFailure::Unsupported { pc: pc as u32, what })
-}
-
fn instance_offset(offset: usize) -> u32 {
offset as u32
}
@@ -273,28 +289,22 @@ impl Builder {
}
/// Builds the IR of the defined function `index` (counting imports) of `module` into `func`.
- pub fn build(&mut self, module: &Module, index: u32, func: &mut Func) -> Result<(), CompileFailure> {
+ pub fn build(&mut self, module: &Module, index: u32, func: &mut Func) {
self.osr = None;
- self.build_function(module, index, func)
+ self.build_function(module, index, func);
}
- /// The types of the operand stack at the loop at module offset `pc`, if it is reachable and in no other loop,
- /// which an OSR compile needs. Builds the function into `func` to find out.
- pub fn probe_osr(
- &mut self,
- module: &Module,
- index: u32,
- pc: u32,
- func: &mut Func,
- ) -> Result<Option<Vec<Type>>, CompileFailure> {
+ /// The types of the operand stack at the loop at module offset `pc`, and the loops around it, if an OSR compile
+ /// can enter it: if it is reachable and in no legacy handler. Builds the function into `func` to find out.
+ pub fn probe_osr(&mut self, module: &Module, index: u32, pc: u32, func: &mut Func) -> Option<OsrEntryPoint> {
self.osr = Some(Osr {
pc,
probing: true,
..Osr::default()
});
- self.build_function(module, index, func)?;
+ self.build_function(module, index, func);
let osr = self.osr.take().expect("the probe is there");
- Ok(osr.found.then_some(osr.stack_types))
+ osr.found.then_some((osr.stack_types, osr.around))
}
/// Builds the OSR compile of the function at the loop at `pc`, whose operand stack has `stack_types` there (see
@@ -304,25 +314,24 @@ impl Builder {
module: &Module,
index: u32,
pc: u32,
- stack_types: Vec<Type>,
+ (stack_types, around): OsrEntryPoint,
func: &mut Func,
- ) -> Result<(), CompileFailure> {
+ ) {
self.osr = Some(Osr {
pc,
stack_types,
- loop_index: NONE,
+ around,
..Osr::default()
});
- let result = self.build_function(module, index, func);
+ self.build_function(module, index, func);
self.osr = None;
- result
}
fn is_osr_compile(&self) -> bool {
self.osr.as_ref().is_some_and(|osr| !osr.probing)
}
- fn build_function(&mut self, module: &Module, index: u32, func: &mut Func) -> Result<(), CompileFailure> {
+ fn build_function(&mut self, module: &Module, index: u32, func: &mut Func) {
self.clear();
func.clear();
let defined = (index - module.imported_function_count) as usize;
@@ -331,22 +340,16 @@ impl Builder {
let ty = module.function_type(index).expect("functions have function types");
let start = body.code.start as usize;
for &param in &ty.params {
- let Some(param) = ir_type(param) else {
- return unsupported(start, "a parameter of a type the JIT does not compile");
- };
+ let param = ir_type(param).expect("the JIT has a type for every value");
func.params.push(param);
self.local_types.push(param);
}
for &result in &ty.results {
- let Some(result) = ir_type(result) else {
- return unsupported(start, "a result of a type the JIT does not compile");
- };
+ let result = ir_type(result).expect("the JIT has a type for every value");
func.results.push(result);
}
for &(count, local) in &body.locals {
- let Some(local) = ir_type(local) else {
- return unsupported(start, "a local of a type the JIT does not compile");
- };
+ let local = ir_type(local).expect("the JIT has a type for every value");
self.local_types.extend(std::iter::repeat_n(local, count as usize));
}
self.current.resize(self.local_types.len(), (NONE, NONE));
@@ -365,7 +368,7 @@ impl Builder {
self.params.push(value);
}
}
- let results = self.push_types(&ty.results)?;
+ let results = self.push_types(&ty.results);
self.controls.push(Control {
kind: ControlKind::Function,
params: (0, 0),
@@ -392,17 +395,31 @@ impl Builder {
let pc = decoder.position();
let instruction = decoder.decode();
if self.controls.last().expect("there is a construct").unreachable {
- self.skip(func, module, &instruction, &mut decoder, pc)?;
+ self.skip(func, module, &instruction, &mut decoder, pc);
continue;
}
- self.instruction(func, module, instruction, &decoder, pc)?;
+ self.instruction(func, module, instruction, &decoder, pc);
}
- Ok(())
}
// Blocks.
/// Makes the entry of an OSR compile (see `Osr`) and returns the block the function's code starts in.
+ /// Loads the bottom values of the operand stack of the interpreter frame at `frame`, of types `types`.
+ fn load_frame_stack(func: &mut Func, frame: Value, types: &[Type]) -> Vec<Value> {
+ let mut offset = -(libwasm_module::abi::FRAME_HEADER_SIZE as i32);
+ let mut stack = Vec::with_capacity(types.len());
+ for &ty in types {
+ // The operand stack grows down from the frame header; a value's lowest slot is its first.
+ offset -= 8 * ty.slots() as i32;
+ stack.push(Self::append(
+ func,
+ Node::new(Op::FrameLoad, ty, 0, [frame, offset as u32, 0]),
+ ));
+ }
+ stack
+ }
+
fn enter_osr(&mut self, func: &mut Func) -> BlockId {
let param_types = std::mem::take(&mut func.params);
func.params.push(Type::Pointer);
@@ -448,19 +465,17 @@ impl Builder {
);
self.write_local(local, value);
}
+ let flag = self.local_types.len() as u32;
+ self.local_types.push(Type::I32);
+ self.current.push((NONE, NONE));
+ let one = self.constant(func, Type::I32, 1);
+ self.write_local(flag, one);
let stack_types = std::mem::take(&mut self.osr.as_mut().expect("this is an OSR compile").stack_types);
- let mut offset = -(libwasm_module::abi::FRAME_HEADER_SIZE as i32);
- let mut stack = Vec::with_capacity(stack_types.len());
- for &ty in &stack_types {
- // The operand stack grows down from the frame header; a value's lowest slot is its first.
- offset -= 8 * ty.slots() as i32;
- stack.push(Self::append(
- func,
- Node::new(Op::FrameLoad, ty, 0, [frame, offset as u32, 0]),
- ));
- }
+ let stack = Self::load_frame_stack(func, frame, &stack_types);
let slot = self.terminate(func, Node::new(Op::Jump, Type::None, 0, [0; 3]), &[NONE]);
let osr = self.osr.as_mut().expect("this is an OSR compile");
+ osr.frame = frame;
+ osr.flag = flag;
osr.block = from_frame;
osr.slot = slot;
osr.stack = stack;
@@ -778,9 +793,12 @@ impl Builder {
continue;
}
let loop_index = func.blocks[frame.block as usize].loop_index;
- let osr_loop = self.osr.as_ref().map_or(NONE, |osr| osr.loop_index);
+ let entered_from_frame = self
+ .osr
+ .as_ref()
+ .is_some_and(|osr| osr.entries.iter().any(|entry| entry.loop_index == loop_index));
if self.may_be_on_cycle(func, frame.block)
- && loop_index != osr_loop
+ && !entered_from_frame
&& self.loop_writes.get(key(loop_index, local)).is_none()
{
// OPTIMIZATION: Everywhere in a loop that does not write the local, it has the value it entered
@@ -883,31 +901,26 @@ impl Builder {
// Types and labels.
- fn push_types(&mut self, types: &[ValType]) -> Result<(u32, u32), CompileFailure> {
+ fn push_types(&mut self, types: &[ValType]) -> (u32, u32) {
let start = self.types.len() as u32;
for &ty in types {
- let Some(ty) = ir_type(ty) else {
- return Err(CompileFailure::Unsupported {
- pc: 0,
- what: "a block of a type the JIT does not compile",
- });
- };
+ let ty = ir_type(ty).expect("the JIT has a type for every value");
self.types.push(ty);
}
- Ok((start, types.len() as u32))
+ (start, types.len() as u32)
}
- fn block_signature(&mut self, module: &Module, block_type: BlockType) -> Result<Signature, CompileFailure> {
+ fn block_signature(&mut self, module: &Module, block_type: BlockType) -> Signature {
match block_type {
- BlockType::Empty => Ok(((0, 0), (0, 0))),
- BlockType::Value(value) => Ok(((0, 0), self.push_types(&[value])?)),
+ BlockType::Empty => ((0, 0), (0, 0)),
+ BlockType::Value(value) => ((0, 0), self.push_types(&[value])),
BlockType::Function(index) => {
let function: &FuncType = module.types[index as usize]
.as_func()
.expect("block types are functions");
- let params = self.push_types(&function.params)?;
- let results = self.push_types(&function.results)?;
- Ok((params, results))
+ let params = self.push_types(&function.params);
+ let results = self.push_types(&function.results);
+ (params, results)
}
}
}
@@ -974,7 +987,7 @@ impl Builder {
instruction: &Instruction,
decoder: &mut Decoder<'_>,
pc: usize,
- ) -> Result<(), CompileFailure> {
+ ) {
match instruction {
Instruction::Else
| Instruction::End
@@ -987,9 +1000,8 @@ impl Builder {
while depth > 0 {
depth += crate::decode::nesting_change(&decoder.decode());
}
- Ok(())
}
- _ => Ok(()),
+ _ => {}
}
}
@@ -1000,7 +1012,7 @@ impl Builder {
instruction: Instruction,
decoder: &Decoder<'_>,
pc: usize,
- ) -> Result<(), CompileFailure> {
+ ) {
use Instruction as I;
match instruction {
I::Nop => {}
@@ -1013,30 +1025,37 @@ impl Builder {
self.set_unreachable();
}
I::Block(block_type) => {
- let (params, results) = self.block_signature(module, block_type)?;
+ let (params, results) = self.block_signature(module, block_type);
self.push_control(ControlKind::Block, params, results, NONE);
}
I::Loop(block_type) => {
- let (params, results) = self.block_signature(module, block_type)?;
+ let (params, results) = self.block_signature(module, block_type);
let at_osr_loop = self.osr.as_ref().is_some_and(|osr| osr.pc == pc as u32);
- if at_osr_loop && self.osr.as_ref().is_some_and(|osr| osr.probing) {
+ if self.osr.as_ref().is_some_and(|osr| osr.probing) {
// NB: A legacy handler's exception is no value the frame has, so loops in handlers do not OSR.
- let outermost = !self
- .controls
- .iter()
- .any(|control| matches!(control.kind, ControlKind::Loop | ControlKind::Catch));
+ let in_handler = self.controls.iter().any(|control| control.kind == ControlKind::Catch);
let stack_types = self.stack.iter().map(|value| func.node(*value).ty).collect();
let osr = self.osr.as_mut().expect("probing");
- osr.found = outermost;
- osr.stack_types = stack_types;
- }
- self.begin_loop(func, params, results);
- if at_osr_loop && self.is_osr_compile() {
- self.enter_osr_loop(func);
+ if at_osr_loop {
+ osr.found = !in_handler;
+ osr.stack_types = stack_types;
+ osr.around = osr.open_loops.clone();
+ }
+ osr.open_loops.push(pc as u32);
+ self.begin_loop(func, params, results, None);
+ } else if let Some(osr) = &self.osr
+ && osr
+ .around
+ .get(osr.entered)
+ .map_or(at_osr_loop, |around| *around == pc as u32)
+ {
+ self.enter_osr_loop(func, params, results, at_osr_loop);
+ } else {
+ self.begin_loop(func, params, results, None);
}
}
I::If(block_type) => {
- let (params, results) = self.block_signature(module, block_type)?;
+ let (params, results) = self.block_signature(module, block_type);
self.begin_if(func, params, results);
}
I::Else => self.begin_else(func),
@@ -1059,7 +1078,7 @@ impl Builder {
self.branch(func, depth);
self.set_unreachable();
}
- I::Call(function) => self.call(func, module, function, CallKind::Normal, pc)?,
+ I::Call(function) => self.call(func, module, function, CallKind::Normal),
I::Drop => {
self.pop();
}
@@ -1093,7 +1112,7 @@ impl Builder {
self.write_local(local, value);
self.note_loop_write(func.blocks[self.current_block as usize].loop_index, local);
}
- I::GlobalGet(global) => self.global_get(func, module, global, pc)?,
+ I::GlobalGet(global) => self.global_get(func, module, global),
I::GlobalSet(global) => self.global_set(func, global),
I::Access { opcode, argument } => {
debug_assert_eq!(argument.memory, 0, "plain accesses are of memory 0");
@@ -1147,21 +1166,21 @@ impl Builder {
I::MemorySize(memory) => self.memory_size(func, module, memory),
I::MemoryGrow(memory) => self.memory_grow(func, module, memory),
I::CallIndirect { type_index, table } => {
- self.call_indirect(func, module, type_index, table, CallKind::Normal, pc)?;
+ self.call_indirect(func, module, type_index, table, CallKind::Normal);
}
- I::CallRef(type_index) => self.call_ref(func, module, type_index, CallKind::Normal, pc)?,
- I::ReturnCall(function) => self.call(func, module, function, CallKind::Tail, pc)?,
+ I::CallRef(type_index) => self.call_ref(func, module, type_index, CallKind::Normal),
+ I::ReturnCall(function) => self.call(func, module, function, CallKind::Tail),
I::ReturnCallIndirect { type_index, table } => {
- self.call_indirect(func, module, type_index, table, CallKind::Tail, pc)?;
+ self.call_indirect(func, module, type_index, table, CallKind::Tail);
}
- I::ReturnCallRef(type_index) => self.call_ref(func, module, type_index, CallKind::Tail, pc)?,
+ I::ReturnCallRef(type_index) => self.call_ref(func, module, type_index, CallKind::Tail),
I::TryTable(block_type) => {
- let (params, results) = self.block_signature(module, block_type)?;
+ let (params, results) = self.block_signature(module, block_type);
let clauses: Vec<[u32; 3]> = decoder.catch_clauses().collect();
self.begin_try_table(params, results, &clauses);
}
I::Try(block_type) => {
- let (params, results) = self.block_signature(module, block_type)?;
+ let (params, results) = self.block_signature(module, block_type);
self.begin_try(module, params, results, decoder.position());
}
I::Catch(_) | I::CatchAll => self.begin_catch(func, module),
@@ -1242,12 +1261,11 @@ impl Builder {
quickening::DROP_V128 => I::Drop,
_ => I::Select,
};
- return self.instruction(func, module, plain, decoder, pc);
+ self.instruction(func, module, plain, decoder, pc);
}
- I::Simd { sub_opcode, checked } => return self.simd(func, module, sub_opcode, checked, decoder, pc),
+ I::Simd { sub_opcode, checked } => self.simd(func, module, sub_opcode, checked, decoder),
I::Atomic(sub_opcode) => self.atomic(func, module, sub_opcode, decoder),
}
- Ok(())
}
fn numeric(&mut self, func: &mut Func, opcode: u8) {
@@ -1354,11 +1372,21 @@ impl Builder {
});
}
- fn begin_loop(&mut self, func: &mut Func, params: (u32, u32), results: (u32, u32)) {
+ /// Begins a loop, entered from the current block, or from `entry`, a block and the slot of its jump, which
+ /// is already made.
+ fn begin_loop(&mut self, func: &mut Func, params: (u32, u32), results: (u32, u32), entry: Option<(BlockId, u32)>) {
let header = self.new_block(func);
// NB: The header is created before the loop's control, so it takes the enclosing loop; fixed up below.
- self.terminate(func, Node::new(Op::Jump, Type::None, 0, [0; 3]), &[header]);
- let entry = self.current_block;
+ let entry = match entry {
+ Some((block, slot)) => {
+ func.successors[slot as usize] = header;
+ block
+ }
+ None => {
+ self.terminate(func, Node::new(Op::Jump, Type::None, 0, [0; 3]), &[header]);
+ self.current_block
+ }
+ };
self.sealed[header as usize] = false;
let loop_index = func.loops.len() as u32;
let parent = func.blocks[header as usize].loop_index;
@@ -1399,40 +1427,104 @@ impl Builder {
self.call_epoch += 1;
}
- /// Makes the loop just begun the one an OSR compile enters (see `Osr`).
- fn enter_osr_loop(&mut self, func: &mut Func) {
+ /// Begins a loop an OSR compile enters from the frame (see `Osr`): the loop the frame is at if `target`, else a
+ /// loop around it.
+ fn enter_osr_loop(&mut self, func: &mut Func, params: (u32, u32), results: (u32, u32), target: bool) {
+ let height = self.stack.len() - params.1 as usize;
+ let mut osr = self.osr.take().expect("this is an OSR compile");
+ let first = osr.entered == 0;
+ let mut entry = None;
+ if !first {
+ // The way in from the frame comes from the branch of the loop around this one, through a block that loads
+ // the operand stack this loop starts with. It goes before the loop's header, in linear order.
+ let slot = self.terminate(func, Node::new(Op::Jump, Type::None, 0, [0; 3]), &[NONE]);
+ entry = Some((self.current_block, slot));
+ let load = self.new_block(func);
+ Self::set_predecessors(func, load, &[osr.block]);
+ func.successors[osr.slot as usize] = load;
+ self.start_block(func, load);
+ let count = if target { osr.stack_types.len() } else { height };
+ osr.stack = Self::load_frame_stack(func, osr.frame, &osr.stack_types[..count]);
+ if !target {
+ // The flag is up again for this loop's header, which branches on it.
+ let one = self.constant(func, Type::I32, 1);
+ self.write_local(osr.flag, one);
+ }
+ osr.block = load;
+ osr.slot = self.terminate(func, Node::new(Op::Jump, Type::None, 0, [0; 3]), &[NONE]);
+ }
+ // The values the loop's parameters have from the frame, which only the loop the frame is at needs.
+ if !target {
+ osr.stack.truncate(height);
+ for index in 0..params.1 {
+ let ty = self.types[(params.0 + index) as usize];
+ let zero = self.constant(func, ty, 0);
+ osr.stack.push(zero);
+ }
+ }
+ self.begin_loop(func, params, results, entry);
let index = self.controls.len() - 1;
let control = self.controls[index];
let header = control.block;
- let height = control.height as usize;
- let mut osr = self.osr.take().expect("this is an OSR compile");
func.successors[osr.slot as usize] = header;
// The edge from the frame comes second, after the one from the function's start and before every back edge.
let values = self.edge_values.len() as u32;
self.edge_values.extend_from_slice(&osr.stack[height..]);
- osr.entry_edge = control.edges;
+ let entry_edge = control.edges;
self.edges.push(Edge {
block: osr.block,
slot: NONE,
values,
next: control.edges,
});
- osr.edge = self.edges.len() as u32 - 1;
- self.controls[index].edges = osr.edge;
- osr.loop_index = control.loop_index;
+ let edge = self.edges.len() as u32 - 1;
+ self.controls[index].edges = edge;
+ let mut below = Vec::with_capacity(height);
for position in 0..height {
let normal = Self::resolve(func, self.stack[position]);
let phi = Self::new_phi(func, header, func.node(normal).ty);
- osr.below.push((phi, normal, osr.stack[position]));
+ below.push((phi, normal, osr.stack[position]));
self.stack[position] = phi;
}
+ osr.entries.push(OsrEntry {
+ loop_index: control.loop_index,
+ entry_edge,
+ edge,
+ below,
+ });
+ osr.entered += 1;
+ let flag = osr.flag;
self.osr = Some(osr);
- // Nothing numbered before the loop dominates the code after it any more. Every construct still open forgets
- // what is numbered from here on when it ends, the loop included.
+ // Nothing numbered before the loop dominates the code after it any more, since the way in from the frame
+ // skips it. Every construct still open forgets what is numbered from here on when it ends, the loop included.
self.unnumber(0);
for control in &mut self.controls {
control.numbering_mark = 0;
}
+ if target {
+ return;
+ }
+ // A loop around the one the frame is at: from the frame, go on to the next loop in.
+ let block = self.current_block;
+ let set = self.read_local(func, block, flag);
+ let slot = self.terminate(func, Node::new(Op::Branch, Type::None, 0, [set, 0, 0]), &[NONE, NONE]);
+ let onward = self.new_block(func);
+ Self::set_predecessors(func, onward, &[block]);
+ func.successors[slot as usize] = onward;
+ self.start_block(func, onward);
+ // The flag is down from here on, so that no back edge or exit of a loop carries it.
+ let zero = self.constant(func, Type::I32, 0);
+ self.write_local(flag, zero);
+ let onward_slot = self.terminate(func, Node::new(Op::Jump, Type::None, 0, [0; 3]), &[NONE]);
+ let body = self.new_block(func);
+ Self::set_predecessors(func, body, &[block]);
+ func.successors[slot as usize + 1] = body;
+ self.start_block(func, body);
+ self.write_local(flag, zero);
+ self.note_loop_write(control.loop_index, flag);
+ let osr = self.osr.as_mut().expect("this is an OSR compile");
+ osr.block = onward;
+ osr.slot = onward_slot;
}
fn begin_if(&mut self, func: &mut Func, params: (u32, u32), results: (u32, u32)) {
@@ -1568,6 +1660,11 @@ impl Builder {
fn end_loop(&mut self, func: &mut Func, index: usize) {
let control = self.controls[index];
+ if let Some(osr) = self.osr.as_mut()
+ && osr.probing
+ {
+ osr.open_loops.pop();
+ }
let header = control.block;
let reachable = !control.unreachable;
// The back edges are the loop label's edges but the first, which enters the loop.
@@ -1619,15 +1716,14 @@ impl Builder {
Self::try_remove_trivial_phi(func, phi);
}
if let Some(osr) = &self.osr
- && osr.loop_index == control.loop_index
- && control.loop_index != NONE
+ && let Some(entry) = osr.entries.iter().find(|entry| entry.loop_index == control.loop_index)
{
- for &(phi, normal, from_frame) in &osr.below {
+ for &(phi, normal, from_frame) in &entry.below {
let start = func.operands.len() as u32;
for &edge in &self.scratch_values {
- let value = if edge == osr.entry_edge {
+ let value = if edge == entry.entry_edge {
normal
- } else if edge == osr.edge {
+ } else if edge == entry.edge {
from_frame
} else {
phi
@@ -1821,11 +1917,9 @@ impl Builder {
)
}
- fn global_get(&mut self, func: &mut Func, module: &Module, global: u32, pc: usize) -> Result<(), CompileFailure> {
+ fn global_get(&mut self, func: &mut Func, module: &Module, global: u32) {
let ty = module.global_space[global as usize];
- let Some(value_type) = ir_type(ty.value) else {
- return unsupported(pc, "a global of a type the JIT does not compile");
- };
+ let value_type = ir_type(ty.value).expect("the JIT has a type for every value");
let storage = self.global_storage(func, global);
let value = if ty.mutable {
let key = numbering_key(&Node::new(
@@ -1850,7 +1944,6 @@ impl Builder {
)
};
self.push(value);
- Ok(())
}
fn global_set(&mut self, func: &mut Func, global: u32) {
diff --git a/Libraries/LibWasm/JIT/src/builder/simd.rs b/Libraries/LibWasm/JIT/src/builder/simd.rs
index 1e09d3fce68..176b1052760 100644
--- a/Libraries/LibWasm/JIT/src/builder/simd.rs
+++ b/Libraries/LibWasm/JIT/src/builder/simd.rs
@@ -11,8 +11,7 @@
//! products are their deterministic counterparts, which they become here, so that they share those nodes' value
//! numbers and code.
-use super::{Builder, unsupported};
-use crate::CompileFailure;
+use super::Builder;
use crate::decode::{Decoder, MemoryArgument};
use crate::ir::{Func, LoadKind, Node, Op, Type, Value};
use libwasm_module::Module;
@@ -90,12 +89,9 @@ impl Builder {
sub_opcode: u32,
checked: bool,
decoder: &Decoder<'_>,
- pc: usize,
- ) -> Result<(), CompileFailure> {
+ ) {
let sub_opcode = canonical(sub_opcode);
- let Some(kind) = simd_kind(sub_opcode) else {
- return unsupported(pc, "an unknown SIMD instruction");
- };
+ let kind = simd_kind(sub_opcode).expect("validation rejects unknown SIMD instructions");
let value = match kind {
SimdKind::Load { size } => {
let index = Self::resolve(func, self.pop());
@@ -112,7 +108,7 @@ impl Builder {
let index = Self::resolve(func, self.pop());
let address = self.simd_address(func, module, checked, decoder.simd_argument(), index, 4);
self.store(func, address, value, 4);
- return Ok(());
+ return;
}
SimdKind::LoadLane { size } => {
// A scalar load, and its value replacing the lane.
@@ -148,7 +144,7 @@ impl Builder {
let scalar = self.pure(func, Node::new(Op::ExtractLane, ty, 0, [vector, extract, lane]));
let address = self.simd_address(func, module, checked, decoder.simd_argument(), index, size_log2);
self.store(func, address, scalar, size_log2);
- return Ok(());
+ return;
}
SimdKind::Const => {
let bits = u128::from_le_bytes(decoder.simd_bytes());
@@ -214,6 +210,5 @@ impl Builder {
}
};
self.push(value);
- Ok(())
}
}
diff --git a/Libraries/LibWasm/JIT/src/codegen/x86_64/mod.rs b/Libraries/LibWasm/JIT/src/codegen/x86_64/mod.rs
index 6dcc1811fd3..f536f4a260a 100644
--- a/Libraries/LibWasm/JIT/src/codegen/x86_64/mod.rs
+++ b/Libraries/LibWasm/JIT/src/codegen/x86_64/mod.rs
@@ -654,8 +654,19 @@ impl<'a> CodeGenerator<'a> {
}
/// `cmp a, b` of type `ty`, `b` an immediate when it is the constant `b_value`.
+ /// The slot of `input`, an input the allocator left there for the node to read (`SLOT_INPUT`).
+ fn input_slot(&self, input: Value) -> Address {
+ let slot = self.allocation.slots[input as usize];
+ debug_assert!(slot != NO_SLOT, "v{input} has no slot");
+ Address::new(FP, slot)
+ }
+
fn compare(&mut self, ty: Type, a: Register, b: Register, b_value: Value) {
- if b == crate::regalloc::CONSTANT_INPUT {
+ if b == crate::regalloc::SLOT_INPUT {
+ let address = self.input_slot(b_value);
+ self.asm
+ .alu_rm(crate::asm::x86_64::AluOp::Cmp, width(ty), gpr(a), &address);
+ } else if b == crate::regalloc::CONSTANT_INPUT {
let bits = self.func.node(b_value).constant().expect("a constant");
self.asm.cmp_ri(width(ty), gpr(a), bits as i32);
} else {
diff --git a/Libraries/LibWasm/JIT/src/codegen/x86_64/numeric.rs b/Libraries/LibWasm/JIT/src/codegen/x86_64/numeric.rs
index 4d2a6b5c9fa..f72800ebe6e 100644
--- a/Libraries/LibWasm/JIT/src/codegen/x86_64/numeric.rs
+++ b/Libraries/LibWasm/JIT/src/codegen/x86_64/numeric.rs
@@ -11,7 +11,7 @@ use crate::asm::x86_64::{AluOp, BitCount, BitwiseOp, Cond, FloatOp, Precision, R
use crate::asm::{Address, Fpr, Gpr, Width};
use crate::convention::Register;
use crate::ir::{FLAG_CANNOT_TRAP, FloatCondition, IntCondition, Op, Type, Value};
-use crate::regalloc::CONSTANT_INPUT;
+use crate::regalloc::{CONSTANT_INPUT, SLOT_INPUT};
use libwasm_module::abi::{TRAP_INTEGER_DIVIDE_BY_ZERO, TRAP_INTEGER_OVERFLOW, TRAP_INVALID_CONVERSION};
/// The sign bit of a float type.
@@ -43,7 +43,13 @@ impl CodeGenerator<'_> {
Op::Xor => self.logic(value, AluOp::Xor, ty, output, a, b),
Op::Mul => {
let (dst, a_register) = (gpr(output), gpr(a));
- if b == CONSTANT_INPUT {
+ if b == SLOT_INPUT {
+ let address = self.input_slot(node.args[1]);
+ if output != a {
+ self.asm.mov_rr(width(ty), dst, a_register);
+ }
+ self.asm.imul_rm(width(ty), dst, &address);
+ } else if b == CONSTANT_INPUT {
let immediate = self.immediate(value, 1) as i32;
self.asm.imul_rri(width(ty), dst, a_register, immediate);
} else if output == a {
@@ -148,7 +154,12 @@ impl CodeGenerator<'_> {
Op::FMul => FloatOp::Mul,
_ => FloatOp::Div,
};
- self.asm.vfloat_rrr(op, precision(ty), fpr(output), fpr(a), fpr(b));
+ if b == SLOT_INPUT {
+ let address = self.input_slot(node.args[1]);
+ self.asm.vfloat_rrm(op, precision(ty), fpr(output), fpr(a), &address);
+ } else {
+ self.asm.vfloat_rrr(op, precision(ty), fpr(output), fpr(a), fpr(b));
+ }
}
Op::FSqrt => self
.asm
@@ -203,9 +214,20 @@ impl CodeGenerator<'_> {
}
}
+ /// `dst = a op [slot of input 1]`, for an input the allocator left in its slot.
+ fn alu_slot(&mut self, value: Value, op: AluOp, ty: Type, output: Register, a: Register) {
+ let address = self.input_slot(self.func.inputs(value)[1]);
+ if output != a {
+ self.asm.mov_rr(width(ty), gpr(output), gpr(a));
+ }
+ self.asm.alu_rm(op, width(ty), gpr(output), &address);
+ }
+
fn add(&mut self, value: Value, ty: Type, output: Register, a: Register, b: Register) {
let (dst, a_register) = (gpr(output), gpr(a));
- if b == CONSTANT_INPUT {
+ if b == SLOT_INPUT {
+ self.alu_slot(value, AluOp::Add, ty, output, a);
+ } else if b == CONSTANT_INPUT {
let immediate = self.immediate(value, 1) as i32;
if output == a {
self.asm.add_ri(width(ty), dst, immediate);
@@ -227,7 +249,9 @@ impl CodeGenerator<'_> {
fn sub(&mut self, value: Value, ty: Type, output: Register, a: Register, b: Register) {
let (dst, a_register) = (gpr(output), gpr(a));
- if b == CONSTANT_INPUT {
+ if b == SLOT_INPUT {
+ self.alu_slot(value, AluOp::Sub, ty, output, a);
+ } else if b == CONSTANT_INPUT {
let immediate = self.immediate(value, 1) as i32;
if output != a {
self.asm.mov_rr(width(ty), dst, a_register);
@@ -246,7 +270,9 @@ impl CodeGenerator<'_> {
fn logic(&mut self, value: Value, op: AluOp, ty: Type, output: Register, a: Register, b: Register) {
let (dst, a_register) = (gpr(output), gpr(a));
- if b == CONSTANT_INPUT {
+ if b == SLOT_INPUT {
+ self.alu_slot(value, op, ty, output, a);
+ } else if b == CONSTANT_INPUT {
let immediate = self.immediate(value, 1) as i32;
if output != a {
self.asm.mov_rr(width(ty), dst, a_register);
diff --git a/Libraries/LibWasm/JIT/src/codegen/x86_64/vector.rs b/Libraries/LibWasm/JIT/src/codegen/x86_64/vector.rs
index 19f3c82d300..9c03d14be09 100644
--- a/Libraries/LibWasm/JIT/src/codegen/x86_64/vector.rs
+++ b/Libraries/LibWasm/JIT/src/codegen/x86_64/vector.rs
@@ -16,7 +16,7 @@ use crate::asm::x86_64::{Cond, VexMap, VexOpcode, VexOperand, VexPrefix};
use crate::asm::{Address, Width};
use crate::convention::Register;
use crate::ir::{Func, Op, Type, Value};
-use crate::regalloc::CONSTANT_INPUT;
+use crate::regalloc::{CONSTANT_INPUT, SLOT_INPUT};
use libwasm_module::opcode::simd::*;
const fn op(prefix: VexPrefix, map: VexMap, opcode: u8) -> VexOpcode {
@@ -472,10 +472,13 @@ impl CodeGenerator<'_> {
/// Input `index` of vector node `value` as an operand: its register, or the constant pool entry of a v128 constant
/// the allocator left where it is.
fn vector_input(&mut self, value: Value, index: usize, register: Register) -> VexOperand {
+ let func = self.func;
+ if register == SLOT_INPUT {
+ return VexOperand::Memory(self.input_slot(func.inputs(value)[index]));
+ }
if register != CONSTANT_INPUT {
return VexOperand::Register(fpr(register).0);
}
- let func = self.func;
let constant = func.node(func.inputs(value)[index]);
debug_assert_eq!(constant.op, Op::Const128);
VexOperand::Label(self.constant_label(func.constants[constant.args[0] as usize]))
diff --git a/Libraries/LibWasm/JIT/src/lib.rs b/Libraries/LibWasm/JIT/src/lib.rs
index 709e1df9735..b84274f9bbf 100644
--- a/Libraries/LibWasm/JIT/src/lib.rs
+++ b/Libraries/LibWasm/JIT/src/lib.rs
@@ -35,12 +35,22 @@ use std::sync::Arc;
/// Why a function was not compiled.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum CompileFailure {
- /// The function uses something the JIT does not compile yet, at module offset `pc`.
- Unsupported { pc: u32, what: &'static str },
+ /// An OSR compile at a loop it cannot enter, at module offset `pc`: one that is unreachable, or in a legacy
+ /// handler, whose exception the interpreter frame has no value for. The frame goes on in the interpreter.
+ NoOsrEntry { pc: u32 },
/// The assembler could not finish the code.
CodeGeneration,
}
+impl CompileFailure {
+ pub fn reason(self) -> &'static str {
+ match self {
+ CompileFailure::NoOsrEntry { .. } => "no OSR entry at the loop",
+ CompileFailure::CodeGeneration => "code generation failed",
+ }
+ }
+}
+
/// Options of a compile.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub struct Options {
@@ -57,6 +67,8 @@ pub struct Options {
/// Replace nodes that compute what a dominating node computed already, beyond what building does (`passes/gvn.rs`).
/// Off by default: it finds about 0.1% of the nodes of real modules redundant, for 7 to 16 ns per code byte.
pub gvn: bool,
+ /// Refuse OSR compiles at loops in no other loop, so that tests reach the loops in them.
+ pub stress_nested_osr: bool,
}
/// The addresses of the runtime compiled code reaches, which are constants of the process.
@@ -164,20 +176,18 @@ pub fn compile(context: &mut CompileContext, request: &CompileRequest) -> Result
}
};
match request.osr {
- None => context.builder.build(module, request.function, &mut context.func)?,
+ None => context.builder.build(module, request.function, &mut context.func),
Some(pc) => {
- let Some(stack_types) = context
+ let Some(entry) = context
.builder
- .probe_osr(module, request.function, pc, &mut context.func)?
+ .probe_osr(module, request.function, pc, &mut context.func)
+ .filter(|(_, around)| !request.options.stress_nested_osr || !around.is_empty())
else {
- return Err(CompileFailure::Unsupported {
- pc,
- what: "OSR at a loop that is unreachable or in another loop",
- });
+ return Err(CompileFailure::NoOsrEntry { pc });
};
context
.builder
- .build_osr(module, request.function, pc, stack_types, &mut context.func)?;
+ .build_osr(module, request.function, pc, entry, &mut context.func);
}
}
lap(0, &mut stats);
diff --git a/Libraries/LibWasm/JIT/src/regalloc/mod.rs b/Libraries/LibWasm/JIT/src/regalloc/mod.rs
index 59019b21d9a..e83d240904a 100644
--- a/Libraries/LibWasm/JIT/src/regalloc/mod.rs
+++ b/Libraries/LibWasm/JIT/src/regalloc/mod.rs
@@ -32,6 +32,15 @@ use liveness::{Liveness, NO_HINT, block_start_position, node_position, predecess
pub const NO_REGISTER: u8 = u8::MAX;
/// An input that code generation uses as an immediate.
pub const CONSTANT_INPUT: u8 = u8::MAX - 1;
+/// An input that code generation reads from its spill slot, as the memory operand of the instruction.
+pub const SLOT_INPUT: u8 = u8::MAX - 2;
+
+/// OPTIMIZATION: A spilled input is read from its slot by the instruction itself unless it is needed again within
+/// this many positions (four per node), where loading it into a register once serves both uses.
+const SLOT_INPUT_REUSE_DISTANCE: u32 = 4 * 8;
+
+/// OPTIMIZATION: Parallel moves up to this many are ordered by rescanning them, more by counting their readers.
+const SMALL_PARALLEL_MOVE: usize = 8;
/// No spill slot.
pub const NO_SLOT: i32 = i32::MIN;
@@ -153,6 +162,8 @@ struct Constraints {
/// Whether the output may take the first input's register where that input dies, as two-address instructions
/// want.
reuse_first: bool,
+ /// The inputs code generation may read from their slots (`SLOT_INPUT`), as a mask.
+ slot_inputs: u8,
}
/// Whether constant `value` fits an instruction as an immediate: sign-extended 32 bits for 64-bit operations.
@@ -186,12 +197,14 @@ fn constraints(func: &Func, value: Value) -> Constraints {
temps: [Temp::None; 2],
clobbers: 0,
reuse_first: false,
+ slot_inputs: 0,
};
let input_type = |index: usize| func.node(func.inputs(value)[index]).ty;
match node.op {
Op::Add | Op::Sub | Op::And | Op::Or | Op::Xor | Op::Mul => {
constraints.inputs[1] = Input::RegisterOrConstant;
constraints.reuse_first = true;
+ constraints.slot_inputs = 0b010;
}
Op::Shl | Op::ShrS | Op::ShrU => constraints.inputs[1] = Input::RegisterOrConstant,
Op::Rotl | Op::Rotr => {
@@ -210,7 +223,11 @@ fn constraints(func: &Func, value: Value) -> Constraints {
let quotient = matches!(node.op, Op::DivS | Op::DivU);
constraints.output = Output::Fixed(if quotient { RAX } else { RDX });
}
- Op::Compare | Op::BranchCompare => constraints.inputs[1] = Input::RegisterOrConstant,
+ Op::Compare | Op::BranchCompare => {
+ constraints.inputs[1] = Input::RegisterOrConstant;
+ constraints.slot_inputs = 0b010;
+ }
+ Op::FAdd | Op::FSub | Op::FMul | Op::FDiv => constraints.slot_inputs = 0b010,
Op::FloatCompare => {
if matches!(
crate::ir::FloatCondition::from_flags(node.flags),
@@ -295,12 +312,14 @@ fn constraints(func: &Func, value: Value) -> Constraints {
if node.op == Op::VectorBinary && codegen::x86_64::is_vector_shift(node.args[2]) {
constraints.inputs[1] = Input::RegisterOrConstant;
}
+ // NB: The operands that may be constants in the constant pool may be in their slots just as well.
let constants = codegen::x86_64::vector_constant_inputs(func, value);
for (index, input) in constraints.inputs.iter_mut().enumerate() {
if constants & (1 << index) != 0 {
*input = Input::RegisterOrVectorConstant;
}
}
+ constraints.slot_inputs = constants;
}
_ => {}
}
@@ -328,6 +347,8 @@ pub struct Allocator {
current_block: BlockId,
pending: Vec<Move>,
resolved: Vec<Move>,
+ /// How many pending moves read each location, in `resolve_many()`.
+ readers: crate::table::Table<u64>,
places: Vec<Place>,
types: Vec<Type>,
/// The inputs of the node being allocated, whose registers only it may take.
@@ -783,6 +804,11 @@ impl Allocator {
fn resolve(&mut self, func: &Func, allocation: &mut Allocation) {
let _ = func;
self.resolved.clear();
+ if self.pending.len() > SMALL_PARALLEL_MOVE {
+ self.resolve_many(allocation);
+ allocation.moves.extend_from_slice(&self.resolved);
+ return;
+ }
while !self.pending.is_empty() {
let ready = self
.pending
@@ -816,6 +842,67 @@ impl Allocator {
allocation.moves.extend_from_slice(&self.resolved);
}
+ /// `resolve()` for many moves, like the edges into a merge with many phis: it counts the readers of each
+ /// location, so that finding the moves whose destination nobody reads any more takes one pass, not one per move.
+ fn resolve_many(&mut self, allocation: &mut Allocation) {
+ fn key(location: Location) -> u64 {
+ match location {
+ Location::Register(register) => (1 << 40) | u64::from(register),
+ Location::Slot(slot) => (2 << 40) | u64::from(slot as u32),
+ Location::Outgoing(index) => (3 << 40) | u64::from(index),
+ Location::ResultArea(index) => (4 << 40) | u64::from(index),
+ Location::Constant(value) => (5 << 40) | u64::from(value),
+ }
+ }
+ let readers = &mut self.readers;
+ readers.clear();
+ let add = |readers: &mut crate::table::Table<u64>, location: Location, delta: i64| {
+ let count = i64::from(readers.get(key(location)).unwrap_or(0)) + delta;
+ readers.insert(key(location), count as u32);
+ };
+ for pending in &self.pending {
+ add(readers, pending.from, 1);
+ }
+ while !self.pending.is_empty() {
+ let mut progress = false;
+ let mut index = 0;
+ while index < self.pending.len() {
+ if readers.get(key(self.pending[index].to)).unwrap_or(0) == 0 {
+ let ready = self.pending.swap_remove(index);
+ add(readers, ready.from, -1);
+ self.resolved.push(ready);
+ progress = true;
+ } else {
+ index += 1;
+ }
+ }
+ if progress || self.pending.is_empty() {
+ continue;
+ }
+ // Every destination is still a source: the moves form cycles. Save one destination in the cycle slot.
+ if allocation.cycle_slot == NO_SLOT {
+ // NB: Two slots, in case the value is a v128.
+ allocation.slot_count += 2;
+ allocation.cycle_slot = convention::spill_slot_offset(allocation.slot_count - 1);
+ }
+ let saved = self.pending[0].to;
+ let temp = Location::Slot(allocation.cycle_slot);
+ let vector = self.pending[0].vector;
+ self.resolved.push(Move {
+ from: saved,
+ to: temp,
+ vector,
+ });
+ for pending in &mut self.pending {
+ if pending.from == saved {
+ pending.from = temp;
+ add(readers, saved, -1);
+ add(readers, temp, 1);
+ }
+ }
+ }
+ }
+
// Nodes.
fn allocate_node(&mut self, func: &Func, liveliness: &Liveliness, allocation: &mut Allocation, value: Value) {
@@ -896,6 +983,21 @@ impl Allocator {
}
}
+ /// Whether the node being allocated should read `input`, one of its inputs that may be a memory operand, from its
+ /// slot: it is in no register, the node takes it once, and it is not needed again soon.
+ fn reads_from_slot(&self, func: &Func, allocation: &Allocation, input: Value) -> bool {
+ if func.node(input).op.is_constant()
+ || self.value_registers[input as usize] != NO_REGISTER
+ || allocation.slots[input as usize] == NO_SLOT
+ || self.inputs.iter().filter(|other| **other == input).count() != 1
+ {
+ return false;
+ }
+ self.liveness
+ .next_use(input, self.position)
+ .is_none_or(|next| next > self.position + SLOT_INPUT_REUSE_DISTANCE)
+ }
+
/// Puts `input` in some register for a node, with the registers in `blocked` taken.
fn register_input(&mut self, func: &Func, allocation: &mut Allocation, input: Value, blocked: u32) -> Register {
let float = is_float(func.node(input).ty);
@@ -965,6 +1067,9 @@ impl Allocator {
Input::RegisterOrVectorConstant if func.node(input).op == Op::Const128 => {
registers[index] = CONSTANT_INPUT;
}
+ _ if constraints.slot_inputs & (1 << index) != 0 && self.reads_from_slot(func, allocation, input) => {
+ registers[index] = SLOT_INPUT;
+ }
_ => {
let register = self.register_input(func, allocation, input, blocked);
blocked |= 1 << register;
diff --git a/Libraries/LibWasm/JIT/src/regalloc/verify.rs b/Libraries/LibWasm/JIT/src/regalloc/verify.rs
index a6f7b78fd4e..3771f35dd6d 100644
--- a/Libraries/LibWasm/JIT/src/regalloc/verify.rs
+++ b/Libraries/LibWasm/JIT/src/regalloc/verify.rs
@@ -10,7 +10,7 @@
//! by their inputs). Slots belong to one value each and are written where it is defined, so reading a value from
//! its own slot is always right.
-use super::{Allocation, CONSTANT_INPUT, Location, NO_REGISTER, REGISTER_COUNT, call_result_types};
+use super::{Allocation, CONSTANT_INPUT, Location, NO_REGISTER, REGISTER_COUNT, SLOT_INPUT, call_result_types};
use crate::convention::{self, Place};
use crate::ir::{BlockId, Func, NONE, Op, Shape, Value};
use crate::passes::cleanup::Liveliness;
@@ -147,6 +147,11 @@ pub fn verify(func: &Func, liveliness: &Liveliness, allocation: &Allocation) ->
};
for (index, &input) in inputs.iter().enumerate().take(count) {
let register = record.inputs[index];
+ if register == SLOT_INPUT {
+ let slot = allocation.slots[input as usize];
+ simulation.check_holds(Location::Slot(slot), input, &format!("v{value} input {index}"));
+ continue;
+ }
if register == CONSTANT_INPUT {
if !func.node(input).op.is_constant() {
simulation.error(format!("v{value} takes v{input} as an immediate"));
@@ -237,6 +242,7 @@ pub fn dump(func: &Func, liveliness: &Liveliness, allocation: &Allocation) -> St
let register = |register: u8| match register {
NO_REGISTER => "-".to_string(),
CONSTANT_INPUT => "#".to_string(),
+ SLOT_INPUT => "[slot]".to_string(),
_ => name(&Location::Register(register)),
};
let moves = |moves: &[super::Move]| {
diff --git a/Libraries/LibWasm/JIT/tests/harness/mod.rs b/Libraries/LibWasm/JIT/tests/harness/mod.rs
index b06381cd9c5..59e1663e14f 100644
--- a/Libraries/LibWasm/JIT/tests/harness/mod.rs
+++ b/Libraries/LibWasm/JIT/tests/harness/mod.rs
@@ -27,6 +27,23 @@ use std::collections::HashMap;
use std::mem::offset_of;
use std::sync::Arc;
+/// Runs a program's `main` on a thread of its own where the C library is musl, whose pthread_getattr_np() finds the
+/// main thread's stack by probing it page by page with mremap(), which never ends under qemu-user. Elsewhere it runs
+/// `main` as it is.
+pub fn run_main<T: Send + 'static>(main: impl FnOnce() -> T + Send + 'static) -> T {
+ #[cfg(target_env = "musl")]
+ {
+ std::thread::Builder::new()
+ .stack_size(8 << 20)
+ .spawn(main)
+ .expect("start the main thread")
+ .join()
+ .expect("the main thread panicked")
+ }
+ #[cfg(not(target_env = "musl"))]
+ main()
+}
+
/// The trap code of a call that reached a function the JIT did not compile.
pub const TRAP_NOT_COMPILED: u32 = 100;
diff --git a/Libraries/LibWasm/JIT/tests/harness/script.rs b/Libraries/LibWasm/JIT/tests/harness/script.rs
index f4bb9a7a8d4..178071fea1c 100644
--- a/Libraries/LibWasm/JIT/tests/harness/script.rs
+++ b/Libraries/LibWasm/JIT/tests/harness/script.rs
@@ -14,6 +14,7 @@ use libwasm_engine::types::{FuncType, GlobalType, Limits, MemoryType, RefType, T
use libwasm_jit::Options;
use serde_json::Value as Json;
use std::collections::{BTreeSet, HashMap};
+use std::io::Write;
use std::path::{Path, PathBuf};
use std::rc::Rc;
use std::sync::Arc;
@@ -233,6 +234,46 @@ struct Script<'a> {
name: String,
options: Options,
runtime: bool,
+ /// Where `--dump` writes what the interpreter did in every action.
+ dump: Option<&'a mut dyn std::io::Write>,
+}
+
+/// A value as `--dump` writes it: the same on every architecture, so NaNs of scalar types and the addresses of
+/// references are left out.
+fn dump_value(value: &Value) -> String {
+ match value {
+ Value::F32(bits) if f32::from_bits(*bits).is_nan() => "f32:nan".to_string(),
+ Value::F64(bits) if f64::from_bits(*bits).is_nan() => "f64:nan".to_string(),
+ Value::Ref(0) => "ref:null".to_string(),
+ Value::Ref(bits) if bits & 1 != 0 => format!("ref:i31:{bits:x}"),
+ Value::Ref(_) => "ref:nonnull".to_string(),
+ other => format!("{other:?}"),
+ }
+}
+
+/// The memories, tables and globals of an instance, as `--dump` writes them: a hash of the memories' bytes, which
+/// table elements are null, and the globals.
+fn dump_state(store: &Store, instance: InstanceAddress) -> String {
+ let instance = store.instance(instance);
+ let mut text = String::new();
+ for memory in &instance.memories {
+ let bytes = store.memory(*memory).bytes();
+ let hash = bytes.iter().fold(0xcbf2_9ce4_8422_2325u64, |hash, byte| {
+ (hash ^ u64::from(*byte)).wrapping_mul(0x0100_0000_01b3)
+ });
+ text.push_str(&format!(" m{}:{hash:x}", bytes.len()));
+ }
+ for table in &instance.tables {
+ let elements = &store.table(*table).elements;
+ let hash = elements.iter().fold(0xcbf2_9ce4_8422_2325u64, |hash, element| {
+ (hash ^ u64::from(*element == 0)).wrapping_mul(0x0100_0000_01b3)
+ });
+ text.push_str(&format!(" t{}:{hash:x}", elements.len()));
+ }
+ for global in &instance.globals {
+ text.push_str(&format!(" g:{}", dump_value(&store.global(*global).get())));
+ }
+ text
}
impl Script<'_> {
@@ -329,6 +370,19 @@ impl Script<'_> {
return;
};
let expected = outcome(self.interpreted.invoke(*interpreted, &arguments));
+ if let Some(dump) = self.dump.as_mut() {
+ let result = match &expected {
+ Outcome::Values(values) => values.iter().map(dump_value).collect::<Vec<_>>().join(" "),
+ Outcome::Trap(code) => format!("trap {code}"),
+ };
+ // NB: How deep the stack gets before it is exhausted differs, and so does what the code did on the way.
+ let state = if expected == Outcome::Trap(libwasm_engine::abi::TRAP_STACK_EXHAUSTED) {
+ String::new()
+ } else {
+ dump_state(&self.interpreted, self.modules[index].interpreted)
+ };
+ let _ = writeln!(dump, "{}:{line} {field:?} => {result} |{state}", self.name);
+ }
let loaded = &mut self.modules[index];
let function = function_index(&self.jit, *jit, loaded.jit);
let actual = match (function, &mut loaded.compiled) {
@@ -460,6 +514,18 @@ pub fn scripts(paths: &[String]) -> Vec<PathBuf> {
/// Runs the scripts at `paths`. With `runtime`, the JIT's store runs every call through the runtime, which compiles
/// what `LIBWASM_JIT` says, instead of calling compiled code directly.
pub fn run(paths: &[String], verbose: bool, options: Options, runtime: bool) -> Totals {
+ run_with_dump(paths, verbose, options, runtime, None)
+}
+
+/// `run()`, writing what the interpreter did in every action to `dump`: a file that should be the same on every
+/// architecture.
+pub fn run_with_dump(
+ paths: &[String],
+ verbose: bool,
+ options: Options,
+ runtime: bool,
+ mut dump: Option<&mut dyn std::io::Write>,
+) -> Totals {
let mut totals = Totals::default();
for path in scripts(paths) {
let Ok(text) = std::fs::read_to_string(&path) else {
@@ -487,6 +553,7 @@ pub fn run(paths: &[String], verbose: bool, options: Options, runtime: bool) ->
name: path.file_name().unwrap().to_string_lossy().into_owned(),
options,
runtime,
+ dump: dump.as_mut().map(|dump| &mut **dump as &mut dyn std::io::Write),
};
runner.run(&script);
}